@causyne/agent 1.20.10 → 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 (88) 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 +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  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/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,250 @@
1
+ import type { ParameterSchema } from './toolSelfRepair.js';
2
+ interface ToolDefinition { name: string; description?: string; parameters?: ParameterSchema; input_schema?: ParameterSchema; }
3
+ interface SearchArgs { query?: string; pack?: string; limit?: number; }
4
+ interface SearchResult { success: boolean; output?: string; error?: string; _unlock_tools?: string[]; _unlock_packs?: string[]; }
5
+ // registry.js imports THIS module to build its tool table, so a static import
6
+ // back the other way is a cycle: whichever side loads first sees the other as
7
+ // uninitialised and the whole registry throws. It happened to work only while
8
+ // registry.js was always imported first. Loaded on demand instead — execute()
9
+ // is async, so this costs nothing.
10
+ async function toolDefinitions(): Promise<ToolDefinition[]> {
11
+ const { getSearchableToolDefinitions } = await import('./registry.js');
12
+ return getSearchableToolDefinitions();
13
+ }
14
+ import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
15
+
16
+ /** Max skills returned alongside the tool matches, so one search stays cheap. */
17
+ const MAX_SKILL_HITS = 5;
18
+
19
+ /**
20
+ * Score the skill catalogue with the same query the tools were scored with.
21
+ *
22
+ * Exists because there was no skill search at all: the system prompt carried a
23
+ * 40-entry catalogue and that was the ONLY way the model could learn a skill id.
24
+ * Replacing that catalogue with a domain header is only safe once this exists.
25
+ *
26
+ * @returns {string[]} formatted lines, empty when nothing matched
27
+ */
28
+ async function searchSkills(terms: string[], pattern: RegExp | null): Promise<string[]> {
29
+ // Imported lazily, not at module scope: registry.js imports THIS module, and
30
+ // skillsManager pulls registry back in transitively — a static import here
31
+ // closes the cycle and the whole tool registry fails to initialise. Same
32
+ // pattern registry.js already uses for capabilityTools.
33
+ let catalogue;
34
+ try {
35
+ const { listCompiledSkills } = await import('../skillsManager.js');
36
+ catalogue = listCompiledSkills();
37
+ } catch (e) {
38
+ return []; // a broken skill store must not take tool search down
39
+ }
40
+
41
+ const scored = [];
42
+ for (const skill of catalogue) {
43
+ const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
44
+ let score = 0;
45
+ if (pattern) {
46
+ if (pattern.test(skill.name) || pattern.test(skill.id)) score += 10;
47
+ if (pattern.test(skill.description || '')) score += 4;
48
+ }
49
+ for (const term of terms) {
50
+ if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term)) score += 8;
51
+ else if (skill.domain.toLowerCase() === term) score += 6;
52
+ else if (haystack.includes(term)) score += 3;
53
+ }
54
+ if (score > 0) scored.push({ skill, score });
55
+ }
56
+
57
+ return scored
58
+ .sort((a, b) => b.score - a.score)
59
+ .slice(0, MAX_SKILL_HITS)
60
+ .map(({ skill }) => `- ${skill.domain}/${skill.id} — ${skill.name}: ${skill.description || ''}`);
61
+ }
62
+
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
+
75
+ function scoreTool(definition: ToolDefinition, terms: string[], pattern: RegExp | null): number {
76
+ const name = (definition.name || '').toLowerCase();
77
+ const description = (definition.description || '').toLowerCase();
78
+
79
+ // Parameter names and descriptions are searchable too — a query like
80
+ // "kill process on port" should find a tool whose `port` argument mentions it.
81
+ let parameterText = '';
82
+ const properties = definition.parameters?.properties || definition.input_schema?.properties;
83
+ if (properties) {
84
+ for (const [key, value] of Object.entries(properties)) {
85
+ parameterText += ` ${key} ${(value && value.description) || ''}`;
86
+ }
87
+ }
88
+ parameterText = parameterText.toLowerCase();
89
+
90
+ let score = 0;
91
+
92
+ if (pattern) {
93
+ if (pattern.test(name)) score += 12;
94
+ if (pattern.test(description)) score += 6;
95
+ if (pattern.test(parameterText)) score += 2;
96
+ }
97
+
98
+ for (const term of terms) {
99
+ if (name.includes(term)) score += 10;
100
+ if (description.includes(term)) score += 4;
101
+ if (parameterText.includes(term)) score += 1;
102
+ }
103
+
104
+ return score;
105
+ }
106
+
107
+ function buildPattern(query: string): RegExp | null {
108
+ // The query may be a natural-language phrase or a regular expression. Trying
109
+ // it as a regex first gives power users exact control; a malformed pattern
110
+ // simply falls back to keyword scoring instead of throwing.
111
+ try {
112
+ return new RegExp(query, 'i');
113
+ } catch (e) {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ export const deferredMcpSearch = {
119
+ schema: {
120
+ name: 'tool.search',
121
+ 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.',
122
+ parameters: {
123
+ type: 'object',
124
+ properties: {
125
+ query: {
126
+ type: 'string',
127
+ description: 'What capability you need. Natural language or a regex pattern matched against tool names, descriptions and argument descriptions.'
128
+ },
129
+ pack: {
130
+ type: 'string',
131
+ enum: [...PACK_NAMES, 'all'],
132
+ description: 'Optional. Load an entire capability pack at once instead of searching: game, web, media, system, or advanced.'
133
+ },
134
+ limit: {
135
+ type: 'integer',
136
+ description: 'Maximum number of tools to return. Defaults to 8.'
137
+ }
138
+ },
139
+ required: ['query']
140
+ }
141
+ },
142
+
143
+ async execute(args: SearchArgs): Promise<SearchResult> {
144
+ try {
145
+ const query = String(args.query || '').trim();
146
+ const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
147
+
148
+ if (!query && !requestedPack) {
149
+ return { success: false, error: 'Provide a "query" describing the capability you need, or a "pack" name to load.' };
150
+ }
151
+
152
+ // Whole-pack load. Cheaper than five searches when the agent already
153
+ // knows it is starting a game or a media pipeline.
154
+ if (requestedPack && requestedPack !== 'all' && Object.hasOwn(PACKS, requestedPack)) {
155
+ const packTools = (await toolDefinitions()).filter(d => packForTool(d.name) === requestedPack);
156
+ return {
157
+ success: true,
158
+ output: `Loaded capability pack "${requestedPack}" (${packTools.length} tools). These are now callable:\n` +
159
+ packTools.map(d => `- ${d.name}: ${d.description || ''}`).join('\n'),
160
+ _unlock_packs: [requestedPack],
161
+ _unlock_tools: packTools.map(d => d.name)
162
+ };
163
+ }
164
+
165
+ const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
166
+ const lower = query.toLowerCase();
167
+ const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
168
+ const pattern = buildPattern(query);
169
+
170
+ const definitions = await toolDefinitions();
171
+ const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
172
+ const scored = (exact ? [exact] : definitions)
173
+ .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
174
+ .filter(entry => entry.score > 0)
175
+ .sort((a, b) => b.score - a.score)
176
+ .slice(0, limit);
177
+
178
+ if (scored.length === 0) {
179
+ // Still search skills. "how do I structure a django migration" matches
180
+ // no tool name and every relevant skill — returning "no tools matched"
181
+ // and stopping was the whole reason a 40-entry catalogue had to sit in
182
+ // the system prompt.
183
+ const skillOnly = await searchSkills(terms, pattern);
184
+ if (skillOnly.length > 0) {
185
+ return {
186
+ success: true,
187
+ output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
188
+ skillOnly.join('\n')
189
+ };
190
+ }
191
+ return {
192
+ success: true,
193
+ output: `Nothing matched "${query}". Available capability packs: ${PACK_NAMES.join(', ')}. ` +
194
+ `Try a broader term, or set the "pack" argument to load a whole pack at once.`
195
+ };
196
+ }
197
+
198
+ const unlockTools = [];
199
+ const lines = [];
200
+
201
+ for (const { definition } of scored) {
202
+ const pack = packForTool(definition.name);
203
+ // Unlock anything that is not already resident. The old condition was
204
+ // `!isCoreTool(...)`, which was correct while the entire core shipped
205
+ // in every request. It is not any more: on a provider without native
206
+ // schema deferral only RESIDENT_TOOLS ship, and a non-resident core
207
+ // tool found here would have been reported as "already loaded" and
208
+ // then stayed invisible forever.
209
+ if (!isResidentTool(definition.name)) {
210
+ unlockTools.push(definition.name);
211
+ }
212
+ const state = isResidentTool(definition.name)
213
+ ? 'already loaded'
214
+ : (isCoreTool(definition.name) ? 'core' : `pack: ${pack || 'custom'}`);
215
+ lines.push(`- ${definition.name} (${state}): ${definition.description || ''}`);
216
+ }
217
+
218
+ // Skills are searched alongside tools because `tool_search` is the only
219
+ // discovery surface the model always has. The compiled skill catalogue is
220
+ // 100 entries; listing it in the system prompt cost ~841 tokens on EVERY
221
+ // request of every task, including a bare "hi". Retrieval replaces the
222
+ // catalogue — but only because the retrieval exists, which it did not
223
+ // before this change.
224
+ const skillLines = await searchSkills(terms, pattern);
225
+
226
+ const parts = [];
227
+ if (scored.length > 0) {
228
+ parts.push(
229
+ `Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +
230
+ lines.join('\n')
231
+ );
232
+ }
233
+ if (skillLines.length > 0) {
234
+ parts.push(
235
+ `\nMatching SKILLS — read one with fs_read_skill before you plan, do not guess syntax it covers:\n` +
236
+ skillLines.join('\n')
237
+ );
238
+ }
239
+
240
+ return {
241
+ success: true,
242
+ output: parts.join('\n'),
243
+ _unlock_tools: unlockTools,
244
+ _unlock_packs: []
245
+ };
246
+ } catch (e) {
247
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
248
+ }
249
+ }
250
+ };