@riotprompt/riotprompt 0.0.8 → 0.0.10

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 (59) hide show
  1. package/.kodrdriv-test-cache.json +6 -0
  2. package/BUG-ANALYSIS.md +523 -0
  3. package/CODE-REVIEW-SUMMARY.md +330 -0
  4. package/FIXES-APPLIED.md +437 -0
  5. package/README.md +2 -2
  6. package/dist/builder.js +3 -0
  7. package/dist/builder.js.map +1 -1
  8. package/dist/chat.d.ts +1 -1
  9. package/dist/chat.js +2 -5
  10. package/dist/chat.js.map +1 -1
  11. package/dist/constants.js +1 -2
  12. package/dist/constants.js.map +1 -1
  13. package/dist/context-manager.d.ts +136 -0
  14. package/dist/context-manager.js +243 -0
  15. package/dist/context-manager.js.map +1 -0
  16. package/dist/conversation-logger.d.ts +285 -0
  17. package/dist/conversation-logger.js +491 -0
  18. package/dist/conversation-logger.js.map +1 -0
  19. package/dist/conversation.d.ts +277 -0
  20. package/dist/conversation.js +649 -0
  21. package/dist/conversation.js.map +1 -0
  22. package/dist/formatter.js.map +1 -1
  23. package/dist/items/section.js +3 -3
  24. package/dist/items/section.js.map +1 -1
  25. package/dist/iteration-strategy.d.ts +233 -0
  26. package/dist/iteration-strategy.js +520 -0
  27. package/dist/iteration-strategy.js.map +1 -0
  28. package/dist/loader.js +21 -3
  29. package/dist/loader.js.map +1 -1
  30. package/dist/message-builder.d.ts +156 -0
  31. package/dist/message-builder.js +256 -0
  32. package/dist/message-builder.js.map +1 -0
  33. package/dist/model-config.d.ts +115 -0
  34. package/dist/model-config.js +205 -0
  35. package/dist/model-config.js.map +1 -0
  36. package/dist/override.js +8 -1
  37. package/dist/override.js.map +1 -1
  38. package/dist/parser.js +3 -3
  39. package/dist/parser.js.map +1 -1
  40. package/dist/recipes.d.ts +42 -0
  41. package/dist/recipes.js +189 -4
  42. package/dist/recipes.js.map +1 -1
  43. package/dist/reflection.d.ts +250 -0
  44. package/dist/reflection.js +419 -0
  45. package/dist/reflection.js.map +1 -0
  46. package/dist/riotprompt.cjs +3854 -178
  47. package/dist/riotprompt.cjs.map +1 -1
  48. package/dist/riotprompt.d.ts +20 -2
  49. package/dist/riotprompt.js +10 -1
  50. package/dist/riotprompt.js.map +1 -1
  51. package/dist/token-budget.d.ts +177 -0
  52. package/dist/token-budget.js +401 -0
  53. package/dist/token-budget.js.map +1 -0
  54. package/dist/tools.d.ts +239 -0
  55. package/dist/tools.js +324 -0
  56. package/dist/tools.js.map +1 -0
  57. package/dist/util/general.js +1 -1
  58. package/dist/util/general.js.map +1 -1
  59. package/package.json +23 -20
@@ -0,0 +1,520 @@
1
+ import { wrapLogger, DEFAULT_LOGGER } from './logger.js';
2
+ import { MetricsCollector, ReflectionReportGenerator } from './reflection.js';
3
+
4
+ function _define_property(obj, key, value) {
5
+ if (key in obj) {
6
+ Object.defineProperty(obj, key, {
7
+ value: value,
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true
11
+ });
12
+ } else {
13
+ obj[key] = value;
14
+ }
15
+ return obj;
16
+ }
17
+ // ===== STRATEGY EXECUTOR =====
18
+ /**
19
+ * StrategyExecutor executes iteration strategies.
20
+ *
21
+ * Features:
22
+ * - Execute multi-phase strategies
23
+ * - Manage tool calls and results
24
+ * - Track state and metrics
25
+ * - Handle timeouts and errors
26
+ * - Provide lifecycle hooks
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const executor = new StrategyExecutor(llmClient);
31
+ *
32
+ * const result = await executor.execute(
33
+ * conversation,
34
+ * toolRegistry,
35
+ * strategy
36
+ * );
37
+ *
38
+ * console.log('Completed in', result.totalIterations, 'iterations');
39
+ * console.log('Used', result.toolCallsExecuted, 'tools');
40
+ * ```
41
+ */ class StrategyExecutor {
42
+ /**
43
+ * Enable reflection generation
44
+ */ withReflection(config) {
45
+ this.reflectionConfig = config;
46
+ return this;
47
+ }
48
+ /**
49
+ * Execute a strategy
50
+ */ async execute(conversation, tools, strategy) {
51
+ var _this_reflectionConfig;
52
+ const startTime = Date.now();
53
+ // Initialize metrics collector if reflection enabled
54
+ if ((_this_reflectionConfig = this.reflectionConfig) === null || _this_reflectionConfig === void 0 ? void 0 : _this_reflectionConfig.enabled) {
55
+ this.metricsCollector = new MetricsCollector(this.logger);
56
+ }
57
+ const state = {
58
+ phase: 0,
59
+ iteration: 0,
60
+ toolCallsExecuted: 0,
61
+ startTime,
62
+ insights: [],
63
+ findings: [],
64
+ errors: [],
65
+ toolFailures: new Map()
66
+ };
67
+ this.logger.info('Starting strategy execution', {
68
+ strategy: strategy.name
69
+ });
70
+ const context = {
71
+ conversation,
72
+ tools,
73
+ llm: this.llm,
74
+ state
75
+ };
76
+ try {
77
+ var _strategy_onStart, _this_reflectionConfig1, _strategy_onComplete;
78
+ // Initialize
79
+ await ((_strategy_onStart = strategy.onStart) === null || _strategy_onStart === void 0 ? void 0 : _strategy_onStart.call(strategy, context));
80
+ // Execute phases or single loop
81
+ const phases = strategy.phases || [
82
+ {
83
+ name: 'default',
84
+ maxIterations: strategy.maxIterations,
85
+ toolUsage: 'encouraged'
86
+ }
87
+ ];
88
+ const phaseResults = [];
89
+ for (const phase of phases){
90
+ var _phase_skipIf, _strategy_onPhaseComplete;
91
+ // Check if should skip phase
92
+ if ((_phase_skipIf = phase.skipIf) === null || _phase_skipIf === void 0 ? void 0 : _phase_skipIf.call(phase, state)) {
93
+ this.logger.debug('Skipping phase', {
94
+ phase: phase.name
95
+ });
96
+ continue;
97
+ }
98
+ state.phase = phase.name;
99
+ state.iteration = 0;
100
+ this.logger.debug('Starting phase', {
101
+ phase: phase.name
102
+ });
103
+ const phaseResult = await this.executePhase(conversation, tools, phase, state, strategy);
104
+ phaseResults.push(phaseResult);
105
+ await ((_strategy_onPhaseComplete = strategy.onPhaseComplete) === null || _strategy_onPhaseComplete === void 0 ? void 0 : _strategy_onPhaseComplete.call(strategy, phaseResult, state));
106
+ // Check if should continue
107
+ if (strategy.shouldContinue && !strategy.shouldContinue(state)) {
108
+ this.logger.debug('Strategy decided to stop');
109
+ break;
110
+ }
111
+ }
112
+ const duration = Date.now() - startTime;
113
+ const result = {
114
+ finalMessage: conversation.getLastMessage(),
115
+ phases: phaseResults,
116
+ totalIterations: state.iteration,
117
+ toolCallsExecuted: state.toolCallsExecuted,
118
+ duration,
119
+ success: true,
120
+ conversation
121
+ };
122
+ // Generate reflection if enabled
123
+ if (this.metricsCollector && ((_this_reflectionConfig1 = this.reflectionConfig) === null || _this_reflectionConfig1 === void 0 ? void 0 : _this_reflectionConfig1.enabled)) {
124
+ const metrics = this.metricsCollector.getMetrics(conversation.getMessages(), conversation.getMetadata().model);
125
+ const generator = new ReflectionReportGenerator(this.logger);
126
+ result.reflection = generator.generate(metrics, result);
127
+ // Save reflection if output path specified
128
+ if (this.reflectionConfig.outputPath && result.reflection) {
129
+ await this.saveReflection(result.reflection, this.reflectionConfig);
130
+ }
131
+ }
132
+ await ((_strategy_onComplete = strategy.onComplete) === null || _strategy_onComplete === void 0 ? void 0 : _strategy_onComplete.call(strategy, result));
133
+ this.logger.info('Strategy execution complete', {
134
+ iterations: result.totalIterations,
135
+ toolCalls: result.toolCallsExecuted,
136
+ duration
137
+ });
138
+ return result;
139
+ } catch (error) {
140
+ this.logger.error('Strategy execution failed', {
141
+ error
142
+ });
143
+ return {
144
+ finalMessage: conversation.getLastMessage(),
145
+ phases: [],
146
+ totalIterations: state.iteration,
147
+ toolCallsExecuted: state.toolCallsExecuted,
148
+ duration: Date.now() - startTime,
149
+ success: false,
150
+ conversation
151
+ };
152
+ }
153
+ }
154
+ /**
155
+ * Save reflection report
156
+ */ async saveReflection(reflection, config) {
157
+ if (!config.outputPath) {
158
+ return;
159
+ }
160
+ try {
161
+ const fs = await import('fs/promises');
162
+ const path = await import('path');
163
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
164
+ const filename = `reflection-${timestamp}.${config.format === 'json' ? 'json' : 'md'}`;
165
+ const fullPath = path.join(config.outputPath, filename);
166
+ // Ensure directory exists
167
+ await fs.mkdir(config.outputPath, {
168
+ recursive: true
169
+ });
170
+ // Save based on format
171
+ if (config.format === 'json') {
172
+ await fs.writeFile(fullPath, JSON.stringify(reflection, null, 2), 'utf-8');
173
+ } else {
174
+ const generator = new ReflectionReportGenerator(this.logger);
175
+ const markdown = generator.formatMarkdown(reflection);
176
+ await fs.writeFile(fullPath, markdown, 'utf-8');
177
+ }
178
+ this.logger.info('Reflection saved', {
179
+ path: fullPath
180
+ });
181
+ } catch (error) {
182
+ this.logger.error('Failed to save reflection', {
183
+ error
184
+ });
185
+ }
186
+ }
187
+ /**
188
+ * Execute a single phase
189
+ */ async executePhase(conversation, tools, phase, state, strategy) {
190
+ const phaseStartTools = state.toolCallsExecuted;
191
+ // Add phase instructions if provided
192
+ if (phase.instructions) {
193
+ conversation.asUser(phase.instructions);
194
+ }
195
+ // Iteration loop for this phase
196
+ for(let i = 0; i < phase.maxIterations; i++){
197
+ var _strategy_onIteration;
198
+ state.iteration++;
199
+ // Track iteration for metrics
200
+ if (this.metricsCollector) {
201
+ this.metricsCollector.incrementIteration();
202
+ }
203
+ this.logger.debug('Iteration', {
204
+ phase: phase.name,
205
+ iteration: i + 1
206
+ });
207
+ // Check iteration hook
208
+ const action = await ((_strategy_onIteration = strategy.onIteration) === null || _strategy_onIteration === void 0 ? void 0 : _strategy_onIteration.call(strategy, i, state));
209
+ if (action === 'stop') {
210
+ break;
211
+ }
212
+ if (action === 'next-phase') {
213
+ break;
214
+ }
215
+ // Get LLM response
216
+ const toolsToProvide = phase.toolUsage !== 'forbidden' ? tools.toOpenAIFormat() : undefined;
217
+ const response = await this.llm.complete(conversation.toMessages(), toolsToProvide);
218
+ // Handle tool calls
219
+ if (response.tool_calls && response.tool_calls.length > 0) {
220
+ if (phase.toolUsage === 'forbidden') {
221
+ this.logger.warn('Tool calls requested but forbidden in this phase');
222
+ conversation.asAssistant(response.content);
223
+ continue;
224
+ }
225
+ conversation.asAssistant(response.content, response.tool_calls);
226
+ // Execute tools
227
+ for (const toolCall of response.tool_calls){
228
+ var _phase_maxConsecutiveToolFailures;
229
+ var _strategy_onToolCall;
230
+ // Check if tool is allowed in this phase
231
+ if (phase.allowedTools && !phase.allowedTools.includes(toolCall.function.name)) {
232
+ this.logger.debug('Tool not allowed in phase', {
233
+ tool: toolCall.function.name
234
+ });
235
+ continue;
236
+ }
237
+ // Circuit breaker: Check if tool has exceeded failure threshold
238
+ const maxFailures = (_phase_maxConsecutiveToolFailures = phase.maxConsecutiveToolFailures) !== null && _phase_maxConsecutiveToolFailures !== void 0 ? _phase_maxConsecutiveToolFailures : 3;
239
+ const consecutiveFailures = state.toolFailures.get(toolCall.function.name) || 0;
240
+ if (consecutiveFailures >= maxFailures) {
241
+ this.logger.warn('Tool circuit breaker triggered', {
242
+ tool: toolCall.function.name,
243
+ failures: consecutiveFailures
244
+ });
245
+ conversation.asTool(toolCall.id, {
246
+ error: `Tool temporarily disabled due to ${consecutiveFailures} consecutive failures`
247
+ }, {
248
+ success: false,
249
+ circuitBreakerTriggered: true
250
+ });
251
+ continue;
252
+ }
253
+ // Check tool call hook
254
+ const toolAction = await ((_strategy_onToolCall = strategy.onToolCall) === null || _strategy_onToolCall === void 0 ? void 0 : _strategy_onToolCall.call(strategy, toolCall, state));
255
+ if (toolAction === 'skip') {
256
+ continue;
257
+ }
258
+ // Execute tool
259
+ const toolStart = Date.now();
260
+ try {
261
+ var _strategy_onToolResult;
262
+ // Parse tool arguments with error handling
263
+ let toolArgs;
264
+ try {
265
+ toolArgs = JSON.parse(toolCall.function.arguments);
266
+ } catch (parseError) {
267
+ const error = new Error(`Invalid JSON in tool arguments for ${toolCall.function.name}: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
268
+ if (parseError instanceof Error) {
269
+ error.cause = parseError; // Preserve original error
270
+ }
271
+ throw error;
272
+ }
273
+ const result = await tools.execute(toolCall.function.name, toolArgs);
274
+ const toolDuration = Date.now() - toolStart;
275
+ const toolResult = {
276
+ callId: toolCall.id,
277
+ toolName: toolCall.function.name,
278
+ result,
279
+ duration: toolDuration
280
+ };
281
+ conversation.asTool(toolCall.id, result, {
282
+ duration: toolDuration,
283
+ success: true
284
+ });
285
+ state.toolCallsExecuted++;
286
+ // Reset failure counter on success
287
+ state.toolFailures.set(toolCall.function.name, 0);
288
+ // Record metrics
289
+ if (this.metricsCollector) {
290
+ this.metricsCollector.recordToolCall(toolCall.function.name, state.iteration, toolDuration, true);
291
+ }
292
+ await ((_strategy_onToolResult = strategy.onToolResult) === null || _strategy_onToolResult === void 0 ? void 0 : _strategy_onToolResult.call(strategy, toolResult, state));
293
+ } catch (error) {
294
+ var _strategy_onToolResult1;
295
+ this.logger.error('Tool execution failed', {
296
+ tool: toolCall.function.name,
297
+ error
298
+ });
299
+ const toolDuration = Date.now() - toolStart;
300
+ const toolResult = {
301
+ callId: toolCall.id,
302
+ toolName: toolCall.function.name,
303
+ result: null,
304
+ error: error,
305
+ duration: toolDuration
306
+ };
307
+ conversation.asTool(toolCall.id, {
308
+ error: error.message
309
+ }, {
310
+ success: false,
311
+ errorName: error.name
312
+ });
313
+ state.errors.push(error);
314
+ // Increment failure counter for circuit breaker
315
+ const failures = (state.toolFailures.get(toolCall.function.name) || 0) + 1;
316
+ state.toolFailures.set(toolCall.function.name, failures);
317
+ // Record metrics
318
+ if (this.metricsCollector) {
319
+ this.metricsCollector.recordToolCall(toolCall.function.name, state.iteration, toolDuration, false, error.message);
320
+ }
321
+ await ((_strategy_onToolResult1 = strategy.onToolResult) === null || _strategy_onToolResult1 === void 0 ? void 0 : _strategy_onToolResult1.call(strategy, toolResult, state));
322
+ }
323
+ }
324
+ } else {
325
+ // No tool calls - add response and potentially end phase
326
+ conversation.asAssistant(response.content);
327
+ // Check if this phase requires tool calls
328
+ if (phase.toolUsage === 'required' && state.toolCallsExecuted === phaseStartTools) {
329
+ this.logger.warn('No tools used but required in phase');
330
+ // Continue to try again
331
+ } else if (phase.earlyExit !== false) {
332
+ break;
333
+ }
334
+ }
335
+ // Check phase completion conditions
336
+ const toolCallsInPhase = state.toolCallsExecuted - phaseStartTools;
337
+ if (phase.minToolCalls && toolCallsInPhase < phase.minToolCalls) {
338
+ continue; // Need more tool calls
339
+ }
340
+ if (phase.maxToolCalls && toolCallsInPhase >= phase.maxToolCalls) {
341
+ break; // Hit max tool calls for phase
342
+ }
343
+ if (phase.continueIf && !phase.continueIf(state)) {
344
+ break; // Condition not met
345
+ }
346
+ }
347
+ return {
348
+ name: phase.name,
349
+ iterations: state.iteration,
350
+ toolCalls: state.toolCallsExecuted - phaseStartTools,
351
+ success: true,
352
+ insights: state.insights
353
+ };
354
+ }
355
+ constructor(llm, logger){
356
+ _define_property(this, "llm", void 0);
357
+ _define_property(this, "logger", void 0);
358
+ _define_property(this, "metricsCollector", void 0);
359
+ _define_property(this, "reflectionConfig", void 0);
360
+ this.llm = llm;
361
+ this.logger = wrapLogger(logger || DEFAULT_LOGGER, 'StrategyExecutor');
362
+ }
363
+ }
364
+ // ===== PRE-BUILT STRATEGIES =====
365
+ /**
366
+ * Factory for creating iteration strategies
367
+ */ class IterationStrategyFactory {
368
+ /**
369
+ * Investigate then respond strategy
370
+ * Phase 1: Use tools to gather information
371
+ * Phase 2: Synthesize into final answer
372
+ */ static investigateThenRespond(config = {}) {
373
+ const { maxInvestigationSteps = 5, requireMinimumTools = 1, finalSynthesis = true } = config;
374
+ return {
375
+ name: 'investigate-then-respond',
376
+ description: 'Investigate using tools, then synthesize findings',
377
+ maxIterations: maxInvestigationSteps + (finalSynthesis ? 1 : 0),
378
+ phases: [
379
+ {
380
+ name: 'investigate',
381
+ maxIterations: maxInvestigationSteps,
382
+ toolUsage: 'encouraged',
383
+ minToolCalls: requireMinimumTools,
384
+ earlyExit: false
385
+ },
386
+ ...finalSynthesis ? [
387
+ {
388
+ name: 'respond',
389
+ maxIterations: 1,
390
+ toolUsage: 'forbidden',
391
+ instructions: 'Based on your investigation, provide a comprehensive answer.',
392
+ requireFinalAnswer: true
393
+ }
394
+ ] : []
395
+ ]
396
+ };
397
+ }
398
+ /**
399
+ * Multi-pass refinement strategy
400
+ * Generate, critique, refine repeatedly
401
+ */ static multiPassRefinement(config = {}) {
402
+ const { passes = 3, critiqueBetweenPasses = true } = config;
403
+ const phases = [];
404
+ for(let i = 0; i < passes; i++){
405
+ phases.push({
406
+ name: `pass-${i + 1}`,
407
+ maxIterations: 1,
408
+ toolUsage: 'optional',
409
+ instructions: i === 0 ? 'Generate your best response' : 'Refine your previous response based on the critique'
410
+ });
411
+ if (critiqueBetweenPasses && i < passes - 1) {
412
+ phases.push({
413
+ name: `critique-${i + 1}`,
414
+ maxIterations: 1,
415
+ toolUsage: 'forbidden',
416
+ instructions: 'Critique the previous response. What can be improved?'
417
+ });
418
+ }
419
+ }
420
+ return {
421
+ name: 'multi-pass-refinement',
422
+ description: 'Iteratively refine response through multiple passes',
423
+ maxIterations: passes * 2,
424
+ phases
425
+ };
426
+ }
427
+ /**
428
+ * Breadth-first investigation
429
+ * Explore broadly before going deep
430
+ */ static breadthFirst(config = {}) {
431
+ const { levelsDeep = 3, toolsPerLevel = 4 } = config;
432
+ const phases = [];
433
+ for(let level = 0; level < levelsDeep; level++){
434
+ phases.push({
435
+ name: `level-${level + 1}`,
436
+ maxIterations: toolsPerLevel,
437
+ toolUsage: 'encouraged',
438
+ minToolCalls: 1,
439
+ maxToolCalls: toolsPerLevel,
440
+ instructions: level === 0 ? 'Get a broad overview' : `Dive deeper into areas discovered in level ${level}`
441
+ });
442
+ }
443
+ return {
444
+ name: 'breadth-first',
445
+ description: 'Explore broadly at each level before going deeper',
446
+ maxIterations: levelsDeep * toolsPerLevel,
447
+ phases
448
+ };
449
+ }
450
+ /**
451
+ * Depth-first investigation
452
+ * Deep dive immediately
453
+ */ static depthFirst(config = {}) {
454
+ const { maxDepth = 5, backtrackOnFailure = true } = config;
455
+ return {
456
+ name: 'depth-first',
457
+ description: 'Deep dive investigation path',
458
+ maxIterations: maxDepth,
459
+ phases: [
460
+ {
461
+ name: 'deep-dive',
462
+ maxIterations: maxDepth,
463
+ toolUsage: 'encouraged',
464
+ adaptiveDepth: true
465
+ }
466
+ ],
467
+ shouldContinue: (state)=>{
468
+ // Continue if making progress
469
+ if (backtrackOnFailure && state.errors.length > 2) {
470
+ return false;
471
+ }
472
+ return true;
473
+ }
474
+ };
475
+ }
476
+ /**
477
+ * Adaptive strategy
478
+ * Changes behavior based on progress
479
+ */ static adaptive(_config = {}) {
480
+ return {
481
+ name: 'adaptive',
482
+ description: 'Adapts strategy based on progress',
483
+ maxIterations: 20,
484
+ onIteration: async (iteration, state)=>{
485
+ // Change behavior based on iteration count
486
+ if (iteration < 5) {
487
+ // Early: broad exploration
488
+ return 'continue';
489
+ } else if (iteration < 15) {
490
+ // Mid: focused investigation
491
+ return 'continue';
492
+ } else {
493
+ // Late: wrap up
494
+ return state.toolCallsExecuted > 0 ? 'continue' : 'stop';
495
+ }
496
+ }
497
+ };
498
+ }
499
+ /**
500
+ * Simple iteration (basic tool-use loop)
501
+ */ static simple(config = {}) {
502
+ const { maxIterations = 10, allowTools = true } = config;
503
+ return {
504
+ name: 'simple',
505
+ description: 'Simple iteration loop',
506
+ maxIterations,
507
+ phases: [
508
+ {
509
+ name: 'main',
510
+ maxIterations,
511
+ toolUsage: allowTools ? 'encouraged' : 'forbidden',
512
+ earlyExit: true
513
+ }
514
+ ]
515
+ };
516
+ }
517
+ }
518
+
519
+ export { IterationStrategyFactory, StrategyExecutor, IterationStrategyFactory as default };
520
+ //# sourceMappingURL=iteration-strategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iteration-strategy.js","sources":["../src/iteration-strategy.ts"],"sourcesContent":["import { ConversationBuilder, type ConversationMessage, type ToolCall } from \"./conversation\";\nimport { ToolRegistry, type Tool } from \"./tools\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { MetricsCollector, ReflectionReportGenerator, type ReflectionReport, type ReflectionConfig } from \"./reflection\";\n\n// ===== TYPE DEFINITIONS =====\n\n/**\n * Tool usage policy for a phase\n */\nexport type ToolUsagePolicy = 'required' | 'encouraged' | 'optional' | 'forbidden';\n\n/**\n * LLM client interface (generic, provider-agnostic)\n */\nexport interface LLMClient {\n complete(messages: ConversationMessage[], tools?: any[]): Promise<{\n content: string | null;\n tool_calls?: ToolCall[];\n }>;\n}\n\n/**\n * Context provided to strategy execution\n */\nexport interface StrategyContext {\n conversation: ConversationBuilder;\n tools: ToolRegistry;\n llm: LLMClient;\n state: StrategyState;\n}\n\n/**\n * Current state of strategy execution\n */\nexport interface StrategyState {\n phase: string | number;\n iteration: number;\n toolCallsExecuted: number;\n startTime: number;\n insights: Insight[];\n findings: any[];\n errors: Error[];\n toolFailures: Map<string, number>; // Track consecutive failures per tool\n [key: string]: any;\n}\n\n/**\n * Insight discovered during execution\n */\nexport interface Insight {\n source: string;\n content: string;\n confidence: number;\n relatedTo?: string[];\n}\n\n/**\n * Result of tool execution\n */\nexport interface ToolResult {\n callId: string;\n toolName: string;\n result: any;\n error?: Error;\n duration: number;\n}\n\n/**\n * Action to take after iteration\n */\nexport type IterationAction = 'continue' | 'stop' | 'next-phase';\n\n/**\n * Action to take for tool call\n */\nexport type ToolCallAction = 'execute' | 'skip' | 'defer';\n\n/**\n * Result of a phase\n */\nexport interface PhaseResult {\n name: string;\n iterations: number;\n toolCalls: number;\n success: boolean;\n insights?: Insight[];\n}\n\n/**\n * Final strategy result\n */\nexport interface StrategyResult {\n finalMessage: ConversationMessage | undefined;\n phases: PhaseResult[];\n totalIterations: number;\n toolCallsExecuted: number;\n duration: number;\n success: boolean;\n conversation: ConversationBuilder;\n reflection?: ReflectionReport;\n}\n\n/**\n * Configuration for a strategy phase\n */\nexport interface StrategyPhase {\n name: string;\n maxIterations: number;\n toolUsage: ToolUsagePolicy;\n allowedTools?: string[];\n minToolCalls?: number;\n maxToolCalls?: number;\n instructions?: string;\n earlyExit?: boolean;\n requireFinalAnswer?: boolean;\n adaptiveDepth?: boolean;\n maxConsecutiveToolFailures?: number; // Circuit breaker threshold (default: 3)\n continueIf?: (state: StrategyState) => boolean;\n skipIf?: (state: StrategyState) => boolean;\n}\n\n/**\n * Iteration strategy interface\n */\nexport interface IterationStrategy {\n name: string;\n description: string;\n maxIterations: number;\n maxToolCalls?: number;\n timeoutMs?: number;\n phases?: StrategyPhase[];\n\n // Lifecycle hooks\n onStart?: (context: StrategyContext) => Promise<void>;\n onIteration?: (iteration: number, state: StrategyState) => Promise<IterationAction>;\n onToolCall?: (toolCall: ToolCall, state: StrategyState) => Promise<ToolCallAction>;\n onToolResult?: (result: ToolResult, state: StrategyState) => Promise<void>;\n onPhaseComplete?: (phase: PhaseResult, state: StrategyState) => Promise<void>;\n onComplete?: (result: StrategyResult) => Promise<void>;\n\n // Decision logic\n shouldContinue?: (state: StrategyState) => boolean;\n shouldCallTool?: (tool: Tool, state: StrategyState) => boolean;\n selectTools?: (available: Tool[], state: StrategyState) => Tool[];\n}\n\n// ===== STRATEGY EXECUTOR =====\n\n/**\n * StrategyExecutor executes iteration strategies.\n *\n * Features:\n * - Execute multi-phase strategies\n * - Manage tool calls and results\n * - Track state and metrics\n * - Handle timeouts and errors\n * - Provide lifecycle hooks\n *\n * @example\n * ```typescript\n * const executor = new StrategyExecutor(llmClient);\n *\n * const result = await executor.execute(\n * conversation,\n * toolRegistry,\n * strategy\n * );\n *\n * console.log('Completed in', result.totalIterations, 'iterations');\n * console.log('Used', result.toolCallsExecuted, 'tools');\n * ```\n */\nexport class StrategyExecutor {\n private llm: LLMClient;\n private logger: any;\n private metricsCollector?: MetricsCollector;\n private reflectionConfig?: ReflectionConfig;\n\n constructor(llm: LLMClient, logger?: any) {\n this.llm = llm;\n this.logger = wrapLogger(logger || DEFAULT_LOGGER, 'StrategyExecutor');\n }\n\n /**\n * Enable reflection generation\n */\n withReflection(config: ReflectionConfig): this {\n this.reflectionConfig = config;\n return this;\n }\n\n /**\n * Execute a strategy\n */\n async execute(\n conversation: ConversationBuilder,\n tools: ToolRegistry,\n strategy: IterationStrategy\n ): Promise<StrategyResult> {\n const startTime = Date.now();\n\n // Initialize metrics collector if reflection enabled\n if (this.reflectionConfig?.enabled) {\n this.metricsCollector = new MetricsCollector(this.logger);\n }\n\n const state: StrategyState = {\n phase: 0,\n iteration: 0,\n toolCallsExecuted: 0,\n startTime,\n insights: [],\n findings: [],\n errors: [],\n toolFailures: new Map<string, number>(),\n };\n\n this.logger.info('Starting strategy execution', { strategy: strategy.name });\n\n const context: StrategyContext = { conversation, tools, llm: this.llm, state };\n\n try {\n // Initialize\n await strategy.onStart?.(context);\n\n // Execute phases or single loop\n const phases = strategy.phases || [\n {\n name: 'default',\n maxIterations: strategy.maxIterations,\n toolUsage: 'encouraged' as ToolUsagePolicy,\n }\n ];\n\n const phaseResults: PhaseResult[] = [];\n\n for (const phase of phases) {\n // Check if should skip phase\n if (phase.skipIf?.(state)) {\n this.logger.debug('Skipping phase', { phase: phase.name });\n continue;\n }\n\n state.phase = phase.name;\n state.iteration = 0;\n\n this.logger.debug('Starting phase', { phase: phase.name });\n\n const phaseResult = await this.executePhase(\n conversation,\n tools,\n phase,\n state,\n strategy\n );\n\n phaseResults.push(phaseResult);\n\n await strategy.onPhaseComplete?.(phaseResult, state);\n\n // Check if should continue\n if (strategy.shouldContinue && !strategy.shouldContinue(state)) {\n this.logger.debug('Strategy decided to stop');\n break;\n }\n }\n\n const duration = Date.now() - startTime;\n\n const result: StrategyResult = {\n finalMessage: conversation.getLastMessage(),\n phases: phaseResults,\n totalIterations: state.iteration,\n toolCallsExecuted: state.toolCallsExecuted,\n duration,\n success: true,\n conversation,\n };\n\n // Generate reflection if enabled\n if (this.metricsCollector && this.reflectionConfig?.enabled) {\n const metrics = this.metricsCollector.getMetrics(\n conversation.getMessages(),\n conversation.getMetadata().model\n );\n\n const generator = new ReflectionReportGenerator(this.logger);\n result.reflection = generator.generate(metrics, result);\n\n // Save reflection if output path specified\n if (this.reflectionConfig.outputPath && result.reflection) {\n await this.saveReflection(result.reflection, this.reflectionConfig);\n }\n }\n\n await strategy.onComplete?.(result);\n\n this.logger.info('Strategy execution complete', {\n iterations: result.totalIterations,\n toolCalls: result.toolCallsExecuted,\n duration\n });\n\n return result;\n\n } catch (error) {\n this.logger.error('Strategy execution failed', { error });\n\n return {\n finalMessage: conversation.getLastMessage(),\n phases: [],\n totalIterations: state.iteration,\n toolCallsExecuted: state.toolCallsExecuted,\n duration: Date.now() - startTime,\n success: false,\n conversation,\n };\n }\n }\n\n /**\n * Save reflection report\n */\n private async saveReflection(\n reflection: ReflectionReport,\n config: ReflectionConfig\n ): Promise<void> {\n if (!config.outputPath) {\n return;\n }\n\n try {\n const fs = await import('fs/promises');\n const path = await import('path');\n\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const filename = `reflection-${timestamp}.${config.format === 'json' ? 'json' : 'md'}`;\n const fullPath = path.join(config.outputPath, filename);\n\n // Ensure directory exists\n await fs.mkdir(config.outputPath, { recursive: true });\n\n // Save based on format\n if (config.format === 'json') {\n await fs.writeFile(fullPath, JSON.stringify(reflection, null, 2), 'utf-8');\n } else {\n const generator = new ReflectionReportGenerator(this.logger);\n const markdown = generator.formatMarkdown(reflection);\n await fs.writeFile(fullPath, markdown, 'utf-8');\n }\n\n this.logger.info('Reflection saved', { path: fullPath });\n } catch (error) {\n this.logger.error('Failed to save reflection', { error });\n }\n }\n\n /**\n * Execute a single phase\n */\n private async executePhase(\n conversation: ConversationBuilder,\n tools: ToolRegistry,\n phase: StrategyPhase,\n state: StrategyState,\n strategy: IterationStrategy\n ): Promise<PhaseResult> {\n const phaseStartTools = state.toolCallsExecuted;\n\n // Add phase instructions if provided\n if (phase.instructions) {\n conversation.asUser(phase.instructions);\n }\n\n // Iteration loop for this phase\n for (let i = 0; i < phase.maxIterations; i++) {\n state.iteration++;\n\n // Track iteration for metrics\n if (this.metricsCollector) {\n this.metricsCollector.incrementIteration();\n }\n\n this.logger.debug('Iteration', { phase: phase.name, iteration: i + 1 });\n\n // Check iteration hook\n const action = await strategy.onIteration?.(i, state);\n if (action === 'stop') {\n break;\n }\n if (action === 'next-phase') {\n break;\n }\n\n // Get LLM response\n const toolsToProvide = phase.toolUsage !== 'forbidden' ? tools.toOpenAIFormat() : undefined;\n const response = await this.llm.complete(\n conversation.toMessages(),\n toolsToProvide\n );\n\n // Handle tool calls\n if (response.tool_calls && response.tool_calls.length > 0) {\n if (phase.toolUsage === 'forbidden') {\n this.logger.warn('Tool calls requested but forbidden in this phase');\n conversation.asAssistant(response.content);\n continue;\n }\n\n conversation.asAssistant(response.content, response.tool_calls);\n\n // Execute tools\n for (const toolCall of response.tool_calls) {\n // Check if tool is allowed in this phase\n if (phase.allowedTools && !phase.allowedTools.includes(toolCall.function.name)) {\n this.logger.debug('Tool not allowed in phase', { tool: toolCall.function.name });\n continue;\n }\n\n // Circuit breaker: Check if tool has exceeded failure threshold\n const maxFailures = phase.maxConsecutiveToolFailures ?? 3;\n const consecutiveFailures = state.toolFailures.get(toolCall.function.name) || 0;\n if (consecutiveFailures >= maxFailures) {\n this.logger.warn('Tool circuit breaker triggered', {\n tool: toolCall.function.name,\n failures: consecutiveFailures\n });\n conversation.asTool(toolCall.id, {\n error: `Tool temporarily disabled due to ${consecutiveFailures} consecutive failures`\n }, {\n success: false,\n circuitBreakerTriggered: true\n });\n continue;\n }\n\n // Check tool call hook\n const toolAction = await strategy.onToolCall?.(toolCall, state);\n if (toolAction === 'skip') {\n continue;\n }\n\n // Execute tool\n const toolStart = Date.now();\n try {\n // Parse tool arguments with error handling\n let toolArgs: any;\n try {\n toolArgs = JSON.parse(toolCall.function.arguments);\n } catch (parseError) {\n const error = new Error(\n `Invalid JSON in tool arguments for ${toolCall.function.name}: ${\n parseError instanceof Error ? parseError.message : String(parseError)\n }`\n );\n if (parseError instanceof Error) {\n (error as any).cause = parseError; // Preserve original error\n }\n throw error;\n }\n\n const result = await tools.execute(\n toolCall.function.name,\n toolArgs\n );\n\n const toolDuration = Date.now() - toolStart;\n\n const toolResult: ToolResult = {\n callId: toolCall.id,\n toolName: toolCall.function.name,\n result,\n duration: toolDuration,\n };\n\n conversation.asTool(toolCall.id, result, {\n duration: toolDuration,\n success: true\n });\n\n state.toolCallsExecuted++;\n\n // Reset failure counter on success\n state.toolFailures.set(toolCall.function.name, 0);\n\n // Record metrics\n if (this.metricsCollector) {\n this.metricsCollector.recordToolCall(\n toolCall.function.name,\n state.iteration,\n toolDuration,\n true\n );\n }\n\n await strategy.onToolResult?.(toolResult, state);\n\n } catch (error) {\n this.logger.error('Tool execution failed', { tool: toolCall.function.name, error });\n\n const toolDuration = Date.now() - toolStart;\n\n const toolResult: ToolResult = {\n callId: toolCall.id,\n toolName: toolCall.function.name,\n result: null,\n error: error as Error,\n duration: toolDuration,\n };\n\n conversation.asTool(toolCall.id, {\n error: (error as Error).message\n }, {\n success: false,\n errorName: (error as Error).name\n });\n\n state.errors.push(error as Error);\n\n // Increment failure counter for circuit breaker\n const failures = (state.toolFailures.get(toolCall.function.name) || 0) + 1;\n state.toolFailures.set(toolCall.function.name, failures);\n\n // Record metrics\n if (this.metricsCollector) {\n this.metricsCollector.recordToolCall(\n toolCall.function.name,\n state.iteration,\n toolDuration,\n false,\n (error as Error).message\n );\n }\n\n await strategy.onToolResult?.(toolResult, state);\n }\n }\n\n } else {\n // No tool calls - add response and potentially end phase\n conversation.asAssistant(response.content);\n\n // Check if this phase requires tool calls\n if (phase.toolUsage === 'required' && state.toolCallsExecuted === phaseStartTools) {\n this.logger.warn('No tools used but required in phase');\n // Continue to try again\n } else if (phase.earlyExit !== false) {\n // Exit phase early if we got a response without tools\n break;\n }\n }\n\n // Check phase completion conditions\n const toolCallsInPhase = state.toolCallsExecuted - phaseStartTools;\n\n if (phase.minToolCalls && toolCallsInPhase < phase.minToolCalls) {\n continue; // Need more tool calls\n }\n\n if (phase.maxToolCalls && toolCallsInPhase >= phase.maxToolCalls) {\n break; // Hit max tool calls for phase\n }\n\n if (phase.continueIf && !phase.continueIf(state)) {\n break; // Condition not met\n }\n }\n\n return {\n name: phase.name,\n iterations: state.iteration,\n toolCalls: state.toolCallsExecuted - phaseStartTools,\n success: true,\n insights: state.insights,\n };\n }\n}\n\n// ===== PRE-BUILT STRATEGIES =====\n\n/**\n * Factory for creating iteration strategies\n */\nexport class IterationStrategyFactory {\n /**\n * Investigate then respond strategy\n * Phase 1: Use tools to gather information\n * Phase 2: Synthesize into final answer\n */\n static investigateThenRespond(config: {\n maxInvestigationSteps?: number;\n requireMinimumTools?: number;\n finalSynthesis?: boolean;\n } = {}): IterationStrategy {\n const {\n maxInvestigationSteps = 5,\n requireMinimumTools = 1,\n finalSynthesis = true,\n } = config;\n\n return {\n name: 'investigate-then-respond',\n description: 'Investigate using tools, then synthesize findings',\n maxIterations: maxInvestigationSteps + (finalSynthesis ? 1 : 0),\n phases: [\n {\n name: 'investigate',\n maxIterations: maxInvestigationSteps,\n toolUsage: 'encouraged',\n minToolCalls: requireMinimumTools,\n earlyExit: false,\n },\n ...(finalSynthesis ? [{\n name: 'respond',\n maxIterations: 1,\n toolUsage: 'forbidden' as ToolUsagePolicy,\n instructions: 'Based on your investigation, provide a comprehensive answer.',\n requireFinalAnswer: true,\n }] : []),\n ],\n };\n }\n\n /**\n * Multi-pass refinement strategy\n * Generate, critique, refine repeatedly\n */\n static multiPassRefinement(config: {\n passes?: number;\n critiqueBetweenPasses?: boolean;\n improvementThreshold?: number;\n } = {}): IterationStrategy {\n const {\n passes = 3,\n critiqueBetweenPasses = true,\n } = config;\n\n const phases: StrategyPhase[] = [];\n\n for (let i = 0; i < passes; i++) {\n phases.push({\n name: `pass-${i + 1}`,\n maxIterations: 1,\n toolUsage: 'optional',\n instructions: i === 0\n ? 'Generate your best response'\n : 'Refine your previous response based on the critique',\n });\n\n if (critiqueBetweenPasses && i < passes - 1) {\n phases.push({\n name: `critique-${i + 1}`,\n maxIterations: 1,\n toolUsage: 'forbidden',\n instructions: 'Critique the previous response. What can be improved?',\n });\n }\n }\n\n return {\n name: 'multi-pass-refinement',\n description: 'Iteratively refine response through multiple passes',\n maxIterations: passes * 2,\n phases,\n };\n }\n\n /**\n * Breadth-first investigation\n * Explore broadly before going deep\n */\n static breadthFirst(config: {\n levelsDeep?: number;\n toolsPerLevel?: number;\n } = {}): IterationStrategy {\n const {\n levelsDeep = 3,\n toolsPerLevel = 4,\n } = config;\n\n const phases: StrategyPhase[] = [];\n\n for (let level = 0; level < levelsDeep; level++) {\n phases.push({\n name: `level-${level + 1}`,\n maxIterations: toolsPerLevel,\n toolUsage: 'encouraged',\n minToolCalls: 1,\n maxToolCalls: toolsPerLevel,\n instructions: level === 0\n ? 'Get a broad overview'\n : `Dive deeper into areas discovered in level ${level}`,\n });\n }\n\n return {\n name: 'breadth-first',\n description: 'Explore broadly at each level before going deeper',\n maxIterations: levelsDeep * toolsPerLevel,\n phases,\n };\n }\n\n /**\n * Depth-first investigation\n * Deep dive immediately\n */\n static depthFirst(config: {\n maxDepth?: number;\n backtrackOnFailure?: boolean;\n } = {}): IterationStrategy {\n const {\n maxDepth = 5,\n backtrackOnFailure = true,\n } = config;\n\n return {\n name: 'depth-first',\n description: 'Deep dive investigation path',\n maxIterations: maxDepth,\n phases: [{\n name: 'deep-dive',\n maxIterations: maxDepth,\n toolUsage: 'encouraged',\n adaptiveDepth: true,\n }],\n shouldContinue: (state) => {\n // Continue if making progress\n if (backtrackOnFailure && state.errors.length > 2) {\n return false;\n }\n return true;\n },\n };\n }\n\n /**\n * Adaptive strategy\n * Changes behavior based on progress\n */\n static adaptive(_config: {\n strategies?: IterationStrategy[];\n switchConditions?: Array<{\n when: (state: StrategyState) => boolean;\n switchTo: number;\n }>;\n } = {}): IterationStrategy {\n return {\n name: 'adaptive',\n description: 'Adapts strategy based on progress',\n maxIterations: 20,\n onIteration: async (iteration, state) => {\n // Change behavior based on iteration count\n if (iteration < 5) {\n // Early: broad exploration\n return 'continue';\n } else if (iteration < 15) {\n // Mid: focused investigation\n return 'continue';\n } else {\n // Late: wrap up\n return state.toolCallsExecuted > 0 ? 'continue' : 'stop';\n }\n },\n };\n }\n\n /**\n * Simple iteration (basic tool-use loop)\n */\n static simple(config: {\n maxIterations?: number;\n allowTools?: boolean;\n } = {}): IterationStrategy {\n const {\n maxIterations = 10,\n allowTools = true,\n } = config;\n\n return {\n name: 'simple',\n description: 'Simple iteration loop',\n maxIterations,\n phases: [{\n name: 'main',\n maxIterations,\n toolUsage: allowTools ? 'encouraged' : 'forbidden',\n earlyExit: true,\n }],\n };\n }\n}\n\nexport default IterationStrategyFactory;\n\n"],"names":["StrategyExecutor","withReflection","config","reflectionConfig","execute","conversation","tools","strategy","startTime","Date","now","enabled","metricsCollector","MetricsCollector","logger","state","phase","iteration","toolCallsExecuted","insights","findings","errors","toolFailures","Map","info","name","context","llm","onStart","phases","maxIterations","toolUsage","phaseResults","skipIf","debug","phaseResult","executePhase","push","onPhaseComplete","shouldContinue","duration","result","finalMessage","getLastMessage","totalIterations","success","metrics","getMetrics","getMessages","getMetadata","model","generator","ReflectionReportGenerator","reflection","generate","outputPath","saveReflection","onComplete","iterations","toolCalls","error","fs","path","timestamp","toISOString","replace","filename","format","fullPath","join","mkdir","recursive","writeFile","JSON","stringify","markdown","formatMarkdown","phaseStartTools","instructions","asUser","i","incrementIteration","action","onIteration","toolsToProvide","toOpenAIFormat","undefined","response","complete","toMessages","tool_calls","length","warn","asAssistant","content","toolCall","allowedTools","includes","function","tool","maxFailures","maxConsecutiveToolFailures","consecutiveFailures","get","failures","asTool","id","circuitBreakerTriggered","toolAction","onToolCall","toolStart","toolArgs","parse","arguments","parseError","Error","message","String","cause","toolDuration","toolResult","callId","toolName","set","recordToolCall","onToolResult","errorName","earlyExit","toolCallsInPhase","minToolCalls","maxToolCalls","continueIf","wrapLogger","DEFAULT_LOGGER","IterationStrategyFactory","investigateThenRespond","maxInvestigationSteps","requireMinimumTools","finalSynthesis","description","requireFinalAnswer","multiPassRefinement","passes","critiqueBetweenPasses","breadthFirst","levelsDeep","toolsPerLevel","level","depthFirst","maxDepth","backtrackOnFailure","adaptiveDepth","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