-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathplugin.ts
More file actions
1786 lines (1567 loc) · 56.2 KB
/
Copy pathplugin.ts
File metadata and controls
1786 lines (1567 loc) · 56.2 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
/**
* Plugin management: install, uninstall, and list plugins.
*
* Plugins live in ~/.webcmd/plugins/<name>/.
* Monorepo clones live in ~/.webcmd/monorepos/<repo-name>/.
* Install source format: "github:user/repo", "github:user/repo/subplugin",
* "https://github.com/user/repo", "file:///local/plugin", or a local directory path.
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { execSync, execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { getPluginsDir, PLUGINS_DIR } from './discovery.js';
import { getErrorMessage, PluginError } from './errors.js';
import { log } from './logger.js';
import { isRecord } from './utils.js';
import { PACKAGE_NAME } from './brand.js';
import { fileSha256, readOverrideRecords } from './override-provenance.js';
import {
readPluginManifest,
isMonorepo,
getEnabledPlugins,
checkCompatibility,
type PluginManifest,
} from './plugin-manifest.js';
const isWindows = process.platform === 'win32';
const LOCAL_PLUGIN_SOURCE_PREFIX = 'local:';
/** Get home directory, respecting HOME environment variable for test isolation. */
function getHomeDir(): string {
return process.env.HOME || process.env.USERPROFILE || os.homedir();
}
/** Path to the lock file that tracks installed plugin versions. */
export function getLockFilePath(): string {
return path.join(getHomeDir(), '.webcmd', 'plugins.lock.json');
}
/** Monorepo clones directory: ~/.webcmd/monorepos/ */
export function getMonoreposDir(): string {
return path.join(getHomeDir(), '.webcmd', 'monorepos');
}
export type PluginSourceRecord =
| { kind: 'git'; url: string }
| { kind: 'local'; path: string }
| { kind: 'monorepo'; url: string; repoName: string; subPath: string };
export interface LockEntry {
source: PluginSourceRecord;
commitHash: string;
installedAt: string;
updatedAt?: string;
}
export interface PluginInfo {
name: string;
path: string;
commands: string[];
source?: string;
version?: string;
installedAt?: string;
/** If from a monorepo, the monorepo name. */
monorepoName?: string;
/** Description from webcmd-plugin.json. */
description?: string;
/** Commands forked into ~/.webcmd/clis with upstream provenance. */
overrides: string[];
/** An override's upstream command changed since it was forked. */
updateAvailable: boolean;
}
interface ParsedSource {
type: 'git' | 'local';
name: string;
subPlugin?: string;
cloneUrl?: string;
localPath?: string;
}
function parseStoredPluginSource(source?: string): PluginSourceRecord | undefined {
if (!source) return undefined;
if (source.startsWith(LOCAL_PLUGIN_SOURCE_PREFIX)) {
return {
kind: 'local',
path: path.resolve(source.slice(LOCAL_PLUGIN_SOURCE_PREFIX.length)),
};
}
return { kind: 'git', url: source };
}
function isLocalPluginSource(source?: string): boolean {
return parseStoredPluginSource(source)?.kind === 'local';
}
function toStoredPluginSource(source: PluginSourceRecord): string {
if (source.kind === 'local') {
return `${LOCAL_PLUGIN_SOURCE_PREFIX}${path.resolve(source.path)}`;
}
return source.url;
}
function toLocalPluginSource(pluginDir: string): string {
return toStoredPluginSource({ kind: 'local', path: pluginDir });
}
// isRecord is imported from './utils.js'
function normalizeLegacyMonorepo(
value: unknown,
): { name: string; subPath: string } | undefined {
if (!isRecord(value)) return undefined;
if (typeof value.name !== 'string' || typeof value.subPath !== 'string') return undefined;
return { name: value.name, subPath: value.subPath };
}
function normalizePluginSource(
source: unknown,
legacyMonorepo?: { name: string; subPath: string },
): PluginSourceRecord | undefined {
if (typeof source === 'string') {
const parsed = parseStoredPluginSource(source);
if (!parsed) return undefined;
if (parsed.kind === 'git' && legacyMonorepo) {
return {
kind: 'monorepo',
url: parsed.url,
repoName: legacyMonorepo.name,
subPath: legacyMonorepo.subPath,
};
}
return parsed;
}
if (!isRecord(source) || typeof source.kind !== 'string') return undefined;
switch (source.kind) {
case 'git':
return typeof source.url === 'string'
? { kind: 'git', url: source.url }
: undefined;
case 'local':
return typeof source.path === 'string'
? { kind: 'local', path: path.resolve(source.path) }
: undefined;
case 'monorepo':
return typeof source.url === 'string'
&& typeof source.repoName === 'string'
&& typeof source.subPath === 'string'
? {
kind: 'monorepo',
url: source.url,
repoName: source.repoName,
subPath: source.subPath,
}
: undefined;
default:
return undefined;
}
}
function normalizeLockEntry(value: unknown): LockEntry | undefined {
if (!isRecord(value)) return undefined;
const legacyMonorepo = normalizeLegacyMonorepo(value.monorepo);
const source = normalizePluginSource(value.source, legacyMonorepo);
if (!source) return undefined;
if (typeof value.commitHash !== 'string' || typeof value.installedAt !== 'string') {
return undefined;
}
const entry: LockEntry = {
source,
commitHash: value.commitHash,
installedAt: value.installedAt,
};
if (typeof value.updatedAt === 'string') {
entry.updatedAt = value.updatedAt;
}
return entry;
}
function resolvePluginSource(lockEntry: LockEntry | undefined, pluginDir: string): PluginSourceRecord | undefined {
if (lockEntry) {
return lockEntry.source;
}
return parseStoredPluginSource(getPluginSource(pluginDir));
}
function resolveStoredPluginSource(lockEntry: LockEntry | undefined, pluginDir: string): string | undefined {
const source = resolvePluginSource(lockEntry, pluginDir);
return source ? toStoredPluginSource(source) : undefined;
}
// ── Filesystem helpers ──────────────────────────────────────────────────────
/**
* Move a directory, with EXDEV fallback.
* fs.renameSync fails when source and destination are on different
* filesystems (e.g. /tmp → ~/.webcmd). In that case we copy then remove.
*/
type MoveDirFsOps = Pick<typeof fs, 'renameSync' | 'cpSync' | 'rmSync'>;
function moveDir(src: string, dest: string, fsOps: MoveDirFsOps = fs): void {
try {
fsOps.renameSync(src, dest);
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === 'EXDEV') {
try {
fsOps.cpSync(src, dest, { recursive: true });
} catch (copyErr) {
try { fsOps.rmSync(dest, { recursive: true, force: true }); } catch {}
throw copyErr;
}
fsOps.rmSync(src, { recursive: true, force: true });
} else {
throw err;
}
}
}
type ReplaceDirFsOps = MoveDirFsOps & Pick<typeof fs, 'existsSync' | 'mkdirSync'>;
function createSiblingTempPath(dest: string, kind: 'tmp' | 'bak'): string {
const suffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
return path.join(path.dirname(dest), `.${path.basename(dest)}.${kind}-${suffix}`);
}
function cloneRepoToTemp(cloneUrl: string): string {
const tmpCloneDir = path.join(
os.tmpdir(),
`webcmd-clone-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
);
try {
execFileSync('git', ['clone', '--depth', '1', cloneUrl, tmpCloneDir], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (err) {
throw new PluginError(`Failed to clone plugin: ${getErrorMessage(err)}`, 'Check the repository URL and your network connection.');
}
return tmpCloneDir;
}
function withTempClone<T>(cloneUrl: string, work: (cloneDir: string) => T): T {
const tmpCloneDir = cloneRepoToTemp(cloneUrl);
try {
return work(tmpCloneDir);
} finally {
try { fs.rmSync(tmpCloneDir, { recursive: true, force: true }); } catch {}
}
}
function resolveRemotePluginSource(lockEntry: LockEntry | undefined, dir: string): string {
const source = resolvePluginSource(lockEntry, dir);
if (!source || source.kind === 'local') {
throw new Error(`Unable to determine remote source for plugin at ${dir}`);
}
return source.url;
}
function pathExistsSync(p: string): boolean {
try {
fs.lstatSync(p);
return true;
} catch {
return false;
}
}
function resolveRepoContainedPath(repoRoot: string, subPath: string): string {
const resolved = path.resolve(repoRoot, subPath);
if (!resolved.startsWith(repoRoot + path.sep) && resolved !== repoRoot) {
throw new PluginError(`Plugin path "${subPath}" escapes repo root.`);
}
return resolved;
}
function removePathSync(p: string): void {
try {
const stat = fs.lstatSync(p);
if (stat.isSymbolicLink()) {
fs.unlinkSync(p);
return;
}
fs.rmSync(p, { recursive: true, force: true });
} catch {}
}
interface TransactionHandle {
finalize(): void;
rollback(): void;
}
class Transaction {
#handles: TransactionHandle[] = [];
#settled = false;
track<T extends TransactionHandle>(handle: T): T {
this.#handles.push(handle);
return handle;
}
commit(): void {
if (this.#settled) return;
this.#settled = true;
for (const handle of this.#handles) {
handle.finalize();
}
}
rollback(): void {
if (this.#settled) return;
this.#settled = true;
for (const handle of [...this.#handles].reverse()) {
handle.rollback();
}
}
}
function runTransaction<T>(work: (tx: Transaction) => T): T {
const tx = new Transaction();
try {
const result = work(tx);
tx.commit();
return result;
} catch (err) {
tx.rollback();
throw err;
}
}
function beginReplaceDir(
stagingDir: string,
dest: string,
fsOps: ReplaceDirFsOps = fs,
): TransactionHandle {
const destExisted = fsOps.existsSync(dest);
fsOps.mkdirSync(path.dirname(dest), { recursive: true });
const tempDest = createSiblingTempPath(dest, 'tmp');
const backupDest = destExisted ? createSiblingTempPath(dest, 'bak') : null;
let settled = false;
try {
moveDir(stagingDir, tempDest, fsOps);
if (backupDest) {
fsOps.renameSync(dest, backupDest);
}
fsOps.renameSync(tempDest, dest);
} catch (err) {
try { fsOps.rmSync(tempDest, { recursive: true, force: true }); } catch {}
if (backupDest && !fsOps.existsSync(dest)) {
try { fsOps.renameSync(backupDest, dest); } catch {}
}
throw err;
}
return {
finalize() {
if (settled) return;
settled = true;
if (backupDest) {
try { fsOps.rmSync(backupDest, { recursive: true, force: true }); } catch {}
}
},
rollback() {
if (settled) return;
settled = true;
try { fsOps.rmSync(dest, { recursive: true, force: true }); } catch {}
if (backupDest) {
try { fsOps.renameSync(backupDest, dest); } catch {}
}
try { fsOps.rmSync(tempDest, { recursive: true, force: true }); } catch {}
},
};
}
function beginReplaceSymlink(target: string, linkPath: string): TransactionHandle {
const linkExists = pathExistsSync(linkPath);
if (linkExists && !isSymlinkSync(linkPath)) {
throw new Error(`Expected monorepo plugin link at ${linkPath} to be a symlink`);
}
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
const tempLink = createSiblingTempPath(linkPath, 'tmp');
const backupLink = linkExists ? createSiblingTempPath(linkPath, 'bak') : null;
const linkType = isWindows ? 'junction' : 'dir';
let settled = false;
try {
fs.symlinkSync(target, tempLink, linkType);
if (backupLink) {
fs.renameSync(linkPath, backupLink);
}
fs.renameSync(tempLink, linkPath);
} catch (err) {
removePathSync(tempLink);
if (backupLink && !pathExistsSync(linkPath)) {
try { fs.renameSync(backupLink, linkPath); } catch {}
}
throw err;
}
return {
finalize() {
if (settled) return;
settled = true;
if (backupLink) {
removePathSync(backupLink);
}
},
rollback() {
if (settled) return;
settled = true;
removePathSync(linkPath);
if (backupLink && !pathExistsSync(linkPath)) {
try { fs.renameSync(backupLink, linkPath); } catch {}
}
removePathSync(tempLink);
},
};
}
// ── Validation helpers ──────────────────────────────────────────────────────
export interface ValidationResult {
valid: boolean;
errors: string[];
}
// ── Lock file helpers ───────────────────────────────────────────────────────
function readLockFileWithWriter(
writeLock: (lock: Record<string, LockEntry>) => void = writeLockFile,
): Record<string, LockEntry> {
try {
const raw = fs.readFileSync(getLockFilePath(), 'utf-8');
const parsed = JSON.parse(raw) as unknown;
if (!isRecord(parsed)) return {};
const lock: Record<string, LockEntry> = {};
let changed = false;
for (const [name, entry] of Object.entries(parsed)) {
const normalized = normalizeLockEntry(entry);
if (!normalized) {
changed = true;
continue;
}
lock[name] = normalized;
if (JSON.stringify(entry) !== JSON.stringify(normalized)) {
changed = true;
}
}
if (changed) {
try {
writeLock(lock);
} catch {}
}
return lock;
} catch {
return {};
}
}
export function readLockFile(): Record<string, LockEntry> {
return readLockFileWithWriter(writeLockFile);
}
type WriteLockFileFsOps = Pick<typeof fs, 'mkdirSync' | 'writeFileSync' | 'renameSync' | 'rmSync'>;
function writeLockFileWithFs(
lock: Record<string, LockEntry>,
fsOps: WriteLockFileFsOps = fs,
): void {
const lockPath = getLockFilePath();
fsOps.mkdirSync(path.dirname(lockPath), { recursive: true });
const tempPath = createSiblingTempPath(lockPath, 'tmp');
try {
fsOps.writeFileSync(tempPath, JSON.stringify(lock, null, 2) + '\n');
fsOps.renameSync(tempPath, lockPath);
} catch (err) {
try { fsOps.rmSync(tempPath, { force: true }); } catch {}
throw err;
}
}
export function writeLockFile(lock: Record<string, LockEntry>): void {
writeLockFileWithFs(lock, fs);
}
/** Get the HEAD commit hash of a git repo directory. */
export function getCommitHash(dir: string): string | undefined {
try {
return execFileSync('git', ['rev-parse', 'HEAD'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch {
return undefined;
}
}
/** True only for git's "this directory has no repository at all" failure. */
function isNotAGitRepositoryError(error: unknown): boolean {
const stderr = typeof (error as { stderr?: unknown })?.stderr === 'string'
? (error as { stderr: string }).stderr
: (error as { stderr?: Buffer })?.stderr?.toString('utf-8') ?? '';
const message = (error as Error)?.message ?? '';
return /not a git repository/i.test(stderr) || /not a git repository/i.test(message);
}
function describeGitError(error: unknown): string {
const stderr = typeof (error as { stderr?: unknown })?.stderr === 'string'
? (error as { stderr: string }).stderr
: (error as { stderr?: Buffer })?.stderr?.toString('utf-8') ?? '';
return stderr.trim() || (error as Error)?.message || String(error);
}
/**
* Report tracked-file modifications and untracked files within `dir` in a git checkout.
*
* Untracked files are included on purpose: `git status` already excludes
* gitignored paths (build output like node_modules/dist never shows up), so
* anything untracked that does show up is real, unsaved user work — e.g. a
* new command file that hasn't been `git add`ed yet — which updating would
* destroy just as surely as an uncommitted edit to a tracked file.
*
* The `-- .` pathspec on `git status` restricts the report to `dir` itself.
* Without it, git reports the *entire enclosing repository* — e.g. a plugin
* living inside a dotfiles repo, or any plugin directory that isn't itself a
* repo root, would surface unrelated dirty files from elsewhere in the repo.
*
* Returns an empty array only when `dir` is genuinely not inside a git
* repository: a plugin installed without git history has no baseline to
* compare against, so there is nothing to protect. Any other failure (git
* missing, "detected dubious ownership in repository", permission errors,
* ...) is a failure to determine dirtiness, not evidence of cleanliness, and
* must fail closed — this guard exists to prevent silent data loss, so an
* inconclusive check must refuse the update rather than proceed as if clean.
*/
export function getDirtyFiles(dir: string): string[] {
try {
execFileSync('git', ['rev-parse', '--git-dir'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (error) {
if (isNotAGitRepositoryError(error)) return [];
throw new PluginError(
`Could not determine whether "${dir}" has uncommitted changes: git failed with: ${describeGitError(error)}`,
'This can happen when git is not installed, or refuses to run here (e.g. "detected dubious ownership in repository"). Re-run with --force to update anyway — this accepts the risk of discarding uncommitted work, which is why it is not the default.',
);
}
try {
const out = execFileSync('git', ['status', '--porcelain', '--', '.'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
return out.split('\n').map((line) => line.trim()).filter(Boolean);
} catch (error) {
throw new PluginError(
`Could not determine whether "${dir}" has uncommitted changes: git failed with: ${describeGitError(error)}`,
'This can happen when git refuses to run here (e.g. "detected dubious ownership in repository"). Re-run with --force to update anyway — this accepts the risk of discarding uncommitted work, which is why it is not the default.',
);
}
}
function describeDirtyEntry(entry: string): string {
const isUntracked = entry.startsWith('??');
const file = entry.replace(/^\?\?\s*/, '').replace(/^[MADRCU! ]+\s*/, '');
return isUntracked ? `${file} (new, unstaged)` : `${file} (modified)`;
}
function assertPluginNotDirty(name: string, dir: string, force: boolean): void {
if (force) return;
const dirty = getDirtyFiles(dir);
if (dirty.length === 0) return;
const described = dirty.slice(0, 10).map(describeDirtyEntry);
throw new PluginError(
`Plugin "${name}" has uncommitted changes that updating would destroy:\n ${described.join('\n ')}`,
'Commit or stash them, re-run with --force to discard them, or develop against a symlinked checkout with "webcmd plugin install file:///path".',
);
}
/**
* Validate that a downloaded plugin directory is a structurally valid plugin.
* Checks for at least one command file (.ts, .js) and a valid
* package.json if it contains .ts files.
*/
export function validatePluginStructure(pluginDir: string): ValidationResult {
const errors: string[] = [];
if (!fs.existsSync(pluginDir)) {
return { valid: false, errors: ['Plugin directory does not exist'] };
}
const files = fs.readdirSync(pluginDir);
const hasTs = files.some(f => f.endsWith('.ts') && !f.endsWith('.d.ts') && !f.endsWith('.test.ts'));
const hasJs = files.some(f => f.endsWith('.js') && !f.endsWith('.d.js'));
if (!hasTs && !hasJs) {
errors.push('No command files found in plugin directory. A plugin must contain at least one .ts or .js command file.');
}
if (hasTs) {
const pkgJsonPath = path.join(pluginDir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) {
errors.push('Plugin contains .ts files but no package.json. A package.json with "type": "module" and "@agentrhq/webcmd" peer dependency is required for TS plugins.');
} else {
try {
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
if (pkg.type !== 'module') {
errors.push('Plugin package.json must have "type": "module" for TypeScript plugins.');
}
} catch {
errors.push('Plugin package.json is malformed or invalid JSON.');
}
}
}
return { valid: errors.length === 0, errors };
}
/** Check whether a directory has its own production dependencies in package.json. */
function hasOwnDependencies(dir: string): boolean {
const pkgPath = path.join(dir, 'package.json');
if (!fs.existsSync(pkgPath)) return false;
try {
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
return pkg.dependencies != null && Object.keys(pkg.dependencies).length > 0;
} catch {
return false;
}
}
function installDependencies(dir: string): void {
const pkgJsonPath = path.join(dir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) return;
try {
// Plugin repositories and their transitive dependencies are untrusted.
// Webcmd adapters do not require install-time lifecycle scripts, so deny
// preinstall/install/postinstall execution with the user's privileges.
execFileSync('npm', ['install', '--omit=dev', '--ignore-scripts'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
...(isWindows && { shell: true }),
});
} catch (err) {
throw new PluginError(`npm install failed in ${dir}: ${getErrorMessage(err)}`, 'Check your network connection and npm configuration.');
}
}
function finalizePluginRuntime(pluginDir: string): void {
// Symlink host webcmd so TS plugins resolve '@agentrhq/webcmd/registry'
// against the running host, not a stale npm-published version.
linkHostWebcmd(pluginDir);
// Transpile .ts → .js via esbuild (production node can't load .ts directly).
transpilePluginTs(pluginDir);
}
/**
* Shared post-install lifecycle for standalone plugins.
*/
function postInstallLifecycle(pluginDir: string): void {
installDependencies(pluginDir);
finalizePluginRuntime(pluginDir);
}
/**
* Monorepo lifecycle: install shared deps at repo root, then install and finalize each sub-plugin.
*
* The root install covers monorepos that use npm workspaces to hoist dependencies.
* For monorepos that do NOT use workspaces, sub-plugins may declare their own
* production dependencies in their package.json. We install those per sub-plugin
* so that runtime imports (e.g. `undici`) can be resolved from the sub-plugin
* directory. When the root already satisfies all deps this is a fast no-op.
*/
function postInstallMonorepoLifecycle(repoDir: string, pluginDirs: string[]): void {
installDependencies(repoDir);
for (const pluginDir of pluginDirs) {
if (pluginDir !== repoDir && hasOwnDependencies(pluginDir)) {
installDependencies(pluginDir);
}
finalizePluginRuntime(pluginDir);
}
}
function ensureStandalonePluginReady(pluginDir: string): void {
const validation = validatePluginStructure(pluginDir);
if (!validation.valid) {
throw new PluginError(`Invalid plugin structure:\n- ${validation.errors.join('\n- ')}`);
}
postInstallLifecycle(pluginDir);
}
type LockEntryInput = Omit<LockEntry, 'installedAt'> & Partial<Pick<LockEntry, 'installedAt'>>;
function upsertLockEntry(
lock: Record<string, LockEntry>,
name: string,
entry: LockEntryInput,
): void {
lock[name] = {
...entry,
installedAt: entry.installedAt ?? new Date().toISOString(),
};
}
function publishStandalonePlugin(
stagingDir: string,
targetDir: string,
writeLock: (commitHash: string | undefined) => void,
): void {
runTransaction((tx) => {
tx.track(beginReplaceDir(stagingDir, targetDir));
writeLock(getCommitHash(targetDir));
});
}
interface MonorepoPublishPlugin {
name: string;
subPath: string;
}
function publishMonorepoPlugins(
repoDir: string,
pluginsDir: string,
plugins: MonorepoPublishPlugin[],
publishRepo?: { stagingDir: string; parentDir: string },
writeLock?: (commitHash: string | undefined) => void,
): void {
runTransaction((tx) => {
if (publishRepo) {
fs.mkdirSync(publishRepo.parentDir, { recursive: true });
tx.track(beginReplaceDir(publishRepo.stagingDir, repoDir));
}
const commitHash = getCommitHash(repoDir);
for (const plugin of plugins) {
const linkPath = path.join(pluginsDir, plugin.name);
const subDir = resolveRepoContainedPath(repoDir, plugin.subPath);
tx.track(beginReplaceSymlink(subDir, linkPath));
}
writeLock?.(commitHash);
});
}
/**
* Install a plugin from a source.
* Supports:
* "github:user/repo" — single plugin or full monorepo
* "github:user/repo/subplugin" — specific sub-plugin from a monorepo
* "https://github.com/user/repo"
* "file:///absolute/path" — local plugin directory (symlinked)
* "/absolute/path" — local plugin directory (symlinked)
*
* Returns the installed plugin name(s).
*/
export function installPlugin(source: string): string | string[] {
const parsed = parseSource(source);
if (!parsed) {
throw new Error(
`Invalid plugin source: "${source}"\n` +
`Supported formats:\n` +
` github:user/repo\n` +
` github:user/repo/subplugin\n` +
` https://github.com/user/repo\n` +
` https://<host>/<path>/repo.git\n` +
` ssh://git@<host>/<path>/repo.git\n` +
` git@<host>:user/repo.git\n` +
` file:///absolute/path\n` +
` /absolute/path`
);
}
const { name: repoName, subPlugin } = parsed;
if (parsed.type === 'local') {
return installLocalPlugin(parsed.localPath!, repoName);
}
return withTempClone(parsed.cloneUrl!, (tmpCloneDir) => {
const manifest = readPluginManifest(tmpCloneDir);
// Check top-level compatibility
if (manifest?.webcmd && !checkCompatibility(manifest.webcmd)) {
throw new Error(
`Plugin requires webcmd ${manifest.webcmd}, but current version is incompatible.`
);
}
if (manifest && isMonorepo(manifest)) {
return installMonorepo(tmpCloneDir, parsed.cloneUrl!, repoName, manifest, subPlugin);
}
// Single plugin mode
return installSinglePlugin(tmpCloneDir, parsed.cloneUrl!, repoName, manifest);
});
}
/** Install a single (non-monorepo) plugin. */
function installSinglePlugin(
cloneDir: string,
cloneUrl: string,
name: string,
manifest: PluginManifest | null,
): string {
const pluginName = manifest?.name ?? name;
const targetDir = path.join(PLUGINS_DIR, pluginName);
if (fs.existsSync(targetDir)) {
throw new PluginError(`Plugin "${pluginName}" is already installed at ${targetDir}`, 'Use "webcmd plugin uninstall" first, or pick a different name.');
}
ensureStandalonePluginReady(cloneDir);
publishStandalonePlugin(cloneDir, targetDir, (commitHash) => {
const lock = readLockFile();
if (commitHash) {
upsertLockEntry(lock, pluginName, {
source: { kind: 'git', url: cloneUrl },
commitHash,
});
writeLockFile(lock);
}
});
return pluginName;
}
/**
* Install a local plugin by creating a symlink.
* Used for plugin development: the source directory is symlinked into
* the plugins dir so changes are reflected immediately.
*/
function installLocalPlugin(localPath: string, name: string): string {
if (!fs.existsSync(localPath)) {
throw new PluginError(`Local plugin path does not exist: ${localPath}`);
}
const stat = fs.statSync(localPath);
if (!stat.isDirectory()) {
throw new PluginError(`Local plugin path is not a directory: ${localPath}`);
}
const manifest = readPluginManifest(localPath);
if (manifest?.webcmd && !checkCompatibility(manifest.webcmd)) {
throw new PluginError(
`Plugin requires webcmd ${manifest.webcmd}, but current version is incompatible.`,
'Upgrade webcmd to a compatible version.',
);
}
const pluginName = manifest?.name ?? name;
const targetDir = path.join(PLUGINS_DIR, pluginName);
if (fs.existsSync(targetDir)) {
throw new PluginError(`Plugin "${pluginName}" is already installed at ${targetDir}`, 'Use "webcmd plugin uninstall" first, or pick a different name.');
}
const validation = validatePluginStructure(localPath);
if (!validation.valid) {
throw new PluginError(`Invalid plugin structure:\n- ${validation.errors.join('\n- ')}`);
}
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
const resolvedPath = path.resolve(localPath);
const linkType = isWindows ? 'junction' : 'dir';
fs.symlinkSync(resolvedPath, targetDir, linkType);
installDependencies(localPath);
finalizePluginRuntime(localPath);
const lock = readLockFile();
const commitHash = getCommitHash(localPath);
upsertLockEntry(lock, pluginName, {
source: { kind: 'local', path: resolvedPath },
commitHash: commitHash ?? 'local',
});
writeLockFile(lock);
return pluginName;
}
function updateLocalPlugin(
name: string,
targetDir: string,
lock: Record<string, LockEntry>,
lockEntry?: LockEntry,
): void {
const pluginDir = fs.realpathSync(targetDir);
const validation = validatePluginStructure(pluginDir);
if (!validation.valid) {
log.warn(`Plugin "${name}" structure invalid:\n- ${validation.errors.join('\n- ')}`);
}
postInstallLifecycle(pluginDir);
upsertLockEntry(lock, name, {
source: lockEntry?.source ?? { kind: 'local', path: pluginDir },
commitHash: getCommitHash(pluginDir) ?? 'local',
installedAt: lockEntry?.installedAt ?? new Date().toISOString(),
updatedAt: new Date().toISOString(),
});
writeLockFile(lock);
}
/** Install sub-plugins from a monorepo. */
function installMonorepo(
cloneDir: string,
cloneUrl: string,
repoName: string,
manifest: PluginManifest,
subPlugin?: string,
): string[] {
const monoreposDir = getMonoreposDir();
const repoDir = path.join(monoreposDir, repoName);
const repoAlreadyInstalled = fs.existsSync(repoDir);
let repoRoot = repoAlreadyInstalled ? repoDir : cloneDir;
let effectiveManifest = repoAlreadyInstalled ? readPluginManifest(repoDir) : manifest;
let publishRepo = repoAlreadyInstalled ? undefined : { stagingDir: cloneDir, parentDir: monoreposDir };
if (
repoAlreadyInstalled
&& subPlugin
&& (!effectiveManifest?.plugins?.[subPlugin] || effectiveManifest.plugins[subPlugin].disabled)
&& manifest.plugins?.[subPlugin]
&& !manifest.plugins[subPlugin].disabled
) {
repoRoot = cloneDir;
effectiveManifest = manifest;
publishRepo = { stagingDir: cloneDir, parentDir: monoreposDir };
}
if (!effectiveManifest || !isMonorepo(effectiveManifest)) {
throw new PluginError(`Monorepo manifest missing or invalid at ${repoRoot}`);
}
let pluginsToInstall = getEnabledPlugins(effectiveManifest);
// If a specific sub-plugin was requested, filter to just that one
if (subPlugin) {
pluginsToInstall = pluginsToInstall.filter((p) => p.name === subPlugin);
if (pluginsToInstall.length === 0) {
// Check if it exists but is disabled
const disabled = effectiveManifest.plugins?.[subPlugin];
if (disabled) {
throw new PluginError(`Sub-plugin "${subPlugin}" is disabled in the manifest.`);
}
throw new PluginError(
`Sub-plugin "${subPlugin}" not found in monorepo. Available: ${Object.keys(effectiveManifest.plugins ?? {}).join(', ')}`
);
}
}
const installedNames: string[] = [];
const lock = readLockFile();
const eligiblePlugins: Array<{ name: string; entry: typeof pluginsToInstall[number]['entry'] }> = [];
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
for (const { name, entry } of pluginsToInstall) {
// Check sub-plugin level compatibility (overrides top-level)
if (entry.webcmd && !checkCompatibility(entry.webcmd)) {
log.warn(`Skipping "${name}": requires webcmd ${entry.webcmd}`);
continue;
}
let subDir: string;
try {
subDir = resolveRepoContainedPath(repoRoot, entry.path);
} catch {
log.warn(`Skipping "${name}": path "${entry.path}" escapes repo root.`);
continue;
}
if (!fs.existsSync(subDir)) {
log.warn(`Skipping "${name}": path "${entry.path}" not found in repo.`);