@causyne/agent 1.20.11 → 1.20.12

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.
Files changed (86) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +264 -82
  34. package/src/providers/antigravity.ts +273 -87
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/subagent/sidechainHarness.js +66 -0
  54. package/src/subagent/sidechainHarness.ts +91 -0
  55. package/src/taskContinuation.js +12 -0
  56. package/src/taskContinuation.ts +13 -0
  57. package/src/tokenTracker.js +406 -539
  58. package/src/tokenTracker.ts +569 -0
  59. package/src/toolPacks.d.ts +2 -0
  60. package/src/toolPacks.js +1 -1
  61. package/src/tools/argumentValidation.js +56 -0
  62. package/src/tools/argumentValidation.ts +50 -0
  63. package/src/tools/browserAutomator.js +2 -2
  64. package/src/tools/browserAutomator.ts +3 -2
  65. package/src/tools/deferredMcpSearch.js +188 -201
  66. package/src/tools/deferredMcpSearch.ts +250 -0
  67. package/src/tools/generateMediaViaApi.js +305 -331
  68. package/src/tools/generateMediaViaApi.ts +330 -0
  69. package/src/tools/historyPruner.js +5 -0
  70. package/src/tools/historyPruner.ts +5 -0
  71. package/src/tools/payloadSanitizer.js +92 -0
  72. package/src/tools/payloadSanitizer.ts +113 -0
  73. package/src/tools/registry.d.ts +1 -0
  74. package/src/tools/sysRun.js +47 -18
  75. package/src/tools/sysRun.ts +52 -20
  76. package/src/tools/toolOutputStore.js +180 -0
  77. package/src/tools/toolOutputStore.ts +209 -0
  78. package/src/tools/toolSelfRepair.js +26 -1
  79. package/src/tools/toolSelfRepair.ts +25 -1
  80. package/src/tui/chatRenderer.d.ts +1 -0
  81. package/src/tui/chatRenderer.js +4 -2
  82. package/src/tui/codeStreamRenderer.js +36 -8
  83. package/src/tui/codeStreamRenderer.ts +38 -8
  84. package/src/tui/stageSurface.js +1 -0
  85. package/src/tui/text.js +4 -1
  86. package/src/tokenTracker.d.ts +0 -1
@@ -45,7 +45,7 @@ function normalizeActions(args) {
45
45
  export const browserAct = {
46
46
  schema: {
47
47
  name: 'browser.act',
48
- description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
48
+ description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Preview uses an internal browser-only origin, not a user-openable URL. Use a real local server when the user needs an interactive URL. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
49
49
  parameters: {
50
50
  type: 'object',
51
51
  properties: {
@@ -110,7 +110,7 @@ export const browserAct = {
110
110
  },
111
111
  async execute(args, sandbox) {
112
112
  try {
113
- const workspace = sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd();
113
+ const workspace = sandbox?.parentLoop?.workspaceRoot ?? sandbox?.workspaceRoot ?? sandbox?.workspacePaths?.[0] ?? process.cwd();
114
114
  const actions = normalizeActions(args);
115
115
  const results = await causyneBrowser({ workspace }).run(actions, { workspace });
116
116
  return { success: true, output: JSON.stringify(results, null, 2), data: results };
@@ -9,6 +9,7 @@ import {
9
9
  interface SandboxContext {
10
10
  workspacePaths?: string[];
11
11
  workspaceRoot?: string;
12
+ parentLoop?: { workspaceRoot?: string };
12
13
  }
13
14
 
14
15
  const SUPPORTED_ACTION_TYPES: BrowserActionType[] = [
@@ -58,7 +59,7 @@ function normalizeActions(args: Record<string, unknown> | undefined): BrowserAct
58
59
  export const browserAct = {
59
60
  schema: {
60
61
  name: 'browser.act',
61
- description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
62
+ description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Preview uses an internal browser-only origin, not a user-openable URL. Use a real local server when the user needs an interactive URL. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
62
63
  parameters: {
63
64
  type: 'object',
64
65
  properties: {
@@ -124,7 +125,7 @@ export const browserAct = {
124
125
 
125
126
  async execute(args: { actions?: BrowserAction[] } & Record<string, unknown>, sandbox?: SandboxContext) {
126
127
  try {
127
- const workspace = sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd();
128
+ const workspace = sandbox?.parentLoop?.workspaceRoot ?? sandbox?.workspaceRoot ?? sandbox?.workspacePaths?.[0] ?? process.cwd();
128
129
  const actions = normalizeActions(args);
129
130
  const results = await causyneBrowser({ workspace }).run(actions, { workspace });
130
131
  return { success: true, output: JSON.stringify(results, null, 2), data: results };
@@ -4,14 +4,12 @@
4
4
  // registry.js was always imported first. Loaded on demand instead — execute()
5
5
  // is async, so this costs nothing.
6
6
  async function toolDefinitions() {
7
- const { getSearchableToolDefinitions } = await import('./registry.js');
8
- return getSearchableToolDefinitions();
7
+ const { getSearchableToolDefinitions } = await import('./registry.js');
8
+ return getSearchableToolDefinitions();
9
9
  }
10
10
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
11
-
12
11
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
13
12
  const MAX_SKILL_HITS = 5;
14
-
15
13
  /**
16
14
  * Score the skill catalogue with the same query the tools were scored with.
17
15
  *
@@ -22,40 +20,44 @@ const MAX_SKILL_HITS = 5;
22
20
  * @returns {string[]} formatted lines, empty when nothing matched
23
21
  */
24
22
  async function searchSkills(terms, pattern) {
25
- // Imported lazily, not at module scope: registry.js imports THIS module, and
26
- // skillsManager pulls registry back in transitively — a static import here
27
- // closes the cycle and the whole tool registry fails to initialise. Same
28
- // pattern registry.js already uses for capabilityTools.
29
- let catalogue;
30
- try {
31
- const { listCompiledSkills } = await import('../skillsManager.js');
32
- catalogue = listCompiledSkills();
33
- } catch (e) {
34
- return []; // a broken skill store must not take tool search down
35
- }
36
-
37
- const scored = [];
38
- for (const skill of catalogue) {
39
- const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
40
- let score = 0;
41
- if (pattern) {
42
- if (pattern.test(skill.name) || pattern.test(skill.id)) score += 10;
43
- if (pattern.test(skill.description || '')) score += 4;
23
+ // Imported lazily, not at module scope: registry.js imports THIS module, and
24
+ // skillsManager pulls registry back in transitively — a static import here
25
+ // closes the cycle and the whole tool registry fails to initialise. Same
26
+ // pattern registry.js already uses for capabilityTools.
27
+ let catalogue;
28
+ try {
29
+ const { listCompiledSkills } = await import('../skillsManager.js');
30
+ catalogue = listCompiledSkills();
44
31
  }
45
- for (const term of terms) {
46
- if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term)) score += 8;
47
- else if (skill.domain.toLowerCase() === term) score += 6;
48
- else if (haystack.includes(term)) score += 3;
32
+ catch (e) {
33
+ return []; // a broken skill store must not take tool search down
34
+ }
35
+ const scored = [];
36
+ for (const skill of catalogue) {
37
+ const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
38
+ let score = 0;
39
+ if (pattern) {
40
+ if (pattern.test(skill.name) || pattern.test(skill.id))
41
+ score += 10;
42
+ if (pattern.test(skill.description || ''))
43
+ score += 4;
44
+ }
45
+ for (const term of terms) {
46
+ if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term))
47
+ score += 8;
48
+ else if (skill.domain.toLowerCase() === term)
49
+ score += 6;
50
+ else if (haystack.includes(term))
51
+ score += 3;
52
+ }
53
+ if (score > 0)
54
+ scored.push({ skill, score });
49
55
  }
50
- if (score > 0) scored.push({ skill, score });
51
- }
52
-
53
- return scored
54
- .sort((a, b) => b.score - a.score)
55
- .slice(0, MAX_SKILL_HITS)
56
- .map(({ skill }) => `- ${skill.domain}/${skill.id} — ${skill.name}: ${skill.description || ''}`);
56
+ return scored
57
+ .sort((a, b) => b.score - a.score)
58
+ .slice(0, MAX_SKILL_HITS)
59
+ .map(({ skill }) => `- ${skill.domain}/${skill.id} — ${skill.name}: ${skill.description || ''}`);
57
60
  }
58
-
59
61
  // Real progressive-disclosure tool search.
60
62
  //
61
63
  // The previous version of this file advertised "80% token savings" while
@@ -67,180 +69,165 @@ async function searchSkills(terms, pattern) {
67
69
  // This version searches the live tool registry and unlocks what it finds. The
68
70
  // agent loop reads the _unlock_* fields off the result and loads the matching
69
71
  // schemas into the next request.
70
-
71
72
  function scoreTool(definition, terms, pattern) {
72
- const name = (definition.name || '').toLowerCase();
73
- const description = (definition.description || '').toLowerCase();
74
-
75
- // Parameter names and descriptions are searchable too — a query like
76
- // "kill process on port" should find a tool whose `port` argument mentions it.
77
- let parameterText = '';
78
- const properties = definition.parameters?.properties || definition.input_schema?.properties;
79
- if (properties) {
80
- for (const [key, value] of Object.entries(properties)) {
81
- parameterText += ` ${key} ${(value && value.description) || ''}`;
73
+ const name = (definition.name || '').toLowerCase();
74
+ const description = (definition.description || '').toLowerCase();
75
+ // Parameter names and descriptions are searchable too — a query like
76
+ // "kill process on port" should find a tool whose `port` argument mentions it.
77
+ let parameterText = '';
78
+ const properties = definition.parameters?.properties || definition.input_schema?.properties;
79
+ if (properties) {
80
+ for (const [key, value] of Object.entries(properties)) {
81
+ parameterText += ` ${key} ${(value && value.description) || ''}`;
82
+ }
83
+ }
84
+ parameterText = parameterText.toLowerCase();
85
+ let score = 0;
86
+ if (pattern) {
87
+ if (pattern.test(name))
88
+ score += 12;
89
+ if (pattern.test(description))
90
+ score += 6;
91
+ if (pattern.test(parameterText))
92
+ score += 2;
82
93
  }
83
- }
84
- parameterText = parameterText.toLowerCase();
85
-
86
- let score = 0;
87
-
88
- if (pattern) {
89
- if (pattern.test(name)) score += 12;
90
- if (pattern.test(description)) score += 6;
91
- if (pattern.test(parameterText)) score += 2;
92
- }
93
-
94
- for (const term of terms) {
95
- if (name.includes(term)) score += 10;
96
- if (description.includes(term)) score += 4;
97
- if (parameterText.includes(term)) score += 1;
98
- }
99
-
100
- return score;
94
+ for (const term of terms) {
95
+ if (name.includes(term))
96
+ score += 10;
97
+ if (description.includes(term))
98
+ score += 4;
99
+ if (parameterText.includes(term))
100
+ score += 1;
101
+ }
102
+ return score;
101
103
  }
102
-
103
104
  function buildPattern(query) {
104
- // The query may be a natural-language phrase or a regular expression. Trying
105
- // it as a regex first gives power users exact control; a malformed pattern
106
- // simply falls back to keyword scoring instead of throwing.
107
- try {
108
- return new RegExp(query, 'i');
109
- } catch (e) {
110
- return null;
111
- }
105
+ // The query may be a natural-language phrase or a regular expression. Trying
106
+ // it as a regex first gives power users exact control; a malformed pattern
107
+ // simply falls back to keyword scoring instead of throwing.
108
+ try {
109
+ return new RegExp(query, 'i');
110
+ }
111
+ catch (e) {
112
+ return null;
113
+ }
112
114
  }
113
-
114
115
  export const deferredMcpSearch = {
115
- schema: {
116
- name: 'tool.search',
117
- description: 'Search your full native tool catalogue and load additional tool schemas on demand. Causyne keeps specialised capability packs (game development, media generation, browser and vision, system control, advanced orchestration) out of your context until you need them. Call this whenever a task needs a capability you cannot currently see — the matching tools become callable immediately on your next turn. Accepts natural language ("generate music", "godot scene", "kill process on port", "read a pdf") or a regular expression.',
118
- parameters: {
119
- type: 'object',
120
- properties: {
121
- query: {
122
- type: 'string',
123
- description: 'What capability you need. Natural language or a regex pattern matched against tool names, descriptions and argument descriptions.'
124
- },
125
- pack: {
126
- type: 'string',
127
- enum: [...PACK_NAMES, 'all'],
128
- description: 'Optional. Load an entire capability pack at once instead of searching: game, web, media, system, or advanced.'
129
- },
130
- limit: {
131
- type: 'integer',
132
- description: 'Maximum number of tools to return. Defaults to 8.'
116
+ schema: {
117
+ name: 'tool.search',
118
+ description: 'Search your full native tool catalogue and load additional tool schemas on demand. Causyne keeps specialised capability packs (game development, media generation, browser and vision, system control, advanced orchestration) out of your context until you need them. Call this whenever a task needs a capability you cannot currently see — the matching tools become callable immediately on your next turn. Accepts natural language ("generate music", "godot scene", "kill process on port", "read a pdf") or a regular expression.',
119
+ parameters: {
120
+ type: 'object',
121
+ properties: {
122
+ query: {
123
+ type: 'string',
124
+ description: 'What capability you need. Natural language or a regex pattern matched against tool names, descriptions and argument descriptions.'
125
+ },
126
+ pack: {
127
+ type: 'string',
128
+ enum: [...PACK_NAMES, 'all'],
129
+ description: 'Optional. Load an entire capability pack at once instead of searching: game, web, media, system, or advanced.'
130
+ },
131
+ limit: {
132
+ type: 'integer',
133
+ description: 'Maximum number of tools to return. Defaults to 8.'
134
+ }
135
+ },
136
+ required: ['query']
133
137
  }
134
- },
135
- required: ['query']
136
- }
137
- },
138
-
139
- async execute(args, context = {}) {
140
- try {
141
- const query = String(args.query || '').trim();
142
- const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
143
-
144
- if (!query && !requestedPack) {
145
- return { success: false, error: 'Provide a "query" describing the capability you need, or a "pack" name to load.' };
146
- }
147
-
148
- // Whole-pack load. Cheaper than five searches when the agent already
149
- // knows it is starting a game or a media pipeline.
150
- if (requestedPack && requestedPack !== 'all' && PACKS[requestedPack]) {
151
- const packTools = (await toolDefinitions()).filter(d => packForTool(d.name) === requestedPack);
152
- return {
153
- success: true,
154
- output: `Loaded capability pack "${requestedPack}" (${packTools.length} tools). These are now callable:\n` +
155
- packTools.map(d => `- ${d.name}: ${d.description || ''}`).join('\n'),
156
- _unlock_packs: [requestedPack],
157
- _unlock_tools: packTools.map(d => d.name)
158
- };
159
- }
160
-
161
- const limit = Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
162
- const lower = query.toLowerCase();
163
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
164
- const pattern = buildPattern(query);
165
-
166
- const scored = (await toolDefinitions())
167
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
168
- .filter(entry => entry.score > 0)
169
- .sort((a, b) => b.score - a.score)
170
- .slice(0, limit);
171
-
172
- if (scored.length === 0) {
173
- // Still search skills. "how do I structure a django migration" matches
174
- // no tool name and every relevant skill — returning "no tools matched"
175
- // and stopping was the whole reason a 40-entry catalogue had to sit in
176
- // the system prompt.
177
- const skillOnly = await searchSkills(terms, pattern);
178
- if (skillOnly.length > 0) {
179
- return {
180
- success: true,
181
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
182
- skillOnly.join('\n')
183
- };
138
+ },
139
+ async execute(args) {
140
+ try {
141
+ const query = String(args.query || '').trim();
142
+ const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
143
+ if (!query && !requestedPack) {
144
+ return { success: false, error: 'Provide a "query" describing the capability you need, or a "pack" name to load.' };
145
+ }
146
+ // Whole-pack load. Cheaper than five searches when the agent already
147
+ // knows it is starting a game or a media pipeline.
148
+ if (requestedPack && requestedPack !== 'all' && Object.hasOwn(PACKS, requestedPack)) {
149
+ const packTools = (await toolDefinitions()).filter(d => packForTool(d.name) === requestedPack);
150
+ return {
151
+ success: true,
152
+ output: `Loaded capability pack "${requestedPack}" (${packTools.length} tools). These are now callable:\n` +
153
+ packTools.map(d => `- ${d.name}: ${d.description || ''}`).join('\n'),
154
+ _unlock_packs: [requestedPack],
155
+ _unlock_tools: packTools.map(d => d.name)
156
+ };
157
+ }
158
+ const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
159
+ const lower = query.toLowerCase();
160
+ const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
161
+ const pattern = buildPattern(query);
162
+ const definitions = await toolDefinitions();
163
+ const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
164
+ const scored = (exact ? [exact] : definitions)
165
+ .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
166
+ .filter(entry => entry.score > 0)
167
+ .sort((a, b) => b.score - a.score)
168
+ .slice(0, limit);
169
+ if (scored.length === 0) {
170
+ // Still search skills. "how do I structure a django migration" matches
171
+ // no tool name and every relevant skill — returning "no tools matched"
172
+ // and stopping was the whole reason a 40-entry catalogue had to sit in
173
+ // the system prompt.
174
+ const skillOnly = await searchSkills(terms, pattern);
175
+ if (skillOnly.length > 0) {
176
+ return {
177
+ success: true,
178
+ output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
179
+ skillOnly.join('\n')
180
+ };
181
+ }
182
+ return {
183
+ success: true,
184
+ output: `Nothing matched "${query}". Available capability packs: ${PACK_NAMES.join(', ')}. ` +
185
+ `Try a broader term, or set the "pack" argument to load a whole pack at once.`
186
+ };
187
+ }
188
+ const unlockTools = [];
189
+ const lines = [];
190
+ for (const { definition } of scored) {
191
+ const pack = packForTool(definition.name);
192
+ // Unlock anything that is not already resident. The old condition was
193
+ // `!isCoreTool(...)`, which was correct while the entire core shipped
194
+ // in every request. It is not any more: on a provider without native
195
+ // schema deferral only RESIDENT_TOOLS ship, and a non-resident core
196
+ // tool found here would have been reported as "already loaded" and
197
+ // then stayed invisible forever.
198
+ if (!isResidentTool(definition.name)) {
199
+ unlockTools.push(definition.name);
200
+ }
201
+ const state = isResidentTool(definition.name)
202
+ ? 'already loaded'
203
+ : (isCoreTool(definition.name) ? 'core' : `pack: ${pack || 'custom'}`);
204
+ lines.push(`- ${definition.name} (${state}): ${definition.description || ''}`);
205
+ }
206
+ // Skills are searched alongside tools because `tool_search` is the only
207
+ // discovery surface the model always has. The compiled skill catalogue is
208
+ // 100 entries; listing it in the system prompt cost ~841 tokens on EVERY
209
+ // request of every task, including a bare "hi". Retrieval replaces the
210
+ // catalogue — but only because the retrieval exists, which it did not
211
+ // before this change.
212
+ const skillLines = await searchSkills(terms, pattern);
213
+ const parts = [];
214
+ if (scored.length > 0) {
215
+ parts.push(`Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +
216
+ lines.join('\n'));
217
+ }
218
+ if (skillLines.length > 0) {
219
+ parts.push(`\nMatching SKILLS — read one with fs_read_skill before you plan, do not guess syntax it covers:\n` +
220
+ skillLines.join('\n'));
221
+ }
222
+ return {
223
+ success: true,
224
+ output: parts.join('\n'),
225
+ _unlock_tools: unlockTools,
226
+ _unlock_packs: []
227
+ };
184
228
  }
185
- return {
186
- success: true,
187
- output: `Nothing matched "${query}". Available capability packs: ${PACK_NAMES.join(', ')}. ` +
188
- `Try a broader term, or set the "pack" argument to load a whole pack at once.`
189
- };
190
- }
191
-
192
- const unlockTools = [];
193
- const unlockPacks = new Set();
194
- const lines = [];
195
-
196
- for (const { definition } of scored) {
197
- const pack = packForTool(definition.name);
198
- // Unlock anything that is not already resident. The old condition was
199
- // `!isCoreTool(...)`, which was correct while the entire core shipped
200
- // in every request. It is not any more: on a provider without native
201
- // schema deferral only RESIDENT_TOOLS ship, and a non-resident core
202
- // tool found here would have been reported as "already loaded" and
203
- // then stayed invisible forever.
204
- if (!isResidentTool(definition.name)) {
205
- unlockTools.push(definition.name);
206
- if (pack) unlockPacks.add(pack);
229
+ catch (e) {
230
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
207
231
  }
208
- const state = isResidentTool(definition.name)
209
- ? 'already loaded'
210
- : (isCoreTool(definition.name) ? 'core' : `pack: ${pack || 'custom'}`);
211
- lines.push(`- ${definition.name} (${state}): ${definition.description || ''}`);
212
- }
213
-
214
- // Skills are searched alongside tools because `tool_search` is the only
215
- // discovery surface the model always has. The compiled skill catalogue is
216
- // 100 entries; listing it in the system prompt cost ~841 tokens on EVERY
217
- // request of every task, including a bare "hi". Retrieval replaces the
218
- // catalogue — but only because the retrieval exists, which it did not
219
- // before this change.
220
- const skillLines = await searchSkills(terms, pattern);
221
-
222
- const parts = [];
223
- if (scored.length > 0) {
224
- parts.push(
225
- `Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +
226
- lines.join('\n')
227
- );
228
- }
229
- if (skillLines.length > 0) {
230
- parts.push(
231
- `\nMatching SKILLS — read one with fs_read_skill before you plan, do not guess syntax it covers:\n` +
232
- skillLines.join('\n')
233
- );
234
- }
235
-
236
- return {
237
- success: true,
238
- output: parts.join('\n'),
239
- _unlock_tools: unlockTools,
240
- _unlock_packs: [...unlockPacks]
241
- };
242
- } catch (e) {
243
- return { success: false, error: e.message };
244
232
  }
245
- }
246
233
  };