JavaScript 65.5%
Python 17.8%
CSS 13%
HTML 3.7%
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 } from './monitor.js';14// Topologie vivante : où tourne chaque app Ka = registre mld (M1M32), jamais codé ici.15import { initRegistry, refreshRegistry, getRegistry, getSites, getProjects, findProject, selfNode, sshTarget, topologyText, describe as describeRegistryEvent, ensureAllNodesTooling } from './registry.js';16import { initAnalytics, recordHit, analyticsSummary, analyticsSeries, analyticsSite, analyticsRealtime, analyticsAnomalies, analyticsInspect, analyticsClasses, analyticsConfig, setAnalyticsConfig, PIXEL } from './analytics.js';17import { initSocial, socialState, socialLog, setAuto, generateDraft, publishDraft, runAutoCycle, cardPath, fbLoginState, generateReelDraft, publishReelDraft, runReelCycle, reelPath, startReelBatch, batchStatus, REEL_BATCH_DEFAULT, getGallery, startGenBatch, genBatchStatus } from './social.js';18import { execFile } from 'node:child_process';1920const __dirname = path.dirname(fileURLToPath(import.meta.url));21const APP_DIR = path.join(__dirname, '..');22const DATA_DIR = path.join(APP_DIR, 'data');23const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts');24const PUBLIC_DIR = path.join(APP_DIR, 'public');25const HOME = os.homedir();2627fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true });2829// ---------- config ----------30const CONFIG_PATH = path.join(DATA_DIR, 'config.json');31if (!fs.existsSync(CONFIG_PATH)) {32 console.error('config.json manquant — exécuter: node server/set-password.js <motdepasse>');33 process.exit(1);34}35const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));36const PORT = config.port || 3300;37const CLAUDE_BIN = config.claudeBin || '/opt/homebrew/bin/claude';38const NODE_BIN = config.nodeBin || '/opt/homebrew/bin/node';3940// toutes les variables de ~/.claude/.env (ANTHROPIC_API_KEY, APIFY_TOKEN, …)41// sont injectées dans les runs claude locaux (les runs distants font42// `export $(cat ~/.claude/.env | xargs)` côté nœud)43function loadClaudeEnv() {44 const out = {};45 try {46 for (const line of fs.readFileSync(path.join(HOME, '.claude', '.env'), 'utf8').split('\n')) {47 const m = line.match(/^([A-Z0-9_]+)=(\S+)/);48 if (m) out[m[1]] = m[2];49 }50 } catch {}51 return out;52}53const CLAUDE_ENV = loadClaudeEnv();54const ANTHROPIC_API_KEY = CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';5556// ---------- Upgradeur de prompt (Anthropic Messages API) ----------57const UPGRADER_KEY = config.anthropicKey || CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';58const UPGRADER_MODEL = config.upgraderModel || 'claude-opus-4-8';5960// Connaissance du Groupe KA injectée dans l'upgradeur pour produire des prompts61// Claude Code précis, conformes aux standards de l'écosystème.62const 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é.6364# Écosystème Groupe KA (12 apps web, stack Node/React, cluster MacLustr)65- 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. auto-ka (auto-ka.com) : véhicules. fabri-ka (fabri-ka.com) : fabricants/artisans/friperies. food-ka (food-ka.com) : alimentation/épicerie. sorti-ka (sorti-ka.com) : sorties/événements. job-ka (job-ka.com) : emplois. api-ka (api-ka.com) : API centrale + supervision des connecteurs. ka-stats (ka-stats.com) : Ka·Stats, l'observatoire de statistiques de l'écosystème — agrège les dashboards /api/stats/dashboard des sites (Node zéro-dépendance). 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, process launchd com.kaX.guardian, PAS pm2). Marché cible : Québec (fr-CA).66- EMPLACEMENTS : les nœuds, répertoires et process PM2 réels de chaque app sont fournis en fin de ce message (bloc « Emplacements ACTUELS », issu du registre mld) — ils changent au fil des migrations, ne jamais en citer de mémoire.67- 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).6869# Conventions NON négociables (rappelle-les dans le prompt quand c'est pertinent)70- 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.71- 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.72- 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.73- Design system ka-ui : tokens/couleurs/footer centralisés (ecosystem.json). Toujours valider en mobile (simulateur/Playwright) après un changement d'UI.7475# Outils de scraping/recherche disponibles sur chaque nœud (variables dans ~/.claude/.env)76- 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.77- 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.78- 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).7980# Comment écrire le prompt amélioré811. Écris en français, à l'impératif, adressé à Claude Code.822. Commence par l'objectif clair, puis le périmètre précis (fichiers/zones probables), puis les critères d'acceptation vérifiables.833. Ajoute les détails manquants que la demande sous-entend (edge cases, validation, mobile, i18n fr-CA) sans dénaturer l'intention.844. Rappelle les étapes de clôture attendues (build, pm2 restart, healthcheck, commit+push spbgit) UNIQUEMENT si la tâche modifie du code.855. Demande à Claude Code d'explorer/lire avant de modifier, et de vérifier son travail.866. Reste concis et actionnable : pas de blabla, pas de sections inutiles. N'invente pas de faits spécifiques non fournis.877. Sortie = le prompt amélioré SEUL, sans préambule ("Voici…"), sans guillemets englobants, sans commentaire méta.`;8889async function upgradePrompt(rawPrompt, project) {90 if (!UPGRADER_KEY) throw new Error('Clé Anthropic non configurée (config.anthropicKey).');91 const ctx = project ? `\n\nContexte : la demande vise le projet "${project.name}" (déployé sur le nœud ${project.node || selfNode()}, répertoire ${project.dir}).` : '';92 const resp = await fetch('https://api.anthropic.com/v1/messages', {93 method: 'POST',94 headers: {95 'x-api-key': UPGRADER_KEY,96 'anthropic-version': '2023-06-01',97 'content-type': 'application/json',98 },99 body: JSON.stringify({100 model: UPGRADER_MODEL,101 max_tokens: 1500,102 system: KA_KNOWLEDGE + '\n\n# ' + topologyText(),103 messages: [{ role: 'user', content: `Réécris cette demande en un prompt Claude Code excellent.${ctx}\n\nDemande brute :\n${rawPrompt}` }],104 }),105 });106 const data = await resp.json();107 if (data.error) throw new Error(data.error.message || 'Erreur Anthropic');108 const text = (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim();109 if (!text) throw new Error('Réponse vide du modèle');110 return text;111}112113// ---------- audit ----------114const AUDIT_PATH = path.join(DATA_DIR, 'audit.jsonl');115function audit(entry) {116 fs.appendFile(AUDIT_PATH, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', () => {});117}118119// ---------- sessions (auth) ----------120const SESSIONS_PATH = path.join(DATA_DIR, 'sessions.json');121let sessions = {};122try { sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH, 'utf8')); } catch {}123function saveSessions() { fs.writeFileSync(SESSIONS_PATH, JSON.stringify(sessions)); }124const SESSION_IDLE_MS = 7 * 24 * 3600 * 1000;125const SESSION_MAX_MS = 30 * 24 * 3600 * 1000;126127function verifyPassword(pw) {128 const hash = crypto.scryptSync(pw, Buffer.from(config.salt, 'hex'), 64).toString('hex');129 return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(config.passwordHash));130}131function newSession() {132 const token = crypto.randomBytes(32).toString('hex');133 sessions[token] = { created: Date.now(), last: Date.now() };134 saveSessions();135 return token;136}137function getSession(req) {138 const cookie = req.headers.cookie || '';139 const m = cookie.match(/(?:^|;\s*)akid=([a-f0-9]{64})/);140 if (!m) return null;141 const s = sessions[m[1]];142 if (!s) return null;143 const now = Date.now();144 if (now - s.last > SESSION_IDLE_MS || now - s.created > SESSION_MAX_MS) {145 delete sessions[m[1]]; saveSessions(); return null;146 }147 s.last = now;148 return m[1];149}150151const loginFails = new Map();152function clientIp(req) {153 const xf = req.headers['x-forwarded-for'];154 return (xf ? String(xf).split(',')[0].trim() : req.socket.remoteAddress) || '?';155}156function loginAllowed(ip) {157 const rec = loginFails.get(ip);158 if (!rec) return true;159 if (Date.now() - rec.first > 15 * 60 * 1000) { loginFails.delete(ip); return true; }160 return rec.count < 8;161}162function loginFailed(ip) {163 const rec = loginFails.get(ip) || { first: Date.now(), count: 0 };164 rec.count++; loginFails.set(ip, rec);165}166167// ---------- chats ----------168const CHATS_PATH = path.join(DATA_DIR, 'chats.json');169let chats = [];170try { chats = JSON.parse(fs.readFileSync(CHATS_PATH, 'utf8')); } catch {}171// migration v1 → v2172for (const c of chats) {173 if (!c.model) c.model = 'fable';174 if (!c.permMode) c.permMode = c.mode === 'auto' ? 'bypass' : 'default';175 if (!c.state) c.state = 'idle';176 if (c.totalCost === undefined) c.totalCost = 0;177 if (!c.alwaysAllow) c.alwaysAllow = [];178 if (c.autoAllowAll === undefined) c.autoAllowAll = false;179}180function saveChats() { fs.writeFileSync(CHATS_PATH, JSON.stringify(chats, null, 1)); }181function getChat(id) { return chats.find(c => c.id === id); }182function publicChat(c) {183 return {184 id: c.id, title: c.title, projectId: c.projectId, projectName: c.projectName,185 model: c.model, permMode: c.permMode, state: c.state, autoAllowAll: !!c.autoAllowAll,186 claudeSessionId: c.claudeSessionId, lastModel: c.lastModel || null,187 totalCost: c.totalCost || 0, turns: c.turns || 0, contextTokens: c.contextTokens || 0,188 batch: c.batch || null,189 created: c.created, updated: c.updated,190 };191}192function transcriptPath(id) { return path.join(TRANSCRIPTS_DIR, id.replace(/[^a-zA-Z0-9_-]/g, '') + '.jsonl'); }193function appendTranscript(chatId, event) {194 fs.appendFile(transcriptPath(chatId), JSON.stringify(event) + '\n', () => {});195}196function readTranscript(chatId) {197 try {198 return fs.readFileSync(transcriptPath(chatId), 'utf8')199 .split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } })200 .filter(Boolean);201 } catch { return []; }202}203204// ---------- prompt bank ----------205const PROMPTS_PATH = path.join(DATA_DIR, 'prompts.json');206let prompts = [];207try { prompts = JSON.parse(fs.readFileSync(PROMPTS_PATH, 'utf8')); } catch {}208function savePrompts() { fs.writeFileSync(PROMPTS_PATH, JSON.stringify(prompts, null, 1)); }209210// ---------- projets (apps Groupe KA) ----------211// La liste des projets Claude Code (app → nœud → repo de prod) est DÉRIVÉE du registre212// mld via registry.js (getProjects/findProject) : quand `mld move` déplace une app, la213// prochaine session s'ouvre sur le bon nœud. Plus aucune table figée ici.214// Orchestrateur : une seule session sur le nœud de la console qui pilote toutes les apps215// via SSH, en gardant le contexte complet de la tâche (CLAUDE.md régénéré par registry.js).216const ORCH_DIR = path.join(HOME, 'ka-orchestrator');217const ORCH_PROJECT = { id: 'ORCH', name: '🎛️ Orchestrateur multi-sites', node: null, dir: ORCH_DIR };218function listProjects() {219 return [220 { id: ORCH_PROJECT.id, name: ORCH_PROJECT.name, node: selfNode(), dir: ORCH_PROJECT.dir },221 ...getProjects().map(p => ({ id: p.id, name: p.name, node: p.node || selfNode(), dir: p.dir })),222 ];223}224function resolveProject(id) {225 if (id === 'ORCH') return ORCH_PROJECT;226 return findProject(id);227}228// Une conversation garde node/dir de sa création ; si l'app a déménagé depuis (registre),229// on la rattache au nœud actuel et on repart d'une session Claude vierge (la session230// `--resume` vivait sur l'ancien nœud).231function realignChat(chat) {232 if (!chat || chat.projectId === 'ORCH') return false;233 const proj = resolveProject(chat.projectId);234 if (!proj) return false;235 if (proj.node === chat.node && proj.dir === chat.dir) return false;236 const from = chat.node || selfNode(), to = proj.node || selfNode();237 chat.projectId = proj.id; chat.node = proj.node; chat.dir = proj.dir;238 chat.claudeSessionId = null; chat.contextTokens = 0;239 saveChats();240 emitAndLog(chat.id, { type: 'notice', text: `📦 ${chat.projectName} a déménagé ${from} → ${to} (registre mld) : cette conversation suit l'app sur son nouveau nœud — nouvelle session Claude Code (l'ancien contexte vivait sur ${from}).` });241 audit({ kind: 'chat_realigned', chatId: chat.id, project: chat.projectId, from, to });242 return true;243}244245// ---------- exécution Claude Code ----------246const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];247// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)248const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };249const DEFAULT_MODEL = 'fable';250const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];251const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';252253const 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.`;254255const orchSystem = () => `Tu es la session ORCHESTRATRICE multi-sites du Groupe KA, lancée sur ${selfNode()}. 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 (GÉNÉRÉE depuis le registre mld, donc à jour) 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 ${selfNode()} 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.\n\n${topologyText()}`;256257const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;258259// chatId -> { proc, permToken, stderr, remote }260const running = new Map();261// requestId -> { chatId, resolve, timer, input, toolKey }262const pendingPerms = new Map();263264function broadcast(chatId, msg) {265 const data = JSON.stringify(msg);266 for (const ws of wss.clients) {267 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);268 }269}270function broadcastAll(msg) {271 const data = JSON.stringify(msg);272 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);273}274function broadcastEco(msg) {275 const data = JSON.stringify(msg);276 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);277}278function emitAndLog(chatId, msg) {279 appendTranscript(chatId, msg);280 broadcast(chatId, msg);281}282function setChatState(chat, state) {283 chat.state = state;284 chat.updated = Date.now();285 saveChats();286 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });287}288289function permKey(tool, input) {290 if (tool === 'Bash') {291 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';292 return 'Bash:' + first;293 }294 return tool;295}296297function startClaude(chat, prompt) {298 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');299 const permToken = crypto.randomBytes(16).toString('hex');300 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;301 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';302 let proc;303304 realignChat(chat); // l'app a-t-elle déménagé depuis la dernière fois ? (registre mld)305 const sysAppend = chat.projectId === 'ORCH' ? orchSystem() : SYSTEM_APPEND + '\n\n' + topologyText();306 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',307 '--model', CLI_MODEL[model], '--append-system-prompt', sysAppend];308 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);309310 if (!chat.node) {311 // exécution locale (app déployée sur M3U96a)312 const args = [...baseArgs];313 if (permMode === 'bypass') {314 args.push('--dangerously-skip-permissions');315 } else {316 args.push('--permission-mode', permMode);317 const mcpCfg = {318 mcpServers: {319 adminka: {320 command: NODE_BIN,321 args: [path.join(__dirname, 'perm-mcp.js')],322 env: {323 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,324 ADMIN_KA_PERM_TOKEN: permToken,325 },326 },327 },328 };329 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);330 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));331 args.push('--mcp-config', cfgPath);332 args.push('--permission-prompt-tool', 'mcp__adminka__approve');333 args.push('--allowedTools', ALLOWED_READONLY);334 }335 proc = spawn(CLAUDE_BIN, args, {336 cwd: chat.dir,337 env: {338 ...process.env, ...CLAUDE_ENV,339 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,340 },341 stdio: ['pipe', 'pipe', 'pipe'],342 detached: false,343 });344 } else {345 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,346 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).347 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];348 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');349 if (permMode === 'bypass') {350 cmd += ' --dangerously-skip-permissions';351 } else {352 const revPort = 21000 + Math.floor(Math.random() * 3000);353 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);354 const mcpCfg = {355 mcpServers: {356 adminka: {357 command: '/opt/homebrew/bin/node',358 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],359 env: {360 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,361 ADMIN_KA_PERM_TOKEN: permToken,362 },363 },364 },365 };366 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;367 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;368 }369 const remoteCmd = [370 `cd ${chat.dir}`,371 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',372 'export $(cat ~/.claude/.env | xargs)',373 `echo $$ > /tmp/adminka-pid-${permToken}`,374 cmd,375 ].join(' && ');376 proc = spawn('ssh', [...sshArgs, sshTarget(chat.node), remoteCmd], {377 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },378 stdio: ['pipe', 'pipe', 'pipe'],379 });380 }381 proc.stdin.write(prompt);382 proc.stdin.end();383384 const state = { proc, permToken, stderr: '', remote: chat.node || null };385 running.set(chat.id, state);386 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || selfNode(), dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });387 emitAndLog(chat.id, { type: 'status', state: 'running' });388 setChatState(chat, 'running');389390 let buf = '';391 proc.stdout.on('data', (d) => {392 buf += d.toString('utf8');393 let idx;394 while ((idx = buf.indexOf('\n')) >= 0) {395 const line = buf.slice(0, idx).trim();396 buf = buf.slice(idx + 1);397 if (!line) continue;398 let ev;399 try { ev = JSON.parse(line); } catch { continue; }400 handleClaudeEvent(chat, ev);401 }402 });403 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });404 proc.on('close', (code) => {405 running.delete(chat.id);406 for (const [rid, p] of pendingPerms) {407 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }408 }409 if (code !== 0 && code !== null) {410 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });411 }412 emitAndLog(chat.id, { type: 'status', state: 'idle' });413 setChatState(chat, 'idle');414 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });415 });416 proc.on('error', (err) => {417 running.delete(chat.id);418 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });419 emitAndLog(chat.id, { type: 'status', state: 'idle' });420 setChatState(chat, 'idle');421 });422}423424function handleClaudeEvent(chat, ev) {425 if (ev.type === 'system' && ev.subtype === 'init') {426 if (ev.session_id) chat.claudeSessionId = ev.session_id;427 if (ev.model) chat.lastModel = ev.model;428 saveChats();429 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });430 }431 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {432 for (const block of ev.message.content) {433 if (block.type === 'tool_use') {434 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });435 }436 }437 }438 if (ev.type === 'result') {439 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);440 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);441 const u = ev.usage || {};442 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);443 saveChats();444 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });445 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });446 }447 if (ev.type === 'stream_event') {448 broadcast(chat.id, { type: 'claude', event: ev });449 } else {450 emitAndLog(chat.id, { type: 'claude', event: ev });451 }452}453454function interrupt(chatId) {455 const st = running.get(chatId);456 if (!st) return;457 audit({ kind: 'interrupt', chatId });458 if (st.remote) {459 spawn('ssh', ['-o', 'BatchMode=yes', sshTarget(st.remote), `kill -TERM $(cat /tmp/adminka-pid-${st.permToken} 2>/dev/null) 2>/dev/null; rm -f /tmp/adminka-pid-${st.permToken}`], {460 env: { ...process.env, HOME }, stdio: 'ignore',461 });462 }463 st.proc.kill('SIGTERM');464 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);465}466467// exécuter un script sur un nœud (local ou ssh) — pour les actions d'admin468function runOnNode(node, script) {469 return new Promise((resolve) => {470 const full = `export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; ${script}`;471 const local = node === selfNode();472 const bin = local ? '/bin/bash' : 'ssh';473 const args = local ? ['-c', full] : ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12', sshTarget(node), full];474 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 } },475 (err, stdout, stderr) => resolve({ stdout: String(stdout || ''), stderr: String(stderr || ''), error: err ? (stderr || err.message) : null }));476 });477}478479// ---------- HTTP ----------480const 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' };481482function readBody(req, limit = 512 * 1024) {483 return new Promise((resolve, reject) => {484 let data = '';485 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });486 req.on('end', () => resolve(data));487 req.on('error', reject);488 });489}490function json(res, code, obj) {491 res.writeHead(code, { 'Content-Type': 'application/json' });492 res.end(JSON.stringify(obj));493}494495const server = http.createServer(async (req, res) => {496 const url = new URL(req.url, 'http://x');497 const p = url.pathname;498499 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }500501 // --- beacon analytics (public, sans auth) : v1 (pings 60 s) et v2 (pv/hb) ---502 if (p === '/collect') {503 try { recordHit(url.searchParams, req); } catch {}504 res.writeHead(200, { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Access-Control-Allow-Origin': '*' });505 return res.end(PIXEL);506 }507508 // logos des sites (favicon/apple-touch-icon en cache) — public, léger509 if (p.startsWith('/icons/')) {510 const icon = getIcon(p.split('/')[2]);511 if (!icon) { res.writeHead(404); return res.end(); }512 res.writeHead(200, { 'Content-Type': icon.type, 'Cache-Control': 'public, max-age=86400' });513 return res.end(icon.buf);514 }515516 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---517 if (p === '/internal/perm' && req.method === 'POST') {518 let body;519 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }520 let chatId = null;521 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;522 if (!chatId) return json(res, 403, { error: 'bad token' });523 const chat = getChat(chatId);524 const toolKey = permKey(body.tool_name, body.input);525526 // « Tout autoriser » activé → toute la session est auto-approuvée : la tâche527 // va au bout sans jamais attendre l'utilisateur528 if (chat && chat.autoAllowAll) {529 audit({ kind: 'permission_auto_all', chatId, tool: body.tool_name });530 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: 'tout autoriser', input: body.input });531 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });532 }533534 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation535 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {536 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });537 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });538 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });539 }540541 const requestId = crypto.randomBytes(8).toString('hex');542 const p2 = new Promise((resolve) => {543 const timer = setTimeout(() => {544 pendingPerms.delete(requestId);545 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });546 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');547 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });548 }, 30 * 60 * 1000);549 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });550 });551 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });552 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });553 if (chat) setChatState(chat, 'waiting_perm');554 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });555 const decision = await p2;556 return json(res, 200, decision);557 }558559 // --- auth ---560 if (p === '/api/login' && req.method === 'POST') {561 const ip = clientIp(req);562 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });563 let body;564 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }565 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {566 loginFailed(ip);567 audit({ kind: 'login_fail', ip });568 return json(res, 401, { error: 'Mot de passe invalide.' });569 }570 const token = newSession();571 audit({ kind: 'login_ok', ip });572 res.writeHead(200, {573 'Content-Type': 'application/json',574 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,575 });576 return res.end(JSON.stringify({ ok: true }));577 }578 if (p === '/api/logout' && req.method === 'POST') {579 const t = getSession(req);580 if (t) { delete sessions[t]; saveSessions(); }581 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });582 return res.end(JSON.stringify({ ok: true }));583 }584585 // --- API authentifiée ---586 if (p.startsWith('/api/')) {587 if (!getSession(req)) return json(res, 401, { error: 'auth' });588 if (p === '/api/me') {589 const r = getRegistry();590 return json(res, 200, { ok: true, host: os.hostname(), node: selfNode(), version: '3.2.0',591 registry: { updated: r.updated, fetchedAt: r.fetchedAt, source: r.source, stale: r.stale, error: r.error, nApps: r.nApps, sites: r.sites.length, nodes: r.nodes } });592 }593 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });594 // --- registre mld (topologie vivante) ---595 if (p === '/api/registry' && req.method === 'GET') return json(res, 200, getRegistry());596 if (p === '/api/registry/refresh' && req.method === 'POST') {597 audit({ kind: 'registry_refresh', ip: clientIp(req) });598 const r = await refreshRegistry('manual');599 return json(res, r.ok ? 200 : 502, { ...r, registry: getRegistry() });600 }601 if (p === '/api/registry/tooling' && req.method === 'POST') {602 audit({ kind: 'registry_tooling', ip: clientIp(req) });603 return json(res, 200, { nodes: await ensureAllNodesTooling({ force: true }) });604 }605 if (p === '/api/chats' && req.method === 'GET') {606 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);607 return json(res, 200, { chats: list });608 }609 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {610 const id = p.split('/')[3];611 const chat = getChat(id);612 if (chat && !running.has(id)) {613 chats = chats.filter(c => c.id !== id); saveChats();614 try { fs.unlinkSync(transcriptPath(id)); } catch {}615 return json(res, 200, { ok: true });616 }617 return json(res, 400, { error: 'introuvable ou en cours' });618 }619 // --- prompt bank ---620 if (p === '/api/prompts' && req.method === 'GET') {621 const list = [...prompts].sort((a, b) => (b.updated || 0) - (a.updated || 0));622 return json(res, 200, { prompts: list });623 }624 if (p === '/api/prompts' && req.method === 'POST') {625 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }626 const text = String(body.text || '').trim();627 if (!text) return json(res, 400, { error: 'texte vide' });628 const pr = {629 id: crypto.randomBytes(6).toString('hex'),630 title: (String(body.title || '').trim() || text.slice(0, 48)),631 text,632 project: resolveProject(body.project) ? body.project : null,633 fav: !!body.fav, uses: 0,634 created: Date.now(), updated: Date.now(),635 };636 prompts.push(pr); savePrompts();637 audit({ kind: 'prompt_save', id: pr.id });638 return json(res, 200, { prompt: pr });639 }640 if (p.startsWith('/api/prompts/') && req.method === 'PUT') {641 const id = p.split('/')[3];642 const pr = prompts.find(x => x.id === id);643 if (!pr) return json(res, 404, { error: 'introuvable' });644 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }645 if (typeof body.text === 'string' && body.text.trim()) pr.text = body.text.trim();646 if (typeof body.title === 'string') pr.title = body.title.trim() || pr.text.slice(0, 48);647 if ('project' in body) pr.project = resolveProject(body.project) ? body.project : null;648 if (typeof body.fav === 'boolean') pr.fav = body.fav;649 if (body.bumpUse) pr.uses = (pr.uses || 0) + 1;650 pr.updated = Date.now(); savePrompts();651 return json(res, 200, { prompt: pr });652 }653 if (p.startsWith('/api/prompts/') && req.method === 'DELETE') {654 const id = p.split('/')[3];655 prompts = prompts.filter(x => x.id !== id); savePrompts();656 return json(res, 200, { ok: true });657 }658 if (p === '/api/upgrade-prompt' && req.method === 'POST') {659 let body;660 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }661 const raw = String(body.prompt || '').trim();662 if (!raw) return json(res, 400, { error: 'prompt vide' });663 try {664 const project = resolveProject(body.project);665 const upgraded = await upgradePrompt(raw, project);666 audit({ kind: 'upgrade_prompt', project: body.project, len_in: raw.length, len_out: upgraded.length });667 return json(res, 200, { upgraded });668 } catch (e) {669 return json(res, 502, { error: e.message });670 }671 }672 if (p === '/api/analytics/summary') return json(res, 200, analyticsSummary(getSites()));673 if (p.startsWith('/api/analytics/series/')) return json(res, 200, analyticsSeries(p.split('/')[4], 30));674 if (p.startsWith('/api/analytics/site/')) return json(res, 200, analyticsSite(p.split('/')[4], Number(url.searchParams.get('days')) || 7));675 if (p === '/api/analytics/realtime') return json(res, 200, analyticsRealtime(getSites()));676 if (p === '/api/analytics/anomalies') return json(res, 200, analyticsAnomalies());677 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') }));678 if (p === '/api/analytics/classes') return json(res, 200, analyticsClasses(Number(url.searchParams.get('ms')) || 864e5));679 if (p === '/api/analytics/config' && req.method === 'GET') return json(res, 200, analyticsConfig());680 if (p === '/api/analytics/config' && req.method === 'PUT') {681 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }682 audit({ kind: 'analytics_config', ip: clientIp(req) });683 return json(res, 200, setAnalyticsConfig(body));684 }685 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());686 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });687 if (p === '/api/eco/nodes') return json(res, 200, ecoNodes());688 if (p.startsWith('/api/eco/site/')) {689 const d = ecoSite(p.split('/')[4]);690 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });691 }692693 // --- actions d'administration par site (pm2 / logs / commits) ---694 if (p === '/api/admin/action' && req.method === 'POST') {695 let body;696 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }697 const site = getSites().find(s => s.app === body.app);698 const action = ['restart', 'stop', 'start'].includes(body.action) ? body.action : null;699 if (!site || !action) return json(res, 400, { error: 'app ou action invalide' });700 audit({ kind: 'admin_action', app: site.app, node: site.node, action, ip: clientIp(req) });701 let out;702 if (site.unit) {703 // sites sous launchd (KA Guardian sur M4M36) — pas de pm2 sur ce nœud704 const cmds = {705 restart: `launchctl kickstart -k gui/$(id -u)/${site.unit}`,706 stop: `launchctl unload ~/Library/LaunchAgents/${site.unit}.plist`,707 start: `launchctl load ~/Library/LaunchAgents/${site.unit}.plist`,708 };709 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é"}')`);710 } else {711 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')"`);712 }713 return json(res, 200, { ok: !out.error, output: (out.stdout || out.error || '').trim().split('\n').pop(), full: (out.stdout || '').slice(-1500) });714 }715 if (p.startsWith('/api/admin/logs/')) {716 const site = getSites().find(s => s.app === p.split('/')[4]);717 if (!site) return json(res, 404, { error: 'site inconnu' });718 const out = site.log719 ? await runOnNode(site.node, `tail -70 ${site.log} 2>&1`)720 : await runOnNode(site.node, `pm2 logs ${site.pm2} --nostream --lines 60 2>&1 | tail -70`);721 return json(res, 200, { logs: out.stdout || out.error || '(vide)' });722 }723 if (p.startsWith('/api/admin/commits/')) {724 const site = getSites().find(s => s.app === p.split('/')[4]);725 if (!site) return json(res, 404, { error: 'site inconnu' });726 const out = await runOnNode(site.node, `cd ${site.repoDir || site.dir} && echo "=== derniers commits ===" && git log --oneline -8 && echo && echo "=== statut ===" && (git status --short | head -10; [ -z "$(git status --short)" ] && echo "propre ✓")`);727 return json(res, 200, { text: out.stdout || out.error || '(vide)' });728 }729 // --- Social : publication automatique + a la demande ---730 if (p === '/api/social/vncpw' && req.method === 'GET') return json(res, 200, { password: config.vncPassword || '492592' });731 if (p === '/api/social/state' && req.method === 'GET') {732 return json(res, 200, { state: socialState(), log: socialLog(40) });733 }734 if (p === '/api/social/auto' && req.method === 'POST') {735 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }736 audit({ kind: 'social_auto', on: !!body.on, ip: clientIp(req) });737 return json(res, 200, { state: setAuto(!!body.on) });738 }739 if (p === '/api/social/login' && req.method === 'GET') {740 try { return json(res, 200, { login: await fbLoginState() }); }741 catch (e) { return json(res, 502, { error: e.message }); }742 }743 if (p === '/api/social/generate' && req.method === 'POST') {744 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }745 try {746 const draft = await generateDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });747 audit({ kind: 'social_generate', site: draft.insight.site });748 return json(res, 200, { draft });749 } catch (e) { return json(res, 502, { error: e.message }); }750 }751 if (p === '/api/social/publish' && req.method === 'POST') {752 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }753 try {754 await publishDraft({ caption: String(body.caption || ''), image: cardPath(body.image || '') });755 audit({ kind: 'social_publish', ip: clientIp(req) });756 return json(res, 200, { ok: true });757 } catch (e) { return json(res, 502, { error: e.message }); }758 }759 if (p === '/api/social/run' && req.method === 'POST') {760 audit({ kind: 'social_run_now', ip: clientIp(req) });761 const r = await runAutoCycle('manuel');762 return json(res, r.ok ? 200 : 502, r);763 }764 if (p.startsWith('/api/social/card/') && req.method === 'GET') {765 const fp = cardPath(p.split('/')[4] || '');766 if (!fp) { res.writeHead(404); return res.end(); }767 res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache' });768 return res.end(fs.readFileSync(fp));769 }770 if (p === '/api/social/reel/generate' && req.method === 'POST') {771 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }772 try {773 const draft = await generateReelDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });774 audit({ kind: 'social_reel_generate', site: draft.insight.site });775 return json(res, 200, { draft });776 } catch (e) { return json(res, 502, { error: e.message }); }777 }778 if (p === '/api/social/reel/publish' && req.method === 'POST') {779 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }780 try {781 await publishReelDraft({ caption: String(body.caption || ''), video: reelPath(body.video || '') });782 audit({ kind: 'social_reel_publish', ip: clientIp(req) });783 return json(res, 200, { ok: true });784 } catch (e) { return json(res, 502, { error: e.message }); }785 }786 if (p === '/api/social/reel/run' && req.method === 'POST') {787 audit({ kind: 'social_reel_run', ip: clientIp(req) });788 const r = await runReelCycle('reel-manuel');789 return json(res, r.ok ? 200 : 502, r);790 }791 if (p === '/api/social/gallery' && req.method === 'GET') return json(res, 200, { items: getGallery(), gen: genBatchStatus() });792 if (p === '/api/social/reel/genbatch' && req.method === 'POST') {793 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }794 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;795 audit({ kind: 'social_genbatch', n: sites.length, ip: clientIp(req) });796 const r = startGenBatch(sites);797 return json(res, r.started ? 200 : 409, r);798 }799 if (p === '/api/social/reel/batch' && req.method === 'POST') {800 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }801 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;802 audit({ kind: 'social_reel_batch', n: sites.length, ip: clientIp(req) });803 const r = startReelBatch(sites);804 return json(res, r.started ? 200 : 409, r);805 }806 if (p === '/api/social/reel/batchstatus' && req.method === 'GET') return json(res, 200, batchStatus());807 if (p.startsWith('/api/social/reel/') && req.method === 'GET') {808 const fp = reelPath(p.split('/')[4] || '');809 if (!fp) { res.writeHead(404); return res.end(); }810 const stat = fs.statSync(fp);811 res.writeHead(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size, 'Cache-Control': 'no-cache' });812 return res.end(fs.readFileSync(fp));813 }814815 return json(res, 404, { error: 'not found' });816 }817818 // --- statique ---819 let file = p === '/' ? '/index.html' : p;820 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');821 const full = path.join(PUBLIC_DIR, file);822 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }823 fs.readFile(full, (err, data) => {824 if (err) { res.writeHead(404); return res.end('not found'); }825 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });826 res.end(data);827 });828});829830// ---------- WebSocket ----------831const wss = new WebSocketServer({ noServer: true });832833// --- pont VNC : WebSocket (noVNC dans l'admin) <-> Partage d'écran du nœud (127.0.0.1:5900) ---834const vncWss = new WebSocketServer({ noServer: true });835vncWss.on('connection', (ws) => {836 const tcp = net.connect(5900, '127.0.0.1');837 tcp.on('data', (d) => { if (ws.readyState === 1) ws.send(d); });838 tcp.on('close', () => { try { ws.close(); } catch {} });839 tcp.on('error', () => { try { ws.close(); } catch {} });840 ws.on('message', (d) => { try { tcp.write(d); } catch {} });841 ws.on('close', () => { try { tcp.end(); } catch {} });842 ws.on('error', () => { try { tcp.destroy(); } catch {} });843});844845server.on('upgrade', (req, socket, head) => {846 const url = new URL(req.url, 'http://x');847 if (!getSession(req)) {848 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');849 return socket.destroy();850 }851 if (url.pathname === '/ws') {852 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));853 } else if (url.pathname === '/vncws') {854 vncWss.handleUpgrade(req, socket, head, (ws) => vncWss.emit('connection', ws, req));855 } else {856 socket.write('HTTP/1.1 404 Not Found\r\n\r\n');857 socket.destroy();858 }859});860861wss.on('connection', (ws) => {862 ws.chatId = null;863 ws.eco = false;864 ws.isAlive = true;865 ws.on('pong', () => { ws.isAlive = true; });866 ws.on('message', (raw) => {867 let msg;868 try { msg = JSON.parse(raw.toString()); } catch { return; }869 try { handleWsMessage(ws, msg); } catch (e) {870 ws.send(JSON.stringify({ type: 'error', message: e.message }));871 }872 });873 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.874});875876setInterval(() => {877 for (const ws of wss.clients) {878 if (!ws.isAlive) { ws.terminate(); continue; }879 ws.isAlive = false; ws.ping();880 }881}, 30000);882883function handleWsMessage(ws, msg) {884 if (msg.type === 'open') {885 const chat = getChat(msg.chatId);886 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));887 ws.chatId = chat.id;888 // rejoue tout l'historique persisté puis raccroche le live889 ws.send(JSON.stringify({890 type: 'history',891 chat: publicChat(chat),892 events: readTranscript(chat.id),893 running: running.has(chat.id),894 }));895 return;896 }897 if (msg.type === 'start') {898 const prompt = String(msg.prompt || '').trim();899 if (!prompt) return;900 let chat = msg.chatId ? getChat(msg.chatId) : null;901 if (!chat) {902 const proj = resolveProject(msg.project) || getProjects()[0];903 if (!proj) { ws.send(JSON.stringify({ type: 'error', message: 'Aucun projet connu : le registre mld est indisponible (voir Réglages → Registre).' })); return; }904 chat = {905 id: crypto.randomBytes(8).toString('hex'),906 title: prompt.slice(0, 60),907 projectId: proj.id, projectName: proj.name,908 node: proj.node, dir: proj.dir,909 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,910 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',911 claudeSessionId: null, state: 'idle',912 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],913 created: Date.now(), updated: Date.now(),914 };915 chats.push(chat); saveChats();916 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));917 } else {918 if (MODELS.includes(msg.model)) chat.model = msg.model;919 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;920 saveChats();921 }922 ws.chatId = chat.id;923 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });924 startClaude(chat, prompt);925 return;926 }927 if (msg.type === 'start_all') {928 // diffuse le MÊME prompt à TOUTES les apps KA en parallèle (1 session/app)929 const prompt = String(msg.prompt || '').trim();930 if (!prompt) return;931 const model = MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL;932 const permMode = PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default';933 const created = [];934 const stamp = new Date().toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });935 const projectsNow = getProjects();936 for (const proj of projectsNow) {937 const chat = {938 id: crypto.randomBytes(8).toString('hex'),939 title: '🌐 ' + prompt.slice(0, 46),940 projectId: proj.id, projectName: proj.name,941 node: proj.node, dir: proj.dir,942 model, permMode,943 claudeSessionId: null, state: 'idle',944 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],945 batch: stamp,946 created: Date.now(), updated: Date.now(),947 };948 chats.push(chat);949 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });950 try { startClaude(chat, prompt); created.push(chat.id); }951 catch (e) { emitAndLog(chat.id, { type: 'error', message: e.message }); }952 }953 saveChats();954 audit({ kind: 'start_all', count: created.length, model, permMode, prompt: prompt.slice(0, 500) });955 ws.send(JSON.stringify({ type: 'batch_created', count: created.length, total: projectsNow.length }));956 return;957 }958 if (msg.type === 'set_opts') {959 const chat = getChat(msg.chatId);960 if (!chat) return;961 if (MODELS.includes(msg.model)) chat.model = msg.model;962 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;963 if (typeof msg.autoAllowAll === 'boolean') chat.autoAllowAll = msg.autoAllowAll;964 saveChats();965 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });966 return;967 }968 if (msg.type === 'clear') {969 const chat = getChat(msg.chatId);970 if (!chat || running.has(chat.id)) return;971 chat.claudeSessionId = null;972 chat.contextTokens = 0;973 saveChats();974 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });975 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });976 return;977 }978 if (msg.type === 'perm') {979 const pending = pendingPerms.get(msg.requestId);980 if (!pending) return;981 clearTimeout(pending.timer);982 pendingPerms.delete(msg.requestId);983 const chat = getChat(pending.chatId);984 if (msg.allow && msg.allowAll && chat) {985 // « Tout autoriser » : plus AUCUNE permission ne sera demandée pour cette986 // conversation — le serveur approuve tout jusqu'à la fin de la tâche987 chat.autoAllowAll = true;988 saveChats();989 emitAndLog(chat.id, { type: 'notice', text: '🔓 Tout autoriser activé — la tâche ira au bout sans autre demande de permission.' });990 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });991 }992 if (msg.allow && msg.always && chat) {993 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);994 saveChats();995 }996 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });997 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });998 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');999 pending.resolve(msg.allow1000 ? { behavior: 'allow', updatedInput: pending.input || {} }1001 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });1002 return;1003 }1004 if (msg.type === 'interrupt') {1005 if (msg.chatId) interrupt(msg.chatId);1006 else if (ws.chatId) interrupt(ws.chatId);1007 return;1008 }1009 if (msg.type === 'eco_sub') { ws.eco = true; return; }1010 if (msg.type === 'eco_unsub') { ws.eco = false; return; }1011}10121013// ---------- registre mld (topologie vivante) — AVANT le monitoring, qui en dépend ----------1014await initRegistry({1015 dataDir: DATA_DIR,1016 orchestratorDocPath: path.join(ORCH_DIR, 'CLAUDE.md'),1017 onChange: (events) => {1018 for (const ev of events) {1019 audit({ kind: 'registry_' + ev.kind, app: ev.app || null, from: ev.from || null, to: ev.to || null });1020 // alerte visible partout (bandeau) : une app a bougé, la console suit1021 broadcastAll({ type: 'eco_alert', kind: 'registry', site: ev.app || 'admin-ka', reason: describeRegistryEvent(ev), ts: Date.now() });1022 }1023 // les conversations rattachées à une app déplacée seront réalignées à leur prochain tour (realignChat)1024 broadcastAll({ type: 'projects', projects: listProjects() });1025 },1026});10271028// ---------- monitoring Écosystème ----------1029startMonitor({1030 dataDir: DATA_DIR,1031 onEvent: (ev) => {1032 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde1033 else broadcastEco(ev); // ticks → abonnés à l'onglet1034 },1035});10361037// module Social : publication automatique horaire + génération sur demande1038initSocial(1039 { anthropicKey: UPGRADER_KEY, upgraderModel: UPGRADER_MODEL,1040 socialModel: config.socialModel, socialIntervalMin: config.socialIntervalMin, reelEvery: config.reelEvery },1041 (line) => broadcastAll({ type: 'social_log', line }),1042);10431044initAnalytics();10451046// au démarrage, les chats marqués "running" par un ancien processus sont orphelins1047for (const c of chats) if (c.state !== 'idle') c.state = 'idle';1048saveChats();10491050server.listen(PORT, '::', () => {1051 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);1052});1053