@causyne/agent 1.20.12 → 1.20.14

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 (72) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/SmartTools.js +33 -0
  4. package/src/SmartTools.ts +37 -0
  5. package/src/acp/client.js +157 -4
  6. package/src/acp/client.ts +152 -5
  7. package/src/agentLoop.js +857 -178
  8. package/src/agentLoop.ts +865 -183
  9. package/src/browser/browserRuntime.js +8 -1
  10. package/src/browser/browserRuntime.ts +8 -1
  11. package/src/browser/causyneBrowser.js +20 -4
  12. package/src/browser/causyneBrowser.ts +20 -4
  13. package/src/browser/urlPolicy.js +35 -0
  14. package/src/browser/urlPolicy.ts +34 -0
  15. package/src/cliMode.js +6 -2
  16. package/src/commands.js +14 -0
  17. package/src/contextManager.d.ts +1 -0
  18. package/src/core/contextCompactor.js +277 -0
  19. package/src/core/contextCompactor.ts +353 -0
  20. package/src/decideTools.js +157 -0
  21. package/src/decideTools.ts +195 -0
  22. package/src/decisionPolicy.js +5 -3
  23. package/src/decisionPolicy.ts +5 -3
  24. package/src/implementationPlan.js +284 -0
  25. package/src/implementationPlan.ts +275 -0
  26. package/src/observer/coldObserver.js +10 -4
  27. package/src/observer/coldObserver.ts +15 -7
  28. package/src/observer/evidence.js +11 -5
  29. package/src/observer/evidence.ts +13 -6
  30. package/src/observer.js +196 -0
  31. package/src/observer.ts +287 -0
  32. package/src/providers/acp.js +362 -109
  33. package/src/providers/acp.ts +359 -111
  34. package/src/providers/antigravity.js +133 -105
  35. package/src/providers/antigravity.ts +130 -109
  36. package/src/providers/base.d.ts +3 -0
  37. package/src/providers/budgetEnforcer.js +13 -0
  38. package/src/providers/budgetEnforcer.ts +13 -3
  39. package/src/provisioning/capabilityProvisioner.js +14 -10
  40. package/src/sandbox.js +4 -2
  41. package/src/saveTools.js +146 -0
  42. package/src/saveTools.ts +169 -0
  43. package/src/session/cachePressure.js +77 -0
  44. package/src/session/cachePressure.ts +122 -0
  45. package/src/smartToolsUse.js +69 -12
  46. package/src/smartToolsUse.ts +103 -12
  47. package/src/taskShape.js +7 -7
  48. package/src/taskShape.ts +7 -7
  49. package/src/timeMachine.js +55 -20
  50. package/src/timeMachine.ts +64 -20
  51. package/src/toolPacks.js +217 -310
  52. package/src/toolPacks.ts +505 -0
  53. package/src/tools/deferredMcpSearch.js +21 -13
  54. package/src/tools/deferredMcpSearch.ts +23 -15
  55. package/src/tools/updatePlan.js +2 -2
  56. package/src/tools/updatePlan.ts +2 -2
  57. package/src/toolsList.js +203 -0
  58. package/src/toolsList.ts +224 -0
  59. package/src/tui/chatRenderer.js +49 -14
  60. package/src/tui/codeStreamRenderer.js +16 -5
  61. package/src/tui/codeStreamRenderer.ts +14 -4
  62. package/src/tui/prompt.js +4 -2
  63. package/src/tui/sessionSidebar.js +10 -2
  64. package/src/tui/sessionSidebar.ts +10 -3
  65. package/src/tui/stageSurface.js +27 -1
  66. package/src/tui/text.d.ts +1 -0
  67. package/src/tui/turnRail.js +274 -0
  68. package/src/tui/turnRail.ts +334 -0
  69. package/src/types/contracts.ts +103 -0
  70. package/src/verificationPlan.js +141 -0
  71. package/src/verificationPlan.ts +166 -0
  72. package/src/toolPacks.d.ts +0 -10
@@ -0,0 +1,353 @@
1
+ /**
2
+ * @file src/core/contextCompactor.ts
3
+ * Enterprise-Grade Context Compactor (OpenAI Codex & Claude Code Architecture).
4
+ *
5
+ * Provides:
6
+ * 1. High-fidelity structured state summarization (Goal, Architecture, Files, Milestones, Next Steps).
7
+ * 2. Non-destructive physical in-place compaction preserving root anchor and recent turns.
8
+ * 3. Proactive auto-compaction before context limits or token budgets choke execution.
9
+ * 4. User-facing `/compact` slash-command handler.
10
+ *
11
+ * Authorship: Strict TypeScript (Causyne Agent).
12
+ */
13
+
14
+ import {
15
+ pruneStaleToolObservations,
16
+ shortenOversizedToolObservations,
17
+ pruneExecutedToolArguments,
18
+ buildRecoverableDroppedSummary,
19
+ type ToolObservation
20
+ } from '../historyPruner.js';
21
+ import { compactInPlace, measureMessages, CHARS_PER_TOKEN } from '../contextManager.js';
22
+
23
+ export interface CodexCompactedState {
24
+ readonly goal: string;
25
+ readonly architectureNotes: readonly string[];
26
+ readonly createdFiles: readonly string[];
27
+ readonly modifiedFiles: readonly string[];
28
+ readonly inspectedFiles: readonly string[];
29
+ readonly verifiedMilestones: readonly string[];
30
+ readonly pendingMilestones: readonly string[];
31
+ readonly toolsSummary: string;
32
+ }
33
+
34
+ export interface CompactionOptions {
35
+ readonly keepRecentTurns?: number;
36
+ readonly taskId?: string;
37
+ readonly originalPrompt?: string;
38
+ readonly maxCharPool?: number;
39
+ }
40
+
41
+ export interface CompactionResult {
42
+ readonly compacted: boolean;
43
+ readonly removedCount: number;
44
+ readonly reclaimedChars: number;
45
+ readonly reclaimedTokens: number;
46
+ readonly initialChars: number;
47
+ readonly finalChars: number;
48
+ readonly summaryText: string;
49
+ readonly reason?: string;
50
+ }
51
+
52
+ /**
53
+ * Extracts a high-fidelity, structured state summary from dropped message history.
54
+ * Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
55
+ */
56
+ export function buildCodexStyleSummary(
57
+ droppedMessages: readonly ToolObservation[],
58
+ originalPrompt?: string
59
+ ): string {
60
+ const createdFiles = new Set<string>();
61
+ const modifiedFiles = new Set<string>();
62
+ const inspectedFiles = new Set<string>();
63
+ const verifiedMilestones = new Set<string>();
64
+ const toolCounts = new Map<string, number>();
65
+ const architectureNotes = new Set<string>();
66
+ const failures = new Set<string>();
67
+
68
+ for (const msg of droppedMessages) {
69
+ if (msg.role === 'assistant') {
70
+ const calls = msg.tool_calls || [];
71
+ for (const call of calls) {
72
+ const fnName = call.function?.name || 'tool';
73
+ toolCounts.set(fnName, (toolCounts.get(fnName) || 0) + 1);
74
+
75
+ try {
76
+ const rawArgs = call.function?.arguments;
77
+ if (typeof rawArgs === 'string') {
78
+ const parsed = JSON.parse(rawArgs);
79
+ if (parsed && typeof parsed === 'object') {
80
+ const target = String(parsed.path || parsed.file_path || parsed.target || '');
81
+ if (target) {
82
+ if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
83
+ createdFiles.add(target);
84
+ } else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
85
+ modifiedFiles.add(target);
86
+ } else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
87
+ inspectedFiles.add(target);
88
+ }
89
+ }
90
+
91
+ // Detect architectural and technology declarations
92
+ if (parsed.command && typeof parsed.command === 'string') {
93
+ const cmd = parsed.command;
94
+ if (/npm\s+i|install/i.test(cmd)) architectureNotes.add(`Dependencies: ${cmd.slice(0, 100)}`);
95
+ if (/tsc|build/i.test(cmd)) architectureNotes.add('Compiled build pipeline invoked');
96
+ }
97
+ }
98
+ }
99
+ } catch {
100
+ // Arguments might be truncated or non-JSON; continue extraction.
101
+ }
102
+ }
103
+
104
+ // Extract technology/design keywords from assistant narrative
105
+ if (typeof msg.content === 'string') {
106
+ const text = msg.content;
107
+ if (/three\.?js|webgl|canvas3d/i.test(text)) architectureNotes.add('Three.js / WebGL 3D rendering pipeline');
108
+ if (/audio(?:\s*context|\s*engine)|\.mp3|\.wav/i.test(text)) architectureNotes.add('Web Audio Engine & sound effects');
109
+ if (/blender/i.test(text)) architectureNotes.add('Blender 3D procedural studio');
110
+ if (/typescript/i.test(text)) architectureNotes.add('Strict TypeScript architecture');
111
+ }
112
+ }
113
+
114
+ if (msg.role === 'tool') {
115
+ const contentStr = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content ?? '');
116
+ try {
117
+ const parsed = JSON.parse(contentStr);
118
+ if (parsed && typeof parsed === 'object') {
119
+ if (parsed.success === true) {
120
+ if (msg.name) verifiedMilestones.add(`${msg.name} verified`);
121
+ } else if (parsed.success === false && parsed.error) {
122
+ failures.add(`${msg.name || 'tool'}: ${String(parsed.error).slice(0, 120)}`);
123
+ }
124
+ }
125
+ } catch {
126
+ // Plain output or decayed marker
127
+ }
128
+ }
129
+ }
130
+
131
+ // Build the Codex-style structured report
132
+ const sections: string[] = [];
133
+
134
+ sections.push('### [COMPACTED CONTEXT CHECKPOINT — CODEX STATE PRESERVATION]');
135
+
136
+ if (originalPrompt && originalPrompt.trim()) {
137
+ sections.push(`**Goal & User Intent:**\n${originalPrompt.trim()}`);
138
+ }
139
+
140
+ if (architectureNotes.size > 0) {
141
+ sections.push(`**Architecture & Technology Stack:**\n${[...architectureNotes].map(a => `- ${a}`).join('\n')}`);
142
+ }
143
+
144
+ const allFilesTouched = [
145
+ ...[...createdFiles].map(f => `- [Created] ${f}`),
146
+ ...[...modifiedFiles].map(f => `- [Modified] ${f}`),
147
+ ...[...inspectedFiles].filter(f => !createdFiles.has(f) && !modifiedFiles.has(f)).map(f => `- [Inspected] ${f}`)
148
+ ];
149
+
150
+ if (allFilesTouched.length > 0) {
151
+ sections.push(`**Files Manifest & Workspace State:**\n${allFilesTouched.slice(0, 20).join('\n')}`);
152
+ }
153
+
154
+ if (toolCounts.size > 0) {
155
+ const summary = [...toolCounts.entries()]
156
+ .sort((a, b) => b[1] - a[1])
157
+ .map(([name, count]) => `${name} (${count}x)`)
158
+ .join(', ');
159
+ sections.push(`**Actions Executed:** ${summary}`);
160
+ }
161
+
162
+ if (verifiedMilestones.size > 0) {
163
+ sections.push(`**Verified Outcomes:** ${[...verifiedMilestones].slice(0, 8).join(', ')}`);
164
+ }
165
+
166
+ if (failures.size > 0) {
167
+ sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
168
+ }
169
+
170
+ sections.push(
171
+ '**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
172
+ + 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.'
173
+ );
174
+
175
+ return sections.join('\n\n');
176
+ }
177
+
178
+ /**
179
+ * Compacts the conversation trajectory in-place.
180
+ * Preserves the Golden Anchor (message 0) and the most recent working turns.
181
+ */
182
+ export function compactSessionMessages(
183
+ messages: any[],
184
+ options: CompactionOptions = {}
185
+ ): CompactionResult {
186
+ const initialChars = measureMessages(messages);
187
+ const keepRecentTurns = Math.max(2, options.keepRecentTurns ?? 4);
188
+
189
+ // Must have enough messages to compact: root message (0) + at least 2 dropped + keepRecent
190
+ if (messages.length < keepRecentTurns + 3) {
191
+ return {
192
+ compacted: false,
193
+ removedCount: 0,
194
+ reclaimedChars: 0,
195
+ reclaimedTokens: 0,
196
+ initialChars,
197
+ finalChars: initialChars,
198
+ summaryText: '',
199
+ reason: 'History contains too few messages for compaction.'
200
+ };
201
+ }
202
+
203
+ // Pre-pass: run Observation Elision and Argument Archiving on all messages
204
+ pruneStaleToolObservations(messages, {
205
+ keepRecent: keepRecentTurns,
206
+ minChars: 300,
207
+ taskId: options.taskId ?? 'compaction'
208
+ });
209
+ shortenOversizedToolObservations(messages, {
210
+ threshold: 1500,
211
+ taskId: options.taskId ?? 'compaction'
212
+ });
213
+ pruneExecutedToolArguments(messages, {
214
+ threshold: 1500,
215
+ taskId: options.taskId ?? 'compaction'
216
+ });
217
+
218
+ // Calculate split index for physical compaction:
219
+ // Messages from index 1 to splitIndex will be collapsed into a single summary
220
+ const splitIndex = messages.length - keepRecentTurns - 1;
221
+ if (splitIndex < 1) {
222
+ return {
223
+ compacted: false,
224
+ removedCount: 0,
225
+ reclaimedChars: 0,
226
+ reclaimedTokens: 0,
227
+ initialChars,
228
+ finalChars: measureMessages(messages),
229
+ summaryText: '',
230
+ reason: 'Split index out of range.'
231
+ };
232
+ }
233
+
234
+ const dropped = messages.slice(1, splitIndex + 1);
235
+ const rootPrompt = typeof messages[0]?.content === 'string'
236
+ ? messages[0].content
237
+ : options.originalPrompt;
238
+
239
+ const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt);
240
+ const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
241
+
242
+ const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
243
+ const finalChars = measureMessages(messages);
244
+ const reclaimedChars = Math.max(0, initialChars - finalChars);
245
+ const reclaimedTokens = Math.round(reclaimedChars / CHARS_PER_TOKEN);
246
+
247
+ return {
248
+ compacted: true,
249
+ removedCount: removed,
250
+ reclaimedChars,
251
+ reclaimedTokens,
252
+ initialChars,
253
+ finalChars,
254
+ summaryText: fullRecoverableSummary
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Proactively checks memory pressure and runs auto-compaction if context threshold is exceeded.
260
+ * Operates silently and seamlessly without interrupting active work.
261
+ */
262
+ export function autoCompactIfUnderPressure(
263
+ loop: any,
264
+ options: { thresholdFraction?: number; minMessages?: number } = {}
265
+ ): CompactionResult | null {
266
+ if (!loop || !Array.isArray(loop.messages) || loop.messages.length < (options.minMessages ?? 12)) {
267
+ return null;
268
+ }
269
+
270
+ const thresholdFraction = options.thresholdFraction ?? 0.70;
271
+ const currentChars = measureMessages(loop.messages);
272
+ const maxPool = loop._contextLimitChars || 120_000;
273
+
274
+ if (currentChars >= maxPool * thresholdFraction) {
275
+ const result = compactSessionMessages(loop.messages, {
276
+ keepRecentTurns: 4,
277
+ taskId: loop.taskId,
278
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt
279
+ });
280
+
281
+ if (result.compacted) {
282
+ if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
283
+ loop.memoryManager.saveHistory(loop.messages);
284
+ }
285
+ if (typeof loop.emitEvent === 'function') {
286
+ loop.emitEvent({
287
+ type: 'status',
288
+ message: `Context auto-compacted: reclaimed ${(result.reclaimedChars / 1024).toFixed(1)} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`
289
+ });
290
+ }
291
+ return result;
292
+ }
293
+ }
294
+
295
+ return null;
296
+ }
297
+
298
+ /**
299
+ * Slash command handler for `/compact`.
300
+ */
301
+ export async function runCompactSlashCommand(
302
+ _argv: string[],
303
+ ctx: { loop?: any; prompt?: any }
304
+ ): Promise<{ ok: boolean; output: string }> {
305
+ const loop = ctx.loop;
306
+ if (!loop || !Array.isArray(loop.messages) || loop.messages.length === 0) {
307
+ return {
308
+ ok: false,
309
+ output: 'No active session or conversation messages to compact.'
310
+ };
311
+ }
312
+
313
+ if (loop.messages.length <= 3) {
314
+ return {
315
+ ok: true,
316
+ output: `Conversation currently contains only ${loop.messages.length} message(s). Compaction is not needed yet.`
317
+ };
318
+ }
319
+
320
+ const result = compactSessionMessages(loop.messages, {
321
+ keepRecentTurns: 4,
322
+ taskId: loop.taskId || 'manual-compact',
323
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt
324
+ });
325
+
326
+ if (!result.compacted) {
327
+ return {
328
+ ok: true,
329
+ output: result.reason || 'Context already compact. No older messages eligible for compaction.'
330
+ };
331
+ }
332
+
333
+ if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
334
+ loop.memoryManager.saveHistory(loop.messages);
335
+ }
336
+
337
+ const reclaimedKb = (result.reclaimedChars / 1024).toFixed(1);
338
+ const finalKb = (result.finalChars / 1024).toFixed(1);
339
+
340
+ const report = [
341
+ '✔ Context successfully compacted (OpenAI Codex structured state model).',
342
+ '',
343
+ ` • Earlier messages condensed: ${result.removedCount}`,
344
+ ` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
345
+ ` • Live active context: ${finalKb} KB`,
346
+ ' • Golden Anchor (original prompt) & recent working turns: Preserved in full',
347
+ ' • Deliverables and source files on disk: 100% intact',
348
+ '',
349
+ 'The agent will continue with a clean, focused context without losing prior achievements.'
350
+ ].join('\n');
351
+
352
+ return { ok: true, output: report };
353
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @file src/decideTools.ts
3
+ * decideTools — stage 2 of the tool pipeline.
4
+ *
5
+ * user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
6
+ *
7
+ * Decides WHICH listed tools a task needs. It never loads anything and never
8
+ * runs a model: it is a pure function over the intent, the task shape and the
9
+ * ToolsList, so it costs no tokens and is identical on every provider.
10
+ *
11
+ * It is entered again whenever the work changes shape — the model asks for a
12
+ * tool, an implementation plan is accepted, verification needs evidence, or a
13
+ * failure demands a different route — and always from the same list.
14
+ *
15
+ * Authorship: Strict TypeScript (Causyne Agent).
16
+ */
17
+ import { determineToolScope, filterSuppressedPacks } from './smartToolsUse.js';
18
+ import { routePacks, packForTool, PACK_NAMES } from './toolPacks.js';
19
+ import { packsFromShape } from './taskShape.js';
20
+ import { buildToolsList } from './toolsList.js';
21
+ /** A single decision from free text never admits more than this many tools. */
22
+ export const MAX_TEXT_TOOLS = 8;
23
+ /** A Three.js, WebGL, canvas or Python game needs no engine pack. */
24
+ export function isDirectGameTask(text) {
25
+ return /\b(three?\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
26
+ && !/\b(godot|unity|unreal|full engine)\b/i.test(text);
27
+ }
28
+ /**
29
+ * What a plan step, a verification need or a failure implies. Every name here
30
+ * is checked against the ToolsList before use, so a stale entry is inert.
31
+ */
32
+ const TRIGGERS = [
33
+ { pattern: /\b(preview|screenshot|visual(?:ly)?|rendered? (?:page|output|ui)|browser|snapshot|look at (?:the )?(?:ui|page|screen))\b/i,
34
+ tools: ['browser_act', 'screenshot', 'view_image'], why: 'rendered output must be looked at' },
35
+ { pattern: /\b(vision|ocr|inspect (?:the )?(?:ui|screen))\b/i, tools: ['vision_inspect_ui'], why: 'screen inspection' },
36
+ { pattern: /\b(blender(?:_act)?|3d\b|mesh|render (?:frame|animation|model)?)\b/i, tools: ['blender_act', 'view_image'], why: '3D work' },
37
+ { pattern: /\b(pdf|docx?|document|proposal|screenplay|shot ?list|report)\b/i, tools: ['document_forge', 'pdf_read'], why: 'document production' },
38
+ { pattern: /\b(image|illustration|logo|poster|thumbnail|music|song|voice|tts|narration|video)\b/i,
39
+ tools: ['generate_media_via_api', 'execute_procedural_media'], why: 'media generation' },
40
+ { pattern: /\b(kill|terminate|port \d+|processes?)\b/i, tools: ['process_list', 'proc_term'], why: 'process control' },
41
+ { pattern: /\b(zip|unzip|archive|extract|tarball)\b/i, tools: ['archive'], why: 'archive handling' },
42
+ { pattern: /\b(sub-?agents?|in parallel|delegate)\b/i, tools: ['agent_subagent_orchestrate'], why: 'delegation' },
43
+ { pattern: /\b(symbols?|definitions?|ast)\b/i, tools: ['code_list_symbols', 'code_search_ast'], why: 'structural code search' },
44
+ { pattern: /\b(syntax|compile|typecheck|lint)\b/i, tools: ['code_verify_syntax'], why: 'static check' },
45
+ { pattern: /\b(godot|\.tscn|gdscript)\b/i, tools: ['godot_act', 'game_scene_build'], why: 'Godot work' },
46
+ { pattern: /\b(clipboard)\b/i, tools: ['clipboard'], why: 'clipboard' },
47
+ { pattern: /\b(gui|desktop app|accessibility|click (?:the )?button)\b/i, tools: ['ax_snapshot', 'desktop_act'], why: 'GUI control' },
48
+ { pattern: /\b(commit|branch|merge|rebase)\b/i, tools: ['gitOp'], why: 'version control' },
49
+ { pattern: /\b(search the web|look up|latest version|official docs?|documentation)\b/i, tools: ['web_search', 'web_fetch'], why: 'external facts' },
50
+ { pattern: /\b(ask the user|decide between|which (?:option|approach))\b/i, tools: ['request_decision'], why: 'user decision' },
51
+ { pattern: /\b(hardware|gpu|disk space|ram)\b/i, tools: ['check_system_specs'], why: 'hardware check' }
52
+ ];
53
+ function listed(list) {
54
+ const entries = Array.isArray(list) ? list : buildToolsList();
55
+ const byLower = new Map();
56
+ for (const entry of entries)
57
+ byLower.set(entry.name.toLowerCase(), entry.name);
58
+ return byLower;
59
+ }
60
+ function unique(values) {
61
+ return [...new Set(values)];
62
+ }
63
+ /** Match free text against the triggers, restricted to tools that are actually listed. */
64
+ export function toolsForText(text, list) {
65
+ const known = listed(list);
66
+ const tools = [];
67
+ const reasons = [];
68
+ for (const trigger of TRIGGERS) {
69
+ if (!trigger.pattern.test(text))
70
+ continue;
71
+ const present = trigger.tools.filter((name) => known.has(name.toLowerCase()));
72
+ if (present.length === 0)
73
+ continue;
74
+ for (const name of present)
75
+ if (!tools.includes(name))
76
+ tools.push(name);
77
+ reasons.push(trigger.why);
78
+ if (tools.length >= MAX_TEXT_TOOLS)
79
+ break;
80
+ }
81
+ return { tools: tools.slice(0, MAX_TEXT_TOOLS), reasons };
82
+ }
83
+ export function decideTools(input) {
84
+ const known = listed(input.list);
85
+ const reasons = [];
86
+ const tools = [];
87
+ const packs = [];
88
+ let archetype = 'generalist';
89
+ let suppressedPacks = [];
90
+ // Names the model asked for are honoured; a listed name is canonicalised.
91
+ for (const raw of input.requested ?? []) {
92
+ const name = String(raw ?? '').trim();
93
+ if (!name)
94
+ continue;
95
+ const canonical = known.get(name.toLowerCase());
96
+ if (canonical)
97
+ tools.push(canonical);
98
+ }
99
+ if (tools.length > 0)
100
+ reasons.push(`requested: ${tools.join(', ')}`);
101
+ const validPacks = new Set(PACK_NAMES);
102
+ for (const pack of input.requestedPacks ?? []) {
103
+ if (validPacks.has(pack))
104
+ packs.push(pack);
105
+ }
106
+ const effectiveSource = input.source ?? (input.prompt ? 'intent' : 'request');
107
+ if (effectiveSource === 'intent') {
108
+ const prompt = input.prompt ?? '';
109
+ const scope = determineToolScope(prompt, input.taskShape);
110
+ archetype = scope.archetype;
111
+ suppressedPacks = scope.suppressedPacks;
112
+ if (scope.toolScope) {
113
+ for (const name of scope.toolScope) {
114
+ const canonical = known.get(name.toLowerCase());
115
+ if (canonical)
116
+ tools.push(canonical);
117
+ }
118
+ reasons.push(`scope ${scope.archetype}`);
119
+ }
120
+ const scored = packsFromShape(input.taskShape ?? null);
121
+ const fallback = routePacks(prompt, input.workspace ?? null);
122
+ const candidates = filterSuppressedPacks([...scored, ...fallback], prompt);
123
+ for (const pack of candidates) {
124
+ if (!validPacks.has(pack))
125
+ continue;
126
+ if (pack === 'game' && isDirectGameTask(prompt))
127
+ continue;
128
+ packs.push(pack);
129
+ }
130
+ if (packs.length > 0)
131
+ reasons.push(`suggested domains ${packs.join(', ')}`);
132
+ for (const name of input.cachedTools ?? []) {
133
+ const canonical = known.get(name.toLowerCase());
134
+ if (!canonical)
135
+ continue;
136
+ tools.push(canonical);
137
+ // A cached route admits IDs only, never an entire domain or permissions.
138
+ }
139
+ if ((input.cachedTools?.length ?? 0) > 0)
140
+ reasons.push('proven route');
141
+ }
142
+ if (input.text) {
143
+ const found = toolsForText(input.text, input.list);
144
+ for (const name of found.tools)
145
+ tools.push(name);
146
+ for (const why of found.reasons)
147
+ reasons.push(why);
148
+ }
149
+ return {
150
+ source: input.source,
151
+ tools: unique(tools),
152
+ packs: unique(packs),
153
+ archetype,
154
+ suppressedPacks,
155
+ reasons
156
+ };
157
+ }