File size: 27,293 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
#!/usr/bin/env node
// 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.
'use strict';

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 };