SPB Git

spb/admin-ka

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

Theme