akm-cli 0.1.3 → 0.2.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/asset-registry.js +48 -0
- package/dist/asset-spec.js +11 -32
- package/dist/cli.js +161 -57
- package/dist/completions.js +4 -2
- package/dist/config.js +34 -6
- package/dist/db.js +178 -22
- package/dist/embedder.js +94 -13
- package/dist/file-context.js +3 -0
- package/dist/indexer.js +88 -37
- package/dist/info.js +92 -0
- package/dist/local-search.js +190 -90
- package/dist/manifest.js +172 -0
- package/dist/metadata.js +165 -2
- package/dist/providers/skills-sh.js +21 -12
- package/dist/providers/static-index.js +3 -1
- package/dist/registry-build-index.js +12 -1
- package/dist/registry-resolve.js +10 -7
- package/dist/search-fields.js +69 -0
- package/dist/search-source.js +42 -0
- package/dist/stash-clone.js +3 -1
- package/dist/stash-provider-factory.js +0 -2
- package/dist/stash-providers/filesystem.js +4 -5
- package/dist/stash-providers/git.js +140 -0
- package/dist/stash-providers/index.js +1 -1
- package/dist/stash-providers/openviking.js +36 -25
- package/dist/stash-providers/provider-utils.js +11 -0
- package/dist/stash-search.js +106 -90
- package/dist/stash-show.js +125 -9
- package/dist/usage-events.js +73 -0
- package/dist/version.js +20 -0
- package/dist/walker.js +1 -2
- package/package.json +3 -2
- package/dist/stash-providers/context-hub.js +0 -390
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usage event helpers for telemetry and utility-based re-ranking.
|
|
3
|
+
*
|
|
4
|
+
* Schema (created by ensureUsageEventsSchema):
|
|
5
|
+
* id, event_type, query, entry_id (nullable), entry_ref, signal, metadata, created_at
|
|
6
|
+
*/
|
|
7
|
+
// ── Schema ──────────────────────────────────────────────────────────────────
|
|
8
|
+
export function ensureUsageEventsSchema(db) {
|
|
9
|
+
db.exec(`
|
|
10
|
+
CREATE TABLE IF NOT EXISTS usage_events (
|
|
11
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
12
|
+
event_type TEXT NOT NULL,
|
|
13
|
+
query TEXT,
|
|
14
|
+
entry_id INTEGER,
|
|
15
|
+
entry_ref TEXT,
|
|
16
|
+
signal TEXT,
|
|
17
|
+
metadata TEXT,
|
|
18
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
19
|
+
);
|
|
20
|
+
CREATE INDEX IF NOT EXISTS idx_usage_events_entry ON usage_events(entry_id);
|
|
21
|
+
CREATE INDEX IF NOT EXISTS idx_usage_events_type ON usage_events(event_type);
|
|
22
|
+
CREATE INDEX IF NOT EXISTS idx_usage_events_ref ON usage_events(entry_ref);
|
|
23
|
+
`);
|
|
24
|
+
}
|
|
25
|
+
// ── Insert ───────────────────────────────────────────────────────────────────
|
|
26
|
+
/**
|
|
27
|
+
* Insert a usage event into the database. Fire-and-forget: errors are
|
|
28
|
+
* silently caught so callers are never blocked or disrupted.
|
|
29
|
+
*/
|
|
30
|
+
export function insertUsageEvent(db, event) {
|
|
31
|
+
try {
|
|
32
|
+
db.prepare(`INSERT INTO usage_events (event_type, query, entry_id, entry_ref, signal, metadata)
|
|
33
|
+
VALUES (?, ?, ?, ?, ?, ?)`).run(event.event_type, event.query ?? null, event.entry_id ?? null, event.entry_ref ?? null, event.signal ?? null, event.metadata ?? null);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
/* fire-and-forget: silently ignore errors */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// ── Query ────────────────────────────────────────────────────────────────────
|
|
40
|
+
/**
|
|
41
|
+
* Retrieve usage events, optionally filtered by event_type and/or entry_ref.
|
|
42
|
+
*/
|
|
43
|
+
export function getUsageEvents(db, filters) {
|
|
44
|
+
const conditions = [];
|
|
45
|
+
const params = [];
|
|
46
|
+
if (filters?.event_type) {
|
|
47
|
+
conditions.push("event_type = ?");
|
|
48
|
+
params.push(filters.event_type);
|
|
49
|
+
}
|
|
50
|
+
if (filters?.entry_ref) {
|
|
51
|
+
conditions.push("entry_ref = ?");
|
|
52
|
+
params.push(filters.entry_ref);
|
|
53
|
+
}
|
|
54
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
55
|
+
const sql = `SELECT id, event_type, query, entry_id, entry_ref, signal, metadata, created_at
|
|
56
|
+
FROM usage_events ${where}
|
|
57
|
+
ORDER BY id ASC`;
|
|
58
|
+
return db.prepare(sql).all(...params);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Delete usage events older than the given number of days.
|
|
62
|
+
*/
|
|
63
|
+
export function purgeOldUsageEvents(db, retentionDays) {
|
|
64
|
+
if (!Number.isFinite(retentionDays) || retentionDays <= 0)
|
|
65
|
+
return;
|
|
66
|
+
try {
|
|
67
|
+
const cutoff = new Date(Date.now() - retentionDays * 86_400_000).toISOString();
|
|
68
|
+
db.prepare("DELETE FROM usage_events WHERE created_at < ?").run(cutoff);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
/* Table may not exist yet */
|
|
72
|
+
}
|
|
73
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
// Version: prefer compile-time define, then package.json, then fallback
|
|
4
|
+
export const pkgVersion = (() => {
|
|
5
|
+
// Injected at compile time via `bun build --define`
|
|
6
|
+
if (typeof AKM_VERSION !== "undefined")
|
|
7
|
+
return AKM_VERSION;
|
|
8
|
+
try {
|
|
9
|
+
const pkgPath = path.resolve(import.meta.dir ?? __dirname, "../package.json");
|
|
10
|
+
if (fs.existsSync(pkgPath)) {
|
|
11
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
12
|
+
if (typeof pkg.version === "string")
|
|
13
|
+
return pkg.version;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// swallow — running as compiled binary without package.json
|
|
18
|
+
}
|
|
19
|
+
return "0.0.0-dev";
|
|
20
|
+
})();
|
package/dist/walker.js
CHANGED
|
@@ -9,6 +9,7 @@ import fs from "node:fs";
|
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { isRelevantAssetFile } from "./asset-spec";
|
|
11
11
|
import { buildFileContext } from "./file-context";
|
|
12
|
+
const SKIP_DIRS = new Set([".git", "node_modules", "bin", ".cache"]);
|
|
12
13
|
/**
|
|
13
14
|
* Walk a type root directory and return files grouped by their parent directory.
|
|
14
15
|
*
|
|
@@ -82,7 +83,6 @@ function walkStashGit(stashRoot) {
|
|
|
82
83
|
// result.success is false if the process exited non-zero OR git was not found
|
|
83
84
|
if (!result.success)
|
|
84
85
|
return null;
|
|
85
|
-
const SKIP_DIRS = new Set([".git", "node_modules", "bin", ".cache"]);
|
|
86
86
|
const SKIP_FILES = new Set([".stash.json", ".gitignore", ".gitattributes"]);
|
|
87
87
|
const stdout = Buffer.isBuffer(result.stdout) ? result.stdout.toString("utf8") : String(result.stdout ?? "");
|
|
88
88
|
const files = stdout
|
|
@@ -139,7 +139,6 @@ function isInsideGitRepo(dir) {
|
|
|
139
139
|
/** Manual walk for non-git directories. */
|
|
140
140
|
function walkStashManual(stashRoot) {
|
|
141
141
|
const results = [];
|
|
142
|
-
const SKIP_DIRS = new Set([".git", "node_modules", "bin", ".cache"]);
|
|
143
142
|
const stack = [stashRoot];
|
|
144
143
|
while (stack.length > 0) {
|
|
145
144
|
const current = stack.pop();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "akm-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "CLI tool to search, open, and run extension assets from an akm stash directory.",
|
|
6
6
|
"keywords": [
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"@clack/prompts": "^1.1.0",
|
|
62
|
-
"citty": "^0.2.1"
|
|
62
|
+
"citty": "^0.2.1",
|
|
63
|
+
"yaml": "^2.8.2"
|
|
63
64
|
}
|
|
64
65
|
}
|
|
@@ -1,390 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { fetchWithRetry } from "../common";
|
|
5
|
-
import { ConfigError, NotFoundError, UsageError } from "../errors";
|
|
6
|
-
import { parseFrontmatter, toStringOrUndefined } from "../frontmatter";
|
|
7
|
-
import { extractFrontmatterOnly, extractLineRange, extractSection, formatToc, parseMarkdownToc } from "../markdown";
|
|
8
|
-
import { getRegistryIndexCacheDir } from "../paths";
|
|
9
|
-
import { extractTarGzSecure } from "../registry-install";
|
|
10
|
-
import { registerStashProvider } from "../stash-provider-factory";
|
|
11
|
-
/** Cache TTL before refreshing the mirrored repo (12 hours). */
|
|
12
|
-
const CACHE_TTL_MS = 12 * 60 * 60 * 1000;
|
|
13
|
-
/** Maximum stale age allowed when refresh fails (7 days). */
|
|
14
|
-
const CACHE_STALE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
15
|
-
const CONTEXT_HUB_REF_PREFIX = "context-hub://";
|
|
16
|
-
class ContextHubStashProvider {
|
|
17
|
-
type = "context-hub";
|
|
18
|
-
name;
|
|
19
|
-
repo;
|
|
20
|
-
constructor(config) {
|
|
21
|
-
this.repo = parseContextHubRepoUrl(config.url ?? "");
|
|
22
|
-
this.name = config.name ?? `${this.repo.owner}/${this.repo.repo}`;
|
|
23
|
-
}
|
|
24
|
-
async search(options) {
|
|
25
|
-
try {
|
|
26
|
-
const entries = await this.loadEntries();
|
|
27
|
-
const filtered = entries
|
|
28
|
-
.filter((entry) => matchesType(entry, options.type))
|
|
29
|
-
.map((entry) => ({ entry, score: scoreEntry(entry, options.query) }))
|
|
30
|
-
.filter(({ score }) => options.query.trim() === "" || score > 0)
|
|
31
|
-
.sort((a, b) => b.score - a.score || a.entry.sortName.localeCompare(b.entry.sortName))
|
|
32
|
-
.slice(0, options.limit);
|
|
33
|
-
return {
|
|
34
|
-
hits: filtered.map(({ entry, score }) => entryToHit(entry, score)),
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
catch (err) {
|
|
38
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
39
|
-
return { hits: [], warnings: [`Stash ${this.name}: ${message}`] };
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
async show(ref, view) {
|
|
43
|
-
const filePath = parseContextHubRef(ref);
|
|
44
|
-
const repoDir = await this.loadRepoDir();
|
|
45
|
-
const resolved = resolveCachedFilePath(repoDir, filePath);
|
|
46
|
-
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
|
|
47
|
-
throw new NotFoundError(`Context Hub asset not found: ${filePath}`);
|
|
48
|
-
}
|
|
49
|
-
const raw = fs.readFileSync(resolved, "utf8");
|
|
50
|
-
const parsed = parseFrontmatter(raw);
|
|
51
|
-
const relFromContent = path.posix.normalize(path.relative(path.join(repoDir, "content"), resolved).replace(/\\/g, "/"));
|
|
52
|
-
const author = sanitizeString(relFromContent.split("/")[0] ?? "") || "unknown";
|
|
53
|
-
const name = sanitizeString(toStringOrUndefined(parsed.data.name) ?? path.basename(path.dirname(resolved)));
|
|
54
|
-
const description = sanitizeString(toStringOrUndefined(parsed.data.description), 1000);
|
|
55
|
-
const assetType = path.basename(resolved) === "SKILL.md" ? "skill" : "knowledge";
|
|
56
|
-
const content = renderContentForView(raw, view);
|
|
57
|
-
return {
|
|
58
|
-
type: assetType,
|
|
59
|
-
name: `${author}/${name}`,
|
|
60
|
-
path: ref,
|
|
61
|
-
content,
|
|
62
|
-
description,
|
|
63
|
-
editable: false,
|
|
64
|
-
origin: this.type,
|
|
65
|
-
action: `Context Hub content from ${this.repo.canonicalUrl}`,
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
canShow(ref) {
|
|
69
|
-
return ref.trim().startsWith(CONTEXT_HUB_REF_PREFIX);
|
|
70
|
-
}
|
|
71
|
-
async loadEntries() {
|
|
72
|
-
const cachePaths = getCachePaths(this.repo.canonicalUrl);
|
|
73
|
-
const index = await ensureContextHubMirror(this.repo, cachePaths);
|
|
74
|
-
return index.entries;
|
|
75
|
-
}
|
|
76
|
-
async loadRepoDir() {
|
|
77
|
-
const cachePaths = getCachePaths(this.repo.canonicalUrl);
|
|
78
|
-
await ensureContextHubMirror(this.repo, cachePaths, { requireRepoDir: true });
|
|
79
|
-
return cachePaths.repoDir;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
registerStashProvider("context-hub", (config) => new ContextHubStashProvider(config));
|
|
83
|
-
registerStashProvider("github", (config) => new ContextHubStashProvider(config));
|
|
84
|
-
function getCachePaths(repoUrl) {
|
|
85
|
-
const key = createHash("sha256").update(repoUrl).digest("hex").slice(0, 16);
|
|
86
|
-
const rootDir = path.join(getRegistryIndexCacheDir(), `context-hub-${key}`);
|
|
87
|
-
return {
|
|
88
|
-
rootDir,
|
|
89
|
-
archivePath: path.join(rootDir, "repo.tar.gz"),
|
|
90
|
-
repoDir: path.join(rootDir, "repo"),
|
|
91
|
-
indexPath: path.join(rootDir, "index.json"),
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
async function ensureContextHubMirror(repo, cachePaths, options) {
|
|
95
|
-
const requireRepoDir = options?.requireRepoDir === true;
|
|
96
|
-
const cached = readCachedIndex(cachePaths.indexPath);
|
|
97
|
-
if (cached && !isExpired(cached.mtime, CACHE_TTL_MS) && (!requireRepoDir || hasExtractedRepo(cachePaths.repoDir))) {
|
|
98
|
-
return { entries: cached.entries };
|
|
99
|
-
}
|
|
100
|
-
try {
|
|
101
|
-
fs.mkdirSync(cachePaths.rootDir, { recursive: true });
|
|
102
|
-
await downloadArchive(buildTarballUrl(repo), cachePaths.archivePath);
|
|
103
|
-
extractTarGzSecure(cachePaths.archivePath, cachePaths.repoDir);
|
|
104
|
-
const entries = buildContextHubIndex(cachePaths.repoDir);
|
|
105
|
-
writeCachedIndex(cachePaths.indexPath, entries);
|
|
106
|
-
return { entries };
|
|
107
|
-
}
|
|
108
|
-
catch (err) {
|
|
109
|
-
if (cached &&
|
|
110
|
-
!isExpired(cached.mtime, CACHE_STALE_MS) &&
|
|
111
|
-
(!requireRepoDir || hasExtractedRepo(cachePaths.repoDir))) {
|
|
112
|
-
return { entries: cached.entries };
|
|
113
|
-
}
|
|
114
|
-
throw err;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
function hasExtractedRepo(repoDir) {
|
|
118
|
-
try {
|
|
119
|
-
return fs.statSync(repoDir).isDirectory() && fs.statSync(path.join(repoDir, "content")).isDirectory();
|
|
120
|
-
}
|
|
121
|
-
catch {
|
|
122
|
-
return false;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
function readCachedIndex(indexPath) {
|
|
126
|
-
try {
|
|
127
|
-
const stat = fs.statSync(indexPath);
|
|
128
|
-
const raw = JSON.parse(fs.readFileSync(indexPath, "utf8"));
|
|
129
|
-
if (!Array.isArray(raw))
|
|
130
|
-
return null;
|
|
131
|
-
const entries = raw.filter(isContextHubEntry);
|
|
132
|
-
return { entries, mtime: stat.mtimeMs };
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
function writeCachedIndex(indexPath, entries) {
|
|
139
|
-
const dir = path.dirname(indexPath);
|
|
140
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
141
|
-
const tmpPath = `${indexPath}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
142
|
-
fs.writeFileSync(tmpPath, JSON.stringify(entries), { encoding: "utf8", mode: 0o600 });
|
|
143
|
-
fs.renameSync(tmpPath, indexPath);
|
|
144
|
-
}
|
|
145
|
-
async function downloadArchive(url, destination) {
|
|
146
|
-
const response = await fetchWithRetry(url, undefined, { timeout: 120_000, retries: 1 });
|
|
147
|
-
if (!response.ok) {
|
|
148
|
-
throw new Error(`Failed to download Context Hub archive (${response.status}) from ${url}`);
|
|
149
|
-
}
|
|
150
|
-
const BunRuntime = globalThis.Bun;
|
|
151
|
-
if (BunRuntime?.write) {
|
|
152
|
-
await BunRuntime.write(destination, response);
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
156
|
-
fs.writeFileSync(destination, Buffer.from(arrayBuffer));
|
|
157
|
-
}
|
|
158
|
-
function buildContextHubIndex(repoDir) {
|
|
159
|
-
const contentDir = path.join(repoDir, "content");
|
|
160
|
-
if (!fs.existsSync(contentDir) || !fs.statSync(contentDir).isDirectory()) {
|
|
161
|
-
throw new Error(`Context Hub repo at ${repoDir} is missing a content/ directory`);
|
|
162
|
-
}
|
|
163
|
-
const files = findEntryFiles(contentDir);
|
|
164
|
-
const entries = [];
|
|
165
|
-
for (const filePath of files) {
|
|
166
|
-
const entry = buildEntry(repoDir, contentDir, filePath);
|
|
167
|
-
if (entry)
|
|
168
|
-
entries.push(entry);
|
|
169
|
-
}
|
|
170
|
-
return entries;
|
|
171
|
-
}
|
|
172
|
-
function findEntryFiles(dir) {
|
|
173
|
-
const results = [];
|
|
174
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
175
|
-
const full = path.join(dir, entry.name);
|
|
176
|
-
if (entry.isDirectory()) {
|
|
177
|
-
results.push(...findEntryFiles(full));
|
|
178
|
-
}
|
|
179
|
-
else if (entry.name === "DOC.md" || entry.name === "SKILL.md") {
|
|
180
|
-
results.push(full);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
return results;
|
|
184
|
-
}
|
|
185
|
-
function buildEntry(repoDir, contentDir, fullPath) {
|
|
186
|
-
const raw = fs.readFileSync(fullPath, "utf8");
|
|
187
|
-
const parsed = parseFrontmatter(raw);
|
|
188
|
-
const relPath = path.posix.normalize(path.relative(repoDir, fullPath).replace(/\\/g, "/"));
|
|
189
|
-
const relFromContent = path.posix.normalize(path.relative(contentDir, fullPath).replace(/\\/g, "/"));
|
|
190
|
-
const segments = relFromContent.split("/");
|
|
191
|
-
const author = sanitizeString(segments[0] ?? "");
|
|
192
|
-
if (!author)
|
|
193
|
-
return null;
|
|
194
|
-
const name = sanitizeString(toStringOrUndefined(parsed.data.name) ?? path.basename(path.dirname(fullPath)));
|
|
195
|
-
if (!name)
|
|
196
|
-
return null;
|
|
197
|
-
const metadata = (parsed.data.metadata ?? {});
|
|
198
|
-
const tags = parseCsv(metadata.tags);
|
|
199
|
-
const language = sanitizeString(toStringOrUndefined(metadata.languages));
|
|
200
|
-
const version = sanitizeString(toStringOrUndefined(metadata.versions));
|
|
201
|
-
const id = `${author}/${name}`;
|
|
202
|
-
const assetType = path.basename(fullPath) === "SKILL.md" ? "skill" : "knowledge";
|
|
203
|
-
return {
|
|
204
|
-
id,
|
|
205
|
-
ref: makeContextHubRef(relPath),
|
|
206
|
-
assetType,
|
|
207
|
-
filePath: relPath,
|
|
208
|
-
description: sanitizeString(toStringOrUndefined(parsed.data.description), 1000),
|
|
209
|
-
tags,
|
|
210
|
-
language: language || undefined,
|
|
211
|
-
version: version || undefined,
|
|
212
|
-
sortName: `${id}:${language ?? ""}:${version ?? ""}`,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
function scoreEntry(entry, query) {
|
|
216
|
-
const trimmed = query.trim().toLowerCase();
|
|
217
|
-
if (!trimmed)
|
|
218
|
-
return 1;
|
|
219
|
-
const tokens = trimmed.split(/\s+/).filter(Boolean);
|
|
220
|
-
if (tokens.length === 0)
|
|
221
|
-
return 1;
|
|
222
|
-
const haystacks = [
|
|
223
|
-
{ text: entry.id.toLowerCase(), weight: 4 },
|
|
224
|
-
{ text: entry.description?.toLowerCase() ?? "", weight: 2 },
|
|
225
|
-
{ text: (entry.tags ?? []).join(" ").toLowerCase(), weight: 2 },
|
|
226
|
-
{ text: entry.language?.toLowerCase() ?? "", weight: 1 },
|
|
227
|
-
{ text: entry.version?.toLowerCase() ?? "", weight: 1 },
|
|
228
|
-
];
|
|
229
|
-
let matched = 0;
|
|
230
|
-
let score = 0;
|
|
231
|
-
for (const token of tokens) {
|
|
232
|
-
let tokenScore = 0;
|
|
233
|
-
for (const { text, weight } of haystacks) {
|
|
234
|
-
if (!text)
|
|
235
|
-
continue;
|
|
236
|
-
if (text === token)
|
|
237
|
-
tokenScore = Math.max(tokenScore, weight * 2);
|
|
238
|
-
else if (text.includes(token))
|
|
239
|
-
tokenScore = Math.max(tokenScore, weight);
|
|
240
|
-
}
|
|
241
|
-
if (tokenScore > 0) {
|
|
242
|
-
matched++;
|
|
243
|
-
score += tokenScore;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
if (matched === 0)
|
|
247
|
-
return 0;
|
|
248
|
-
const coverage = matched / tokens.length;
|
|
249
|
-
return Math.round((score * coverage + (entry.id.toLowerCase() === trimmed ? 5 : 0)) * 1000) / 1000;
|
|
250
|
-
}
|
|
251
|
-
function matchesType(entry, requested) {
|
|
252
|
-
if (!requested || requested === "any")
|
|
253
|
-
return true;
|
|
254
|
-
return entry.assetType === requested;
|
|
255
|
-
}
|
|
256
|
-
function entryToHit(entry, score) {
|
|
257
|
-
const details = [entry.language, entry.version].filter(Boolean).join(" • ");
|
|
258
|
-
const description = [entry.description, details].filter(Boolean).join(" — ") || undefined;
|
|
259
|
-
return {
|
|
260
|
-
type: entry.assetType,
|
|
261
|
-
name: entry.id,
|
|
262
|
-
path: entry.ref,
|
|
263
|
-
ref: entry.ref,
|
|
264
|
-
origin: "context-hub",
|
|
265
|
-
editable: false,
|
|
266
|
-
description,
|
|
267
|
-
tags: entry.tags,
|
|
268
|
-
action: `akm show ${entry.ref}`,
|
|
269
|
-
score,
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
function renderContentForView(content, view) {
|
|
273
|
-
if (!view || view.mode === "full")
|
|
274
|
-
return content;
|
|
275
|
-
switch (view.mode) {
|
|
276
|
-
case "toc":
|
|
277
|
-
return formatToc(parseMarkdownToc(content));
|
|
278
|
-
case "frontmatter":
|
|
279
|
-
return extractFrontmatterOnly(content) ?? "(no frontmatter)";
|
|
280
|
-
case "section": {
|
|
281
|
-
const section = extractSection(content, view.heading);
|
|
282
|
-
if (!section) {
|
|
283
|
-
throw new UsageError(`Section not found: ${view.heading}`);
|
|
284
|
-
}
|
|
285
|
-
return section.content;
|
|
286
|
-
}
|
|
287
|
-
case "lines":
|
|
288
|
-
return extractLineRange(content, view.start, view.end);
|
|
289
|
-
default:
|
|
290
|
-
return content;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
function resolveCachedFilePath(repoDir, filePath) {
|
|
294
|
-
const normalized = path.posix.normalize(filePath.replace(/\\/g, "/"));
|
|
295
|
-
if (!normalized.startsWith("content/")) {
|
|
296
|
-
throw new UsageError(`Invalid Context Hub ref: ${filePath}`);
|
|
297
|
-
}
|
|
298
|
-
const resolved = path.resolve(repoDir, normalized);
|
|
299
|
-
const root = path.resolve(repoDir);
|
|
300
|
-
if (!resolved.startsWith(root + path.sep)) {
|
|
301
|
-
throw new UsageError(`Invalid Context Hub ref: ${filePath}`);
|
|
302
|
-
}
|
|
303
|
-
return resolved;
|
|
304
|
-
}
|
|
305
|
-
function buildTarballUrl(repo) {
|
|
306
|
-
return `https://github.com/${repo.owner}/${repo.repo}/archive/refs/heads/${repo.ref}.tar.gz`;
|
|
307
|
-
}
|
|
308
|
-
function parseContextHubRepoUrl(rawUrl) {
|
|
309
|
-
if (!rawUrl) {
|
|
310
|
-
throw new ConfigError("Context Hub provider requires a GitHub repository URL");
|
|
311
|
-
}
|
|
312
|
-
let parsed;
|
|
313
|
-
try {
|
|
314
|
-
parsed = new URL(rawUrl);
|
|
315
|
-
}
|
|
316
|
-
catch {
|
|
317
|
-
throw new ConfigError(`Context Hub URL is not valid: "${rawUrl}"`);
|
|
318
|
-
}
|
|
319
|
-
if (parsed.protocol !== "https:") {
|
|
320
|
-
throw new ConfigError(`Context Hub URL must use https://, got "${parsed.protocol}"`);
|
|
321
|
-
}
|
|
322
|
-
if (parsed.hostname !== "github.com") {
|
|
323
|
-
throw new ConfigError(`Context Hub provider only supports github.com URLs, got "${parsed.hostname}"`);
|
|
324
|
-
}
|
|
325
|
-
const segments = parsed.pathname.split("/").filter(Boolean);
|
|
326
|
-
if (segments.length < 2) {
|
|
327
|
-
throw new ConfigError(`Context Hub URL must point to a GitHub repository, got "${rawUrl}"`);
|
|
328
|
-
}
|
|
329
|
-
const owner = sanitizeString(segments[0]);
|
|
330
|
-
const repo = sanitizeString(segments[1].replace(/\.git$/i, ""));
|
|
331
|
-
let ref = "main";
|
|
332
|
-
if (segments[2] === "tree" && segments.length >= 4) {
|
|
333
|
-
ref = sanitizeString(segments.slice(3).join("/"), 255) || "main";
|
|
334
|
-
}
|
|
335
|
-
if (!owner || !repo || !/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) {
|
|
336
|
-
throw new ConfigError(`Unsupported Context Hub repository URL: "${rawUrl}"`);
|
|
337
|
-
}
|
|
338
|
-
if (!ref || ref.includes("..") || !/^[A-Za-z0-9._/-]+$/.test(ref)) {
|
|
339
|
-
throw new ConfigError(`Unsupported Context Hub branch/ref in URL: "${rawUrl}"`);
|
|
340
|
-
}
|
|
341
|
-
return {
|
|
342
|
-
owner,
|
|
343
|
-
repo,
|
|
344
|
-
ref,
|
|
345
|
-
canonicalUrl: `https://github.com/${owner}/${repo}/tree/${ref}`,
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
function makeContextHubRef(filePath) {
|
|
349
|
-
return `${CONTEXT_HUB_REF_PREFIX}${path.posix.normalize(filePath)}`;
|
|
350
|
-
}
|
|
351
|
-
function parseContextHubRef(ref) {
|
|
352
|
-
const trimmed = ref.trim();
|
|
353
|
-
if (!trimmed.startsWith(CONTEXT_HUB_REF_PREFIX)) {
|
|
354
|
-
throw new UsageError(`Invalid Context Hub ref: ${ref}`);
|
|
355
|
-
}
|
|
356
|
-
const filePath = trimmed.slice(CONTEXT_HUB_REF_PREFIX.length);
|
|
357
|
-
if (!filePath) {
|
|
358
|
-
throw new UsageError(`Invalid Context Hub ref: ${ref}`);
|
|
359
|
-
}
|
|
360
|
-
return filePath;
|
|
361
|
-
}
|
|
362
|
-
function parseCsv(value) {
|
|
363
|
-
if (typeof value !== "string")
|
|
364
|
-
return undefined;
|
|
365
|
-
const items = value
|
|
366
|
-
.split(",")
|
|
367
|
-
.map((item) => sanitizeString(item.trim(), 100))
|
|
368
|
-
.filter(Boolean);
|
|
369
|
-
return items.length > 0 ? items : undefined;
|
|
370
|
-
}
|
|
371
|
-
function sanitizeString(value, maxLength = 255) {
|
|
372
|
-
if (typeof value !== "string")
|
|
373
|
-
return "";
|
|
374
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: strips untrusted control chars from remote metadata
|
|
375
|
-
return value.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, maxLength);
|
|
376
|
-
}
|
|
377
|
-
function isExpired(mtimeMs, ttlMs) {
|
|
378
|
-
return Date.now() - mtimeMs > ttlMs;
|
|
379
|
-
}
|
|
380
|
-
function isContextHubEntry(value) {
|
|
381
|
-
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
382
|
-
return false;
|
|
383
|
-
const obj = value;
|
|
384
|
-
return (typeof obj.id === "string" &&
|
|
385
|
-
typeof obj.ref === "string" &&
|
|
386
|
-
(obj.assetType === "knowledge" || obj.assetType === "skill") &&
|
|
387
|
-
typeof obj.filePath === "string" &&
|
|
388
|
-
typeof obj.sortName === "string");
|
|
389
|
-
}
|
|
390
|
-
export { ContextHubStashProvider, buildContextHubIndex, makeContextHubRef, parseContextHubRef, parseContextHubRepoUrl };
|