SPB Git

spb/admin-ka

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

Theme