-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic.js
More file actions
867 lines (793 loc) · 34.3 KB
/
logic.js
File metadata and controls
867 lines (793 loc) · 34.3 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
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
import yaml from 'js-yaml';
import { glob } from 'glob';
// Environment & Constants
const HOME = process.env.TEST_HOME || os.homedir();
export const REPO_ROOT = process.cwd();
export const AGENTS_ROOT = path.join(REPO_ROOT, 'agents');
export const SKILLS_ROOT = path.join(REPO_ROOT, 'skills');
export const SCHEMAS_DIR = path.join(REPO_ROOT, 'schemas');
// --- Schema Registry & Platform System ---
class SchemaRegistry {
constructor() {
this.platforms = {};
this.loaded = false;
}
async load() {
if (this.loaded) return;
if (!await fs.pathExists(SCHEMAS_DIR)) return;
const files = await fs.readdir(SCHEMAS_DIR);
for (const file of files) {
if (file.endsWith('.yaml') || file.endsWith('.yml')) {
try {
const content = await fs.readFile(path.join(SCHEMAS_DIR, file), 'utf8');
const schema = yaml.load(content);
if (schema.name) {
this.platforms[schema.name] = schema;
}
} catch (e) {
console.error(`Failed to load schema ${file}:`, e);
}
}
}
this.loaded = true;
}
getPlatform(name) {
return this.platforms[name];
}
getAllPlatforms() {
return Object.values(this.platforms);
}
}
export const registry = new SchemaRegistry();
// Helper: Expand Tilde in paths
function expandPath(p) {
if (!p) return p;
if (p.startsWith('~/')) {
return path.join(HOME, p.slice(2));
}
return p;
}
const PLATFORM_ALIASES = {
opencode: 'opencode_cli',
claude: 'claude_code',
kilocode: 'kilo_code_vscode',
copilot: 'github_copilot'
};
const PLATFORM_REVERSE_ALIASES = {
opencode_cli: 'opencode',
claude_code: 'claude',
kilo_code: 'kilocode',
kilo_code_vscode: 'kilocode',
github_copilot: 'copilot'
};
function normalizePlatformName(name) {
return PLATFORM_ALIASES[name] || name;
}
function toLegacyPlatformName(name) {
return PLATFORM_REVERSE_ALIASES[name] || name;
}
function platformSupports(schema, feature) {
return Array.isArray(schema?.features) && schema.features.includes(feature);
}
async function getPlatformSchema(platformName) {
await registry.load();
const normalized = normalizePlatformName(platformName);
const schema = registry.getPlatform(normalized);
if (!schema) throw new Error(`Unknown platform: ${platformName}`);
return { schema, normalized };
}
// --- Detection Logic ---
export async function detectPlatforms() {
await registry.load();
const detected = {};
for (const platform of registry.getAllPlatforms()) {
let isDetected = false;
// Check global detection paths
if (platform.target_detection && platform.target_detection.paths) {
for (const rawPath of platform.target_detection.paths) {
const p = expandPath(rawPath);
if (await fs.pathExists(p)) {
isDetected = true;
break;
}
}
}
// Always return the platform key, value is boolean detected status
// But for UI "available platforms", we might just return the object if detected?
// UI expects object keys to be platform names.
if (isDetected) {
detected[toLegacyPlatformName(platform.name)] = true;
}
}
return detected; // { opencode: true, claude_code: true }
}
export async function loadConfig() {
// Minimal config loader (if needed for language)
return { language: 'zh' };
}
export async function detectProjectRoot() {
if (process.env.AGENTSHARE_PROJECT_ROOT) {
return process.env.AGENTSHARE_PROJECT_ROOT;
}
return process.cwd();
}
// --- Legacy Support & Constants ---
export const PROJECT_LEVEL_PATHS = {
opencode: 'opencode.json',
kilocode: '.vscode/mcp.json'
};
// Generate PLATFORM_PATHS from Registry (for legacy UI or other consumers)
// Note: This is an async getter in concept, but variable must be synchronous.
// We'll export a Proxy or empty object, but best to rely on functions.
// index.js imports it. We can try to emulate it.
// Assuming detectPlatforms logic uses registry, we don't need PLATFORM_PATHS for detection in index.js anymore
// because we updated index.js to use registry? No, we updated detectPlatforms.
// BUT index.js imports PLATFORM_PATHS line 10.
export const PLATFORM_PATHS = new Proxy({}, {
get: (target, prop) => {
// Fallback for legacy static access?
// It's irrelevant if detectPlatforms is refactored.
// But we need to export it to satisfy import.
return [];
}
});
// --- Legacy Agent Functions (Stubs/Adapters) ---
export async function checkAgentExists(agentName, platform) {
try {
const resolved = await resolveAgentTarget(platform, 'global');
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
return await fs.pathExists(targetPath);
}
const modes = await readCustomModes(resolved.targetPath);
return modes.some((m) => m && m.slug === agentName);
} catch (e) {
return false;
}
}
export async function checkAgentExistsInProject(agentName, platform, projectRoot) {
try {
const resolved = await resolveAgentTarget(platform, 'project', projectRoot);
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
return await fs.pathExists(targetPath);
}
const modes = await readCustomModes(resolved.targetPath);
return modes.some((m) => m && m.slug === agentName);
} catch (e) {
return false;
}
}
export async function deployAgentToProject(agentName, platform, projectRoot) {
await deployAgent(agentName, platform, 'project', projectRoot);
}
export async function extractAgent(agentName, platform) {
const resolved = await resolveAgentTarget(platform, 'global');
let output;
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
if (!await fs.pathExists(targetPath)) throw new Error(`Agent ${agentName} not found`);
const content = await fs.readFile(targetPath, 'utf8');
const { frontmatter, body } = parseFrontmatter(content);
if (!frontmatter) throw new Error('Agent frontmatter missing');
const neutralFrontmatter = buildNeutralFrontmatterFromPlatform(frontmatter, resolved.schema, resolved.normalized, agentName);
output = buildAgentMarkdown(neutralFrontmatter, body, true);
} else {
const modes = await readCustomModes(resolved.targetPath);
const mode = modes.find((m) => m && m.slug === agentName);
if (!mode) throw new Error(`Agent ${agentName} not found`);
const neutralFrontmatter = buildNeutralFrontmatterFromKiloMode(mode, resolved.normalized);
const body = buildAgentBodyFromKiloMode(mode);
output = buildAgentMarkdown(neutralFrontmatter, body, true);
}
const agentDir = path.join(REPO_ROOT, 'agents', agentName);
await fs.ensureDir(agentDir);
await fs.writeFile(path.join(agentDir, 'agent.md'), output);
}
export async function extractAgentFromProject(agentName, platform, projectRoot) {
const resolved = await resolveAgentTarget(platform, 'project', projectRoot);
let output;
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
if (!await fs.pathExists(targetPath)) throw new Error(`Agent ${agentName} not found`);
const content = await fs.readFile(targetPath, 'utf8');
const { frontmatter, body } = parseFrontmatter(content);
if (!frontmatter) throw new Error('Agent frontmatter missing');
const neutralFrontmatter = buildNeutralFrontmatterFromPlatform(frontmatter, resolved.schema, resolved.normalized, agentName);
output = buildAgentMarkdown(neutralFrontmatter, body, true);
} else {
const modes = await readCustomModes(resolved.targetPath);
const mode = modes.find((m) => m && m.slug === agentName);
if (!mode) throw new Error(`Agent ${agentName} not found`);
const neutralFrontmatter = buildNeutralFrontmatterFromKiloMode(mode, resolved.normalized);
const body = buildAgentBodyFromKiloMode(mode);
output = buildAgentMarkdown(neutralFrontmatter, body, true);
}
const agentDir = path.join(projectRoot, 'agents', agentName);
await fs.ensureDir(agentDir);
await fs.writeFile(path.join(agentDir, 'agent.md'), output);
}
export async function uninstallAgent(agentName, platform) {
try {
const resolved = await resolveAgentTarget(platform, 'global');
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
if (await fs.pathExists(targetPath)) {
await fs.remove(targetPath);
}
} else {
await removeKiloMode(resolved.targetPath, agentName);
}
const agentPath = path.join(REPO_ROOT, 'agents', agentName, 'agent.md');
if (await fs.pathExists(agentPath)) {
const content = await fs.readFile(agentPath, 'utf8');
const { frontmatter } = parseFrontmatter(content);
if (frontmatter) {
await removeMcps(frontmatter, platform, 'global', REPO_ROOT);
}
}
} catch (e) {
throw e;
}
}
export async function uninstallAgentFromProject(agentName, platform, projectRoot) {
try {
const resolved = await resolveAgentTarget(platform, 'project', projectRoot);
if (resolved.kind === 'agent_definition') {
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
if (await fs.pathExists(targetPath)) {
await fs.remove(targetPath);
}
} else {
await removeKiloMode(resolved.targetPath, agentName);
}
const agentPath = path.join(projectRoot, 'agents', agentName, 'agent.md');
if (await fs.pathExists(agentPath)) {
const content = await fs.readFile(agentPath, 'utf8');
const { frontmatter } = parseFrontmatter(content);
if (frontmatter) {
await removeMcps(frontmatter, platform, 'project', projectRoot);
}
}
} catch (e) {
throw e;
}
}
// --- Agent Logic (Legacy/Schema-Hybrid) ---
export async function scanAgents(dir) {
if (!await fs.pathExists(dir)) return [];
const items = await fs.readdir(dir);
const agents = [];
for (const item of items) {
const fullPath = path.join(dir, item);
if ((await fs.stat(fullPath)).isDirectory()) {
if (await fs.pathExists(path.join(fullPath, 'agent.md'))) {
agents.push(item);
}
}
}
return agents;
}
export async function scanInstalledAgents(platforms) {
await registry.load();
const result = { opencode: [], claude: [], kilocode: [], copilot: [] };
for (const platform of registry.getAllPlatforms()) {
const legacyName = toLegacyPlatformName(platform.name);
if (platforms && !platforms[legacyName]) continue;
try {
const resolved = await resolveAgentTarget(platform.name, 'global');
if (resolved.kind === 'agent_definition') {
const pattern = resolved.targetTemplate.replace('{agent_name}', '*');
const baseTemplate = path.basename(resolved.targetTemplate);
const regex = new RegExp('^' + baseTemplate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace('\\{agent_name\\}', '(.+)') + '$');
const files = await glob(pattern, { nodir: true });
const names = files.map(f => {
const m = path.basename(f).match(regex);
return m ? m[1] : null;
}).filter(Boolean);
result[legacyName] = names;
} else {
const modes = await readCustomModes(resolved.targetPath);
result[legacyName] = modes.map((m) => m && m.slug ? String(m.slug) : null).filter(Boolean);
}
} catch (e) {
result[legacyName] = [];
}
}
return result;
}
export async function scanProjectAgents(projectRoot) {
await registry.load();
const result = { opencode: [], claude: [], kilocode: [], copilot: [] };
if (!projectRoot) return result;
for (const platform of registry.getAllPlatforms()) {
const legacyName = toLegacyPlatformName(platform.name);
try {
const resolved = await resolveAgentTarget(platform.name, 'project', projectRoot);
if (resolved.kind === 'agent_definition') {
const pattern = resolved.targetTemplate.replace('{agent_name}', '*');
const baseTemplate = path.basename(resolved.targetTemplate);
const regex = new RegExp('^' + baseTemplate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace('\\{agent_name\\}', '(.+)') + '$');
const files = await glob(pattern, { nodir: true });
const names = files.map(f => {
const m = path.basename(f).match(regex);
return m ? m[1] : null;
}).filter(Boolean);
result[legacyName] = names;
} else {
const modes = await readCustomModes(resolved.targetPath);
result[legacyName] = modes.map((m) => m && m.slug ? String(m.slug) : null).filter(Boolean);
}
} catch (e) {
result[legacyName] = [];
}
}
return result;
}
export async function deployAgent(agentName, platformName, scope, projectRoot) {
const actualScope = typeof scope === 'string' ? scope : 'global';
const root = projectRoot || REPO_ROOT;
const agentPath = path.join(root, 'agents', agentName, 'agent.md');
if (!await fs.pathExists(agentPath)) throw new Error(`Agent not found: ${agentPath}`);
const content = await fs.readFile(agentPath, 'utf8');
const { frontmatter, body } = parseFrontmatter(content);
if (!frontmatter) throw new Error('Agent frontmatter missing');
if (!frontmatter.name || frontmatter.name !== agentName) {
throw new Error(`Agent frontmatter name mismatch: ${agentName}`);
}
const resolved = await resolveAgentTarget(platformName, actualScope, root);
if (resolved.kind === 'agent_definition') {
const outputFrontmatter = buildAgentFrontmatter(frontmatter, resolved.schema, resolved.normalized);
const output = buildAgentMarkdown(outputFrontmatter, resolved.agentDef.include_body ? body : '', resolved.agentDef.include_body);
const targetPath = resolved.targetTemplate.replace('{agent_name}', agentName);
await fs.ensureDir(path.dirname(targetPath));
await fs.writeFile(targetPath, output);
} else {
const platformConfig = frontmatter.platforms && frontmatter.platforms[resolved.normalized] ? frontmatter.platforms[resolved.normalized] : null;
const modeName = platformConfig && platformConfig.name ? platformConfig.name : frontmatter.name;
const desc = platformConfig && platformConfig.description ? platformConfig.description : frontmatter.description;
const roleDefinition = platformConfig && platformConfig.roleDefinition ? platformConfig.roleDefinition : (body || '').trim();
const groups = platformConfig && Array.isArray(platformConfig.groups) ? platformConfig.groups : null;
const whenToUse = platformConfig && platformConfig.whenToUse !== undefined ? platformConfig.whenToUse : undefined;
const customInstructions = platformConfig && platformConfig.customInstructions !== undefined ? platformConfig.customInstructions : undefined;
if (!groups) {
throw new Error(`Platform ${platformName} requires platforms.${resolved.normalized}.groups for custom mode deployment`);
}
if (!roleDefinition) {
throw new Error('Agent body is required for custom mode deployment');
}
await upsertKiloMode(resolved.targetPath, {
slug: agentName,
name: modeName,
description: desc,
roleDefinition,
groups,
...(whenToUse !== undefined ? { whenToUse } : {}),
...(customInstructions !== undefined ? { customInstructions } : {})
});
}
await applyMcps(frontmatter, platformName, actualScope, root);
}
// --- Skill Logic (Fully Schema Driven) ---
export async function scanProjectSkills(projectRoot) {
if (!projectRoot) return [];
const skillsDir = path.join(projectRoot, 'skills');
if (!await fs.pathExists(skillsDir)) return [];
const items = await fs.readdir(skillsDir);
const skills = [];
for (const item of items) {
if ((await fs.stat(path.join(skillsDir, item))).isDirectory()) {
if (await fs.pathExists(path.join(skillsDir, item, 'SKILL.md'))) {
skills.push(item);
}
}
}
return skills;
}
function parseFrontmatter(content) {
const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n?/);
if (!match) {
return { frontmatter: null, body: content };
}
const data = yaml.load(match[1]) || {};
const body = content.slice(match[0].length);
return { frontmatter: data, body };
}
function getByPath(obj, pathValue) {
if (!obj || !pathValue) return undefined;
const parts = pathValue.split('.');
let current = obj;
for (const part of parts) {
if (current && Object.prototype.hasOwnProperty.call(current, part)) {
current = current[part];
} else {
return undefined;
}
}
return current;
}
function setByPath(obj, pathValue, value) {
const parts = pathValue.split('.');
let current = obj;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (i === parts.length - 1) {
current[part] = value;
} else {
if (!current[part] || typeof current[part] !== 'object') {
current[part] = {};
}
current = current[part];
}
}
}
async function resolveDetectedPlatformRoot(schema) {
const paths = schema.target_detection?.paths || [];
for (const rawPath of paths) {
const p = expandPath(rawPath);
if (await fs.pathExists(p)) {
const stat = await fs.stat(p);
return stat.isFile() ? path.dirname(p) : p;
}
}
return null;
}
async function resolveCustomModesTarget(platformName, scope, projectRoot) {
const { schema, normalized } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'agents')) {
throw new Error(`Platform ${platformName} does not support agents`);
}
const customDef = schema.outputs?.custom_modes;
if (!customDef) throw new Error(`Platform ${platformName} does not support custom modes`);
let targetPath;
if (scope === 'global') {
targetPath = expandPath(customDef.target);
if (!path.isAbsolute(targetPath)) {
const root = await resolveDetectedPlatformRoot(schema);
if (!root) throw new Error(`Platform ${platformName} not detected`);
targetPath = path.join(root, targetPath);
}
} else if (scope === 'project') {
if (!projectRoot) throw new Error("Project root required for project scope");
if (schema.project_paths && schema.project_paths.custom_modes) {
targetPath = path.join(projectRoot, schema.project_paths.custom_modes);
} else {
const candidate = expandPath(customDef.target);
if (path.isAbsolute(candidate)) {
throw new Error(`Platform ${platformName} does not support project-scoped custom modes`);
}
targetPath = path.join(projectRoot, candidate);
}
}
return { targetPath, schema, normalized, customDef };
}
async function resolveAgentTarget(platformName, scope, projectRoot) {
const { schema, normalized } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'agents')) {
throw new Error(`Platform ${platformName} does not support agents`);
}
if (schema.outputs?.agent_definition) {
const resolved = await resolveAgentDefinitionTarget(platformName, scope, projectRoot);
return { kind: 'agent_definition', ...resolved };
}
if (schema.outputs?.custom_modes) {
const resolved = await resolveCustomModesTarget(platformName, scope, projectRoot);
return { kind: 'custom_modes', ...resolved };
}
throw new Error(`Platform ${platformName} does not support agents`);
}
async function readCustomModes(targetPath) {
if (!await fs.pathExists(targetPath)) return [];
const raw = await fs.readFile(targetPath, 'utf8');
if (!raw.trim()) return [];
const parsed = yaml.load(raw);
if (!parsed || typeof parsed !== 'object') return [];
const obj = parsed;
const list = Array.isArray(obj.customModes)
? obj.customModes
: Array.isArray(obj.custom_modes)
? obj.custom_modes
: [];
return Array.isArray(list) ? list : [];
}
async function writeCustomModes(targetPath, modes) {
const payload = { customModes: modes };
const content = yaml.dump(payload, { lineWidth: 120 });
await fs.ensureDir(path.dirname(targetPath));
await fs.writeFile(targetPath, content);
}
function buildNeutralFrontmatterFromKiloMode(mode, platformName) {
const frontmatter = {
name: mode.slug,
description: mode.description
};
const platformConfig = {};
if (mode.name !== undefined) platformConfig.name = mode.name;
if (mode.slug !== undefined) platformConfig.slug = mode.slug;
if (mode.groups !== undefined) platformConfig.groups = mode.groups;
if (mode.whenToUse !== undefined) platformConfig.whenToUse = mode.whenToUse;
if (mode.customInstructions !== undefined) platformConfig.customInstructions = mode.customInstructions;
frontmatter.platforms = { [platformName]: platformConfig };
return frontmatter;
}
function buildAgentBodyFromKiloMode(mode) {
const parts = [];
if (mode.roleDefinition) parts.push(String(mode.roleDefinition).trim());
if (mode.customInstructions) parts.push(String(mode.customInstructions).trim());
return parts.filter(Boolean).join('\n\n').trim();
}
async function upsertKiloMode(targetPath, mode) {
const modes = await readCustomModes(targetPath);
const next = [];
let replaced = false;
for (const m of modes) {
if (m && m.slug === mode.slug) {
next.push(mode);
replaced = true;
} else {
next.push(m);
}
}
if (!replaced) next.push(mode);
await writeCustomModes(targetPath, next);
}
async function removeKiloMode(targetPath, slug) {
if (!await fs.pathExists(targetPath)) return;
const modes = await readCustomModes(targetPath);
const next = modes.filter((m) => !(m && m.slug === slug));
if (next.length === modes.length) return;
if (next.length === 0) {
await fs.remove(targetPath);
return;
}
await writeCustomModes(targetPath, next);
}
async function resolveAgentDefinitionTarget(platformName, scope, projectRoot) {
const { schema, normalized } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'agents')) {
throw new Error(`Platform ${platformName} does not support agents`);
}
const agentDef = schema.outputs?.agent_definition;
if (!agentDef) throw new Error(`Platform ${platformName} does not support agents`);
let targetTemplate;
if (scope === 'global') {
targetTemplate = expandPath(agentDef.target);
if (!path.isAbsolute(targetTemplate)) {
const root = await resolveDetectedPlatformRoot(schema);
if (!root) throw new Error(`Platform ${platformName} not detected`);
targetTemplate = path.join(root, targetTemplate);
}
} else if (scope === 'project') {
if (!projectRoot) throw new Error("Project root required for project scope");
if (schema.project_paths && schema.project_paths.agents) {
targetTemplate = path.join(projectRoot, schema.project_paths.agents, path.basename(agentDef.target));
} else {
targetTemplate = expandPath(agentDef.target);
if (path.isAbsolute(targetTemplate)) {
throw new Error(`Platform ${platformName} does not support project-scoped agents`);
}
targetTemplate = path.join(projectRoot, targetTemplate);
}
}
return { targetTemplate, schema, agentDef, normalized };
}
function buildAgentFrontmatter(frontmatter, schema, platformName) {
const agentDef = schema.outputs?.agent_definition;
const fields = agentDef?.frontmatter || [];
const exclude = agentDef?.exclude_fields || [];
const result = {};
for (const item of fields) {
if (typeof item === 'string') {
if (exclude.includes(item)) continue;
const value = frontmatter[item];
if (value !== undefined) result[item] = value;
} else if (item && typeof item === 'object') {
const [key, pathValue] = Object.entries(item)[0];
if (exclude.includes(key)) continue;
const value = getByPath(frontmatter, pathValue.replace('platforms.' + platformName, `platforms.${platformName}`));
if (value !== undefined) result[key] = value;
}
}
if (!result.name) throw new Error('Agent name missing');
if (!result.description) throw new Error('Agent description missing');
return result;
}
function buildNeutralFrontmatterFromPlatform(frontmatter, schema, platformName, agentName) {
const agentDef = schema.outputs?.agent_definition;
const fields = agentDef?.frontmatter || [];
const result = {};
for (const item of fields) {
if (typeof item === 'string') {
const value = frontmatter[item];
if (value !== undefined) result[item] = value;
} else if (item && typeof item === 'object') {
const [key, pathValue] = Object.entries(item)[0];
const value = frontmatter[key];
if (value !== undefined) {
setByPath(result, pathValue, value);
}
}
}
if (!result.name) result.name = agentName;
if (!result.description) throw new Error('Agent description missing');
return result;
}
function buildAgentMarkdown(frontmatter, body, includeBody = true) {
const yamlText = yaml.dump(frontmatter);
if (!includeBody) return `---\n${yamlText}---\n`;
return `---\n${yamlText}---\n\n${body || ''}`.trimEnd() + '\n';
}
async function resolveMcpConfigTarget(platformName, scope, projectRoot) {
const { schema } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'mcps')) {
throw new Error(`Platform ${platformName} does not support mcps`);
}
const configDef = schema.outputs?.skill_config;
if (!configDef) throw new Error(`Platform ${platformName} does not support mcps`);
let targetPath;
if (scope === 'global') {
targetPath = expandPath(configDef.target);
if (!path.isAbsolute(targetPath)) {
const root = await resolveDetectedPlatformRoot(schema);
if (!root) throw new Error(`Platform ${platformName} not detected`);
targetPath = path.join(root, targetPath);
}
} else if (scope === 'project') {
if (!projectRoot) throw new Error("Project root required for project scope");
if (schema.project_paths && schema.project_paths.config) {
targetPath = path.join(projectRoot, schema.project_paths.config);
} else {
const candidate = expandPath(configDef.target);
if (path.isAbsolute(candidate)) {
throw new Error(`Platform ${platformName} does not support project-scoped mcps`);
}
targetPath = path.join(projectRoot, candidate);
}
}
return { targetPath, configDef };
}
function buildMcpEntries(frontmatter) {
const entries = {};
for (const [name, mcp] of Object.entries(frontmatter.mcps || {})) {
if (mcp && mcp.enabled === false) continue;
const command = Array.isArray(mcp?.command) ? mcp.command[0] : mcp?.command;
const args = Array.isArray(mcp?.command) ? mcp.command.slice(1) : (mcp?.args || []);
entries[name] = {
command,
args,
env: mcp?.env || {}
};
}
return entries;
}
async function applyMcps(frontmatter, platformName, scope, projectRoot) {
if (!frontmatter?.mcps) return;
const resolved = await resolveMcpConfigTarget(platformName, scope, projectRoot);
const { targetPath, configDef } = resolved;
const key = configDef.key || 'mcpServers';
const entries = buildMcpEntries(frontmatter);
let config = {};
let hasExisting = false;
if (await fs.pathExists(targetPath)) {
try {
config = await fs.readJson(targetPath);
hasExisting = true;
} catch (e) {
config = {};
}
}
if (!hasExisting && configDef.template) {
const payload = configDef.template.replace('{mcps}', JSON.stringify(entries, null, 2));
await fs.ensureDir(path.dirname(targetPath));
await fs.writeFile(targetPath, payload);
return;
}
if (!config[key]) config[key] = {};
for (const [name, value] of Object.entries(entries)) {
config[key][name] = value;
}
await fs.ensureDir(path.dirname(targetPath));
await fs.writeJson(targetPath, config, { spaces: 2 });
}
async function removeMcps(frontmatter, platformName, scope, projectRoot) {
if (!frontmatter?.mcps) return;
const resolved = await resolveMcpConfigTarget(platformName, scope, projectRoot);
const { targetPath, configDef } = resolved;
if (!await fs.pathExists(targetPath)) return;
let config = {};
try { config = await fs.readJson(targetPath); } catch (e) { return; }
const key = configDef.key || 'mcpServers';
if (!config[key]) return;
for (const name of Object.keys(frontmatter.mcps)) {
delete config[key][name];
}
await fs.writeJson(targetPath, config, { spaces: 2 });
}
async function resolveSkillsDirTarget(platformName, scope, projectRoot) {
const { schema } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'skills')) {
throw new Error(`Platform ${platformName} does not support skills`);
}
if (!schema.outputs.skills) {
throw new Error(`Platform ${platformName} does not support Skills (outputs.skills missing)`);
}
const skillsDef = schema.outputs.skills;
let targetPath;
if (scope === 'global') {
targetPath = expandPath(skillsDef.target);
if (!path.isAbsolute(targetPath)) {
const root = await resolveDetectedPlatformRoot(schema);
if (!root) throw new Error(`Platform ${platformName} not detected`);
targetPath = path.join(root, targetPath);
}
} else if (scope === 'project') {
if (!projectRoot) throw new Error("Project root required for project scope");
if (schema.project_paths && schema.project_paths.skills) {
targetPath = path.join(projectRoot, schema.project_paths.skills);
} else {
targetPath = expandPath(skillsDef.target);
if (path.isAbsolute(targetPath)) {
throw new Error(`Platform ${platformName} does not support project-scoped skills`);
}
targetPath = path.join(projectRoot, targetPath);
}
}
return { targetPath, skillsDef };
}
export async function scanPlatformSkills(platformName, scope, projectRoot) {
try {
const { schema } = await getPlatformSchema(platformName);
if (!platformSupports(schema, 'skills')) return null;
const { targetPath } = await resolveSkillsDirTarget(platformName, scope, projectRoot);
if (!await fs.pathExists(targetPath)) return [];
const items = await fs.readdir(targetPath);
const skills = [];
for (const item of items) {
const fullPath = path.join(targetPath, item);
if ((await fs.stat(fullPath)).isDirectory()) {
if (await fs.pathExists(path.join(fullPath, 'SKILL.md'))) {
skills.push(item);
}
}
}
return skills;
} catch (e) {
// console.warn(`Scan failed for ${platformName} ${scope}: ${e.message}`);
}
return [];
}
export async function deploySkill(skillName, platformName, scope, projectRoot = REPO_ROOT) {
const { targetPath } = await resolveSkillsDirTarget(platformName, scope, projectRoot);
const skillDir = path.join(projectRoot, 'skills', skillName);
const skillDocPath = path.join(skillDir, 'SKILL.md');
if (!await fs.pathExists(skillDocPath)) throw new Error(`Skill definition not found: ${skillDocPath}`);
const skillContent = await fs.readFile(skillDocPath, 'utf8');
const { frontmatter } = parseFrontmatter(skillContent);
if (!frontmatter || frontmatter.name !== skillName) {
throw new Error(`Skill frontmatter name mismatch: ${skillName}`);
}
await fs.ensureDir(targetPath);
const destDir = path.join(targetPath, skillName);
await fs.copy(skillDir, destDir, { overwrite: true });
}
export async function extractSkill(skillName, platformName, scope, projectRoot = REPO_ROOT) {
const { targetPath } = await resolveSkillsDirTarget(platformName, scope, projectRoot);
const sourceDir = path.join(targetPath, skillName);
const skillDocPath = path.join(sourceDir, 'SKILL.md');
if (!await fs.pathExists(skillDocPath)) {
throw new Error(`Skill ${skillName} not found in ${platformName}`);
}
const destDir = path.join(projectRoot, 'skills', skillName);
await fs.ensureDir(path.dirname(destDir));
await fs.copy(sourceDir, destDir, { overwrite: true });
}
export async function uninstallSkill(skillName, platformName, scope, projectRoot = REPO_ROOT) {
const { targetPath } = await resolveSkillsDirTarget(platformName, scope, projectRoot);
const skillDir = path.join(targetPath, skillName);
if (await fs.pathExists(skillDir)) {
await fs.remove(skillDir);
}
}