#!/usr/bin/env node // Runs at every container start (scripts/entrypoint.sh), before the server. // Quick part (foreground): // - programs whose links/permissions the Storage Bucket lost get wrappers // (npm globals, ~/.local/bin scripts) and skills get their execute bits; // - MCP servers registered straight from ~/mcp-servers (their node_modules or // venv break on every restart) are moved to agentweb-mcp-run, which keeps // the source on the bucket and builds the runnable copy on local disk. // Slow part (background, --background): // - every managed MCP server and recorded tool is (re)built on local disk; // - once: tokens/passwords in old chat logs and Claude transcripts are masked. 'use strict'; const fs = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const install = require(path.join(__dirname, 'agentweb-install.js')); let redact = null; let skills = null; try { redact = require(path.join(__dirname, '..', 'server', 'redact.js')); skills = require(path.join(__dirname, '..', 'server', 'skills.js')); } catch { redact = null; } const HOME = process.env.HOME; const SERVERS = path.join(HOME, 'mcp-servers'); const STATE_DIR = path.join(HOME, '.cc-web'); const REDACT_MARK = path.join(STATE_DIR, 'redacted-v1'); const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; function log(msg) { console.log(`[boot] ${msg}`); } function readJson(file, fallback) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; } } // ~/mcp-servers// for a path inside the servers folder. function serverPath(p) { if (typeof p !== 'string') return null; const abs = p.replace(/^~(?=\/)/, HOME); const root = SERVERS + path.sep; if (!abs.startsWith(root)) return null; const rel = abs.slice(root.length); const dir = rel.split('/')[0]; if (!NAME_RE.test(dir)) return null; return { dir, rest: rel.slice(dir.length + 1) }; } // The manifest an existing hand-made MCP entry corresponds to, or null. function manifestFor(entry) { if (!entry || typeof entry !== 'object' || (entry.type && entry.type !== 'stdio')) return null; const cmd = String(entry.command || ''); const args = Array.isArray(entry.args) ? entry.args.map(String) : []; if (cmd === 'agentweb-mcp-run' || /agentweb-mcp-run$/.test(cmd)) return null; // node ~/mcp-servers/x/dist/index.js ... if (/(^|\/)node$/.test(cmd) && args.length) { const sp = serverPath(args[0]); if (sp) return { dir: sp.dir, kind: 'node', run: ['node', `{build}/${sp.rest}`, ...args.slice(1)] }; } // uv --directory ~/mcp-servers/x run [-m mod | script] ... if (/(^|\/)uv$/.test(cmd)) { const at = args.indexOf('--directory'); const sp = at >= 0 ? serverPath(args[at + 1]) : null; const runAt = args.indexOf('run'); if (sp && runAt >= 0) { const rest = args.slice(runAt + 1).filter((a) => a !== '--frozen' && a !== '--no-sync'); if (rest[0] === '-m' || rest[0] === 'python') return { dir: sp.dir, kind: 'python', run: ['{venv}/bin/python', ...(rest[0] === 'python' ? rest.slice(1) : rest)] }; if (rest[0]) return { dir: sp.dir, kind: 'python', run: [`{venv}/bin/${rest[0]}`, ...rest.slice(1)] }; } } // ~/mcp-servers/x/.venv/bin/ ... or ~/mcp-servers/x/node_modules/.bin/ ... const sp = serverPath(cmd); if (sp) { const venv = /^(?:\.venv|venv)\/bin\/(.+)$/.exec(sp.rest); if (venv) return { dir: sp.dir, kind: 'python', run: [`{venv}/bin/${venv[1]}`, ...args] }; const nbin = /^node_modules\/\.bin\/(.+)$/.exec(sp.rest); if (nbin) return { dir: sp.dir, kind: 'node', run: [`{bin}/${nbin[1]}`, ...args] }; } return null; } function migrateMcp() { const configFile = path.join(HOME, '.claude.json'); const config = readJson(configFile, null); if (!config || typeof config !== 'object') return 0; const lists = [config.mcpServers]; for (const project of Object.values(config.projects || {})) if (project && project.mcpServers) lists.push(project.mcpServers); let changed = 0; for (const servers of lists) { if (!servers || typeof servers !== 'object') continue; for (const [name, entry] of Object.entries(servers)) { const m = manifestFor(entry); if (!m) continue; const src = path.join(SERVERS, m.dir); if (!fs.existsSync(src)) continue; const manifestFile = path.join(src, install.MANIFEST); if (!fs.existsSync(manifestFile)) { const kind = install.detectKind(src) || m.kind; const manifest = { name: m.dir, kind, run: m.run, env: {}, createdAt: new Date().toISOString(), migratedFrom: { command: entry.command, args: entry.args } }; fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`); } servers[name] = { type: 'stdio', command: 'agentweb-mcp-run', args: [m.dir], env: entry.env || {} }; changed += 1; log(`MCP "${name}" agentweb-mcp-run'a taşındı (kaynak ${src}; çalışan kopya yerel diskte kurulacak).`); } } if (changed) { const backup = `${configFile}.agentweb-backup-mcp`; if (!fs.existsSync(backup)) fs.copyFileSync(configFile, backup); const tmp = `${configFile}.agentweb-tmp`; fs.writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); fs.renameSync(tmp, configFile); } return changed; } async function restoreSkillBits() { if (!skills) return 0; let count = 0; for (const root of [path.join(HOME, '.claude', 'skills'), path.join(HOME, '.claude', 'plugins', 'cache')]) { if (fs.existsSync(root)) count += await skills.restoreExecBits(root); } return count; } function* jsonlFiles(dir, depth = 0) { if (depth > 5) return; let dirents; try { dirents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const d of dirents) { const p = path.join(dir, d.name); if (d.isDirectory()) yield* jsonlFiles(p, depth + 1); else if (d.isFile() && d.name.endsWith('.jsonl')) yield p; } } // Tokens pasted or echoed in earlier conversations (git clone URLs with a // token, export FOO_TOKEN=...) are masked in the logs, once. function redactOldLogs() { if (!redact || fs.existsSync(REDACT_MARK)) return; const roots = [path.join(STATE_DIR, 'chats'), path.join(HOME, '.claude', 'projects')]; let files = 0; let changedFiles = 0; for (const root of roots) { for (const file of jsonlFiles(root)) { files += 1; try { const text = fs.readFileSync(file, 'utf8'); const out = text .split('\n') .map((line) => (line ? redact.redactJsonLine(line) : line)) .join('\n'); if (out !== text) { const tmp = `${file}.redact-tmp`; fs.writeFileSync(tmp, out); fs.renameSync(tmp, file); changedFiles += 1; } } catch (err) { log(`${file} maskelenemedi: ${err.message}`); } } } for (const file of [path.join(HOME, '.claude', 'history.jsonl')]) { try { const text = fs.readFileSync(file, 'utf8'); const out = redact.redactText(text); if (out !== text) { fs.writeFileSync(file, out); changedFiles += 1; } } catch { // yok } } fs.mkdirSync(STATE_DIR, { recursive: true }); fs.writeFileSync(REDACT_MARK, `${new Date().toISOString()} ${changedFiles}/${files}\n`); log(`eski kayıtlardaki gizli anahtarlar maskelendi: ${changedFiles}/${files} dosya.`); } // pnpm projects on the bucket get a flat node_modules (no symlinks to lose) // and keep their store on local disk. pnpm's own config file, so npm does // not warn about settings it does not know. function pnpmDefaults() { const dir = path.join(process.env.XDG_CONFIG_HOME || path.join(HOME, '.config'), 'pnpm'); const file = path.join(dir, 'rc'); let text = ''; try { text = fs.readFileSync(file, 'utf8'); } catch { text = ''; } const add = []; if (!/^\s*node-linker\s*=/m.test(text)) add.push('node-linker=hoisted'); if (!/^\s*store-dir\s*=/m.test(text)) add.push(`store-dir=${path.join(install.LOCAL, 'pnpm-store')}`); if (!add.length) return; fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, `${text}${text && !text.endsWith('\n') ? '\n' : ''}# Agent Web: bucket symlink saklamaz\n${add.join('\n')}\n`); } async function foreground() { fs.mkdirSync(path.join(install.LOCAL, 'bin'), { recursive: true }); try { pnpmDefaults(); } catch (err) { log(`pnpm ayari yazilamadi: ${err.message}`); } try { const n = install.fixBins(); if (n) log(`${n} program bağlantısı/izni onarıldı.`); } catch (err) { log(`programlar onarılamadı: ${err.message}`); } try { migrateMcp(); } catch (err) { log(`MCP taşıma hatası: ${err.message}`); } try { const n = await restoreSkillBits(); if (n) log(`${n} skill dosyasının çalıştırma izni geri verildi.`); } catch (err) { log(`skill izinleri: ${err.message}`); } // The slow part goes on in the background; the app starts right away. const logFile = path.join(STATE_DIR, 'boot.log'); fs.mkdirSync(STATE_DIR, { recursive: true }); try { if (fs.statSync(logFile).size > 2 * 1024 * 1024) fs.renameSync(logFile, `${logFile}.1`); } catch { // ilk kez } const out = fs.openSync(logFile, 'a'); const child = spawn(process.execPath, [__filename, '--background'], { detached: true, stdio: ['ignore', out, out], env: process.env }); child.unref(); log(`MCP sunucuları ve araçlar arka planda hazırlanıyor (günlük: ${logFile}).`); } function background() { console.log(`---- ${new Date().toISOString()} ----`); try { redactOldLogs(); } catch (err) { log(`maskeleme: ${err.message}`); } const res = require('child_process').spawnSync(process.execPath, [path.join(__dirname, 'agentweb-install.js'), 'restore'], { stdio: 'inherit', env: process.env }); if (res.status !== 0) log('geri yükleme hatayla bitti.'); } if (require.main === module) { if (!HOME) process.exit(0); if (process.argv.includes('--background')) background(); else foreground().catch((err) => log(`hata: ${err.message}`)); } module.exports = { manifestFor, migrateMcp, redactOldLogs };