skilld 2.3.0 → 3.0.0-beta.2

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.
Files changed (146) hide show
  1. package/README.md +142 -353
  2. package/bin/skilld.mjs +56 -0
  3. package/loader/resolve-artifact.mjs +37 -0
  4. package/package.json +28 -55
  5. package/dist/_chunks/add.mjs +0 -95
  6. package/dist/_chunks/add.mjs.map +0 -1
  7. package/dist/_chunks/agent-prompt.mjs +0 -90
  8. package/dist/_chunks/agent-prompt.mjs.map +0 -1
  9. package/dist/_chunks/agent.mjs +0 -1817
  10. package/dist/_chunks/agent.mjs.map +0 -1
  11. package/dist/_chunks/args.mjs +0 -49
  12. package/dist/_chunks/args.mjs.map +0 -1
  13. package/dist/_chunks/assemble.mjs +0 -126
  14. package/dist/_chunks/assemble.mjs.map +0 -1
  15. package/dist/_chunks/author.mjs +0 -432
  16. package/dist/_chunks/author.mjs.map +0 -1
  17. package/dist/_chunks/cache.mjs +0 -367
  18. package/dist/_chunks/cache.mjs.map +0 -1
  19. package/dist/_chunks/cache2.mjs +0 -151
  20. package/dist/_chunks/cache2.mjs.map +0 -1
  21. package/dist/_chunks/changes-digest.mjs +0 -49
  22. package/dist/_chunks/changes-digest.mjs.map +0 -1
  23. package/dist/_chunks/changes.mjs +0 -23
  24. package/dist/_chunks/changes.mjs.map +0 -1
  25. package/dist/_chunks/client.mjs +0 -182
  26. package/dist/_chunks/client.mjs.map +0 -1
  27. package/dist/_chunks/core.mjs +0 -13
  28. package/dist/_chunks/detect.mjs +0 -614
  29. package/dist/_chunks/detect.mjs.map +0 -1
  30. package/dist/_chunks/detect2.mjs +0 -2
  31. package/dist/_chunks/eject.mjs +0 -69
  32. package/dist/_chunks/eject.mjs.map +0 -1
  33. package/dist/_chunks/embedding-cache.mjs +0 -2
  34. package/dist/_chunks/embedding-cache2.mjs +0 -61
  35. package/dist/_chunks/embedding-cache2.mjs.map +0 -1
  36. package/dist/_chunks/env.mjs +0 -19
  37. package/dist/_chunks/env.mjs.map +0 -1
  38. package/dist/_chunks/index-identity.mjs +0 -365
  39. package/dist/_chunks/index-identity.mjs.map +0 -1
  40. package/dist/_chunks/index-identity2.mjs +0 -2
  41. package/dist/_chunks/install-many.mjs +0 -542
  42. package/dist/_chunks/install-many.mjs.map +0 -1
  43. package/dist/_chunks/install.mjs +0 -259
  44. package/dist/_chunks/install.mjs.map +0 -1
  45. package/dist/_chunks/intro.mjs +0 -63
  46. package/dist/_chunks/intro.mjs.map +0 -1
  47. package/dist/_chunks/list.mjs +0 -102
  48. package/dist/_chunks/list.mjs.map +0 -1
  49. package/dist/_chunks/lockfile.mjs +0 -174
  50. package/dist/_chunks/lockfile.mjs.map +0 -1
  51. package/dist/_chunks/login.mjs +0 -247
  52. package/dist/_chunks/login.mjs.map +0 -1
  53. package/dist/_chunks/logout.mjs +0 -27
  54. package/dist/_chunks/logout.mjs.map +0 -1
  55. package/dist/_chunks/map.mjs +0 -11
  56. package/dist/_chunks/map.mjs.map +0 -1
  57. package/dist/_chunks/markdown.mjs +0 -101
  58. package/dist/_chunks/markdown.mjs.map +0 -1
  59. package/dist/_chunks/menu.mjs +0 -33
  60. package/dist/_chunks/menu.mjs.map +0 -1
  61. package/dist/_chunks/model-picker.mjs +0 -61
  62. package/dist/_chunks/model-picker.mjs.map +0 -1
  63. package/dist/_chunks/monorepo.mjs +0 -74
  64. package/dist/_chunks/monorepo.mjs.map +0 -1
  65. package/dist/_chunks/package-json.mjs +0 -84
  66. package/dist/_chunks/package-json.mjs.map +0 -1
  67. package/dist/_chunks/paths.mjs +0 -47
  68. package/dist/_chunks/paths.mjs.map +0 -1
  69. package/dist/_chunks/pipeline.mjs +0 -993
  70. package/dist/_chunks/pipeline.mjs.map +0 -1
  71. package/dist/_chunks/pool.mjs +0 -2
  72. package/dist/_chunks/pool2.mjs +0 -121
  73. package/dist/_chunks/pool2.mjs.map +0 -1
  74. package/dist/_chunks/portable.mjs +0 -152
  75. package/dist/_chunks/portable.mjs.map +0 -1
  76. package/dist/_chunks/prepare-hook.mjs +0 -2
  77. package/dist/_chunks/prepare-hook2.mjs +0 -61
  78. package/dist/_chunks/prepare-hook2.mjs.map +0 -1
  79. package/dist/_chunks/prepare.mjs +0 -113
  80. package/dist/_chunks/prepare.mjs.map +0 -1
  81. package/dist/_chunks/prepare2.mjs +0 -80
  82. package/dist/_chunks/prepare2.mjs.map +0 -1
  83. package/dist/_chunks/prompts.mjs +0 -1252
  84. package/dist/_chunks/prompts.mjs.map +0 -1
  85. package/dist/_chunks/pull.mjs +0 -190
  86. package/dist/_chunks/pull.mjs.map +0 -1
  87. package/dist/_chunks/regex.mjs +0 -19
  88. package/dist/_chunks/regex.mjs.map +0 -1
  89. package/dist/_chunks/retriv.mjs +0 -2
  90. package/dist/_chunks/retriv2.mjs +0 -177
  91. package/dist/_chunks/retriv2.mjs.map +0 -1
  92. package/dist/_chunks/sanitize.mjs +0 -260
  93. package/dist/_chunks/sanitize.mjs.map +0 -1
  94. package/dist/_chunks/search-helpers.mjs +0 -88
  95. package/dist/_chunks/search-helpers.mjs.map +0 -1
  96. package/dist/_chunks/search-interactive.mjs +0 -249
  97. package/dist/_chunks/search-interactive.mjs.map +0 -1
  98. package/dist/_chunks/search.mjs +0 -247
  99. package/dist/_chunks/search.mjs.map +0 -1
  100. package/dist/_chunks/semver.mjs +0 -2831
  101. package/dist/_chunks/semver.mjs.map +0 -1
  102. package/dist/_chunks/skill-installer.mjs +0 -2
  103. package/dist/_chunks/skill-installer2.mjs +0 -163
  104. package/dist/_chunks/skill-installer2.mjs.map +0 -1
  105. package/dist/_chunks/skills.mjs +0 -187
  106. package/dist/_chunks/skills.mjs.map +0 -1
  107. package/dist/_chunks/store.mjs +0 -107
  108. package/dist/_chunks/store.mjs.map +0 -1
  109. package/dist/_chunks/sync.mjs +0 -1009
  110. package/dist/_chunks/sync.mjs.map +0 -1
  111. package/dist/_chunks/sync2.mjs +0 -2
  112. package/dist/_chunks/telemetry.mjs +0 -26
  113. package/dist/_chunks/telemetry.mjs.map +0 -1
  114. package/dist/_chunks/uninstall.mjs +0 -214
  115. package/dist/_chunks/uninstall.mjs.map +0 -1
  116. package/dist/_chunks/update.mjs +0 -133
  117. package/dist/_chunks/update.mjs.map +0 -1
  118. package/dist/_chunks/upload.mjs +0 -155
  119. package/dist/_chunks/upload.mjs.map +0 -1
  120. package/dist/_chunks/validate.mjs +0 -60
  121. package/dist/_chunks/validate.mjs.map +0 -1
  122. package/dist/_chunks/version.mjs +0 -19
  123. package/dist/_chunks/version.mjs.map +0 -1
  124. package/dist/_chunks/watch.mjs +0 -2
  125. package/dist/_chunks/watch2.mjs +0 -118
  126. package/dist/_chunks/watch2.mjs.map +0 -1
  127. package/dist/_chunks/whoami.mjs +0 -21
  128. package/dist/_chunks/whoami.mjs.map +0 -1
  129. package/dist/_chunks/wizard.mjs +0 -2
  130. package/dist/_chunks/wizard2.mjs +0 -200
  131. package/dist/_chunks/wizard2.mjs.map +0 -1
  132. package/dist/_chunks/yaml.mjs +0 -33
  133. package/dist/_chunks/yaml.mjs.map +0 -1
  134. package/dist/cli-entry.d.mts +0 -1
  135. package/dist/cli-entry.mjs +0 -5
  136. package/dist/cli-entry.mjs.map +0 -1
  137. package/dist/cli.d.mts +0 -1
  138. package/dist/cli.mjs +0 -1330
  139. package/dist/cli.mjs.map +0 -1
  140. package/dist/prepare.d.mts +0 -1
  141. package/dist/prepare.mjs +0 -84
  142. package/dist/prepare.mjs.map +0 -1
  143. package/dist/retriv/worker.d.mts +0 -37
  144. package/dist/retriv/worker.d.mts.map +0 -1
  145. package/dist/retriv/worker.mjs +0 -46
  146. package/dist/retriv/worker.mjs.map +0 -1
@@ -1,367 +0,0 @@
1
- import { defaultFeatures, hasIndexEmbeddingIdentity, readConfig, resolveEmbeddingIdentity } from "./index-identity.mjs";
2
- import { REFERENCES_DIR, REPOS_DIR, getPackageDbPath, getRepoCacheDir, skillInternalDir } from "./paths.mjs";
3
- import { sanitizeMarkdown } from "./sanitize.mjs";
4
- import { getCacheDir, getPkgKeyFiles, getVersionKey, hasShippedDocs, resolvePkgDir } from "./prepare.mjs";
5
- import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
6
- import { dirname, join, resolve } from "pathe";
7
- const STATIC_REGEX_1 = /^issues\/issue-(\d+)\.md$/;
8
- const STATIC_REGEX_2 = /^discussions\/discussion-(\d+)\.md$/;
9
- function classifyCachedDoc(path) {
10
- const issueMatch = path.match(STATIC_REGEX_1);
11
- if (issueMatch) return {
12
- type: "issue",
13
- number: Number(issueMatch[1])
14
- };
15
- const discussionMatch = path.match(STATIC_REGEX_2);
16
- if (discussionMatch) return {
17
- type: "discussion",
18
- number: Number(discussionMatch[1])
19
- };
20
- if (path.startsWith("releases/")) return { type: "release" };
21
- return { type: "doc" };
22
- }
23
- function safeSymlink(target, linkPath) {
24
- const resolved = resolve(target);
25
- if (!resolved.startsWith(REFERENCES_DIR) && !resolved.startsWith(REPOS_DIR)) throw new Error(`Symlink target outside allowed dirs: ${resolved}`);
26
- try {
27
- const stat = lstatSync(linkPath);
28
- if (stat.isSymbolicLink() || stat.isFile()) unlinkSync(linkPath);
29
- } catch {}
30
- symlinkSync(target, linkPath, "junction");
31
- }
32
- function isCached(name, version) {
33
- return existsSync(getCacheDir(name, version));
34
- }
35
- function isReadmeOnlyCache(cacheDir) {
36
- const docsDir = join(cacheDir, "docs");
37
- if (!existsSync(docsDir)) return false;
38
- const files = readdirSync(docsDir);
39
- return files.length === 1 && files[0] === "README.md";
40
- }
41
- function inferDocsTypeFromCache(cacheDir, source) {
42
- if (source?.includes("llms.txt") || existsSync(join(cacheDir, "docs", "llms.txt"))) return "llms.txt";
43
- return isReadmeOnlyCache(cacheDir) ? "readme" : "docs";
44
- }
45
- function ensureCacheDir() {
46
- mkdirSync(REFERENCES_DIR, {
47
- recursive: true,
48
- mode: 448
49
- });
50
- mkdirSync(REPOS_DIR, {
51
- recursive: true,
52
- mode: 448
53
- });
54
- }
55
- function writeToCache(name, version, docs) {
56
- const cacheDir = getCacheDir(name, version);
57
- mkdirSync(cacheDir, {
58
- recursive: true,
59
- mode: 448
60
- });
61
- for (const doc of docs) {
62
- const filePath = join(cacheDir, doc.path);
63
- mkdirSync(join(filePath, ".."), {
64
- recursive: true,
65
- mode: 448
66
- });
67
- writeFileSync(filePath, sanitizeMarkdown(doc.content), { mode: 384 });
68
- }
69
- return cacheDir;
70
- }
71
- function writeToRepoCache(owner, repo, docs) {
72
- const repoDir = getRepoCacheDir(owner, repo);
73
- mkdirSync(repoDir, {
74
- recursive: true,
75
- mode: 448
76
- });
77
- for (const doc of docs) {
78
- const filePath = join(repoDir, doc.path);
79
- mkdirSync(join(filePath, ".."), {
80
- recursive: true,
81
- mode: 448
82
- });
83
- writeFileSync(filePath, sanitizeMarkdown(doc.content), { mode: 384 });
84
- }
85
- return repoDir;
86
- }
87
- function linkRepoCachedDir(skillDir, owner, repo, subdir) {
88
- const repoDir = getRepoCacheDir(owner, repo);
89
- const referencesDir = skillInternalDir(skillDir);
90
- const linkPath = join(referencesDir, subdir);
91
- const cachedPath = join(repoDir, subdir);
92
- mkdirSync(referencesDir, { recursive: true });
93
- if (existsSync(cachedPath)) safeSymlink(cachedPath, linkPath);
94
- }
95
- function linkCachedDir(skillDir, name, version, subdir) {
96
- const cacheDir = getCacheDir(name, version);
97
- const referencesDir = skillInternalDir(skillDir);
98
- const linkPath = join(referencesDir, subdir);
99
- const cachedPath = join(cacheDir, subdir);
100
- mkdirSync(referencesDir, { recursive: true });
101
- if (existsSync(cachedPath)) safeSymlink(cachedPath, linkPath);
102
- }
103
- function linkPkg(skillDir, name, cwd, version) {
104
- const pkgPath = resolvePkgDir(name, cwd, version);
105
- if (!pkgPath) return;
106
- const referencesDir = skillInternalDir(skillDir);
107
- mkdirSync(referencesDir, { recursive: true });
108
- const pkgLinkPath = join(referencesDir, "pkg");
109
- try {
110
- lstatSync(pkgLinkPath);
111
- unlinkSync(pkgLinkPath);
112
- } catch {}
113
- symlinkSync(pkgPath, pkgLinkPath, "junction");
114
- }
115
- function linkPkgNamed(skillDir, name, cwd, version) {
116
- const pkgPath = resolvePkgDir(name, cwd, version);
117
- if (!pkgPath) return;
118
- const shortName = name.split("/").pop().toLowerCase();
119
- const referencesDir = skillInternalDir(skillDir);
120
- mkdirSync(referencesDir, { recursive: true });
121
- const linkPath = join(referencesDir, `pkg-${shortName}`);
122
- try {
123
- lstatSync(linkPath);
124
- unlinkSync(linkPath);
125
- } catch {}
126
- symlinkSync(pkgPath, linkPath, "junction");
127
- }
128
- function writeSections(name, version, sections) {
129
- const cacheDir = getCacheDir(name, version);
130
- const sectionsDir = join(cacheDir, "sections");
131
- mkdirSync(sectionsDir, {
132
- recursive: true,
133
- mode: 448
134
- });
135
- for (const { file, content } of sections) writeFileSync(join(sectionsDir, file), content, { mode: 384 });
136
- }
137
- function readCachedSection(name, version, file) {
138
- const path = join(getCacheDir(name, version), "sections", file);
139
- if (!existsSync(path)) return null;
140
- return readFileSync(path, "utf-8");
141
- }
142
- function readCachedDocs(name, version) {
143
- const cacheDir = getCacheDir(name, version);
144
- if (!existsSync(cacheDir)) return [];
145
- const docs = [];
146
- function walk(dir, prefix = "") {
147
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
148
- const entryPath = join(dir, entry.name);
149
- const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
150
- if (entry.isDirectory()) walk(entryPath, relativePath);
151
- else if (entry.name.endsWith(".md") || entry.name.endsWith(".mdx")) docs.push({
152
- path: relativePath,
153
- content: readFileSync(entryPath, "utf-8")
154
- });
155
- }
156
- }
157
- walk(cacheDir);
158
- return docs;
159
- }
160
- function clearCache(name, version) {
161
- const cacheDir = getCacheDir(name, version);
162
- if (!existsSync(cacheDir)) return false;
163
- rmSync(cacheDir, { recursive: true });
164
- return true;
165
- }
166
- function listReferenceFiles(skillDir, maxDepth = 3) {
167
- const referencesDir = skillInternalDir(skillDir);
168
- if (!existsSync(referencesDir)) return [];
169
- const files = [];
170
- function walk(dir, depth) {
171
- if (depth > maxDepth) return;
172
- try {
173
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
174
- const full = join(dir, entry.name);
175
- if (entry.isDirectory() || entry.isSymbolicLink()) try {
176
- if (statSync(full).isDirectory()) {
177
- walk(full, depth + 1);
178
- continue;
179
- }
180
- } catch {
181
- continue;
182
- }
183
- if (entry.name.endsWith(".md")) files.push(full);
184
- }
185
- } catch {}
186
- }
187
- walk(referencesDir, 0);
188
- return files;
189
- }
190
- function getSkillReferenceDirs(skillDir) {
191
- const refsDir = skillInternalDir(skillDir);
192
- if (!existsSync(refsDir)) return [];
193
- const resolved = readdirSync(refsDir).map((entry) => join(refsDir, entry)).filter((p) => lstatSync(p).isSymbolicLink() && existsSync(p)).map((p) => realpathSync(p));
194
- const parents = /* @__PURE__ */ new Set();
195
- for (const p of resolved) {
196
- const parent = dirname(p);
197
- if (!resolved.includes(parent)) parents.add(parent);
198
- }
199
- return [...resolved, ...parents];
200
- }
201
- function clearSkillInternalDir(skillDir) {
202
- const refsDir = skillInternalDir(skillDir);
203
- if (existsSync(refsDir)) rmSync(refsDir, {
204
- recursive: true,
205
- force: true
206
- });
207
- }
208
- function forceClearCache(packageName, version, repoInfo) {
209
- clearCache(packageName, version);
210
- const forcedDbPath = getPackageDbPath(packageName, version);
211
- if (existsSync(forcedDbPath)) rmSync(forcedDbPath, {
212
- recursive: true,
213
- force: true
214
- });
215
- if (repoInfo) {
216
- const repoDir = getRepoCacheDir(repoInfo.owner, repoInfo.repo);
217
- if (existsSync(repoDir)) rmSync(repoDir, {
218
- recursive: true,
219
- force: true
220
- });
221
- }
222
- }
223
- function linkAllReferences(skillDir, packageName, cwd, version, docsType, extraPackages, features, repoInfo) {
224
- const f = features ?? readConfig().features ?? defaultFeatures;
225
- try {
226
- linkPkg(skillDir, packageName, cwd, version);
227
- linkPkgNamed(skillDir, packageName, cwd, version);
228
- if (!hasShippedDocs(packageName, cwd, version) && docsType !== "readme") linkCachedDir(skillDir, packageName, version, "docs");
229
- if (f.issues) {
230
- if (repoInfo) linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, "issues");
231
- else linkCachedDir(skillDir, packageName, version, "issues");
232
- }
233
- if (f.discussions) {
234
- if (repoInfo) linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, "discussions");
235
- else linkCachedDir(skillDir, packageName, version, "discussions");
236
- }
237
- if (f.releases) {
238
- if (repoInfo) linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, "releases");
239
- else linkCachedDir(skillDir, packageName, version, "releases");
240
- }
241
- linkCachedDir(skillDir, packageName, version, "sections");
242
- if (extraPackages) {
243
- for (const pkg of extraPackages) if (pkg.name !== packageName) linkPkgNamed(skillDir, pkg.name, cwd, pkg.version);
244
- }
245
- } catch {}
246
- }
247
- function detectDocsType(packageName, version, repoUrl, llmsUrl) {
248
- const cacheDir = getCacheDir(packageName, version);
249
- if (existsSync(join(cacheDir, "docs", "index.md")) || existsSync(join(cacheDir, "docs", "guide"))) return {
250
- docsType: "docs",
251
- docSource: repoUrl ? `${repoUrl}/tree/v${version}/docs` : "git"
252
- };
253
- if (existsSync(join(cacheDir, "llms.txt"))) return {
254
- docsType: "llms.txt",
255
- docSource: llmsUrl || "llms.txt"
256
- };
257
- if (existsSync(join(cacheDir, "docs", "README.md"))) return { docsType: "readme" };
258
- return { docsType: "readme" };
259
- }
260
- function ejectReferences(skillDir, packageName, cwd, version, docsType, features, repoInfo) {
261
- const f = features ?? readConfig().features ?? defaultFeatures;
262
- const cacheDir = getCacheDir(packageName, version);
263
- const refsDir = join(skillDir, "references");
264
- const repoDir = repoInfo ? getRepoCacheDir(repoInfo.owner, repoInfo.repo) : cacheDir;
265
- if (!hasShippedDocs(packageName, cwd, version) && docsType !== "readme") copyCachedSubdir(cacheDir, refsDir, "docs");
266
- if (f.issues) copyCachedSubdir(repoDir, refsDir, "issues");
267
- if (f.discussions) copyCachedSubdir(repoDir, refsDir, "discussions");
268
- if (f.releases) copyCachedSubdir(repoDir, refsDir, "releases");
269
- }
270
- function copyCachedSubdir(cacheDir, refsDir, subdir) {
271
- const srcDir = join(cacheDir, subdir);
272
- if (!existsSync(srcDir)) return;
273
- const destDir = join(refsDir, subdir);
274
- mkdirSync(destDir, { recursive: true });
275
- function walk(dir, rel) {
276
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
277
- const srcPath = join(dir, entry.name);
278
- const destPath = join(destDir, rel ? `${rel}/${entry.name}` : entry.name);
279
- if (entry.isDirectory()) {
280
- mkdirSync(destPath, { recursive: true });
281
- walk(srcPath, rel ? `${rel}/${entry.name}` : entry.name);
282
- } else copyFileSync(srcPath, destPath);
283
- }
284
- }
285
- walk(srcDir, "");
286
- }
287
- function loadCachedReferences(opts) {
288
- const { packageName, version, repoUrl, llmsUrl, readmeUrl, onProgress, generateDocsIndex } = opts;
289
- onProgress("Loading cached docs");
290
- const detected = detectDocsType(packageName, version, repoUrl, llmsUrl);
291
- const docsType = detected.docsType;
292
- const docSource = detected.docSource ?? readmeUrl ?? "readme";
293
- const docsToIndex = [];
294
- const dbPath = getPackageDbPath(packageName, version);
295
- if (!existsSync(dbPath) || !hasIndexEmbeddingIdentity(dbPath, resolveEmbeddingIdentity())) {
296
- onProgress("Reading cached docs for indexing");
297
- const cached = readCachedDocs(packageName, version);
298
- for (const doc of cached) docsToIndex.push({
299
- id: doc.path,
300
- content: doc.content,
301
- metadata: {
302
- package: packageName,
303
- source: doc.path,
304
- ...classifyCachedDoc(doc.path)
305
- }
306
- });
307
- }
308
- let backfillIndex;
309
- if (docsType !== "readme" && !existsSync(join(getCacheDir(packageName, version), "docs", "_INDEX.md"))) {
310
- onProgress("Generating docs index");
311
- const cached = readCachedDocs(packageName, version);
312
- if (cached.filter((d) => d.path.startsWith("docs/") && d.path.endsWith(".md")).length > 1) {
313
- const docsIndex = generateDocsIndex(cached);
314
- if (docsIndex) backfillIndex = {
315
- path: "docs/_INDEX.md",
316
- content: docsIndex
317
- };
318
- }
319
- }
320
- return {
321
- docsToIndex,
322
- docSource,
323
- docsType,
324
- backfillIndex
325
- };
326
- }
327
- function createReferenceCache(packageName, version) {
328
- const requireVersion = (op) => {
329
- if (!version) throw new Error(`ReferenceCache.${op} requires a version (package: ${packageName})`);
330
- return version;
331
- };
332
- return {
333
- packageName,
334
- version,
335
- get versionKey() {
336
- return getVersionKey(requireVersion("versionKey"));
337
- },
338
- get dir() {
339
- return getCacheDir(packageName, requireVersion("dir"));
340
- },
341
- ensure: () => ensureCacheDir(),
342
- has: () => !!version && isCached(packageName, version),
343
- isReadmeOnly: () => isReadmeOnlyCache(getCacheDir(packageName, requireVersion("isReadmeOnly"))),
344
- inferDocsType: (source) => inferDocsTypeFromCache(getCacheDir(packageName, requireVersion("inferDocsType")), source),
345
- write: (docs) => void writeToCache(packageName, requireVersion("write"), docs),
346
- writeSections: (sections) => writeSections(packageName, requireVersion("writeSections"), sections),
347
- readSection: (file) => readCachedSection(packageName, requireVersion("readSection"), file),
348
- readDocs: () => readCachedDocs(packageName, requireVersion("readDocs")),
349
- detectDocs: (repoUrl, llmsUrl) => detectDocsType(packageName, requireVersion("detectDocs"), repoUrl, llmsUrl),
350
- load: (opts) => loadCachedReferences({
351
- ...opts,
352
- packageName,
353
- version: requireVersion("load")
354
- }),
355
- linkInto: (skillDir, cwd, docsType, opts) => linkAllReferences(skillDir, packageName, cwd, requireVersion("linkInto"), docsType, opts?.extraPackages, opts?.features, opts?.repoInfo),
356
- linkPkgNamed: (skillDir, cwd) => linkPkgNamed(skillDir, packageName, cwd, version),
357
- eject: (skillDir, cwd, docsType, opts) => ejectReferences(skillDir, packageName, cwd, requireVersion("eject"), docsType, opts?.features, opts?.repoInfo),
358
- clearForce: (repoInfo) => forceClearCache(packageName, requireVersion("clearForce"), repoInfo),
359
- clearSkillInternal: (skillDir) => clearSkillInternalDir(skillDir),
360
- pkgDir: (cwd) => resolvePkgDir(packageName, cwd, version),
361
- hasShipped: (cwd) => hasShippedDocs(packageName, cwd, version),
362
- keyFiles: (cwd) => getPkgKeyFiles(packageName, cwd, version)
363
- };
364
- }
365
- export { createReferenceCache, ensureCacheDir, getSkillReferenceDirs, listReferenceFiles, writeToRepoCache };
366
-
367
- //# sourceMappingURL=cache.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache.mjs","names":[],"sources":["../../src/cache/internal/classify.ts","../../src/cache/internal/storage.ts","../../src/cache/internal/references.ts","../../src/cache/reference-cache.ts"],"sourcesContent":["const STATIC_REGEX_1 = /^issues\\/issue-(\\d+)\\.md$/\nconst STATIC_REGEX_2 = /^discussions\\/discussion-(\\d+)\\.md$/\n\n/**\n * Classify a cached doc path into the right metadata type.\n * Pure utility — no I/O.\n */\nexport function classifyCachedDoc(path: string): { type: string, number?: number } {\n const issueMatch = path.match(STATIC_REGEX_1)\n if (issueMatch)\n return { type: 'issue', number: Number(issueMatch[1]) }\n const discussionMatch = path.match(STATIC_REGEX_2)\n if (discussionMatch)\n return { type: 'discussion', number: Number(discussionMatch[1]) }\n if (path.startsWith('releases/'))\n return { type: 'release' }\n return { type: 'doc' }\n}\n","/**\n * Cache storage operations\n */\n\nimport type { CachedDoc, CachedPackage } from '../types.ts'\nimport { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'pathe'\nimport { getRepoCacheDir, REFERENCES_DIR, REPOS_DIR, skillInternalDir } from '../../core/paths.ts'\nimport { resolvePkgDir } from '../../core/prepare.ts'\nimport { sanitizeMarkdown } from '../../core/sanitize.ts'\nimport { getCacheDir } from './version.ts'\n\n/** Safely create a symlink, validating target is under REFERENCES_DIR or REPOS_DIR */\nfunction safeSymlink(target: string, linkPath: string): void {\n const resolved = resolve(target)\n if (!resolved.startsWith(REFERENCES_DIR) && !resolved.startsWith(REPOS_DIR))\n throw new Error(`Symlink target outside allowed dirs: ${resolved}`)\n // Remove pre-existing symlink (check with lstat to detect symlinks)\n try {\n const stat = lstatSync(linkPath)\n if (stat.isSymbolicLink() || stat.isFile())\n unlinkSync(linkPath)\n }\n catch {}\n symlinkSync(target, linkPath, 'junction')\n}\n\n/**\n * Check if package is cached at given version\n * @internal\n */\nexport function isCached(name: string, version: string): boolean {\n return existsSync(getCacheDir(name, version))\n}\n\n/** Check if cache only has docs/README.md (pkg/ already has this) */\nexport function isReadmeOnlyCache(cacheDir: string): boolean {\n const docsDir = join(cacheDir, 'docs')\n if (!existsSync(docsDir))\n return false\n const files = readdirSync(docsDir)\n return files.length === 1 && files[0] === 'README.md'\n}\n\nexport function inferDocsTypeFromCache(cacheDir: string, source?: string): 'llms.txt' | 'readme' | 'docs' {\n if (source?.includes('llms.txt') || existsSync(join(cacheDir, 'docs', 'llms.txt')))\n return 'llms.txt'\n return isReadmeOnlyCache(cacheDir) ? 'readme' : 'docs'\n}\n\n/**\n * Ensure cache directories exist\n */\nexport function ensureCacheDir(): void {\n mkdirSync(REFERENCES_DIR, { recursive: true, mode: 0o700 })\n mkdirSync(REPOS_DIR, { recursive: true, mode: 0o700 })\n}\n\n/**\n * Write docs to cache\n * @internal\n */\nexport function writeToCache(\n name: string,\n version: string,\n docs: CachedDoc[],\n): string {\n const cacheDir = getCacheDir(name, version)\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n\n for (const doc of docs) {\n const filePath = join(cacheDir, doc.path)\n mkdirSync(join(filePath, '..'), { recursive: true, mode: 0o700 })\n writeFileSync(filePath, sanitizeMarkdown(doc.content), { mode: 0o600 })\n }\n\n return cacheDir\n}\n\n/**\n * Write docs to repo-level cache (~/.skilld/repos/<owner>/<repo>/)\n */\nexport function writeToRepoCache(\n owner: string,\n repo: string,\n docs: CachedDoc[],\n): string {\n const repoDir = getRepoCacheDir(owner, repo)\n mkdirSync(repoDir, { recursive: true, mode: 0o700 })\n\n for (const doc of docs) {\n const filePath = join(repoDir, doc.path)\n mkdirSync(join(filePath, '..'), { recursive: true, mode: 0o700 })\n writeFileSync(filePath, sanitizeMarkdown(doc.content), { mode: 0o600 })\n }\n\n return repoDir\n}\n\n/**\n * Create symlink from .skilld dir to a repo-level cached subdirectory.\n * .claude/skills/<skill>/.skilld/<subdir> -> ~/.skilld/repos/<owner>/<repo>/<subdir>\n */\nexport function linkRepoCachedDir(skillDir: string, owner: string, repo: string, subdir: string): void {\n const repoDir = getRepoCacheDir(owner, repo)\n const referencesDir = skillInternalDir(skillDir)\n const linkPath = join(referencesDir, subdir)\n const cachedPath = join(repoDir, subdir)\n\n mkdirSync(referencesDir, { recursive: true })\n\n if (existsSync(cachedPath)) {\n safeSymlink(cachedPath, linkPath)\n }\n}\n\n/**\n * Create symlink from .skilld dir to a cached subdirectory.\n * Unified handler for docs, issues, discussions, sections, releases.\n *\n * Structure:\n * .claude/skills/<skill>/.skilld/<subdir> -> ~/.skilld/references/<pkg>@<version>/<subdir>\n *\n * The .skilld/ dirs are gitignored. After clone, `skilld install` recreates from lockfile.\n */\nexport function linkCachedDir(skillDir: string, name: string, version: string, subdir: string): void {\n const cacheDir = getCacheDir(name, version)\n const referencesDir = skillInternalDir(skillDir)\n const linkPath = join(referencesDir, subdir)\n const cachedPath = join(cacheDir, subdir)\n\n mkdirSync(referencesDir, { recursive: true })\n\n if (existsSync(cachedPath)) {\n safeSymlink(cachedPath, linkPath)\n }\n}\n\n/**\n * Create symlink from .skilld dir to package directory\n *\n * Structure:\n * .claude/skills/<skill>/.skilld/pkg -> node_modules/<pkg> OR ~/.skilld/references/<pkg>@<version>/pkg\n *\n * This gives access to package.json, README.md, dist/, and any shipped docs/\n */\nexport function linkPkg(skillDir: string, name: string, cwd: string, version?: string): void {\n const pkgPath = resolvePkgDir(name, cwd, version)\n if (!pkgPath)\n return\n\n const referencesDir = skillInternalDir(skillDir)\n mkdirSync(referencesDir, { recursive: true })\n\n const pkgLinkPath = join(referencesDir, 'pkg')\n try {\n lstatSync(pkgLinkPath)\n unlinkSync(pkgLinkPath)\n }\n catch {}\n symlinkSync(pkgPath, pkgLinkPath, 'junction')\n}\n\n/**\n * Create named symlink from .skilld dir to package directory.\n * Short name = last segment of package name (e.g., @vue/reactivity → pkg-reactivity)\n *\n * Structure:\n * .claude/skills/<skill>/.skilld/pkg-<short> -> node_modules/<pkg>\n */\nexport function linkPkgNamed(skillDir: string, name: string, cwd: string, version?: string): void {\n const pkgPath = resolvePkgDir(name, cwd, version)\n if (!pkgPath)\n return\n\n const shortName = name.split('/').pop()!.toLowerCase()\n const referencesDir = skillInternalDir(skillDir)\n mkdirSync(referencesDir, { recursive: true })\n\n const linkPath = join(referencesDir, `pkg-${shortName}`)\n try {\n lstatSync(linkPath)\n unlinkSync(linkPath)\n }\n catch {}\n symlinkSync(pkgPath, linkPath, 'junction')\n}\n\n/**\n * Write LLM-generated section outputs to global cache for cross-project reuse\n *\n * Structure:\n * ~/.skilld/references/<pkg>@<version>/sections/_BEST_PRACTICES.md\n */\nexport function writeSections(name: string, version: string, sections: Array<{ file: string, content: string }>): void {\n const cacheDir = getCacheDir(name, version)\n const sectionsDir = join(cacheDir, 'sections')\n mkdirSync(sectionsDir, { recursive: true, mode: 0o700 })\n for (const { file, content } of sections) {\n writeFileSync(join(sectionsDir, file), content, { mode: 0o600 })\n }\n}\n\n/**\n * Read a cached section from the global references dir\n */\nexport function readCachedSection(name: string, version: string, file: string): string | null {\n const path = join(getCacheDir(name, version), 'sections', file)\n if (!existsSync(path))\n return null\n return readFileSync(path, 'utf-8')\n}\n\n/**\n * List all cached packages\n */\nexport function listCached(): CachedPackage[] {\n if (!existsSync(REFERENCES_DIR))\n return []\n\n return readdirSync(REFERENCES_DIR)\n .filter(name => name.includes('@'))\n .map((dir) => {\n const atIdx = dir.lastIndexOf('@')\n return { name: dir.slice(0, atIdx), version: dir.slice(atIdx + 1), dir: join(REFERENCES_DIR, dir) }\n })\n}\n\n/**\n * Read cached docs for a package\n */\nexport function readCachedDocs(name: string, version: string): CachedDoc[] {\n const cacheDir = getCacheDir(name, version)\n if (!existsSync(cacheDir))\n return []\n\n const docs: CachedDoc[] = []\n\n function walk(dir: string, prefix = '') {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const entryPath = join(dir, entry.name)\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name\n\n if (entry.isDirectory()) {\n walk(entryPath, relativePath)\n }\n else if (entry.name.endsWith('.md') || entry.name.endsWith('.mdx')) {\n docs.push({\n path: relativePath,\n content: readFileSync(entryPath, 'utf-8'),\n })\n }\n }\n }\n\n walk(cacheDir)\n return docs\n}\n\n/**\n * Clear cache for a specific package\n */\nexport function clearCache(name: string, version: string): boolean {\n const cacheDir = getCacheDir(name, version)\n if (!existsSync(cacheDir))\n return false\n\n rmSync(cacheDir, { recursive: true })\n return true\n}\n\n/**\n * List files in .skilld directory (pkg + docs) as relative paths for prompt context\n * Returns paths like ./.skilld/pkg/README.md, ./.skilld/docs/api.md\n */\nexport function listReferenceFiles(skillDir: string, maxDepth = 3): string[] {\n const referencesDir = skillInternalDir(skillDir)\n if (!existsSync(referencesDir))\n return []\n\n const files: string[] = []\n\n function walk(dir: string, depth: number) {\n if (depth > maxDepth)\n return\n try {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name)\n if (entry.isDirectory() || entry.isSymbolicLink()) {\n try {\n const stat = statSync(full)\n if (stat.isDirectory()) {\n walk(full, depth + 1)\n continue\n }\n }\n catch { continue }\n }\n if (entry.name.endsWith('.md')) {\n files.push(full)\n }\n }\n }\n catch {\n // Broken symlink or permission error\n }\n }\n\n walk(referencesDir, 0)\n return files\n}\n","/**\n * Higher-level reference-cache operations: composition over the cache\n * primitives in `src/cache/index.ts`.\n *\n * Owns:\n * - The on-disk shape of `~/.skilld/references/<pkg>@<version>/`\n * - `.skilld/` symlinks inside agent skill dirs (linkAllReferences)\n * - Loading cached docs back as a `ResolvedContent`-shaped result\n * - Force-clearing and ejecting (portable copy) caches\n *\n * Callers (sync, sync-parallel, sync-git, install, author) should use these\n * helpers instead of touching cache primitives directly.\n */\n\nimport type { FeaturesConfig } from '../../core/config.ts'\nimport type { IndexDoc } from '../../sources/content-resolver.ts'\nimport type { CachedReferencesResult, LoadCachedReferencesOptions } from '../types.ts'\nimport { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync } from 'node:fs'\nimport { dirname, join } from 'pathe'\nimport { defaultFeatures, readConfig } from '../../core/config.ts'\nimport { getPackageDbPath, getRepoCacheDir, skillInternalDir } from '../../core/paths.ts'\nimport { hasShippedDocs } from '../../core/prepare.ts'\nimport { hasIndexEmbeddingIdentity, resolveEmbeddingIdentity } from '../../retriv/index-identity.ts'\nimport { classifyCachedDoc } from './classify.ts'\nimport {\n clearCache,\n linkCachedDir,\n linkPkg,\n linkPkgNamed,\n linkRepoCachedDir,\n readCachedDocs,\n} from './storage.ts'\nimport { getCacheDir } from './version.ts'\n\n/**\n * Resolve every symlink under `<skillDir>/.skilld/` to its real path, plus\n * the parent dirs CLI sandboxes need (e.g. Gemini). What an LLM CLI passes to\n * `--add-dir` to make references readable.\n */\nexport function getSkillReferenceDirs(skillDir: string): string[] {\n const refsDir = skillInternalDir(skillDir)\n if (!existsSync(refsDir))\n return []\n const resolved = readdirSync(refsDir)\n .map(entry => join(refsDir, entry))\n .filter(p => lstatSync(p).isSymbolicLink() && existsSync(p))\n .map(p => realpathSync(p))\n\n const parents = new Set<string>()\n for (const p of resolved) {\n const parent = dirname(p)\n if (!resolved.includes(parent))\n parents.add(parent)\n }\n\n return [...resolved, ...parents]\n}\n\n/**\n * Remove the transient `<skillDir>/.skilld/` symlink dir. Used after eject to\n * clean up references that have been copied as real files.\n */\nexport function clearSkillInternalDir(skillDir: string): void {\n const refsDir = skillInternalDir(skillDir)\n if (existsSync(refsDir))\n rmSync(refsDir, { recursive: true, force: true })\n}\n\n/** Clear cache + db for --force flag */\nexport function forceClearCache(packageName: string, version: string, repoInfo?: { owner: string, repo: string }): void {\n clearCache(packageName, version)\n const forcedDbPath = getPackageDbPath(packageName, version)\n if (existsSync(forcedDbPath))\n rmSync(forcedDbPath, { recursive: true, force: true })\n // Also clear repo-level cache when force is used\n if (repoInfo) {\n const repoDir = getRepoCacheDir(repoInfo.owner, repoInfo.repo)\n if (existsSync(repoDir))\n rmSync(repoDir, { recursive: true, force: true })\n }\n}\n\n/** Link all reference symlinks (pkg, docs, issues, discussions, releases) */\nexport function linkAllReferences(skillDir: string, packageName: string, cwd: string, version: string, docsType: string, extraPackages?: Array<{ name: string, version?: string }>, features?: FeaturesConfig, repoInfo?: { owner: string, repo: string }): void {\n const f = features ?? readConfig().features ?? defaultFeatures\n try {\n linkPkg(skillDir, packageName, cwd, version)\n linkPkgNamed(skillDir, packageName, cwd, version)\n if (!hasShippedDocs(packageName, cwd, version) && docsType !== 'readme') {\n linkCachedDir(skillDir, packageName, version, 'docs')\n }\n // Issues/discussions/releases: use repo cache when available, else package cache\n if (f.issues) {\n if (repoInfo)\n linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, 'issues')\n else\n linkCachedDir(skillDir, packageName, version, 'issues')\n }\n if (f.discussions) {\n if (repoInfo)\n linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, 'discussions')\n else\n linkCachedDir(skillDir, packageName, version, 'discussions')\n }\n if (f.releases) {\n if (repoInfo)\n linkRepoCachedDir(skillDir, repoInfo.owner, repoInfo.repo, 'releases')\n else\n linkCachedDir(skillDir, packageName, version, 'releases')\n }\n linkCachedDir(skillDir, packageName, version, 'sections')\n // Create named symlinks for additional packages in multi-package skills\n if (extraPackages) {\n for (const pkg of extraPackages) {\n if (pkg.name !== packageName)\n linkPkgNamed(skillDir, pkg.name, cwd, pkg.version)\n }\n }\n }\n catch {\n // Symlink may fail on some systems\n }\n}\n\n/** Detect docs type from cached directory contents */\nexport function detectDocsType(packageName: string, version: string, repoUrl?: string, llmsUrl?: string): { docsType: 'docs' | 'llms.txt' | 'readme', docSource?: string } {\n const cacheDir = getCacheDir(packageName, version)\n if (existsSync(join(cacheDir, 'docs', 'index.md')) || existsSync(join(cacheDir, 'docs', 'guide'))) {\n return {\n docsType: 'docs',\n docSource: repoUrl ? `${repoUrl}/tree/v${version}/docs` : 'git',\n }\n }\n if (existsSync(join(cacheDir, 'llms.txt'))) {\n return {\n docsType: 'llms.txt',\n docSource: llmsUrl || 'llms.txt',\n }\n }\n if (existsSync(join(cacheDir, 'docs', 'README.md'))) {\n return { docsType: 'readme' }\n }\n return { docsType: 'readme' }\n}\n\n/** Eject (portable copy) of cached references into a skill dir */\nexport function ejectReferences(skillDir: string, packageName: string, cwd: string, version: string, docsType: string, features?: FeaturesConfig, repoInfo?: { owner: string, repo: string }): void {\n const f = features ?? readConfig().features ?? defaultFeatures\n const cacheDir = getCacheDir(packageName, version)\n const refsDir = join(skillDir, 'references')\n // Repo-level data source (falls back to package cache)\n const repoDir = repoInfo ? getRepoCacheDir(repoInfo.owner, repoInfo.repo) : cacheDir\n\n // Copy cached docs (skip pkg — eject is for portable sharing, pkg references node_modules)\n if (!hasShippedDocs(packageName, cwd, version) && docsType !== 'readme')\n copyCachedSubdir(cacheDir, refsDir, 'docs')\n\n if (f.issues)\n copyCachedSubdir(repoDir, refsDir, 'issues')\n if (f.discussions)\n copyCachedSubdir(repoDir, refsDir, 'discussions')\n if (f.releases)\n copyCachedSubdir(repoDir, refsDir, 'releases')\n}\n\n/** Recursively copy a cached subdirectory into the references dir */\nfunction copyCachedSubdir(cacheDir: string, refsDir: string, subdir: string): void {\n const srcDir = join(cacheDir, subdir)\n if (!existsSync(srcDir))\n return\n\n const destDir = join(refsDir, subdir)\n mkdirSync(destDir, { recursive: true })\n\n function walk(dir: string, rel: string) {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const srcPath = join(dir, entry.name)\n const destPath = join(destDir, rel ? `${rel}/${entry.name}` : entry.name)\n if (entry.isDirectory()) {\n mkdirSync(destPath, { recursive: true })\n walk(srcPath, rel ? `${rel}/${entry.name}` : entry.name)\n }\n else {\n copyFileSync(srcPath, destPath)\n }\n }\n }\n\n walk(srcDir, '')\n}\n\n/**\n * Load cached references for a package and produce the index/backfill data\n * needed to continue the sync pipeline without re-fetching.\n */\nexport function loadCachedReferences(opts: LoadCachedReferencesOptions): CachedReferencesResult {\n const { packageName, version, repoUrl, llmsUrl, readmeUrl, onProgress, generateDocsIndex } = opts\n onProgress('Loading cached docs')\n const detected = detectDocsType(packageName, version, repoUrl, llmsUrl)\n const docsType = detected.docsType\n const docSource = detected.docSource ?? readmeUrl ?? 'readme'\n const docsToIndex: IndexDoc[] = []\n\n // Load cached docs for indexing if db doesn't exist yet\n const dbPath = getPackageDbPath(packageName, version)\n if (!existsSync(dbPath) || !hasIndexEmbeddingIdentity(dbPath, resolveEmbeddingIdentity())) {\n onProgress('Reading cached docs for indexing')\n const cached = readCachedDocs(packageName, version)\n for (const doc of cached) {\n docsToIndex.push({\n id: doc.path,\n content: doc.content,\n metadata: { package: packageName, source: doc.path, ...classifyCachedDoc(doc.path) },\n })\n }\n }\n\n // Backfill docs index for caches created before this feature\n let backfillIndex: { path: string, content: string } | undefined\n if (docsType !== 'readme' && !existsSync(join(getCacheDir(packageName, version), 'docs', '_INDEX.md'))) {\n onProgress('Generating docs index')\n const cached = readCachedDocs(packageName, version)\n const docFiles = cached.filter(d => d.path.startsWith('docs/') && d.path.endsWith('.md'))\n if (docFiles.length > 1) {\n const docsIndex = generateDocsIndex(cached)\n if (docsIndex)\n backfillIndex = { path: 'docs/_INDEX.md', content: docsIndex }\n }\n }\n\n return { docsToIndex, docSource, docsType, backfillIndex }\n}\n","/**\n * Per-package reference cache facade. Closes over `(packageName, version)` so\n * call sites stop threading those tuples through chained primitives.\n */\n\nimport type { FeaturesConfig } from '../core/config.ts'\nimport type { CachedDoc, CachedReferencesResult, LoadCachedReferencesOptions } from './types.ts'\nimport { getPkgKeyFiles, hasShippedDocs, resolvePkgDir } from '../core/prepare.ts'\nimport {\n clearSkillInternalDir,\n detectDocsType,\n ejectReferences,\n forceClearCache,\n linkAllReferences,\n loadCachedReferences,\n} from './internal/references.ts'\nimport {\n ensureCacheDir,\n inferDocsTypeFromCache,\n isCached,\n isReadmeOnlyCache,\n linkPkgNamed,\n readCachedDocs,\n readCachedSection,\n writeSections,\n writeToCache,\n} from './internal/storage.ts'\nimport { getCacheDir, getVersionKey } from './internal/version.ts'\n\nexport interface ReferenceCacheLinkOpts {\n extraPackages?: Array<{ name: string, version?: string }>\n features?: FeaturesConfig\n repoInfo?: { owner: string, repo: string }\n}\n\nexport interface ReferenceCacheEjectOpts {\n features?: FeaturesConfig\n repoInfo?: { owner: string, repo: string }\n}\n\nexport interface ReferenceCache {\n readonly packageName: string\n /** May be undefined when caller only knows the package name (e.g. merge against a lock without a recorded version). Cache-keyed methods/getters throw in that case; pkg/has/keyFiles fall back to node_modules. */\n readonly version: string | undefined\n /** Throws if accessed when version is undefined. */\n readonly versionKey: string\n /** Throws if accessed when version is undefined. */\n readonly dir: string\n ensure: () => void\n has: () => boolean\n isReadmeOnly: () => boolean\n inferDocsType: (source?: string) => 'llms.txt' | 'readme' | 'docs'\n write: (docs: CachedDoc[]) => void\n writeSections: (sections: Array<{ file: string, content: string }>) => void\n readSection: (file: string) => string | null\n readDocs: () => CachedDoc[]\n detectDocs: (\n repoUrl?: string,\n llmsUrl?: string,\n ) => { docsType: 'docs' | 'llms.txt' | 'readme', docSource?: string }\n load: (\n opts: Omit<LoadCachedReferencesOptions, 'packageName' | 'version'>,\n ) => CachedReferencesResult\n linkInto: (\n skillDir: string,\n cwd: string,\n docsType: string,\n opts?: ReferenceCacheLinkOpts,\n ) => void\n linkPkgNamed: (skillDir: string, cwd: string) => void\n eject: (\n skillDir: string,\n cwd: string,\n docsType: string,\n opts?: ReferenceCacheEjectOpts,\n ) => void\n clearForce: (repoInfo?: { owner: string, repo: string }) => void\n clearSkillInternal: (skillDir: string) => void\n pkgDir: (cwd: string) => string | null\n hasShipped: (cwd: string) => boolean\n keyFiles: (cwd: string) => string[]\n}\n\nexport function createReferenceCache(packageName: string, version?: string): ReferenceCache {\n const requireVersion = (op: string): string => {\n if (!version)\n throw new Error(`ReferenceCache.${op} requires a version (package: ${packageName})`)\n return version\n }\n return {\n packageName,\n version,\n get versionKey() { return getVersionKey(requireVersion('versionKey')) },\n get dir() { return getCacheDir(packageName, requireVersion('dir')) },\n ensure: () => ensureCacheDir(),\n has: () => !!version && isCached(packageName, version),\n isReadmeOnly: () => isReadmeOnlyCache(getCacheDir(packageName, requireVersion('isReadmeOnly'))),\n inferDocsType: source => inferDocsTypeFromCache(getCacheDir(packageName, requireVersion('inferDocsType')), source),\n write: docs => void writeToCache(packageName, requireVersion('write'), docs),\n writeSections: sections => writeSections(packageName, requireVersion('writeSections'), sections),\n readSection: file => readCachedSection(packageName, requireVersion('readSection'), file),\n readDocs: () => readCachedDocs(packageName, requireVersion('readDocs')),\n detectDocs: (repoUrl, llmsUrl) =>\n detectDocsType(packageName, requireVersion('detectDocs'), repoUrl, llmsUrl),\n load: opts =>\n loadCachedReferences({ ...opts, packageName, version: requireVersion('load') }),\n linkInto: (skillDir, cwd, docsType, opts) =>\n linkAllReferences(\n skillDir,\n packageName,\n cwd,\n requireVersion('linkInto'),\n docsType,\n opts?.extraPackages,\n opts?.features,\n opts?.repoInfo,\n ),\n linkPkgNamed: (skillDir, cwd) =>\n linkPkgNamed(skillDir, packageName, cwd, version),\n eject: (skillDir, cwd, docsType, opts) =>\n ejectReferences(\n skillDir,\n packageName,\n cwd,\n requireVersion('eject'),\n docsType,\n opts?.features,\n opts?.repoInfo,\n ),\n clearForce: repoInfo => forceClearCache(packageName, requireVersion('clearForce'), repoInfo),\n clearSkillInternal: skillDir => clearSkillInternalDir(skillDir),\n pkgDir: cwd => resolvePkgDir(packageName, cwd, version),\n hasShipped: cwd => hasShippedDocs(packageName, cwd, version),\n keyFiles: cwd => getPkgKeyFiles(packageName, cwd, version),\n }\n}\n"],"mappings":";;;;;;AAAA,MAAM,iBAAiB;AAC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s";
4
- import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
5
- import { styleText } from "node:util";
6
- import * as p from "@clack/prompts";
7
- import { defineCommand } from "citty";
8
- import { join } from "pathe";
9
- const LLM_CACHE_DIR = join(CACHE_DIR, "llm-cache");
10
- const LLM_CACHE_MAX_AGE = 6048e5;
11
- function safeRemove(path) {
12
- try {
13
- const size = statSync(path).size;
14
- rmSync(path);
15
- return size;
16
- } catch {
17
- try {
18
- rmSync(path);
19
- } catch {}
20
- return 0;
21
- }
22
- }
23
- async function cacheCleanCommand() {
24
- let expiredLlm = 0;
25
- let freedBytes = 0;
26
- if (existsSync(LLM_CACHE_DIR)) {
27
- const now = Date.now();
28
- for (const entry of readdirSync(LLM_CACHE_DIR)) {
29
- const path = join(LLM_CACHE_DIR, entry);
30
- try {
31
- const { timestamp } = JSON.parse(readFileSync(path, "utf-8"));
32
- if (now - timestamp > LLM_CACHE_MAX_AGE) {
33
- freedBytes += safeRemove(path);
34
- expiredLlm++;
35
- }
36
- } catch {
37
- freedBytes += safeRemove(path);
38
- expiredLlm++;
39
- }
40
- }
41
- }
42
- const embeddingDbPath = join(CACHE_DIR, "embeddings.db");
43
- let embeddingCleared = false;
44
- if (existsSync(embeddingDbPath)) {
45
- const size = statSync(embeddingDbPath).size;
46
- clearEmbeddingCache();
47
- freedBytes += size;
48
- embeddingCleared = true;
49
- }
50
- const freedKB = Math.round(freedBytes / 1024);
51
- if (expiredLlm > 0 || embeddingCleared) {
52
- const parts = [];
53
- if (expiredLlm > 0) parts.push(`${expiredLlm} expired enhancement cache entries`);
54
- if (embeddingCleared) parts.push("embedding cache");
55
- p.log.success(`Removed ${parts.join(" + ")} (${freedKB}KB freed)`);
56
- } else p.log.info("Cache is clean — no expired entries");
57
- }
58
- function dirEntries(dir) {
59
- if (!existsSync(dir)) return [];
60
- return readdirSync(dir, {
61
- withFileTypes: true,
62
- recursive: true
63
- });
64
- }
65
- function sumFileBytes(entries) {
66
- return entries.filter((e) => e.isFile()).reduce((sum, e) => {
67
- try {
68
- return sum + statSync(join(e.parentPath, e.name)).size;
69
- } catch {
70
- return sum;
71
- }
72
- }, 0);
73
- }
74
- function fmtBytes(n) {
75
- const units = [
76
- "B",
77
- "KB",
78
- "MB",
79
- "GB"
80
- ];
81
- let i = 0;
82
- while (n >= 1024 && i < units.length - 1) {
83
- n /= 1024;
84
- i++;
85
- }
86
- return i === 0 ? `${n}${units[i]}` : `${n.toFixed(1)}${units[i]}`;
87
- }
88
- function cacheStatsCommand() {
89
- const dim = (s) => styleText("gray", s);
90
- const refs = dirEntries(REFERENCES_DIR);
91
- const repos = dirEntries(REPOS_DIR);
92
- const llm = dirEntries(LLM_CACHE_DIR);
93
- const embPath = join(CACHE_DIR, "embeddings.db");
94
- const embSize = existsSync(embPath) ? statSync(embPath).size : 0;
95
- const packages = refs.filter((e) => e.isDirectory() && (e.parentPath === REFERENCES_DIR ? !e.name.startsWith("@") : e.parentPath.startsWith(REFERENCES_DIR))).length;
96
- const llmFiles = llm.filter((e) => e.isFile());
97
- const sizes = {
98
- refs: sumFileBytes(refs),
99
- repos: sumFileBytes(repos),
100
- llm: sumFileBytes(llmFiles),
101
- emb: embSize
102
- };
103
- const total = sizes.refs + sizes.repos + sizes.llm + sizes.emb;
104
- const lines = [
105
- `References ${fmtBytes(sizes.refs)} ${dim(`${packages} packages`)}`,
106
- ...sizes.repos > 0 ? [`Repos ${fmtBytes(sizes.repos)}`] : [],
107
- `LLM cache ${fmtBytes(sizes.llm)} ${dim(`${llmFiles.length} entries`)}`,
108
- ...sizes.emb > 0 ? [`Embeddings ${fmtBytes(sizes.emb)}`] : [],
109
- "",
110
- `Total ${fmtBytes(total)} ${dim(CACHE_DIR)}`
111
- ];
112
- p.log.message(lines.join("\n"));
113
- }
114
- const cacheCommandDef = defineCommand({
115
- meta: {
116
- name: "cache",
117
- description: "Cache management",
118
- hidden: true
119
- },
120
- args: {
121
- clean: {
122
- type: "boolean",
123
- alias: "c",
124
- description: "Remove expired enhancement cache entries",
125
- default: false
126
- },
127
- stats: {
128
- type: "boolean",
129
- alias: "s",
130
- description: "Show cache disk usage",
131
- default: false
132
- }
133
- },
134
- async run({ args }) {
135
- if (args.stats) {
136
- p.intro(`${styleText(["bold", "magenta"], "skilld")} cache stats`);
137
- cacheStatsCommand();
138
- return;
139
- }
140
- if (args.clean) {
141
- p.intro(`${styleText(["bold", "magenta"], "skilld")} cache clean`);
142
- await cacheCleanCommand();
143
- return;
144
- }
145
- p.intro(`${styleText(["bold", "magenta"], "skilld")} cache`);
146
- p.log.message("Usage:\n skilld cache --clean Remove expired cache entries\n skilld cache --stats Show cache disk usage");
147
- }
148
- });
149
- export { cacheCommandDef };
150
-
151
- //# sourceMappingURL=cache2.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache2.mjs","names":[],"sources":["../../src/commands/cache.ts"],"sourcesContent":["/**\n * Cache management commands\n */\n\nimport type { Dirent } from 'node:fs'\nimport { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'\nimport { styleText } from 'node:util'\nimport * as p from '@clack/prompts'\nimport { defineCommand } from 'citty'\nimport { join } from 'pathe'\nimport { CACHE_DIR, REFERENCES_DIR, REPOS_DIR } from '../cache/index.ts'\nimport { clearEmbeddingCache } from '../retriv/embedding-cache.ts'\n\nconst LLM_CACHE_DIR = join(CACHE_DIR, 'llm-cache')\nconst LLM_CACHE_MAX_AGE = 7 * 24 * 60 * 60 * 1000\n\nfunction safeRemove(path: string): number {\n try {\n const size = statSync(path).size\n rmSync(path)\n return size\n }\n catch {\n try {\n rmSync(path)\n }\n catch {}\n return 0\n }\n}\n\nexport async function cacheCleanCommand(): Promise<void> {\n let expiredLlm = 0\n let freedBytes = 0\n\n // Clean expired LLM cache entries\n if (existsSync(LLM_CACHE_DIR)) {\n const now = Date.now()\n for (const entry of readdirSync(LLM_CACHE_DIR)) {\n const path = join(LLM_CACHE_DIR, entry)\n try {\n const { timestamp } = JSON.parse(readFileSync(path, 'utf-8'))\n if (now - timestamp > LLM_CACHE_MAX_AGE) {\n freedBytes += safeRemove(path)\n expiredLlm++\n }\n }\n catch {\n // Corrupt cache entry — remove it\n freedBytes += safeRemove(path)\n expiredLlm++\n }\n }\n }\n\n // Clear embedding cache\n const embeddingDbPath = join(CACHE_DIR, 'embeddings.db')\n let embeddingCleared = false\n if (existsSync(embeddingDbPath)) {\n const size = statSync(embeddingDbPath).size\n clearEmbeddingCache()\n freedBytes += size\n embeddingCleared = true\n }\n\n const freedKB = Math.round(freedBytes / 1024)\n if (expiredLlm > 0 || embeddingCleared) {\n const parts: string[] = []\n if (expiredLlm > 0)\n parts.push(`${expiredLlm} expired enhancement cache entries`)\n if (embeddingCleared)\n parts.push('embedding cache')\n p.log.success(`Removed ${parts.join(' + ')} (${freedKB}KB freed)`)\n }\n else {\n p.log.info('Cache is clean — no expired entries')\n }\n}\n\nfunction dirEntries(dir: string): Dirent[] {\n if (!existsSync(dir))\n return []\n return readdirSync(dir, { withFileTypes: true, recursive: true })\n}\n\nfunction sumFileBytes(entries: Dirent[]): number {\n return entries\n .filter(e => e.isFile())\n .reduce((sum, e) => {\n try {\n return sum + statSync(join(e.parentPath, e.name)).size\n }\n catch { return sum }\n }, 0)\n}\n\nfunction fmtBytes(n: number): string {\n const units = ['B', 'KB', 'MB', 'GB'] as const\n let i = 0\n while (n >= 1024 && i < units.length - 1) {\n n /= 1024\n i++\n }\n return i === 0 ? `${n}${units[i]}` : `${n.toFixed(1)}${units[i]}`\n}\n\nexport function cacheStatsCommand(): void {\n const dim = (s: string) => styleText('gray', s)\n\n const refs = dirEntries(REFERENCES_DIR)\n const repos = dirEntries(REPOS_DIR)\n const llm = dirEntries(LLM_CACHE_DIR)\n const embPath = join(CACHE_DIR, 'embeddings.db')\n const embSize = existsSync(embPath) ? statSync(embPath).size : 0\n\n // Count packages: top-level non-scoped dirs + dirs inside @scope/ dirs\n const packages = refs.filter(e =>\n e.isDirectory()\n && (e.parentPath === REFERENCES_DIR\n ? !e.name.startsWith('@')\n : e.parentPath.startsWith(REFERENCES_DIR)),\n ).length\n\n const llmFiles = llm.filter(e => e.isFile())\n const sizes = { refs: sumFileBytes(refs), repos: sumFileBytes(repos), llm: sumFileBytes(llmFiles), emb: embSize }\n const total = sizes.refs + sizes.repos + sizes.llm + sizes.emb\n\n const lines = [\n `References ${fmtBytes(sizes.refs)} ${dim(`${packages} packages`)}`,\n ...(sizes.repos > 0 ? [`Repos ${fmtBytes(sizes.repos)}`] : []),\n `LLM cache ${fmtBytes(sizes.llm)} ${dim(`${llmFiles.length} entries`)}`,\n ...(sizes.emb > 0 ? [`Embeddings ${fmtBytes(sizes.emb)}`] : []),\n '',\n `Total ${fmtBytes(total)} ${dim(CACHE_DIR)}`,\n ]\n p.log.message(lines.join('\\n'))\n}\n\nexport const cacheCommandDef = defineCommand({\n meta: { name: 'cache', description: 'Cache management', hidden: true },\n args: {\n clean: {\n type: 'boolean',\n alias: 'c',\n description: 'Remove expired enhancement cache entries',\n default: false,\n },\n stats: {\n type: 'boolean',\n alias: 's',\n description: 'Show cache disk usage',\n default: false,\n },\n },\n async run({ args }) {\n if (args.stats) {\n p.intro(`${styleText(['bold', 'magenta'], 'skilld')} cache stats`)\n cacheStatsCommand()\n return\n }\n if (args.clean) {\n p.intro(`${styleText(['bold', 'magenta'], 'skilld')} cache clean`)\n await cacheCleanCommand()\n return\n }\n // No flag: show usage\n p.intro(`${styleText(['bold', 'magenta'], 'skilld')} cache`)\n p.log.message('Usage:\\n skilld cache --clean Remove expired cache entries\\n skilld cache --stats Show cache disk usage')\n },\n})\n"],"mappings":";;;;;;;;AAaA,MAAM,gBAAgB,KAAK,WAAW,WAAW;AACjD,MAAM,oBAAoB;AAE1B,SAAS,WAAW,MAAsB;CACxC,IAAI;EACF,MAAM,OAAO,SAAS,IAAI,CAAC,CAAC;EAC5B,OAAO,IAAI;EACX,OAAO;CACT,QACM;EACJ,IAAI;GACF,OAAO,IAAI;EACb,QACM,CAAC;EACP,OAAO;CACT;A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M,GAAG,GAAG,IAAI,CAAC;EAC9D;EACA,eAAe,SAAS,KAAK,EAAE,IAAI,IAAI,SAAS;CAClD;CACA,EAAE,IAAI,QAAQ,MAAM,KAAK,IAAI,CAAC;AAChC;AAEA,MAAa,kBAAkB,cAAc;CAC3C,MAAM;EAAE,MAAM;EAAS,aAAa;EAAoB,QAAQ;CAAK;CACrE,MAAM;EACJ,OAAO;GACL,MAAM;GACN,OAAO;GACP,aAAa;GACb,SAAS;EACX;EACA,OAAO;GACL,MAAM;GACN,OAAO;GACP,aAAa;GACb,SAAS;EACX;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI,KAAK,OAAO;GACd,EAAE,MAAM,GAAG,UAAU,CAAC,QAAQ,SAAS,GAAG,QAAQ,EAAE,aAAa;GACjE,kBAAkB;GAClB;EACF;EACA,IAAI,KAAK,OAAO;GACd,EAAE,MAAM,GAAG,UAAU,CAAC,QAAQ,SAAS,GAAG,QAAQ,EAAE,aAAa;GACjE,MAAM,kBAAkB;GACxB;EACF;EAEA,EAAE,MAAM,GAAG,UAAU,CAAC,QAAQ,SAAS,GAAG,QAAQ,EAAE,OAAO;EAC3D,EAAE,IAAI,QAAQ,+GAA+G;CAC/H;AACF,CAAC"}
@@ -1,49 +0,0 @@
1
- import { loadSession, peekMarker, updateMarker } from "./store.mjs";
2
- import { createRegistryClient } from "./client.mjs";
3
- import { styleText } from "node:util";
4
- import * as p from "@clack/prompts";
5
- const RELATIVE_FORMATTER = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
6
- function relative(iso, now = Date.now()) {
7
- const minutes = (new Date(iso).getTime() - now) / 1e3 / 60;
8
- if (Math.abs(minutes) < 60) return RELATIVE_FORMATTER.format(Math.round(minutes), "minute");
9
- const hours = minutes / 60;
10
- if (Math.abs(hours) < 24) return RELATIVE_FORMATTER.format(Math.round(hours), "hour");
11
- return RELATIVE_FORMATTER.format(Math.round(hours / 24), "day");
12
- }
13
- function formatDigestLines(entries, now = Date.now()) {
14
- const byRepo = /* @__PURE__ */ new Map();
15
- for (const entry of entries) {
16
- const list = byRepo.get(entry.repo) ?? [];
17
- list.push(entry);
18
- byRepo.set(entry.repo, list);
19
- }
20
- const lines = [];
21
- for (const [repo, items] of byRepo) {
22
- lines.push(styleText("cyan", repo));
23
- for (const item of items) {
24
- const when = styleText("gray", relative(item.at, now));
25
- lines.push(` ${styleText("green", "•")} ${item.skill} ${when}`);
26
- if (item.summary) lines.push(` ${styleText("gray", item.summary)}`);
27
- lines.push(` ${styleText("gray", `https://skilld.dev/gh/${item.repo}/${encodeURIComponent(item.skill)}`)}`);
28
- }
29
- }
30
- return lines;
31
- }
32
- function renderDigest(entries) {
33
- if (entries.length === 0) {
34
- p.log.success("No new updates since last digest.");
35
- return;
36
- }
37
- p.log.message(formatDigestLines(entries).join("\n"));
38
- }
39
- async function renderChangesDigest(showEmpty = false) {
40
- if (!await loadSession()) return "auth-required";
41
- const marker = peekMarker();
42
- const digest = await createRegistryClient().my.changes({ since: marker?.lastDigestAt });
43
- if (digest.entries.length > 0 || showEmpty) renderDigest(digest.entries);
44
- updateMarker({ lastDigestAt: digest.windowEnd });
45
- return digest.entries.length > 0 ? "shown" : "empty";
46
- }
47
- export { renderChangesDigest };
48
-
49
- //# sourceMappingURL=changes-digest.mjs.map