cladogram 0.6.0-beta.7 → 0.6.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/release.md +14 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +1286 -81
- package/plugins/agent/style.css +50 -0
- package/src/agent/pi-bridge.js +621 -58
- package/src/agent/pi-config.js +137 -11
- package/src/server/agent.js +94 -15
- package/src/server/assets/library.js +9 -1
- package/src/server/plugin-registry.js +664 -2
- package/src/server/workspace.js +120 -3
|
@@ -6,12 +6,27 @@
|
|
|
6
6
|
* - 轻量 JSON Registry 索引读取与检索(loadRegistryIndex / searchRegistry)
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { homedir } from 'node:os';
|
|
12
|
+
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
11
13
|
import { z } from 'zod/v4';
|
|
12
14
|
import { VERSION } from '../util/version.js';
|
|
13
15
|
import { fail, locked } from '../workspace/storage.js';
|
|
14
16
|
import { inspectWorkspacePlugins, installWorkspacePlugin, isReservedPluginId } from './plugins.js';
|
|
17
|
+
import {
|
|
18
|
+
deletePiPrompt,
|
|
19
|
+
deletePiSkill,
|
|
20
|
+
deleteRole,
|
|
21
|
+
inspectPiEcosystem,
|
|
22
|
+
installPiPackage,
|
|
23
|
+
listRoles,
|
|
24
|
+
removePiPackage,
|
|
25
|
+
resolvePiAgentDir,
|
|
26
|
+
savePiPrompt,
|
|
27
|
+
savePiSkill,
|
|
28
|
+
saveRole,
|
|
29
|
+
} from '../agent/pi-config.js';
|
|
15
30
|
|
|
16
31
|
const registryEntrySchema = z.strictObject({
|
|
17
32
|
id: z.string().regex(/^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/).max(80),
|
|
@@ -274,6 +289,8 @@ export function listInstalledWorkspacePlugins(stateDir) {
|
|
|
274
289
|
} catch {}
|
|
275
290
|
return {
|
|
276
291
|
...item,
|
|
292
|
+
description: String(manifestData.description || '').trim(),
|
|
293
|
+
hasConfiguration: Boolean(manifestData?.configuration?.schema),
|
|
277
294
|
permissions: Array.isArray(manifestData.permissions) ? manifestData.permissions : [],
|
|
278
295
|
audit: auditPluginPermissions(manifestData),
|
|
279
296
|
};
|
|
@@ -440,3 +457,648 @@ export function searchRegistry(registryData, query = '') {
|
|
|
440
457
|
|| (item.kind && item.kind.toLowerCase().includes(q))
|
|
441
458
|
);
|
|
442
459
|
}
|
|
460
|
+
|
|
461
|
+
// ============================================================================
|
|
462
|
+
// Local Directory Plugin Market Sources & Real-Time Live Scanner
|
|
463
|
+
// ============================================================================
|
|
464
|
+
|
|
465
|
+
const SKIP_SCAN_DIRS = new Set(['node_modules', '.git', '.clado', '.pi', 'dist', 'build', 'coverage', '.cache', '__pycache__', 'target']);
|
|
466
|
+
|
|
467
|
+
function expandUserPath(raw) {
|
|
468
|
+
const s = String(raw || '').trim();
|
|
469
|
+
if (!s) return '';
|
|
470
|
+
if (s === '~') return homedir();
|
|
471
|
+
if (s.startsWith('~/') || s.startsWith('~\\')) return resolve(homedir(), s.slice(2));
|
|
472
|
+
return resolve(s);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function pluginSourcesFile(agentDir = resolvePiAgentDir()) {
|
|
476
|
+
return join(agentDir, 'clado-plugin-sources.json');
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function readPluginSourcesRaw(agentDir = resolvePiAgentDir()) {
|
|
480
|
+
const file = pluginSourcesFile(agentDir);
|
|
481
|
+
if (!existsSync(file)) return [];
|
|
482
|
+
try {
|
|
483
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
484
|
+
return Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.sources) ? parsed.sources : []);
|
|
485
|
+
} catch {
|
|
486
|
+
return [];
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function writePluginSourcesRaw(agentDir, sources) {
|
|
491
|
+
mkdirSync(agentDir, { recursive: true });
|
|
492
|
+
writeFileSync(pluginSourcesFile(agentDir), JSON.stringify(sources, null, 2) + '\n', 'utf8');
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export function listPluginSources(agentDir = resolvePiAgentDir()) {
|
|
496
|
+
return readPluginSourcesRaw(agentDir)
|
|
497
|
+
.filter(s => s && typeof s === 'object' && s.id && (s.path || s.url))
|
|
498
|
+
.map(s => ({
|
|
499
|
+
id: String(s.id),
|
|
500
|
+
type: s.type === 'json' ? 'json' : 'local-dir',
|
|
501
|
+
name: String(s.name || (s.path ? basename(s.path) : s.url) || '本地市场').trim(),
|
|
502
|
+
path: s.path ? String(s.path) : '',
|
|
503
|
+
url: s.url ? String(s.url) : '',
|
|
504
|
+
enabled: s.enabled !== false,
|
|
505
|
+
createdAt: s.createdAt || '',
|
|
506
|
+
}));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
export function addPluginSource(input = {}, agentDir = resolvePiAgentDir()) {
|
|
510
|
+
const type = input?.type === 'json' ? 'json' : 'local-dir';
|
|
511
|
+
const current = listPluginSources(agentDir);
|
|
512
|
+
if (type === 'local-dir') {
|
|
513
|
+
const absPath = expandUserPath(input?.path || input?.dir || '');
|
|
514
|
+
if (!absPath) fail('请填写要注册的本地目录路径。', 400);
|
|
515
|
+
if (!existsSync(absPath) || !lstatSync(absPath).isDirectory()) {
|
|
516
|
+
fail(`本地目录不存在或不是文件夹:${absPath}`, 404);
|
|
517
|
+
}
|
|
518
|
+
const existing = current.find(s => s.type === 'local-dir' && resolve(s.path) === absPath);
|
|
519
|
+
if (existing) {
|
|
520
|
+
existing.enabled = true;
|
|
521
|
+
if (input?.name && String(input.name).trim()) existing.name = String(input.name).trim().slice(0, 80);
|
|
522
|
+
writePluginSourcesRaw(agentDir, current);
|
|
523
|
+
return { source: existing, sources: current, existed: true };
|
|
524
|
+
}
|
|
525
|
+
const source = {
|
|
526
|
+
id: 'src_' + randomUUID().replace(/-/g, '').slice(0, 10),
|
|
527
|
+
type: 'local-dir',
|
|
528
|
+
name: String(input?.name || basename(absPath) || absPath).trim().slice(0, 80),
|
|
529
|
+
path: absPath,
|
|
530
|
+
url: '',
|
|
531
|
+
enabled: true,
|
|
532
|
+
createdAt: new Date().toISOString(),
|
|
533
|
+
};
|
|
534
|
+
const next = [...current, source];
|
|
535
|
+
writePluginSourcesRaw(agentDir, next);
|
|
536
|
+
return { source, sources: next, existed: false };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const rawUrl = String(input?.url || input?.path || '').trim();
|
|
540
|
+
if (!rawUrl) fail('请填写插件索引 URL 或本地 JSON 文件路径。', 400);
|
|
541
|
+
const isHttp = /^https?:\/\//i.test(rawUrl);
|
|
542
|
+
const normalizedTarget = isHttp ? rawUrl : expandUserPath(rawUrl.replace(/^file:\/\//, ''));
|
|
543
|
+
if (!isHttp && (!existsSync(normalizedTarget) || !lstatSync(normalizedTarget).isFile())) {
|
|
544
|
+
fail(`插件索引文件不存在:${normalizedTarget}`, 404);
|
|
545
|
+
}
|
|
546
|
+
const existing = current.find(s => s.type === 'json' && (s.url === normalizedTarget || s.path === normalizedTarget));
|
|
547
|
+
if (existing) {
|
|
548
|
+
existing.enabled = true;
|
|
549
|
+
if (input?.name && String(input.name).trim()) existing.name = String(input.name).trim().slice(0, 80);
|
|
550
|
+
writePluginSourcesRaw(agentDir, current);
|
|
551
|
+
return { source: existing, sources: current, existed: true };
|
|
552
|
+
}
|
|
553
|
+
const source = {
|
|
554
|
+
id: 'src_' + randomUUID().replace(/-/g, '').slice(0, 10),
|
|
555
|
+
type: 'json',
|
|
556
|
+
name: String(input?.name || (isHttp ? new URL(normalizedTarget).hostname : basename(normalizedTarget))).trim().slice(0, 80),
|
|
557
|
+
path: isHttp ? '' : normalizedTarget,
|
|
558
|
+
url: isHttp ? normalizedTarget : '',
|
|
559
|
+
enabled: true,
|
|
560
|
+
createdAt: new Date().toISOString(),
|
|
561
|
+
};
|
|
562
|
+
const next = [...current, source];
|
|
563
|
+
writePluginSourcesRaw(agentDir, next);
|
|
564
|
+
return { source, sources: next, existed: false };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
export function removePluginSource(id, agentDir = resolvePiAgentDir()) {
|
|
568
|
+
const cleanId = String(id || '').trim();
|
|
569
|
+
if (!cleanId) fail('缺少市场源 ID。', 400);
|
|
570
|
+
const current = listPluginSources(agentDir);
|
|
571
|
+
const next = current.filter(s => s.id !== cleanId);
|
|
572
|
+
if (next.length === current.length) fail(`找不到插件市场源:${cleanId}`, 404);
|
|
573
|
+
writePluginSourcesRaw(agentDir, next);
|
|
574
|
+
return { removed: true, id: cleanId, sources: next };
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
export function togglePluginSource(id, enabled, agentDir = resolvePiAgentDir()) {
|
|
578
|
+
const cleanId = String(id || '').trim();
|
|
579
|
+
const current = listPluginSources(agentDir);
|
|
580
|
+
const found = current.find(s => s.id === cleanId);
|
|
581
|
+
if (!found) fail(`找不到插件市场源:${cleanId}`, 404);
|
|
582
|
+
found.enabled = Boolean(enabled);
|
|
583
|
+
writePluginSourcesRaw(agentDir, current);
|
|
584
|
+
return { source: found, sources: current };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function parseSimpleFrontmatter(mdText = '') {
|
|
588
|
+
const text = String(mdText || '');
|
|
589
|
+
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
|
|
590
|
+
if (!m) return { attrs: {}, body: text };
|
|
591
|
+
const attrs = {};
|
|
592
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
593
|
+
const kv = line.match(/^([a-zA-Z0-9_-]+)\s*:\s*(.+)$/);
|
|
594
|
+
if (!kv) continue;
|
|
595
|
+
let val = kv[2].trim();
|
|
596
|
+
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
|
597
|
+
val = val.slice(1, -1);
|
|
598
|
+
}
|
|
599
|
+
attrs[kv[1].toLowerCase()] = val;
|
|
600
|
+
}
|
|
601
|
+
return { attrs, body: m[2] || '' };
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function slugifyMarketId(raw) {
|
|
605
|
+
return String(raw || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function buildInstalledLookup({ workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir() } = {}) {
|
|
609
|
+
const wsPlugins = stateDir ? listInstalledWorkspacePlugins(stateDir) : [];
|
|
610
|
+
const wsPluginMap = new Map(wsPlugins.map(p => [p.id, p]));
|
|
611
|
+
const roles = listRoles(agentDir);
|
|
612
|
+
const customRolesPath = join(agentDir, 'clado-roles.json');
|
|
613
|
+
let customRoleIds = new Set();
|
|
614
|
+
try {
|
|
615
|
+
if (existsSync(customRolesPath)) {
|
|
616
|
+
const arr = JSON.parse(readFileSync(customRolesPath, 'utf8'));
|
|
617
|
+
if (Array.isArray(arr)) customRoleIds = new Set(arr.map(r => r?.id).filter(Boolean));
|
|
618
|
+
}
|
|
619
|
+
} catch {}
|
|
620
|
+
const roleMap = new Map(roles.map(r => [r.id, r]));
|
|
621
|
+
|
|
622
|
+
let eco = { packages: [], skills: [], prompts: [] };
|
|
623
|
+
try {
|
|
624
|
+
eco = await inspectPiEcosystem(workspace, agentDir);
|
|
625
|
+
} catch {}
|
|
626
|
+
|
|
627
|
+
const skillMap = new Map();
|
|
628
|
+
for (const s of eco.skills || []) skillMap.set(s.name, s);
|
|
629
|
+
const promptMap = new Map();
|
|
630
|
+
for (const p of eco.prompts || []) promptMap.set(p.name, p);
|
|
631
|
+
const pkgPaths = new Map();
|
|
632
|
+
for (const p of eco.packages || []) {
|
|
633
|
+
if (p.source) {
|
|
634
|
+
pkgPaths.set(p.source, p);
|
|
635
|
+
try {
|
|
636
|
+
if (!/^(npm:|git:|https?:)/i.test(p.source)) pkgPaths.set(resolve(p.source), p);
|
|
637
|
+
} catch {}
|
|
638
|
+
}
|
|
639
|
+
if (p.installedPath) pkgPaths.set(resolve(p.installedPath), p);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
return { wsPlugins, wsPluginMap, roleMap, customRoleIds, skillMap, promptMap, pkgPaths, workspace, agentDir };
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function collectRolesFromJsonFile(filePath) {
|
|
646
|
+
let raw;
|
|
647
|
+
try { raw = JSON.parse(readFileSync(filePath, 'utf8')); } catch { return []; }
|
|
648
|
+
const arr = Array.isArray(raw)
|
|
649
|
+
? raw
|
|
650
|
+
: (Array.isArray(raw?.roles) ? raw.roles : (raw && typeof raw === 'object' && raw.name ? [raw] : []));
|
|
651
|
+
return arr
|
|
652
|
+
.filter(r => r && typeof r === 'object' && String(r.name || '').trim())
|
|
653
|
+
.map(r => {
|
|
654
|
+
const name = String(r.name).trim();
|
|
655
|
+
const id = String(r.id || slugifyMarketId(name) || basename(filePath, '.json')).trim().slice(0, 36);
|
|
656
|
+
return {
|
|
657
|
+
id,
|
|
658
|
+
name: name.slice(0, 40),
|
|
659
|
+
phase: String(r.phase || '自定义阶段').trim().slice(0, 20),
|
|
660
|
+
tone: ['sky', 'emerald', 'violet', 'amber'].includes(r.tone) ? r.tone : 'sky',
|
|
661
|
+
description: String(r.description || '').trim().slice(0, 240),
|
|
662
|
+
systemPrompt: String(r.systemPrompt || '').trim().slice(0, 6000),
|
|
663
|
+
model: String(r.model || '').trim().slice(0, 120),
|
|
664
|
+
};
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
export async function scanLocalPluginDirectory(dirPath, {
|
|
669
|
+
workspace = process.cwd(),
|
|
670
|
+
stateDir = '',
|
|
671
|
+
agentDir = resolvePiAgentDir(),
|
|
672
|
+
sourceId = 'local',
|
|
673
|
+
sourceName = '',
|
|
674
|
+
installedLookup = null,
|
|
675
|
+
} = {}) {
|
|
676
|
+
const root = expandUserPath(dirPath);
|
|
677
|
+
const label = sourceName || basename(root) || root;
|
|
678
|
+
if (!root || !existsSync(root) || !lstatSync(root).isDirectory()) {
|
|
679
|
+
return { exists: false, path: root, items: [], error: '目录不存在或不可访问' };
|
|
680
|
+
}
|
|
681
|
+
const lookup = installedLookup || await buildInstalledLookup({ workspace, stateDir, agentDir });
|
|
682
|
+
const items = [];
|
|
683
|
+
const seenKeys = new Set();
|
|
684
|
+
|
|
685
|
+
const pushUnique = item => {
|
|
686
|
+
const key = `${item.kind}:${item.id}:${item.sourcePath}`;
|
|
687
|
+
if (seenKeys.has(key)) return;
|
|
688
|
+
seenKeys.add(key);
|
|
689
|
+
items.push(item);
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
const scanDir = (dir, depth) => {
|
|
693
|
+
// 1. Check clado-plugin.json
|
|
694
|
+
const manifestPath = join(dir, 'clado-plugin.json');
|
|
695
|
+
if (existsSync(manifestPath) && lstatSync(manifestPath).isFile()) {
|
|
696
|
+
try {
|
|
697
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
698
|
+
const id = String(manifest?.id || '').trim();
|
|
699
|
+
if (id && !isReservedPluginId(id)) {
|
|
700
|
+
const inst = lookup.wsPluginMap.get(id);
|
|
701
|
+
pushUnique({
|
|
702
|
+
uid: `${sourceId}:clado-plugin:${id}`,
|
|
703
|
+
kind: 'clado-plugin',
|
|
704
|
+
id,
|
|
705
|
+
name: String(manifest.name || id).trim(),
|
|
706
|
+
version: String(manifest.version || '0.1.0'),
|
|
707
|
+
description: String(manifest.description || '').trim(),
|
|
708
|
+
sourceId,
|
|
709
|
+
sourceName: label,
|
|
710
|
+
sourcePath: dir,
|
|
711
|
+
installed: Boolean(inst),
|
|
712
|
+
installedScope: inst ? 'workspace' : '',
|
|
713
|
+
installedVersion: inst?.version || '',
|
|
714
|
+
hasConfiguration: Boolean(manifest?.configuration?.schema),
|
|
715
|
+
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [],
|
|
716
|
+
audit: auditPluginPermissions(manifest),
|
|
717
|
+
});
|
|
718
|
+
return; // Do not descend inside a Clado plugin directory
|
|
719
|
+
}
|
|
720
|
+
} catch {}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// 2. Check SKILL.md
|
|
724
|
+
const skillPath = join(dir, 'SKILL.md');
|
|
725
|
+
if (existsSync(skillPath) && lstatSync(skillPath).isFile()) {
|
|
726
|
+
try {
|
|
727
|
+
const raw = readFileSync(skillPath, 'utf8');
|
|
728
|
+
const { attrs, body } = parseSimpleFrontmatter(raw);
|
|
729
|
+
const slug = slugifyMarketId(attrs.name || basename(dir));
|
|
730
|
+
if (slug) {
|
|
731
|
+
const userSkillFile = join(lookup.agentDir, 'skills', slug, 'SKILL.md');
|
|
732
|
+
const projSkillFile = join(lookup.workspace, '.pi', 'skills', slug, 'SKILL.md');
|
|
733
|
+
const installedUser = existsSync(userSkillFile);
|
|
734
|
+
const installedProj = existsSync(projSkillFile);
|
|
735
|
+
const ecoSkill = lookup.skillMap.get(slug);
|
|
736
|
+
const installed = installedUser || installedProj || Boolean(ecoSkill);
|
|
737
|
+
const firstLine = body.split(/\r?\n/).map(l => l.replace(/^#+\s*/, '').trim()).find(Boolean) || '';
|
|
738
|
+
pushUnique({
|
|
739
|
+
uid: `${sourceId}:skill:${slug}`,
|
|
740
|
+
kind: 'skill',
|
|
741
|
+
id: slug,
|
|
742
|
+
name: attrs.name || basename(dir),
|
|
743
|
+
version: String(attrs.version || ''),
|
|
744
|
+
description: attrs.description || firstLine.slice(0, 180),
|
|
745
|
+
sourceId,
|
|
746
|
+
sourceName: label,
|
|
747
|
+
sourcePath: dir,
|
|
748
|
+
installed,
|
|
749
|
+
installedScope: installedProj ? 'project' : (installedUser ? 'user' : (ecoSkill?.scope || '')),
|
|
750
|
+
hasConfiguration: false,
|
|
751
|
+
permissions: [],
|
|
752
|
+
audit: { highestRisk: 'low', items: [] },
|
|
753
|
+
});
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
} catch {}
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// 3. Check role definitions (clado-role.json / roles.json)
|
|
760
|
+
for (const roleFileName of ['clado-role.json', 'roles.json']) {
|
|
761
|
+
const rf = join(dir, roleFileName);
|
|
762
|
+
if (existsSync(rf) && lstatSync(rf).isFile()) {
|
|
763
|
+
for (const r of collectRolesFromJsonFile(rf)) {
|
|
764
|
+
const isInst = lookup.customRoleIds.has(r.id);
|
|
765
|
+
pushUnique({
|
|
766
|
+
uid: `${sourceId}:role:${r.id}`,
|
|
767
|
+
kind: 'role',
|
|
768
|
+
id: r.id,
|
|
769
|
+
name: r.name,
|
|
770
|
+
version: '',
|
|
771
|
+
description: r.description || `${r.phase} · 自定义人设`,
|
|
772
|
+
sourceId,
|
|
773
|
+
sourceName: label,
|
|
774
|
+
sourcePath: rf,
|
|
775
|
+
installed: isInst,
|
|
776
|
+
installedScope: isInst ? 'user' : '',
|
|
777
|
+
hasConfiguration: false,
|
|
778
|
+
permissions: [],
|
|
779
|
+
audit: { highestRisk: 'low', items: [] },
|
|
780
|
+
roleData: r,
|
|
781
|
+
meta: { phase: r.phase, tone: r.tone, model: r.model },
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// 4. Check roles/*.json directory
|
|
788
|
+
const rolesDir = join(dir, 'roles');
|
|
789
|
+
if (existsSync(rolesDir) && lstatSync(rolesDir).isDirectory()) {
|
|
790
|
+
try {
|
|
791
|
+
for (const ent of readdirSync(rolesDir, { withFileTypes: true })) {
|
|
792
|
+
if (!ent.isFile() || !ent.name.endsWith('.json')) continue;
|
|
793
|
+
const rf = join(rolesDir, ent.name);
|
|
794
|
+
for (const r of collectRolesFromJsonFile(rf)) {
|
|
795
|
+
const isInst = lookup.customRoleIds.has(r.id);
|
|
796
|
+
pushUnique({
|
|
797
|
+
uid: `${sourceId}:role:${r.id}`,
|
|
798
|
+
kind: 'role',
|
|
799
|
+
id: r.id,
|
|
800
|
+
name: r.name,
|
|
801
|
+
version: '',
|
|
802
|
+
description: r.description || `${r.phase} · 自定义人设`,
|
|
803
|
+
sourceId,
|
|
804
|
+
sourceName: label,
|
|
805
|
+
sourcePath: rf,
|
|
806
|
+
installed: isInst,
|
|
807
|
+
installedScope: isInst ? 'user' : '',
|
|
808
|
+
hasConfiguration: false,
|
|
809
|
+
permissions: [],
|
|
810
|
+
audit: { highestRisk: 'low', items: [] },
|
|
811
|
+
roleData: r,
|
|
812
|
+
meta: { phase: r.phase, tone: r.tone, model: r.model },
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
} catch {}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// 5. Check prompts/*.md directory
|
|
820
|
+
const promptsDir = join(dir, 'prompts');
|
|
821
|
+
if (existsSync(promptsDir) && lstatSync(promptsDir).isDirectory()) {
|
|
822
|
+
try {
|
|
823
|
+
for (const ent of readdirSync(promptsDir, { withFileTypes: true })) {
|
|
824
|
+
if (!ent.isFile() || !ent.name.endsWith('.md')) continue;
|
|
825
|
+
const pf = join(promptsDir, ent.name);
|
|
826
|
+
const slug = slugifyMarketId(basename(ent.name, '.md'));
|
|
827
|
+
if (!slug) continue;
|
|
828
|
+
const raw = readFileSync(pf, 'utf8');
|
|
829
|
+
const { attrs, body } = parseSimpleFrontmatter(raw);
|
|
830
|
+
const installedUser = existsSync(join(lookup.agentDir, 'prompts', slug + '.md'));
|
|
831
|
+
const installedProj = existsSync(join(lookup.workspace, '.pi', 'prompts', slug + '.md'));
|
|
832
|
+
const ecoPrompt = lookup.promptMap.get(slug);
|
|
833
|
+
const installed = installedUser || installedProj || Boolean(ecoPrompt);
|
|
834
|
+
const firstLine = body.split(/\r?\n/).map(l => l.replace(/^#+\s*/, '').trim()).find(Boolean) || '';
|
|
835
|
+
pushUnique({
|
|
836
|
+
uid: `${sourceId}:prompt:${slug}`,
|
|
837
|
+
kind: 'prompt',
|
|
838
|
+
id: slug,
|
|
839
|
+
name: '/' + slug,
|
|
840
|
+
version: '',
|
|
841
|
+
description: attrs.description || firstLine.slice(0, 180),
|
|
842
|
+
sourceId,
|
|
843
|
+
sourceName: label,
|
|
844
|
+
sourcePath: pf,
|
|
845
|
+
installed,
|
|
846
|
+
installedScope: installedProj ? 'project' : (installedUser ? 'user' : (ecoPrompt?.scope || '')),
|
|
847
|
+
hasConfiguration: false,
|
|
848
|
+
permissions: [],
|
|
849
|
+
audit: { highestRisk: 'low', items: [] },
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
} catch {}
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// 6. Check Pi extension/package (package.json without clado-plugin.json)
|
|
856
|
+
const pkgPath = join(dir, 'package.json');
|
|
857
|
+
if (existsSync(pkgPath) && lstatSync(pkgPath).isFile()) {
|
|
858
|
+
try {
|
|
859
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
860
|
+
const kws = Array.isArray(pkg.keywords) ? pkg.keywords.map(k => String(k).toLowerCase()) : [];
|
|
861
|
+
const hasPiMarker = Boolean(pkg.pi)
|
|
862
|
+
|| kws.includes('pi-package')
|
|
863
|
+
|| kws.includes('pi-extension')
|
|
864
|
+
|| kws.includes('clado-extension');
|
|
865
|
+
const hasEntryFile = Boolean(pkg.main)
|
|
866
|
+
|| existsSync(join(dir, 'index.js'))
|
|
867
|
+
|| existsSync(join(dir, 'index.mjs'))
|
|
868
|
+
|| existsSync(join(dir, 'index.ts'));
|
|
869
|
+
if (hasPiMarker || (depth >= 1 && pkg.name && hasEntryFile)) {
|
|
870
|
+
const pkgId = String(pkg.name || basename(dir)).trim();
|
|
871
|
+
const instPkg = lookup.pkgPaths.get(resolve(dir)) || lookup.pkgPaths.get(dir);
|
|
872
|
+
pushUnique({
|
|
873
|
+
uid: `${sourceId}:pi-package:${pkgId}`,
|
|
874
|
+
kind: 'pi-package',
|
|
875
|
+
id: pkgId,
|
|
876
|
+
name: String(pkg.displayName || pkg.name || basename(dir)).trim(),
|
|
877
|
+
version: String(pkg.version || '0.1.0'),
|
|
878
|
+
description: String(pkg.description || '本地 Pi 扩展包').trim(),
|
|
879
|
+
sourceId,
|
|
880
|
+
sourceName: label,
|
|
881
|
+
sourcePath: dir,
|
|
882
|
+
installed: Boolean(instPkg),
|
|
883
|
+
installedScope: instPkg?.scope || '',
|
|
884
|
+
hasConfiguration: false,
|
|
885
|
+
permissions: [],
|
|
886
|
+
audit: { highestRisk: 'medium', items: [{ permission: 'pi.package', risk: 'medium', summary: `挂载本地 Pi 扩展包:${dir}` }] },
|
|
887
|
+
});
|
|
888
|
+
if (depth >= 1) return;
|
|
889
|
+
}
|
|
890
|
+
} catch {}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (depth >= 2) return;
|
|
894
|
+
let entries;
|
|
895
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
896
|
+
for (const ent of entries) {
|
|
897
|
+
if (!ent.isDirectory()) continue;
|
|
898
|
+
if (ent.name.startsWith('.') || SKIP_SCAN_DIRS.has(ent.name)) continue;
|
|
899
|
+
if (ent.name === 'roles' || ent.name === 'prompts') continue;
|
|
900
|
+
scanDir(join(dir, ent.name), depth + 1);
|
|
901
|
+
}
|
|
902
|
+
};
|
|
903
|
+
|
|
904
|
+
scanDir(root, 0);
|
|
905
|
+
items.sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name));
|
|
906
|
+
return { exists: true, path: root, items, error: '' };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
export async function scanAllPluginSources({
|
|
910
|
+
workspace = process.cwd(),
|
|
911
|
+
stateDir = '',
|
|
912
|
+
agentDir = resolvePiAgentDir(),
|
|
913
|
+
query = '',
|
|
914
|
+
fetchImpl = fetch,
|
|
915
|
+
} = {}) {
|
|
916
|
+
const rawSources = listPluginSources(agentDir);
|
|
917
|
+
const lookup = await buildInstalledLookup({ workspace, stateDir, agentDir });
|
|
918
|
+
const enrichedSources = [];
|
|
919
|
+
const allItems = [];
|
|
920
|
+
|
|
921
|
+
for (const src of rawSources) {
|
|
922
|
+
if (!src.enabled) {
|
|
923
|
+
enrichedSources.push({ ...src, exists: src.type === 'local-dir' ? existsSync(src.path) : true, itemCount: 0, error: '' });
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
if (src.type === 'local-dir') {
|
|
927
|
+
const scanned = await scanLocalPluginDirectory(src.path, {
|
|
928
|
+
workspace,
|
|
929
|
+
stateDir,
|
|
930
|
+
agentDir,
|
|
931
|
+
sourceId: src.id,
|
|
932
|
+
sourceName: src.name,
|
|
933
|
+
installedLookup: lookup,
|
|
934
|
+
});
|
|
935
|
+
enrichedSources.push({
|
|
936
|
+
...src,
|
|
937
|
+
exists: scanned.exists,
|
|
938
|
+
itemCount: scanned.items.length,
|
|
939
|
+
error: scanned.error || '',
|
|
940
|
+
});
|
|
941
|
+
allItems.push(...scanned.items);
|
|
942
|
+
} else {
|
|
943
|
+
try {
|
|
944
|
+
const reg = await loadRegistryIndex({ registry: src.url || src.path, stateDir, fetchImpl });
|
|
945
|
+
const mapped = reg.plugins.map(p => {
|
|
946
|
+
const inst = lookup.wsPluginMap.get(p.id);
|
|
947
|
+
return {
|
|
948
|
+
uid: `${src.id}:clado-plugin:${p.id}`,
|
|
949
|
+
kind: 'clado-plugin',
|
|
950
|
+
id: p.id,
|
|
951
|
+
name: p.name,
|
|
952
|
+
version: p.version,
|
|
953
|
+
description: p.description || '',
|
|
954
|
+
sourceId: src.id,
|
|
955
|
+
sourceName: src.name || reg.name,
|
|
956
|
+
sourcePath: p.sourceDir || '',
|
|
957
|
+
registryUrl: src.url || src.path,
|
|
958
|
+
installed: Boolean(inst),
|
|
959
|
+
installedScope: inst ? 'workspace' : '',
|
|
960
|
+
installedVersion: inst?.version || '',
|
|
961
|
+
hasConfiguration: false,
|
|
962
|
+
permissions: p.permissions || [],
|
|
963
|
+
audit: p.audit || auditPluginPermissions(p),
|
|
964
|
+
};
|
|
965
|
+
});
|
|
966
|
+
enrichedSources.push({ ...src, exists: true, itemCount: mapped.length, error: '' });
|
|
967
|
+
allItems.push(...mapped);
|
|
968
|
+
} catch (err) {
|
|
969
|
+
enrichedSources.push({ ...src, exists: false, itemCount: 0, error: err?.message || '索引拉取失败' });
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
const q = String(query || '').trim().toLowerCase();
|
|
975
|
+
const filteredItems = q
|
|
976
|
+
? allItems.filter(it =>
|
|
977
|
+
it.id.toLowerCase().includes(q)
|
|
978
|
+
|| it.name.toLowerCase().includes(q)
|
|
979
|
+
|| it.description.toLowerCase().includes(q)
|
|
980
|
+
|| it.kind.toLowerCase().includes(q)
|
|
981
|
+
|| it.sourceName.toLowerCase().includes(q)
|
|
982
|
+
)
|
|
983
|
+
: allItems;
|
|
984
|
+
|
|
985
|
+
return {
|
|
986
|
+
sources: enrichedSources,
|
|
987
|
+
items: filteredItems,
|
|
988
|
+
installedPlugins: lookup.wsPlugins,
|
|
989
|
+
scannedAt: new Date().toISOString(),
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
export async function installLocalMarketItem(item = {}, {
|
|
994
|
+
ctx = null,
|
|
995
|
+
runtime = null,
|
|
996
|
+
workspace = process.cwd(),
|
|
997
|
+
stateDir = '',
|
|
998
|
+
agentDir = resolvePiAgentDir(),
|
|
999
|
+
scope = 'user',
|
|
1000
|
+
fetchImpl = fetch,
|
|
1001
|
+
} = {}) {
|
|
1002
|
+
const kind = String(item.kind || '').trim();
|
|
1003
|
+
if (!kind) fail('缺少要安装的扩展类型(kind)。', 400);
|
|
1004
|
+
|
|
1005
|
+
if (kind === 'clado-plugin') {
|
|
1006
|
+
if (!ctx) fail('当前工作区上下文不可用。', 500);
|
|
1007
|
+
if (item.sourcePath && existsSync(item.sourcePath)) {
|
|
1008
|
+
return { ok: true, kind, result: installPluginFromDirectory(ctx, item.sourcePath, runtime) };
|
|
1009
|
+
}
|
|
1010
|
+
if (item.registryUrl && item.id) {
|
|
1011
|
+
return {
|
|
1012
|
+
ok: true,
|
|
1013
|
+
kind,
|
|
1014
|
+
result: await installCatalogPlugin(ctx, item.id, { runtime, registry: item.registryUrl, fetchImpl }),
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
fail('找不到插件源码目录或索引地址。', 404);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
if (kind === 'skill') {
|
|
1021
|
+
const srcDir = expandUserPath(item.sourcePath || '');
|
|
1022
|
+
const skillFile = existsSync(join(srcDir, 'SKILL.md')) ? join(srcDir, 'SKILL.md') : srcDir;
|
|
1023
|
+
if (!existsSync(skillFile) || !lstatSync(skillFile).isFile()) fail(`找不到 SKILL.md:${srcDir}`, 404);
|
|
1024
|
+
const raw = readFileSync(skillFile, 'utf8');
|
|
1025
|
+
const { attrs } = parseSimpleFrontmatter(raw);
|
|
1026
|
+
const slug = slugifyMarketId(item.id || attrs.name || basename(dirname(skillFile)));
|
|
1027
|
+
if (!slug) fail('无法识别 Skill 名称。', 400);
|
|
1028
|
+
const targetDir = scope === 'project' ? join(workspace, '.pi', 'skills', slug) : join(agentDir, 'skills', slug);
|
|
1029
|
+
mkdirSync(targetDir, { recursive: true });
|
|
1030
|
+
if (existsSync(srcDir) && lstatSync(srcDir).isDirectory()) {
|
|
1031
|
+
cpSync(srcDir, targetDir, {
|
|
1032
|
+
recursive: true,
|
|
1033
|
+
force: true,
|
|
1034
|
+
filter: src => !basename(src).startsWith('.') && basename(src) !== 'node_modules',
|
|
1035
|
+
});
|
|
1036
|
+
} else {
|
|
1037
|
+
savePiSkill({ name: slug, description: attrs.description || item.description || slug, content: raw, scope }, workspace, agentDir);
|
|
1038
|
+
}
|
|
1039
|
+
return { ok: true, kind, id: slug, scope, path: targetDir };
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
if (kind === 'role') {
|
|
1043
|
+
let roleData = item.roleData && typeof item.roleData === 'object' ? item.roleData : null;
|
|
1044
|
+
if (!roleData && item.sourcePath && existsSync(item.sourcePath)) {
|
|
1045
|
+
const list = collectRolesFromJsonFile(item.sourcePath);
|
|
1046
|
+
roleData = list.find(r => r.id === item.id) || list[0] || null;
|
|
1047
|
+
}
|
|
1048
|
+
if (!roleData) fail('找不到有效的角色定义数据。', 400);
|
|
1049
|
+
const saved = saveRole(roleData, agentDir);
|
|
1050
|
+
return { ok: true, kind, id: saved.id, role: saved };
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
if (kind === 'prompt') {
|
|
1054
|
+
const pf = expandUserPath(item.sourcePath || '');
|
|
1055
|
+
if (!existsSync(pf) || !lstatSync(pf).isFile()) fail(`找不到 Prompt 文件:${pf}`, 404);
|
|
1056
|
+
const raw = readFileSync(pf, 'utf8');
|
|
1057
|
+
const { attrs } = parseSimpleFrontmatter(raw);
|
|
1058
|
+
const slug = slugifyMarketId(item.id || basename(pf, '.md'));
|
|
1059
|
+
const saved = savePiPrompt({ name: slug, description: attrs.description || item.description || '/' + slug, content: raw, scope }, workspace, agentDir);
|
|
1060
|
+
return { ok: true, kind, id: saved.name, scope, path: saved.path };
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
if (kind === 'pi-package') {
|
|
1064
|
+
const srcDir = expandUserPath(item.sourcePath || '');
|
|
1065
|
+
if (!existsSync(srcDir)) fail(`找不到 Pi 扩展目录:${srcDir}`, 404);
|
|
1066
|
+
const installed = await installPiPackage(srcDir, { local: scope === 'project' }, workspace, agentDir);
|
|
1067
|
+
return { ok: true, kind, id: item.id || basename(srcDir), scope, ...installed };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
fail(`不支持的扩展类型:${kind}`, 400);
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
export async function uninstallLocalMarketItem(item = {}, {
|
|
1074
|
+
ctx = null,
|
|
1075
|
+
removePluginFn = null,
|
|
1076
|
+
workspace = process.cwd(),
|
|
1077
|
+
agentDir = resolvePiAgentDir(),
|
|
1078
|
+
} = {}) {
|
|
1079
|
+
const kind = String(item.kind || '').trim();
|
|
1080
|
+
const id = String(item.id || '').trim();
|
|
1081
|
+
if (!kind) fail('缺少要卸载的扩展类型(kind)。', 400);
|
|
1082
|
+
|
|
1083
|
+
if (kind === 'clado-plugin') {
|
|
1084
|
+
if (removePluginFn) return { ok: true, kind, result: removePluginFn(id) };
|
|
1085
|
+
if (!ctx) fail('当前工作区上下文不可用。', 500);
|
|
1086
|
+
return { ok: true, kind, result: removeWorkspacePlugin(ctx, id) };
|
|
1087
|
+
}
|
|
1088
|
+
if (kind === 'skill') {
|
|
1089
|
+
return { ok: true, kind, result: deletePiSkill(id, workspace, agentDir) };
|
|
1090
|
+
}
|
|
1091
|
+
if (kind === 'role') {
|
|
1092
|
+
return { ok: true, kind, result: deleteRole(id, agentDir) };
|
|
1093
|
+
}
|
|
1094
|
+
if (kind === 'prompt') {
|
|
1095
|
+
return { ok: true, kind, result: deletePiPrompt(id, workspace, agentDir) };
|
|
1096
|
+
}
|
|
1097
|
+
if (kind === 'pi-package') {
|
|
1098
|
+
const src = expandUserPath(item.sourcePath || id);
|
|
1099
|
+
const rGlobal = await removePiPackage(src, { local: false }, workspace, agentDir).catch(() => ({ ok: false }));
|
|
1100
|
+
const rLocal = await removePiPackage(src, { local: true }, workspace, agentDir).catch(() => ({ ok: false }));
|
|
1101
|
+
return { ok: Boolean(rGlobal.ok || rLocal.ok), kind, id, source: src };
|
|
1102
|
+
}
|
|
1103
|
+
fail(`不支持卸载该类型:${kind}`, 400);
|
|
1104
|
+
}
|