Download scripts/agentweb-install.js from Cnass/Claude: direct link, hf CLI and curl.
- Browser
- Download file 27.3 kB
-
https://huggingface.co/spaces/Cnass/Claude/resolve/main/scripts/agentweb-install.js
- Command line
-
hf download hf://spaces/Cnass/Claude/scripts/agentweb-install.js
-
curl -L -o agentweb-install.js https://huggingface.co/spaces/Cnass/Claude/resolve/main/scripts/agentweb-install.js
27.3 kB
| // agentweb-install: installs that survive a Space restart. | |
| // | |
| // The Storage Bucket at /data keeps plain files, but not symlinks, hard links | |
| // or execute permissions. node_modules (.bin links, pnpm's linked layout), | |
| // Python virtualenvs (bin/python is a link) and `npm i -g` / `uv tool` bins | |
| // therefore break after every restart. This tool keeps the SOURCES on the | |
| // bucket and rebuilds the runnable part on local disk ($AGENTWEB_LOCAL), | |
| // automatically, at every start. | |
| // | |
| // agentweb-install mcp <name> --git <url> [--ref <branch>] [--sub <folder>] [--run "<cmd>"] [--env K=V ...] [--scope user|local] [--no-register] | |
| // agentweb-install mcp <name> --dir <path> ... (copies an existing folder) | |
| // agentweb-install mcp <name> --npm <package> ... (an MCP published on npm) | |
| // agentweb-install mcp <name> --pypi <package> ... (an MCP published on PyPI) | |
| // agentweb-install tool <pypi-package>... (uv tool install, restored at boot) | |
| // agentweb-install list | remove <name> | prepare [name] | restore | fix-bins | help | |
| // | |
| // MCP servers installed this way are registered as `agentweb-mcp-run <name>`, | |
| // which builds them on local disk when needed and then runs them. | |
| ; | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const os = require('os'); | |
| const crypto = require('crypto'); | |
| const { spawnSync, spawn } = require('child_process'); | |
| const HOME = process.env.HOME || os.homedir(); | |
| const LOCAL = process.env.AGENTWEB_LOCAL || '/home/node/.agentweb-local'; | |
| const SERVERS = path.join(HOME, 'mcp-servers'); | |
| const STATE_DIR = path.join(HOME, '.cc-web'); | |
| const RESTORE_FILE = path.join(STATE_DIR, 'restore.json'); | |
| const STATUS_FILE = path.join(STATE_DIR, 'restore-status.json'); | |
| const MANIFEST = 'agentweb.json'; | |
| const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; | |
| const COPY_SKIP = new Set(['node_modules', '.venv', 'venv', '.git', '__pycache__', '.pnpm-store', 'dist-cache']); | |
| const LOCK_WAIT_MS = 15 * 60 * 1000; | |
| function log(msg) { | |
| process.stderr.write(`[agentweb-install] ${msg}\n`); | |
| } | |
| function fail(msg, code = 1) { | |
| log(`HATA: ${msg}`); | |
| process.exit(code); | |
| } | |
| function readJson(file, fallback) { | |
| try { | |
| return JSON.parse(fs.readFileSync(file, 'utf8')); | |
| } catch { | |
| return fallback; | |
| } | |
| } | |
| function writeJson(file, data) { | |
| fs.mkdirSync(path.dirname(file), { recursive: true }); | |
| const tmp = `${file}.tmp-${process.pid}`; | |
| fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); | |
| fs.renameSync(tmp, file); | |
| } | |
| // Tools write to stderr only: stdout of agentweb-mcp-run is the MCP channel. | |
| function sh(cmd, args, opts = {}) { | |
| log(`$ ${[cmd, ...args].join(' ')}${opts.cwd ? ` (${opts.cwd})` : ''}`); | |
| const res = spawnSync(cmd, args, { | |
| stdio: ['ignore', 2, 2], | |
| env: { ...buildEnv(), ...(opts.env || {}) }, | |
| cwd: opts.cwd, | |
| timeout: opts.timeout || 20 * 60 * 1000, | |
| }); | |
| if (res.error) return { ok: false, error: res.error.message }; | |
| return { ok: res.status === 0, status: res.status }; | |
| } | |
| function which(name) { | |
| for (const dir of String(process.env.PATH || '').split(':')) { | |
| if (!dir) continue; | |
| const candidate = path.join(dir, name); | |
| try { | |
| fs.accessSync(candidate, fs.constants.X_OK); | |
| return candidate; | |
| } catch { | |
| // yok | |
| } | |
| } | |
| return null; | |
| } | |
| // Caches and package-manager homes on local disk: they are rebuilt freely | |
| // and must not leave broken links on the bucket. | |
| function buildEnv() { | |
| return { | |
| ...process.env, | |
| npm_config_cache: process.env.npm_config_cache || path.join(LOCAL, 'cache', 'npm'), | |
| UV_CACHE_DIR: process.env.UV_CACHE_DIR || path.join(LOCAL, 'cache', 'uv'), | |
| UV_PYTHON_INSTALL_DIR: process.env.UV_PYTHON_INSTALL_DIR || path.join(LOCAL, 'uv-python'), | |
| COREPACK_HOME: process.env.COREPACK_HOME || path.join(LOCAL, 'corepack'), | |
| COREPACK_ENABLE_DOWNLOAD_PROMPT: '0', | |
| npm_config_store_dir: path.join(LOCAL, 'pnpm-store'), | |
| PIP_CACHE_DIR: path.join(LOCAL, 'cache', 'pip'), | |
| npm_config_update_notifier: 'false', | |
| npm_config_fund: 'false', | |
| npm_config_audit: 'false', | |
| }; | |
| } | |
| // ---- manifests ---- | |
| function serverDir(name) { | |
| return path.join(SERVERS, name); | |
| } | |
| function manifestOf(name) { | |
| return readJson(path.join(serverDir(name), MANIFEST), null); | |
| } | |
| function buildDir(name) { | |
| return path.join(LOCAL, 'mcp', name); | |
| } | |
| function detectKind(src) { | |
| if (fs.existsSync(path.join(src, 'package.json'))) return 'node'; | |
| if (['pyproject.toml', 'requirements.txt', 'setup.py', 'uv.lock'].some((f) => fs.existsSync(path.join(src, f)))) return 'python'; | |
| return null; | |
| } | |
| // What to run when the user gave no --run: package.json bin/main/start, or | |
| // the Python project's script entry point. | |
| function defaultRun(kind, src) { | |
| if (kind === 'node') { | |
| const pkg = readJson(path.join(src, 'package.json'), {}); | |
| let entry = null; | |
| if (typeof pkg.bin === 'string') entry = pkg.bin; | |
| else if (pkg.bin && typeof pkg.bin === 'object') entry = Object.values(pkg.bin)[0]; | |
| if (!entry && pkg.main) entry = pkg.main; | |
| if (!entry && pkg.scripts && /^node\s+(\S+)/.test(pkg.scripts.start || '')) entry = /^node\s+(\S+)/.exec(pkg.scripts.start)[1]; | |
| if (!entry) entry = fs.existsSync(path.join(src, 'index.js')) ? 'index.js' : null; | |
| return entry ? ['node', `{build}/${entry.replace(/^\.\//, '')}`] : null; | |
| } | |
| if (kind === 'python') { | |
| const text = (() => { | |
| try { | |
| return fs.readFileSync(path.join(src, 'pyproject.toml'), 'utf8'); | |
| } catch { | |
| return ''; | |
| } | |
| })(); | |
| const scripts = /\[project\.scripts\]([\s\S]*?)(?:\n\[|$)/.exec(text); | |
| if (scripts) { | |
| const first = /^\s*([A-Za-z0-9_.-]+)\s*=/m.exec(scripts[1]); | |
| if (first) return [`{venv}/bin/${first[1]}`]; | |
| } | |
| const name = (/^\s*name\s*=\s*"([^"]+)"/m.exec(text) || [])[1]; | |
| if (name) return ['{venv}/bin/python', '-m', name.replace(/-/g, '_')]; | |
| return null; | |
| } | |
| return null; | |
| } | |
| function expand(arg, name, manifest) { | |
| const build = buildDir(name); | |
| return String(arg) | |
| .replace(/\{build\}/g, build) | |
| .replace(/\{src\}/g, serverDir(name)) | |
| .replace(/\{venv\}/g, path.join(build, '.venv')) | |
| .replace(/\{home\}/g, HOME) | |
| .replace(/\{local\}/g, LOCAL) | |
| .replace(/\{bin\}/g, path.join(build, 'node_modules', '.bin')); | |
| } | |
| function filesSignature(dir) { | |
| const hash = crypto.createHash('sha1'); | |
| const walk = (d, depth) => { | |
| if (depth > 12) return; | |
| let dirents; | |
| try { | |
| dirents = fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)); | |
| } catch { | |
| return; | |
| } | |
| for (const e of dirents) { | |
| if (COPY_SKIP.has(e.name)) continue; | |
| const child = path.join(d, e.name); | |
| if (e.isDirectory()) walk(child, depth + 1); | |
| else if (e.isFile()) { | |
| const st = fs.statSync(child); | |
| hash.update(`${path.relative(dir, child)}:${st.size}:${Math.round(st.mtimeMs)}\n`); | |
| } | |
| } | |
| }; | |
| walk(dir, 0); | |
| return hash.digest('hex').slice(0, 16); | |
| } | |
| function signature(name, manifest) { | |
| const h = crypto.createHash('sha1').update(JSON.stringify(manifest)); | |
| if (manifest.kind === 'node' || manifest.kind === 'python') h.update(filesSignature(serverDir(name))); | |
| return h.digest('hex').slice(0, 16); | |
| } | |
| function copySource(src, dest) { | |
| fs.rmSync(dest, { recursive: true, force: true }); | |
| fs.mkdirSync(dest, { recursive: true }); | |
| fs.cpSync(src, dest, { | |
| recursive: true, | |
| filter: (p) => !COPY_SKIP.has(path.basename(p)) || p === src, | |
| }); | |
| } | |
| function nodeInstall(dir) { | |
| const pkg = readJson(path.join(dir, 'package.json'), {}); | |
| let ok = false; | |
| if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) { | |
| const pm = typeof pkg.packageManager === 'string' && pkg.packageManager.startsWith('pnpm@') ? pkg.packageManager.split('+')[0] : 'pnpm@9'; | |
| ok = sh('npx', ['--yes', pm, 'install', '--frozen-lockfile'], { cwd: dir }).ok || sh('npx', ['--yes', pm, 'install'], { cwd: dir }).ok; | |
| } else if (fs.existsSync(path.join(dir, 'yarn.lock'))) { | |
| ok = sh('npx', ['--yes', 'yarn@1', 'install', '--frozen-lockfile'], { cwd: dir }).ok; | |
| } else if (fs.existsSync(path.join(dir, 'package-lock.json'))) { | |
| ok = sh('npm', ['ci'], { cwd: dir }).ok; | |
| } | |
| if (!ok) ok = sh('npm', ['install'], { cwd: dir }).ok; | |
| return ok; | |
| } | |
| // Builds the runnable copy of a server on local disk (skipped when nothing changed). | |
| function prepare(name, { force = false } = {}) { | |
| const manifest = manifestOf(name); | |
| if (!manifest) throw new Error(`"${name}" için ${MANIFEST} yok (agentweb-install mcp ile kurulmamış).`); | |
| const build = buildDir(name); | |
| const stampFile = path.join(build, '.agentweb-stamp'); | |
| const sig = signature(name, manifest); | |
| if (!force && fs.existsSync(stampFile) && fs.readFileSync(stampFile, 'utf8').trim() === sig) return { name, built: false }; | |
| return withLock(name, () => { | |
| if (!force && fs.existsSync(stampFile) && fs.readFileSync(stampFile, 'utf8').trim() === sig) return { name, built: false }; | |
| const started = Date.now(); | |
| log(`"${name}" yerel diske hazırlanıyor (${manifest.kind})…`); | |
| const src = serverDir(name); | |
| let ok = false; | |
| if (manifest.kind === 'node') { | |
| copySource(src, build); | |
| // A plain script without dependencies needs no install. | |
| ok = fs.existsSync(path.join(build, 'package.json')) ? nodeInstall(build) : true; | |
| const pkg = readJson(path.join(build, 'package.json'), {}); | |
| if (ok && manifest.build !== false && pkg.scripts && pkg.scripts.build && (manifest.build === true || !runTargetExists(name, manifest))) { | |
| ok = sh('npm', ['run', 'build'], { cwd: build }).ok; | |
| } | |
| } else if (manifest.kind === 'python') { | |
| fs.mkdirSync(build, { recursive: true }); | |
| const venv = path.join(build, '.venv'); | |
| if (fs.existsSync(path.join(src, 'pyproject.toml')) || fs.existsSync(path.join(src, 'uv.lock'))) { | |
| const env = { UV_PROJECT_ENVIRONMENT: venv }; | |
| ok = sh('uv', ['sync', '--frozen', '--directory', src], { env }).ok || sh('uv', ['sync', '--directory', src], { env }).ok; | |
| } else if (fs.existsSync(path.join(src, 'requirements.txt'))) { | |
| ok = sh('uv', ['venv', '--allow-existing', venv]).ok && sh('uv', ['pip', 'install', '-p', path.join(venv, 'bin', 'python'), '-r', path.join(src, 'requirements.txt')]).ok; | |
| } | |
| } else if (manifest.kind === 'npm') { | |
| fs.mkdirSync(build, { recursive: true }); | |
| ok = sh('npm', ['install', '--prefix', build, '--omit=dev', manifest.package]).ok; | |
| } else if (manifest.kind === 'pypi') { | |
| fs.mkdirSync(build, { recursive: true }); | |
| const venv = path.join(build, '.venv'); | |
| ok = sh('uv', ['venv', '--allow-existing', venv]).ok && sh('uv', ['pip', 'install', '-p', path.join(venv, 'bin', 'python'), manifest.package]).ok; | |
| } else { | |
| throw new Error(`Bilinmeyen tür: ${manifest.kind}`); | |
| } | |
| if (!ok) throw new Error(`"${name}" hazırlanamadı (yukarıdaki çıktıya bak).`); | |
| fs.writeFileSync(stampFile, `${sig}\n`); | |
| log(`"${name}" hazır (${Math.round((Date.now() - started) / 1000)} sn).`); | |
| return { name, built: true }; | |
| }); | |
| } | |
| function runTargetExists(name, manifest) { | |
| const run = (manifest.run || []).map((a) => expand(a, name, manifest)); | |
| return run.some((a) => a.startsWith(buildDir(name)) && fs.existsSync(a)); | |
| } | |
| // One build at a time per server (boot prepare + a starting Claude). | |
| function withLock(name, fn) { | |
| const lock = path.join(LOCAL, 'locks', `${name}.lock`); | |
| fs.mkdirSync(path.dirname(lock), { recursive: true }); | |
| const deadline = Date.now() + LOCK_WAIT_MS; | |
| for (;;) { | |
| try { | |
| fs.mkdirSync(lock); | |
| break; | |
| } catch { | |
| let stale = false; | |
| try { | |
| stale = Date.now() - fs.statSync(lock).mtimeMs > LOCK_WAIT_MS; | |
| } catch { | |
| stale = true; | |
| } | |
| if (stale) { | |
| fs.rmSync(lock, { recursive: true, force: true }); | |
| continue; | |
| } | |
| if (Date.now() > deadline) throw new Error(`"${name}" kilidi bekleme süresi doldu.`); | |
| Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 500); | |
| } | |
| } | |
| try { | |
| return fn(); | |
| } finally { | |
| fs.rmSync(lock, { recursive: true, force: true }); | |
| } | |
| } | |
| // agentweb-mcp-run <name>: make sure it is built, then become the server. | |
| function runServer(name) { | |
| const manifest = manifestOf(name); | |
| if (!manifest) fail(`"${name}" için ${MANIFEST} yok.`); | |
| try { | |
| prepare(name); | |
| } catch (err) { | |
| fail(err.message); | |
| } | |
| const run = (manifest.run || []).map((a) => expand(a, name, manifest)); | |
| if (!run.length) fail(`"${name}" için çalıştırma komutu yok (${MANIFEST} içinde "run").`); | |
| const env = { ...process.env, ...(manifest.env || {}) }; | |
| // Python projects run from their source folder (the venv is only the | |
| // dependencies); the others from the local build. | |
| const fromSrc = manifest.cwd === 'src' || (manifest.kind === 'python' && manifest.cwd !== 'build'); | |
| const cwd = fromSrc || !fs.existsSync(buildDir(name)) ? serverDir(name) : buildDir(name); | |
| if (manifest.kind === 'python') env.PYTHONPATH = [serverDir(name), env.PYTHONPATH].filter(Boolean).join(':'); | |
| const child = spawn(run[0], run.slice(1), { stdio: 'inherit', env, cwd }); | |
| child.on('error', (err) => fail(`çalıştırılamadı: ${err.message}`)); | |
| child.on('exit', (code, signal) => process.exit(signal ? 1 : code || 0)); | |
| for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(sig, () => child.kill(sig)); | |
| } | |
| function parseArgs(argv) { | |
| const out = { _: [], env: {} }; | |
| for (let i = 0; i < argv.length; i += 1) { | |
| const a = argv[i]; | |
| if (a === '--env' || a === '-e') { | |
| const kv = argv[++i] || ''; | |
| const at = kv.indexOf('='); | |
| if (at > 0) out.env[kv.slice(0, at)] = kv.slice(at + 1); | |
| } else if (a.startsWith('--no-')) { | |
| out[a.slice(5)] = false; | |
| } else if (a.startsWith('--')) { | |
| const key = a.slice(2); | |
| const next = argv[i + 1]; | |
| if (next !== undefined && !next.startsWith('--')) { | |
| out[key] = next; | |
| i += 1; | |
| } else { | |
| out[key] = true; | |
| } | |
| } else { | |
| out._.push(a); | |
| } | |
| } | |
| return out; | |
| } | |
| function splitCommand(text) { | |
| const out = []; | |
| const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g; | |
| let m; | |
| while ((m = re.exec(text))) out.push(m[1] !== undefined ? m[1].replace(/\\(.)/g, '$1') : m[2] !== undefined ? m[2] : m[3]); | |
| return out; | |
| } | |
| function claudeBin() { | |
| return which('claude') || '/usr/local/bin/claude'; | |
| } | |
| function register(name, scope, env) { | |
| const args = ['mcp', 'add', '--scope', scope]; | |
| for (const [k, v] of Object.entries(env || {})) args.push('-e', `${k}=${v}`); | |
| args.push(name, '--', 'agentweb-mcp-run', name); | |
| sh(claudeBin(), ['mcp', 'remove', '--scope', scope, name], {}); | |
| const res = sh(claudeBin(), args, {}); | |
| if (!res.ok) throw new Error('claude mcp add başarısız.'); | |
| } | |
| function installMcp(name, opts) { | |
| if (!NAME_RE.test(name || '')) fail('Geçersiz ad (harf, rakam, . _ -).'); | |
| const dest = serverDir(name); | |
| const manifest = { name, kind: null, run: null, env: opts.env || {}, createdAt: new Date().toISOString() }; | |
| if (opts.git) { | |
| if (fs.existsSync(dest) && !opts.force) fail(`${dest} zaten var (--force ile üzerine yaz).`); | |
| fs.rmSync(dest, { recursive: true, force: true }); | |
| const tmp = path.join(LOCAL, 'tmp', `${name}-${Date.now()}`); | |
| fs.mkdirSync(path.dirname(tmp), { recursive: true }); | |
| const args = ['clone', '--depth', '1']; | |
| if (opts.ref) args.push('--branch', String(opts.ref)); | |
| args.push(String(opts.git), tmp); | |
| if (!sh('git', args).ok) fail('git clone başarısız.'); | |
| const from = opts.sub ? path.join(tmp, String(opts.sub)) : tmp; | |
| copySource(from, dest); | |
| fs.rmSync(tmp, { recursive: true, force: true }); | |
| manifest.source = { git: String(opts.git), ref: opts.ref || null, sub: opts.sub || null }; | |
| } else if (opts.dir) { | |
| const from = path.resolve(String(opts.dir)); | |
| if (!fs.existsSync(from)) fail(`${from} yok.`); | |
| if (path.resolve(from) !== path.resolve(dest)) copySource(from, dest); | |
| manifest.source = { dir: from }; | |
| } else if (opts.npm) { | |
| fs.mkdirSync(dest, { recursive: true }); | |
| manifest.kind = 'npm'; | |
| manifest.package = String(opts.npm); | |
| } else if (opts.pypi) { | |
| fs.mkdirSync(dest, { recursive: true }); | |
| manifest.kind = 'pypi'; | |
| manifest.package = String(opts.pypi); | |
| } else { | |
| fail('Kaynak gerekli: --git <url> | --dir <klasör> | --npm <paket> | --pypi <paket>'); | |
| } | |
| if (!manifest.kind) manifest.kind = opts.kind || detectKind(dest); | |
| if (!manifest.kind) fail('Tür anlaşılamadı (package.json / pyproject.toml / requirements.txt yok); --kind node|python ver.'); | |
| if (opts.run) manifest.run = splitCommand(String(opts.run)); | |
| else if (manifest.kind === 'npm' || manifest.kind === 'pypi') { | |
| const bin = opts.bin || String(manifest.package).replace(/^@[^/]+\//, '').replace(/[@=<>].*$/, ''); | |
| manifest.run = [manifest.kind === 'npm' ? `{bin}/${bin}` : `{venv}/bin/${bin}`]; | |
| } else manifest.run = defaultRun(manifest.kind, dest); | |
| if (!manifest.run) fail('Çalıştırma komutu bulunamadı; --run "node {build}/dist/index.js" gibi ver.'); | |
| if (opts.cwd === 'src') manifest.cwd = 'src'; | |
| writeJson(path.join(dest, MANIFEST), manifest); | |
| try { | |
| prepare(name, { force: true }); | |
| } catch (err) { | |
| fail(err.message); | |
| } | |
| if (opts.register !== false) { | |
| register(name, opts.scope === 'local' ? 'local' : 'user', manifest.env); | |
| log(`"${name}" kaydedildi (agentweb-mcp-run ${name}). Agent Web'de MCP sunucuları → "Claude'u yeniden başlat" ile yüklenir.`); | |
| } | |
| log(`Kaynak: ${dest} (kalıcı) · Çalışan kopya: ${buildDir(name)} (her açılışta otomatik yeniden kurulur).`); | |
| } | |
| // ---- tools (uv tool) and npm globals ---- | |
| function restoreList() { | |
| const data = readJson(RESTORE_FILE, {}); | |
| return { uvTools: Array.isArray(data.uvTools) ? data.uvTools : [], pipx: Array.isArray(data.pipx) ? data.pipx : [] }; | |
| } | |
| function addRestore(kind, specs) { | |
| const data = restoreList(); | |
| for (const spec of specs) { | |
| const clean = String(spec).trim(); | |
| if (!clean || clean.startsWith('-')) continue; | |
| const base = clean.replace(/[@=<>!~].*$/, ''); | |
| data[kind] = data[kind].filter((s) => s.replace(/[@=<>!~].*$/, '') !== base); | |
| data[kind].push(clean); | |
| } | |
| writeJson(RESTORE_FILE, data); | |
| } | |
| function uvToolEnv() { | |
| return { UV_TOOL_DIR: path.join(LOCAL, 'uv-tools'), UV_TOOL_BIN_DIR: path.join(LOCAL, 'bin') }; | |
| } | |
| function installTools(specs) { | |
| for (const spec of specs) { | |
| if (!sh('uv', ['tool', 'install', '--force', spec], { env: uvToolEnv() }).ok) log(`"${spec}" kurulamadı.`); | |
| } | |
| addRestore('uvTools', specs); | |
| } | |
| // Wrappers for programs whose links were lost: npm globals under | |
| // ~/.local/lib/node_modules and plain scripts in ~/.local/bin. | |
| function fixBins() { | |
| const binDir = path.join(LOCAL, 'bin'); | |
| fs.mkdirSync(binDir, { recursive: true }); | |
| let made = 0; | |
| const userBin = path.join(HOME, '.local', 'bin'); | |
| try { | |
| for (const f of fs.readdirSync(userBin)) { | |
| const p = path.join(userBin, f); | |
| try { | |
| const st = fs.lstatSync(p); | |
| if (st.isFile() && (st.mode & 0o111) !== 0o111) { | |
| fs.chmodSync(p, st.mode | 0o755); | |
| made += 1; | |
| } | |
| } catch { | |
| // yok say | |
| } | |
| } | |
| } catch { | |
| // klasor yok | |
| } | |
| const globalRoot = path.join(HOME, '.local', 'lib', 'node_modules'); | |
| let pkgs = []; | |
| try { | |
| pkgs = fs.readdirSync(globalRoot).flatMap((d) => (d.startsWith('@') ? fs.readdirSync(path.join(globalRoot, d)).map((s) => `${d}/${s}`) : [d])); | |
| } catch { | |
| pkgs = []; | |
| } | |
| for (const pkgName of pkgs) { | |
| const dir = path.join(globalRoot, pkgName); | |
| const pkg = readJson(path.join(dir, 'package.json'), null); | |
| if (!pkg || !pkg.bin) continue; | |
| const bins = typeof pkg.bin === 'string' ? { [pkgName.replace(/^@[^/]+\//, '')]: pkg.bin } : pkg.bin; | |
| for (const [binName, rel] of Object.entries(bins)) { | |
| if (!/^[A-Za-z0-9._-]+$/.test(binName)) continue; | |
| const target = path.join(dir, rel); | |
| if (!fs.existsSync(target)) continue; | |
| const head = fs.readFileSync(target).subarray(0, 120).toString(); | |
| const isNode = /\.(c|m)?js$/.test(target) || /^#!.*\bnode\b/.test(head); | |
| const wrapper = isNode ? `#!/bin/sh\nexec node "${target}" "$@"\n` : `#!/bin/sh\nexec "${target}" "$@"\n`; | |
| if (!isNode) { | |
| try { | |
| fs.chmodSync(target, 0o755); | |
| } catch { | |
| // yok say | |
| } | |
| } | |
| const out = path.join(binDir, binName); | |
| fs.writeFileSync(out, wrapper, { mode: 0o755 }); | |
| fs.chmodSync(out, 0o755); | |
| made += 1; | |
| } | |
| } | |
| return made; | |
| } | |
| // ---- recording installs made by plain commands (PostToolUse hook) ---- | |
| function recordFromCommand(command) { | |
| const recorded = []; | |
| for (const part of String(command || '').split(/&&|\|\||;|\n/)) { | |
| const words = splitCommand(part.trim()); | |
| const at = words.findIndex((w) => w === 'uv' || w === 'pipx'); | |
| if (at === -1) continue; | |
| const w = words.slice(at); | |
| if (w[0] === 'uv' && w[1] === 'tool' && w[2] === 'install') { | |
| const specs = w.slice(3).filter((x) => !x.startsWith('-')); | |
| if (specs.length) { | |
| addRestore('uvTools', specs.slice(0, 1)); | |
| recorded.push(...specs.slice(0, 1)); | |
| } | |
| } else if (w[0] === 'pipx' && w[1] === 'install') { | |
| const specs = w.slice(2).filter((x) => !x.startsWith('-')); | |
| if (specs.length) { | |
| addRestore('uvTools', specs.slice(0, 1)); | |
| recorded.push(...specs.slice(0, 1)); | |
| } | |
| } | |
| } | |
| return recorded; | |
| } | |
| function recordHook() { | |
| let raw = ''; | |
| process.stdin.setEncoding('utf8'); | |
| process.stdin.on('data', (c) => { | |
| raw += c; | |
| }); | |
| process.stdin.on('end', () => { | |
| try { | |
| const event = JSON.parse(raw); | |
| if (event.tool_name !== 'Bash') return; | |
| const cmd = event.tool_input && event.tool_input.command; | |
| const recorded = recordFromCommand(cmd); | |
| if (recorded.length) { | |
| process.stdout.write( | |
| JSON.stringify({ | |
| hookSpecificOutput: { | |
| hookEventName: 'PostToolUse', | |
| additionalContext: `Agent Web: ${recorded.join(', ')} is recorded and will be reinstalled automatically after every restart (uv tool venvs cannot live on the Storage Bucket).`, | |
| }, | |
| }) | |
| ); | |
| } | |
| } catch { | |
| // sessiz | |
| } | |
| }); | |
| } | |
| // ---- boot restore ---- | |
| function managedServers() { | |
| try { | |
| return fs.readdirSync(SERVERS).filter((d) => fs.existsSync(path.join(SERVERS, d, MANIFEST))); | |
| } catch { | |
| return []; | |
| } | |
| } | |
| function restoreAll() { | |
| const status = { startedAt: new Date().toISOString(), bins: 0, tools: [], mcp: [], errors: [] }; | |
| const save = () => writeJson(STATUS_FILE, status); | |
| status.bins = fixBins(); | |
| save(); | |
| for (const name of managedServers()) { | |
| try { | |
| const r = prepare(name); | |
| status.mcp.push({ name, ok: true, built: r.built }); | |
| } catch (err) { | |
| status.mcp.push({ name, ok: false, error: err.message }); | |
| status.errors.push(`${name}: ${err.message}`); | |
| } | |
| save(); | |
| } | |
| const { uvTools } = restoreList(); | |
| for (const spec of uvTools) { | |
| const ok = sh('uv', ['tool', 'install', '--force', spec], { env: uvToolEnv() }).ok; | |
| status.tools.push({ spec, ok }); | |
| if (!ok) status.errors.push(`${spec}: kurulamadı`); | |
| save(); | |
| } | |
| status.endedAt = new Date().toISOString(); | |
| save(); | |
| log(`geri yükleme bitti: ${status.mcp.length} MCP, ${status.tools.length} araç, ${status.bins} program bağlantısı${status.errors.length ? `, ${status.errors.length} hata` : ''}.`); | |
| } | |
| function list() { | |
| const servers = managedServers().map((name) => { | |
| const m = manifestOf(name); | |
| const stamp = path.join(buildDir(name), '.agentweb-stamp'); | |
| return ` ${name} [${m.kind}] ${(m.run || []).join(' ')} ${fs.existsSync(stamp) ? 'hazır' : 'hazırlanmadı'}`; | |
| }); | |
| const { uvTools } = restoreList(); | |
| process.stdout.write( | |
| [ | |
| 'MCP sunucuları (~/mcp-servers, agentweb-mcp-run ile):', | |
| ...(servers.length ? servers : [' (yok)']), | |
| 'Açılışta yeniden kurulan araçlar (uv tool):', | |
| ...(uvTools.length ? uvTools.map((t) => ` ${t}`) : [' (yok)']), | |
| '', | |
| ].join('\n') | |
| ); | |
| } | |
| const HELP = `agentweb-install: Space yeniden başlasa da çalışan kurulumlar. | |
| Kalıcı disk (Storage Bucket) symlink ve çalıştırma iznini saklamaz; bu araç kaynakları | |
| ~/mcp-servers altında tutar, çalışan kopyayı her açılışta yerel diske otomatik kurar. | |
| agentweb-install mcp <ad> --git <url> [--ref <dal>] [--sub <alt-klasör>] [--run "<komut>"] [--env K=V] [--scope user|local] | |
| agentweb-install mcp <ad> --dir <klasör> [...] var olan bir klasörden | |
| agentweb-install mcp <ad> --npm <paket> [--bin <ad>] npm'deki bir MCP | |
| agentweb-install mcp <ad> --pypi <paket> [--bin <ad>] PyPI'daki bir MCP | |
| agentweb-install tool <pypi-paketi>... uv tool kurulumu (açılışta geri gelir) | |
| agentweb-install list | remove <ad> | prepare [ad] | restore | fix-bins | |
| --run içinde: {build} çalışan kopya, {src} kaynak, {venv} Python ortamı, {bin} node_modules/.bin. | |
| Örnek: agentweb-install mcp pixel --git https://github.com/ehm-93/pixel-mcp --env PIXEL_MCP_DATA_DIR=$HOME/pixel-mcp-data | |
| `; | |
| function main() { | |
| const invoked = path.basename(process.argv[1] || ''); | |
| const argv = process.argv.slice(2); | |
| if (invoked === 'agentweb-mcp-run' || argv[0] === 'run') { | |
| const name = invoked === 'agentweb-mcp-run' ? argv[0] : argv[1]; | |
| if (!name || !NAME_RE.test(name)) fail('Kullanım: agentweb-mcp-run <ad>'); | |
| runServer(name); | |
| return; | |
| } | |
| const opts = parseArgs(argv); | |
| const [cmd, ...rest] = opts._; | |
| switch (cmd) { | |
| case 'mcp': | |
| installMcp(rest[0], opts); | |
| break; | |
| case 'tool': | |
| if (!rest.length) fail('Paket adı gerekli.'); | |
| installTools(rest); | |
| break; | |
| case 'prepare': | |
| for (const name of rest.length ? rest : managedServers()) { | |
| try { | |
| prepare(name, { force: !!opts.force }); | |
| } catch (err) { | |
| log(`${name}: ${err.message}`); | |
| process.exitCode = 1; | |
| } | |
| } | |
| break; | |
| case 'restore': | |
| restoreAll(); | |
| break; | |
| case 'fix-bins': | |
| log(`${fixBins()} program bağlantısı/izni düzeltildi.`); | |
| break; | |
| case 'record-hook': | |
| recordHook(); | |
| break; | |
| case 'list': | |
| list(); | |
| break; | |
| case 'remove': { | |
| const name = rest[0]; | |
| if (!NAME_RE.test(name || '')) fail('Ad gerekli.'); | |
| sh(claudeBin(), ['mcp', 'remove', '--scope', 'user', name], {}); | |
| fs.rmSync(buildDir(name), { recursive: true, force: true }); | |
| if (opts.source) fs.rmSync(serverDir(name), { recursive: true, force: true }); | |
| log(`"${name}" kaldırıldı${opts.source ? ' (kaynak dahil)' : ' (kaynak ~/mcp-servers içinde duruyor; --source ile o da silinir)'}.`); | |
| break; | |
| } | |
| case 'help': | |
| case undefined: | |
| process.stdout.write(HELP); | |
| break; | |
| default: | |
| fail(`Bilinmeyen komut: ${cmd}\n${HELP}`); | |
| } | |
| } | |
| if (require.main === module) main(); | |
| module.exports = { detectKind, defaultRun, recordFromCommand, splitCommand, fixBins, prepare, managedServers, manifestOf, serverDir, buildDir, MANIFEST, LOCAL }; | |