@blockrun/franklin 3.49.16 → 3.49.18

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.
@@ -1,14 +1,7 @@
1
- /**
2
- * SKILL.md loader — parses Anthropic-spec frontmatter + markdown body.
3
- *
4
- * The frontmatter parser is intentionally minimal: flat `key: value` lines
5
- * with scalar values (string, boolean, number). Quoted strings, nested
6
- * objects, and arrays are out of scope for MVP — Anthropic's SKILL.md spec
7
- * never needs them and adding a YAML dependency would be heavier than the
8
- * spec warrants.
9
- */
1
+ /** SKILL.md frontmatter and Markdown loader. Metadata is data, never executable. */
10
2
  import { readdirSync, readFileSync, statSync } from 'node:fs';
11
3
  import { join } from 'node:path';
4
+ import { parseDocument } from 'yaml';
12
5
  const FRONTMATTER_FENCE = '---';
13
6
  export function parseSkill(content) {
14
7
  const fmMatch = extractFrontmatter(content);
@@ -20,10 +13,10 @@ export function parseSkill(content) {
20
13
  if ('error' in parsedFrontmatter)
21
14
  return { error: parsedFrontmatter.error };
22
15
  const { fields, warnings } = parsedFrontmatter;
23
- if (typeof fields.name !== 'string' || fields.name.length === 0) {
16
+ if (typeof fields.name !== 'string' || fields.name.trim().length === 0) {
24
17
  return { error: 'frontmatter missing required field: name' };
25
18
  }
26
- if (typeof fields.description !== 'string' || fields.description.length === 0) {
19
+ if (typeof fields.description !== 'string' || fields.description.trim().length === 0) {
27
20
  return { error: 'frontmatter missing required field: description' };
28
21
  }
29
22
  const skill = {
@@ -61,7 +54,7 @@ export function parseSkill(content) {
61
54
  return { skill, warnings };
62
55
  }
63
56
  function extractFrontmatter(content) {
64
- const normalized = content.replace(/\r\n/g, '\n');
57
+ const normalized = content.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
65
58
  if (!normalized.startsWith(FRONTMATTER_FENCE + '\n'))
66
59
  return null;
67
60
  const rest = normalized.slice(FRONTMATTER_FENCE.length + 1);
@@ -72,54 +65,19 @@ function extractFrontmatter(content) {
72
65
  const body = rest.slice(closeIdx + 1 + FRONTMATTER_FENCE.length + 1);
73
66
  return { frontmatter, body };
74
67
  }
75
- const LIST_ITEM_RE = /^\s+-\s+(.+)$/;
76
68
  function parseFrontmatter(text) {
77
- const fields = {};
78
- const warnings = [];
79
- const lines = text.split('\n');
80
- for (let i = 0; i < lines.length; i++) {
81
- const line = lines[i];
82
- if (line.trim() === '' || line.trim().startsWith('#'))
83
- continue;
84
- // YAML list continuation: skip — handled by the key-line that opened it.
85
- if (LIST_ITEM_RE.test(line))
86
- continue;
87
- const colon = line.indexOf(':');
88
- if (colon < 0) {
89
- return { error: `frontmatter line ${i + 1} is not key: value — got "${line}"` };
90
- }
91
- const key = line.slice(0, colon).trim();
92
- const rawValue = line.slice(colon + 1).trim();
93
- if (key.length === 0) {
94
- return { error: `frontmatter line ${i + 1} has empty key` };
95
- }
96
- // Empty value followed by indented `- item` lines = YAML list.
97
- if (rawValue === '') {
98
- const items = [];
99
- let j = i + 1;
100
- while (j < lines.length) {
101
- const next = lines[j];
102
- if (next.trim() === '') {
103
- j++;
104
- continue;
105
- }
106
- const m = LIST_ITEM_RE.exec(next);
107
- if (!m)
108
- break;
109
- items.push(parseScalarString(m[1].trim()));
110
- j++;
111
- }
112
- if (items.length > 0) {
113
- fields[key] = items;
114
- continue;
115
- }
116
- // No list followed; treat as empty string.
117
- fields[key] = '';
118
- continue;
119
- }
120
- fields[key] = parseScalar(rawValue);
69
+ try {
70
+ const doc = parseDocument(text, { schema: 'core', uniqueKeys: true });
71
+ if (doc.errors.length)
72
+ return { error: 'Invalid YAML frontmatter: ' + doc.errors[0].message.split('\n')[0] };
73
+ const fields = doc.toJS({ maxAliasCount: 0 });
74
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields))
75
+ return { error: 'Frontmatter must be a mapping' };
76
+ return { fields: fields, warnings: doc.warnings.map((w) => w.message.split('\n')[0]) };
77
+ }
78
+ catch {
79
+ return { error: 'Invalid YAML frontmatter (aliases are not supported)' };
121
80
  }
122
- return { fields, warnings };
123
81
  }
124
82
  /**
125
83
  * Discover and parse every `<dir>/<name>/SKILL.md` under `root`.
@@ -174,22 +132,3 @@ export function loadSkillsFromDir(root, source) {
174
132
  }
175
133
  return result;
176
134
  }
177
- function parseScalar(raw) {
178
- if (raw === 'true')
179
- return true;
180
- if (raw === 'false')
181
- return false;
182
- if (/^-?\d+$/.test(raw))
183
- return Number.parseInt(raw, 10);
184
- if (/^-?\d+\.\d+$/.test(raw))
185
- return Number.parseFloat(raw);
186
- return parseScalarString(raw);
187
- }
188
- /** Strip surrounding quotes from a string-shaped value, leaving everything else as-is. */
189
- function parseScalarString(raw) {
190
- if ((raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) ||
191
- (raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2)) {
192
- return raw.slice(1, -1);
193
- }
194
- return raw;
195
- }
@@ -0,0 +1,28 @@
1
+ export declare const MAX_SKILL_BYTES: number;
2
+ export declare function listManagedSkills(workDir: string): {
3
+ skills: {
4
+ name: string;
5
+ description: string;
6
+ source: import("./types.js").SkillSource;
7
+ hidden: boolean;
8
+ modelInvocable: boolean;
9
+ enabled: boolean;
10
+ removable: boolean;
11
+ notes: string[];
12
+ }[];
13
+ errors: string[];
14
+ };
15
+ export declare function importSkill(workDir: string, content: unknown): {
16
+ name: string;
17
+ };
18
+ export declare function toggleSkill(workDir: string, name: unknown, enabled: unknown): {
19
+ ok: boolean;
20
+ };
21
+ export declare function removeSkill(workDir: string, name: unknown): {
22
+ ok: boolean;
23
+ };
24
+ /** Same prompt resolver used by slash dispatch; does not call models or tools. */
25
+ export declare function resolveManagedSkill(workDir: string, input: unknown): {
26
+ name: string;
27
+ prompt: string;
28
+ };
@@ -0,0 +1,113 @@
1
+ /** Local skill management. Importing instructions never executes their contents. */
2
+ import { lstatSync, mkdirSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { BLOCKRUN_DIR } from '../config.js';
5
+ import { loadAllSkills } from './bootstrap.js';
6
+ import { parseSkill } from './loader.js';
7
+ import { matchSkill } from './invoke.js';
8
+ import { disabledSkills, setSkillEnabled } from './state.js';
9
+ export const MAX_SKILL_BYTES = 256 * 1024;
10
+ const root = join(BLOCKRUN_DIR, 'skills');
11
+ const reserved = new Set(('learned explain search find refactor scaffold doc moa noplan stash unstash log status diff undo tokens help history transcript bug version mcp context doctor plan ultrathink dump execute sessions cost clear failures compact commit push pr review fix test debug init todo deps optimize security lint migrate clean tasks ultraplan session-search ssearch goal remember flush dream loop market insights learnings brain auto model branch wallet delete resume retry exit').split(' '));
12
+ function validName(name) {
13
+ if (typeof name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name.length > 64)
14
+ throw new Error('Skill name must be lowercase letters, numbers and hyphens (up to 64 characters)');
15
+ }
16
+ function safeRoot() {
17
+ mkdirSync(root, { recursive: true });
18
+ if (!lstatSync(root).isDirectory() || lstatSync(root).isSymbolicLink())
19
+ throw new Error('Skills directory must not be a symlink');
20
+ }
21
+ function describe(entry, disabled) {
22
+ const localBody = entry.skill.body.replace(/https?:\/\/[^\s`"')\]]+/g, '');
23
+ const supportFiles = /(?:\b(?:python3?|node|bash|sh)\s+[^\n`]*\.(?:py|m?js|cjs|sh)\b|(?:scripts|references|assets)\/[^\s`\])]+)/i.test(localBody);
24
+ return {
25
+ name: entry.skill.name, description: entry.skill.description, source: entry.source,
26
+ hidden: !!entry.skill.hidden, modelInvocable: !entry.skill.disableModelInvocation,
27
+ enabled: !disabled.has(entry.skill.name), removable: entry.source === 'user',
28
+ notes: [
29
+ ...(supportFiles ? ['References supporting files. A SKILL.md import does not include those files; provide them separately before use.'] : []),
30
+ ...entry.warnings,
31
+ ],
32
+ };
33
+ }
34
+ export function listManagedSkills(workDir) {
35
+ const loaded = loadAllSkills(workDir, { includeDisabled: true });
36
+ const disabled = disabledSkills();
37
+ return { skills: loaded.registry.list().map((s) => describe(s, disabled)), errors: loaded.errors.map((e) => e.error) };
38
+ }
39
+ export function importSkill(workDir, content) {
40
+ if (typeof content !== 'string' || Buffer.byteLength(content, 'utf8') > MAX_SKILL_BYTES)
41
+ throw new Error('Provide a SKILL.md file up to 256 KiB');
42
+ const parsed = parseSkill(content);
43
+ if ('error' in parsed)
44
+ throw new Error(parsed.error);
45
+ const { name, body, budgetCapUsd } = parsed.skill;
46
+ validName(name);
47
+ if (reserved.has(name))
48
+ throw new Error(`/${name} is reserved by Franklin`);
49
+ if (!body.trim())
50
+ throw new Error('Skill instructions must not be empty');
51
+ if (budgetCapUsd !== undefined && (!Number.isFinite(budgetCapUsd) || budgetCapUsd < 0))
52
+ throw new Error('budget-cap-usd must be a non-negative number');
53
+ if (loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name))
54
+ throw new Error(`/${name} already exists; remove your imported copy before replacing it`);
55
+ safeRoot();
56
+ const dir = join(root, name);
57
+ // mkdir is exclusive, including against dangling symlinks and concurrent imports.
58
+ try {
59
+ mkdirSync(dir, { mode: 0o700 });
60
+ }
61
+ catch (err) {
62
+ if (err.code === 'EEXIST')
63
+ throw new Error(`/${name} already exists on disk`);
64
+ throw err;
65
+ }
66
+ try {
67
+ writeFileSync(join(dir, 'SKILL.md'), content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
68
+ setSkillEnabled(name, true);
69
+ }
70
+ catch (err) {
71
+ try {
72
+ unlinkSync(join(dir, 'SKILL.md'));
73
+ rmdirSync(dir);
74
+ }
75
+ catch { /* preserve unexpected files */ }
76
+ throw err;
77
+ }
78
+ return { name };
79
+ }
80
+ export function toggleSkill(workDir, name, enabled) {
81
+ validName(name);
82
+ if (typeof enabled !== 'boolean')
83
+ throw new Error('enabled must be a boolean');
84
+ if (!loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name))
85
+ throw new Error('Skill not found');
86
+ setSkillEnabled(name, enabled);
87
+ return { ok: true };
88
+ }
89
+ export function removeSkill(workDir, name) {
90
+ validName(name);
91
+ const entry = loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name);
92
+ if (!entry || entry.source !== 'user')
93
+ throw new Error('Only imported user skills can be removed here');
94
+ safeRoot();
95
+ const dir = join(root, name), file = join(dir, 'SKILL.md');
96
+ if (lstatSync(dir).isSymbolicLink() || lstatSync(file).isSymbolicLink())
97
+ throw new Error('Cannot remove a linked skill');
98
+ if (readdirSync(dir).some((f) => f !== 'SKILL.md'))
99
+ throw new Error('Skill contains supporting files; manage its folder directly');
100
+ unlinkSync(file);
101
+ rmdirSync(dir);
102
+ setSkillEnabled(name, true);
103
+ return { ok: true };
104
+ }
105
+ /** Same prompt resolver used by slash dispatch; does not call models or tools. */
106
+ export function resolveManagedSkill(workDir, input) {
107
+ if (typeof input !== 'string' || input.length > MAX_SKILL_BYTES)
108
+ throw new Error('Provide a skill command');
109
+ const match = matchSkill(input, loadAllSkills(workDir).registry, {});
110
+ if (!match)
111
+ throw new Error('Skill not found or disabled');
112
+ return { name: match.skill.name, prompt: match.rewritten };
113
+ }
@@ -0,0 +1,2 @@
1
+ export declare function disabledSkills(): Set<string>;
2
+ export declare function setSkillEnabled(name: string, enabled: boolean): void;
@@ -0,0 +1,26 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { BLOCKRUN_DIR } from '../config.js';
5
+ const stateFile = join(BLOCKRUN_DIR, 'skills-disabled.json');
6
+ export function disabledSkills() {
7
+ if (!existsSync(stateFile))
8
+ return new Set();
9
+ if (lstatSync(stateFile).isSymbolicLink())
10
+ throw new Error('Skill state must not be a symlink');
11
+ const names = JSON.parse(readFileSync(stateFile, 'utf8'));
12
+ if (!Array.isArray(names) || !names.every((n) => typeof n === 'string'))
13
+ throw new Error('Invalid skill state');
14
+ return new Set(names);
15
+ }
16
+ export function setSkillEnabled(name, enabled) {
17
+ const names = disabledSkills();
18
+ if (enabled)
19
+ names.delete(name);
20
+ else
21
+ names.add(name);
22
+ mkdirSync(BLOCKRUN_DIR, { recursive: true });
23
+ const temp = `${stateFile}.${randomUUID()}.tmp`;
24
+ writeFileSync(temp, JSON.stringify([...names]), { mode: 0o600, flag: 'wx' });
25
+ renameSync(temp, stateFile);
26
+ }
@@ -3,7 +3,8 @@
3
3
  */
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { isHostCredentialPath, isWalletKeyPath } from './sensitive-paths.js';
6
+ import { setImmediate as yieldToRequests } from 'node:timers/promises';
7
+ import { isCredentialPathAsync } from './sensitive-paths.js';
7
8
  const MAX_RESULTS = 200;
8
9
  const MAX_OUTPUT_CHARS = 12_000; // ~3,000 tokens — prevents huge glob results from blowing up context
9
10
  /**
@@ -22,14 +23,15 @@ function globMatch(pattern, text) {
22
23
  const regex = new RegExp(`^${regexStr}$`);
23
24
  return regex.test(text.replace(/\\/g, '/'));
24
25
  }
25
- function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
26
+ async function walkDirectory(dir, baseDir, pattern, results, depth, signal, visited) {
27
+ signal.throwIfAborted();
26
28
  if (depth > 50 || results.length >= MAX_RESULTS)
27
29
  return;
28
30
  // Symlink loop protection
29
31
  const visitedSet = visited ?? new Set();
30
32
  let realDir;
31
33
  try {
32
- realDir = fs.realpathSync(dir);
34
+ realDir = await fs.promises.realpath(dir);
33
35
  }
34
36
  catch {
35
37
  return;
@@ -37,18 +39,25 @@ function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
37
39
  if (visitedSet.has(realDir))
38
40
  return;
39
41
  visitedSet.add(realDir);
42
+ signal.throwIfAborted();
40
43
  let entries;
41
44
  try {
42
- entries = fs.readdirSync(dir, { withFileTypes: true });
45
+ entries = await fs.promises.readdir(dir, { withFileTypes: true });
43
46
  }
44
47
  catch {
45
48
  return; // Permission denied or similar
46
49
  }
50
+ let checked = 0;
47
51
  for (const entry of entries) {
52
+ signal.throwIfAborted();
48
53
  if (results.length >= MAX_RESULTS)
49
54
  break;
55
+ // Large flat directories also need to yield, even when nothing matches.
56
+ if (++checked % 128 === 0)
57
+ await yieldToRequests(undefined, { signal });
50
58
  // Skip hidden dirs and common large dirs
51
- const isDir = entry.isDirectory() || (entry.isSymbolicLink() && isSymlinkDir(path.join(dir, entry.name)));
59
+ const isDir = entry.isDirectory() || (entry.isSymbolicLink() && await isSymlinkDir(path.join(dir, entry.name)));
60
+ signal.throwIfAborted();
52
61
  if (entry.name.startsWith('.') && isDir)
53
62
  continue;
54
63
  if (entry.name === 'node_modules' || entry.name === '__pycache__' || entry.name === '.git')
@@ -56,59 +65,78 @@ function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
56
65
  const fullPath = path.join(dir, entry.name);
57
66
  const relativePath = path.relative(baseDir, fullPath);
58
67
  if (entry.isFile() || (entry.isSymbolicLink() && !isDir)) {
59
- // Don't hand the model a map to the key store or host credentials.
60
- if (isWalletKeyPath(fullPath) || isHostCredentialPath(fullPath))
68
+ if (!globMatch(pattern, relativePath))
61
69
  continue;
62
- if (globMatch(pattern, relativePath)) {
70
+ // Don't hand the model a map to the key store or host credentials.
71
+ const secret = await isCredentialPathAsync(fullPath);
72
+ signal.throwIfAborted();
73
+ if (!secret)
63
74
  results.push(fullPath);
64
- }
65
75
  }
66
76
  else if (isDir) {
67
77
  // Recurse for ** patterns; for patterns with /, only recurse if current dir is on the path
68
78
  if (pattern.includes('**')) {
69
- walkDirectory(fullPath, baseDir, pattern, results, depth + 1, visitedSet);
79
+ await walkDirectory(fullPath, baseDir, pattern, results, depth + 1, signal, visitedSet);
70
80
  }
71
81
  else if (pattern.includes('/')) {
72
82
  // Check if this directory could be part of the pattern path
73
83
  const relativePath = path.relative(baseDir, fullPath);
74
84
  const patternDir = pattern.split('/').slice(0, -1).join('/');
75
85
  if (patternDir.startsWith(relativePath) || relativePath.startsWith(patternDir)) {
76
- walkDirectory(fullPath, baseDir, pattern, results, depth + 1, visitedSet);
86
+ await walkDirectory(fullPath, baseDir, pattern, results, depth + 1, signal, visitedSet);
77
87
  }
78
88
  }
79
89
  }
80
90
  }
81
91
  }
82
- function isSymlinkDir(p) {
92
+ async function isSymlinkDir(p) {
83
93
  try {
84
- return fs.statSync(p).isDirectory();
94
+ return (await fs.promises.stat(p)).isDirectory();
85
95
  }
86
96
  catch {
87
97
  return false;
88
98
  }
89
99
  }
90
100
  async function execute(input, ctx) {
101
+ try {
102
+ return await search(input, ctx);
103
+ }
104
+ catch (err) {
105
+ if (ctx.abortSignal.aborted)
106
+ return { output: 'File search cancelled.', isError: true };
107
+ throw err;
108
+ }
109
+ }
110
+ async function search(input, ctx) {
91
111
  const { pattern, path: searchPath } = input;
112
+ ctx.abortSignal.throwIfAborted();
92
113
  if (!pattern) {
93
114
  return { output: 'Error: pattern is required', isError: true };
94
115
  }
95
116
  const baseDir = searchPath
96
117
  ? (path.isAbsolute(searchPath) ? searchPath : path.resolve(ctx.workingDir, searchPath))
97
118
  : ctx.workingDir;
98
- if (!fs.existsSync(baseDir)) {
119
+ try {
120
+ await fs.promises.access(baseDir);
121
+ }
122
+ catch {
99
123
  return { output: `Error: directory not found: ${baseDir}`, isError: true };
100
124
  }
101
125
  const results = [];
102
- walkDirectory(baseDir, baseDir, pattern, results, 0);
126
+ await walkDirectory(baseDir, baseDir, pattern, results, 0, ctx.abortSignal);
127
+ ctx.abortSignal.throwIfAborted();
103
128
  // Sort by modification time (most recent first)
104
- const withMtime = results.map(f => {
129
+ const withMtime = [];
130
+ for (const f of results) {
131
+ ctx.abortSignal.throwIfAborted();
105
132
  try {
106
- return { path: f, mtime: fs.statSync(f).mtimeMs };
133
+ withMtime.push({ path: f, mtime: (await fs.promises.stat(f)).mtimeMs });
107
134
  }
108
135
  catch {
109
- return { path: f, mtime: 0 };
136
+ withMtime.push({ path: f, mtime: 0 });
110
137
  }
111
- });
138
+ }
139
+ ctx.abortSignal.throwIfAborted();
112
140
  withMtime.sort((a, b) => b.mtime - a.mtime);
113
141
  // Convert to relative paths to save tokens
114
142
  const sorted = withMtime.map(f => {
@@ -28,6 +28,8 @@ export declare function walletKeyFilesUnder(absDir: string): string[];
28
28
  * credential store (see hostCredentialDirs / hostCredentialFiles).
29
29
  */
30
30
  export declare function isHostCredentialPath(resolvedAbsPath: string): boolean;
31
+ /** Same file-search exclusion policy without blocking the agent's RPC loop. */
32
+ export declare function isCredentialPathAsync(resolvedAbsPath: string): Promise<boolean>;
31
33
  /** Home-relative credential directories, for tools that keep their own blocklist. */
32
34
  export declare function hostCredentialDirPaths(): string[];
33
35
  /** The single refusal used by every model-facing tool that reads files. */
@@ -145,6 +145,29 @@ export function isHostCredentialPath(resolvedAbsPath) {
145
145
  catch { /* best-effort symlink check */ }
146
146
  return false;
147
147
  }
148
+ /** Same file-search exclusion policy without blocking the agent's RPC loop. */
149
+ export async function isCredentialPathAsync(resolvedAbsPath) {
150
+ const home = os.homedir();
151
+ const matches = (candidate) => matchesKeyFile(candidate) || matchesHostCredential(candidate, home);
152
+ if (matches(resolvedAbsPath))
153
+ return true;
154
+ try {
155
+ const canonical = await fs.promises.realpath(resolvedAbsPath);
156
+ if (matches(canonical))
157
+ return true;
158
+ // Windows temp homes may use an 8.3 alias while native realpath expands
159
+ // it; macOS also aliases /var. Compare against the same home namespace.
160
+ const canonicalHome = await fs.promises.realpath(home);
161
+ const relative = path.relative(canonicalHome, canonical);
162
+ if (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep)) {
163
+ return matches(path.resolve(home, relative));
164
+ }
165
+ return false;
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ }
148
171
  /** Home-relative credential directories, for tools that keep their own blocklist. */
149
172
  export function hostCredentialDirPaths() {
150
173
  return hostCredentialDirs(os.homedir());
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import readline from 'node:readline';
6
6
  import chalk from 'chalk';
7
+ import { sortModelsNewestFirst } from '@blockrun/model-catalog';
7
8
  import { getGatewayModels } from '../gateway-models.js';
8
9
  import { FREE_DEFAULT_MODEL } from '../free-models.js';
9
10
  import { getModelCatalog, onModelCatalogChange } from '../model-catalog.js';
@@ -457,100 +458,6 @@ function providerHeading(provider) {
457
458
  function modelSuffix(id) {
458
459
  return id.includes('/') ? id.slice(id.indexOf('/') + 1) : id;
459
460
  }
460
- function versionScoreFrom(match) {
461
- if (!match)
462
- return 0;
463
- const parts = match[1].split('.').map(part => Number.parseInt(part, 10) || 0);
464
- return parts.slice(0, 3).reduce((score, part, index) => score + part * [1_000_000, 100_000, 1_000][index], 0);
465
- }
466
- function providerVersionScore(provider, suffix) {
467
- switch (provider) {
468
- case 'anthropic':
469
- return versionScoreFrom(suffix.match(/claude-(?:fable|opus|sonnet|haiku)-(\d+(?:\.\d+)*)/));
470
- case 'openai':
471
- if (suffix.startsWith('gpt-4o'))
472
- return versionScoreFrom(['', '4.0']);
473
- return versionScoreFrom(suffix.match(/(?:gpt-|o)(\d+(?:\.\d+)*)/));
474
- case 'google':
475
- return versionScoreFrom(suffix.match(/gemini-(\d+(?:\.\d+)*)/));
476
- case 'xai':
477
- return versionScoreFrom(suffix.match(/grok-(\d+(?:\.\d+)*)/));
478
- case 'zai':
479
- return versionScoreFrom(suffix.match(/glm-(\d+(?:\.\d+)*)/));
480
- case 'moonshot':
481
- return versionScoreFrom(suffix.match(/kimi-k(\d+(?:\.\d+)*)/));
482
- case 'minimax':
483
- return versionScoreFrom(suffix.match(/minimax-m(\d+(?:\.\d+)*)/));
484
- case 'deepseek':
485
- return versionScoreFrom(suffix.match(/deepseek-v(\d+(?:\.\d+)*)/));
486
- case 'nvidia':
487
- return versionScoreFrom(suffix.match(/deepseek-v(\d+(?:\.\d+)*)/) ??
488
- suffix.match(/qwen(\d+(?:\.\d+)*)/) ??
489
- suffix.match(/step-(\d+(?:\.\d+)*)/) ??
490
- suffix.match(/nemotron-(\d+(?:\.\d+)*)/) ??
491
- suffix.match(/mistral-large-(\d+(?:\.\d+)*)/) ??
492
- suffix.match(/v(\d+(?:\.\d+)*)/));
493
- default:
494
- return versionScoreFrom(suffix.match(/(?:^|[^\d])(\d+(?:\.\d+)*)(?:[^\d]|$)/));
495
- }
496
- }
497
- function expandedModelRank(model) {
498
- const suffix = modelSuffix(model.id).toLowerCase();
499
- const provider = providerOf(model.id);
500
- let score = providerVersionScore(provider, suffix);
501
- switch (provider) {
502
- case 'anthropic':
503
- score += suffix.includes('fable') ? 90_000 : suffix.includes('opus') ? 80_000 : suffix.includes('sonnet') ? 70_000 : suffix.includes('haiku') ? 40_000 : 0;
504
- break;
505
- case 'openai':
506
- score += suffix.startsWith('gpt-') ? 80_000 : suffix.startsWith('o') ? 65_000 : 0;
507
- if (suffix.includes('codex'))
508
- score += 8_000;
509
- if (suffix.includes('pro') || suffix.includes('sol'))
510
- score += 3_000;
511
- if (suffix.includes('terra'))
512
- score += 2_000;
513
- if (suffix.includes('luna'))
514
- score += 1_000;
515
- if (suffix.includes('mini'))
516
- score -= 8_000;
517
- if (suffix.includes('nano'))
518
- score -= 12_000;
519
- break;
520
- case 'google':
521
- score += suffix.includes('gemini') ? 80_000 : 0;
522
- if (suffix.includes('pro'))
523
- score += 5_000;
524
- if (suffix.includes('flash'))
525
- score -= 5_000;
526
- break;
527
- case 'xai':
528
- score += suffix.includes('grok') ? 80_000 : 0;
529
- if (suffix.includes('fast'))
530
- score -= 4_000;
531
- if (suffix.includes('build'))
532
- score -= 8_000;
533
- break;
534
- case 'zai':
535
- score += suffix.includes('glm') ? 80_000 : 0;
536
- if (suffix.includes('turbo'))
537
- score -= 5_000;
538
- break;
539
- case 'moonshot':
540
- score += suffix.includes('kimi') ? 80_000 : 0;
541
- break;
542
- case 'minimax':
543
- score += suffix.includes('minimax') ? 80_000 : 0;
544
- break;
545
- case 'deepseek':
546
- score += suffix.includes('v4-pro') ? 90_000 : suffix.includes('reasoner') ? 75_000 : suffix.includes('chat') ? 70_000 : 0;
547
- break;
548
- case 'nvidia':
549
- score += suffix.includes('qwen3-next') ? 80_000 : suffix.includes('qwen') ? 70_000 : suffix.includes('nemotron') ? 60_000 : 0;
550
- break;
551
- }
552
- return score;
553
- }
554
461
  function cleanGatewayLabel(model) {
555
462
  return (model.name || modelSuffix(model.id))
556
463
  .replace(/\s*\((?:free|paid)\)\s*$/i, '')
@@ -657,30 +564,24 @@ export async function getExpandedPickerCategories() {
657
564
  }
658
565
  export function reconcileExpandedPicker(catalog) {
659
566
  const categories = [{ ...PICKER_CATEGORIES[0], models: [...PICKER_CATEGORIES[0].models] }];
660
- const curated = new Set();
661
567
  const curatedRows = new Map();
662
568
  for (const cat of PICKER_CATEGORIES) {
663
569
  for (const row of cat.models) {
664
- curated.add(row.id);
665
570
  if (!isSyntheticId(row.id))
666
571
  curatedRows.set(row.id, row);
667
572
  }
668
573
  }
669
574
  const shortcutById = buildShortcutById();
670
- const chatModels = catalog
671
- .filter(m => m.categories?.includes('chat'))
672
- .sort((a, b) => {
673
- const providerDelta = providerRank(providerOf(a.id)) - providerRank(providerOf(b.id));
674
- if (providerDelta !== 0)
675
- return providerDelta;
676
- const rankDelta = expandedModelRank(b) - expandedModelRank(a);
677
- if (rankDelta !== 0)
678
- return rankDelta;
679
- const curatedDelta = Number(!curated.has(a.id)) - Number(!curated.has(b.id));
680
- if (curatedDelta !== 0)
681
- return curatedDelta;
682
- return modelSuffix(a.id).localeCompare(modelSuffix(b.id));
683
- });
575
+ const byProviderModels = new Map();
576
+ for (const model of catalog) {
577
+ if (model.available === false || !model.categories?.includes('chat'))
578
+ continue;
579
+ const provider = providerOf(model.id);
580
+ const rows = byProviderModels.get(provider) ?? [];
581
+ rows.push(model);
582
+ byProviderModels.set(provider, rows);
583
+ }
584
+ const chatModels = [...byProviderModels.values()].flatMap(rows => sortModelsNewestFirst(rows));
684
585
  const byProvider = new Map();
685
586
  for (const model of chatModels) {
686
587
  const provider = providerOf(model.id);