File size: 10,244 Bytes
765fe0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | #!/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/<dir>/<rest> 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/<prog> ... or ~/mcp-servers/x/node_modules/.bin/<prog> ...
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 };
|