agent-space-manager 0.0.0-stage → 1.0.1

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/adapters.mjs ADDED
@@ -0,0 +1,1228 @@
1
+ // adapters.mjs
2
+ // Native-format component adapters & ownership manifest manager.
3
+ // Guarantees non-destructive syncs:
4
+ // 1. Creates a `.asm-bak` backup before modifying any existing user-owned config file.
5
+ // 2. Tracks every junction, file copy, JSON key, and Markdown/TOML block in `.asm-state/<id>.json`.
6
+ // 3. Only prunes items that Agent Space Manager itself created (or legacy junctions pointing inside hubRoot).
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import {
11
+ getHomeDir,
12
+ resolveEffectiveAgentPaths,
13
+ resolveEffectiveProjectPaths,
14
+ } from "./agents.mjs";
15
+
16
+ const BLOCK_START_MD = "<!-- agent-space-manager:start -->";
17
+ const BLOCK_END_MD = "<!-- agent-space-manager:end -->";
18
+ const BLOCK_START_TOML = "# >>> agent-space-manager";
19
+ const BLOCK_END_TOML = "# <<< agent-space-manager";
20
+
21
+ export function ensureDir(dirPath) {
22
+ if (dirPath && !fs.existsSync(dirPath)) {
23
+ fs.mkdirSync(dirPath, { recursive: true });
24
+ }
25
+ }
26
+
27
+ export function getStateDir() {
28
+ const dir = path.join(getHomeDir(), ".agent-space-manager", "state");
29
+ ensureDir(dir);
30
+ return dir;
31
+ }
32
+
33
+ export function getStateFilePath(ownerId) {
34
+ const safeId = String(ownerId || "default").replace(/[^a-zA-Z0-9_-]/g, "_");
35
+ return path.join(getStateDir(), `${safeId}.json`);
36
+ }
37
+
38
+ export function loadOwnershipState(ownerId) {
39
+ const file = getStateFilePath(ownerId);
40
+ try {
41
+ if (fs.existsSync(file)) {
42
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
43
+ return {
44
+ meta: parsed.meta && typeof parsed.meta === "object" ? parsed.meta : null,
45
+ links: Array.isArray(parsed.links) ? parsed.links : [],
46
+ files: Array.isArray(parsed.files) ? parsed.files : [],
47
+ jsonKeys: parsed.jsonKeys && typeof parsed.jsonKeys === "object" ? parsed.jsonKeys : {},
48
+ blocks: Array.isArray(parsed.blocks) ? parsed.blocks : [],
49
+ };
50
+ }
51
+ } catch {}
52
+ return { meta: null, links: [], files: [], jsonKeys: {}, blocks: [] };
53
+ }
54
+
55
+ export function saveOwnershipState(ownerId, state) {
56
+ const file = getStateFilePath(ownerId);
57
+ ensureDir(path.dirname(file));
58
+ fs.writeFileSync(file, JSON.stringify(state, null, 2), "utf8");
59
+ }
60
+
61
+ export function deleteOwnershipState(ownerId) {
62
+ const file = getStateFilePath(ownerId);
63
+ try {
64
+ if (fs.existsSync(file)) {
65
+ fs.unlinkSync(file);
66
+ return true;
67
+ }
68
+ } catch {}
69
+ return false;
70
+ }
71
+
72
+ export function listAllOwnershipStates() {
73
+ const dir = getStateDir();
74
+ const results = [];
75
+ try {
76
+ if (fs.existsSync(dir)) {
77
+ for (const name of fs.readdirSync(dir)) {
78
+ if (name.endsWith(".json")) {
79
+ const ownerId = name.slice(0, -5);
80
+ const state = loadOwnershipState(ownerId);
81
+ results.push({ ownerId, file: path.join(dir, name), ...state });
82
+ }
83
+ }
84
+ }
85
+ } catch {}
86
+ return results;
87
+ }
88
+
89
+ export function ensureBackupOnce(filePath) {
90
+ try {
91
+ if (fs.existsSync(filePath)) {
92
+ const bak = `${filePath}.asm-bak`;
93
+ if (!fs.existsSync(bak)) {
94
+ fs.copyFileSync(filePath, bak);
95
+ }
96
+ }
97
+ } catch {}
98
+ }
99
+
100
+ /**
101
+ * Extracts simple YAML frontmatter key/values (e.g. name, description) and Markdown body.
102
+ */
103
+ export function parseMarkdownFrontmatter(raw = "") {
104
+ const text = String(raw || "").replace(/^\uFEFF/, "");
105
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
106
+ if (!m) {
107
+ return { frontmatter: {}, body: text.trim() };
108
+ }
109
+ const yamlBlock = m[1];
110
+ const body = m[2].trim();
111
+ const fm = {};
112
+ for (const line of yamlBlock.split(/\r?\n/)) {
113
+ const kv = line.match(/^([a-zA-Z0-9_-]+)\s*:\s*(.+)$/);
114
+ if (kv) {
115
+ const key = kv[1];
116
+ let val = kv[2].trim();
117
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
118
+ val = val.slice(1, -1);
119
+ }
120
+ fm[key] = val;
121
+ }
122
+ }
123
+ return { frontmatter: fm, body };
124
+ }
125
+
126
+ /**
127
+ * Checks whether a target path is located inside any known hub path or plugin source path.
128
+ */
129
+ export function isTargetInsideHub(targetPath, activePlugins = [], hubRoot = "") {
130
+ if (!targetPath) return false;
131
+ const resolved = path.resolve(targetPath).toLowerCase();
132
+ if (hubRoot) {
133
+ const hubRes = path.resolve(hubRoot).toLowerCase();
134
+ if (resolved.startsWith(hubRes)) return true;
135
+ }
136
+ for (const p of activePlugins) {
137
+ if (p.path) {
138
+ const pRes = path.resolve(p.path).toLowerCase();
139
+ const parentRes = path.dirname(pRes).toLowerCase();
140
+ if (resolved.startsWith(pRes) || resolved.startsWith(parentRes)) return true;
141
+ }
142
+ }
143
+ if (resolved.includes("ai agent space") || resolved.includes("ai-agent-space")) {
144
+ return true;
145
+ }
146
+ return false;
147
+ }
148
+
149
+ /**
150
+ * Collects all enabled skills, MCP server configs, rules, subagents, and hooks from the active plugin list.
151
+ */
152
+ export function collectEnabledComponents(allPlugins = [], enabledMap = {}) {
153
+ const skills = []; // { name, sourceDir, pluginId }
154
+ const seenSkills = new Set();
155
+ const mcpServers = {}; // { [serverName]: serverDef }
156
+ const rules = []; // { name, sourceFile, pluginId }
157
+ const seenRules = new Set();
158
+ const agents = []; // { name, sourceFile, pluginId }
159
+ const seenAgents = new Set();
160
+ const hooks = []; // { id, def, pluginId }
161
+ const seenHooks = new Set();
162
+ const conflicts = [];
163
+
164
+ for (const plugin of allPlugins) {
165
+ const isEnabled = Boolean(
166
+ enabledMap &&
167
+ (enabledMap[plugin.id] === true ||
168
+ (plugin.isRootSkills && enabledMap[plugin.id] !== false && Object.values(enabledMap).some((v) => v === true)))
169
+ );
170
+ if (!isEnabled || !plugin.path || !fs.existsSync(plugin.path)) continue;
171
+
172
+ // 1. Skills
173
+ for (const sName of plugin.skills || []) {
174
+ const skillDir = plugin.isRootSkills
175
+ ? path.join(plugin.path, sName)
176
+ : path.join(plugin.path, "skills", sName);
177
+ if (!fs.existsSync(skillDir)) continue;
178
+ if (seenSkills.has(sName)) {
179
+ conflicts.push({ type: "skill", name: sName, pluginId: plugin.id, reason: "duplicate skill name" });
180
+ continue;
181
+ }
182
+ seenSkills.add(sName);
183
+ skills.push({ name: sName, sourceDir: skillDir, pluginId: plugin.id });
184
+ }
185
+
186
+ // 2. MCP Servers
187
+ const mcpFile = path.join(plugin.path, "mcp_config.json");
188
+ if (plugin.hasMcp && fs.existsSync(mcpFile)) {
189
+ try {
190
+ const parsed = JSON.parse(fs.readFileSync(mcpFile, "utf8"));
191
+ const servers = parsed.mcpServers || parsed.servers || {};
192
+ for (const [srvName, srvDef] of Object.entries(servers)) {
193
+ if (srvDef && typeof srvDef === "object") {
194
+ mcpServers[srvName] = srvDef;
195
+ }
196
+ }
197
+ } catch {}
198
+ }
199
+
200
+ // 3. Rules
201
+ const rulesDir = path.join(plugin.path, "rules");
202
+ for (const rName of plugin.rules || []) {
203
+ const ruleFile = path.join(rulesDir, rName);
204
+ if (fs.existsSync(ruleFile) && !seenRules.has(rName)) {
205
+ seenRules.add(rName);
206
+ rules.push({ name: rName, sourceFile: ruleFile, pluginId: plugin.id });
207
+ }
208
+ }
209
+
210
+ // 4. Subagents
211
+ const agentsDir = path.join(plugin.path, "agents");
212
+ for (const aName of plugin.agents || []) {
213
+ const agentFile = path.join(agentsDir, aName);
214
+ if (fs.existsSync(agentFile) && !seenAgents.has(aName)) {
215
+ seenAgents.add(aName);
216
+ agents.push({ name: aName, sourceFile: agentFile, pluginId: plugin.id });
217
+ }
218
+ }
219
+
220
+ // 5. Hooks
221
+ const hooksFile = path.join(plugin.path, "hooks.json");
222
+ if (plugin.hasHooks && fs.existsSync(hooksFile)) {
223
+ try {
224
+ const parsed = JSON.parse(fs.readFileSync(hooksFile, "utf8"));
225
+ const list = Array.isArray(parsed) ? parsed : (parsed.hooks || []);
226
+ for (const h of list) {
227
+ const hId = typeof h === "string" ? h : (h.id || h.name);
228
+ if (hId && !seenHooks.has(hId)) {
229
+ seenHooks.add(hId);
230
+ hooks.push({ id: hId, def: h, pluginId: plugin.id });
231
+ }
232
+ }
233
+ } catch {}
234
+ }
235
+ }
236
+
237
+ return { skills, mcpServers, rules, agents, hooks, conflicts };
238
+ }
239
+
240
+ /**
241
+ * Checks whether a directory is managed/owned by Agent Space Manager via .asm-owned.json
242
+ */
243
+ export function isAsmOwnedDirectory(dirPath) {
244
+ try {
245
+ return fs.existsSync(path.join(dirPath, ".asm-owned.json"));
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Materializes a single skill directory with real top-level files (especially SKILL.md)
253
+ * and child links for subfolders, bypassing Go os.ReadDir Windows junction issues.
254
+ */
255
+ export function materializeSkillDir(sourceDir, destDir, ownerId = "asm", createJunctionFn = null) {
256
+ try {
257
+ ensureDir(destDir);
258
+ const markerPath = path.join(destDir, ".asm-owned.json");
259
+ fs.writeFileSync(
260
+ markerPath,
261
+ JSON.stringify({ owner: ownerId, source: sourceDir, type: "skill", updatedAt: Date.now() }, null, 2),
262
+ "utf8"
263
+ );
264
+
265
+ const entries = fs.readdirSync(sourceDir, { withFileTypes: true });
266
+ for (const ent of entries) {
267
+ if (ent.name === ".asm-owned.json" || ent.name === ".git") continue;
268
+ const srcChild = path.join(sourceDir, ent.name);
269
+ const destChild = path.join(destDir, ent.name);
270
+ if (ent.isFile()) {
271
+ try {
272
+ fs.copyFileSync(srcChild, destChild);
273
+ } catch {}
274
+ } else if (ent.isDirectory()) {
275
+ if (createJunctionFn) {
276
+ createJunctionFn(srcChild, destChild);
277
+ } else {
278
+ try {
279
+ ensureDir(destChild);
280
+ } catch {}
281
+ }
282
+ }
283
+ }
284
+ return { success: true };
285
+ } catch (err) {
286
+ return { success: false, error: err.message };
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Materializes a plugin bundle into a real directory containing real top-level files,
292
+ * real skills directory with materialized skill subfolders, and child junctions for subfolders.
293
+ */
294
+ export function materializePluginBundle(sourceDir, destDir, ownerId = "asm", createJunctionFn = null) {
295
+ try {
296
+ ensureDir(destDir);
297
+ const markerPath = path.join(destDir, ".asm-owned.json");
298
+ fs.writeFileSync(
299
+ markerPath,
300
+ JSON.stringify({ owner: ownerId, source: sourceDir, type: "plugin", updatedAt: Date.now() }, null, 2),
301
+ "utf8"
302
+ );
303
+
304
+ const entries = fs.readdirSync(sourceDir, { withFileTypes: true });
305
+ for (const ent of entries) {
306
+ if (ent.name === ".asm-owned.json" || ent.name === ".git") continue;
307
+ const srcChild = path.join(sourceDir, ent.name);
308
+ const destChild = path.join(destDir, ent.name);
309
+
310
+ if (ent.isFile()) {
311
+ try {
312
+ fs.copyFileSync(srcChild, destChild);
313
+ } catch {}
314
+ } else if (ent.isDirectory()) {
315
+ if (ent.name === "skills") {
316
+ ensureDir(destChild);
317
+ try {
318
+ const subSkills = fs.readdirSync(srcChild, { withFileTypes: true });
319
+ for (const sub of subSkills) {
320
+ if (sub.isDirectory() || sub.isSymbolicLink()) {
321
+ const subSrc = path.join(srcChild, sub.name);
322
+ const subDest = path.join(destChild, sub.name);
323
+ materializeSkillDir(subSrc, subDest, ownerId, createJunctionFn);
324
+ }
325
+ }
326
+ } catch {}
327
+ } else if (ent.name === "rules" || ent.name === "agents") {
328
+ ensureDir(destChild);
329
+ try {
330
+ const subFiles = fs.readdirSync(srcChild, { withFileTypes: true });
331
+ for (const sf of subFiles) {
332
+ if (sf.isFile()) {
333
+ fs.copyFileSync(path.join(srcChild, sf.name), path.join(destChild, sf.name));
334
+ }
335
+ }
336
+ } catch {}
337
+ } else {
338
+ if (createJunctionFn) {
339
+ createJunctionFn(srcChild, destChild);
340
+ } else {
341
+ ensureDir(destChild);
342
+ }
343
+ }
344
+ }
345
+ }
346
+ return { success: true };
347
+ } catch (err) {
348
+ return { success: false, error: err.message };
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Syncs plugin bundles into primaryDir (e.g. ~/.gemini/config/plugins) using real-directory
354
+ * materialization on Windows with .asm-owned.json markers, while strictly preserving foreign symlinks and folders.
355
+ */
356
+ export function syncPluginBundles(
357
+ primaryDir,
358
+ activePluginMap,
359
+ prevLinks = [],
360
+ createJunctionFn = null,
361
+ removeJunctionFn = null,
362
+ allPlugins = [],
363
+ ownerId = "asm"
364
+ ) {
365
+ ensureDir(primaryDir);
366
+ const bundleLinks = [];
367
+ const results = [];
368
+ const prevLinksSet = new Set((prevLinks || []).map((p) => path.resolve(p)));
369
+
370
+ // 1. Prune stale owned junctions or ASM-owned directories
371
+ try {
372
+ const existingEntries = fs.readdirSync(primaryDir);
373
+ for (const entryName of existingEntries) {
374
+ const entryPath = path.join(primaryDir, entryName);
375
+ const resolvedEntry = path.resolve(entryPath);
376
+ try {
377
+ const stat = fs.lstatSync(entryPath);
378
+ if (stat.isSymbolicLink()) {
379
+ let currentTarget = "";
380
+ try {
381
+ currentTarget = fs.readlinkSync(entryPath);
382
+ } catch {}
383
+
384
+ const isOwned = prevLinksSet.has(resolvedEntry) || isTargetInsideHub(currentTarget, allPlugins);
385
+ if (!isOwned) continue; // Foreign user symlink — preserve!
386
+
387
+ const activeTarget = activePluginMap.get(entryName);
388
+ const targetMatches =
389
+ activeTarget && currentTarget && path.resolve(currentTarget) === path.resolve(activeTarget);
390
+ if (!targetMatches) {
391
+ if (removeJunctionFn) removeJunctionFn(entryPath);
392
+ else {
393
+ try { fs.unlinkSync(entryPath); } catch {}
394
+ }
395
+ results.push({ plugin: entryName, action: "unlinked", success: true });
396
+ }
397
+ } else if (stat.isDirectory()) {
398
+ const isAsmDir = isAsmOwnedDirectory(entryPath) || prevLinksSet.has(resolvedEntry) || isTargetInsideHub(entryPath, allPlugins, resolveHubRoot());
399
+ const hasPluginJson = fs.existsSync(path.join(entryPath, "plugin.json"));
400
+ if ((isAsmDir || !hasPluginJson) && !activePluginMap.has(entryName)) {
401
+ try { fs.rmSync(entryPath, { recursive: true, force: true }); } catch {}
402
+ results.push({ plugin: entryName, action: "unlinked", success: true });
403
+ }
404
+ }
405
+ } catch {}
406
+ }
407
+ } catch {}
408
+
409
+ // 2. Materialize or update active plugin bundles
410
+ for (const [pluginId, sourcePath] of activePluginMap.entries()) {
411
+ const linkPath = path.join(primaryDir, pluginId);
412
+ let isSym = false;
413
+ try {
414
+ const st = fs.lstatSync(linkPath);
415
+ isSym = st.isSymbolicLink();
416
+ } catch {}
417
+
418
+ if (isSym) {
419
+ if (removeJunctionFn) removeJunctionFn(linkPath);
420
+ else {
421
+ try { fs.unlinkSync(linkPath); } catch {}
422
+ }
423
+ }
424
+
425
+ const res = materializePluginBundle(sourcePath, linkPath, ownerId, createJunctionFn);
426
+ if (res.success) {
427
+ bundleLinks.push(path.resolve(linkPath));
428
+ }
429
+ results.push({ plugin: pluginId, action: "linked", ...res });
430
+ }
431
+
432
+ return { bundleLinks, results };
433
+ }
434
+
435
+ /**
436
+ * Syncs individual skill directories (<skillsDir>/<skill-name> -> <plugin>/skills/<skill-name>)
437
+ * while preserving user-created skills and non-owned symlinks.
438
+ * Materializes real directories with .asm-owned.json so Go os.ReadDir never skips skills on Windows.
439
+ */
440
+ export function syncFlattenedSkills(
441
+ skills,
442
+ skillsDir,
443
+ prevLinks = [],
444
+ createJunctionFn = null,
445
+ removeJunctionFn = null,
446
+ allPlugins = [],
447
+ ownerId = "asm"
448
+ ) {
449
+ const nextLinks = [];
450
+ const results = [];
451
+ if (!skillsDir) return { nextLinks, results };
452
+
453
+ try {
454
+ const dirStat = fs.lstatSync(skillsDir);
455
+ if (dirStat.isSymbolicLink()) {
456
+ if (removeJunctionFn) removeJunctionFn(skillsDir);
457
+ else {
458
+ try { fs.unlinkSync(skillsDir); } catch {}
459
+ }
460
+ }
461
+ } catch {}
462
+
463
+ ensureDir(skillsDir);
464
+
465
+ const desiredMap = new Map();
466
+ for (const s of skills) {
467
+ desiredMap.set(s.name, s.sourceDir);
468
+ }
469
+
470
+ const prevSet = new Set((prevLinks || []).map((p) => path.resolve(p)));
471
+
472
+ // 1. Prune previously owned links or ASM-owned directories in skillsDir that are no longer desired
473
+ try {
474
+ const entries = fs.readdirSync(skillsDir);
475
+ for (const entryName of entries) {
476
+ const entryPath = path.join(skillsDir, entryName);
477
+ const resolvedEntry = path.resolve(entryPath);
478
+ try {
479
+ const stat = fs.lstatSync(entryPath);
480
+ if (stat.isSymbolicLink()) {
481
+ let currentTarget = "";
482
+ try {
483
+ currentTarget = fs.readlinkSync(entryPath);
484
+ } catch {}
485
+ const isOwned = prevSet.has(resolvedEntry) || isTargetInsideHub(currentTarget, allPlugins);
486
+ if (!isOwned) continue; // Foreign user symlink — never touch!
487
+
488
+ const desiredTarget = desiredMap.get(entryName);
489
+ const matchesDesired =
490
+ desiredTarget && currentTarget && path.resolve(currentTarget) === path.resolve(desiredTarget);
491
+ if (!matchesDesired) {
492
+ if (removeJunctionFn) removeJunctionFn(entryPath);
493
+ else {
494
+ try { fs.unlinkSync(entryPath); } catch {}
495
+ }
496
+ results.push({ skill: entryName, action: "unlinked", success: true });
497
+ }
498
+ } else if (stat.isDirectory()) {
499
+ const isAsmDir = isAsmOwnedDirectory(entryPath) || prevSet.has(resolvedEntry);
500
+ if (isAsmDir && !desiredMap.has(entryName)) {
501
+ fs.rmSync(entryPath, { recursive: true, force: true });
502
+ results.push({ skill: entryName, action: "unlinked", success: true });
503
+ }
504
+ }
505
+ } catch {}
506
+ }
507
+ } catch {}
508
+
509
+ // Also clean any prevLinks that lived in a previous skillsDir if configPath changed
510
+ for (const oldLink of prevLinks || []) {
511
+ if (path.dirname(path.resolve(oldLink)) !== path.resolve(skillsDir)) {
512
+ if (removeJunctionFn) removeJunctionFn(oldLink);
513
+ else {
514
+ try {
515
+ if (fs.existsSync(oldLink)) {
516
+ const st = fs.lstatSync(oldLink);
517
+ if (st.isSymbolicLink()) fs.unlinkSync(oldLink);
518
+ else if (isAsmOwnedDirectory(oldLink)) fs.rmSync(oldLink, { recursive: true, force: true });
519
+ }
520
+ } catch {}
521
+ }
522
+ }
523
+ }
524
+
525
+ // 2. Create or verify desired skill directories
526
+ for (const [skillName, sourceDir] of desiredMap.entries()) {
527
+ const linkPath = path.join(skillsDir, skillName);
528
+ let isSym = false;
529
+ try {
530
+ const st = fs.lstatSync(linkPath);
531
+ isSym = st.isSymbolicLink();
532
+ } catch {}
533
+
534
+ if (isSym) {
535
+ if (removeJunctionFn) removeJunctionFn(linkPath);
536
+ else {
537
+ try { fs.unlinkSync(linkPath); } catch {}
538
+ }
539
+ }
540
+
541
+ const res = materializeSkillDir(sourceDir, linkPath, ownerId, createJunctionFn);
542
+ if (res.success) {
543
+ nextLinks.push(path.resolve(linkPath));
544
+ }
545
+ results.push({ skill: skillName, action: "linked", ...res });
546
+ }
547
+
548
+ return { nextLinks, results };
549
+ }
550
+
551
+ /**
552
+ * Generates `/` quick-action slash command files (in ~/.config/opencode/commands, ~/.claude/commands,
553
+ * ~/.cursor/commands, ~/.codeium/windsurf/global_workflows, Code/User/prompts, ~/.gemini/commands, etc.)
554
+ * so every enabled skill is immediately available in the agent's `/` autocomplete menu.
555
+ */
556
+ export function syncSkillSlashCommands(skills = [], commandsSpec = null, prevOwnedFiles = []) {
557
+ if (!commandsSpec) return { nextFiles: [] };
558
+ const dir = typeof commandsSpec === "string" ? commandsSpec : commandsSpec.dir;
559
+ const suffix = typeof commandsSpec === "object" && commandsSpec.suffix ? commandsSpec.suffix : ".md";
560
+ const format = typeof commandsSpec === "object" && commandsSpec.format ? commandsSpec.format : "markdown-command";
561
+ if (!dir) return { nextFiles: [] };
562
+
563
+ const prevSet = new Set((prevOwnedFiles || []).map((f) => path.resolve(f)));
564
+ const nextFiles = [];
565
+
566
+ if ((!skills || skills.length === 0) && prevSet.size === 0) {
567
+ return { nextFiles: [] };
568
+ }
569
+
570
+ ensureDir(dir);
571
+
572
+ const desiredMap = new Map();
573
+ for (const s of skills || []) {
574
+ const destName = `${s.name}${suffix}`;
575
+ const destPath = path.resolve(path.join(dir, destName));
576
+ desiredMap.set(destPath, s);
577
+ }
578
+
579
+ // Prune previously owned command files that are no longer enabled
580
+ for (const oldFile of prevSet) {
581
+ if (!desiredMap.has(oldFile)) {
582
+ try {
583
+ if (fs.existsSync(oldFile)) fs.unlinkSync(oldFile);
584
+ } catch {}
585
+ }
586
+ }
587
+
588
+ // Write or update active slash command files
589
+ for (const [destResolved, skill] of desiredMap.entries()) {
590
+ if (fs.existsSync(destResolved) && !prevSet.has(destResolved)) {
591
+ // Check if an existing file was previously generated by us via marker or skip user-owned file
592
+ try {
593
+ const existingContent = fs.readFileSync(destResolved, "utf8");
594
+ if (!existingContent.includes("SKILL.md")) {
595
+ continue; // Respect pre-existing user command file
596
+ }
597
+ } catch {
598
+ continue;
599
+ }
600
+ }
601
+
602
+ const skillMdPath = path.join(skill.sourceDir, "SKILL.md");
603
+ let desc = `Execute the ${skill.name} skill`;
604
+ if (fs.existsSync(skillMdPath)) {
605
+ try {
606
+ const raw = fs.readFileSync(skillMdPath, "utf8");
607
+ const { frontmatter } = parseMarkdownFrontmatter(raw);
608
+ if (frontmatter.description) {
609
+ desc = frontmatter.description.replace(/\r?\n/g, " ").trim();
610
+ }
611
+ } catch {}
612
+ }
613
+
614
+ const posixSkillFile = skillMdPath.replace(/\\/g, "/");
615
+ let content = "";
616
+ if (format === "gemini-toml-command") {
617
+ content = [
618
+ `description = ${JSON.stringify(desc)}`,
619
+ `prompt = ${JSON.stringify(`Read and follow the skill instructions in ${posixSkillFile} to complete the user's request.\n\n{{args}}`)}`,
620
+ "",
621
+ ].join("\n");
622
+ } else {
623
+ content = [
624
+ "---",
625
+ `description: ${JSON.stringify(desc)}`,
626
+ "---",
627
+ "",
628
+ `Read and follow the skill instructions in \`${posixSkillFile}\` to complete the user's request.`,
629
+ "",
630
+ "$ARGUMENTS",
631
+ "",
632
+ ].join("\n");
633
+ }
634
+
635
+ try {
636
+ let needsWrite = true;
637
+ if (fs.existsSync(destResolved)) {
638
+ try {
639
+ if (fs.readFileSync(destResolved, "utf8") === content) {
640
+ needsWrite = false;
641
+ }
642
+ } catch {}
643
+ }
644
+ if (needsWrite) {
645
+ fs.writeFileSync(destResolved, content, "utf8");
646
+ }
647
+ nextFiles.push(destResolved);
648
+ } catch {}
649
+ }
650
+
651
+ return { nextFiles };
652
+ }
653
+
654
+ /**
655
+ * Transforms standard MCP server definition to OpenCode's `opencode.json` schema.
656
+ * Supports remote servers (`url`, `serverUrl`, `httpUrl`) and local command servers.
657
+ * Returns `null` if neither a remote URL nor a command is defined.
658
+ */
659
+ export function toOpenCodeMcpEntry(def) {
660
+ const remoteUrl = def.url || def.serverUrl || def.httpUrl;
661
+ if (remoteUrl) {
662
+ return {
663
+ type: "remote",
664
+ url: remoteUrl,
665
+ enabled: true,
666
+ };
667
+ }
668
+ const cmd = def.command ? [def.command, ...(Array.isArray(def.args) ? def.args : [])] : [];
669
+ if (cmd.length === 0) {
670
+ return null;
671
+ }
672
+ const entry = {
673
+ type: "local",
674
+ command: cmd,
675
+ enabled: true,
676
+ };
677
+ if (def.env && Object.keys(def.env).length > 0) {
678
+ entry.environment = { ...def.env };
679
+ }
680
+ return entry;
681
+ }
682
+
683
+ /**
684
+ * Merges managed MCP servers into a native JSON file (e.g. ~/.claude.json, ~/.cursor/mcp.json,
685
+ * Code/User/mcp.json, opencode.json) while preserving all user-defined keys and servers.
686
+ */
687
+ export function syncJsonMcpServers(mcpSpec, mcpServers, prevOwnedKeys = []) {
688
+ if (!mcpSpec || !mcpSpec.file) return { ownedKeys: [] };
689
+ const filePath = mcpSpec.file;
690
+ const rootKey = mcpSpec.key || "mcpServers";
691
+ const isOpenCode = mcpSpec.format === "opencode-json";
692
+
693
+ const desiredNames = Object.keys(mcpServers || {});
694
+ if (desiredNames.length === 0 && (!prevOwnedKeys || prevOwnedKeys.length === 0) && !fs.existsSync(filePath)) {
695
+ return { ownedKeys: [] };
696
+ }
697
+
698
+ ensureDir(path.dirname(filePath));
699
+ ensureBackupOnce(filePath);
700
+
701
+ let doc = {};
702
+ if (fs.existsSync(filePath)) {
703
+ try {
704
+ doc = JSON.parse(fs.readFileSync(filePath, "utf8"));
705
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) doc = {};
706
+ } catch {
707
+ doc = {};
708
+ }
709
+ }
710
+
711
+ if (!doc[rootKey] || typeof doc[rootKey] !== "object" || Array.isArray(doc[rootKey])) {
712
+ doc[rootKey] = {};
713
+ }
714
+
715
+ const container = doc[rootKey];
716
+ const prevSet = new Set(prevOwnedKeys || []);
717
+
718
+ // Remove previously owned keys that are no longer active
719
+ for (const oldKey of prevSet) {
720
+ if (!(oldKey in mcpServers)) {
721
+ delete container[oldKey];
722
+ }
723
+ }
724
+
725
+ // When unlinking all, ensure any server pointing to AI Agent Space or hub is cleaned
726
+ if (desiredNames.length === 0) {
727
+ for (const [k, v] of Object.entries(container)) {
728
+ const vStr = JSON.stringify(v || "");
729
+ if (vStr.includes("AI Agent Space") || vStr.includes("agent-space-manager")) {
730
+ delete container[k];
731
+ }
732
+ }
733
+ }
734
+
735
+ const nextOwned = [];
736
+ for (const [srvName, srvDef] of Object.entries(mcpServers)) {
737
+ // Only overwrite if key doesn't exist OR was already owned by us
738
+ if (!(srvName in container) || prevSet.has(srvName)) {
739
+ if (isOpenCode) {
740
+ const ocEntry = toOpenCodeMcpEntry(srvDef);
741
+ if (!ocEntry) {
742
+ delete container[srvName];
743
+ continue;
744
+ }
745
+ container[srvName] = ocEntry;
746
+ } else {
747
+ const normalizedDef = { ...srvDef };
748
+ if (!normalizedDef.url && (normalizedDef.serverUrl || normalizedDef.httpUrl)) {
749
+ normalizedDef.url = normalizedDef.serverUrl || normalizedDef.httpUrl;
750
+ }
751
+ container[srvName] = normalizedDef;
752
+ }
753
+ nextOwned.push(srvName);
754
+ }
755
+ }
756
+
757
+ fs.writeFileSync(filePath, JSON.stringify(doc, null, 2), "utf8");
758
+ return { ownedKeys: nextOwned };
759
+ }
760
+
761
+ /**
762
+ * Formats a value as a TOML literal.
763
+ */
764
+ function toTomlValue(val) {
765
+ if (typeof val === "string") return JSON.stringify(val);
766
+ if (typeof val === "number" || typeof val === "boolean") return String(val);
767
+ if (Array.isArray(val)) return `[${val.map(toTomlValue).join(", ")}]`;
768
+ return JSON.stringify(String(val));
769
+ }
770
+
771
+ /**
772
+ * Syncs managed `[mcp_servers.<name>]` sections into Codex's `config.toml` between marker comments.
773
+ */
774
+ export function syncTomlMcpServers(filePath, mcpServers, hadBlockBefore = false) {
775
+ if (!filePath) return { hasBlock: false };
776
+ const entries = Object.entries(mcpServers || {});
777
+ if (entries.length === 0 && !hadBlockBefore && !fs.existsSync(filePath)) {
778
+ return { hasBlock: false };
779
+ }
780
+
781
+ ensureDir(path.dirname(filePath));
782
+ ensureBackupOnce(filePath);
783
+
784
+ let existing = "";
785
+ if (fs.existsSync(filePath)) {
786
+ try {
787
+ existing = fs.readFileSync(filePath, "utf8");
788
+ } catch {}
789
+ }
790
+
791
+ const blockRegex = new RegExp(
792
+ `${escapeRegExp(BLOCK_START_TOML)}[\\s\\S]*?${escapeRegExp(BLOCK_END_TOML)}\\r?\\n?`,
793
+ "g"
794
+ );
795
+ let cleaned = existing.replace(blockRegex, "").trimEnd();
796
+
797
+ if (entries.length === 0) {
798
+ if (fs.existsSync(filePath)) {
799
+ fs.writeFileSync(filePath, cleaned ? `${cleaned}\n` : "", "utf8");
800
+ }
801
+ return { hasBlock: false };
802
+ }
803
+
804
+ const lines = [BLOCK_START_TOML];
805
+ for (const [rawName, def] of entries) {
806
+ const safeKey = /^[A-Za-z0-9_-]+$/.test(rawName) ? rawName : JSON.stringify(rawName);
807
+ lines.push(`[mcp_servers.${safeKey}]`);
808
+ if (def.command) lines.push(`command = ${toTomlValue(def.command)}`);
809
+ if (Array.isArray(def.args)) lines.push(`args = ${toTomlValue(def.args)}`);
810
+ const remoteUrl = def.url || def.serverUrl || def.httpUrl;
811
+ if (remoteUrl) lines.push(`url = ${toTomlValue(remoteUrl)}`);
812
+ if (def.env && typeof def.env === "object" && Object.keys(def.env).length > 0) {
813
+ lines.push(`[mcp_servers.${safeKey}.env]`);
814
+ for (const [ek, ev] of Object.entries(def.env)) {
815
+ const safeEnvKey = /^[A-Za-z0-9_-]+$/.test(ek) ? ek : JSON.stringify(ek);
816
+ lines.push(`${safeEnvKey} = ${toTomlValue(ev)}`);
817
+ }
818
+ }
819
+ lines.push("");
820
+ }
821
+ lines.push(BLOCK_END_TOML);
822
+
823
+ const nextContent = (cleaned ? `${cleaned}\n\n` : "") + lines.join("\n") + "\n";
824
+ fs.writeFileSync(filePath, nextContent, "utf8");
825
+ return { hasBlock: true };
826
+ }
827
+
828
+ /**
829
+ * Syncs a managed Markdown rules block into CLAUDE.md / AGENTS.md / GEMINI.md / global_rules.md.
830
+ */
831
+ export function syncMarkdownRulesBlock(rulesSpec, rules, hadBlockBefore = false) {
832
+ if (!rulesSpec || !rulesSpec.file) return { hasBlock: false };
833
+ const filePath = rulesSpec.file;
834
+
835
+ if ((!rules || rules.length === 0) && !hadBlockBefore && !fs.existsSync(filePath)) {
836
+ return { hasBlock: false };
837
+ }
838
+
839
+ ensureDir(path.dirname(filePath));
840
+ ensureBackupOnce(filePath);
841
+
842
+ let existing = "";
843
+ if (fs.existsSync(filePath)) {
844
+ try {
845
+ existing = fs.readFileSync(filePath, "utf8");
846
+ } catch {}
847
+ }
848
+
849
+ const blockRegex = new RegExp(
850
+ `${escapeRegExp(BLOCK_START_MD)}[\\s\\S]*?${escapeRegExp(BLOCK_END_MD)}\\r?\\n?`,
851
+ "g"
852
+ );
853
+ const cleaned = existing.replace(blockRegex, "").trimEnd();
854
+
855
+ if (!rules || rules.length === 0) {
856
+ if (fs.existsSync(filePath)) {
857
+ fs.writeFileSync(filePath, cleaned ? `${cleaned}\n` : "", "utf8");
858
+ }
859
+ return { hasBlock: false };
860
+ }
861
+
862
+ const lines = [BLOCK_START_MD];
863
+ if (rulesSpec.format === "import-block") {
864
+ for (const r of rules) {
865
+ const posixPath = r.sourceFile.replace(/\\/g, "/");
866
+ lines.push(`@${posixPath}`);
867
+ }
868
+ } else {
869
+ for (const r of rules) {
870
+ try {
871
+ const body = fs.readFileSync(r.sourceFile, "utf8").trim();
872
+ lines.push(`<!-- rule: ${r.name} -->\n${body}`);
873
+ } catch {}
874
+ }
875
+ }
876
+ lines.push(BLOCK_END_MD);
877
+
878
+ const nextContent = (cleaned ? `${cleaned}\n\n` : "") + lines.join("\n\n") + "\n";
879
+ fs.writeFileSync(filePath, nextContent, "utf8");
880
+ return { hasBlock: true };
881
+ }
882
+
883
+ /**
884
+ * Copies owned single-file components (subagents or directory-based rules) and removes stale owned copies.
885
+ * Normalizes frontmatter when `targetDirSpec.format === "opencode-agent"` so OpenCode's Effect Schema never skips subagents.
886
+ */
887
+ export function syncOwnedFiles(items, targetDirSpec, prevOwnedFiles = []) {
888
+ if (!targetDirSpec) return { nextFiles: [] };
889
+ const dir = typeof targetDirSpec === "string" ? targetDirSpec : targetDirSpec.dir;
890
+ const suffix = typeof targetDirSpec === "object" && targetDirSpec.suffix ? targetDirSpec.suffix : ".md";
891
+ const format = typeof targetDirSpec === "object" && targetDirSpec.format ? targetDirSpec.format : "raw";
892
+ if (!dir) return { nextFiles: [] };
893
+
894
+ const prevSet = new Set((prevOwnedFiles || []).map((f) => path.resolve(f)));
895
+ const nextFiles = [];
896
+
897
+ if ((!items || items.length === 0) && prevSet.size === 0) {
898
+ return { nextFiles: [] };
899
+ }
900
+
901
+ ensureDir(dir);
902
+
903
+ const desiredPaths = new Map();
904
+ for (const item of items || []) {
905
+ const baseNoExt = item.name.replace(/\.md$/i, "");
906
+ const destName = `${baseNoExt}${suffix}`;
907
+ const destPath = path.join(dir, destName);
908
+ desiredPaths.set(path.resolve(destPath), item.sourceFile);
909
+ }
910
+
911
+ // Delete previously owned files that are no longer desired
912
+ for (const oldFile of prevSet) {
913
+ if (!desiredPaths.has(oldFile)) {
914
+ try {
915
+ if (fs.existsSync(oldFile)) fs.unlinkSync(oldFile);
916
+ } catch {}
917
+ }
918
+ }
919
+
920
+ // Copy active files (unless a non-owned user file already exists at that path)
921
+ for (const [destResolved, srcFile] of desiredPaths.entries()) {
922
+ if (fs.existsSync(destResolved) && !prevSet.has(destResolved)) {
923
+ continue; // Respect pre-existing user file
924
+ }
925
+ try {
926
+ if (format === "opencode-agent") {
927
+ const raw = fs.readFileSync(srcFile, "utf8");
928
+ const { frontmatter, body } = parseMarkdownFrontmatter(raw);
929
+ const desc = (frontmatter.description || `Subagent ${path.basename(destResolved, suffix)}`)
930
+ .replace(/\r?\n/g, " ")
931
+ .trim();
932
+ const formatted = [
933
+ "---",
934
+ `description: ${JSON.stringify(desc)}`,
935
+ "mode: subagent",
936
+ "---",
937
+ "",
938
+ body,
939
+ "",
940
+ ].join("\n");
941
+ fs.writeFileSync(destResolved, formatted, "utf8");
942
+ } else if (format === "antigravity-rule") {
943
+ const raw = fs.readFileSync(srcFile, "utf8");
944
+ const { frontmatter, body } = parseMarkdownFrontmatter(raw);
945
+ const desc = (frontmatter.description || `Rule ${path.basename(destResolved, suffix)}`)
946
+ .replace(/\r?\n/g, " ")
947
+ .trim();
948
+ const trigger = frontmatter.trigger || "always_on";
949
+ const formatted = [
950
+ "---",
951
+ `description: ${JSON.stringify(desc)}`,
952
+ `trigger: ${trigger}`,
953
+ "---",
954
+ "",
955
+ body,
956
+ "",
957
+ ].join("\n");
958
+ fs.writeFileSync(destResolved, formatted, "utf8");
959
+ } else {
960
+ fs.copyFileSync(srcFile, destResolved);
961
+ }
962
+ nextFiles.push(destResolved);
963
+ } catch {}
964
+ }
965
+
966
+ return { nextFiles };
967
+ }
968
+
969
+ /**
970
+ * Adds relative paths to `<repo>/.git/info/exclude` so synced workspace links/files are never committed.
971
+ */
972
+ export function ensureGitInfoExclude(repoPath, relPaths = []) {
973
+ if (!repoPath || !relPaths || relPaths.length === 0) return;
974
+ const excludeFile = path.join(repoPath, ".git", "info", "exclude");
975
+ if (!fs.existsSync(path.dirname(excludeFile))) return;
976
+ try {
977
+ let content = fs.existsSync(excludeFile) ? fs.readFileSync(excludeFile, "utf8") : "";
978
+ let changed = false;
979
+ for (const rel of relPaths) {
980
+ const norm = rel.replace(/\\/g, "/");
981
+ if (!content.split(/\r?\n/).some((line) => line.trim() === norm)) {
982
+ if (content && !content.endsWith("\n")) content += "\n";
983
+ content += `${norm}\n`;
984
+ changed = true;
985
+ }
986
+ }
987
+ if (changed) {
988
+ fs.writeFileSync(excludeFile, content, "utf8");
989
+ }
990
+ } catch {}
991
+ }
992
+
993
+ function escapeRegExp(str) {
994
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
995
+ }
996
+
997
+ /**
998
+ * Syncs managed hooks into native hooks.json while preserving user-defined hooks.
999
+ */
1000
+ export function syncJsonHooks(hooksSpec, hooksList = [], prevOwnedKeys = []) {
1001
+ if (!hooksSpec || !hooksSpec.file) return { ownedKeys: [] };
1002
+ const filePath = hooksSpec.file;
1003
+ const desiredKeys = new Set(hooksList.map((h) => (typeof h === "string" ? h : h.id || h.name)));
1004
+ if (desiredKeys.size === 0 && (!prevOwnedKeys || prevOwnedKeys.length === 0) && !fs.existsSync(filePath)) {
1005
+ return { ownedKeys: [] };
1006
+ }
1007
+
1008
+ ensureDir(path.dirname(filePath));
1009
+ ensureBackupOnce(filePath);
1010
+
1011
+ let doc = { hooks: {} };
1012
+ if (fs.existsSync(filePath)) {
1013
+ try {
1014
+ doc = JSON.parse(fs.readFileSync(filePath, "utf8"));
1015
+ if (!doc || typeof doc !== "object") doc = { hooks: {} };
1016
+ } catch {
1017
+ doc = { hooks: {} };
1018
+ }
1019
+ }
1020
+
1021
+ if (Array.isArray(doc)) {
1022
+ doc = { hooks: doc };
1023
+ } else if (!doc.hooks) {
1024
+ doc.hooks = {};
1025
+ }
1026
+
1027
+ const prevSet = new Set(prevOwnedKeys || []);
1028
+ if (Array.isArray(doc.hooks)) {
1029
+ doc.hooks = doc.hooks.filter((h) => {
1030
+ const id = typeof h === "string" ? h : h.id || h.name;
1031
+ return !prevSet.has(id) || desiredKeys.has(id);
1032
+ });
1033
+ for (const h of hooksList) {
1034
+ const id = typeof h === "string" ? h : h.id || h.name;
1035
+ if (!doc.hooks.some((ex) => (typeof ex === "string" ? ex : ex.id || ex.name) === id)) {
1036
+ doc.hooks.push(h.def || h);
1037
+ }
1038
+ }
1039
+ } else {
1040
+ for (const oldKey of prevSet) {
1041
+ if (!desiredKeys.has(oldKey)) {
1042
+ delete doc.hooks[oldKey];
1043
+ }
1044
+ }
1045
+ for (const h of hooksList) {
1046
+ const id = typeof h === "string" ? h : h.id || h.name;
1047
+ doc.hooks[id] = h.def || h;
1048
+ }
1049
+ }
1050
+
1051
+ fs.writeFileSync(filePath, JSON.stringify(doc, null, 2), "utf8");
1052
+ return { ownedKeys: Array.from(desiredKeys) };
1053
+ }
1054
+
1055
+ /**
1056
+ * Generates and maintains live cross-agent communication files in D:\Software\AI Agent Space
1057
+ * (or effective hubRoot):
1058
+ * 1. agent-space-bridge.json: runtime status of all connected agents & projects
1059
+ * 2. shared/agent-connectors.json: cross-agent messaging, handoff inboxes, and discovery registry
1060
+ * 3. skills.json, plugins.json, mcp_config.json: consolidated catalogs
1061
+ */
1062
+ export function writeHubCommunicationFiles(hubRoot, hubConfig, allPlugins = [], syncSummary = null) {
1063
+ if (!hubRoot) return false;
1064
+ try {
1065
+ ensureDir(hubRoot);
1066
+ } catch {
1067
+ return false;
1068
+ }
1069
+
1070
+ const ides = Array.isArray(hubConfig?.ides) ? hubConfig.ides : [];
1071
+ const projects = Array.isArray(hubConfig?.projects) ? hubConfig.projects : [];
1072
+
1073
+ const activeAgents = ides
1074
+ .filter((i) => i.enabled !== false)
1075
+ .map((ide) => {
1076
+ const effectivePaths = resolveEffectiveAgentPaths(ide);
1077
+ return {
1078
+ id: ide.id,
1079
+ name: ide.name,
1080
+ agentType: ide.agentType,
1081
+ exePath: ide.exePath || null,
1082
+ configPath: ide.configPath,
1083
+ componentPaths: ide.componentPaths || {},
1084
+ effectivePaths,
1085
+ status: "connected",
1086
+ };
1087
+ });
1088
+
1089
+ const activeProjects = projects.map((proj) => {
1090
+ const parentIde = ides.find((i) => i.id === proj.ideId) || ides[0] || null;
1091
+ const effectivePaths = resolveEffectiveProjectPaths(proj, parentIde);
1092
+ return {
1093
+ id: proj.id,
1094
+ name: proj.name,
1095
+ repoPath: proj.repoPath,
1096
+ ideId: proj.ideId || null,
1097
+ componentPaths: proj.componentPaths || {},
1098
+ effectivePaths,
1099
+ status: "connected",
1100
+ };
1101
+ });
1102
+
1103
+ const allSkills = [];
1104
+ const seenSkills = new Set();
1105
+ const allMcp = {};
1106
+ const allRules = [];
1107
+ const allAgents = [];
1108
+ const allHooks = [];
1109
+
1110
+ for (const p of allPlugins) {
1111
+ for (const s of p.skills || []) {
1112
+ if (!seenSkills.has(s)) {
1113
+ seenSkills.add(s);
1114
+ allSkills.push({ name: s, pluginId: p.id, path: path.join(p.path, p.isRootSkills ? "" : "skills", s) });
1115
+ }
1116
+ }
1117
+ const mcpFile = path.join(p.path, "mcp_config.json");
1118
+ if (p.hasMcp && fs.existsSync(mcpFile)) {
1119
+ try {
1120
+ const parsed = JSON.parse(fs.readFileSync(mcpFile, "utf8"));
1121
+ const srvs = parsed.mcpServers || parsed.servers || {};
1122
+ Object.assign(allMcp, srvs);
1123
+ } catch {}
1124
+ }
1125
+ for (const r of p.rules || []) {
1126
+ allRules.push({ name: r, pluginId: p.id });
1127
+ }
1128
+ for (const a of p.agents || []) {
1129
+ allAgents.push({ name: a, pluginId: p.id });
1130
+ }
1131
+ for (const h of p.hooks || []) {
1132
+ allHooks.push({ id: typeof h === "string" ? h : h.id, pluginId: p.id });
1133
+ }
1134
+ }
1135
+
1136
+ // 1. <hubRoot>/agent-space-bridge.json
1137
+ const bridgePayload = {
1138
+ version: "1.0.0",
1139
+ bridgeProtocol: "magpie-asm-v1",
1140
+ updatedAt: new Date().toISOString(),
1141
+ hubRoot,
1142
+ componentCounts: {
1143
+ plugins: allPlugins.length,
1144
+ skills: allSkills.length,
1145
+ mcpServers: Object.keys(allMcp).length,
1146
+ rules: allRules.length,
1147
+ agents: allAgents.length,
1148
+ hooks: allHooks.length,
1149
+ },
1150
+ activeAgents,
1151
+ activeProjects,
1152
+ smartMiddleware: hubConfig?.smartMiddleware || { enabled: true, maxTools: 96 },
1153
+ syncSummary: syncSummary || null,
1154
+ };
1155
+ try {
1156
+ fs.writeFileSync(path.join(hubRoot, "agent-space-bridge.json"), JSON.stringify(bridgePayload, null, 2), "utf8");
1157
+ } catch {}
1158
+
1159
+ // 2. <hubRoot>/shared/agent-connectors.json
1160
+ const sharedDir = path.join(hubRoot, "shared");
1161
+ ensureDir(sharedDir);
1162
+ const handoffDir = path.join(sharedDir, "handoff");
1163
+ ensureDir(handoffDir);
1164
+
1165
+ const connectors = {};
1166
+ for (const a of activeAgents) {
1167
+ const aHandoff = path.join(handoffDir, a.id);
1168
+ ensureDir(aHandoff);
1169
+ connectors[a.id] = {
1170
+ name: a.name,
1171
+ agentType: a.agentType,
1172
+ cliCommand: a.exePath || a.agentType,
1173
+ configPath: a.configPath,
1174
+ skillsDirectory: a.effectivePaths?.skills || a.effectivePaths?.bundle || null,
1175
+ mcpConfigFile: a.effectivePaths?.mcp?.file || null,
1176
+ rulesFile: a.effectivePaths?.rules?.file || a.effectivePaths?.rulesDir?.dir || null,
1177
+ handoffInbox: aHandoff,
1178
+ capabilities: a.effectivePaths?.capabilities || {},
1179
+ };
1180
+ }
1181
+
1182
+ try {
1183
+ fs.writeFileSync(
1184
+ path.join(sharedDir, "agent-connectors.json"),
1185
+ JSON.stringify(
1186
+ {
1187
+ version: "1.0.0",
1188
+ updatedAt: new Date().toISOString(),
1189
+ hubRoot,
1190
+ handoffRoot: handoffDir,
1191
+ connectors,
1192
+ },
1193
+ null,
1194
+ 2
1195
+ ),
1196
+ "utf8"
1197
+ );
1198
+ } catch {}
1199
+
1200
+ // 3. Consolidated root manifests
1201
+ try {
1202
+ fs.writeFileSync(path.join(hubRoot, "skills.json"), JSON.stringify({ skills: allSkills }, null, 2), "utf8");
1203
+ fs.writeFileSync(
1204
+ path.join(hubRoot, "plugins.json"),
1205
+ JSON.stringify(
1206
+ {
1207
+ plugins: allPlugins.map((p) => ({
1208
+ id: p.id,
1209
+ name: p.name,
1210
+ version: p.version,
1211
+ description: p.description,
1212
+ skillsCount: p.skills?.length || 0,
1213
+ hasMcp: p.hasMcp,
1214
+ hasHooks: p.hasHooks,
1215
+ })),
1216
+ },
1217
+ null,
1218
+ 2
1219
+ ),
1220
+ "utf8"
1221
+ );
1222
+ if (Object.keys(allMcp).length > 0) {
1223
+ fs.writeFileSync(path.join(hubRoot, "mcp_config.json"), JSON.stringify({ mcpServers: allMcp }, null, 2), "utf8");
1224
+ }
1225
+ } catch {}
1226
+
1227
+ return true;
1228
+ }