forked from agent-sh/agentsys
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·2027 lines (1779 loc) · 68.8 KB
/
cli.js
File metadata and controls
executable file
·2027 lines (1779 loc) · 68.8 KB
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* AgentSys CLI installer
*
* Install: npm install -g agentsys@latest
* Run: agentsys
* Update: npm update -g agentsys
* Remove: npm uninstall -g agentsys && agentsys --remove
*/
const { execSync, execFileSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const https = require('https');
const { createGunzip } = require('zlib');
const VERSION = require('../package.json').version;
// Use the installed npm package directory as source (no git clone needed)
const PACKAGE_DIR = path.join(__dirname, '..');
const discovery = require('../lib/discovery');
const transforms = require('../lib/adapter-transforms');
// Valid tool names
const VALID_TOOLS = ['claude', 'opencode', 'codex', 'cursor'];
function getInstallDir() {
const home = process.env.HOME || process.env.USERPROFILE;
return path.join(home, '.agentsys');
}
function getClaudePluginsDir() {
const home = process.env.HOME || process.env.USERPROFILE;
return path.join(home, '.claude', 'plugins');
}
function getOpenCodeConfigDir() {
const home = process.env.HOME || process.env.USERPROFILE;
const xdgConfigHome = process.env.XDG_CONFIG_HOME;
if (xdgConfigHome && xdgConfigHome.trim()) {
return path.join(xdgConfigHome, 'opencode');
}
return path.join(home, '.config', 'opencode');
}
function getConfigPath(platform) {
if (platform === 'opencode') {
return path.join(getOpenCodeConfigDir(), 'opencode.json');
}
if (platform === 'codex') {
const home = process.env.HOME || process.env.USERPROFILE;
return path.join(home, '.codex', 'config.toml');
}
return null;
}
function commandExists(cmd) {
try {
execFileSync(process.platform === 'win32' ? 'where.exe' : 'which', [cmd], { stdio: 'pipe' });
return true;
} catch {
return false;
}
}
function copyDirRecursive(src, dest) {
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyDirRecursive(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
function parseArgs(args) {
const result = {
help: false,
version: false,
remove: false,
development: false,
stripModels: true, // Default: strip models
tool: null, // Single tool
tools: [], // Multiple tools
only: [], // --only flag: selective plugin install
subcommand: null, // 'update', 'list', 'install', 'remove', 'search'
subcommandArg: null, // argument for subcommand (e.g. plugin name)
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--help' || arg === '-h') {
result.help = true;
} else if (arg === '--version' || arg === '-v') {
result.version = true;
} else if (arg === '--remove' || arg === '--uninstall') {
result.remove = true;
} else if (arg === '--development' || arg === '--dev') {
result.development = true;
} else if (arg === '--no-strip' || arg === '-ns') {
result.stripModels = false;
} else if (arg === '--strip-models') {
// Legacy flag, now default behavior
result.stripModels = true;
} else if (arg === '--only' && args[i + 1]) {
const pluginList = args[i + 1].split(',').map(p => p.trim()).filter(Boolean);
result.only.push(...pluginList);
i++;
} else if (arg === '--tool' && args[i + 1]) {
const tool = args[i + 1].toLowerCase();
if (VALID_TOOLS.includes(tool)) {
result.tool = tool;
} else {
console.error(`[ERROR] Invalid tool: ${tool}. Valid options: ${VALID_TOOLS.join(', ')}`);
process.exit(1);
}
i++;
} else if (arg === '--tools' && args[i + 1]) {
const toolList = args[i + 1].toLowerCase().split(',').map(t => t.trim());
for (const tool of toolList) {
if (!VALID_TOOLS.includes(tool)) {
console.error(`[ERROR] Invalid tool: ${tool}. Valid options: ${VALID_TOOLS.join(', ')}`);
process.exit(1);
}
result.tools.push(tool);
}
i++;
} else if (['update', 'list', 'install', 'remove', 'search'].includes(arg)) {
result.subcommand = arg;
// Check for subcommand --help
if (args[i + 1] && (args[i + 1] === '--help' || args[i + 1] === '-h')) {
result.subcommandArg = '--help';
i++;
// For 'list': accept --all, --agents, --skills, --commands, --hooks, --plugins
} else if (arg === 'list' && args[i + 1] && ['--all', '--agents', '--skills', '--commands', '--hooks', '--plugins'].includes(args[i + 1])) {
result.subcommandArg = args[i + 1];
i++;
} else if (args[i + 1] && !args[i + 1].startsWith('-')) {
result.subcommandArg = args[i + 1];
i++;
}
}
}
// Environment variable override for strip models (legacy support)
if (['0', 'false', 'no'].includes((process.env.AGENTSYS_STRIP_MODELS || '').toLowerCase())) {
result.stripModels = false;
}
return result;
}
async function multiSelect(question, options) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log(`\n${question}\n`);
console.log('Enter numbers separated by spaces (e.g., "1 2" or "1,2,3"), then press Enter:\n');
options.forEach((opt, i) => {
console.log(` ${i + 1}) ${opt.label}`);
});
console.log();
return new Promise((resolve) => {
rl.question('Your selection: ', (answer) => {
rl.close();
// Parse input like "1 2 3" or "1,2,3" or "1, 2, 3"
const nums = answer.split(/[\s,]+/).map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n));
const result = [];
for (const num of nums) {
if (num >= 1 && num <= options.length) {
result.push(options[num - 1].value);
}
}
resolve([...new Set(result)]); // Dedupe
});
});
}
function cleanOldInstallation(installDir) {
if (fs.existsSync(installDir)) {
console.log('Removing previous installation...');
fs.rmSync(installDir, { recursive: true, force: true });
}
}
function copyFromPackage(installDir) {
console.log('Installing AgentSys files...');
// Copy from npm package to ~/.agentsys
fs.cpSync(PACKAGE_DIR, installDir, {
recursive: true,
filter: (src) => {
// Skip node_modules and .git directories
const basename = path.basename(src);
return basename !== 'node_modules' && basename !== '.git';
}
});
}
function installDependencies(installDir) {
console.log('Installing dependencies...');
execSync('npm install --production', { cwd: installDir, stdio: 'inherit' });
}
// --- External Plugin Fetching ---
function getPluginCacheDir() {
const home = process.env.HOME || process.env.USERPROFILE;
return path.join(home, '.agentsys', 'plugins');
}
function loadMarketplace() {
const marketplacePath = path.join(PACKAGE_DIR, '.claude-plugin', 'marketplace.json');
if (!fs.existsSync(marketplacePath)) {
console.error('[ERROR] marketplace.json not found at ' + marketplacePath);
process.exit(1);
}
return JSON.parse(fs.readFileSync(marketplacePath, 'utf8'));
}
/**
* Resolve the source URL string from a plugin's source field.
* Handles both legacy string format ("https://...") and the new object
* format ({ source: "url", url: "https://..." }) from Claude Code plugin schema.
* Returns null for local/bundled sources or missing values.
*/
function resolveSourceUrl(source) {
if (!source) return null;
if (typeof source === 'string') return source;
if (typeof source === 'object' && source.url) return source.url;
return null;
}
/**
* Resolve plugin dependencies transitively.
*
* Circular dependencies are expected and handled: the `visiting` Set tracks
* the current DFS path and short-circuits any back-edge (e.g. next-task ->
* ship -> next-task), adding the already-visited node to `resolved` and
* returning immediately so the traversal terminates without infinite recursion.
*
* @param {string[]} names - Plugin names to resolve
* @param {Object} marketplace - Parsed marketplace.json
* @returns {string[]} All required plugin names (deduplicated, topologically ordered)
*/
function resolvePluginDeps(names, marketplace) {
const pluginMap = {};
for (const p of marketplace.plugins) {
pluginMap[p.name] = p;
}
// Validate requested names exist
for (const name of names) {
if (!pluginMap[name]) {
console.error(`[ERROR] Unknown plugin: ${name}. Available: ${marketplace.plugins.map(p => p.name).join(', ')}`);
process.exit(1);
}
}
const resolved = new Set();
const visiting = new Set();
function visit(name) {
if (resolved.has(name)) return;
if (visiting.has(name)) {
// Circular dep - just add it and stop recursing
resolved.add(name);
return;
}
visiting.add(name);
visiting.delete(name);
resolved.add(name);
}
for (const name of names) {
visit(name);
}
return [...resolved];
}
/**
* Download a GitHub repo tarball and extract to cache directory.
*
* @param {string} name - Plugin name
* @param {string} source - GitHub source URL (e.g. "github:agent-sh/agentsys-plugin-next-task")
* @param {string} version - Expected version string
* @returns {Promise<string>} Path to extracted plugin directory
*/
async function fetchPlugin(name, source, version) {
const cacheDir = getPluginCacheDir();
const pluginDir = path.join(cacheDir, name);
const versionFile = path.join(pluginDir, '.version');
// Check cache
if (fs.existsSync(versionFile)) {
const cached = fs.readFileSync(versionFile, 'utf8').trim();
if (cached === version) {
return pluginDir;
}
}
// Parse source formats:
// "https://github.com/owner/repo" or "https://github.com/owner/repo#ref"
// "github:owner/repo" or "github:owner/repo#ref"
let owner, repo, ref;
const urlMatch = source.match(/github\.com\/([^/]+)\/([^/#]+)(?:#(.+))?/);
const shortMatch = !urlMatch && source.match(/^github:([^/]+)\/([^#]+)(?:#(.+))?$/);
const match = urlMatch || shortMatch;
if (!match) {
throw new Error(`Unsupported source format for ${name}: ${source}`);
}
owner = match[1];
repo = match[2].replace(/\.git$/, '');
ref = match[3] || `v${version}`;
console.log(` Fetching ${name}@${version} from ${owner}/${repo}...`);
// Clean and recreate
if (fs.existsSync(pluginDir)) {
fs.rmSync(pluginDir, { recursive: true, force: true });
}
fs.mkdirSync(pluginDir, { recursive: true });
// Download and extract tarball, falling back to main branch if version tag 404s
const tarballUrl = `https://api.github.com/repos/${owner}/${repo}/tarball/${ref}`;
try {
await downloadAndExtractTarball(tarballUrl, pluginDir);
} catch (err) {
if (ref !== 'main' && err.message && err.message.includes('404')) {
const mainUrl = `https://api.github.com/repos/${owner}/${repo}/tarball/main`;
await downloadAndExtractTarball(mainUrl, pluginDir);
} else {
throw err;
}
}
// Write version marker
fs.writeFileSync(versionFile, version);
return pluginDir;
}
/**
* Download a tarball from URL and extract to dest directory.
* Strips the top-level directory from the tarball (GitHub tarballs have owner-repo-sha/).
*/
function downloadAndExtractTarball(url, dest) {
return new Promise((resolve, reject) => {
const ghToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const request = (reqUrl, redirectCount = 0) => {
if (redirectCount > 5) {
reject(new Error(`Too many redirects fetching tarball from ${url}`));
return;
}
const headers = {
'User-Agent': `agentsys/${VERSION}`,
'Accept': 'application/vnd.github+json'
};
if (ghToken) headers['Authorization'] = `Bearer ${ghToken}`;
https.get(reqUrl, { headers }, (res) => {
// Follow redirects (GitHub API returns 302 to S3)
if (res.statusCode === 301 || res.statusCode === 302) {
res.resume();
request(res.headers.location, redirectCount + 1);
return;
}
if (res.statusCode !== 200) {
res.resume();
const hint = res.statusCode === 403 ? ' (rate limited — set GITHUB_TOKEN env var)' : '';
reject(new Error(`HTTP ${res.statusCode}${hint} fetching tarball from ${reqUrl}`));
return;
}
// Use tar command to extract (available on all supported platforms)
// On Windows/MSYS2, convert backslash paths to forward slashes for tar
const tarDest = process.platform === 'win32' ? dest.replace(/\\/g, '/') : dest;
const tar = require('child_process').spawn('tar', [
'xz', '--strip-components=1', '-C', tarDest
], { stdio: ['pipe', 'inherit', 'pipe'] });
let stderr = '';
tar.stderr.on('data', (d) => { stderr += d; });
res.pipe(tar.stdin);
tar.on('close', (code) => {
if (code !== 0) {
reject(new Error(`tar extraction failed (code ${code}): ${stderr}`));
} else {
resolve();
}
});
tar.on('error', reject);
}).on('error', reject);
};
request(url);
});
}
/**
* Discover plugins from the external cache directory (~/.agentsys/plugins/).
* Falls back to PACKAGE_DIR/plugins/ if cache doesn't exist (bundled install).
*
* @param {string[]} [onlyPlugins] - If provided, only return these plugins
* @returns {string} The root directory to use for plugin discovery
*/
function resolvePluginRoot(onlyPlugins) {
const cacheDir = getPluginCacheDir();
// If we have cached external plugins, use the cache dir
if (fs.existsSync(cacheDir)) {
const entries = fs.readdirSync(cacheDir).filter(e => {
const pluginJson = path.join(cacheDir, e, '.claude-plugin', 'plugin.json');
return fs.existsSync(pluginJson);
});
if (entries.length > 0) {
// Return a synthetic root where plugins/ is the cache dir
// We need to restructure: cache has ~/.agentsys/plugins/<name>/
// but discovery expects <root>/plugins/<name>/
// The cache dir IS the plugins dir, so root is its parent
return path.join(cacheDir, '..');
}
}
// Fallback to bundled
return PACKAGE_DIR;
}
/**
* Fetch all requested plugins (with dependency resolution) to the cache.
*
* @param {string[]} pluginNames - Plugins to fetch (empty = all)
* @param {Object} marketplace - Parsed marketplace.json
* @returns {Promise<string[]>} Names of fetched plugins
*/
async function fetchExternalPlugins(pluginNames, marketplace) {
const pluginMap = {};
for (const p of marketplace.plugins) {
pluginMap[p.name] = p;
}
// Determine which plugins to fetch
let toFetch;
if (pluginNames.length > 0) {
toFetch = resolvePluginDeps(pluginNames, marketplace);
} else {
toFetch = marketplace.plugins.map(p => p.name);
}
console.log(`\nFetching ${toFetch.length} plugin(s): ${toFetch.join(', ')}\n`);
const fetched = [];
const failed = [];
for (const name of toFetch) {
const plugin = pluginMap[name];
if (!plugin) continue;
// If source is local (starts with ./), plugin is bundled - just use PACKAGE_DIR
const sourceUrl = resolveSourceUrl(plugin.source);
if (!sourceUrl || sourceUrl.startsWith('./') || sourceUrl.startsWith('../')) {
// Bundled plugin, no fetch needed
fetched.push(name);
continue;
}
try {
await fetchPlugin(name, sourceUrl, plugin.version);
fetched.push(name);
} catch (err) {
failed.push(name);
console.error(` [ERROR] Failed to fetch ${name}: ${err.message}`);
}
}
if (failed.length > 0) {
const missingDeps = failed.filter(f => toFetch.includes(f) && !pluginNames.includes(f));
if (missingDeps.length > 0) {
console.error(`\n [WARN] Missing dependencies: ${missingDeps.join(', ')}`);
console.error(` Some plugins may not work correctly without their dependencies.`);
}
}
return fetched;
}
/**
* List installed plugins and their components.
* @param {string} [filter] - 'all', 'plugins', 'agents', 'skills', 'commands', 'hooks', or null (default: plugins summary)
*/
function listInstalledPlugins(filter) {
const cacheDir = getPluginCacheDir();
const installed = loadInstalledJson();
const showAll = filter === 'all' || filter === '--all';
const showPlugins = !filter || filter === 'plugins' || filter === '--plugins' || showAll;
const showAgents = filter === 'agents' || filter === '--agents' || showAll;
const showSkills = filter === 'skills' || filter === '--skills' || showAll;
const showCommands = filter === 'commands' || filter === '--commands' || showAll;
const showHooks = filter === 'hooks' || filter === '--hooks' || showAll;
console.log(`\nagentsys v${VERSION}\n`);
// Gather all cached plugins
const plugins = [];
if (fs.existsSync(cacheDir)) {
const entries = fs.readdirSync(cacheDir).filter(e => {
return fs.statSync(path.join(cacheDir, e)).isDirectory();
}).sort();
for (const name of entries) {
const pluginDir = path.join(cacheDir, name);
const versionFile = path.join(pluginDir, '.version');
const ver = fs.existsSync(versionFile) ? fs.readFileSync(versionFile, 'utf8').trim() : 'unknown';
const components = loadComponents(pluginDir);
const entry = installed.plugins[name] || {};
const hooksFile = path.join(pluginDir, 'hooks', 'hooks.json');
const hasHooks = fs.existsSync(hooksFile);
plugins.push({ name, version: ver, components, entry, hasHooks, dir: pluginDir });
}
}
if (plugins.length === 0) {
console.log('No plugins installed. Run: agentsys install <plugin>\n');
return;
}
if (showPlugins && !showAll) {
// Default view: plugin summary
console.log('PLUGINS');
for (const p of plugins) {
const scope = p.entry.scope || 'full';
const scopeTag = scope === 'partial' ? '[partial]' : '[full]';
const platforms = p.entry.platforms ? p.entry.platforms.join(', ') : '';
const counts = [];
if (p.components.agents.length) counts.push(`${p.components.agents.length} agents`);
if (p.components.skills.length) counts.push(`${p.components.skills.length} skills`);
if (p.components.commands.length) counts.push(`${p.components.commands.length} cmds`);
if (p.hasHooks) counts.push('hooks');
console.log(` ${p.name.padEnd(18)} ${p.version.padEnd(10)} ${scopeTag.padEnd(10)} ${counts.join(', ')} ${platforms}`);
}
console.log();
console.log(` ${plugins.length} plugins. Use --all, --agents, --skills, --commands, --hooks for details.`);
console.log();
return;
}
if (showAll || showPlugins) {
console.log('PLUGINS');
for (const p of plugins) {
const scope = p.entry.scope || 'full';
const scopeTag = scope === 'partial' ? '[partial]' : '[full]';
console.log(` ${p.name}@${p.version} ${scopeTag}`);
}
console.log();
}
if (showAgents) {
console.log('AGENTS');
let total = 0;
for (const p of plugins) {
for (const a of p.components.agents) {
console.log(` ${p.name}:${a.name.padEnd(28)} ${(a.model || '').padEnd(8)} ${a.description || ''}`);
total++;
}
}
if (total === 0) console.log(' (none)');
console.log();
}
if (showSkills) {
console.log('SKILLS');
let total = 0;
for (const p of plugins) {
for (const s of p.components.skills) {
console.log(` ${p.name}:${s.name.padEnd(28)} ${s.description || ''}`);
total++;
}
}
if (total === 0) console.log(' (none)');
console.log();
}
if (showCommands) {
console.log('COMMANDS');
let total = 0;
for (const p of plugins) {
for (const c of p.components.commands) {
console.log(` /${c.name.padEnd(29)} ${c.description || ''}`);
total++;
}
}
if (total === 0) console.log(' (none)');
console.log();
}
if (showHooks) {
console.log('HOOKS');
let total = 0;
for (const p of plugins) {
if (p.hasHooks) {
try {
const hooks = JSON.parse(fs.readFileSync(path.join(p.dir, 'hooks', 'hooks.json'), 'utf8'));
const hookList = Array.isArray(hooks) ? hooks : (hooks.hooks || []);
for (const h of hookList) {
const event = h.event || h.matcher || 'unknown';
console.log(` ${p.name}:${String(event).padEnd(28)} ${h.description || ''}`);
total++;
}
} catch { /* skip malformed hooks */ }
}
}
if (total === 0) console.log(' (none)');
console.log();
}
}
/**
* Re-fetch all installed external plugins (update to latest versions).
*/
async function updatePlugins() {
console.log(`\nagentsys v${VERSION} - Updating plugins\n`);
const marketplace = loadMarketplace();
const cacheDir = getPluginCacheDir();
if (!fs.existsSync(cacheDir)) {
console.log('No cached plugins found. Run agentsys to install first.');
return;
}
// Get currently installed external plugins
const installed = fs.readdirSync(cacheDir).filter(e => {
return fs.statSync(path.join(cacheDir, e)).isDirectory();
});
if (installed.length === 0) {
console.log('No external plugins installed.');
return;
}
// Force re-fetch by removing version files
for (const name of installed) {
const versionFile = path.join(cacheDir, name, '.version');
if (fs.existsSync(versionFile)) {
fs.unlinkSync(versionFile);
}
}
await fetchExternalPlugins(installed, marketplace);
console.log('\n[OK] Plugins updated.');
}
// --- installed.json manifest ---
function getInstalledJsonPath() {
const home = process.env.HOME || process.env.USERPROFILE;
return path.join(home, '.agentsys', 'installed.json');
}
function loadInstalledJson() {
const p = getInstalledJsonPath();
if (fs.existsSync(p)) {
try {
return JSON.parse(fs.readFileSync(p, 'utf8'));
} catch {
return { plugins: {} };
}
}
return { plugins: {} };
}
function saveInstalledJson(data) {
const p = getInstalledJsonPath();
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, JSON.stringify(data, null, 2) + '\n');
}
function recordInstall(name, version, platforms, granular) {
const data = loadInstalledJson();
const entry = {
version,
installedAt: new Date().toISOString(),
platforms,
scope: 'full'
};
if (granular && granular.scope === 'partial') {
entry.scope = 'partial';
entry.agents = granular.agents || [];
entry.skills = granular.skills || [];
entry.commands = granular.commands || [];
}
data.plugins[name] = entry;
saveInstalledJson(data);
}
function recordRemove(name) {
const data = loadInstalledJson();
delete data.plugins[name];
saveInstalledJson(data);
}
// --- Core version compatibility check ---
/**
* Simple semver range check. Supports ">=X.Y.Z" format.
* Returns true if ver satisfies the range.
*/
function satisfiesRange(ver, range) {
if (!range) return true;
const parseVer = (s) => {
const m = s.match(/^(\d+)\.(\d+)\.(\d+)/);
return m ? [parseInt(m[1]), parseInt(m[2]), parseInt(m[3])] : null;
};
const greaterEq = range.match(/^>=(.+)$/);
if (greaterEq) {
const required = parseVer(greaterEq[1]);
const actual = parseVer(ver);
if (!required || !actual) return true;
for (let i = 0; i < 3; i++) {
if (actual[i] > required[i]) return true;
if (actual[i] < required[i]) return false;
}
return true; // equal
}
return true; // unknown range format, don't block
}
function checkCoreCompat(pluginEntry) {
// Core version compat check removed - field deprecated in schema
}
// --- Granular install helpers ---
/**
* Parse "plugin:component" install target format.
* @param {string} arg - e.g. "next-task:ci-fixer" or "next-task" or "next-task@1.0.0"
* @returns {{ plugin: string, component: string|null, version: string|null }}
*/
function parseInstallTarget(arg) {
if (!arg || typeof arg !== 'string') {
return { plugin: null, component: null, version: null };
}
let plugin = arg;
let component = null;
let version = null;
// Check for colon (component separator) before @ (version separator)
const colonIdx = plugin.indexOf(':');
if (colonIdx > 0) {
component = plugin.slice(colonIdx + 1) || null;
plugin = plugin.slice(0, colonIdx);
}
// Check for @version on the plugin part
const atIdx = plugin.indexOf('@');
if (atIdx > 0) {
version = plugin.slice(atIdx + 1) || null;
plugin = plugin.slice(0, atIdx);
}
return { plugin: plugin || null, component, version };
}
/**
* Load components.json from a cached plugin directory.
* @param {string} pluginDir - Path to the cached plugin directory
* @returns {{ agents: Array, skills: Array, commands: Array }}
*/
function loadComponents(pluginDir) {
const componentsPath = path.join(pluginDir, 'components.json');
if (fs.existsSync(componentsPath)) {
try {
const data = JSON.parse(fs.readFileSync(componentsPath, 'utf8'));
const normalize = (arr) => (arr || []).map(item =>
typeof item === 'string' ? { name: item } : item
);
return {
agents: normalize(data.agents),
skills: normalize(data.skills),
commands: normalize(data.commands)
};
} catch {
// Fall through to filesystem scan
}
}
// Fallback: scan filesystem
const components = { agents: [], skills: [], commands: [] };
const agentsDir = path.join(pluginDir, 'agents');
if (fs.existsSync(agentsDir)) {
const files = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md'));
for (const f of files) {
components.agents.push({ name: f.replace(/\.md$/, ''), file: `agents/${f}` });
}
}
const skillsDir = path.join(pluginDir, 'skills');
if (fs.existsSync(skillsDir)) {
const dirs = fs.readdirSync(skillsDir, { withFileTypes: true }).filter(d => d.isDirectory());
for (const d of dirs) {
if (fs.existsSync(path.join(skillsDir, d.name, 'SKILL.md'))) {
components.skills.push({ name: d.name, dir: `skills/${d.name}` });
}
}
}
const commandsDir = path.join(pluginDir, 'commands');
if (fs.existsSync(commandsDir)) {
const files = fs.readdirSync(commandsDir).filter(f => f.endsWith('.md'));
for (const f of files) {
components.commands.push({ name: f.replace(/\.md$/, ''), file: `commands/${f}` });
}
}
return components;
}
/**
* Resolve which type a component belongs to.
* @param {{ agents: Array, skills: Array, commands: Array }} components
* @param {string} name - Component name to find
* @returns {{ type: string, name: string, file?: string, dir?: string }|null}
*/
function resolveComponent(components, name) {
if (!name || !components) return null;
for (const agent of components.agents) {
if (agent.name === name) return { type: 'agent', name: agent.name, file: agent.file };
}
for (const skill of components.skills) {
if (skill.name === name) return { type: 'skill', name: skill.name, dir: skill.dir };
}
for (const cmd of components.commands) {
if (cmd.name === name) return { type: 'command', name: cmd.name, file: cmd.file };
}
return null;
}
/**
* Build a filter object from a resolved component.
* @param {{ type: string, name: string }} resolved
* @returns {{ agents: string[], skills: string[], commands: string[] }}
*/
function buildFilterFromComponent(resolved) {
const filter = { agents: [], skills: [], commands: [] };
if (resolved.type === 'agent') filter.agents.push(resolved.name);
else if (resolved.type === 'skill') filter.skills.push(resolved.name);
else if (resolved.type === 'command') filter.commands.push(resolved.name);
return filter;
}
// --- Detect which platforms are installed ---
function detectInstalledPlatforms() {
const home = process.env.HOME || process.env.USERPROFILE;
const platforms = [];
if (fs.existsSync(path.join(home, '.claude'))) platforms.push('claude');
const opencodeDir = getOpenCodeConfigDir();
if (fs.existsSync(opencodeDir)) platforms.push('opencode');
if (fs.existsSync(path.join(home, '.codex'))) platforms.push('codex');
// Cursor rules are project-scoped; detect only if Cursor rules/commands/skills exist in CWD
const cursorDir = path.join(process.cwd(), '.cursor');
if (fs.existsSync(path.join(cursorDir, 'rules')) || fs.existsSync(path.join(cursorDir, 'commands')) || fs.existsSync(path.join(cursorDir, 'skills'))) platforms.push('cursor');
return platforms;
}
// --- install subcommand ---
async function installPlugin(nameWithVersion, args) {
// Parse plugin:component and name[@version]
const target = parseInstallTarget(nameWithVersion);
let name = target.plugin;
let requestedVersion = target.version;
const componentName = target.component;
// Legacy fallback: handle plain name@version (parseInstallTarget already handles this)
if (!name) {
console.error('[ERROR] Usage: agentsys install <plugin[:component][@version]>');
process.exit(1);
}
const marketplace = loadMarketplace();
const pluginMap = {};
for (const p of marketplace.plugins) {
pluginMap[p.name] = p;
}
if (!pluginMap[name]) {
console.error(`[ERROR] Unknown plugin: ${name}`);
console.error(`Available: ${marketplace.plugins.map(p => p.name).join(', ')}`);
process.exit(1);
}
const plugin = pluginMap[name];
checkCoreCompat(plugin);
// Resolve deps
const toFetch = resolvePluginDeps([name], marketplace);
console.log(`\nInstalling ${name} (+ deps: ${toFetch.filter(n => n !== name).join(', ') || 'none'})\n`);
// Fetch all
for (const depName of toFetch) {
const dep = pluginMap[depName];
const depSourceUrl = resolveSourceUrl(dep && dep.source);
if (!dep || !depSourceUrl || depSourceUrl.startsWith('./')) continue;
checkCoreCompat(dep);
const ver = depName === name && requestedVersion ? requestedVersion : dep.version;
try {
await fetchPlugin(depName, depSourceUrl, ver);
} catch (err) {
console.error(` [ERROR] Failed to fetch ${depName}: ${err.message}`);
}
}
// Determine platforms
let platforms;
if (args.tool) {
platforms = [args.tool];
} else if (args.tools.length > 0) {
platforms = args.tools;
} else {
platforms = detectInstalledPlatforms();
if (platforms.length === 0) platforms = ['claude']; // default
}
console.log(`Installing for platforms: ${platforms.join(', ')}`);
// Resolve component filter if a specific component was requested
let filter = null;
if (componentName) {
const cacheDir = getPluginCacheDir();
const pluginDir = path.join(cacheDir, name);
if (!fs.existsSync(pluginDir)) {
console.error(`[ERROR] Plugin ${name} not found in cache after fetch.`);
process.exit(1);
}
const components = loadComponents(pluginDir);
const resolved = resolveComponent(components, componentName);
if (!resolved) {
const allNames = [
...components.agents.map(a => a.name),
...components.skills.map(s => s.name),
...components.commands.map(c => c.name)
];
console.error(`[ERROR] Component "${componentName}" not found in plugin ${name}.`);
if (allNames.length > 0) {
console.error(`Available components: ${allNames.join(', ')}`);
}
process.exit(1);
}
filter = buildFilterFromComponent(resolved);
console.log(` Installing ${resolved.type}: ${resolved.name}`);
}
// Use cache as install source
const installDir = getInstallDir();
const needsLocal = platforms.includes('opencode') || platforms.includes('codex') || platforms.includes('cursor');
if (needsLocal && !fs.existsSync(path.join(installDir, 'lib'))) {
// Need local install for transforms
cleanOldInstallation(installDir);
copyFromPackage(installDir);
}
for (const platform of platforms) {
if (platform === 'claude') {
if (filter) {
console.log(' [NOTE] Claude Code installs whole plugins (granular not supported). Installing full plugin.');
}
// Claude uses marketplace install
if (commandExists('claude')) {
try { execSync('claude plugin marketplace add agent-sh/agentsys', { stdio: 'pipe' }); } catch {}
for (const depName of toFetch) {
if (!/^[a-z0-9][a-z0-9-]*$/.test(depName)) continue;
try {
execSync(`claude plugin install ${depName}@agentsys`, { stdio: 'pipe' });
} catch {
try { execSync(`claude plugin update ${depName}@agentsys`, { stdio: 'pipe' }); } catch {}
}
}
}
}
// OpenCode and Codex get handled through normal install flow with cached plugins
}