@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.93",
3
+ "version": "1.20.94",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -53,7 +53,7 @@ import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, build
53
53
  // Provider imports
54
54
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
55
55
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
56
- import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
56
+ import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
57
57
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
58
58
  import fsSync from 'fs';
59
59
  import os from 'os';
@@ -4536,12 +4536,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4536
4536
  let resultString = JSON.stringify(result);
4537
4537
  // Per tool, not one number for all of them. A build log and a
4538
4538
  // source file are not equally worth their space in the window.
4539
+ // Compatibility fallback preserves complete output when primary store is unavailable.
4539
4540
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4541
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4540
4542
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4541
4543
  let spill = null;
4542
- if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
4544
+ if (resultString.length > inlineLimit) {
4543
4545
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4544
- const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
4546
+ const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4547
+ const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
4545
4548
  if (stored.isTruncated && stored.diskPath) {
4546
4549
  spill = { path: stored.diskPath };
4547
4550
  resultString = JSON.stringify({
@@ -4550,9 +4553,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4550
4553
  output: stored.contentForModel
4551
4554
  });
4552
4555
  }
4553
- else if (document.length > 2500) {
4554
- // Compatibility recovery store if the primary store is unavailable.
4555
- // spillToolResult preserves the full document; never truncate on failure.
4556
+ else if (document.length > inlineLimit) {
4556
4557
  const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4557
4558
  if (fallback) {
4558
4559
  spill = fallback;
@@ -4952,28 +4953,30 @@ You are operating in a text-and-code modality without direct image pixel renderi
4952
4953
  }
4953
4954
  return val;
4954
4955
  };
4955
- // 1. File operations must have absolute paths
4956
+ // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
4956
4957
  const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
4957
- const pathFields = [
4958
- 'path', 'searchPath', 'cwd', 'directory',
4959
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
4960
- 'targetFile', 'outputFile', 'outputPath',
4961
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
4962
- ];
4963
- for (const field of pathFields) {
4964
- if (args[field] && typeof args[field] === 'string') {
4965
- const resolved = resolveOne(args[field]);
4966
- if (resolved !== null) {
4967
- args[field] = resolved;
4958
+ if (toolName !== 'fs_read_skill') {
4959
+ const pathFields = [
4960
+ 'path', 'searchPath', 'cwd', 'directory',
4961
+ 'source', 'destination', 'file_path', 'filePath', 'filepath',
4962
+ 'targetFile', 'outputFile', 'outputPath',
4963
+ ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
4964
+ ];
4965
+ for (const field of pathFields) {
4966
+ if (args[field] && typeof args[field] === 'string') {
4967
+ const resolved = resolveOne(args[field]);
4968
+ if (resolved !== null) {
4969
+ args[field] = resolved;
4970
+ }
4968
4971
  }
4969
4972
  }
4970
- }
4971
- if (Array.isArray(args.target_directories)) {
4972
- args.target_directories = args.target_directories.map((entry) => {
4973
- if (typeof entry !== 'string')
4974
- return entry;
4975
- return resolveOne(entry) ?? entry;
4976
- });
4973
+ if (Array.isArray(args.target_directories)) {
4974
+ args.target_directories = args.target_directories.map((entry) => {
4975
+ if (typeof entry !== 'string')
4976
+ return entry;
4977
+ return resolveOne(entry) ?? entry;
4978
+ });
4979
+ }
4977
4980
  }
4978
4981
  // 2. Terminal commands must have a command string
4979
4982
  if ((toolName === 'sysRun' || toolName === 'sysRunBg') && !args.command) {
package/src/agentLoop.ts CHANGED
@@ -94,7 +94,7 @@ import {
94
94
  // Provider imports
95
95
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
96
96
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
97
- import { defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
97
+ import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
98
98
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
99
99
  import fsSync from 'fs';
100
100
  import os from 'os';
@@ -4767,12 +4767,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4767
4767
  let resultString = JSON.stringify(result);
4768
4768
  // Per tool, not one number for all of them. A build log and a
4769
4769
  // source file are not equally worth their space in the window.
4770
+ // Compatibility fallback preserves complete output when primary store is unavailable.
4770
4771
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4772
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4771
4773
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4772
4774
  let spill = null;
4773
- if (resultString.length > Math.min(MAX_RESULT_CHARS, 2500)) {
4775
+ if (resultString.length > inlineLimit) {
4774
4776
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4775
- const stored = processToolOutputWithStore(this.taskId, toolCall.id, document);
4777
+ const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4778
+ const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
4776
4779
  if (stored.isTruncated && stored.diskPath) {
4777
4780
  spill = { path: stored.diskPath };
4778
4781
  resultString = JSON.stringify({
@@ -4780,9 +4783,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4780
4783
  ...(typeof result?.error === 'string' ? { error: result.error.slice(0, 500) } : {}),
4781
4784
  output: stored.contentForModel
4782
4785
  });
4783
- } else if (document.length > 2500) {
4784
- // Compatibility recovery store if the primary store is unavailable.
4785
- // spillToolResult preserves the full document; never truncate on failure.
4786
+ } else if (document.length > inlineLimit) {
4786
4787
  const fallback = spillToolResult(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4787
4788
  if (fallback) {
4788
4789
  spill = fallback;
@@ -5214,27 +5215,29 @@ You are operating in a text-and-code modality without direct image pixel renderi
5214
5215
  return val;
5215
5216
  };
5216
5217
 
5217
- // 1. File operations must have absolute paths
5218
+ // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
5218
5219
  const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
5219
- const pathFields = [
5220
- 'path', 'searchPath', 'cwd', 'directory',
5221
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
5222
- 'targetFile', 'outputFile', 'outputPath',
5223
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5224
- ];
5225
- for (const field of pathFields) {
5226
- if (args[field] && typeof args[field] === 'string') {
5227
- const resolved = resolveOne(args[field]);
5228
- if (resolved !== null) {
5229
- args[field] = resolved;
5220
+ if (toolName !== 'fs_read_skill') {
5221
+ const pathFields = [
5222
+ 'path', 'searchPath', 'cwd', 'directory',
5223
+ 'source', 'destination', 'file_path', 'filePath', 'filepath',
5224
+ 'targetFile', 'outputFile', 'outputPath',
5225
+ ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5226
+ ];
5227
+ for (const field of pathFields) {
5228
+ if (args[field] && typeof args[field] === 'string') {
5229
+ const resolved = resolveOne(args[field]);
5230
+ if (resolved !== null) {
5231
+ args[field] = resolved;
5232
+ }
5230
5233
  }
5231
5234
  }
5232
- }
5233
- if (Array.isArray(args.target_directories)) {
5234
- args.target_directories = args.target_directories.map((entry: unknown) => {
5235
- if (typeof entry !== 'string') return entry;
5236
- return resolveOne(entry) ?? entry;
5237
- });
5235
+ if (Array.isArray(args.target_directories)) {
5236
+ args.target_directories = args.target_directories.map((entry: unknown) => {
5237
+ if (typeof entry !== 'string') return entry;
5238
+ return resolveOne(entry) ?? entry;
5239
+ });
5240
+ }
5238
5241
  }
5239
5242
 
5240
5243
  // 2. Terminal commands must have a command string
@@ -46,6 +46,8 @@ export const RESULT_CAPS = {
46
46
  fs_read: 32000,
47
47
  code_search_ast: 32000,
48
48
  MultiEdit: 32000,
49
+ fs_read_skill: 16000,
50
+ tool_search: 8000,
49
51
 
50
52
  // Command output. Low information density, high volume, and the conclusion is
51
53
  // almost always in the first and last few lines.
@@ -59,7 +59,16 @@ export function pruneExecutedToolArguments(messages, options = {}) {
59
59
  * not make a 60 KB result safe to resend in full on every model call.
60
60
  */
61
61
  export function shortenOversizedToolObservations(messages, options = {}) {
62
- const threshold = Math.max(1, options.threshold ?? 2500);
62
+ const explicitThreshold = options.threshold !== undefined ? Math.max(1, options.threshold) : undefined;
63
+ const thresholdFor = (toolName) => {
64
+ if (explicitThreshold !== undefined)
65
+ return explicitThreshold;
66
+ if (toolName === 'fs_read_skill')
67
+ return 16000;
68
+ if (toolName === 'tool_search')
69
+ return 8000;
70
+ return 2500;
71
+ };
63
72
  let pruned = 0;
64
73
  let reclaimedChars = 0;
65
74
  let spillFailures = 0;
@@ -68,8 +77,14 @@ export function shortenOversizedToolObservations(messages, options = {}) {
68
77
  if (!message || message.role !== 'tool' || typeof message.content !== 'string')
69
78
  continue;
70
79
  const original = message.content;
80
+ const threshold = thresholdFor(message.name);
71
81
  if (original.length <= threshold || original.startsWith(MARKER))
72
82
  continue;
83
+ // Do not truncate an observation a second time when ToolOutputStore has
84
+ // already persisted the complete payload and added its recovery notice.
85
+ if (message.spillPath && original.includes('Causyne ToolOutputStore:') && original.length <= Math.max(threshold + 1000, 4000)) {
86
+ continue;
87
+ }
73
88
  let spillPath = message.spillPath;
74
89
  if (!spillPath) {
75
90
  const spill = spillToolResult(original, {
@@ -70,7 +70,13 @@ export function shortenOversizedToolObservations(
70
70
  messages: ToolObservation[],
71
71
  options: { threshold?: number; taskId?: string } = {}
72
72
  ): ObservationPruneResult {
73
- const threshold = Math.max(1, options.threshold ?? 2500);
73
+ const explicitThreshold = options.threshold !== undefined ? Math.max(1, options.threshold) : undefined;
74
+ const thresholdFor = (toolName?: string): number => {
75
+ if (explicitThreshold !== undefined) return explicitThreshold;
76
+ if (toolName === 'fs_read_skill') return 16000;
77
+ if (toolName === 'tool_search') return 8000;
78
+ return 2500;
79
+ };
74
80
  let pruned = 0;
75
81
  let reclaimedChars = 0;
76
82
  let spillFailures = 0;
@@ -78,7 +84,13 @@ export function shortenOversizedToolObservations(
78
84
  const message = messages[index];
79
85
  if (!message || message.role !== 'tool' || typeof message.content !== 'string') continue;
80
86
  const original = message.content;
87
+ const threshold = thresholdFor(message.name);
81
88
  if (original.length <= threshold || original.startsWith(MARKER)) continue;
89
+ // Do not truncate an observation a second time when ToolOutputStore has
90
+ // already persisted the complete payload and added its recovery notice.
91
+ if (message.spillPath && original.includes('Causyne ToolOutputStore:') && original.length <= Math.max(threshold + 1000, 4000)) {
92
+ continue;
93
+ }
82
94
  let spillPath = message.spillPath;
83
95
  if (!spillPath) {
84
96
  const spill = spillToolResult(original, {
package/src/sandbox.js CHANGED
@@ -221,7 +221,8 @@ export class Sandbox {
221
221
 
222
222
  validate(toolName, args) {
223
223
  // 1. Tool availability check
224
- if (this.deniedTools.has(String(toolName).replace(/\./g, '_'))) {
224
+ const canonicalToolName = String(toolName || '').replace(/\./g, '_');
225
+ if (this.deniedTools.has(canonicalToolName)) {
225
226
  return { allowed: false, reason: `Tool ${toolName} is denied by local policy`, risk: 'forbidden' };
226
227
  }
227
228
  if (!this.allowedTools.includes('*') && !this.allowedTools.includes(toolName)) {
@@ -233,19 +234,24 @@ export class Sandbox {
233
234
  // file_path, the Blender/Godot automators use filepath and directory, the
234
235
  // media tools use outputPath. Checking only `path` let all of those write
235
236
  // outside the workspace unchallenged.
237
+ // fs_read_skill parameters (`skill_id`, `file_path`) identify bundled or
238
+ // user-skill resources bounded strictly by skillResourceSafety.ts rather
239
+ // than workspace filesystem paths.
236
240
  const safeArgs = args && typeof args === 'object' ? args : {};
237
- const PATH_ARGUMENTS = [
238
- 'path', 'searchPath', 'cwd', 'source', 'destination',
239
- 'file_path', 'filePath', 'filepath', 'directory',
240
- 'targetFile', 'outputFile', 'outputPath'
241
- ];
242
241
  const pathsToCheck = [];
243
- for (const field of PATH_ARGUMENTS) {
244
- if (safeArgs[field]) pathsToCheck.push(safeArgs[field]);
245
- }
246
- if (Array.isArray(safeArgs.target_directories)) {
247
- for (const dir of safeArgs.target_directories) {
248
- if (typeof dir === 'string' && dir.trim()) pathsToCheck.push(dir);
242
+ if (canonicalToolName !== 'fs_read_skill') {
243
+ const PATH_ARGUMENTS = [
244
+ 'path', 'searchPath', 'cwd', 'source', 'destination',
245
+ 'file_path', 'filePath', 'filepath', 'directory',
246
+ 'targetFile', 'outputFile', 'outputPath'
247
+ ];
248
+ for (const field of PATH_ARGUMENTS) {
249
+ if (safeArgs[field]) pathsToCheck.push(safeArgs[field]);
250
+ }
251
+ if (Array.isArray(safeArgs.target_directories)) {
252
+ for (const dir of safeArgs.target_directories) {
253
+ if (typeof dir === 'string' && dir.trim()) pathsToCheck.push(dir);
254
+ }
249
255
  }
250
256
  }
251
257
 
@@ -10,6 +10,7 @@ async function toolDefinitions() {
10
10
  import { buildToolsList } from '../toolsList.js';
11
11
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
12
12
  import { literalSearchPattern, formatSkillSearchLine, MAX_TOOL_SEARCH_QUERY } from '../skills/skillSearchSafety.js';
13
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
13
14
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
14
15
  const MAX_SKILL_HITS = 5;
15
16
  /**
@@ -21,7 +22,7 @@ const MAX_SKILL_HITS = 5;
21
22
  *
22
23
  * @returns {string[]} formatted lines, empty when nothing matched
23
24
  */
24
- async function searchSkills(terms, pattern) {
25
+ async function searchSkills(terms, pattern, options = {}) {
25
26
  // Imported lazily, not at module scope: registry.js imports THIS module, and
26
27
  // skillsManager pulls registry back in transitively — a static import here
27
28
  // closes the cycle and the whole tool registry fails to initialise. Same
@@ -35,73 +36,107 @@ async function searchSkills(terms, pattern) {
35
36
  return []; // a broken skill store must not take tool search down
36
37
  }
37
38
  const scored = [];
39
+ const minCoverage = requiredCoverage(terms.length);
38
40
  for (const skill of catalogue) {
39
- const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
41
+ // Whole-word matching: a substring test let "kill" match every "skill"
42
+ // and "and" match every "android".
43
+ const titleWords = wordsOf(`${skill.id} ${skill.name}`);
44
+ const domainWords = wordsOf(skill.domain);
45
+ const allWords = wordsOf(`${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`);
40
46
  let score = 0;
47
+ let coverage = 0;
48
+ let phraseHit = false;
41
49
  if (pattern) {
42
- if (pattern.test(skill.name) || pattern.test(skill.id))
50
+ if (pattern.test(skill.name) || pattern.test(skill.id)) {
43
51
  score += 10;
52
+ phraseHit = true;
53
+ }
44
54
  if (pattern.test(skill.description || ''))
45
55
  score += 4;
46
56
  }
47
57
  for (const term of terms) {
48
- if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term))
58
+ if (termMatches(term, titleWords)) {
49
59
  score += 8;
50
- else if (skill.domain.toLowerCase() === term)
60
+ coverage++;
61
+ }
62
+ else if (termMatches(term, domainWords)) {
51
63
  score += 6;
52
- else if (haystack.includes(term))
64
+ coverage++;
65
+ }
66
+ else if (termMatches(term, allWords)) {
53
67
  score += 3;
68
+ coverage++;
69
+ }
54
70
  }
55
71
  if (score > 0)
56
- scored.push({ skill, score });
72
+ scored.push({ skill, score, coverage, phraseHit });
57
73
  }
58
- return scored
59
- .sort((a, b) => b.score - a.score)
74
+ const strong = scored.filter(entry => entry.phraseHit || entry.coverage >= minCoverage);
75
+ const pool = strong.length > 0 ? strong : (options.allowFallback ? scored : []);
76
+ return pool
77
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
60
78
  .slice(0, MAX_SKILL_HITS)
61
79
  .map(({ skill }) => formatSkillSearchLine(skill));
62
80
  }
63
- // Real progressive-disclosure tool search.
64
- //
65
- // The previous version of this file advertised "80% token savings" while
66
- // searching a hardcoded catalogue of seven tools that did not exist in the
67
- // registry (mcp_postgres_data, mcp_github_workflow, mcp_android_cli). Any tool
68
- // the model discovered that way led straight to a "Tool does not exist" error,
69
- // and nothing was ever actually deferred.
70
- //
71
- // This version searches the live tool registry and unlocks what it finds. The
72
- // agent loop reads the _unlock_* fields off the result and loads the matching
73
- // schemas into the next request.
74
81
  function scoreTool(definition, terms, pattern) {
75
82
  const name = (definition.name || '').toLowerCase();
76
83
  const description = (definition.description || '').toLowerCase();
77
- // Parameter names and descriptions are searchable too — a query like
78
- // "kill process on port" should find a tool whose `port` argument mentions it.
79
- let parameterText = '';
84
+ // Parameter names (e.g. `port`) identify capabilities directly; parameter
85
+ // descriptions often list example platforms and act only as tiebreakers.
86
+ let paramKeysText = '';
87
+ let paramDescText = '';
80
88
  const properties = definition.parameters?.properties || definition.input_schema?.properties;
81
89
  if (properties) {
82
90
  for (const [key, value] of Object.entries(properties)) {
83
- parameterText += ` ${key} ${(value && value.description) || ''}`;
91
+ paramKeysText += ` ${key}`;
92
+ if (value && value.description) {
93
+ paramDescText += ` ${value.description}`;
94
+ }
84
95
  }
85
96
  }
86
- parameterText = parameterText.toLowerCase();
97
+ paramKeysText = paramKeysText.toLowerCase();
98
+ paramDescText = paramDescText.toLowerCase();
87
99
  let score = 0;
100
+ let coverage = 0;
101
+ let nameHit = false;
88
102
  if (pattern) {
89
- if (pattern.test(name))
103
+ if (pattern.test(name)) {
90
104
  score += 12;
105
+ nameHit = true;
106
+ }
91
107
  if (pattern.test(description))
92
108
  score += 6;
93
- if (pattern.test(parameterText))
109
+ if (pattern.test(paramKeysText) || pattern.test(paramDescText))
94
110
  score += 2;
95
111
  }
112
+ // Whole-word matching. Substring tests let "and" hit "command", "kill" hit
113
+ // "skill" and "port" hit "export", which unlocked unrelated schemas.
114
+ const nameWords = wordsOf(definition.name || '');
115
+ const descriptionWords = wordsOf(description);
116
+ const paramKeyWords = wordsOf(paramKeysText);
117
+ const paramDescWords = wordsOf(paramDescText);
96
118
  for (const term of terms) {
97
- if (name.includes(term))
119
+ let matched = false;
120
+ if (termMatches(term, nameWords)) {
98
121
  score += 10;
99
- if (description.includes(term))
122
+ matched = true;
123
+ }
124
+ if (termMatches(term, descriptionWords)) {
100
125
  score += 4;
101
- if (parameterText.includes(term))
126
+ matched = true;
127
+ }
128
+ if (termMatches(term, paramKeyWords)) {
129
+ score += 3;
130
+ matched = true;
131
+ }
132
+ if (matched) {
133
+ coverage++;
134
+ }
135
+ else if (termMatches(term, paramDescWords)) {
102
136
  score += 1;
137
+ }
103
138
  }
104
- return score;
139
+ return { score, coverage, nameHit };
105
140
  }
106
141
  function buildPattern(query) {
107
142
  // Never compile LLM-generated regex. A pattern such as (a+)+$ can freeze
@@ -176,26 +211,29 @@ export const deferredMcpSearch = {
176
211
  }
177
212
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
178
213
  const lower = query.toLowerCase();
179
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
214
+ const terms = queryTerms(query);
180
215
  const pattern = buildPattern(query);
216
+ // Tool discovery stays bounded: an entry sharing a single generic word
217
+ // with a multi-word request is not a match.
218
+ const minCoverage = requiredCoverage(terms.length);
181
219
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
182
220
  const scored = (exact ? [exact] : definitions)
183
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
184
- .filter(entry => entry.score > 0)
185
- .sort((a, b) => b.score - a.score)
221
+ .map(definition => ({ definition, ...scoreTool(definition, terms, pattern) }))
222
+ .filter(entry => entry.score > 0 && (exact !== undefined || entry.nameHit || entry.coverage >= minCoverage))
223
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
186
224
  .slice(0, limit);
187
225
  if (scored.length === 0) {
188
226
  // Still search skills. "how do I structure a django migration" matches
189
227
  // no tool name and every relevant skill — returning "no tools matched"
190
228
  // and stopping was the whole reason a 40-entry catalogue had to sit in
191
229
  // the system prompt.
192
- const skillOnly = await searchSkills(terms, pattern);
230
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
193
231
  if (skillOnly.length > 0) {
194
232
  const canUnlockSkillReader = !isResidentTool('fs_read_skill') &&
195
233
  definitions.some((definition) => definition.name === 'fs_read_skill');
196
234
  return {
197
235
  success: true,
198
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
236
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
199
237
  skillOnly.join('\n'),
200
238
  ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
201
239
  };
@@ -227,7 +265,7 @@ export const deferredMcpSearch = {
227
265
  // request of every task, including a bare "hi". Retrieval replaces the
228
266
  // catalogue — but only because the retrieval exists, which it did not
229
267
  // before this change.
230
- const skillLines = await searchSkills(terms, pattern);
268
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
231
269
  const parts = [];
232
270
  if (scored.length > 0) {
233
271
  parts.push(`Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +