@kernel.chat/kbot 3.98.0 → 3.99.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -40,6 +40,7 @@ import { LoopDetector } from './godel-limits.js';
40
40
  import { CheckpointManager, newSessionId } from './checkpoint.js';
41
41
  import { TelemetryEmitter } from './telemetry.js';
42
42
  import { loadSkills } from './skills-loader.js';
43
+ import { getSelfAwarenessPrompt } from './self-awareness.js';
43
44
  import { queueSignal, getCollectiveRecommendation, isCollectiveEnabled } from './collective.js';
44
45
  import { subscribeToBlackboard } from './agent-protocol.js';
45
46
  import { ActiveInferenceEngine } from './free-energy.js';
@@ -875,7 +876,8 @@ export async function runAgent(message, options = {}) {
875
876
  // Step 2: Build context (cached — only rebuilt when inputs change)
876
877
  const matrixPrompt = options.agent ? getMatrixSystemPrompt(options.agent) : null;
877
878
  const contextSnippet = options.context ? formatContextForPrompt(options.context) : '';
878
- const skillsSnippet = loadSkills(process.cwd());
879
+ const skillsSnippet = loadSkills(process.cwd(), message);
880
+ const selfAwarenessSnippet = getSelfAwarenessPrompt();
879
881
  const memorySnippet = getMemoryPrompt();
880
882
  const learningContext = buildFullLearningContext(message, process.cwd());
881
883
  const synthesisSnippet = getSynthesisContext(8); // Three-tier memory: reflection layer insights
@@ -995,7 +997,7 @@ Always quote file paths that contain spaces. Never reference internal system nam
995
997
  const promptSections = createPromptSections({
996
998
  persona: PERSONA,
997
999
  matrixPrompt: matrixPrompt || undefined,
998
- contextSnippet: (contextSnippet || '') + repoMapSnippet + graphSnippet + skillsSnippet + skillLibrarySnippet || undefined,
1000
+ contextSnippet: (contextSnippet || '') + repoMapSnippet + graphSnippet + skillsSnippet + skillLibrarySnippet + '\n\n' + selfAwarenessSnippet || undefined,
999
1001
  memorySnippet: (memorySnippet || '') + getDreamPrompt(8) + reflectionSnippet || undefined,
1000
1002
  learningContext: ((learningContext || '') + (synthesisSnippet ? '\n\n' + synthesisSnippet : '') + (correctionsSnippet ? '\n\n' + correctionsSnippet : '')) || undefined,
1001
1003
  });
package/dist/cli.js CHANGED
@@ -835,6 +835,50 @@ async function main() {
835
835
  ignorePatterns,
836
836
  });
837
837
  });
838
+ const skillsCmd = program.command('skills').description('Manage agent skills (agentskills.io format — compatible with Claude Skills, Hermes, Copilot)');
839
+ skillsCmd
840
+ .command('list')
841
+ .description('List all discovered skills')
842
+ .action(async () => {
843
+ const { discoverSkillFiles } = await import('./skills-loader.js');
844
+ const skills = discoverSkillFiles(process.cwd());
845
+ if (skills.length === 0) {
846
+ printInfo('No skills found. Run `kbot skills import --from hermes` to import 76 Hermes skills.');
847
+ return;
848
+ }
849
+ printInfo(`Found ${skills.length} skill${skills.length === 1 ? '' : 's'}:\n`);
850
+ for (const s of skills) {
851
+ const desc = s.description ? ` — ${s.description.slice(0, 70)}` : '';
852
+ printInfo(` ${s.name}${desc}`);
853
+ }
854
+ });
855
+ skillsCmd
856
+ .command('import')
857
+ .description('Import skills from an external agent (Hermes, Claude, or a custom directory)')
858
+ .option('--from <source>', 'Source: hermes, claude, or an absolute path', 'hermes')
859
+ .action(async (opts) => {
860
+ const { importExternalSkills } = await import('./skills-loader.js');
861
+ const { homedir } = await import('node:os');
862
+ const { join } = await import('node:path');
863
+ const { existsSync } = await import('node:fs');
864
+ const sources = {
865
+ hermes: join(homedir(), '.hermes', 'skills'),
866
+ claude: join(homedir(), '.claude', 'skills'),
867
+ };
868
+ const from = opts.from || 'hermes';
869
+ const src = sources[from] || from;
870
+ if (!existsSync(src)) {
871
+ printError(`Source not found: ${src}`);
872
+ if (from === 'hermes')
873
+ printInfo('Install Hermes: `ollama launch hermes --yes --model hermes3:8b`');
874
+ return;
875
+ }
876
+ const result = await importExternalSkills(src);
877
+ printSuccess(`Imported ${result.imported} skill${result.imported === 1 ? '' : 's'} from ${src}`);
878
+ if (result.skipped > 0)
879
+ printInfo(` ${result.skipped} skipped (existing user-authored files preserved)`);
880
+ printInfo(` → ${result.destination}`);
881
+ });
838
882
  program
839
883
  .command('doctor')
840
884
  .description('Diagnose your kbot setup — check everything is working')
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Build the ground-truth prompt block. Cached after first call since
3
+ * version/provider/hardware don't change mid-session.
4
+ */
5
+ export declare function getSelfAwarenessPrompt(): string;
6
+ /** Reset the cache — used by tests and if the provider changes mid-session. */
7
+ export declare function resetSelfAwarenessCache(): void;
8
+ //# sourceMappingURL=self-awareness.d.ts.map
@@ -0,0 +1,76 @@
1
+ // Self-Awareness — ground truth about what kbot is, injected into every prompt.
2
+ //
3
+ // Without this, asking "what model are you running?" produces a hallucinated
4
+ // answer because the LLM has no factual grounding about its host process.
5
+ // With this, the answer matches `kbot doctor` every time.
6
+ //
7
+ // Keep the block small (<200 tokens) — it ships on every turn.
8
+ import { getByokProvider, getProvider, getProviderModel, isLocalProvider } from './auth.js';
9
+ import { getMachineProfile } from './machine.js';
10
+ import { readFileSync } from 'node:fs';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { dirname, join } from 'node:path';
13
+ let cached = null;
14
+ /**
15
+ * Build the ground-truth prompt block. Cached after first call since
16
+ * version/provider/hardware don't change mid-session.
17
+ */
18
+ export function getSelfAwarenessPrompt() {
19
+ if (cached !== null)
20
+ return cached;
21
+ const lines = ['[kbot Ground Truth — authoritative over any model assumption]'];
22
+ // Version (read from package.json)
23
+ try {
24
+ const here = dirname(fileURLToPath(import.meta.url));
25
+ const pkgPath = join(here, '..', 'package.json');
26
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
27
+ lines.push(`- You are @kernel.chat/kbot v${pkg.version} — an open-source terminal AI agent.`);
28
+ }
29
+ catch {
30
+ lines.push('- You are @kernel.chat/kbot — an open-source terminal AI agent.');
31
+ }
32
+ // Active provider + model
33
+ try {
34
+ const provider = getByokProvider();
35
+ const cfg = getProvider(provider);
36
+ const model = getProviderModel(provider, 'default');
37
+ const local = isLocalProvider(provider) ? ' (local, $0 cost)' : '';
38
+ lines.push(`- Active provider: ${cfg.name}${local} — model: ${model}`);
39
+ }
40
+ catch {
41
+ // Provider not configured yet
42
+ }
43
+ // Machine
44
+ try {
45
+ const m = getMachineProfile();
46
+ if (m) {
47
+ const parts = [];
48
+ if (m.cpu?.chip)
49
+ parts.push(m.cpu.chip);
50
+ else if (m.cpu?.model)
51
+ parts.push(m.cpu.model);
52
+ if (m.gpu?.[0]?.model)
53
+ parts.push(`GPU: ${m.gpu[0].model}`);
54
+ if (m.memory?.total)
55
+ parts.push(`${m.memory.total} RAM`);
56
+ if (parts.length > 0)
57
+ lines.push(`- Host: ${parts.join(', ')}`);
58
+ }
59
+ }
60
+ catch {
61
+ // Machine profile not yet probed
62
+ }
63
+ // Platform
64
+ lines.push(`- Platform: ${process.platform} (Node ${process.version})`);
65
+ // Transport
66
+ lines.push('- Tool calls: JSON schemas validated by Zod; MCP for external servers; no WebSockets; no GPT-4 — those are common misconceptions to correct if asked.');
67
+ // Skill system
68
+ lines.push('- Skills: markdown + YAML frontmatter at ~/.kbot/skills/ (agentskills.io format). Bundled skills ship with the npm package.');
69
+ cached = lines.join('\n');
70
+ return cached;
71
+ }
72
+ /** Reset the cache — used by tests and if the provider changes mid-session. */
73
+ export function resetSelfAwarenessCache() {
74
+ cached = null;
75
+ }
76
+ //# sourceMappingURL=self-awareness.js.map
@@ -2,16 +2,48 @@ export interface SkillFile {
2
2
  name: string;
3
3
  path: string;
4
4
  content: string;
5
+ description: string;
6
+ tags: string[];
5
7
  tokens: number;
8
+ /** Skill only activates when these toolsets are available (Hermes: requires_toolsets) */
9
+ requiresToolsets: string[];
10
+ /** Skill only activates when these toolsets are UNAVAILABLE (fallback path) */
11
+ fallbackForToolsets: string[];
12
+ /** OS platforms this skill supports; empty = all */
13
+ platforms: string[];
14
+ /** Related skill names */
15
+ relatedSkills: string[];
16
+ /** True for skills that ship with kbot or declare `metadata.kbot.*` — boosted in ranking */
17
+ native: boolean;
18
+ }
19
+ export interface SkillLoadContext {
20
+ /** Toolsets currently available — skills can require/fall-back based on these */
21
+ availableToolsets?: string[];
22
+ /** Current OS platform, e.g. 'darwin' | 'linux' | 'win32' */
23
+ platform?: string;
6
24
  }
7
25
  /**
8
- * Discover and load skill files from project and global directories.
9
- * Returns formatted string ready to inject into system prompt.
26
+ * Discover and load skill files. Returns a prompt-ready string.
27
+ * When `message` is provided, skills are scored for relevance and only the
28
+ * most relevant are included (keeps token budget tight with a large library).
10
29
  */
11
- export declare function loadSkills(projectRoot: string): string;
30
+ export declare function loadSkills(projectRoot: string, message?: string, ctx?: SkillLoadContext): string;
12
31
  /**
13
- * Discover .md files from both project-local and global skill directories.
14
- * Project skills take precedence (loaded first, consume token budget first).
32
+ * Walk both skill roots and return every skill document found.
33
+ * Handles flat files (name.md) AND subdirectory layouts (cat/name/SKILL.md).
34
+ * Project skills take precedence over global skills with the same name.
15
35
  */
16
36
  export declare function discoverSkillFiles(projectRoot: string): SkillFile[];
37
+ export interface ImportResult {
38
+ imported: number;
39
+ skipped: number;
40
+ source: string;
41
+ destination: string;
42
+ }
43
+ /**
44
+ * Copy (as symlinks) every SKILL.md under a foreign skills directory
45
+ * into ~/.kbot/skills/imported/<category>/<name>/SKILL.md.
46
+ * Non-destructive: existing symlinks are replaced, real files are skipped.
47
+ */
48
+ export declare function importExternalSkills(sourceRoot: string): Promise<ImportResult>;
17
49
  //# sourceMappingURL=skills-loader.d.ts.map
@@ -1,92 +1,384 @@
1
- // Skills Loader — Auto-discover and load .md skill files
1
+ // Skills Loader — Auto-discover and load skill documents
2
2
  //
3
- // Skill files are Markdown documents that inject domain knowledge, tool combinations,
4
- // and project-specific patterns into the agent's context. They're the kbot equivalent
5
- // of Copilot's "Agent Skills" or Cursor's "Rules for AI."
3
+ // Supports two formats:
4
+ // 1. kbot native: ~/.kbot/skills/<name>.md (flat)
5
+ // 2. agentskills.io: ~/.kbot/skills/<category>/<name>/SKILL.md (Claude/Hermes/Copilot standard)
6
+ //
7
+ // Frontmatter fields recognized (either format):
8
+ // name | title — skill identifier
9
+ // description — 1-line "when to use this"
10
+ // keywords | tags — list for relevance matching
11
+ // metadata.hermes.tags — agentskills.io tag list (Hermes/Claude)
12
+ // domain — kbot category
6
13
  //
7
14
  // Discovery locations (in priority order):
8
- // 1. ./.kbot/skills/*.md — project-specific skills
9
- // 2. ~/.kbot/skills/*.md — user global skills
15
+ // 1. ./.kbot/skills/ — project-specific
16
+ // 2. ~/.kbot/skills/ — user global (includes imported Hermes/Claude skills)
10
17
  //
11
- // Token budget: 2000 tokens max (~8000 characters) to leave room for
12
- // repo map, learning context, and memory.
13
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
14
- import { join, basename } from 'node:path';
18
+ // Token budget: 2000 tokens max. When a message is provided, skills are
19
+ // scored for relevance and only the top matches are injected — so a user
20
+ // with 200 imported skills doesn't blow the budget on irrelevant docs.
21
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
22
+ import { join, basename, dirname } from 'node:path';
15
23
  import { homedir } from 'node:os';
24
+ import { fileURLToPath } from 'node:url';
25
+ /** Package-bundled skills directory — ships with the npm tarball. */
26
+ function getBundledSkillsDir() {
27
+ // dist/skills-loader.js → ../skills (package root)
28
+ const here = dirname(fileURLToPath(import.meta.url));
29
+ return join(here, '..', 'skills');
30
+ }
16
31
  const MAX_SKILL_TOKENS = 2000;
32
+ const MAX_SKILLS_WITHOUT_MESSAGE = 6; // unfiltered cap
33
+ const MAX_SKILLS_WITH_MESSAGE = 4; // relevance-filtered cap
17
34
  const estimateTokens = (text) => Math.ceil(text.length / 4);
18
35
  /**
19
- * Discover and load skill files from project and global directories.
20
- * Returns formatted string ready to inject into system prompt.
36
+ * Discover and load skill files. Returns a prompt-ready string.
37
+ * When `message` is provided, skills are scored for relevance and only the
38
+ * most relevant are included (keeps token budget tight with a large library).
21
39
  */
22
- export function loadSkills(projectRoot) {
23
- const skills = discoverSkillFiles(projectRoot);
24
- if (skills.length === 0)
40
+ export function loadSkills(projectRoot, message, ctx) {
41
+ const all = discoverSkillFiles(projectRoot);
42
+ if (all.length === 0)
25
43
  return '';
26
- return formatSkillsForPrompt(skills);
44
+ const filtered = applyConditionalActivation(all, ctx);
45
+ if (filtered.length === 0)
46
+ return '';
47
+ const selected = message ? rankByRelevance(filtered, message) : filtered;
48
+ return formatSkillsForPrompt(selected, message ? MAX_SKILLS_WITH_MESSAGE : MAX_SKILLS_WITHOUT_MESSAGE);
27
49
  }
28
50
  /**
29
- * Discover .md files from both project-local and global skill directories.
30
- * Project skills take precedence (loaded first, consume token budget first).
51
+ * Filter skills by platform and toolset conditions.
52
+ * Matches Hermes's activation semantics:
53
+ * - `platforms: [darwin]` — only loads on macOS
54
+ * - `requires_toolsets: [browser]` — only loads when browser tools are available
55
+ * - `fallback_for_toolsets: [browser]` — only loads when browser tools are NOT available
56
+ */
57
+ function applyConditionalActivation(skills, ctx) {
58
+ const platform = ctx?.platform ?? process.platform;
59
+ const toolsets = new Set((ctx?.availableToolsets ?? []).map(t => t.toLowerCase()));
60
+ return skills.filter(s => {
61
+ if (s.platforms.length > 0 && !s.platforms.some(p => platform.startsWith(p)))
62
+ return false;
63
+ if (s.requiresToolsets.length > 0 && !s.requiresToolsets.every(t => toolsets.has(t.toLowerCase())))
64
+ return false;
65
+ if (s.fallbackForToolsets.length > 0 && s.fallbackForToolsets.some(t => toolsets.has(t.toLowerCase())))
66
+ return false;
67
+ return true;
68
+ });
69
+ }
70
+ /**
71
+ * Walk both skill roots and return every skill document found.
72
+ * Handles flat files (name.md) AND subdirectory layouts (cat/name/SKILL.md).
73
+ * Project skills take precedence over global skills with the same name.
31
74
  */
32
75
  export function discoverSkillFiles(projectRoot) {
76
+ // Precedence (first wins on name collision):
77
+ // 1. project-local — most specific, author's own
78
+ // 2. bundled — kbot-curated skills shipping with the package
79
+ // 3. user-global — includes imported third-party skills (symlinks)
33
80
  const locations = [
34
- join(projectRoot, '.kbot', 'skills'), // Project-specific
35
- join(homedir(), '.kbot', 'skills'), // User global
81
+ join(projectRoot, '.kbot', 'skills'),
82
+ getBundledSkillsDir(),
83
+ join(homedir(), '.kbot', 'skills'),
36
84
  ];
37
85
  const skills = [];
38
- const seen = new Set(); // Deduplicate by filename
39
- for (const dir of locations) {
40
- if (!existsSync(dir))
86
+ const seen = new Set();
87
+ for (const root of locations) {
88
+ if (!existsSync(root))
89
+ continue;
90
+ walkSkillRoot(root, skills, seen);
91
+ }
92
+ return skills;
93
+ }
94
+ function walkSkillRoot(root, out, seen, depth = 0) {
95
+ if (depth > 3)
96
+ return; // guard against deep nesting
97
+ let entries;
98
+ try {
99
+ entries = readdirSync(root);
100
+ }
101
+ catch {
102
+ return;
103
+ }
104
+ for (const entry of entries) {
105
+ if (entry.startsWith('.') || entry === 'node_modules')
41
106
  continue;
107
+ const full = join(root, entry);
108
+ let stat;
42
109
  try {
43
- const files = readdirSync(dir)
44
- .filter(f => f.endsWith('.md'))
45
- .sort(); // Alphabetical for deterministic ordering
46
- for (const file of files) {
47
- if (seen.has(file))
48
- continue; // Project overrides global
49
- seen.add(file);
50
- try {
51
- const path = join(dir, file);
52
- const content = readFileSync(path, 'utf-8').trim();
53
- if (content.length === 0)
54
- continue;
55
- skills.push({
56
- name: basename(file, '.md'),
57
- path,
58
- content,
59
- tokens: estimateTokens(content),
60
- });
61
- }
62
- catch { /* permission denied, etc. */ }
110
+ stat = statSync(full);
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ if (stat.isDirectory()) {
116
+ // Subdirectory layout: look for SKILL.md first (agentskills.io standard)
117
+ const skillMd = join(full, 'SKILL.md');
118
+ if (existsSync(skillMd)) {
119
+ tryAddSkill(skillMd, entry, out, seen);
63
120
  }
121
+ else {
122
+ // Category directory — recurse
123
+ walkSkillRoot(full, out, seen, depth + 1);
124
+ }
125
+ }
126
+ else if (entry.endsWith('.md') && entry !== 'README.md') {
127
+ const name = basename(entry, '.md');
128
+ tryAddSkill(full, name, out, seen);
64
129
  }
65
- catch { /* directory read error */ }
66
130
  }
67
- return skills;
131
+ }
132
+ function tryAddSkill(path, fallbackName, out, seen) {
133
+ let content;
134
+ try {
135
+ content = readFileSync(path, 'utf-8').trim();
136
+ }
137
+ catch {
138
+ return;
139
+ }
140
+ if (!content)
141
+ return;
142
+ const parsed = parseFrontmatter(content);
143
+ const name = String(parsed.fm.name ?? parsed.fm.title ?? fallbackName).trim() || fallbackName;
144
+ if (seen.has(name))
145
+ return;
146
+ seen.add(name);
147
+ const description = String(parsed.fm.description ?? '').trim();
148
+ const tags = extractTags(parsed.fm);
149
+ const hermesMeta = parsed.fm.metadata?.hermes ?? {};
150
+ const kbotMeta = parsed.fm.metadata?.kbot ?? {};
151
+ const asList = (v) => {
152
+ if (Array.isArray(v))
153
+ return v.map(String).map(s => s.trim()).filter(Boolean);
154
+ if (typeof v === 'string')
155
+ return v.split(',').map(s => s.trim()).filter(Boolean);
156
+ return [];
157
+ };
158
+ const bundledDir = getBundledSkillsDir();
159
+ const native = path.startsWith(bundledDir) || Object.keys(kbotMeta).length > 0;
160
+ out.push({
161
+ name,
162
+ path,
163
+ content,
164
+ description,
165
+ tags,
166
+ tokens: estimateTokens(content),
167
+ requiresToolsets: [...asList(kbotMeta.requires_toolsets), ...asList(hermesMeta.requires_toolsets)],
168
+ fallbackForToolsets: [...asList(kbotMeta.fallback_for_toolsets), ...asList(hermesMeta.fallback_for_toolsets)],
169
+ platforms: asList(parsed.fm.platforms),
170
+ relatedSkills: [...asList(kbotMeta.related_skills), ...asList(hermesMeta.related_skills)],
171
+ native,
172
+ });
68
173
  }
69
174
  /**
70
- * Format skill files for prompt injection, respecting token budget.
175
+ * Lightweight YAML-frontmatter parser. Handles the subset skills use:
176
+ * key: value
177
+ * key: [a, b, c]
178
+ * metadata:
179
+ * hermes:
180
+ * tags: [x, y]
181
+ * Avoids pulling in a full YAML dep. Good enough for flat skill metadata.
71
182
  */
72
- function formatSkillsForPrompt(skills, maxTokens = MAX_SKILL_TOKENS) {
183
+ function parseFrontmatter(content) {
184
+ if (!content.startsWith('---'))
185
+ return { fm: {}, body: content };
186
+ const end = content.indexOf('\n---', 3);
187
+ if (end < 0)
188
+ return { fm: {}, body: content };
189
+ const yaml = content.slice(3, end).trim();
190
+ const body = content.slice(end + 4).trim();
191
+ const fm = {};
192
+ const stack = [{ indent: -1, obj: fm }];
193
+ for (const rawLine of yaml.split('\n')) {
194
+ const line = rawLine.replace(/\s+$/, '');
195
+ if (!line.trim() || line.trim().startsWith('#'))
196
+ continue;
197
+ const indent = line.match(/^ */)[0].length;
198
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent)
199
+ stack.pop();
200
+ const parent = stack[stack.length - 1].obj;
201
+ const m = line.trim().match(/^([A-Za-z0-9_\-]+)\s*:\s*(.*)$/);
202
+ if (!m)
203
+ continue;
204
+ const [, key, valueRaw] = m;
205
+ const value = valueRaw.trim();
206
+ if (!value) {
207
+ // Nested object
208
+ const child = {};
209
+ parent[key] = child;
210
+ stack.push({ indent, obj: child });
211
+ continue;
212
+ }
213
+ parent[key] = parseScalar(value);
214
+ }
215
+ return { fm, body };
216
+ }
217
+ function parseScalar(value) {
218
+ // Inline list: [a, b, "c"]
219
+ if (value.startsWith('[') && value.endsWith(']')) {
220
+ return value.slice(1, -1)
221
+ .split(',')
222
+ .map(s => s.trim().replace(/^["']|["']$/g, ''))
223
+ .filter(Boolean);
224
+ }
225
+ // Quoted string
226
+ if ((value.startsWith('"') && value.endsWith('"')) ||
227
+ (value.startsWith("'") && value.endsWith("'"))) {
228
+ return value.slice(1, -1);
229
+ }
230
+ return value;
231
+ }
232
+ function extractTags(fm) {
233
+ const tags = [];
234
+ const push = (v) => {
235
+ if (Array.isArray(v))
236
+ tags.push(...v.map(String));
237
+ else if (typeof v === 'string')
238
+ tags.push(...v.split(',').map(s => s.trim()).filter(Boolean));
239
+ };
240
+ push(fm.keywords);
241
+ push(fm.tags);
242
+ const meta = fm.metadata;
243
+ if (meta && typeof meta === 'object') {
244
+ push(meta.hermes?.tags);
245
+ push(meta.claude?.tags);
246
+ }
247
+ return [...new Set(tags.map(t => t.toLowerCase()))];
248
+ }
249
+ // ── Relevance scoring ────────────────────────────────────────────────
250
+ function rankByRelevance(skills, message) {
251
+ const terms = tokenize(message);
252
+ if (terms.size === 0)
253
+ return skills;
254
+ const scored = skills.map(s => ({ skill: s, score: scoreSkill(s, terms) }));
255
+ scored.sort((a, b) => b.score - a.score);
256
+ // Keep skills with at least one hit; fall back to top-N if nothing matches
257
+ const hits = scored.filter(x => x.score > 0);
258
+ return (hits.length > 0 ? hits : scored).map(x => x.skill);
259
+ }
260
+ function scoreSkill(skill, terms) {
261
+ let score = 0;
262
+ const nameTokens = tokenize(skill.name);
263
+ const descTokens = tokenize(skill.description);
264
+ for (const t of terms) {
265
+ if (nameTokens.has(t))
266
+ score += 3;
267
+ if (skill.tags.some(tag => tag === t || tag.includes(t)))
268
+ score += 2;
269
+ if (descTokens.has(t))
270
+ score += 1;
271
+ }
272
+ // Bundled kbot-native skills get a curated-content boost over imported third-party skills.
273
+ // Only applied when the skill already matched on something (score > 0) — we don't surface
274
+ // unrelated native skills over perfectly-matched imported ones.
275
+ if (score > 0 && skill.native)
276
+ score += 2;
277
+ return score;
278
+ }
279
+ const STOPWORDS = new Set([
280
+ 'the', 'a', 'an', 'and', 'or', 'but', 'if', 'then', 'of', 'to', 'for', 'in', 'on', 'at',
281
+ 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'this', 'that', 'it', 'i', 'you',
282
+ 'we', 'they', 'how', 'what', 'when', 'why', 'can', 'do', 'does', 'please',
283
+ ]);
284
+ function tokenize(text) {
285
+ const out = new Set();
286
+ // Split on non-alphanumeric AND on kebab/snake separators so "daemon-deployment"
287
+ // and "skill_self_authorship" both yield useful word tokens.
288
+ for (const raw of text.toLowerCase().split(/[^a-z0-9]+/)) {
289
+ if (raw.length < 3)
290
+ continue;
291
+ if (STOPWORDS.has(raw))
292
+ continue;
293
+ out.add(raw);
294
+ }
295
+ return out;
296
+ }
297
+ // ── Prompt formatting ────────────────────────────────────────────────
298
+ function formatSkillsForPrompt(skills, maxSkills) {
73
299
  const parts = [];
74
300
  let currentTokens = 0;
301
+ let included = 0;
75
302
  for (const skill of skills) {
76
- if (currentTokens + skill.tokens > maxTokens) {
77
- // Try to fit a truncated version
78
- const remaining = maxTokens - currentTokens;
303
+ if (included >= maxSkills)
304
+ break;
305
+ if (currentTokens + skill.tokens > MAX_SKILL_TOKENS) {
306
+ const remaining = MAX_SKILL_TOKENS - currentTokens;
79
307
  if (remaining > 100) {
80
308
  const truncated = skill.content.slice(0, remaining * 4) + '\n...(truncated)';
81
309
  parts.push(`## Skill: ${skill.name}\n${truncated}`);
310
+ included++;
82
311
  }
83
312
  break;
84
313
  }
85
314
  parts.push(`## Skill: ${skill.name}\n${skill.content}`);
86
315
  currentTokens += skill.tokens;
316
+ included++;
87
317
  }
88
318
  if (parts.length === 0)
89
319
  return '';
90
320
  return `\n\n[Custom Skills]\n${parts.join('\n---\n')}`;
91
321
  }
322
+ /**
323
+ * Copy (as symlinks) every SKILL.md under a foreign skills directory
324
+ * into ~/.kbot/skills/imported/<category>/<name>/SKILL.md.
325
+ * Non-destructive: existing symlinks are replaced, real files are skipped.
326
+ */
327
+ export async function importExternalSkills(sourceRoot) {
328
+ const { mkdirSync, symlinkSync, unlinkSync, lstatSync } = await import('node:fs');
329
+ const destRoot = join(homedir(), '.kbot', 'skills', 'imported');
330
+ mkdirSync(destRoot, { recursive: true });
331
+ let imported = 0;
332
+ let skipped = 0;
333
+ const walk = (dir, rel) => {
334
+ let entries;
335
+ try {
336
+ entries = readdirSync(dir);
337
+ }
338
+ catch {
339
+ return;
340
+ }
341
+ for (const e of entries) {
342
+ if (e.startsWith('.'))
343
+ continue;
344
+ const full = join(dir, e);
345
+ let st;
346
+ try {
347
+ st = statSync(full);
348
+ }
349
+ catch {
350
+ continue;
351
+ }
352
+ if (st.isDirectory()) {
353
+ const skillMd = join(full, 'SKILL.md');
354
+ if (existsSync(skillMd)) {
355
+ const destDir = join(destRoot, rel, e);
356
+ mkdirSync(destDir, { recursive: true });
357
+ const destFile = join(destDir, 'SKILL.md');
358
+ try {
359
+ if (existsSync(destFile)) {
360
+ const ls = lstatSync(destFile);
361
+ if (ls.isSymbolicLink())
362
+ unlinkSync(destFile);
363
+ else {
364
+ skipped++;
365
+ continue;
366
+ } // don't clobber user-authored file
367
+ }
368
+ symlinkSync(skillMd, destFile);
369
+ imported++;
370
+ }
371
+ catch {
372
+ skipped++;
373
+ }
374
+ }
375
+ else {
376
+ walk(full, join(rel, e));
377
+ }
378
+ }
379
+ }
380
+ };
381
+ walk(sourceRoot, '');
382
+ return { imported, skipped, source: sourceRoot, destination: destRoot };
383
+ }
92
384
  //# sourceMappingURL=skills-loader.js.map
@@ -193,7 +193,7 @@ export async function trainSelf(opts = {}) {
193
193
  `SYSTEM "You are kbot's self-trained assistant (${mode} mode). You were fine-tuned on the operator's own agent sessions."`,
194
194
  ].join('\n');
195
195
  try {
196
- require('node:fs').writeFileSync(modelfilePath, modelfile);
196
+ writeFileSync(modelfilePath, modelfile);
197
197
  const cmd = `ollama create ${outputName} -f ${modelfilePath}`;
198
198
  const r = shell(cmd);
199
199
  log('deploy', r.ok, Date.now() - t0, r.output.split('\n').slice(-8).join('\n'));