@ctout-uk/agentsmith 0.0.0-stage → 0.1.0

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/dist/index.cjs ADDED
@@ -0,0 +1,2308 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ ALL_TARGETS: () => ALL_TARGETS,
24
+ AWESOME_COPILOT_REPO_URL: () => AWESOME_COPILOT_REPO_URL,
25
+ MASS_REMOVAL_THRESHOLD: () => MASS_REMOVAL_THRESHOLD,
26
+ SOURCE_NAME: () => SOURCE_NAME,
27
+ TARGET_TERMINOLOGY: () => TARGET_TERMINOLOGY,
28
+ USER_GENERAL_POSITIVE_SEGMENTS: () => USER_GENERAL_POSITIVE_SEGMENTS,
29
+ USER_TECH_SPECIFIC_SEGMENTS: () => USER_TECH_SPECIFIC_SEGMENTS,
30
+ VENDOR_PREFIXES: () => VENDOR_PREFIXES,
31
+ VERSION: () => VERSION,
32
+ assertPathWithin: () => assertPathWithin,
33
+ awesomeCopilotRoot: () => awesomeCopilotRoot,
34
+ cacheRoot: () => cacheRoot,
35
+ cataloguePath: () => cataloguePath,
36
+ centreAndPad: () => centreAndPad,
37
+ cleanDescription: () => cleanDescription,
38
+ computeAssetStatus: () => computeAssetStatus,
39
+ detectRepoStack: () => detectRepoStack,
40
+ detectTargets: () => detectTargets,
41
+ ensureAwesomeCopilotRepo: () => ensureAwesomeCopilotRepo,
42
+ filterCatalogueBySearch: () => filterCatalogueBySearch,
43
+ findSubscription: () => findSubscription,
44
+ formatAssetBadges: () => formatAssetBadges,
45
+ formatStatusLine: () => formatStatusLine,
46
+ getRecommendedAssetIds: () => getRecommendedAssetIds,
47
+ getTargetAdapter: () => getTargetAdapter,
48
+ getTargetDisplayPath: () => getTargetDisplayPath,
49
+ getTargetTypeLabel: () => getTargetTypeLabel,
50
+ getTargetTypePlural: () => getTargetTypePlural,
51
+ hashAssetPath: () => hashAssetPath,
52
+ hashDirectory: () => hashDirectory,
53
+ hashFile: () => hashFile,
54
+ hashString: () => hashString,
55
+ installAsset: () => installAsset,
56
+ isRepoRecommended: () => isRepoRecommended,
57
+ isUserRecommended: () => isUserRecommended,
58
+ isValidScope: () => isValidScope,
59
+ isValidTarget: () => isValidTarget,
60
+ legacyCacheRoot: () => legacyCacheRoot,
61
+ listAssetStatuses: () => listAssetStatuses,
62
+ loadCatalogue: () => loadCatalogue,
63
+ loadManifest: () => loadManifest,
64
+ loadSubscriptions: () => loadSubscriptions,
65
+ manifestPath: () => manifestPath,
66
+ normaliseTargetAssetType: () => normaliseTargetAssetType,
67
+ parseFrontmatter: () => parseFrontmatter,
68
+ promptSelectAssetsToInstall: () => promptSelectAssetsToInstall,
69
+ promptSelectAssetsToRemove: () => promptSelectAssetsToRemove,
70
+ promptSelectTarget: () => promptSelectTarget,
71
+ removeAsset: () => removeAsset,
72
+ removeSubscriptionRecord: () => removeSubscriptionRecord,
73
+ resolveTarget: () => resolveTarget,
74
+ saveSubscriptions: () => saveSubscriptions,
75
+ scanAwesomeCopilotRepo: () => scanAwesomeCopilotRepo,
76
+ serialiseFrontmatter: () => serialiseFrontmatter,
77
+ subscriptionsPath: () => subscriptionsPath,
78
+ syncAwesomeCopilot: () => syncAwesomeCopilot,
79
+ truncateAndPad: () => truncateAndPad,
80
+ updateSubscribedAssets: () => updateSubscribedAssets,
81
+ upsertSubscription: () => upsertSubscription,
82
+ validateSyncSafety: () => validateSyncSafety
83
+ });
84
+ module.exports = __toCommonJS(src_exports);
85
+
86
+ // src/utils/paths.ts
87
+ var import_node_os = require("os");
88
+ var import_node_path = require("path");
89
+ var import_node_fs = require("fs");
90
+ function cacheRoot() {
91
+ return process.env.AGENTSMITH_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".agentsmith");
92
+ }
93
+ function legacyCacheRoot() {
94
+ return process.env.AWESOME_COPILOT_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".awesome-copilot");
95
+ }
96
+ function awesomeCopilotRoot() {
97
+ return (0, import_node_path.join)(cacheRoot(), "sources", "awesome-copilot");
98
+ }
99
+ function cataloguePath() {
100
+ return (0, import_node_path.join)(cacheRoot(), "catalogue.json");
101
+ }
102
+ function manifestPath() {
103
+ return (0, import_node_path.join)(cacheRoot(), "manifest.json");
104
+ }
105
+ function subscriptionsPath() {
106
+ return (0, import_node_path.join)(cacheRoot(), "subscriptions.json");
107
+ }
108
+ function assertPathWithin(targetPath, baseDir, allowEqual = false) {
109
+ const resolvedTarget = (0, import_node_path.resolve)(targetPath);
110
+ const resolvedBase = (0, import_node_path.resolve)(baseDir);
111
+ const rel = (0, import_node_path.relative)(resolvedBase, resolvedTarget);
112
+ const isEqual = rel === "";
113
+ const isOutside = rel.startsWith("..") || (0, import_node_path.isAbsolute)(rel);
114
+ if (isOutside || isEqual && !allowEqual) {
115
+ throw new Error(
116
+ `Security: path '${resolvedTarget}' traverses outside authorised directory '${resolvedBase}'.`
117
+ );
118
+ }
119
+ if (!isEqual) {
120
+ const segments = rel.split(import_node_path.sep);
121
+ let current = resolvedBase;
122
+ for (const segment of segments) {
123
+ if (!segment || segment === ".") continue;
124
+ current = (0, import_node_path.join)(current, segment);
125
+ try {
126
+ const stat = (0, import_node_fs.lstatSync)(current);
127
+ if (stat.isSymbolicLink()) {
128
+ throw new Error(
129
+ `Security: path '${resolvedTarget}' traverses a symbolic link at '${current}'.`
130
+ );
131
+ }
132
+ } catch (err) {
133
+ if (err.code === "ENOENT") continue;
134
+ throw err;
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ // src/utils/frontmatter.ts
141
+ function unquote(val) {
142
+ const trimmed = val.trim();
143
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
144
+ return trimmed.slice(1, -1).replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
145
+ }
146
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
147
+ return trimmed.slice(1, -1).replace(/''/g, "'");
148
+ }
149
+ return trimmed;
150
+ }
151
+ function escapeDoubleQuoted(str) {
152
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
153
+ }
154
+ function parseScalarValue(raw) {
155
+ const trimmed = raw.trim();
156
+ if (trimmed === "true") return true;
157
+ if (trimmed === "false") return false;
158
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
159
+ const inner = trimmed.slice(1, -1).trim();
160
+ if (!inner) return [];
161
+ return inner.split(",").map((item) => unquote(item));
162
+ }
163
+ return unquote(trimmed);
164
+ }
165
+ function parseBlockScalar(lines, indicator) {
166
+ const isFolded = indicator.startsWith(">");
167
+ const nonEmpty = lines.filter((l) => l.trim().length > 0);
168
+ if (nonEmpty.length === 0) return "";
169
+ const minIndent = Math.min(
170
+ ...nonEmpty.map((l) => {
171
+ const m = l.match(/^ +/);
172
+ return m ? m[0].length : 0;
173
+ })
174
+ );
175
+ const strippedLines = lines.map(
176
+ (l) => l.length >= minIndent ? l.slice(minIndent) : l.trim()
177
+ );
178
+ while (strippedLines.length > 0 && strippedLines[0].trim() === "") {
179
+ strippedLines.shift();
180
+ }
181
+ while (strippedLines.length > 0 && strippedLines[strippedLines.length - 1].trim() === "") {
182
+ strippedLines.pop();
183
+ }
184
+ if (!isFolded) {
185
+ return strippedLines.join("\n");
186
+ }
187
+ const paragraphs = [];
188
+ let current = [];
189
+ for (const line of strippedLines) {
190
+ if (line.trim() === "") {
191
+ if (current.length > 0) {
192
+ paragraphs.push(current.join(" "));
193
+ current = [];
194
+ }
195
+ } else {
196
+ current.push(line.trim());
197
+ }
198
+ }
199
+ if (current.length > 0) {
200
+ paragraphs.push(current.join(" "));
201
+ }
202
+ return paragraphs.join("\n");
203
+ }
204
+ function parseFrontmatter(content) {
205
+ const normalised = content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
206
+ const match = normalised.match(
207
+ /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(?:\n+|$)([\s\S]*)$/
208
+ );
209
+ if (!match) {
210
+ return {
211
+ attributes: {},
212
+ body: normalised,
213
+ hasFrontmatter: false
214
+ };
215
+ }
216
+ const yamlBlock = match[1] ?? "";
217
+ const body = match[2];
218
+ const attributes = {};
219
+ const lines = yamlBlock.split("\n");
220
+ let currentListKey = null;
221
+ for (let i = 0; i < lines.length; i++) {
222
+ const line = lines[i];
223
+ const trimmed = line.trim();
224
+ if (!trimmed || trimmed.startsWith("#")) {
225
+ continue;
226
+ }
227
+ const isIndented = /^\s/.test(line);
228
+ if (trimmed.startsWith("- ") && currentListKey) {
229
+ const list = attributes[currentListKey];
230
+ if (Array.isArray(list)) {
231
+ list.push(unquote(trimmed.slice(2)));
232
+ }
233
+ continue;
234
+ }
235
+ if (isIndented) {
236
+ continue;
237
+ }
238
+ const colonIndex = line.indexOf(":");
239
+ if (colonIndex === -1) {
240
+ currentListKey = null;
241
+ continue;
242
+ }
243
+ const key = line.slice(0, colonIndex).trim();
244
+ const rawValue = line.slice(colonIndex + 1).trim();
245
+ if (!key) {
246
+ currentListKey = null;
247
+ continue;
248
+ }
249
+ if (/^[|>][-+]?$/.test(rawValue)) {
250
+ currentListKey = null;
251
+ const blockLines = [];
252
+ while (i + 1 < lines.length) {
253
+ const nextLine = lines[i + 1];
254
+ if (nextLine.trim() === "" || /^\s+/.test(nextLine)) {
255
+ blockLines.push(nextLine);
256
+ i++;
257
+ } else {
258
+ break;
259
+ }
260
+ }
261
+ attributes[key] = parseBlockScalar(blockLines, rawValue);
262
+ } else if (rawValue === "") {
263
+ attributes[key] = [];
264
+ currentListKey = key;
265
+ } else {
266
+ attributes[key] = parseScalarValue(rawValue);
267
+ currentListKey = null;
268
+ }
269
+ }
270
+ return {
271
+ attributes,
272
+ body,
273
+ hasFrontmatter: true
274
+ };
275
+ }
276
+ function formatYamlValue(value) {
277
+ if (typeof value === "boolean" || typeof value === "number") {
278
+ return String(value);
279
+ }
280
+ if (Array.isArray(value)) {
281
+ const items = value.map((item) => `"${escapeDoubleQuoted(String(item))}"`).join(", ");
282
+ return `[${items}]`;
283
+ }
284
+ const str = String(value ?? "");
285
+ if (str.includes(":") || str.includes("*") || str.includes("#") || str.includes("[") || str.includes("]") || str.includes("{") || str.includes("}") || str.includes('"') || str.includes("'") || str.includes("\n") || str.startsWith(">") || str.startsWith("|") || str.startsWith(" ") || str.endsWith(" ")) {
286
+ return `"${escapeDoubleQuoted(str)}"`;
287
+ }
288
+ return str;
289
+ }
290
+ function serialiseFrontmatter(attributes, body) {
291
+ const keys = Object.keys(attributes).filter(
292
+ (key) => attributes[key] !== void 0
293
+ );
294
+ const normalisedBody = body.replace(/\r\n/g, "\n").replace(/^\n+/, "");
295
+ if (keys.length === 0) {
296
+ return normalisedBody;
297
+ }
298
+ const yamlLines = keys.map(
299
+ (key) => `${key}: ${formatYamlValue(attributes[key])}`
300
+ );
301
+ return `---
302
+ ${yamlLines.join("\n")}
303
+ ---
304
+
305
+ ${normalisedBody}`;
306
+ }
307
+
308
+ // src/lifecycle/hash.ts
309
+ var import_node_crypto = require("crypto");
310
+ var import_node_fs2 = require("fs");
311
+ var import_node_path2 = require("path");
312
+ function hashString(content) {
313
+ const normalised = content.replace(/\r\n/g, "\n");
314
+ return (0, import_node_crypto.createHash)("sha256").update(normalised, "utf-8").digest("hex");
315
+ }
316
+ var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
317
+ function hashFile(filePath) {
318
+ const buf = (0, import_node_fs2.readFileSync)(filePath);
319
+ if (!buf.includes(0)) {
320
+ try {
321
+ const text = utf8Decoder.decode(buf);
322
+ return hashString(text);
323
+ } catch {
324
+ }
325
+ }
326
+ return (0, import_node_crypto.createHash)("sha256").update(buf).digest("hex");
327
+ }
328
+ function collectFilesRecursive(dirPath, rootDir) {
329
+ const entries = (0, import_node_fs2.readdirSync)(dirPath, { withFileTypes: true });
330
+ const files = [];
331
+ for (const entry of entries) {
332
+ if (entry.name === ".git") continue;
333
+ const fullPath = (0, import_node_path2.join)(dirPath, entry.name);
334
+ if (entry.isDirectory()) {
335
+ files.push(...collectFilesRecursive(fullPath, rootDir));
336
+ } else if (entry.isFile()) {
337
+ files.push(fullPath);
338
+ }
339
+ }
340
+ return files;
341
+ }
342
+ function hashDirectory(dirPath) {
343
+ const files = collectFilesRecursive(dirPath, dirPath);
344
+ const items = files.map((fullPath) => {
345
+ const relPosix = (0, import_node_path2.relative)(dirPath, fullPath).split("\\").join("/");
346
+ return { relPosix, fullPath };
347
+ }).sort((a, b) => a.relPosix.localeCompare(b.relPosix));
348
+ const hash = (0, import_node_crypto.createHash)("sha256");
349
+ for (const item of items) {
350
+ hash.update(`${item.relPosix}:${hashFile(item.fullPath)}
351
+ `, "utf-8");
352
+ }
353
+ return hash.digest("hex");
354
+ }
355
+ function hashAssetPath(targetPath) {
356
+ const stat = (0, import_node_fs2.statSync)(targetPath);
357
+ if (stat.isDirectory()) {
358
+ return hashDirectory(targetPath);
359
+ }
360
+ return hashFile(targetPath);
361
+ }
362
+
363
+ // src/sources/awesome-copilot.ts
364
+ var import_node_fs3 = require("fs");
365
+ var import_node_path3 = require("path");
366
+ var import_simple_git = require("simple-git");
367
+ var AWESOME_COPILOT_REPO_URL = "https://github.com/github/awesome-copilot.git";
368
+ var SOURCE_NAME = "awesome-copilot";
369
+ var MASS_REMOVAL_THRESHOLD = 0.25;
370
+ function stripAssetSuffix(filename) {
371
+ return filename.replace(/\.instructions\.md$/i, "").replace(/\.agent\.md$/i, "").replace(/\.chatmode\.md$/i, "").replace(/\.prompt\.md$/i, "").replace(/\.md$/i, "");
372
+ }
373
+ function humaniseSlug(slug) {
374
+ return slug.split(/[-_]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
375
+ }
376
+ function extractHeadingAndSummary(body) {
377
+ const lines = body.split("\n").map((l) => l.trim()).filter(Boolean);
378
+ let heading;
379
+ let summary;
380
+ for (const line of lines) {
381
+ const h1Match = line.match(/^#\s+([^#].*)$/);
382
+ if (h1Match) {
383
+ if (!heading) {
384
+ const candidate = h1Match[1]?.trim();
385
+ if (candidate && !/^\d+\.\s/.test(candidate)) {
386
+ heading = candidate;
387
+ }
388
+ }
389
+ continue;
390
+ }
391
+ if (line.startsWith("#")) {
392
+ continue;
393
+ }
394
+ if (!summary) {
395
+ summary = line;
396
+ break;
397
+ }
398
+ }
399
+ return { heading, summary };
400
+ }
401
+ function parseAssetMetadata(id, type, localPath, isDirectory, markdownContent) {
402
+ const { attributes, body } = parseFrontmatter(markdownContent);
403
+ const { heading, summary } = extractHeadingAndSummary(body);
404
+ const title = typeof attributes.title === "string" && attributes.title.trim() || typeof attributes.name === "string" && attributes.name.trim() || heading || humaniseSlug(id);
405
+ const rawDescription = typeof attributes.description === "string" && attributes.description.trim() || summary || `${humaniseSlug(type)} asset for ${title}`;
406
+ const description = rawDescription.replace(/\r?\n\s*[-*•+]\s*/g, " ").replace(/\r?\n/g, " ").replace(/\s+/g, " ").trim();
407
+ const rawTags = attributes.tags;
408
+ const tags = Array.isArray(rawTags) ? rawTags.map((t) => String(t).trim()).filter(Boolean) : typeof rawTags === "string" ? rawTags.split(",").map((t) => t.trim()).filter(Boolean) : [];
409
+ const requiresSetup = Boolean(
410
+ attributes.requiresSetup === true || attributes.mcpServers !== void 0 || attributes.setup !== void 0 || /requires?\s+setup|API_KEY/i.test(body)
411
+ );
412
+ const hash = hashAssetPath(localPath);
413
+ return {
414
+ id,
415
+ type,
416
+ title,
417
+ description,
418
+ source: SOURCE_NAME,
419
+ localPath,
420
+ isDirectory,
421
+ hash,
422
+ requiresSetup,
423
+ tags
424
+ };
425
+ }
426
+ function scanAwesomeCopilotRepo(repoDir) {
427
+ if (!(0, import_node_fs3.existsSync)(repoDir)) {
428
+ return [];
429
+ }
430
+ const assets = [];
431
+ const seenIds = /* @__PURE__ */ new Set();
432
+ const registerAsset = (asset) => {
433
+ let candidateId = asset.id;
434
+ if (seenIds.has(candidateId)) {
435
+ candidateId = `${asset.type}-${asset.id}`;
436
+ }
437
+ let suffix = 2;
438
+ while (seenIds.has(candidateId)) {
439
+ candidateId = `${asset.type}-${asset.id}-${suffix}`;
440
+ suffix++;
441
+ }
442
+ asset.id = candidateId;
443
+ seenIds.add(asset.id);
444
+ assets.push(asset);
445
+ };
446
+ const instructionsDir = (0, import_node_path3.join)(repoDir, "instructions");
447
+ if ((0, import_node_fs3.existsSync)(instructionsDir)) {
448
+ const entries = (0, import_node_fs3.readdirSync)(instructionsDir, {
449
+ withFileTypes: true
450
+ }).sort((a, b) => a.name.localeCompare(b.name));
451
+ for (const entry of entries) {
452
+ if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name.toLowerCase() === "readme.md") {
453
+ continue;
454
+ }
455
+ const fullPath = (0, import_node_path3.join)(instructionsDir, entry.name);
456
+ const id = stripAssetSuffix(entry.name);
457
+ const content = (0, import_node_fs3.readFileSync)(fullPath, "utf-8");
458
+ registerAsset(
459
+ parseAssetMetadata(id, "instruction", fullPath, false, content)
460
+ );
461
+ }
462
+ }
463
+ for (const folder of ["agents", "chatmodes"]) {
464
+ const agentsDir = (0, import_node_path3.join)(repoDir, folder);
465
+ if (!(0, import_node_fs3.existsSync)(agentsDir)) continue;
466
+ const entries = (0, import_node_fs3.readdirSync)(agentsDir, { withFileTypes: true }).sort(
467
+ (a, b) => a.name.localeCompare(b.name)
468
+ );
469
+ for (const entry of entries) {
470
+ if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name.toLowerCase() === "readme.md") {
471
+ continue;
472
+ }
473
+ const fullPath = (0, import_node_path3.join)(agentsDir, entry.name);
474
+ const id = stripAssetSuffix(entry.name);
475
+ const content = (0, import_node_fs3.readFileSync)(fullPath, "utf-8");
476
+ registerAsset(
477
+ parseAssetMetadata(id, "agent", fullPath, false, content)
478
+ );
479
+ }
480
+ }
481
+ const skillsDir = (0, import_node_path3.join)(repoDir, "skills");
482
+ if ((0, import_node_fs3.existsSync)(skillsDir)) {
483
+ const entries = (0, import_node_fs3.readdirSync)(skillsDir, { withFileTypes: true }).sort(
484
+ (a, b) => a.name.localeCompare(b.name)
485
+ );
486
+ for (const entry of entries) {
487
+ if (!entry.isDirectory()) continue;
488
+ const skillPath = (0, import_node_path3.join)(skillsDir, entry.name);
489
+ const skillMdPath = (0, import_node_path3.join)(skillPath, "SKILL.md");
490
+ const readmePath = (0, import_node_path3.join)(skillPath, "README.md");
491
+ const docPath = (0, import_node_fs3.existsSync)(skillMdPath) ? skillMdPath : (0, import_node_fs3.existsSync)(readmePath) ? readmePath : null;
492
+ if (!docPath) continue;
493
+ const content = (0, import_node_fs3.readFileSync)(docPath, "utf-8");
494
+ registerAsset(
495
+ parseAssetMetadata(
496
+ entry.name,
497
+ "skill",
498
+ skillPath,
499
+ true,
500
+ content
501
+ )
502
+ );
503
+ }
504
+ }
505
+ return assets;
506
+ }
507
+ async function ensureAwesomeCopilotRepo(repoDir = awesomeCopilotRoot(), remoteUrl = AWESOME_COPILOT_REPO_URL) {
508
+ const gitDir = (0, import_node_path3.join)(repoDir, ".git");
509
+ if ((0, import_node_fs3.existsSync)(gitDir)) {
510
+ const git = (0, import_simple_git.simpleGit)(repoDir);
511
+ await git.pull(["--ff-only"]);
512
+ } else {
513
+ (0, import_node_fs3.mkdirSync)(repoDir, { recursive: true });
514
+ const git = (0, import_simple_git.simpleGit)();
515
+ await git.clone(remoteUrl, repoDir, ["--depth", "1"]);
516
+ }
517
+ }
518
+ function loadCatalogue() {
519
+ const file = cataloguePath();
520
+ if (!(0, import_node_fs3.existsSync)(file)) return [];
521
+ return JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
522
+ }
523
+ function loadManifest() {
524
+ const file = manifestPath();
525
+ if (!(0, import_node_fs3.existsSync)(file)) return [];
526
+ return JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
527
+ }
528
+ function validateSyncSafety(assets, previousManifest, force = false) {
529
+ if (force) return;
530
+ if (assets.length === 0) {
531
+ throw new Error(
532
+ "Safety check failed: structural change detected \u2014 no valid assets found in awesome-copilot source. Pass --force to override."
533
+ );
534
+ }
535
+ if (previousManifest.length > 0) {
536
+ const currentIds = new Set(assets.map((a) => a.id));
537
+ const removedCount = previousManifest.filter(
538
+ (m) => !currentIds.has(m.id)
539
+ ).length;
540
+ const removalRatio = removedCount / previousManifest.length;
541
+ if (removalRatio > MASS_REMOVAL_THRESHOLD) {
542
+ throw new Error(
543
+ `Safety check failed: mass removal detected (${removedCount}/${previousManifest.length} assets removed). Pass --force to override.`
544
+ );
545
+ }
546
+ }
547
+ }
548
+ async function syncAwesomeCopilot(options = {}) {
549
+ const repoDir = options.repoDir ?? awesomeCopilotRoot();
550
+ const dryRun = Boolean(options.dryRun);
551
+ const force = Boolean(options.force);
552
+ const legacyCacheDetected = !(0, import_node_fs3.existsSync)(cataloguePath()) && (0, import_node_fs3.existsSync)(legacyCacheRoot());
553
+ if (!options.skipGit) {
554
+ await ensureAwesomeCopilotRepo(repoDir, options.remoteUrl);
555
+ }
556
+ const previousManifest = loadManifest();
557
+ const assets = scanAwesomeCopilotRepo(repoDir);
558
+ validateSyncSafety(assets, previousManifest, force);
559
+ const prevById = new Map(previousManifest.map((m) => [m.id, m]));
560
+ const currentById = new Map(assets.map((a) => [a.id, a]));
561
+ const added = [];
562
+ const updated = [];
563
+ const unchanged = [];
564
+ const removed = [];
565
+ for (const asset of assets) {
566
+ const prev = prevById.get(asset.id);
567
+ if (!prev) {
568
+ added.push(asset.id);
569
+ } else if (prev.hash !== asset.hash) {
570
+ updated.push(asset.id);
571
+ } else {
572
+ unchanged.push(asset.id);
573
+ }
574
+ }
575
+ for (const prev of previousManifest) {
576
+ if (!currentById.has(prev.id)) {
577
+ removed.push(prev.id);
578
+ }
579
+ }
580
+ if (!dryRun) {
581
+ (0, import_node_fs3.mkdirSync)(cacheRoot(), { recursive: true });
582
+ const now = (/* @__PURE__ */ new Date()).toISOString();
583
+ const catalogue = assets.map((asset) => ({
584
+ id: asset.id,
585
+ type: asset.type,
586
+ title: asset.title,
587
+ description: asset.description,
588
+ source: asset.source,
589
+ requiresSetup: asset.requiresSetup,
590
+ tags: asset.tags
591
+ }));
592
+ const manifest = assets.map((asset) => ({
593
+ id: asset.id,
594
+ type: asset.type,
595
+ localPath: asset.localPath,
596
+ hash: asset.hash,
597
+ syncedAt: now
598
+ }));
599
+ (0, import_node_fs3.writeFileSync)(
600
+ cataloguePath(),
601
+ JSON.stringify(catalogue, null, 2) + "\n",
602
+ "utf-8"
603
+ );
604
+ (0, import_node_fs3.writeFileSync)(
605
+ manifestPath(),
606
+ JSON.stringify(manifest, null, 2) + "\n",
607
+ "utf-8"
608
+ );
609
+ }
610
+ return {
611
+ assets,
612
+ added,
613
+ updated,
614
+ removed,
615
+ unchanged,
616
+ dryRun,
617
+ legacyCacheDetected
618
+ };
619
+ }
620
+
621
+ // src/targets/vscode.ts
622
+ var import_node_os2 = require("os");
623
+ var import_node_path4 = require("path");
624
+ function resolveVscodeBaseDir(scope, cwd = process.cwd(), home = (0, import_node_os2.homedir)()) {
625
+ return scope === "repo" ? (0, import_node_path4.join)(cwd, ".github") : (0, import_node_path4.join)(home, ".copilot");
626
+ }
627
+ function resolveVscodeTargetPath(assetId, type, scope, cwd = process.cwd(), home = (0, import_node_os2.homedir)()) {
628
+ const baseDir = resolveVscodeBaseDir(scope, cwd, home);
629
+ let targetPath;
630
+ switch (type) {
631
+ case "instruction":
632
+ case "rule":
633
+ targetPath = (0, import_node_path4.join)(
634
+ baseDir,
635
+ "instructions",
636
+ `${assetId}.instructions.md`
637
+ );
638
+ break;
639
+ case "agent":
640
+ targetPath = (0, import_node_path4.join)(baseDir, "agents", `${assetId}.agent.md`);
641
+ break;
642
+ case "skill":
643
+ targetPath = (0, import_node_path4.join)(baseDir, "skills", assetId);
644
+ break;
645
+ default:
646
+ return null;
647
+ }
648
+ assertPathWithin(targetPath, baseDir);
649
+ return targetPath;
650
+ }
651
+ function adaptForVscode(content, type) {
652
+ if (type !== "instruction" && type !== "rule" && type !== "agent" && type !== "skill") {
653
+ return {
654
+ outcome: "unsupported",
655
+ content,
656
+ adaptations: [],
657
+ reason: `Asset type '${type}' is not supported by the VS Code target adapter.`
658
+ };
659
+ }
660
+ if (type === "skill" || type === "agent") {
661
+ return {
662
+ outcome: "native",
663
+ content,
664
+ adaptations: []
665
+ };
666
+ }
667
+ const { attributes, body, hasFrontmatter } = parseFrontmatter(content);
668
+ if (!hasFrontmatter) {
669
+ return {
670
+ outcome: "native",
671
+ content,
672
+ adaptations: []
673
+ };
674
+ }
675
+ const adaptations = [];
676
+ const updated = { ...attributes };
677
+ if (updated.inclusion !== void 0 && updated.applyTo === void 0) {
678
+ const pattern = typeof updated.fileMatchPattern === "string" ? updated.fileMatchPattern : "**";
679
+ updated.applyTo = pattern;
680
+ delete updated.inclusion;
681
+ delete updated.fileMatchPattern;
682
+ adaptations.push(`inclusion -> applyTo: ${pattern}`);
683
+ }
684
+ if (updated.trigger !== void 0 && updated.applyTo === void 0) {
685
+ const pattern = typeof updated.globs === "string" ? updated.globs : "**";
686
+ updated.applyTo = pattern;
687
+ delete updated.trigger;
688
+ delete updated.globs;
689
+ adaptations.push(`trigger -> applyTo: ${pattern}`);
690
+ }
691
+ if (adaptations.length > 0) {
692
+ return {
693
+ outcome: "adapted",
694
+ content: serialiseFrontmatter(updated, body),
695
+ adaptations
696
+ };
697
+ }
698
+ return {
699
+ outcome: "native",
700
+ content,
701
+ adaptations: []
702
+ };
703
+ }
704
+
705
+ // src/targets/kiro.ts
706
+ var import_node_os3 = require("os");
707
+ var import_node_path5 = require("path");
708
+ function resolveKiroBaseDir(scope, cwd = process.cwd(), home = (0, import_node_os3.homedir)()) {
709
+ return scope === "repo" ? (0, import_node_path5.join)(cwd, ".kiro") : (0, import_node_path5.join)(home, ".kiro");
710
+ }
711
+ function resolveKiroTargetPath(assetId, type, scope, cwd = process.cwd(), home = (0, import_node_os3.homedir)()) {
712
+ const baseDir = resolveKiroBaseDir(scope, cwd, home);
713
+ let targetPath;
714
+ switch (type) {
715
+ case "instruction":
716
+ case "rule":
717
+ targetPath = (0, import_node_path5.join)(baseDir, "steering", `${assetId}.md`);
718
+ break;
719
+ case "agent":
720
+ targetPath = (0, import_node_path5.join)(baseDir, "agents", `${assetId}.md`);
721
+ break;
722
+ case "skill":
723
+ targetPath = (0, import_node_path5.join)(baseDir, "skills", assetId);
724
+ break;
725
+ default:
726
+ return null;
727
+ }
728
+ assertPathWithin(targetPath, baseDir);
729
+ return targetPath;
730
+ }
731
+ function adaptForKiro(content, type) {
732
+ if (type !== "instruction" && type !== "rule" && type !== "agent" && type !== "skill") {
733
+ return {
734
+ outcome: "unsupported",
735
+ content,
736
+ adaptations: [],
737
+ reason: `Asset type '${type}' is not supported by the Kiro target adapter.`
738
+ };
739
+ }
740
+ if (type === "skill") {
741
+ return {
742
+ outcome: "native",
743
+ content,
744
+ adaptations: []
745
+ };
746
+ }
747
+ const { attributes, body, hasFrontmatter } = parseFrontmatter(content);
748
+ if (type === "agent") {
749
+ if (!hasFrontmatter) {
750
+ return { outcome: "native", content, adaptations: [] };
751
+ }
752
+ const updated2 = { ...attributes };
753
+ const adaptations2 = [];
754
+ for (const field of ["chat-tools", "handoffs", "target"]) {
755
+ if (updated2[field] !== void 0) {
756
+ delete updated2[field];
757
+ adaptations2.push(`omitted ${field}`);
758
+ }
759
+ }
760
+ if (adaptations2.length > 0) {
761
+ return {
762
+ outcome: "adapted",
763
+ content: serialiseFrontmatter(updated2, body),
764
+ adaptations: adaptations2
765
+ };
766
+ }
767
+ return { outcome: "native", content, adaptations: [] };
768
+ }
769
+ const updated = { ...attributes };
770
+ const adaptations = [];
771
+ if (updated.inclusion !== void 0) {
772
+ return {
773
+ outcome: "native",
774
+ content,
775
+ adaptations: []
776
+ };
777
+ }
778
+ if (updated.applyTo !== void 0) {
779
+ const applyTo = String(updated.applyTo).trim();
780
+ delete updated.applyTo;
781
+ if (!applyTo || applyTo === "**" || applyTo === "*" || applyTo === "**/*") {
782
+ updated.inclusion = "always";
783
+ adaptations.push("applyTo -> inclusion: always");
784
+ } else {
785
+ updated.inclusion = "fileMatch";
786
+ updated.fileMatchPattern = applyTo;
787
+ adaptations.push(
788
+ `applyTo -> inclusion: fileMatch, fileMatchPattern: ${applyTo}`
789
+ );
790
+ }
791
+ } else if (updated.trigger !== void 0) {
792
+ const globs = typeof updated.globs === "string" ? updated.globs.trim() : "";
793
+ delete updated.trigger;
794
+ delete updated.globs;
795
+ if (globs && globs !== "**" && globs !== "*") {
796
+ updated.inclusion = "fileMatch";
797
+ updated.fileMatchPattern = globs;
798
+ adaptations.push(
799
+ `trigger -> inclusion: fileMatch, fileMatchPattern: ${globs}`
800
+ );
801
+ } else {
802
+ updated.inclusion = "always";
803
+ adaptations.push("trigger -> inclusion: always");
804
+ }
805
+ } else {
806
+ updated.inclusion = "always";
807
+ adaptations.push("added inclusion: always");
808
+ }
809
+ return {
810
+ outcome: "adapted",
811
+ content: serialiseFrontmatter(updated, body),
812
+ adaptations
813
+ };
814
+ }
815
+
816
+ // src/targets/antigravity.ts
817
+ var import_node_os4 = require("os");
818
+ var import_node_path6 = require("path");
819
+ function resolveAntigravityBaseDir(scope, cwd = process.cwd(), home = (0, import_node_os4.homedir)()) {
820
+ return scope === "repo" ? (0, import_node_path6.join)(cwd, ".agents") : (0, import_node_path6.join)(home, ".gemini", "config");
821
+ }
822
+ function resolveAntigravityTargetPath(assetId, type, scope, cwd = process.cwd(), home = (0, import_node_os4.homedir)()) {
823
+ const baseDir = resolveAntigravityBaseDir(scope, cwd, home);
824
+ let targetPath;
825
+ switch (type) {
826
+ case "instruction":
827
+ case "rule":
828
+ targetPath = (0, import_node_path6.join)(baseDir, "rules", `${assetId}.md`);
829
+ break;
830
+ case "agent":
831
+ targetPath = (0, import_node_path6.join)(
832
+ baseDir,
833
+ "plugins",
834
+ assetId,
835
+ "agents",
836
+ `${assetId}.md`
837
+ );
838
+ break;
839
+ case "skill":
840
+ targetPath = (0, import_node_path6.join)(baseDir, "plugins", assetId, "skills", assetId);
841
+ break;
842
+ default:
843
+ return null;
844
+ }
845
+ assertPathWithin(targetPath, baseDir);
846
+ return targetPath;
847
+ }
848
+ function adaptForAntigravity(content, type) {
849
+ if (type !== "instruction" && type !== "rule" && type !== "agent" && type !== "skill") {
850
+ return {
851
+ outcome: "unsupported",
852
+ content,
853
+ adaptations: [],
854
+ reason: `Asset type '${type}' is not supported by the Antigravity target adapter.`
855
+ };
856
+ }
857
+ if (type === "skill") {
858
+ return {
859
+ outcome: "native",
860
+ content,
861
+ adaptations: []
862
+ };
863
+ }
864
+ const { attributes, body, hasFrontmatter } = parseFrontmatter(content);
865
+ if (type === "agent") {
866
+ if (!hasFrontmatter) {
867
+ return { outcome: "native", content, adaptations: [] };
868
+ }
869
+ const updated2 = { ...attributes };
870
+ const adaptations2 = [];
871
+ for (const field of ["chat-tools", "handoffs", "target"]) {
872
+ if (updated2[field] !== void 0) {
873
+ delete updated2[field];
874
+ adaptations2.push(`omitted ${field}`);
875
+ }
876
+ }
877
+ if (adaptations2.length > 0) {
878
+ return {
879
+ outcome: "adapted",
880
+ content: serialiseFrontmatter(updated2, body),
881
+ adaptations: adaptations2
882
+ };
883
+ }
884
+ return { outcome: "native", content, adaptations: [] };
885
+ }
886
+ const updated = { ...attributes };
887
+ const adaptations = [];
888
+ if (updated.trigger !== void 0) {
889
+ return {
890
+ outcome: "native",
891
+ content,
892
+ adaptations: []
893
+ };
894
+ }
895
+ if (updated.applyTo !== void 0) {
896
+ const applyTo = String(updated.applyTo).trim();
897
+ delete updated.applyTo;
898
+ if (!applyTo || applyTo === "**" || applyTo === "*" || applyTo === "**/*") {
899
+ updated.trigger = "always_on";
900
+ adaptations.push("applyTo -> trigger: always_on");
901
+ } else {
902
+ updated.trigger = "glob";
903
+ updated.globs = applyTo;
904
+ adaptations.push(`applyTo -> trigger: glob, globs: ${applyTo}`);
905
+ }
906
+ } else if (updated.inclusion !== void 0) {
907
+ const pattern = typeof updated.fileMatchPattern === "string" ? updated.fileMatchPattern.trim() : "";
908
+ delete updated.inclusion;
909
+ delete updated.fileMatchPattern;
910
+ if (pattern && pattern !== "**" && pattern !== "*") {
911
+ updated.trigger = "glob";
912
+ updated.globs = pattern;
913
+ adaptations.push(`inclusion -> trigger: glob, globs: ${pattern}`);
914
+ } else {
915
+ updated.trigger = "always_on";
916
+ adaptations.push("inclusion -> trigger: always_on");
917
+ }
918
+ } else {
919
+ updated.trigger = "always_on";
920
+ adaptations.push("added trigger: always_on");
921
+ }
922
+ return {
923
+ outcome: "adapted",
924
+ content: serialiseFrontmatter(updated, body),
925
+ adaptations
926
+ };
927
+ }
928
+
929
+ // src/targets/index.ts
930
+ var ALL_TARGETS = [
931
+ "vscode",
932
+ "kiro",
933
+ "antigravity"
934
+ ];
935
+ var adapters = {
936
+ vscode: {
937
+ target: "vscode",
938
+ resolveBaseDir: resolveVscodeBaseDir,
939
+ resolveTargetPath: resolveVscodeTargetPath,
940
+ adaptContent: adaptForVscode
941
+ },
942
+ kiro: {
943
+ target: "kiro",
944
+ resolveBaseDir: resolveKiroBaseDir,
945
+ resolveTargetPath: resolveKiroTargetPath,
946
+ adaptContent: adaptForKiro
947
+ },
948
+ antigravity: {
949
+ target: "antigravity",
950
+ resolveBaseDir: resolveAntigravityBaseDir,
951
+ resolveTargetPath: resolveAntigravityTargetPath,
952
+ adaptContent: adaptForAntigravity
953
+ }
954
+ };
955
+ function isValidTarget(value) {
956
+ return value === "vscode" || value === "kiro" || value === "antigravity";
957
+ }
958
+ function isValidScope(value) {
959
+ return value === "repo" || value === "user";
960
+ }
961
+ var TARGET_TERMINOLOGY = {
962
+ vscode: {
963
+ singular: {
964
+ instruction: "instruction",
965
+ rule: "instruction",
966
+ agent: "agent",
967
+ skill: "skill",
968
+ plugin: "plugin",
969
+ workflow: "workflow"
970
+ },
971
+ plural: {
972
+ instruction: "instructions",
973
+ rule: "instructions",
974
+ agent: "agents",
975
+ skill: "skills",
976
+ plugin: "plugins",
977
+ workflow: "workflows"
978
+ }
979
+ },
980
+ kiro: {
981
+ singular: {
982
+ instruction: "steering",
983
+ rule: "steering",
984
+ agent: "agent",
985
+ skill: "skill",
986
+ plugin: "plugin",
987
+ workflow: "workflow"
988
+ },
989
+ plural: {
990
+ instruction: "steering",
991
+ rule: "steering",
992
+ agent: "agents",
993
+ skill: "skills",
994
+ plugin: "plugins",
995
+ workflow: "workflows"
996
+ }
997
+ },
998
+ antigravity: {
999
+ singular: {
1000
+ instruction: "rule",
1001
+ rule: "rule",
1002
+ agent: "agent",
1003
+ skill: "skill",
1004
+ plugin: "plugin",
1005
+ workflow: "workflow"
1006
+ },
1007
+ plural: {
1008
+ instruction: "rules",
1009
+ rule: "rules",
1010
+ agent: "agents",
1011
+ skill: "skills",
1012
+ plugin: "plugins",
1013
+ workflow: "workflows"
1014
+ }
1015
+ }
1016
+ };
1017
+ function getTargetTypeLabel(type, target) {
1018
+ return TARGET_TERMINOLOGY[target]?.singular[type] ?? type;
1019
+ }
1020
+ function getTargetTypePlural(type, target) {
1021
+ return TARGET_TERMINOLOGY[target]?.plural[type] ?? `${type}s`;
1022
+ }
1023
+ function normaliseTargetAssetType(rawType, _target) {
1024
+ const lower = rawType.toLowerCase().trim();
1025
+ if (lower === "instruction" || lower === "instructions")
1026
+ return "instruction";
1027
+ if (lower === "agent" || lower === "agents") return "agent";
1028
+ if (lower === "skill" || lower === "skills") return "skill";
1029
+ if (lower === "steering") return "instruction";
1030
+ if (lower === "rule" || lower === "rules") return "instruction";
1031
+ if (lower === "plugin" || lower === "plugins") return "plugin";
1032
+ if (lower === "workflow" || lower === "workflows") return "workflow";
1033
+ return void 0;
1034
+ }
1035
+ function getTargetAdapter(target) {
1036
+ const adapter = adapters[target];
1037
+ if (!adapter) {
1038
+ throw new Error(`Unknown target environment: '${String(target)}'`);
1039
+ }
1040
+ return adapter;
1041
+ }
1042
+
1043
+ // src/lifecycle/install.ts
1044
+ var import_node_fs5 = require("fs");
1045
+ var import_node_path8 = require("path");
1046
+
1047
+ // src/lifecycle/subscriptions.ts
1048
+ var import_node_fs4 = require("fs");
1049
+ var import_node_path7 = require("path");
1050
+ function isSameOrWithinPath(installedPath, constraintPath) {
1051
+ const resolvedInstalled = (0, import_node_path7.resolve)(installedPath);
1052
+ const resolvedConstraint = (0, import_node_path7.resolve)(constraintPath);
1053
+ if (resolvedInstalled === resolvedConstraint) return true;
1054
+ const rel = (0, import_node_path7.relative)(resolvedConstraint, resolvedInstalled);
1055
+ return rel !== "" && !rel.startsWith("..") && (0, import_node_path7.resolve)(rel) !== rel;
1056
+ }
1057
+ function loadSubscriptions() {
1058
+ const file = subscriptionsPath();
1059
+ if (!(0, import_node_fs4.existsSync)(file)) return [];
1060
+ return JSON.parse((0, import_node_fs4.readFileSync)(file, "utf-8"));
1061
+ }
1062
+ function saveSubscriptions(subscriptions) {
1063
+ (0, import_node_fs4.mkdirSync)(cacheRoot(), { recursive: true });
1064
+ (0, import_node_fs4.writeFileSync)(
1065
+ subscriptionsPath(),
1066
+ JSON.stringify(subscriptions, null, 2) + "\n",
1067
+ "utf-8"
1068
+ );
1069
+ }
1070
+ function findSubscription(id, target, scope, installedPathOrBaseDir) {
1071
+ const subscriptions = loadSubscriptions();
1072
+ return subscriptions.find(
1073
+ (s) => s.id === id && s.target === target && s.scope === scope && (!installedPathOrBaseDir || isSameOrWithinPath(s.installedPath, installedPathOrBaseDir))
1074
+ );
1075
+ }
1076
+ function upsertSubscription(sub) {
1077
+ const subscriptions = loadSubscriptions();
1078
+ const resolvedInstalled = (0, import_node_path7.resolve)(sub.installedPath);
1079
+ const index = subscriptions.findIndex(
1080
+ (s) => s.id === sub.id && s.target === sub.target && s.scope === sub.scope && (sub.scope === "user" || (0, import_node_path7.resolve)(s.installedPath) === resolvedInstalled)
1081
+ );
1082
+ if (index >= 0) {
1083
+ subscriptions[index] = sub;
1084
+ } else {
1085
+ subscriptions.push(sub);
1086
+ }
1087
+ saveSubscriptions(subscriptions);
1088
+ }
1089
+ function removeSubscriptionRecord(id, target, scope, installedPathOrBaseDir) {
1090
+ const subscriptions = loadSubscriptions();
1091
+ const filtered = subscriptions.filter(
1092
+ (s) => !(s.id === id && s.target === target && s.scope === scope && (!installedPathOrBaseDir || isSameOrWithinPath(s.installedPath, installedPathOrBaseDir)))
1093
+ );
1094
+ if (filtered.length === subscriptions.length) {
1095
+ return false;
1096
+ }
1097
+ saveSubscriptions(filtered);
1098
+ return true;
1099
+ }
1100
+ function computeAssetStatus(subscription, manifest = loadManifest()) {
1101
+ const exists = (0, import_node_fs4.existsSync)(subscription.installedPath);
1102
+ let locallyModified = false;
1103
+ if (exists) {
1104
+ try {
1105
+ const currentHash = hashAssetPath(subscription.installedPath);
1106
+ locallyModified = currentHash !== subscription.installedHash;
1107
+ } catch {
1108
+ locallyModified = false;
1109
+ }
1110
+ }
1111
+ const upstream = manifest.find((m) => m.id === subscription.id);
1112
+ const updateAvailable = Boolean(
1113
+ upstream && upstream.hash !== subscription.sourceHash
1114
+ );
1115
+ return {
1116
+ subscription,
1117
+ exists,
1118
+ locallyModified,
1119
+ updateAvailable,
1120
+ upstreamHash: upstream?.hash
1121
+ };
1122
+ }
1123
+ function listAssetStatuses(filter) {
1124
+ const subscriptions = loadSubscriptions();
1125
+ const manifest = loadManifest();
1126
+ return subscriptions.filter((s) => {
1127
+ if (filter?.target && s.target !== filter.target) return false;
1128
+ if (filter?.scope && s.scope !== filter.scope) return false;
1129
+ return true;
1130
+ }).map((s) => computeAssetStatus(s, manifest));
1131
+ }
1132
+
1133
+ // src/lifecycle/install.ts
1134
+ function installAsset(assetId, options) {
1135
+ if (/[/\\]|\.\./.test(assetId)) {
1136
+ return {
1137
+ id: assetId,
1138
+ target: options.target,
1139
+ scope: options.scope,
1140
+ success: false,
1141
+ action: "failed",
1142
+ reason: `Invalid asset ID '${assetId}': IDs must not contain path separators or traversal sequences.`
1143
+ };
1144
+ }
1145
+ const { target, scope, dryRun = false, force = false, cwd, home } = options;
1146
+ const manifest = loadManifest();
1147
+ const entry = manifest.find((m) => m.id === assetId);
1148
+ if (!entry) {
1149
+ return {
1150
+ id: assetId,
1151
+ target,
1152
+ scope,
1153
+ success: false,
1154
+ action: "failed",
1155
+ reason: `Asset '${assetId}' not found in local cache. Run 'agentsmith sync' first.`
1156
+ };
1157
+ }
1158
+ if (!(0, import_node_fs5.existsSync)(entry.localPath)) {
1159
+ return {
1160
+ id: assetId,
1161
+ target,
1162
+ scope,
1163
+ success: false,
1164
+ action: "failed",
1165
+ reason: `Cached source file missing at '${entry.localPath}'. Run 'agentsmith sync' to repair.`
1166
+ };
1167
+ }
1168
+ const adapter = getTargetAdapter(target);
1169
+ let targetPath;
1170
+ try {
1171
+ targetPath = adapter.resolveTargetPath(
1172
+ entry.id,
1173
+ entry.type,
1174
+ scope,
1175
+ cwd,
1176
+ home
1177
+ );
1178
+ } catch (err) {
1179
+ return {
1180
+ id: assetId,
1181
+ target,
1182
+ scope,
1183
+ success: false,
1184
+ action: "failed",
1185
+ reason: err.message
1186
+ };
1187
+ }
1188
+ if (!targetPath) {
1189
+ return {
1190
+ id: assetId,
1191
+ target,
1192
+ scope,
1193
+ success: false,
1194
+ action: "skipped",
1195
+ reason: `Asset type '${entry.type}' is not supported by target '${target}'.`
1196
+ };
1197
+ }
1198
+ const baseDir = adapter.resolveBaseDir(scope, cwd, home);
1199
+ assertPathWithin(targetPath, baseDir);
1200
+ const existing = findSubscription(entry.id, target, scope, targetPath);
1201
+ if (existing && !force) {
1202
+ const status = computeAssetStatus(existing, manifest);
1203
+ if (status.locallyModified) {
1204
+ return {
1205
+ id: assetId,
1206
+ target,
1207
+ scope,
1208
+ success: false,
1209
+ action: "skipped",
1210
+ reason: `Local modifications detected at '${existing.installedPath}'. Pass --force to overwrite.`
1211
+ };
1212
+ }
1213
+ }
1214
+ const isDir = (0, import_node_fs5.statSync)(entry.localPath).isDirectory();
1215
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1216
+ if (isDir) {
1217
+ if (!existing && !force && (0, import_node_fs5.existsSync)(targetPath)) {
1218
+ try {
1219
+ if (hashAssetPath(targetPath) !== entry.hash) {
1220
+ return {
1221
+ id: assetId,
1222
+ target,
1223
+ scope,
1224
+ success: false,
1225
+ action: "skipped",
1226
+ reason: `Existing untracked asset detected at '${targetPath}'. Pass --force to overwrite.`
1227
+ };
1228
+ }
1229
+ } catch {
1230
+ }
1231
+ }
1232
+ if (!dryRun) {
1233
+ if ((0, import_node_fs5.existsSync)(targetPath)) {
1234
+ (0, import_node_fs5.rmSync)(targetPath, { recursive: true, force: true });
1235
+ }
1236
+ (0, import_node_fs5.mkdirSync)((0, import_node_path8.dirname)(targetPath), { recursive: true });
1237
+ (0, import_node_fs5.cpSync)(entry.localPath, targetPath, {
1238
+ recursive: true,
1239
+ force: true
1240
+ });
1241
+ const installedHash = hashAssetPath(targetPath);
1242
+ upsertSubscription({
1243
+ id: entry.id,
1244
+ type: entry.type,
1245
+ target,
1246
+ scope,
1247
+ installedPath: targetPath,
1248
+ installedHash,
1249
+ sourceHash: entry.hash,
1250
+ installedAt: existing?.installedAt ?? now,
1251
+ updatedAt: now
1252
+ });
1253
+ }
1254
+ return {
1255
+ id: entry.id,
1256
+ target,
1257
+ scope,
1258
+ success: true,
1259
+ action: existing ? "updated" : "installed",
1260
+ adapted: false,
1261
+ adaptations: []
1262
+ };
1263
+ }
1264
+ const rawContent = (0, import_node_fs5.readFileSync)(entry.localPath, "utf-8");
1265
+ const adaptation = adapter.adaptContent(rawContent, entry.type);
1266
+ if (adaptation.outcome === "unsupported") {
1267
+ return {
1268
+ id: entry.id,
1269
+ target,
1270
+ scope,
1271
+ success: false,
1272
+ action: "skipped",
1273
+ reason: adaptation.reason ?? "Unsupported asset format."
1274
+ };
1275
+ }
1276
+ if (!existing && !force && (0, import_node_fs5.existsSync)(targetPath)) {
1277
+ try {
1278
+ if (hashAssetPath(targetPath) !== hashString(adaptation.content)) {
1279
+ return {
1280
+ id: assetId,
1281
+ target,
1282
+ scope,
1283
+ success: false,
1284
+ action: "skipped",
1285
+ reason: `Existing untracked file detected at '${targetPath}'. Pass --force to overwrite.`
1286
+ };
1287
+ }
1288
+ } catch {
1289
+ }
1290
+ }
1291
+ if (!dryRun) {
1292
+ (0, import_node_fs5.mkdirSync)((0, import_node_path8.dirname)(targetPath), { recursive: true });
1293
+ (0, import_node_fs5.writeFileSync)(targetPath, adaptation.content, "utf-8");
1294
+ const installedHash = hashAssetPath(targetPath);
1295
+ upsertSubscription({
1296
+ id: entry.id,
1297
+ type: entry.type,
1298
+ target,
1299
+ scope,
1300
+ installedPath: targetPath,
1301
+ installedHash,
1302
+ sourceHash: entry.hash,
1303
+ installedAt: existing?.installedAt ?? now,
1304
+ updatedAt: now
1305
+ });
1306
+ }
1307
+ return {
1308
+ id: entry.id,
1309
+ target,
1310
+ scope,
1311
+ success: true,
1312
+ action: existing ? "updated" : "installed",
1313
+ adapted: adaptation.outcome === "adapted",
1314
+ adaptations: adaptation.adaptations
1315
+ };
1316
+ }
1317
+
1318
+ // src/lifecycle/update.ts
1319
+ var import_node_path9 = require("path");
1320
+ function inferRepoCwdFromSubscription(subscription) {
1321
+ if (subscription.scope !== "repo") return void 0;
1322
+ const marker = subscription.target === "vscode" ? ".github" : subscription.target === "kiro" ? ".kiro" : ".agents";
1323
+ let current = (0, import_node_path9.resolve)(subscription.installedPath);
1324
+ while (true) {
1325
+ const parent = (0, import_node_path9.dirname)(current);
1326
+ if (parent === current) break;
1327
+ if ((0, import_node_path9.basename)(current) === marker) {
1328
+ return parent;
1329
+ }
1330
+ current = parent;
1331
+ }
1332
+ return void 0;
1333
+ }
1334
+ function updateSubscribedAssets(options = {}) {
1335
+ const statuses = listAssetStatuses({
1336
+ target: options.target,
1337
+ scope: options.scope
1338
+ });
1339
+ const results = [];
1340
+ for (const status of statuses) {
1341
+ const { subscription } = status;
1342
+ if (status.locallyModified && !options.force) {
1343
+ results.push({
1344
+ id: subscription.id,
1345
+ target: subscription.target,
1346
+ scope: subscription.scope,
1347
+ success: false,
1348
+ action: "skipped",
1349
+ reason: `Local modifications detected at '${subscription.installedPath}'. Pass --force to overwrite.`
1350
+ });
1351
+ continue;
1352
+ }
1353
+ if (status.exists && !status.updateAvailable && !options.force) {
1354
+ results.push({
1355
+ id: subscription.id,
1356
+ target: subscription.target,
1357
+ scope: subscription.scope,
1358
+ success: true,
1359
+ action: "skipped",
1360
+ reason: "Already up to date."
1361
+ });
1362
+ continue;
1363
+ }
1364
+ const subCwd = inferRepoCwdFromSubscription(subscription) ?? options.cwd;
1365
+ const res = installAsset(subscription.id, {
1366
+ target: subscription.target,
1367
+ scope: subscription.scope,
1368
+ dryRun: options.dryRun,
1369
+ force: options.force,
1370
+ cwd: subCwd,
1371
+ home: options.home
1372
+ });
1373
+ results.push({
1374
+ ...res,
1375
+ action: res.success ? "updated" : res.action
1376
+ });
1377
+ }
1378
+ return results;
1379
+ }
1380
+
1381
+ // src/lifecycle/remove.ts
1382
+ var import_node_fs6 = require("fs");
1383
+ var import_node_path10 = require("path");
1384
+ function inferRepoCwdFromSubscription2(subscription, target) {
1385
+ if (subscription.scope !== "repo") return void 0;
1386
+ const marker = target === "vscode" ? ".github" : target === "kiro" ? ".kiro" : ".agents";
1387
+ let current = (0, import_node_path10.resolve)(subscription.installedPath);
1388
+ while (true) {
1389
+ const parent = (0, import_node_path10.dirname)(current);
1390
+ if (parent === current) break;
1391
+ if ((0, import_node_path10.basename)(current) === marker) return parent;
1392
+ current = parent;
1393
+ }
1394
+ return void 0;
1395
+ }
1396
+ function removeAsset(assetId, options) {
1397
+ const { target, scope, dryRun = false, cwd, home } = options;
1398
+ if (/[/\\]|\.\./.test(assetId)) {
1399
+ return {
1400
+ id: assetId,
1401
+ target: options.target,
1402
+ scope: options.scope,
1403
+ success: false,
1404
+ action: "failed",
1405
+ reason: `Invalid asset ID '${assetId}': IDs must not contain path separators or traversal sequences.`
1406
+ };
1407
+ }
1408
+ const adapter = getTargetAdapter(target);
1409
+ const subscription = findSubscription(assetId, target, scope);
1410
+ if (!subscription) {
1411
+ return {
1412
+ id: assetId,
1413
+ target,
1414
+ scope,
1415
+ success: false,
1416
+ action: "failed",
1417
+ reason: `Asset '${assetId}' is not installed for target '${target}' (${scope} scope).`
1418
+ };
1419
+ }
1420
+ const inferredCwd = inferRepoCwdFromSubscription2(subscription, target) ?? cwd;
1421
+ const baseDir = adapter.resolveBaseDir(scope, inferredCwd, home);
1422
+ try {
1423
+ assertPathWithin(subscription.installedPath, baseDir);
1424
+ } catch (err) {
1425
+ return {
1426
+ id: assetId,
1427
+ target,
1428
+ scope,
1429
+ success: false,
1430
+ action: "failed",
1431
+ reason: err.message
1432
+ };
1433
+ }
1434
+ if (!dryRun) {
1435
+ if ((0, import_node_fs6.existsSync)(subscription.installedPath)) {
1436
+ (0, import_node_fs6.rmSync)(subscription.installedPath, {
1437
+ recursive: true,
1438
+ force: true
1439
+ });
1440
+ let parentDir = (0, import_node_path10.dirname)(subscription.installedPath);
1441
+ const resolvedBase = (0, import_node_path10.resolve)(baseDir);
1442
+ while ((0, import_node_path10.resolve)(parentDir) === resolvedBase || (0, import_node_path10.resolve)(parentDir).startsWith(resolvedBase + import_node_path10.sep)) {
1443
+ try {
1444
+ if ((0, import_node_fs6.existsSync)(parentDir) && (0, import_node_fs6.readdirSync)(parentDir).length === 0) {
1445
+ (0, import_node_fs6.rmdirSync)(parentDir);
1446
+ parentDir = (0, import_node_path10.dirname)(parentDir);
1447
+ } else {
1448
+ break;
1449
+ }
1450
+ } catch {
1451
+ break;
1452
+ }
1453
+ }
1454
+ }
1455
+ removeSubscriptionRecord(
1456
+ assetId,
1457
+ target,
1458
+ scope,
1459
+ subscription.installedPath
1460
+ );
1461
+ }
1462
+ return {
1463
+ id: assetId,
1464
+ target,
1465
+ scope,
1466
+ success: true,
1467
+ action: "removed"
1468
+ };
1469
+ }
1470
+
1471
+ // src/lifecycle/recommendations.ts
1472
+ var import_node_fs7 = require("fs");
1473
+ var import_node_path11 = require("path");
1474
+ var VENDOR_PREFIXES = [
1475
+ "amplitude",
1476
+ "atlassian",
1477
+ "aws",
1478
+ "azure",
1479
+ "datadog",
1480
+ "drupal",
1481
+ "firebase",
1482
+ "magento",
1483
+ "neon",
1484
+ "pagerduty",
1485
+ "salesforce",
1486
+ "shopify",
1487
+ "snowflake",
1488
+ "strapi",
1489
+ "stripe",
1490
+ "supabase",
1491
+ "twilio",
1492
+ "wordpress"
1493
+ ];
1494
+ var USER_TECH_SPECIFIC_SEGMENTS = [
1495
+ "csharp",
1496
+ "dotnet",
1497
+ "python",
1498
+ "java",
1499
+ "kotlin",
1500
+ "go",
1501
+ "rust",
1502
+ "ruby",
1503
+ "php",
1504
+ "swift",
1505
+ "typescript",
1506
+ "javascript",
1507
+ "react",
1508
+ "angular",
1509
+ "vue",
1510
+ "nextjs",
1511
+ "nuxt",
1512
+ "svelte",
1513
+ "ember",
1514
+ "laravel",
1515
+ "django",
1516
+ "android",
1517
+ "ios",
1518
+ "maui",
1519
+ "electron",
1520
+ "azure",
1521
+ "aws",
1522
+ "gcp",
1523
+ "terraform",
1524
+ "bicep",
1525
+ "kubernetes",
1526
+ "docker",
1527
+ "salesforce",
1528
+ "shopify",
1529
+ "drupal",
1530
+ "wordpress",
1531
+ "postgres",
1532
+ "mysql",
1533
+ "redis",
1534
+ "playwright",
1535
+ "powershell"
1536
+ ];
1537
+ var USER_GENERAL_POSITIVE_SEGMENTS = [
1538
+ "beast",
1539
+ "mode",
1540
+ "critical",
1541
+ "thinking",
1542
+ "review",
1543
+ "reviewer",
1544
+ "doublecheck",
1545
+ "mentor",
1546
+ "plan",
1547
+ "planner",
1548
+ "blueprint",
1549
+ "specification",
1550
+ "architect",
1551
+ "architecture",
1552
+ "tdd",
1553
+ "swe",
1554
+ "qa",
1555
+ "security",
1556
+ "owasp",
1557
+ "safety",
1558
+ "clean",
1559
+ "refactor",
1560
+ "debt",
1561
+ "engineer",
1562
+ "evaluator",
1563
+ "investigator",
1564
+ "documenter",
1565
+ "documentation",
1566
+ "accessibility",
1567
+ "a11y",
1568
+ "performance",
1569
+ "memory",
1570
+ "orchestrator",
1571
+ "debugger",
1572
+ "debug"
1573
+ ];
1574
+ function detectRepoStack(cwd = process.cwd()) {
1575
+ const tags = /* @__PURE__ */ new Set();
1576
+ tags.add("security");
1577
+ tags.add("owasp");
1578
+ if (!(0, import_node_fs7.existsSync)(cwd)) {
1579
+ return Array.from(tags);
1580
+ }
1581
+ try {
1582
+ const entries = (0, import_node_fs7.readdirSync)(cwd, { withFileTypes: true });
1583
+ const fileNames = /* @__PURE__ */ new Set();
1584
+ const extensions = /* @__PURE__ */ new Set();
1585
+ for (const entry of entries) {
1586
+ if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist" || entry.name === "bin" || entry.name === "obj") {
1587
+ continue;
1588
+ }
1589
+ fileNames.add(entry.name.toLowerCase());
1590
+ const dotIdx = entry.name.lastIndexOf(".");
1591
+ if (dotIdx > 0) {
1592
+ extensions.add(entry.name.slice(dotIdx).toLowerCase());
1593
+ }
1594
+ }
1595
+ if (extensions.has(".ts") || extensions.has(".tsx") || fileNames.has("tsconfig.json")) {
1596
+ tags.add("typescript");
1597
+ }
1598
+ if (extensions.has(".js") || extensions.has(".jsx") || extensions.has(".mjs") || fileNames.has("package.json")) {
1599
+ tags.add("javascript");
1600
+ }
1601
+ if (extensions.has(".cs") || extensions.has(".csproj") || extensions.has(".sln")) {
1602
+ tags.add("csharp");
1603
+ tags.add("dotnet");
1604
+ }
1605
+ if (extensions.has(".py") || fileNames.has("requirements.txt") || fileNames.has("pyproject.toml") || fileNames.has("pipfile")) {
1606
+ tags.add("python");
1607
+ }
1608
+ if (extensions.has(".go") || fileNames.has("go.mod")) {
1609
+ tags.add("go");
1610
+ }
1611
+ if (extensions.has(".rs") || fileNames.has("cargo.toml")) {
1612
+ tags.add("rust");
1613
+ }
1614
+ if (extensions.has(".java") || fileNames.has("pom.xml") || fileNames.has("build.gradle")) {
1615
+ tags.add("java");
1616
+ }
1617
+ if (extensions.has(".kt") || extensions.has(".kts")) {
1618
+ tags.add("kotlin");
1619
+ }
1620
+ if (extensions.has(".tf") || fileNames.has("main.tf")) {
1621
+ tags.add("terraform");
1622
+ }
1623
+ if (extensions.has(".bicep")) {
1624
+ tags.add("bicep");
1625
+ tags.add("azure");
1626
+ }
1627
+ if (extensions.has(".ps1") || extensions.has(".psm1")) {
1628
+ tags.add("powershell");
1629
+ }
1630
+ if (fileNames.has("dockerfile") || fileNames.has("docker-compose.yml") || fileNames.has("compose.yaml")) {
1631
+ tags.add("docker");
1632
+ tags.add("container");
1633
+ }
1634
+ if ((0, import_node_fs7.existsSync)((0, import_node_path11.join)(cwd, ".github", "workflows"))) {
1635
+ tags.add("github-actions");
1636
+ }
1637
+ if (fileNames.has("playwright.config.ts") || fileNames.has("playwright.config.js")) {
1638
+ tags.add("playwright");
1639
+ }
1640
+ const pkgPath = (0, import_node_path11.join)(cwd, "package.json");
1641
+ if ((0, import_node_fs7.existsSync)(pkgPath)) {
1642
+ try {
1643
+ const pkg = JSON.parse((0, import_node_fs7.readFileSync)(pkgPath, "utf-8"));
1644
+ const allDeps = {
1645
+ ...pkg.dependencies,
1646
+ ...pkg.devDependencies
1647
+ };
1648
+ const depNames = Object.keys(allDeps).map(
1649
+ (d) => d.toLowerCase()
1650
+ );
1651
+ if (depNames.some(
1652
+ (d) => d === "react" || d.startsWith("@types/react")
1653
+ )) {
1654
+ tags.add("react");
1655
+ }
1656
+ if (depNames.some((d) => d === "next")) {
1657
+ tags.add("nextjs");
1658
+ tags.add("react");
1659
+ }
1660
+ if (depNames.some((d) => d.startsWith("@angular/"))) {
1661
+ tags.add("angular");
1662
+ }
1663
+ if (depNames.some((d) => d === "vue")) {
1664
+ tags.add("vue");
1665
+ }
1666
+ if (depNames.some((d) => d === "nuxt")) {
1667
+ tags.add("nuxt");
1668
+ }
1669
+ if (depNames.some((d) => d === "svelte")) {
1670
+ tags.add("svelte");
1671
+ }
1672
+ if (depNames.some((d) => d.startsWith("@nestjs/"))) {
1673
+ tags.add("nestjs");
1674
+ }
1675
+ if (depNames.some((d) => d === "electron")) {
1676
+ tags.add("electron");
1677
+ }
1678
+ } catch {
1679
+ }
1680
+ }
1681
+ } catch {
1682
+ }
1683
+ return Array.from(tags);
1684
+ }
1685
+ function isRepoRecommended(entry, tags) {
1686
+ if (entry.requiresSetup) {
1687
+ return false;
1688
+ }
1689
+ if (tags.length === 0) {
1690
+ return false;
1691
+ }
1692
+ const segments = entry.id.toLowerCase().split("-");
1693
+ const firstSegment = segments[0] ?? "";
1694
+ if (VENDOR_PREFIXES.includes(firstSegment) && !tags.includes(firstSegment)) {
1695
+ return false;
1696
+ }
1697
+ const tagSet = new Set(tags.map((t) => t.toLowerCase()));
1698
+ let score = 0;
1699
+ for (const segment of segments) {
1700
+ if (tagSet.has(segment)) {
1701
+ score += 2;
1702
+ }
1703
+ }
1704
+ const titleWords = entry.title.toLowerCase().split(/[^a-z0-9_-]+/);
1705
+ for (const word of titleWords) {
1706
+ if (tagSet.has(word)) {
1707
+ score += 2;
1708
+ }
1709
+ }
1710
+ for (const tag of entry.tags) {
1711
+ if (tagSet.has(tag.toLowerCase())) {
1712
+ score += 2;
1713
+ }
1714
+ }
1715
+ const descWords = entry.description.toLowerCase().split(/[^a-z0-9_-]+/);
1716
+ for (const word of descWords) {
1717
+ if (tagSet.has(word)) {
1718
+ score += 1;
1719
+ }
1720
+ }
1721
+ return score >= 2;
1722
+ }
1723
+ function isUserRecommended(entry) {
1724
+ if (entry.requiresSetup) {
1725
+ return false;
1726
+ }
1727
+ const idLower = entry.id.toLowerCase();
1728
+ const titleLower = entry.title.toLowerCase();
1729
+ const descLower = entry.description.toLowerCase();
1730
+ const segments = idLower.split("-");
1731
+ for (const tech of USER_TECH_SPECIFIC_SEGMENTS) {
1732
+ if (segments.includes(tech)) {
1733
+ return false;
1734
+ }
1735
+ const regex = new RegExp(`\\b${tech}\\b`, "i");
1736
+ if (regex.test(titleLower)) {
1737
+ return false;
1738
+ }
1739
+ }
1740
+ for (const pos of USER_GENERAL_POSITIVE_SEGMENTS) {
1741
+ if (segments.includes(pos)) {
1742
+ return true;
1743
+ }
1744
+ const regex = new RegExp(`\\b${pos}\\b`, "i");
1745
+ if (regex.test(titleLower)) {
1746
+ return true;
1747
+ }
1748
+ }
1749
+ const positiveDescPatterns = [
1750
+ /\bcode review\b/i,
1751
+ /\bclean code\b/i,
1752
+ /\brefactor\b/i,
1753
+ /\bdebugging\b/i,
1754
+ /\bunit test\b/i,
1755
+ /\bsoftware architect\b/i,
1756
+ /\bdesign pattern\b/i,
1757
+ /\bsecurity audit\b/i,
1758
+ /\baccessibility\b/i,
1759
+ /\ba11y\b/i,
1760
+ /\bdocumentation\b/i
1761
+ ];
1762
+ for (const pattern of positiveDescPatterns) {
1763
+ if (pattern.test(descLower)) {
1764
+ return true;
1765
+ }
1766
+ }
1767
+ return false;
1768
+ }
1769
+ function getRecommendedAssetIds(catalogue, scope, cwd = process.cwd()) {
1770
+ const recommended = /* @__PURE__ */ new Set();
1771
+ if (scope === "user") {
1772
+ for (const entry of catalogue) {
1773
+ if (isUserRecommended(entry)) {
1774
+ recommended.add(entry.id);
1775
+ }
1776
+ }
1777
+ } else {
1778
+ const stackTags = detectRepoStack(cwd);
1779
+ for (const entry of catalogue) {
1780
+ if (isRepoRecommended(entry, stackTags)) {
1781
+ recommended.add(entry.id);
1782
+ }
1783
+ }
1784
+ }
1785
+ return recommended;
1786
+ }
1787
+
1788
+ // src/cli/detect.ts
1789
+ var import_node_fs8 = require("fs");
1790
+ var import_node_path13 = require("path");
1791
+
1792
+ // src/cli/picker.ts
1793
+ var import_prompts = require("@inquirer/prompts");
1794
+ var import_node_os5 = require("os");
1795
+ var import_node_path12 = require("path");
1796
+ function formatAssetBadges(options) {
1797
+ const badges = [];
1798
+ if (options.recommended) badges.push("\u2605");
1799
+ if (options.installed) badges.push("[*]");
1800
+ if (options.updateAvailable) badges.push("[\u2191]");
1801
+ if (options.locallyModified) badges.push("[~]");
1802
+ if (options.requiresSetup) badges.push("[!]");
1803
+ return badges.join(" ");
1804
+ }
1805
+ function formatStatusLine(status, catalogueEntry) {
1806
+ const { subscription } = status;
1807
+ const badgeStr = formatAssetBadges({
1808
+ installed: status.exists,
1809
+ updateAvailable: status.updateAvailable,
1810
+ locallyModified: status.locallyModified,
1811
+ requiresSetup: catalogueEntry?.requiresSetup
1812
+ });
1813
+ const missingTag = status.exists ? "" : " [missing]";
1814
+ const prefix = badgeStr ? `${badgeStr} ` : "";
1815
+ const typeLabel = getTargetTypeLabel(
1816
+ subscription.type,
1817
+ subscription.target
1818
+ );
1819
+ return `${prefix}${subscription.id} (${typeLabel}) -> ${subscription.target}:${subscription.scope}${missingTag}`;
1820
+ }
1821
+ function cleanDescription(desc) {
1822
+ return desc.replace(/\r?\n\s*[-*•+]\s*/g, " ").replace(/\r?\n/g, " ").replace(/\s+/g, " ").trim();
1823
+ }
1824
+ function truncateAndPad(str, width) {
1825
+ if (str.length > width) {
1826
+ return `${str.slice(0, Math.max(0, width - 1))}\u2026`;
1827
+ }
1828
+ return str.padEnd(width);
1829
+ }
1830
+ function centreAndPad(str, width) {
1831
+ if (str.length >= width) {
1832
+ return str;
1833
+ }
1834
+ const remaining = width - str.length;
1835
+ const padLeft = Math.floor(remaining / 2);
1836
+ const padRight = remaining - padLeft;
1837
+ return " ".repeat(padLeft) + str + " ".repeat(padRight);
1838
+ }
1839
+ function getTargetDisplayPath(assetId, type, target, scope = "repo") {
1840
+ const adapter = getTargetAdapter(target);
1841
+ const resolved = adapter.resolveTargetPath(assetId, type, scope);
1842
+ if (!resolved) return "";
1843
+ const cwd = process.cwd();
1844
+ const home = (0, import_node_os5.homedir)();
1845
+ if (scope === "user" && resolved.startsWith(home)) {
1846
+ return `~${resolved.slice(home.length).replace(/\\/g, "/")}`;
1847
+ }
1848
+ const rel = (0, import_node_path12.relative)(cwd, resolved).replace(/\\/g, "/");
1849
+ return rel;
1850
+ }
1851
+ var TECH_ALIASES = {
1852
+ ts: ["typescript"],
1853
+ js: ["javascript"],
1854
+ py: ["python"],
1855
+ rb: ["ruby"],
1856
+ rs: ["rust"],
1857
+ cs: ["csharp", "dotnet"],
1858
+ tf: ["terraform"],
1859
+ k8s: ["kubernetes"],
1860
+ gh: ["github"]
1861
+ };
1862
+ function escapeRegExp(str) {
1863
+ return str.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
1864
+ }
1865
+ function filterCatalogueBySearch(catalogue, query, target) {
1866
+ const trimmed = query.trim().toLowerCase();
1867
+ if (!trimmed) return [...catalogue];
1868
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
1869
+ const scored = [];
1870
+ for (const entry of catalogue) {
1871
+ const idLower = entry.id.toLowerCase();
1872
+ const titleLower = entry.title.toLowerCase();
1873
+ const descLower = entry.description.toLowerCase();
1874
+ const idSegments = idLower.split(/[-_]/).filter(Boolean);
1875
+ const acronym = idSegments.map((s) => s[0]).join("");
1876
+ const targetTypeLabel = getTargetTypeLabel(
1877
+ entry.type,
1878
+ target
1879
+ ).toLowerCase();
1880
+ const targetTypePlural = getTargetTypePlural(
1881
+ entry.type,
1882
+ target
1883
+ ).toLowerCase();
1884
+ const canonicalType = entry.type.toLowerCase();
1885
+ const tags = entry.tags.map((t) => t.toLowerCase());
1886
+ let totalScore = 0;
1887
+ let allTokensMatch = true;
1888
+ for (const token of tokens) {
1889
+ let tokenScore = 0;
1890
+ const fullWordRegex = new RegExp(
1891
+ `\\b${escapeRegExp(token)}\\b`,
1892
+ "i"
1893
+ );
1894
+ const prefixWordRegex = new RegExp(
1895
+ `\\b${escapeRegExp(token)}`,
1896
+ "i"
1897
+ );
1898
+ if (idLower === token) {
1899
+ tokenScore += 100;
1900
+ } else if (idSegments.some((s) => s === token)) {
1901
+ tokenScore += 60;
1902
+ } else if (idSegments.some((s) => s.startsWith(token))) {
1903
+ tokenScore += 40;
1904
+ } else if (token.length > 2 && idLower.includes(token)) {
1905
+ tokenScore += 30;
1906
+ }
1907
+ if (fullWordRegex.test(titleLower)) {
1908
+ tokenScore += 50;
1909
+ } else if (prefixWordRegex.test(titleLower)) {
1910
+ tokenScore += 35;
1911
+ }
1912
+ if (token === targetTypeLabel || token === targetTypePlural || token === canonicalType || token === "instructions" && canonicalType === "instruction" || token === "rules" && canonicalType === "instruction" || token === "steering" && canonicalType === "instruction") {
1913
+ tokenScore += 40;
1914
+ }
1915
+ if (tags.some((t) => t === token)) {
1916
+ tokenScore += 45;
1917
+ } else if (tags.some((t) => token.length > 2 && t.includes(token))) {
1918
+ tokenScore += 25;
1919
+ }
1920
+ if (fullWordRegex.test(descLower)) {
1921
+ tokenScore += 20;
1922
+ }
1923
+ if (tokenScore === 0 && token.length >= 2 && token.length <= 4 && acronym === token) {
1924
+ tokenScore += 35;
1925
+ }
1926
+ if (tokenScore === 0 && TECH_ALIASES[token]) {
1927
+ for (const alias of TECH_ALIASES[token] ?? []) {
1928
+ if (idLower.includes(alias) || tags.includes(alias) || descLower.includes(alias)) {
1929
+ tokenScore += 30;
1930
+ break;
1931
+ }
1932
+ }
1933
+ }
1934
+ if (tokenScore === 0) {
1935
+ allTokensMatch = false;
1936
+ break;
1937
+ }
1938
+ totalScore += tokenScore;
1939
+ }
1940
+ if (allTokensMatch && totalScore > 0) {
1941
+ scored.push({ entry, score: totalScore });
1942
+ }
1943
+ }
1944
+ scored.sort(
1945
+ (a, b) => b.score - a.score || a.entry.title.localeCompare(b.entry.title)
1946
+ );
1947
+ return scored.map((s) => s.entry);
1948
+ }
1949
+ function renderAssetCheckboxPicker(catalogue, target, scope, statusById, recommendedIds) {
1950
+ const sortedCatalogue = [...catalogue].sort((a, b) => {
1951
+ const aRec = recommendedIds.has(a.id) ? 0 : 1;
1952
+ const bRec = recommendedIds.has(b.id) ? 0 : 1;
1953
+ if (aRec !== bRec) return aRec - bRec;
1954
+ const aInst = statusById.get(a.id)?.exists ? 0 : 1;
1955
+ const bInst = statusById.get(b.id)?.exists ? 0 : 1;
1956
+ if (aInst !== bInst) return aInst - bInst;
1957
+ return a.title.localeCompare(b.title);
1958
+ });
1959
+ const iconsWidth = 7;
1960
+ const typeWidth = 15;
1961
+ const header = " " + centreAndPad("ICONS", iconsWidth) + " " + centreAndPad("TYPE", typeWidth) + " ASSET NAME";
1962
+ const choices = sortedCatalogue.map((entry) => {
1963
+ const st = statusById.get(entry.id);
1964
+ const isRec = recommendedIds.has(entry.id);
1965
+ const badges = formatAssetBadges({
1966
+ installed: Boolean(st?.exists),
1967
+ updateAvailable: Boolean(st?.updateAvailable),
1968
+ locallyModified: Boolean(st?.locallyModified),
1969
+ requiresSetup: entry.requiresSetup,
1970
+ recommended: isRec
1971
+ });
1972
+ const targetTypeLabel = getTargetTypeLabel(entry.type, target);
1973
+ const displayPath = getTargetDisplayPath(
1974
+ entry.id,
1975
+ entry.type,
1976
+ target,
1977
+ scope
1978
+ );
1979
+ const iconsCol = centreAndPad(badges, iconsWidth);
1980
+ const typeCol = centreAndPad(`[${targetTypeLabel}]`, typeWidth);
1981
+ const rowName = `${iconsCol} ${typeCol} ${entry.title}`;
1982
+ const sanitizedDesc = cleanDescription(entry.description);
1983
+ const descriptionLines = [
1984
+ `Target: ${displayPath} (${target}:${scope})`,
1985
+ `Description: ${sanitizedDesc}`
1986
+ ];
1987
+ return {
1988
+ name: rowName,
1989
+ value: entry.id,
1990
+ checked: isRec && !st?.exists,
1991
+ description: descriptionLines.join("\n")
1992
+ };
1993
+ });
1994
+ const recCount = sortedCatalogue.filter(
1995
+ (e) => recommendedIds.has(e.id)
1996
+ ).length;
1997
+ const recNote = recCount > 0 ? ` (${recCount} recommended \u2605)` : "";
1998
+ return (0, import_prompts.checkbox)({
1999
+ message: `Select assets to install for ${target} (${scope} scope)${recNote}:`,
2000
+ choices,
2001
+ pageSize: 15,
2002
+ theme: {
2003
+ style: {
2004
+ message: (text, status) => {
2005
+ if (status === "done") return text;
2006
+ return `${text}
2007
+ ${header}`;
2008
+ }
2009
+ }
2010
+ }
2011
+ });
2012
+ }
2013
+ async function promptSelectAssetsToInstall(catalogue, statuses, target, options = {}) {
2014
+ const opts = options instanceof Set ? { recommendedIds: options } : options;
2015
+ const recommendedIds = opts.recommendedIds ?? /* @__PURE__ */ new Set();
2016
+ const currentScope = opts.scope ?? "repo";
2017
+ const scopeContext = currentScope === "user" ? "user profile" : "this repository";
2018
+ const statusById = new Map(
2019
+ statuses.filter((s) => s.subscription.target === target).map((s) => [s.subscription.id, s])
2020
+ );
2021
+ if (opts.searchQuery) {
2022
+ const workingCatalogue = filterCatalogueBySearch(
2023
+ catalogue,
2024
+ opts.searchQuery,
2025
+ target
2026
+ );
2027
+ if (workingCatalogue.length === 0) {
2028
+ console.log(`No assets found matching '${opts.searchQuery}'.`);
2029
+ return [];
2030
+ }
2031
+ return renderAssetCheckboxPicker(
2032
+ workingCatalogue,
2033
+ target,
2034
+ currentScope,
2035
+ statusById,
2036
+ recommendedIds
2037
+ );
2038
+ }
2039
+ if (opts.typeFilter) {
2040
+ const workingCatalogue = catalogue.filter(
2041
+ (e) => e.type === opts.typeFilter || opts.typeFilter === "instruction" && e.type === "rule"
2042
+ );
2043
+ return renderAssetCheckboxPicker(
2044
+ workingCatalogue,
2045
+ target,
2046
+ currentScope,
2047
+ statusById,
2048
+ recommendedIds
2049
+ );
2050
+ }
2051
+ while (true) {
2052
+ let workingCatalogue = [...catalogue];
2053
+ if (!opts.skipFilterMenu && catalogue.length > 25) {
2054
+ const instructionPlural = getTargetTypePlural(
2055
+ "instruction",
2056
+ target
2057
+ );
2058
+ const instructionCount = catalogue.filter(
2059
+ (e) => e.type === "instruction" || e.type === "rule"
2060
+ ).length;
2061
+ const agentCount = catalogue.filter(
2062
+ (e) => e.type === "agent"
2063
+ ).length;
2064
+ const skillCount = catalogue.filter(
2065
+ (e) => e.type === "skill"
2066
+ ).length;
2067
+ const recCount = catalogue.filter(
2068
+ (e) => recommendedIds.has(e.id)
2069
+ ).length;
2070
+ const filterMode = await (0, import_prompts.select)({
2071
+ message: `What would you like to install for ${target} (${scopeContext})?`,
2072
+ choices: [
2073
+ ...recCount > 0 ? [
2074
+ {
2075
+ name: `\u2605 Recommended for ${scopeContext} (${recCount} items)`,
2076
+ value: "recommended"
2077
+ }
2078
+ ] : [],
2079
+ {
2080
+ name: `\u{1F50D} Search by keyword / fuzzy match...`,
2081
+ value: "search"
2082
+ },
2083
+ {
2084
+ name: `All ${instructionPlural} (${instructionCount} items)`,
2085
+ value: "instruction"
2086
+ },
2087
+ {
2088
+ name: `All agents (${agentCount} items)`,
2089
+ value: "agent"
2090
+ },
2091
+ {
2092
+ name: `All skills (${skillCount} items)`,
2093
+ value: "skill"
2094
+ },
2095
+ {
2096
+ name: `Browse everything (${catalogue.length} assets)`,
2097
+ value: "all"
2098
+ },
2099
+ {
2100
+ name: `\u2716 Cancel`,
2101
+ value: "cancel"
2102
+ }
2103
+ ]
2104
+ });
2105
+ if (filterMode === "cancel") {
2106
+ return [];
2107
+ }
2108
+ if (filterMode === "recommended") {
2109
+ workingCatalogue = catalogue.filter(
2110
+ (e) => recommendedIds.has(e.id)
2111
+ );
2112
+ } else if (filterMode === "search") {
2113
+ const query = await (0, import_prompts.input)({
2114
+ message: `Search assets (or press Enter to return):`
2115
+ });
2116
+ if (!query.trim()) {
2117
+ continue;
2118
+ }
2119
+ workingCatalogue = filterCatalogueBySearch(
2120
+ catalogue,
2121
+ query,
2122
+ target
2123
+ );
2124
+ if (workingCatalogue.length === 0) {
2125
+ console.log(`No assets found matching '${query}'.`);
2126
+ continue;
2127
+ }
2128
+ } else if (filterMode === "instruction") {
2129
+ workingCatalogue = catalogue.filter(
2130
+ (e) => e.type === "instruction" || e.type === "rule"
2131
+ );
2132
+ } else if (filterMode === "agent") {
2133
+ workingCatalogue = catalogue.filter((e) => e.type === "agent");
2134
+ } else if (filterMode === "skill") {
2135
+ workingCatalogue = catalogue.filter((e) => e.type === "skill");
2136
+ }
2137
+ }
2138
+ const selectedIds = await renderAssetCheckboxPicker(
2139
+ workingCatalogue,
2140
+ target,
2141
+ currentScope,
2142
+ statusById,
2143
+ recommendedIds
2144
+ );
2145
+ if (selectedIds.length > 0) {
2146
+ return selectedIds;
2147
+ }
2148
+ if (!opts.skipFilterMenu && catalogue.length > 25) {
2149
+ const nextAction = await (0, import_prompts.select)({
2150
+ message: "No assets were selected. What would you like to do?",
2151
+ choices: [
2152
+ { name: "\u2190 Back to category / search menu", value: "back" },
2153
+ { name: "\u2716 Cancel installation", value: "cancel" }
2154
+ ]
2155
+ });
2156
+ if (nextAction === "back") {
2157
+ continue;
2158
+ }
2159
+ }
2160
+ return [];
2161
+ }
2162
+ }
2163
+ async function promptSelectAssetsToRemove(subscriptions) {
2164
+ if (subscriptions.length === 0) return [];
2165
+ const typeWidth = 15;
2166
+ const header = " " + centreAndPad("TYPE", typeWidth) + " " + truncateAndPad("ASSET ID", 28) + " ENVIRONMENT";
2167
+ const choices = subscriptions.map((sub) => {
2168
+ const typeLabel = getTargetTypeLabel(sub.type, sub.target);
2169
+ const typeCol = centreAndPad(`[${typeLabel}]`, typeWidth);
2170
+ const idCol = truncateAndPad(sub.id, 28);
2171
+ const envCol = `${sub.target}:${sub.scope}`;
2172
+ return {
2173
+ name: `${typeCol} ${idCol} ${envCol}`,
2174
+ value: sub.id,
2175
+ description: `Target: ${sub.installedPath} (${sub.target}:${sub.scope})`
2176
+ };
2177
+ });
2178
+ return (0, import_prompts.checkbox)({
2179
+ message: "Select installed assets to remove:",
2180
+ choices,
2181
+ pageSize: 15,
2182
+ theme: {
2183
+ style: {
2184
+ message: (text, status) => {
2185
+ if (status === "done") return text;
2186
+ return `${text}
2187
+ ${header}`;
2188
+ }
2189
+ }
2190
+ }
2191
+ });
2192
+ }
2193
+ async function promptSelectTarget(targets = ALL_TARGETS) {
2194
+ const choices = (targets.length > 0 ? targets : ALL_TARGETS).map((t) => ({
2195
+ name: t,
2196
+ value: t
2197
+ }));
2198
+ choices.push({
2199
+ name: "\u2716 Cancel",
2200
+ value: "cancel"
2201
+ });
2202
+ const chosen = await (0, import_prompts.select)({
2203
+ message: "Select target environment:",
2204
+ choices
2205
+ });
2206
+ if (chosen === "cancel") {
2207
+ const cancelErr = new Error("Prompt was cancelled");
2208
+ cancelErr.name = "CancelPromptError";
2209
+ throw cancelErr;
2210
+ }
2211
+ return chosen;
2212
+ }
2213
+
2214
+ // src/cli/detect.ts
2215
+ function detectTargets(cwd = process.cwd(), fallbackToDefault = true) {
2216
+ const detected = [];
2217
+ if ((0, import_node_fs8.existsSync)((0, import_node_path13.join)(cwd, ".github"))) {
2218
+ detected.push("vscode");
2219
+ }
2220
+ if ((0, import_node_fs8.existsSync)((0, import_node_path13.join)(cwd, ".kiro"))) {
2221
+ detected.push("kiro");
2222
+ }
2223
+ if ((0, import_node_fs8.existsSync)((0, import_node_path13.join)(cwd, ".agents")) || (0, import_node_fs8.existsSync)((0, import_node_path13.join)(cwd, ".gemini"))) {
2224
+ detected.push("antigravity");
2225
+ }
2226
+ if (detected.length === 0 && fallbackToDefault) {
2227
+ return ["vscode"];
2228
+ }
2229
+ return detected;
2230
+ }
2231
+ async function resolveTarget(explicitTarget, cwd = process.cwd(), promptFn = promptSelectTarget) {
2232
+ if (explicitTarget) {
2233
+ return explicitTarget;
2234
+ }
2235
+ const detected = detectTargets(cwd, false);
2236
+ if (detected.length === 1) {
2237
+ return detected[0];
2238
+ }
2239
+ const choices = detected.length > 1 ? detected : [...ALL_TARGETS];
2240
+ return promptFn(choices);
2241
+ }
2242
+
2243
+ // src/index.ts
2244
+ var VERSION = "0.1.0";
2245
+ // Annotate the CommonJS export names for ESM import in node:
2246
+ 0 && (module.exports = {
2247
+ ALL_TARGETS,
2248
+ AWESOME_COPILOT_REPO_URL,
2249
+ MASS_REMOVAL_THRESHOLD,
2250
+ SOURCE_NAME,
2251
+ TARGET_TERMINOLOGY,
2252
+ USER_GENERAL_POSITIVE_SEGMENTS,
2253
+ USER_TECH_SPECIFIC_SEGMENTS,
2254
+ VENDOR_PREFIXES,
2255
+ VERSION,
2256
+ assertPathWithin,
2257
+ awesomeCopilotRoot,
2258
+ cacheRoot,
2259
+ cataloguePath,
2260
+ centreAndPad,
2261
+ cleanDescription,
2262
+ computeAssetStatus,
2263
+ detectRepoStack,
2264
+ detectTargets,
2265
+ ensureAwesomeCopilotRepo,
2266
+ filterCatalogueBySearch,
2267
+ findSubscription,
2268
+ formatAssetBadges,
2269
+ formatStatusLine,
2270
+ getRecommendedAssetIds,
2271
+ getTargetAdapter,
2272
+ getTargetDisplayPath,
2273
+ getTargetTypeLabel,
2274
+ getTargetTypePlural,
2275
+ hashAssetPath,
2276
+ hashDirectory,
2277
+ hashFile,
2278
+ hashString,
2279
+ installAsset,
2280
+ isRepoRecommended,
2281
+ isUserRecommended,
2282
+ isValidScope,
2283
+ isValidTarget,
2284
+ legacyCacheRoot,
2285
+ listAssetStatuses,
2286
+ loadCatalogue,
2287
+ loadManifest,
2288
+ loadSubscriptions,
2289
+ manifestPath,
2290
+ normaliseTargetAssetType,
2291
+ parseFrontmatter,
2292
+ promptSelectAssetsToInstall,
2293
+ promptSelectAssetsToRemove,
2294
+ promptSelectTarget,
2295
+ removeAsset,
2296
+ removeSubscriptionRecord,
2297
+ resolveTarget,
2298
+ saveSubscriptions,
2299
+ scanAwesomeCopilotRepo,
2300
+ serialiseFrontmatter,
2301
+ subscriptionsPath,
2302
+ syncAwesomeCopilot,
2303
+ truncateAndPad,
2304
+ updateSubscribedAssets,
2305
+ upsertSubscription,
2306
+ validateSyncSafety
2307
+ });
2308
+ //# sourceMappingURL=index.cjs.map