kovence-cli 1.2.0 → 1.3.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.
@@ -0,0 +1,425 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { ensureStorageDirs, resolvePaths } = require("./paths");
6
+
7
+ const STOP_WORDS = new Set([
8
+ "the",
9
+ "and",
10
+ "for",
11
+ "with",
12
+ "from",
13
+ "this",
14
+ "that",
15
+ "into",
16
+ "your",
17
+ "use",
18
+ "using",
19
+ "make",
20
+ "build",
21
+ "create",
22
+ "write",
23
+ "file",
24
+ "files",
25
+ "code",
26
+ "kore",
27
+ "koro",
28
+ "amar",
29
+ "ekta",
30
+ "jeno",
31
+ "eta",
32
+ "seta",
33
+ "er",
34
+ "te",
35
+ "e",
36
+ "o",
37
+ "tai",
38
+ "project",
39
+ "task",
40
+ "work",
41
+ "help",
42
+ ]);
43
+
44
+ const SYNONYM_GROUPS = [
45
+ [
46
+ "frontend",
47
+ "ui",
48
+ "ux",
49
+ "web",
50
+ "css",
51
+ "html",
52
+ "tailwind",
53
+ "react",
54
+ "next",
55
+ "vue",
56
+ "component",
57
+ "layout",
58
+ "page",
59
+ "design",
60
+ "style",
61
+ "styling",
62
+ "responsive",
63
+ ],
64
+ ["backend", "api", "server", "express", "rest", "graphql", "endpoint", "route", "controller", "middleware"],
65
+ ["database", "db", "sql", "postgres", "mysql", "sqlite", "mongo", "prisma", "schema", "migration"],
66
+ ["auth", "authentication", "login", "oauth", "jwt", "session", "permission", "rbac"],
67
+ ["test", "testing", "unit", "e2e", "spec", "jest", "vitest", "mocha", "playwright"],
68
+ ["deploy", "docker", "kubernetes", "k8s", "ci", "cd", "nginx", "linux"],
69
+ ];
70
+
71
+ function slugifySkillName(raw) {
72
+ return (
73
+ String(raw || "skill")
74
+ .toLowerCase()
75
+ .replace(/[^a-z0-9]+/g, "-")
76
+ .replace(/^-+|-+$/g, "")
77
+ .slice(0, 64) || "skill"
78
+ );
79
+ }
80
+
81
+ function titleFromSlug(slug) {
82
+ return String(slug || "Skill")
83
+ .split(/[-_\s]+/)
84
+ .filter(Boolean)
85
+ .map((w) => w[0].toUpperCase() + w.slice(1))
86
+ .join(" ");
87
+ }
88
+
89
+ function parseListField(raw) {
90
+ const s = String(raw || "").trim();
91
+ if (!s) return [];
92
+ const inner = s.startsWith("[") && s.endsWith("]") ? s.slice(1, -1) : s;
93
+ return inner
94
+ .split(",")
95
+ .map((x) =>
96
+ x
97
+ .trim()
98
+ .replace(/^["']|["']$/g, "")
99
+ .toLowerCase()
100
+ )
101
+ .filter(Boolean);
102
+ }
103
+
104
+ function tokenizeKeywords(text) {
105
+ return String(text || "")
106
+ .toLowerCase()
107
+ .split(/[^a-z0-9_+.-]+/)
108
+ .map((t) => t.replace(/^[.-]+|[.-]+$/g, ""))
109
+ .filter((t) => t.length >= 2 && !STOP_WORDS.has(t));
110
+ }
111
+
112
+ function expandQueryTokens(tokens) {
113
+ const out = new Set(tokens);
114
+ for (const tok of tokens) {
115
+ for (const grp of SYNONYM_GROUPS) {
116
+ if (grp.includes(tok)) {
117
+ for (const syn of grp) out.add(syn);
118
+ }
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+
124
+ function inferTagsFromContent(title, description, body) {
125
+ const freq = new Map();
126
+ const bump = (txt, weight) => {
127
+ for (const tok of tokenizeKeywords(txt)) {
128
+ freq.set(tok, (freq.get(tok) || 0) + weight);
129
+ }
130
+ };
131
+ bump(title, 3);
132
+ bump(description, 2);
133
+ // Boost markdown headings
134
+ for (const line of String(body || "").split(/\r?\n/)) {
135
+ if (/^#{1,3}\s+/.test(line)) bump(line, 2);
136
+ }
137
+ bump(body, 1);
138
+ return [...freq.entries()]
139
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
140
+ .slice(0, 8)
141
+ .map(([k]) => k);
142
+ }
143
+
144
+ /**
145
+ * Parse a markdown skill document (with optional YAML frontmatter) and auto-infer title, description, and tags.
146
+ */
147
+ function parseSkillMarkdown(rawText, fallbackName = "") {
148
+ const text = String(rawText || "")
149
+ .replace(/\r\n/g, "\n")
150
+ .trim();
151
+ const fmMatch = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
152
+ const meta = {};
153
+ let body = text;
154
+
155
+ if (fmMatch) {
156
+ body = fmMatch[2].trim();
157
+ let listKey = null;
158
+ for (const line of fmMatch[1].split("\n")) {
159
+ const listItem = line.match(/^\s*-\s+(.+)$/);
160
+ if (listItem && listKey) {
161
+ if (!Array.isArray(meta[listKey])) meta[listKey] = [];
162
+ meta[listKey].push(listItem[1].trim().replace(/^["']|["']$/g, ""));
163
+ continue;
164
+ }
165
+ const kv = line.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
166
+ if (!kv) {
167
+ listKey = null;
168
+ continue;
169
+ }
170
+ const k = kv[1].trim().toLowerCase();
171
+ const v = kv[2].trim();
172
+ if (!v) {
173
+ meta[k] = [];
174
+ listKey = k;
175
+ } else {
176
+ listKey = null;
177
+ meta[k] = v.replace(/^["']|["']$/g, "");
178
+ }
179
+ }
180
+ }
181
+
182
+ // Extract first markdown heading and first prose paragraph for fallback inference
183
+ let firstHeading = "";
184
+ const proseLines = [];
185
+ for (const line of body.split("\n")) {
186
+ const trimmed = line.trim();
187
+ if (!trimmed) {
188
+ if (proseLines.length) break;
189
+ continue;
190
+ }
191
+ const hMatch = trimmed.match(/^#\s+(.+)$/);
192
+ if (hMatch && !firstHeading) {
193
+ firstHeading = hMatch[1].trim();
194
+ continue;
195
+ }
196
+ if (/^#{1,6}\s/.test(trimmed) || /^```/.test(trimmed)) continue;
197
+ proseLines.push(trimmed.replace(/^[-*]\s+/, ""));
198
+ if (proseLines.join(" ").length >= 200) break;
199
+ }
200
+
201
+ const title = String(meta.title || meta.label || firstHeading || titleFromSlug(meta.name || fallbackName)).trim();
202
+ const slug = slugifySkillName(meta.slug || meta.name || fallbackName || title);
203
+ const inferredDesc = proseLines.join(" ").replace(/\s+/g, " ").trim().slice(0, 240);
204
+ const description = String(meta.description || meta.summary || inferredDesc || title).trim();
205
+
206
+ const rawTags = meta.tags ?? meta.keywords;
207
+ const explicitTags = Array.isArray(rawTags)
208
+ ? rawTags.map((x) => String(x).trim().toLowerCase()).filter(Boolean)
209
+ : typeof rawTags === "string"
210
+ ? parseListField(rawTags)
211
+ : [];
212
+ const tags = [...new Set([...explicitTags, ...inferTagsFromContent(title, description, body)])].slice(0, 12);
213
+
214
+ return {
215
+ slug,
216
+ title,
217
+ description,
218
+ tags,
219
+ body: body || `# ${title}\n\n${description}`,
220
+ };
221
+ }
222
+
223
+ function serializeSkillMarkdown(skill) {
224
+ const cleanTitle = String(skill.title || titleFromSlug(skill.slug)).replace(/"/g, "'");
225
+ const cleanDesc = String(skill.description || cleanTitle)
226
+ .replace(/\r?\n/g, " ")
227
+ .replace(/"/g, "'");
228
+ const tagsList = Array.isArray(skill.tags) ? skill.tags.filter(Boolean) : [];
229
+ const yaml = [
230
+ "---",
231
+ `name: ${slugifySkillName(skill.slug || cleanTitle)}`,
232
+ `title: "${cleanTitle}"`,
233
+ `description: "${cleanDesc}"`,
234
+ `tags: [${tagsList.join(", ")}]`,
235
+ "---",
236
+ "",
237
+ String(skill.body || "").trim(),
238
+ "",
239
+ ];
240
+ return yaml.join("\n");
241
+ }
242
+
243
+ function getSkillDirectories(paths = resolvePaths()) {
244
+ const fallback = !paths?.globalDir || !paths?.projectDir ? resolvePaths(paths?.cwd) : null;
245
+ const globalDir = paths?.globalDir || fallback.globalDir;
246
+ const projectDir = paths?.projectDir || fallback.projectDir;
247
+ return {
248
+ globalSkillsDir: path.join(globalDir, "skills"),
249
+ projectSkillsDir: path.join(projectDir, "skills"),
250
+ };
251
+ }
252
+
253
+ function saveSkillFromMarkdown({
254
+ markdownText = "",
255
+ filePath = "",
256
+ scope = "global",
257
+ title = "",
258
+ description = "",
259
+ tags = null,
260
+ paths = resolvePaths(),
261
+ } = {}) {
262
+ ensureStorageDirs(paths);
263
+ let raw = String(markdownText || "");
264
+ let fallbackName = title || "";
265
+
266
+ if (filePath) {
267
+ const abs = path.resolve(paths.cwd || process.cwd(), filePath);
268
+ if (!fs.existsSync(abs)) {
269
+ throw new Error(`Skill markdown file not found: ${filePath}`);
270
+ }
271
+ raw = fs.readFileSync(abs, "utf8");
272
+ const base = path.basename(abs, path.extname(abs));
273
+ fallbackName = fallbackName || (base.toLowerCase() === "skill" ? path.basename(path.dirname(abs)) : base);
274
+ }
275
+
276
+ if (!raw.trim() && !title && !description) {
277
+ throw new Error("Skill content or file path is required.");
278
+ }
279
+
280
+ const parsed = parseSkillMarkdown(raw, fallbackName);
281
+ if (title) parsed.title = String(title).trim();
282
+ if (description) parsed.description = String(description).trim();
283
+ if (Array.isArray(tags) && tags.length) {
284
+ parsed.tags = [...new Set([...tags.map((t) => String(t).trim().toLowerCase()), ...parsed.tags])].slice(0, 12);
285
+ }
286
+ parsed.slug = slugifySkillName(title ? parsed.title : parsed.slug);
287
+
288
+ const { globalSkillsDir, projectSkillsDir } = getSkillDirectories(paths);
289
+ const targetDir = scope === "project" ? projectSkillsDir : globalSkillsDir;
290
+ fs.mkdirSync(targetDir, { recursive: true });
291
+ const outFile = path.join(targetDir, `${parsed.slug}.md`);
292
+ fs.writeFileSync(outFile, serializeSkillMarkdown(parsed), "utf8");
293
+
294
+ return {
295
+ ...parsed,
296
+ scope,
297
+ filePath: outFile,
298
+ };
299
+ }
300
+
301
+ function loadAllSkills(paths = resolvePaths()) {
302
+ const { globalSkillsDir, projectSkillsDir } = getSkillDirectories(paths);
303
+ const bySlug = new Map();
304
+
305
+ const readDirSkills = (dir, scope) => {
306
+ if (!fs.existsSync(dir)) return;
307
+ let entries = [];
308
+ try {
309
+ entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
310
+ } catch {
311
+ return;
312
+ }
313
+ for (const ent of entries) {
314
+ if (!ent.isFile() && !ent.isSymbolicLink()) continue;
315
+ if (!ent.name.endsWith(".md")) continue;
316
+ const full = path.join(dir, ent.name);
317
+ try {
318
+ const raw = fs.readFileSync(full, "utf8");
319
+ const parsed = parseSkillMarkdown(raw, path.basename(ent.name, ".md"));
320
+ bySlug.set(parsed.slug, {
321
+ ...parsed,
322
+ scope,
323
+ filePath: full,
324
+ });
325
+ } catch {
326
+ // Skip unreadable skill file
327
+ }
328
+ }
329
+ };
330
+
331
+ readDirSkills(globalSkillsDir, "global");
332
+ readDirSkills(projectSkillsDir, "project");
333
+ return [...bySlug.values()].sort((a, b) => a.title.localeCompare(b.title));
334
+ }
335
+
336
+ function removeSkill(identifier, paths = resolvePaths()) {
337
+ const clean = String(identifier || "")
338
+ .trim()
339
+ .toLowerCase();
340
+ if (!clean) return { removed: false, reason: "Skill name or slug is required." };
341
+ const slugTarget = slugifySkillName(clean);
342
+ const skills = loadAllSkills(paths);
343
+ const hit = skills.find((s) => s.slug === slugTarget || s.slug === clean || s.title.toLowerCase() === clean);
344
+ if (!hit) return { removed: false, reason: `Skill '${identifier}' not found.` };
345
+ try {
346
+ fs.unlinkSync(hit.filePath);
347
+ return { removed: true, skill: hit };
348
+ } catch (err) {
349
+ return { removed: false, reason: err.message };
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Score and return stored skills relevant to the user's prompt.
355
+ */
356
+ function matchRelevantSkills(prompt, skills = [], limit = 10) {
357
+ const rawPrompt = String(prompt || "").trim();
358
+ if (!rawPrompt || !Array.isArray(skills) || !skills.length) return [];
359
+ const directTokens = tokenizeKeywords(rawPrompt);
360
+ if (!directTokens.length) return [];
361
+ const expandedTokens = expandQueryTokens(directTokens);
362
+ const lowerPrompt = rawPrompt.toLowerCase();
363
+
364
+ const scored = [];
365
+ for (const s of skills) {
366
+ let score = 0;
367
+ const slugLower = s.slug.toLowerCase();
368
+ const titleLower = s.title.toLowerCase();
369
+ const descLower = s.description.toLowerCase();
370
+ const titleTokens = new Set(tokenizeKeywords(s.title));
371
+ const descTokens = new Set(tokenizeKeywords(s.description));
372
+ const tagTokens = new Set((s.tags || []).map((t) => String(t).toLowerCase()));
373
+ const bodyTokens = new Set(tokenizeKeywords(s.body));
374
+
375
+ if (lowerPrompt.includes(slugLower) || lowerPrompt.includes(titleLower)) {
376
+ score += 12;
377
+ }
378
+ for (const tok of directTokens) {
379
+ if (tagTokens.has(tok) || slugLower.includes(tok)) score += 6;
380
+ if (titleTokens.has(tok) || titleLower.includes(tok)) score += 5;
381
+ if (descTokens.has(tok) || descLower.includes(tok)) score += 3;
382
+ if (bodyTokens.has(tok)) score += 1;
383
+ }
384
+ // Check domain synonym expansions at lower weight so "build a React UI" matches "frontend" skills
385
+ for (const syn of expandedTokens) {
386
+ if (directTokens.includes(syn)) continue;
387
+ if (tagTokens.has(syn)) score += 3;
388
+ if (titleTokens.has(syn)) score += 2;
389
+ if (descTokens.has(syn)) score += 1;
390
+ }
391
+
392
+ if (score > 0) {
393
+ scored.push({ skill: s, score });
394
+ }
395
+ }
396
+
397
+ scored.sort((a, b) => b.score - a.score || a.skill.title.localeCompare(b.skill.title));
398
+ return scored.slice(0, limit).map((x) => x.skill);
399
+ }
400
+
401
+ function formatSelectedSkillsBlock(selectedSkills = []) {
402
+ if (!Array.isArray(selectedSkills) || !selectedSkills.length) return "";
403
+ const parts = [
404
+ `[Active User-Selected Skills (${selectedSkills.length})]`,
405
+ "Follow the guidelines, patterns, and checklists from every selected skill carefully:",
406
+ ];
407
+ for (const s of selectedSkills) {
408
+ parts.push(
409
+ `\n## Skill: ${s.title} (${s.slug})\n${s.description ? `Summary: ${s.description}\n` : ""}${s.body}`
410
+ );
411
+ }
412
+ return parts.join("\n");
413
+ }
414
+
415
+ module.exports = {
416
+ slugifySkillName,
417
+ parseSkillMarkdown,
418
+ serializeSkillMarkdown,
419
+ getSkillDirectories,
420
+ saveSkillFromMarkdown,
421
+ loadAllSkills,
422
+ removeSkill,
423
+ matchRelevantSkills,
424
+ formatSelectedSkillsBlock,
425
+ };
@@ -11,16 +11,17 @@ const READ_TOOLS = new Set([
11
11
  "glob_files",
12
12
  "read_file",
13
13
  "search_files",
14
+ "command_output",
14
15
  "todo_write",
15
16
  "web_search",
16
- "google_search",
17
17
  "git_status",
18
18
  "git_diff",
19
19
  "git_log",
20
20
  "ask_user",
21
+ "task",
21
22
  ]);
22
23
 
23
- const NETWORK_READ_TOOLS = new Set(["web_fetch", "web_search", "google_search"]);
24
+ const NETWORK_READ_TOOLS = new Set(["web_fetch", "web_search"]);
24
25
 
25
26
  const FILE_EDIT_TOOLS = new Set(["write_file", "edit_file", "multi_edit", "apply_patch", "move_file", "mkdir"]);
26
27
 
@@ -39,12 +40,13 @@ const FILE_PATH_TOOLS = new Set([
39
40
  "mkdir",
40
41
  ]);
41
42
 
42
- const MEMORY_WRITE_TOOLS = new Set(["save_session_memory", "save_global_memory", "delete_global_memory"]);
43
+ const MEMORY_WRITE_TOOLS = new Set(["memory", "save_session_memory", "save_global_memory", "delete_global_memory"]);
43
44
 
44
45
  const PLAN_BLOCKED_TOOLS = new Set([
45
46
  ...FILE_EDIT_TOOLS,
46
47
  "delete_file",
47
48
  "download_file",
49
+ "command_kill",
48
50
  ...MEMORY_WRITE_TOOLS,
49
51
  "undo_checkpoint",
50
52
  ]);
@@ -158,6 +160,7 @@ function extractToolPaths(toolName, args, workspaceRoot) {
158
160
  const candidates = [];
159
161
  if (args?.path) candidates.push(args.path);
160
162
  if (args?.file) candidates.push(args.file);
163
+ if (args?.workdir) candidates.push(args.workdir);
161
164
  if (args?.from) candidates.push(args.from);
162
165
  if (args?.to) candidates.push(args.to);
163
166
  if (args?.destination) candidates.push(args.destination);
@@ -704,7 +707,7 @@ function evaluatePermission({
704
707
  }
705
708
 
706
709
  // 5. Non-workspace boundary check (in 'auto' mode, allowed automatically unless explicitly set to 'deny')
707
- if (FILE_PATH_TOOLS.has(toolName)) {
710
+ if (FILE_PATH_TOOLS.has(toolName) || (toolName === "run_command" && args?.workdir)) {
708
711
  const targetPaths = extractToolPaths(toolName, args, workspaceRoot);
709
712
  const outside = targetPaths.find((p) => !isPathInsideWorkspace(p, workspaceRoot, extraDirs));
710
713
  if (outside) {
@@ -753,10 +756,23 @@ function evaluatePermission({
753
756
  return { decision: "allow", risk: isRead ? "LOW" : "MEDIUM" };
754
757
  }
755
758
 
756
- if (READ_TOOLS.has(toolName) || toolName === "web_fetch" || toolName === "save_session_memory") {
759
+ if (
760
+ READ_TOOLS.has(toolName) ||
761
+ toolName === "web_fetch" ||
762
+ toolName === "save_session_memory" ||
763
+ (toolName === "memory" && args?.action === "save_session") ||
764
+ (toolName === "browser" && ["status", "console", "close"].includes(String(args?.action || "").toLowerCase()))
765
+ ) {
757
766
  return { decision: "allow", risk: "LOW" };
758
767
  }
759
768
 
769
+ if (isAcceptEditsMode && toolName === "browser" && String(args?.action || "").toLowerCase() !== "install") {
770
+ const domain = getUrlDomain(args?.url);
771
+ if (!domain || domain === "localhost" || domain === "127.0.0.1" || domain === "::1" || domain === "[::1]") {
772
+ return { decision: "allow", risk: "LOW" };
773
+ }
774
+ }
775
+
760
776
  if (isAcceptEditsMode && (FILE_EDIT_TOOLS.has(toolName) || isReadOnlyCmd)) {
761
777
  return { decision: "allow", risk: isReadOnlyCmd ? "LOW" : "MEDIUM" };
762
778
  }
@@ -809,7 +825,7 @@ function buildSuggestedRules(toolName, args = {}, workspaceRoot = process.cwd())
809
825
  }
810
826
  }
811
827
 
812
- if (toolName === "web_fetch" || toolName === "download_file") {
828
+ if (toolName === "web_fetch" || toolName === "download_file" || toolName === "browser") {
813
829
  const domain = getUrlDomain(args?.url);
814
830
  if (domain) {
815
831
  suggestions.push({
@@ -28,11 +28,14 @@ function normalizeRule(raw) {
28
28
  }
29
29
 
30
30
  function fileForTarget(target, paths = resolvePaths()) {
31
- return target === "project" ? paths.projectPermissionsFile : paths.globalPermissionsFile;
31
+ const p = paths || resolvePaths();
32
+ return target === "project" ? p.projectPermissionsFile : p.globalPermissionsFile;
32
33
  }
33
34
 
34
35
  function loadPermissionRules(target = "global", paths = resolvePaths()) {
36
+ if (paths === null) return [];
35
37
  const file = fileForTarget(target, paths);
38
+ if (!file) return [];
36
39
  const data = readJsonSafe(file, { version: 1, rules: [] });
37
40
  const rawRules = Array.isArray(data?.rules) ? data.rules : [];
38
41
  return rawRules.map(normalizeRule).filter(Boolean);