@blockrun/franklin 3.28.5 → 3.29.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.
@@ -219,7 +219,7 @@ const DIRECT_COMMANDS = {
219
219
  if (ctx.skillRegistry) {
220
220
  const visible = ctx.skillRegistry
221
221
  .list()
222
- .filter((l) => !l.skill.disableModelInvocation);
222
+ .filter((l) => !l.skill.disableModelInvocation && !l.skill.hidden);
223
223
  if (visible.length > 0) {
224
224
  skillsBlock =
225
225
  `\n **Skills:**\n` +
@@ -318,20 +318,48 @@ const DIRECT_COMMANDS = {
318
318
  emitDone(ctx);
319
319
  },
320
320
  '/mcp': async (ctx) => {
321
- const { listMcpServers } = await import('../mcp/client.js');
321
+ const { listMcpServers, listMcpFailures, getMcpStderrTail } = await import('../mcp/client.js');
322
322
  const servers = listMcpServers();
323
- if (servers.length === 0) {
324
- ctx.onEvent({ kind: 'text_delta', text: 'No MCP servers connected.\nAdd servers to `~/.blockrun/mcp.json` or `.mcp.json` in your project.\n' });
323
+ const failures = listMcpFailures();
324
+ let text = '';
325
+ if (servers.length === 0 && failures.length === 0) {
326
+ text = 'No MCP servers connected.\nAdd servers to `~/.blockrun/mcp.json` or `.mcp.json` in your project.\n';
325
327
  }
326
328
  else {
327
- let text = `**${servers.length} MCP server(s) connected:**\n\n`;
329
+ if (servers.length > 0) {
330
+ text += `**${servers.length} MCP server(s) connected:**\n\n`;
331
+ for (const s of servers) {
332
+ const oauthFlag = s.hasOAuth ? (s.oauthAuthorized ? ' · oauth ✓' : ' · oauth ✗') : '';
333
+ const filterNote = s.filtered > 0 ? ` (+${s.filtered} hidden by enabled_tools/disabled_tools)` : '';
334
+ text += ` **${s.name}** [${s.transport}] — ${s.toolCount} tools${filterNote}${oauthFlag}\n`;
335
+ for (const t of s.tools)
336
+ text += ` · ${t}\n`;
337
+ }
338
+ }
339
+ if (failures.length > 0) {
340
+ text += `\n**${failures.length} MCP server(s) failed to connect:**\n\n`;
341
+ for (const f of failures) {
342
+ text += ` **${f.name}** [${f.transport}] — ${f.reason}\n`;
343
+ if (f.stderrTail.length > 0) {
344
+ text += ` stderr (last ${f.stderrTail.length} lines):\n`;
345
+ for (const line of f.stderrTail.slice(-10)) {
346
+ text += ` | ${line.slice(0, 200)}\n`;
347
+ }
348
+ }
349
+ }
350
+ }
351
+ // Surface live stderr from running stdio servers (debug helper).
328
352
  for (const s of servers) {
329
- text += ` **${s.name}** — ${s.toolCount} tools\n`;
330
- for (const t of s.tools)
331
- text += ` · ${t}\n`;
353
+ const tail = getMcpStderrTail(s.name);
354
+ if (tail.length > 0 && s.transport === 'stdio') {
355
+ text += `\n ${s.name} recent stderr (${tail.length} lines):\n`;
356
+ for (const line of tail.slice(-5)) {
357
+ text += ` | ${line.slice(0, 200)}\n`;
358
+ }
359
+ }
332
360
  }
333
- ctx.onEvent({ kind: 'text_delta', text });
334
361
  }
362
+ ctx.onEvent({ kind: 'text_delta', text });
335
363
  emitDone(ctx);
336
364
  },
337
365
  '/context': async (ctx) => {
@@ -9,7 +9,7 @@ import { BLOCKRUN_DIR } from '../config.js';
9
9
  import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
10
10
  import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
12
- import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt, loadSkills, formatSkillsForPrompt } from '../learnings/store.js';
12
+ import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt } from '../learnings/store.js';
13
13
  // ─── System Instructions Assembly ──────────────────────────────────────────
14
14
  // Composable prompt sections — each independently maintainable and conditionally includable.
15
15
  function getCoreInstructions() {
@@ -505,18 +505,12 @@ export function assembleInstructions(workingDir, model) {
505
505
  }
506
506
  }
507
507
  catch { /* learnings are optional — never block startup */ }
508
- // Inject relevant skills (procedural memory from past complex tasks)
509
- try {
510
- const allSkills = loadSkills();
511
- if (allSkills.length > 0) {
512
- // Skills are matched lazily on first user message — for now inject top skills by use count
513
- const topSkills = allSkills.sort((a, b) => b.uses - a.uses).slice(0, 5);
514
- const skillsSection = formatSkillsForPrompt(topSkills);
515
- if (skillsSection)
516
- parts.push(skillsSection);
517
- }
518
- }
519
- catch { /* skills are optional */ }
508
+ // Procedural skills (bundled + learned + user + project) used to be
509
+ // injected here at session boot. They now flow through the unified
510
+ // src/skills/ Registry and are matched per-turn against the user's
511
+ // message in src/skills/triggers.ts, so we no longer pre-inject all
512
+ // top-by-use skills into every system prompt — the per-turn hint is both
513
+ // more relevant and cheaper.
520
514
  // Model-specific execution guidance
521
515
  if (model) {
522
516
  parts.push(getModelGuidance(model));
@@ -6,7 +6,8 @@ import { ModelClient } from './llm.js';
6
6
  import { autoCompactIfNeeded, forceCompact, microCompact, projectCompactionSavings } from './compact.js';
7
7
  import { estimateHistoryTokens, updateActualTokens, resetTokenAnchor, getAnchoredTokenCount, getContextWindow, setEstimationModel } from './tokens.js';
8
8
  import { handleSlashCommand } from './commands.js';
9
- import { loadBundledSkills, getSkillVars } from '../skills/bootstrap.js';
9
+ import { loadAllSkills, getSkillVars } from '../skills/bootstrap.js';
10
+ import { matchSkillTriggers, formatSkillHints } from '../skills/triggers.js';
10
11
  import { reduceTokens } from './reduce.js';
11
12
  import { redactSecrets, stashSecretsToEnv, formatRedactionWarning } from './secret-redact.js';
12
13
  import { PermissionManager } from './permissions.js';
@@ -543,10 +544,12 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
543
544
  config.baseModel = config.model; // User's intended model — /model command updates this
544
545
  let turnFailedModels = new Set(); // Models that failed this turn (cleared each new turn)
545
546
  // ── Skills (file-loaded SKILL.md prompt-rewrite slash commands) ──
546
- // Bundled-only in Phase 1 of the skills MVP. User-global and project-local
547
- // discovery + the budget-cap-usd / cost-receipt enforcement contract land
548
- // in Phase 2 — see docs/plans/2026-04-29-franklin-skills-mvp-design.md.
549
- const skillBoot = loadBundledSkills();
547
+ // Loaded from four sources, precedence project > user > learned > bundled,
548
+ // in a single Registry that handles name conflicts. Learned skills are
549
+ // written by the learnings extractor under ~/.blockrun/skills/learned/
550
+ // and join the same Registry — they show up via trigger matching but are
551
+ // hidden from /help unless the user explicitly lists them.
552
+ const skillBoot = loadAllSkills(workDir);
550
553
  if (skillBoot.errors.length > 0 && config.debug) {
551
554
  for (const err of skillBoot.errors) {
552
555
  onEvent({ kind: 'text_delta', text: `[skills] ${err.path}: ${err.error}\n` });
@@ -724,6 +727,26 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
724
727
  input = redactedText;
725
728
  }
726
729
  lastUserInput = input;
730
+ // ── Skill trigger auto-invoke ──
731
+ // Match the user message against every skill's `triggers:` list. Strong
732
+ // matches surface as a soft hint appended to this turn's system prompt
733
+ // so the model treats the skill's procedure as guidance rather than
734
+ // mandatory rewriting (which would surprise the user). The skill body
735
+ // is NEVER substituted into the visible user message — that breaks the
736
+ // session transcript and the user's intent representation. See
737
+ // src/skills/triggers.ts for the matching algorithm.
738
+ let turnSkillHints = '';
739
+ try {
740
+ const matches = matchSkillTriggers(input, skillRegistry.list());
741
+ if (matches.length > 0) {
742
+ turnSkillHints = formatSkillHints(matches);
743
+ if (config.debug && matches.length > 0) {
744
+ const summary = matches.map(m => `${m.skill.skill.name}(${m.score.toFixed(1)})`).join(', ');
745
+ onEvent({ kind: 'text_delta', text: `*[skill triggers] ${summary}*\n` });
746
+ }
747
+ }
748
+ }
749
+ catch { /* trigger matching is best-effort */ }
727
750
  // Push the user's clean message; any harness-injected annotations
728
751
  // (pushback SYSTEM NOTE, prefetch context block) are applied AFTER
729
752
  // the turn analyzer runs so they get driven by model-decided flags
@@ -1257,6 +1280,11 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1257
1280
  callMaxTokens = 2048; // Short plan output
1258
1281
  callSystemPrompt = systemPrompt + '\n\n' + getPlanningPrompt();
1259
1282
  }
1283
+ // Skill-trigger hints from this turn — see the trigger-match block
1284
+ // above, computed once per user message.
1285
+ if (turnSkillHints) {
1286
+ callSystemPrompt = callSystemPrompt + '\n\n' + turnSkillHints;
1287
+ }
1260
1288
  // ── Hallucination guard for weak models ──
1261
1289
  // Weak / free models (nemotron-ultra, GLM-4, qwen coder, free-profile
1262
1290
  // resolves) have been observed inventing tool names (e.g. MixtureOfAgents)
@@ -4,5 +4,6 @@
4
4
  */
5
5
  export interface SkillsCommandOptions {
6
6
  json?: boolean;
7
+ all?: boolean;
7
8
  }
8
9
  export declare function skillsCommand(action: string | undefined, arg: string | undefined, opts?: SkillsCommandOptions): Promise<void>;
@@ -3,7 +3,7 @@
3
3
  * during a session. Phase 1 of the skills MVP — bundled only.
4
4
  */
5
5
  import chalk from 'chalk';
6
- import { loadBundledSkills } from '../skills/bootstrap.js';
6
+ import { loadAllSkills } from '../skills/bootstrap.js';
7
7
  export async function skillsCommand(action, arg, opts = {}) {
8
8
  const sub = action ?? 'list';
9
9
  if (sub === 'list') {
@@ -19,8 +19,13 @@ export async function skillsCommand(action, arg, opts = {}) {
19
19
  process.exit(1);
20
20
  }
21
21
  function runList(opts) {
22
- const { registry, errors } = loadBundledSkills();
23
- const skills = registry.list();
22
+ const { registry, errors } = loadAllSkills(process.cwd());
23
+ const all = registry.list();
24
+ // Hidden skills (e.g. auto-generated learned skills) stay active for trigger
25
+ // matching and explicit `which` lookup, but are kept out of the default list.
26
+ // `--all` reveals them; `--json` always includes everything for tooling.
27
+ const skills = opts.json || opts.all ? all : all.filter((l) => !l.skill.hidden);
28
+ const hiddenCount = all.length - skills.length;
24
29
  if (opts.json) {
25
30
  process.stdout.write(JSON.stringify({
26
31
  skills: skills.map((l) => ({
@@ -32,6 +37,8 @@ function runList(opts) {
32
37
  costReceipt: l.skill.costReceipt ?? false,
33
38
  budgetCapUsd: l.skill.budgetCapUsd ?? null,
34
39
  disableModelInvocation: l.skill.disableModelInvocation ?? false,
40
+ hidden: l.skill.hidden ?? false,
41
+ autoGenerated: l.skill.autoGenerated ?? false,
35
42
  })),
36
43
  errors,
37
44
  shadowed: registry.shadowed().map((s) => ({
@@ -41,9 +48,12 @@ function runList(opts) {
41
48
  }, null, 2) + '\n');
42
49
  return;
43
50
  }
44
- if (skills.length === 0) {
51
+ if (skills.length === 0 && hiddenCount === 0) {
45
52
  console.log(chalk.dim('No skills loaded.'));
46
53
  }
54
+ else if (skills.length === 0) {
55
+ console.log(chalk.dim(`No visible skills. ${hiddenCount} hidden — run with --all to show.`));
56
+ }
47
57
  else {
48
58
  console.log(chalk.bold(`Skills (${skills.length})`));
49
59
  console.log('');
@@ -56,10 +66,16 @@ function runList(opts) {
56
66
  flags.push(`cap $${l.skill.budgetCapUsd.toFixed(2)}`);
57
67
  if (l.skill.disableModelInvocation)
58
68
  flags.push('manual-only');
69
+ if (l.skill.hidden)
70
+ flags.push('hidden');
59
71
  const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';
60
72
  const sourceTag = chalk.dim(`(${l.source})`);
61
73
  console.log(` ${chalk.cyan('/' + l.skill.name.padEnd(nameWidth))} ${l.skill.description}${flagStr} ${sourceTag}`);
62
74
  }
75
+ if (hiddenCount > 0) {
76
+ console.log('');
77
+ console.log(chalk.dim(` +${hiddenCount} hidden — run with --all to show.`));
78
+ }
63
79
  }
64
80
  const shadowed = registry.shadowed();
65
81
  if (shadowed.length > 0) {
@@ -83,7 +99,7 @@ function runWhich(name) {
83
99
  console.log(chalk.red('Usage: franklin skills which <name>'));
84
100
  process.exit(1);
85
101
  }
86
- const { registry } = loadBundledSkills();
102
+ const { registry } = loadAllSkills(process.cwd());
87
103
  const skill = registry.lookup(name);
88
104
  if (!skill) {
89
105
  console.log(chalk.red(`Skill not found: ${name}`));
package/dist/index.js CHANGED
@@ -158,6 +158,7 @@ program
158
158
  .command('skills [action] [arg]')
159
159
  .description('Manage Franklin skills — list | which <name>')
160
160
  .option('--json', 'Output the skill list as JSON')
161
+ .option('--all', 'Include hidden (auto-generated) skills in the list')
161
162
  .action(async (action, arg, opts) => {
162
163
  const { skillsCommand } = await import('./commands/skills.js');
163
164
  await skillsCommand(action, arg, opts);
@@ -13,13 +13,34 @@ export declare function mergeLearning(existing: Learning[], newEntry: {
13
13
  }): Learning[];
14
14
  export declare function decayLearnings(learnings: Learning[]): Learning[];
15
15
  export declare function formatForPrompt(learnings: Learning[]): string;
16
- /** Load all skills from disk. */
16
+ /**
17
+ * One-time migration of legacy auto-extracted skills.
18
+ *
19
+ * Before the unified registry, learned skills were flat markdown files at
20
+ * `~/.blockrun/skills/<name>.md`. The new layout expects
21
+ * `~/.blockrun/skills/learned/<name>/SKILL.md`, and the user-source loader
22
+ * only reads `<dir>/SKILL.md` — so the old flat files would be silently
23
+ * orphaned on upgrade. This moves each one into the new layout (normalizing
24
+ * it through `saveSkill`, which adds `hidden`/`auto-generated`) and deletes
25
+ * the old file. Idempotent and cheap: returns immediately when there are no
26
+ * flat `.md` files left to migrate.
27
+ */
28
+ export declare function migrateLegacyLearnedSkills(): number;
29
+ /** Load all learned skills from `~/.blockrun/skills/learned/`. */
17
30
  export declare function loadSkills(): Skill[];
18
- /** Save a new skill to disk. */
31
+ /** Save a new auto-extracted skill to disk in unified SKILL.md format. */
19
32
  export declare function saveSkill(skill: Skill): void;
20
33
  /** Bump use count for a skill. */
21
34
  export declare function bumpSkillUse(skill: Skill): void;
22
- /** Find skills relevant to a user message, by trigger matching. */
35
+ /**
36
+ * Compat shim retained so older callers keep working while the rest of the
37
+ * codebase migrates to `src/skills/triggers.ts`. New code should NOT depend
38
+ * on this — it ignores `hidden` and `disableModelInvocation` flags.
39
+ */
23
40
  export declare function matchSkills(input: string, skills: Skill[]): Skill[];
24
- /** Format matched skills for system prompt injection. */
41
+ /**
42
+ * Compat shim. The new code path injects skills per-turn via
43
+ * `formatSkillHints` rather than baking them into the boot-time system
44
+ * prompt, so callers should not need this any more.
45
+ */
25
46
  export declare function formatSkillsForPrompt(skills: Skill[]): string;
@@ -158,25 +158,99 @@ export function formatForPrompt(learnings) {
158
158
  return '# Personal Context\nLearned from previous sessions:\n\n' + sections.join('\n\n');
159
159
  }
160
160
  // ─── Skills (procedural memory) ──────────────────────────────────────────
161
- // Stored as individual markdown files in ~/.blockrun/skills/
162
- // Larger than learnings, conditionally injected based on trigger matching.
161
+ //
162
+ // Auto-extracted "skills" from sessions are now stored under
163
+ // `~/.blockrun/skills/learned/<name>/SKILL.md` in the unified Anthropic
164
+ // SKILL.md format. The skills/ directory layout looks like:
165
+ //
166
+ // ~/.blockrun/skills/
167
+ // ├── my-handwritten/SKILL.md (user-authored)
168
+ // └── learned/
169
+ // ├── refactor-step-flow/SKILL.md (extracted by Franklin)
170
+ // └── pricing-quote-flow/SKILL.md
171
+ //
172
+ // The runtime registry (src/skills/bootstrap.loadAllSkills) discovers all
173
+ // three sources (bundled / learned / user / project) in one pass and
174
+ // trigger matching (src/skills/triggers.matchSkillTriggers) handles
175
+ // auto-invoke. The legacy `loadSkills`/`matchSkills`/`formatSkillsForPrompt`
176
+ // exports below are kept as compat shims (delegating to the new disk layout)
177
+ // so older callers don't break; new code should import from src/skills/.
163
178
  const SKILLS_DIR = path.join(BLOCKRUN_DIR, 'skills');
164
- const MAX_SKILLS_IN_PROMPT = 5;
165
- const MAX_SKILL_CHARS = 1500;
166
- function ensureSkillsDir() {
167
- if (!fs.existsSync(SKILLS_DIR)) {
168
- fs.mkdirSync(SKILLS_DIR, { recursive: true });
179
+ const LEARNED_SKILLS_DIR = path.join(SKILLS_DIR, 'learned');
180
+ function ensureLearnedSkillsDir() {
181
+ if (!fs.existsSync(LEARNED_SKILLS_DIR)) {
182
+ fs.mkdirSync(LEARNED_SKILLS_DIR, { recursive: true });
169
183
  }
170
184
  }
171
- /** Load all skills from disk. */
185
+ /**
186
+ * One-time migration of legacy auto-extracted skills.
187
+ *
188
+ * Before the unified registry, learned skills were flat markdown files at
189
+ * `~/.blockrun/skills/<name>.md`. The new layout expects
190
+ * `~/.blockrun/skills/learned/<name>/SKILL.md`, and the user-source loader
191
+ * only reads `<dir>/SKILL.md` — so the old flat files would be silently
192
+ * orphaned on upgrade. This moves each one into the new layout (normalizing
193
+ * it through `saveSkill`, which adds `hidden`/`auto-generated`) and deletes
194
+ * the old file. Idempotent and cheap: returns immediately when there are no
195
+ * flat `.md` files left to migrate.
196
+ */
197
+ export function migrateLegacyLearnedSkills() {
198
+ let entries;
199
+ try {
200
+ entries = fs.readdirSync(SKILLS_DIR);
201
+ }
202
+ catch {
203
+ return 0; // no skills dir yet — nothing to migrate
204
+ }
205
+ const flatFiles = entries.filter((f) => f.endsWith('.md'));
206
+ if (flatFiles.length === 0)
207
+ return 0;
208
+ let migrated = 0;
209
+ for (const file of flatFiles) {
210
+ const oldPath = path.join(SKILLS_DIR, file);
211
+ try {
212
+ if (!fs.statSync(oldPath).isFile())
213
+ continue;
214
+ const raw = fs.readFileSync(oldPath, 'utf-8');
215
+ const skill = parseSkillFile(raw, file.replace(/\.md$/, ''));
216
+ if (!skill)
217
+ continue;
218
+ const destDir = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name));
219
+ // Don't clobber a skill already present in the new layout.
220
+ if (!fs.existsSync(path.join(destDir, 'SKILL.md'))) {
221
+ saveSkill(skill);
222
+ }
223
+ fs.rmSync(oldPath);
224
+ migrated++;
225
+ }
226
+ catch { /* skip unreadable/locked file */ }
227
+ }
228
+ return migrated;
229
+ }
230
+ function safeDirName(name) {
231
+ return name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() || 'skill';
232
+ }
233
+ function escapeYamlValue(v) {
234
+ if (/[:#'"\n]/.test(v)) {
235
+ return JSON.stringify(v);
236
+ }
237
+ return v;
238
+ }
239
+ /** Load all learned skills from `~/.blockrun/skills/learned/`. */
172
240
  export function loadSkills() {
173
- ensureSkillsDir();
241
+ ensureLearnedSkillsDir();
174
242
  const skills = [];
175
243
  try {
176
- for (const file of fs.readdirSync(SKILLS_DIR).filter(f => f.endsWith('.md'))) {
244
+ for (const entry of fs.readdirSync(LEARNED_SKILLS_DIR)) {
245
+ const dirPath = path.join(LEARNED_SKILLS_DIR, entry);
177
246
  try {
178
- const raw = fs.readFileSync(path.join(SKILLS_DIR, file), 'utf-8');
179
- const skill = parseSkillFile(raw);
247
+ if (!fs.statSync(dirPath).isDirectory())
248
+ continue;
249
+ const filePath = path.join(dirPath, 'SKILL.md');
250
+ if (!fs.existsSync(filePath))
251
+ continue;
252
+ const raw = fs.readFileSync(filePath, 'utf-8');
253
+ const skill = parseSkillFile(raw, entry);
180
254
  if (skill)
181
255
  skills.push(skill);
182
256
  }
@@ -186,49 +260,79 @@ export function loadSkills() {
186
260
  catch { /* dir doesn't exist yet */ }
187
261
  return skills;
188
262
  }
189
- function parseSkillFile(raw) {
190
- const m = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
263
+ function parseSkillFile(raw, fallbackName) {
264
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
191
265
  if (!m)
192
266
  return null;
193
267
  const fm = m[1];
194
- const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim() || '';
268
+ const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim() || fallbackName;
195
269
  const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim() || '';
196
- const triggersRaw = fm.match(/^triggers:\s*\[([^\]]*)\]/m)?.[1] || '';
197
- const triggers = triggersRaw.split(',').map(t => t.trim()).filter(Boolean);
270
+ // Triggers may be a YAML list (- "foo") OR a legacy inline form ([a, b]).
271
+ let triggers = [];
272
+ const inline = fm.match(/^triggers:\s*\[([^\]]*)\]/m)?.[1];
273
+ if (inline !== undefined) {
274
+ triggers = inline.split(',').map(t => t.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
275
+ }
276
+ else {
277
+ const lines = fm.split('\n');
278
+ const triggersIdx = lines.findIndex(l => /^triggers:\s*$/.test(l));
279
+ if (triggersIdx >= 0) {
280
+ for (let i = triggersIdx + 1; i < lines.length; i++) {
281
+ const m = lines[i].match(/^\s+-\s+(.+)$/);
282
+ if (!m)
283
+ break;
284
+ triggers.push(m[1].trim().replace(/^["']|["']$/g, ''));
285
+ }
286
+ }
287
+ }
198
288
  const created = fm.match(/^created:\s*(.+)$/m)?.[1]?.trim() || '';
199
289
  const uses = parseInt(fm.match(/^uses:\s*(\d+)$/m)?.[1] || '0');
200
- const source = fm.match(/^source_session:\s*(.+)$/m)?.[1]?.trim() || '';
290
+ const source = fm.match(/^source(?:[-_]session):\s*(.+)$/m)?.[1]?.trim() || '';
201
291
  if (!name)
202
292
  return null;
203
293
  return { name, description, triggers, steps: m[2].trim(), created, uses, source_session: source };
204
294
  }
205
- /** Save a new skill to disk. */
295
+ /** Save a new auto-extracted skill to disk in unified SKILL.md format. */
206
296
  export function saveSkill(skill) {
207
- ensureSkillsDir();
208
- const filename = skill.name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() + '.md';
209
- const fm = [
210
- '---',
211
- `name: ${skill.name}`,
212
- `description: ${skill.description}`,
213
- `triggers: [${skill.triggers.join(', ')}]`,
214
- `created: ${skill.created}`,
215
- `uses: ${skill.uses}`,
216
- `source_session: ${skill.source_session}`,
217
- '---',
218
- ].join('\n');
219
- fs.writeFileSync(path.join(SKILLS_DIR, filename), `${fm}\n${skill.steps}\n`);
297
+ ensureLearnedSkillsDir();
298
+ const dir = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name));
299
+ fs.mkdirSync(dir, { recursive: true });
300
+ const fmLines = ['---'];
301
+ fmLines.push(`name: ${escapeYamlValue(skill.name)}`);
302
+ fmLines.push(`description: ${escapeYamlValue(skill.description)}`);
303
+ if (skill.triggers.length > 0) {
304
+ fmLines.push(`triggers:`);
305
+ for (const t of skill.triggers) {
306
+ fmLines.push(` - ${escapeYamlValue(t)}`);
307
+ }
308
+ }
309
+ fmLines.push(`hidden: true`);
310
+ fmLines.push(`auto-generated: true`);
311
+ if (skill.created)
312
+ fmLines.push(`created: ${skill.created}`);
313
+ fmLines.push(`uses: ${skill.uses}`);
314
+ if (skill.source_session) {
315
+ fmLines.push(`source-session: ${escapeYamlValue(skill.source_session)}`);
316
+ }
317
+ fmLines.push('---');
318
+ fmLines.push('');
319
+ fmLines.push(skill.steps);
320
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), fmLines.join('\n') + '\n');
220
321
  }
221
322
  /** Bump use count for a skill. */
222
323
  export function bumpSkillUse(skill) {
223
- const filename = skill.name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() + '.md';
224
- const fp = path.join(SKILLS_DIR, filename);
324
+ const filePath = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name), 'SKILL.md');
225
325
  try {
226
- const raw = fs.readFileSync(fp, 'utf-8');
227
- fs.writeFileSync(fp, raw.replace(/^uses:\s*\d+$/m, `uses: ${skill.uses + 1}`));
326
+ const raw = fs.readFileSync(filePath, 'utf-8');
327
+ fs.writeFileSync(filePath, raw.replace(/^uses:\s*\d+$/m, `uses: ${skill.uses + 1}`));
228
328
  }
229
329
  catch { /* non-critical */ }
230
330
  }
231
- /** Find skills relevant to a user message, by trigger matching. */
331
+ /**
332
+ * Compat shim retained so older callers keep working while the rest of the
333
+ * codebase migrates to `src/skills/triggers.ts`. New code should NOT depend
334
+ * on this — it ignores `hidden` and `disableModelInvocation` flags.
335
+ */
232
336
  export function matchSkills(input, skills) {
233
337
  const lower = input.toLowerCase();
234
338
  const scored = [];
@@ -244,12 +348,17 @@ export function matchSkills(input, skills) {
244
348
  if (score > 0)
245
349
  scored.push({ skill: s, score });
246
350
  }
247
- return scored.sort((a, b) => b.score - a.score).slice(0, MAX_SKILLS_IN_PROMPT).map(m => m.skill);
351
+ return scored.sort((a, b) => b.score - a.score).slice(0, 5).map(m => m.skill);
248
352
  }
249
- /** Format matched skills for system prompt injection. */
353
+ /**
354
+ * Compat shim. The new code path injects skills per-turn via
355
+ * `formatSkillHints` rather than baking them into the boot-time system
356
+ * prompt, so callers should not need this any more.
357
+ */
250
358
  export function formatSkillsForPrompt(skills) {
251
359
  if (skills.length === 0)
252
360
  return '';
361
+ const MAX_SKILL_CHARS = 1500;
253
362
  const parts = ['# Learned Skills\nProcedures from previous experience — use when relevant:\n'];
254
363
  for (const s of skills) {
255
364
  const body = s.steps.length > MAX_SKILL_CHARS ? s.steps.slice(0, MAX_SKILL_CHARS) + '\n…' : s.steps;
@@ -1,55 +1,73 @@
1
1
  /**
2
2
  * MCP Client for Franklin.
3
+ *
3
4
  * Connects to MCP servers, discovers tools, and wraps them as CapabilityHandlers.
4
- * Supports stdio and HTTP (SSE) transports.
5
+ * Supports:
6
+ * - stdio transport (local subprocess)
7
+ * - StreamableHTTP transport (remote, with optional OAuth)
8
+ * - SSE transport (legacy remote)
9
+ *
10
+ * Per-server features:
11
+ * - `enabled_tools` / `disabled_tools` allowlist (mirrors Codex)
12
+ * - stderr piping into the franklin debug log so misconfigured servers can
13
+ * be diagnosed without dumping into the user's terminal
14
+ * - OAuth via the SDK's `OAuthClientProvider` contract; tokens persisted
15
+ * under `~/.blockrun/mcp/oauth/<server>.json`
16
+ * - connection status + last-error snapshot surfaced to `/mcp` command
5
17
  */
6
18
  import type { CapabilityHandler } from '../agent/types.js';
7
19
  export interface McpServerConfig {
8
- /** Transport type */
9
- transport: 'stdio' | 'http';
20
+ /** Transport type. `stdio` runs a local subprocess; `http` connects to a
21
+ * remote MCP server via StreamableHTTP (preferred) or SSE (legacy). */
22
+ transport: 'stdio' | 'http' | 'sse';
10
23
  /** For stdio: command to run */
11
24
  command?: string;
12
25
  /** For stdio: arguments */
13
26
  args?: string[];
14
- /** For stdio: environment variables */
27
+ /** For stdio / http: environment / extra headers passthrough */
15
28
  env?: Record<string, string>;
16
- /** For http: server URL */
29
+ /** For http / sse: server URL */
17
30
  url?: string;
18
- /** For http: headers */
31
+ /** For http / sse: static request headers (use OAuth for dynamic auth) */
19
32
  headers?: Record<string, string>;
33
+ /** Allowlist: only expose these tool names to the model (post-discovery).
34
+ * Wildcards not supported — match by exact tool short name. */
35
+ enabled_tools?: string[];
36
+ /** Denylist: hide these tool names. Applied after `enabled_tools`. */
37
+ disabled_tools?: string[];
20
38
  /** Human-readable label */
21
39
  label?: string;
22
- /** Disable this server */
40
+ /** Disable this server entirely */
23
41
  disabled?: boolean;
42
+ /** Enable OAuth flow for http/sse transports. Set to a hint string
43
+ * (e.g. "interactive" or "device") or `true` for the default. */
44
+ oauth?: boolean | {
45
+ scopes?: string[];
46
+ clientName?: string;
47
+ };
24
48
  }
25
49
  export interface McpConfig {
26
50
  mcpServers: Record<string, McpServerConfig>;
27
51
  }
28
- /**
29
- * Connect to all configured MCP servers and return discovered tools.
30
- * Each connection has a 5s timeout to avoid blocking startup.
31
- */
32
52
  export declare function connectMcpServers(config: McpConfig, debug?: boolean): Promise<CapabilityHandler[]>;
33
- /**
34
- * Disconnect all MCP servers.
35
- */
36
53
  export declare function disconnectMcpServers(): Promise<void>;
37
- /**
38
- * Aggregate server-level instructions from all connected MCP servers into a
39
- * single system-prompt section, or '' if no server supplied any.
40
- *
41
- * These come from the `initialize` response of servers Franklin chose to
42
- * connect (built-in, or user-configured + trusted), so they're treated as
43
- * trusted guidance rather than untrusted data. The agent reads this once per
44
- * session to learn each toolset's playbook (which tool for which question,
45
- * common chains, anti-patterns) instead of rediscovering it by trial.
46
- */
47
54
  export declare function getMcpServerInstructions(): string;
48
- /**
49
- * List connected MCP servers and their tools.
50
- */
51
- export declare function listMcpServers(): Array<{
55
+ export interface McpServerStatus {
52
56
  name: string;
57
+ transport: 'stdio' | 'http' | 'sse';
53
58
  toolCount: number;
54
59
  tools: string[];
55
- }>;
60
+ filtered: number;
61
+ hasOAuth: boolean;
62
+ oauthAuthorized: boolean;
63
+ }
64
+ export declare function listMcpServers(): McpServerStatus[];
65
+ export interface McpServerFailure {
66
+ name: string;
67
+ reason: string;
68
+ transport: 'stdio' | 'http' | 'sse';
69
+ stderrTail: string[];
70
+ }
71
+ export declare function listMcpFailures(): McpServerFailure[];
72
+ /** Most recent N stderr lines from a connected stdio MCP server (for `/mcp`). */
73
+ export declare function getMcpStderrTail(name: string): string[];