@causyne/agent 1.20.93 → 1.20.94

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.
@@ -15,6 +15,7 @@ async function toolDefinitions(): Promise<ToolDefinition[]> {
15
15
  import { buildToolsList } from '../toolsList.js';
16
16
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
17
17
  import { literalSearchPattern, formatSkillSearchLine, MAX_TOOL_SEARCH_QUERY } from '../skills/skillSearchSafety.js';
18
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
18
19
 
19
20
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
20
21
  const MAX_SKILL_HITS = 5;
@@ -28,7 +29,11 @@ const MAX_SKILL_HITS = 5;
28
29
  *
29
30
  * @returns {string[]} formatted lines, empty when nothing matched
30
31
  */
31
- async function searchSkills(terms: string[], pattern: RegExp | null): Promise<string[]> {
32
+ async function searchSkills(
33
+ terms: string[],
34
+ pattern: RegExp | null,
35
+ options: { allowFallback?: boolean } = {}
36
+ ): Promise<string[]> {
32
37
  // Imported lazily, not at module scope: registry.js imports THIS module, and
33
38
  // skillsManager pulls registry back in transitively — a static import here
34
39
  // closes the cycle and the whole tool registry fails to initialise. Same
@@ -42,23 +47,32 @@ async function searchSkills(terms: string[], pattern: RegExp | null): Promise<st
42
47
  }
43
48
 
44
49
  const scored = [];
50
+ const minCoverage = requiredCoverage(terms.length);
45
51
  for (const skill of catalogue) {
46
- const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
52
+ // Whole-word matching: a substring test let "kill" match every "skill"
53
+ // and "and" match every "android".
54
+ const titleWords = wordsOf(`${skill.id} ${skill.name}`);
55
+ const domainWords = wordsOf(skill.domain);
56
+ const allWords = wordsOf(`${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`);
47
57
  let score = 0;
58
+ let coverage = 0;
59
+ let phraseHit = false;
48
60
  if (pattern) {
49
- if (pattern.test(skill.name) || pattern.test(skill.id)) score += 10;
61
+ if (pattern.test(skill.name) || pattern.test(skill.id)) { score += 10; phraseHit = true; }
50
62
  if (pattern.test(skill.description || '')) score += 4;
51
63
  }
52
64
  for (const term of terms) {
53
- if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term)) score += 8;
54
- else if (skill.domain.toLowerCase() === term) score += 6;
55
- else if (haystack.includes(term)) score += 3;
65
+ if (termMatches(term, titleWords)) { score += 8; coverage++; }
66
+ else if (termMatches(term, domainWords)) { score += 6; coverage++; }
67
+ else if (termMatches(term, allWords)) { score += 3; coverage++; }
56
68
  }
57
- if (score > 0) scored.push({ skill, score });
69
+ if (score > 0) scored.push({ skill, score, coverage, phraseHit });
58
70
  }
59
71
 
60
- return scored
61
- .sort((a, b) => b.score - a.score)
72
+ const strong = scored.filter(entry => entry.phraseHit || entry.coverage >= minCoverage);
73
+ const pool = strong.length > 0 ? strong : (options.allowFallback ? scored : []);
74
+ return pool
75
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
62
76
  .slice(0, MAX_SKILL_HITS)
63
77
  .map(({ skill }) => formatSkillSearchLine(skill));
64
78
  }
@@ -75,36 +89,57 @@ async function searchSkills(terms: string[], pattern: RegExp | null): Promise<st
75
89
  // agent loop reads the _unlock_* fields off the result and loads the matching
76
90
  // schemas into the next request.
77
91
 
78
- function scoreTool(definition: ToolDefinition, terms: string[], pattern: RegExp | null): number {
92
+ interface ToolScore { score: number; coverage: number; nameHit: boolean; }
93
+
94
+ function scoreTool(definition: ToolDefinition, terms: string[], pattern: RegExp | null): ToolScore {
79
95
  const name = (definition.name || '').toLowerCase();
80
96
  const description = (definition.description || '').toLowerCase();
81
97
 
82
- // Parameter names and descriptions are searchable too — a query like
83
- // "kill process on port" should find a tool whose `port` argument mentions it.
84
- let parameterText = '';
98
+ // Parameter names (e.g. `port`) identify capabilities directly; parameter
99
+ // descriptions often list example platforms and act only as tiebreakers.
100
+ let paramKeysText = '';
101
+ let paramDescText = '';
85
102
  const properties = definition.parameters?.properties || definition.input_schema?.properties;
86
103
  if (properties) {
87
104
  for (const [key, value] of Object.entries(properties)) {
88
- parameterText += ` ${key} ${(value && value.description) || ''}`;
105
+ paramKeysText += ` ${key}`;
106
+ if (value && value.description) {
107
+ paramDescText += ` ${value.description}`;
108
+ }
89
109
  }
90
110
  }
91
- parameterText = parameterText.toLowerCase();
111
+ paramKeysText = paramKeysText.toLowerCase();
112
+ paramDescText = paramDescText.toLowerCase();
92
113
 
93
114
  let score = 0;
115
+ let coverage = 0;
116
+ let nameHit = false;
94
117
 
95
118
  if (pattern) {
96
- if (pattern.test(name)) score += 12;
119
+ if (pattern.test(name)) { score += 12; nameHit = true; }
97
120
  if (pattern.test(description)) score += 6;
98
- if (pattern.test(parameterText)) score += 2;
121
+ if (pattern.test(paramKeysText) || pattern.test(paramDescText)) score += 2;
99
122
  }
100
123
 
124
+ // Whole-word matching. Substring tests let "and" hit "command", "kill" hit
125
+ // "skill" and "port" hit "export", which unlocked unrelated schemas.
126
+ const nameWords = wordsOf(definition.name || '');
127
+ const descriptionWords = wordsOf(description);
128
+ const paramKeyWords = wordsOf(paramKeysText);
129
+ const paramDescWords = wordsOf(paramDescText);
101
130
  for (const term of terms) {
102
- if (name.includes(term)) score += 10;
103
- if (description.includes(term)) score += 4;
104
- if (parameterText.includes(term)) score += 1;
131
+ let matched = false;
132
+ if (termMatches(term, nameWords)) { score += 10; matched = true; }
133
+ if (termMatches(term, descriptionWords)) { score += 4; matched = true; }
134
+ if (termMatches(term, paramKeyWords)) { score += 3; matched = true; }
135
+ if (matched) {
136
+ coverage++;
137
+ } else if (termMatches(term, paramDescWords)) {
138
+ score += 1;
139
+ }
105
140
  }
106
141
 
107
- return score;
142
+ return { score, coverage, nameHit };
108
143
  }
109
144
 
110
145
  function buildPattern(query: string): RegExp | null {
@@ -187,14 +222,17 @@ export const deferredMcpSearch = {
187
222
 
188
223
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
189
224
  const lower = query.toLowerCase();
190
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
225
+ const terms = queryTerms(query);
191
226
  const pattern = buildPattern(query);
227
+ // Tool discovery stays bounded: an entry sharing a single generic word
228
+ // with a multi-word request is not a match.
229
+ const minCoverage = requiredCoverage(terms.length);
192
230
 
193
231
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
194
232
  const scored = (exact ? [exact] : definitions)
195
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
196
- .filter(entry => entry.score > 0)
197
- .sort((a, b) => b.score - a.score)
233
+ .map(definition => ({ definition, ...scoreTool(definition, terms, pattern) }))
234
+ .filter(entry => entry.score > 0 && (exact !== undefined || entry.nameHit || entry.coverage >= minCoverage))
235
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
198
236
  .slice(0, limit);
199
237
 
200
238
  if (scored.length === 0) {
@@ -202,14 +240,14 @@ export const deferredMcpSearch = {
202
240
  // no tool name and every relevant skill — returning "no tools matched"
203
241
  // and stopping was the whole reason a 40-entry catalogue had to sit in
204
242
  // the system prompt.
205
- const skillOnly = await searchSkills(terms, pattern);
243
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
206
244
  if (skillOnly.length > 0) {
207
245
  const canUnlockSkillReader =
208
246
  !isResidentTool('fs_read_skill') &&
209
247
  definitions.some((definition) => definition.name === 'fs_read_skill');
210
248
  return {
211
249
  success: true,
212
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
250
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
213
251
  skillOnly.join('\n'),
214
252
  ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
215
253
  };
@@ -243,7 +281,7 @@ export const deferredMcpSearch = {
243
281
  // request of every task, including a bare "hi". Retrieval replaces the
244
282
  // catalogue — but only because the retrieval exists, which it did not
245
283
  // before this change.
246
- const skillLines = await searchSkills(terms, pattern);
284
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
247
285
 
248
286
  const parts = [];
249
287
  if (scored.length > 0) {
@@ -9,6 +9,38 @@
9
9
  import { listCompiledSkills, readCompiledSkill } from '../skillsManager.js';
10
10
  import { parseSkillId, userSkillsRoot } from '../userSkills.js';
11
11
  import { listSkillResourcePaths, readSkillTextResource } from '../skills/skillResourceSafety.js';
12
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
13
+ function suggestSimilarSkills(allSkills, seed, limit = 3) {
14
+ const terms = queryTerms(seed);
15
+ if (terms.length === 0)
16
+ return [];
17
+ const minCoverage = requiredCoverage(terms.length);
18
+ const ranked = allSkills
19
+ .map((skill) => {
20
+ const titleWords = wordsOf(`${skill.domain} ${skill.id} ${skill.name || ''}`);
21
+ const descWords = wordsOf(skill.description || '');
22
+ let score = 0;
23
+ let coverage = 0;
24
+ for (const term of terms) {
25
+ if (termMatches(term, titleWords)) {
26
+ score += 10;
27
+ coverage += 1;
28
+ }
29
+ else if (termMatches(term, descWords)) {
30
+ score += 3;
31
+ coverage += 1;
32
+ }
33
+ }
34
+ return { skill, score, coverage };
35
+ })
36
+ .filter((entry) => entry.score > 0);
37
+ const strong = ranked.filter((entry) => entry.coverage >= minCoverage);
38
+ const pool = strong.length > 0 ? strong : ranked;
39
+ return pool
40
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
41
+ .slice(0, limit)
42
+ .map((entry) => `${entry.skill.domain}/${entry.skill.id}`);
43
+ }
12
44
  export default {
13
45
  schema: {
14
46
  name: 'fs_read_skill',
@@ -47,27 +79,7 @@ export default {
47
79
  id = directMatch.id;
48
80
  }
49
81
  else if ('error' in parsed) {
50
- const queryTokens = rawSkillId.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
51
- const suggestions = allSkills
52
- .map(s => {
53
- let score = 0;
54
- const d = s.domain.toLowerCase();
55
- const n = s.id.toLowerCase();
56
- const desc = (s.description || '').toLowerCase();
57
- for (const t of queryTokens) {
58
- if (n.includes(t))
59
- score += 10;
60
- if (d.includes(t))
61
- score += 8;
62
- if (desc.includes(t))
63
- score += 2;
64
- }
65
- return { skill: s, score };
66
- })
67
- .filter(item => item.score > 0)
68
- .sort((a, b) => b.score - a.score)
69
- .slice(0, 3)
70
- .map(item => `${item.skill.domain}/${item.skill.id}`);
82
+ const suggestions = suggestSimilarSkills(allSkills, rawSkillId);
71
83
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
72
84
  return { success: false, error: `Invalid skill id "${rawSkillId}".${hint} Expected "domain/name", for example android/gradle-build-configuration.` };
73
85
  }
@@ -82,27 +94,7 @@ export default {
82
94
  }
83
95
  }
84
96
  if (!info) {
85
- const queryTokens = `${domain || ''} ${id || ''} ${rawSkillId}`.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
86
- const suggestions = allSkills
87
- .map(s => {
88
- let score = 0;
89
- const d = s.domain.toLowerCase();
90
- const n = s.id.toLowerCase();
91
- const desc = (s.description || '').toLowerCase();
92
- for (const t of queryTokens) {
93
- if (n.includes(t))
94
- score += 10;
95
- if (d.includes(t))
96
- score += 8;
97
- if (desc.includes(t))
98
- score += 2;
99
- }
100
- return { skill: s, score };
101
- })
102
- .filter(item => item.score > 0)
103
- .sort((a, b) => b.score - a.score)
104
- .slice(0, 3)
105
- .map(item => `${item.skill.domain}/${item.skill.id}`);
97
+ const suggestions = suggestSimilarSkills(allSkills, `${domain || ''} ${id || ''} ${rawSkillId}`);
106
98
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
107
99
  return { success: false, error: `Unknown skill ${domain ? `${domain}/${id}` : rawSkillId}.${hint} Search the current catalog with tool_search first.` };
108
100
  }
@@ -9,6 +9,7 @@
9
9
  import { listCompiledSkills, readCompiledSkill } from '../skillsManager.js';
10
10
  import { parseSkillId, userSkillsRoot } from '../userSkills.js';
11
11
  import { listSkillResourcePaths, readSkillTextResource } from '../skills/skillResourceSafety.js';
12
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
12
13
 
13
14
  interface SkillReadArgs {
14
15
  skill_id?: string;
@@ -19,6 +20,41 @@ interface SkillReadArgs {
19
20
  }
20
21
  interface SkillReadResult { success: boolean; result?: string; error?: string; }
21
22
 
23
+ function suggestSimilarSkills(
24
+ allSkills: ReturnType<typeof listCompiledSkills>,
25
+ seed: string,
26
+ limit = 3
27
+ ): string[] {
28
+ const terms = queryTerms(seed);
29
+ if (terms.length === 0) return [];
30
+ const minCoverage = requiredCoverage(terms.length);
31
+ const ranked = allSkills
32
+ .map((skill) => {
33
+ const titleWords = wordsOf(`${skill.domain} ${skill.id} ${skill.name || ''}`);
34
+ const descWords = wordsOf(skill.description || '');
35
+ let score = 0;
36
+ let coverage = 0;
37
+ for (const term of terms) {
38
+ if (termMatches(term, titleWords)) {
39
+ score += 10;
40
+ coverage += 1;
41
+ } else if (termMatches(term, descWords)) {
42
+ score += 3;
43
+ coverage += 1;
44
+ }
45
+ }
46
+ return { skill, score, coverage };
47
+ })
48
+ .filter((entry) => entry.score > 0);
49
+
50
+ const strong = ranked.filter((entry) => entry.coverage >= minCoverage);
51
+ const pool = strong.length > 0 ? strong : ranked;
52
+ return pool
53
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
54
+ .slice(0, limit)
55
+ .map((entry) => `${entry.skill.domain}/${entry.skill.id}`);
56
+ }
57
+
22
58
  export default {
23
59
  schema: {
24
60
  name: 'fs_read_skill',
@@ -57,24 +93,7 @@ export default {
57
93
  domain = directMatch.domain;
58
94
  id = directMatch.id;
59
95
  } else if ('error' in parsed) {
60
- const queryTokens = rawSkillId.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
61
- const suggestions = allSkills
62
- .map(s => {
63
- let score = 0;
64
- const d = s.domain.toLowerCase();
65
- const n = s.id.toLowerCase();
66
- const desc = (s.description || '').toLowerCase();
67
- for (const t of queryTokens) {
68
- if (n.includes(t)) score += 10;
69
- if (d.includes(t)) score += 8;
70
- if (desc.includes(t)) score += 2;
71
- }
72
- return { skill: s, score };
73
- })
74
- .filter(item => item.score > 0)
75
- .sort((a, b) => b.score - a.score)
76
- .slice(0, 3)
77
- .map(item => `${item.skill.domain}/${item.skill.id}`);
96
+ const suggestions = suggestSimilarSkills(allSkills, rawSkillId);
78
97
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
79
98
  return { success: false, error: `Invalid skill id "${rawSkillId}".${hint} Expected "domain/name", for example android/gradle-build-configuration.` };
80
99
  }
@@ -91,24 +110,7 @@ export default {
91
110
  }
92
111
 
93
112
  if (!info) {
94
- const queryTokens = `${domain || ''} ${id || ''} ${rawSkillId}`.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
95
- const suggestions = allSkills
96
- .map(s => {
97
- let score = 0;
98
- const d = s.domain.toLowerCase();
99
- const n = s.id.toLowerCase();
100
- const desc = (s.description || '').toLowerCase();
101
- for (const t of queryTokens) {
102
- if (n.includes(t)) score += 10;
103
- if (d.includes(t)) score += 8;
104
- if (desc.includes(t)) score += 2;
105
- }
106
- return { skill: s, score };
107
- })
108
- .filter(item => item.score > 0)
109
- .sort((a, b) => b.score - a.score)
110
- .slice(0, 3)
111
- .map(item => `${item.skill.domain}/${item.skill.id}`);
113
+ const suggestions = suggestSimilarSkills(allSkills, `${domain || ''} ${id || ''} ${rawSkillId}`);
112
114
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
113
115
  return { success: false, error: `Unknown skill ${domain ? `${domain}/${id}` : rawSkillId}.${hint} Search the current catalog with tool_search first.` };
114
116
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Causyne Agent — word-level relevance for tool and skill discovery.
3
+ *
4
+ * Substring matching made short query words hit unrelated entries ("and"
5
+ * inside "command", "kill" inside "skill", "git" inside "digit"), so one
6
+ * capability search could unlock a dozen irrelevant tool schemas. Matching is
7
+ * done on whole words with a bounded prefix rule instead. Deterministic,
8
+ * synchronous, linear-time, and never compiles user-supplied patterns.
9
+ */
10
+ /** English function words and search meta-words that carry no capability signal. */
11
+ const STOPWORDS = new Set([
12
+ 'and', 'the', 'for', 'with', 'from', 'into', 'onto', 'that', 'this', 'these', 'those',
13
+ 'using', 'use', 'via', 'any', 'all', 'are', 'was', 'were', 'can', 'how', 'what', 'which',
14
+ 'when', 'where', 'who', 'why', 'you', 'your', 'our', 'its', 'not', 'but', 'has', 'have',
15
+ 'should', 'would', 'could', 'please', 'about', 'also', 'then', 'than', 'them', 'they',
16
+ 'there', 'some', 'more', 'most', 'each', 'other', 'only', 'own', 'same', 'such', 'very',
17
+ 'just', 'like', 'need', 'want', 'help', 'let', 'get', 'take', 'out', 'over', 'under', 'per',
18
+ 'capability', 'capabilities', 'matching'
19
+ ]);
20
+ /** Upper bound on distinct query terms, so scoring cost stays constant. */
21
+ export const MAX_RELEVANCE_TERMS = 16;
22
+ /**
23
+ * Lower-case text and fold British -ise/-isation spellings onto -ize/-ization
24
+ * so "optimisation" and "optimization" compare equal. Applied identically to
25
+ * queries and catalog text.
26
+ */
27
+ export function normalizeSpelling(text) {
28
+ return text.toLowerCase().replace(/is(ations?|ing|ed|es|e)\b/g, 'iz$1');
29
+ }
30
+ /** Distinct meaningful query terms: alphanumeric words longer than two characters. */
31
+ export function queryTerms(query) {
32
+ const terms = [];
33
+ for (const word of normalizeSpelling(String(query || '')).split(/[^a-z0-9]+/)) {
34
+ if (word.length <= 2 || STOPWORDS.has(word) || terms.includes(word))
35
+ continue;
36
+ terms.push(word);
37
+ if (terms.length >= MAX_RELEVANCE_TERMS)
38
+ break;
39
+ }
40
+ return terms;
41
+ }
42
+ /** Whole words of catalog text, splitting snake_case, kebab-case and camelCase names. */
43
+ export function wordsOf(text) {
44
+ const spaced = String(text || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2');
45
+ return new Set(normalizeSpelling(spaced).split(/[^a-z0-9]+/).filter(word => word.length > 0));
46
+ }
47
+ /**
48
+ * A term matches a word exactly, or as a bounded stem: "build" matches
49
+ * "builds"/"builder", and "screenshots" matches "screenshot". Short words
50
+ * never match as a fragment of a longer one.
51
+ */
52
+ export function termMatches(term, words) {
53
+ if (words.has(term))
54
+ return true;
55
+ for (const word of words) {
56
+ if (term.length >= 4 && word.startsWith(term))
57
+ return true;
58
+ if (word.length >= 4 && term.startsWith(word) && term.length - word.length <= 3)
59
+ return true;
60
+ }
61
+ return false;
62
+ }
63
+ /**
64
+ * Minimum number of distinct query terms an entry must match. A multi-word
65
+ * capability description is not satisfied by an entry that shares only one
66
+ * generic word with it (for example "build" in "android build optimization").
67
+ */
68
+ export function requiredCoverage(termCount) {
69
+ return termCount >= 3 ? 2 : 1;
70
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Causyne Agent — word-level relevance for tool and skill discovery.
3
+ *
4
+ * Substring matching made short query words hit unrelated entries ("and"
5
+ * inside "command", "kill" inside "skill", "git" inside "digit"), so one
6
+ * capability search could unlock a dozen irrelevant tool schemas. Matching is
7
+ * done on whole words with a bounded prefix rule instead. Deterministic,
8
+ * synchronous, linear-time, and never compiles user-supplied patterns.
9
+ */
10
+
11
+ /** English function words and search meta-words that carry no capability signal. */
12
+ const STOPWORDS = new Set([
13
+ 'and', 'the', 'for', 'with', 'from', 'into', 'onto', 'that', 'this', 'these', 'those',
14
+ 'using', 'use', 'via', 'any', 'all', 'are', 'was', 'were', 'can', 'how', 'what', 'which',
15
+ 'when', 'where', 'who', 'why', 'you', 'your', 'our', 'its', 'not', 'but', 'has', 'have',
16
+ 'should', 'would', 'could', 'please', 'about', 'also', 'then', 'than', 'them', 'they',
17
+ 'there', 'some', 'more', 'most', 'each', 'other', 'only', 'own', 'same', 'such', 'very',
18
+ 'just', 'like', 'need', 'want', 'help', 'let', 'get', 'take', 'out', 'over', 'under', 'per',
19
+ 'capability', 'capabilities', 'matching'
20
+ ]);
21
+
22
+ /** Upper bound on distinct query terms, so scoring cost stays constant. */
23
+ export const MAX_RELEVANCE_TERMS = 16;
24
+
25
+ /**
26
+ * Lower-case text and fold British -ise/-isation spellings onto -ize/-ization
27
+ * so "optimisation" and "optimization" compare equal. Applied identically to
28
+ * queries and catalog text.
29
+ */
30
+ export function normalizeSpelling(text: string): string {
31
+ return text.toLowerCase().replace(/is(ations?|ing|ed|es|e)\b/g, 'iz$1');
32
+ }
33
+
34
+ /** Distinct meaningful query terms: alphanumeric words longer than two characters. */
35
+ export function queryTerms(query: string): string[] {
36
+ const terms: string[] = [];
37
+ for (const word of normalizeSpelling(String(query || '')).split(/[^a-z0-9]+/)) {
38
+ if (word.length <= 2 || STOPWORDS.has(word) || terms.includes(word)) continue;
39
+ terms.push(word);
40
+ if (terms.length >= MAX_RELEVANCE_TERMS) break;
41
+ }
42
+ return terms;
43
+ }
44
+
45
+ /** Whole words of catalog text, splitting snake_case, kebab-case and camelCase names. */
46
+ export function wordsOf(text: string): Set<string> {
47
+ const spaced = String(text || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2');
48
+ return new Set(normalizeSpelling(spaced).split(/[^a-z0-9]+/).filter(word => word.length > 0));
49
+ }
50
+
51
+ /**
52
+ * A term matches a word exactly, or as a bounded stem: "build" matches
53
+ * "builds"/"builder", and "screenshots" matches "screenshot". Short words
54
+ * never match as a fragment of a longer one.
55
+ */
56
+ export function termMatches(term: string, words: Set<string>): boolean {
57
+ if (words.has(term)) return true;
58
+ for (const word of words) {
59
+ if (term.length >= 4 && word.startsWith(term)) return true;
60
+ if (word.length >= 4 && term.startsWith(word) && term.length - word.length <= 3) return true;
61
+ }
62
+ return false;
63
+ }
64
+
65
+ /**
66
+ * Minimum number of distinct query terms an entry must match. A multi-word
67
+ * capability description is not satisfied by an entry that shares only one
68
+ * generic word with it (for example "build" in "android build optimization").
69
+ */
70
+ export function requiredCoverage(termCount: number): number {
71
+ return termCount >= 3 ? 2 : 1;
72
+ }
@@ -978,9 +978,10 @@ export function coerceArgumentTypes(toolName, args, schema) {
978
978
  /**
979
979
  * Automatically normalize relative file paths to absolute paths using cwd.
980
980
  */
981
- export function normalizePaths(args, cwd = process.cwd(), schema) {
981
+ export function normalizePaths(args, cwd = process.cwd(), schema, options = {}) {
982
982
  const repairs = [];
983
983
  const modified = { ...args };
984
+ const skipKeys = new Set(options.skipKeys || []);
984
985
  const targetSchema = schema?.properties?.target;
985
986
  const hasEnumTarget = Boolean(targetSchema && 'enum' in targetSchema);
986
987
  const pathKeys = [
@@ -1007,12 +1008,14 @@ export function normalizePaths(args, cwd = process.cwd(), schema) {
1007
1008
  return rawValue;
1008
1009
  };
1009
1010
  for (const key of pathKeys) {
1011
+ if (skipKeys.has(key))
1012
+ continue;
1010
1013
  const val = modified[key];
1011
1014
  if (typeof val === 'string' && val.trim() !== '') {
1012
1015
  modified[key] = normalizeOne(val, key);
1013
1016
  }
1014
1017
  }
1015
- if (Array.isArray(modified.target_directories)) {
1018
+ if (!skipKeys.has('target_directories') && Array.isArray(modified.target_directories)) {
1016
1019
  modified.target_directories = modified.target_directories.map((entry, idx) => {
1017
1020
  if (typeof entry !== 'string' || entry.trim() === '')
1018
1021
  return entry;
@@ -1099,8 +1102,10 @@ export function selfRepairToolCall(toolCall, toolSchema, options = {}) {
1099
1102
  // 3. Coerce argument types
1100
1103
  const typeResult = coerceArgumentTypes(canonicalName, aliasResult.args, toolSchema);
1101
1104
  allRepairs.push(...typeResult.repairs);
1102
- // 4. Normalize filesystem paths
1103
- const pathResult = normalizePaths(typeResult.args, options.cwd || process.cwd(), toolSchema);
1105
+ // 4. Normalize filesystem paths (fs_read_skill uses relative skill-bundle paths, never cwd paths)
1106
+ const pathResult = canonicalName === 'fs_read_skill'
1107
+ ? { args: typeResult.args, repaired: false, repairs: [] }
1108
+ : normalizePaths(typeResult.args, options.cwd || process.cwd(), toolSchema);
1104
1109
  allRepairs.push(...pathResult.repairs);
1105
1110
  const browserResult = canonicalName === 'browser_act'
1106
1111
  ? repairBrowserActions(pathResult.args, options.cwd || process.cwd())
@@ -1011,10 +1011,12 @@ export function coerceArgumentTypes(
1011
1011
  export function normalizePaths(
1012
1012
  args: Record<string, unknown>,
1013
1013
  cwd: string = process.cwd(),
1014
- schema?: ParameterSchema
1014
+ schema?: ParameterSchema,
1015
+ options: { skipKeys?: ReadonlySet<string> | Iterable<string> } = {}
1015
1016
  ): RepairResult {
1016
1017
  const repairs: string[] = [];
1017
1018
  const modified = { ...args };
1019
+ const skipKeys = new Set(options.skipKeys || []);
1018
1020
  const targetSchema = schema?.properties?.target;
1019
1021
  const hasEnumTarget = Boolean(targetSchema && 'enum' in targetSchema);
1020
1022
  const pathKeys = [
@@ -1043,13 +1045,14 @@ export function normalizePaths(
1043
1045
  };
1044
1046
 
1045
1047
  for (const key of pathKeys) {
1048
+ if (skipKeys.has(key)) continue;
1046
1049
  const val = modified[key];
1047
1050
  if (typeof val === 'string' && val.trim() !== '') {
1048
1051
  modified[key] = normalizeOne(val, key);
1049
1052
  }
1050
1053
  }
1051
1054
 
1052
- if (Array.isArray(modified.target_directories)) {
1055
+ if (!skipKeys.has('target_directories') && Array.isArray(modified.target_directories)) {
1053
1056
  modified.target_directories = modified.target_directories.map((entry, idx) => {
1054
1057
  if (typeof entry !== 'string' || entry.trim() === '') return entry;
1055
1058
  return normalizeOne(entry, `target_directories[${idx}]`);
@@ -1148,8 +1151,10 @@ export function selfRepairToolCall(
1148
1151
  const typeResult = coerceArgumentTypes(canonicalName, aliasResult.args, toolSchema);
1149
1152
  allRepairs.push(...typeResult.repairs);
1150
1153
 
1151
- // 4. Normalize filesystem paths
1152
- const pathResult = normalizePaths(typeResult.args, options.cwd || process.cwd(), toolSchema);
1154
+ // 4. Normalize filesystem paths (fs_read_skill uses relative skill-bundle paths, never cwd paths)
1155
+ const pathResult = canonicalName === 'fs_read_skill'
1156
+ ? { args: typeResult.args, repaired: false, repairs: [] }
1157
+ : normalizePaths(typeResult.args, options.cwd || process.cwd(), toolSchema);
1153
1158
  allRepairs.push(...pathResult.repairs);
1154
1159
 
1155
1160
  const browserResult = canonicalName === 'browser_act'
@@ -0,0 +1,45 @@
1
+ export function composerGeometry(requestedWidth, barColumns, gutterColumns) {
2
+ const width = Number.isFinite(requestedWidth)
3
+ ? Math.max(4, Math.trunc(requestedWidth))
4
+ : 80;
5
+ const boxWidth = width - 1; // never occupy the terminal's deferred-wrap cell
6
+ const glyph = Number.isFinite(barColumns) ? Math.max(0, Math.trunc(barColumns)) : 1;
7
+ const gutter = Number.isFinite(gutterColumns) ? Math.max(0, Math.trunc(gutterColumns)) : 1;
8
+ const inset = Math.min(glyph + gutter, Math.max(0, boxWidth - 2));
9
+ const bodyWidth = Math.max(1, boxWidth - inset);
10
+ const editorWidth = Math.max(1, bodyWidth - 1); // reserve a full cursor cell
11
+ return { boxWidth, inset, bodyWidth, editorWidth, maxCaretCol: boxWidth - 1 };
12
+ }
13
+ /**
14
+ * In a small terminal the editor is more important than the full brand banner.
15
+ * This helper never loses the caret or returns more rows than the Stage owns.
16
+ * The ordinary roomy Home composition is unchanged.
17
+ */
18
+ export function fitHomeContent(logoRows, promptRows, stageHeight, caretRow, requestedSpacer) {
19
+ const available = Number.isFinite(stageHeight)
20
+ ? Math.max(1, Math.trunc(stageHeight))
21
+ : 24;
22
+ const prompt = promptRows.length ? [...promptRows] : [''];
23
+ const caret = Number.isFinite(caretRow)
24
+ ? Math.max(0, Math.min(prompt.length - 1, Math.trunc(caretRow)))
25
+ : 0;
26
+ const promptCount = Math.min(available, prompt.length);
27
+ const start = prompt.length > available
28
+ ? Math.min(Math.max(0, caret - Math.floor(available / 2)), prompt.length - available)
29
+ : 0;
30
+ const visiblePrompt = prompt.slice(start, start + promptCount);
31
+ const remaining = available - visiblePrompt.length;
32
+ // A cropped rotor/wordmark looks broken. On cramped terminals, hide the
33
+ // banner as a whole rather than displaying an arbitrary bottom fragment.
34
+ const showLogo = logoRows.length > 0 && remaining >= logoRows.length;
35
+ const visibleLogo = showLogo ? [...logoRows] : [];
36
+ const spacer = showLogo
37
+ ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - logoRows.length)
38
+ : 0;
39
+ return {
40
+ logoRows: visibleLogo,
41
+ promptRows: visiblePrompt,
42
+ spacer,
43
+ caretRow: Math.max(0, Math.min(visiblePrompt.length - 1, caret - start))
44
+ };
45
+ }