@x12i/ai-gateway 7.9.1

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 (179) hide show
  1. package/README.md +4259 -0
  2. package/config.defaults.json +31 -0
  3. package/dist/activity-manager.d.ts +206 -0
  4. package/dist/activity-manager.js +1051 -0
  5. package/dist/config/activity-tracking-config.d.ts +11 -0
  6. package/dist/config/activity-tracking-config.js +15 -0
  7. package/dist/config.defaults.json +31 -0
  8. package/dist/content-normalizer/content-normalizer.d.ts +46 -0
  9. package/dist/content-normalizer/content-normalizer.js +393 -0
  10. package/dist/content-normalizer/index.d.ts +7 -0
  11. package/dist/content-normalizer/index.js +6 -0
  12. package/dist/content-normalizer/types.d.ts +33 -0
  13. package/dist/content-normalizer/types.js +4 -0
  14. package/dist/defaults/instructions-blocks.json +61 -0
  15. package/dist/defaults/model-config.json +16 -0
  16. package/dist/defaults/template-rendering.json +6 -0
  17. package/dist/flex-md-loader.d.ts +109 -0
  18. package/dist/flex-md-loader.js +940 -0
  19. package/dist/gateway-config.d.ts +49 -0
  20. package/dist/gateway-config.js +292 -0
  21. package/dist/gateway-conversion.d.ts +29 -0
  22. package/dist/gateway-conversion.js +174 -0
  23. package/dist/gateway-instructions.d.ts +30 -0
  24. package/dist/gateway-instructions.js +62 -0
  25. package/dist/gateway-memory.d.ts +51 -0
  26. package/dist/gateway-memory.js +207 -0
  27. package/dist/gateway-messages.d.ts +23 -0
  28. package/dist/gateway-messages.js +83 -0
  29. package/dist/gateway-meta.d.ts +25 -0
  30. package/dist/gateway-meta.js +87 -0
  31. package/dist/gateway-provider-auto-register.d.ts +17 -0
  32. package/dist/gateway-provider-auto-register.js +159 -0
  33. package/dist/gateway-provider.d.ts +54 -0
  34. package/dist/gateway-provider.js +202 -0
  35. package/dist/gateway-rate-limiter-constants.d.ts +16 -0
  36. package/dist/gateway-rate-limiter-constants.js +16 -0
  37. package/dist/gateway-rate-limiter.d.ts +56 -0
  38. package/dist/gateway-rate-limiter.js +107 -0
  39. package/dist/gateway-retry.d.ts +49 -0
  40. package/dist/gateway-retry.js +204 -0
  41. package/dist/gateway-utils.d.ts +21 -0
  42. package/dist/gateway-utils.js +181 -0
  43. package/dist/gateway-validation.d.ts +13 -0
  44. package/dist/gateway-validation.js +50 -0
  45. package/dist/gateway.d.ts +39 -0
  46. package/dist/gateway.js +430 -0
  47. package/dist/index.d.ts +36 -0
  48. package/dist/index.js +55 -0
  49. package/dist/instruction-errors.d.ts +16 -0
  50. package/dist/instruction-errors.js +29 -0
  51. package/dist/instruction-optimizer.d.ts +113 -0
  52. package/dist/instruction-optimizer.js +293 -0
  53. package/dist/instructions-parser.d.ts +31 -0
  54. package/dist/instructions-parser.js +56 -0
  55. package/dist/logger-factory.d.ts +17 -0
  56. package/dist/logger-factory.js +42 -0
  57. package/dist/message-builder.d.ts +41 -0
  58. package/dist/message-builder.js +522 -0
  59. package/dist/object-types-library-integration.d.ts +22 -0
  60. package/dist/object-types-library-integration.js +27 -0
  61. package/dist/object-types-library.d.ts +351 -0
  62. package/dist/object-types-library.js +210 -0
  63. package/dist/output-auditor.d.ts +44 -0
  64. package/dist/output-auditor.js +49 -0
  65. package/dist/request-report-generator.d.ts +60 -0
  66. package/dist/request-report-generator.js +169 -0
  67. package/dist/response-analyzer/format-type-detector.d.ts +35 -0
  68. package/dist/response-analyzer/format-type-detector.js +115 -0
  69. package/dist/response-analyzer/index.d.ts +9 -0
  70. package/dist/response-analyzer/index.js +8 -0
  71. package/dist/response-analyzer/object-type-detector.d.ts +42 -0
  72. package/dist/response-analyzer/object-type-detector.js +95 -0
  73. package/dist/response-analyzer/response-analyzer.d.ts +38 -0
  74. package/dist/response-analyzer/response-analyzer.js +97 -0
  75. package/dist/response-analyzer/types.d.ts +97 -0
  76. package/dist/response-analyzer/types.js +4 -0
  77. package/dist/response-fallback-fixer.d.ts +11 -0
  78. package/dist/response-fallback-fixer.js +123 -0
  79. package/dist/runtime-objects.d.ts +52 -0
  80. package/dist/runtime-objects.js +46 -0
  81. package/dist/template-parser.d.ts +58 -0
  82. package/dist/template-parser.js +99 -0
  83. package/dist/template-render-merge.d.ts +9 -0
  84. package/dist/template-render-merge.js +40 -0
  85. package/dist/troubleshooting-helper.d.ts +123 -0
  86. package/dist/troubleshooting-helper.js +596 -0
  87. package/dist/types.d.ts +1173 -0
  88. package/dist/types.js +6 -0
  89. package/dist/usage-tracker.d.ts +78 -0
  90. package/dist/usage-tracker.js +79 -0
  91. package/dist-cjs/activity-manager.cjs +1056 -0
  92. package/dist-cjs/activity-manager.d.ts +206 -0
  93. package/dist-cjs/config/activity-tracking-config.cjs +18 -0
  94. package/dist-cjs/config/activity-tracking-config.d.ts +11 -0
  95. package/dist-cjs/config.defaults.json +31 -0
  96. package/dist-cjs/content-normalizer/content-normalizer.cjs +398 -0
  97. package/dist-cjs/content-normalizer/content-normalizer.d.ts +46 -0
  98. package/dist-cjs/content-normalizer/index.cjs +12 -0
  99. package/dist-cjs/content-normalizer/index.d.ts +7 -0
  100. package/dist-cjs/content-normalizer/types.cjs +5 -0
  101. package/dist-cjs/content-normalizer/types.d.ts +33 -0
  102. package/dist-cjs/defaults/instructions-blocks.json +61 -0
  103. package/dist-cjs/defaults/model-config.json +16 -0
  104. package/dist-cjs/defaults/template-rendering.json +6 -0
  105. package/dist-cjs/flex-md-loader.cjs +986 -0
  106. package/dist-cjs/flex-md-loader.d.ts +109 -0
  107. package/dist-cjs/gateway-config.cjs +331 -0
  108. package/dist-cjs/gateway-config.d.ts +49 -0
  109. package/dist-cjs/gateway-conversion.cjs +212 -0
  110. package/dist-cjs/gateway-conversion.d.ts +29 -0
  111. package/dist-cjs/gateway-instructions.cjs +67 -0
  112. package/dist-cjs/gateway-instructions.d.ts +30 -0
  113. package/dist-cjs/gateway-memory.cjs +211 -0
  114. package/dist-cjs/gateway-memory.d.ts +51 -0
  115. package/dist-cjs/gateway-messages.cjs +86 -0
  116. package/dist-cjs/gateway-messages.d.ts +23 -0
  117. package/dist-cjs/gateway-meta.cjs +90 -0
  118. package/dist-cjs/gateway-meta.d.ts +25 -0
  119. package/dist-cjs/gateway-provider-auto-register.cjs +195 -0
  120. package/dist-cjs/gateway-provider-auto-register.d.ts +17 -0
  121. package/dist-cjs/gateway-provider.cjs +214 -0
  122. package/dist-cjs/gateway-provider.d.ts +54 -0
  123. package/dist-cjs/gateway-rate-limiter-constants.cjs +19 -0
  124. package/dist-cjs/gateway-rate-limiter-constants.d.ts +16 -0
  125. package/dist-cjs/gateway-rate-limiter.cjs +111 -0
  126. package/dist-cjs/gateway-rate-limiter.d.ts +56 -0
  127. package/dist-cjs/gateway-retry.cjs +212 -0
  128. package/dist-cjs/gateway-retry.d.ts +49 -0
  129. package/dist-cjs/gateway-utils.cjs +219 -0
  130. package/dist-cjs/gateway-utils.d.ts +21 -0
  131. package/dist-cjs/gateway-validation.cjs +54 -0
  132. package/dist-cjs/gateway-validation.d.ts +13 -0
  133. package/dist-cjs/gateway.cjs +434 -0
  134. package/dist-cjs/gateway.d.ts +39 -0
  135. package/dist-cjs/index.cjs +108 -0
  136. package/dist-cjs/index.d.ts +36 -0
  137. package/dist-cjs/instruction-errors.cjs +34 -0
  138. package/dist-cjs/instruction-errors.d.ts +16 -0
  139. package/dist-cjs/instruction-optimizer.cjs +299 -0
  140. package/dist-cjs/instruction-optimizer.d.ts +113 -0
  141. package/dist-cjs/instructions-parser.cjs +61 -0
  142. package/dist-cjs/instructions-parser.d.ts +31 -0
  143. package/dist-cjs/logger-factory.cjs +45 -0
  144. package/dist-cjs/logger-factory.d.ts +17 -0
  145. package/dist-cjs/message-builder.cjs +558 -0
  146. package/dist-cjs/message-builder.d.ts +41 -0
  147. package/dist-cjs/object-types-library-integration.cjs +32 -0
  148. package/dist-cjs/object-types-library-integration.d.ts +22 -0
  149. package/dist-cjs/object-types-library.cjs +215 -0
  150. package/dist-cjs/object-types-library.d.ts +351 -0
  151. package/dist-cjs/output-auditor.cjs +52 -0
  152. package/dist-cjs/output-auditor.d.ts +44 -0
  153. package/dist-cjs/request-report-generator.cjs +172 -0
  154. package/dist-cjs/request-report-generator.d.ts +60 -0
  155. package/dist-cjs/response-analyzer/format-type-detector.cjs +119 -0
  156. package/dist-cjs/response-analyzer/format-type-detector.d.ts +35 -0
  157. package/dist-cjs/response-analyzer/index.cjs +14 -0
  158. package/dist-cjs/response-analyzer/index.d.ts +9 -0
  159. package/dist-cjs/response-analyzer/object-type-detector.cjs +99 -0
  160. package/dist-cjs/response-analyzer/object-type-detector.d.ts +42 -0
  161. package/dist-cjs/response-analyzer/response-analyzer.cjs +101 -0
  162. package/dist-cjs/response-analyzer/response-analyzer.d.ts +38 -0
  163. package/dist-cjs/response-analyzer/types.cjs +5 -0
  164. package/dist-cjs/response-analyzer/types.d.ts +97 -0
  165. package/dist-cjs/response-fallback-fixer.cjs +126 -0
  166. package/dist-cjs/response-fallback-fixer.d.ts +11 -0
  167. package/dist-cjs/runtime-objects.cjs +52 -0
  168. package/dist-cjs/runtime-objects.d.ts +52 -0
  169. package/dist-cjs/template-parser.cjs +136 -0
  170. package/dist-cjs/template-parser.d.ts +58 -0
  171. package/dist-cjs/template-render-merge.cjs +43 -0
  172. package/dist-cjs/template-render-merge.d.ts +9 -0
  173. package/dist-cjs/troubleshooting-helper.cjs +611 -0
  174. package/dist-cjs/troubleshooting-helper.d.ts +123 -0
  175. package/dist-cjs/types.cjs +7 -0
  176. package/dist-cjs/types.d.ts +1173 -0
  177. package/dist-cjs/usage-tracker.cjs +83 -0
  178. package/dist-cjs/usage-tracker.d.ts +78 -0
  179. package/package.json +91 -0
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Instruction Optimizer Feature
3
+ *
4
+ * Uses AI to analyze and fix poorly-written instructions.
5
+ * This is a meta-feature that uses the AI Gateway (via router) to improve AI instructions.
6
+ */
7
+ import type { AIGateway } from './gateway.js';
8
+ /**
9
+ * Result from instruction optimization
10
+ */
11
+ export interface InstructionOptimizationResult {
12
+ analysis: {
13
+ problems_found: string[];
14
+ missing_elements: string[];
15
+ clarity_score: number;
16
+ };
17
+ fixed_instructions: {
18
+ complete_text: string;
19
+ breakdown: {
20
+ core_task: string;
21
+ task_description: string;
22
+ output_requirements: string;
23
+ constraints: string[];
24
+ schemas: Array<{
25
+ type: string;
26
+ schema: Record<string, unknown>;
27
+ when_to_use: string;
28
+ }>;
29
+ tokens_preserved: string[];
30
+ };
31
+ };
32
+ changes_made: Array<{
33
+ change_type: string;
34
+ original: string;
35
+ fixed: string;
36
+ reason: string;
37
+ }>;
38
+ quality_improvements: {
39
+ before_score: number;
40
+ after_score: number;
41
+ summary: string;
42
+ };
43
+ }
44
+ /**
45
+ * Options for instruction optimization
46
+ */
47
+ export interface OptimizeInstructionsOptions {
48
+ /**
49
+ * Agent ID for the optimization request
50
+ */
51
+ agentId?: string;
52
+ /**
53
+ * Target use case (helps optimizer know what to prioritize)
54
+ */
55
+ targetUseCase?: 'json-extraction' | 'chat' | 'reasoning' | 'general';
56
+ /**
57
+ * Whether to enforce JSON output in fixed instructions
58
+ */
59
+ enforceJsonOutput?: boolean;
60
+ /**
61
+ * Model to use for optimization (default: gpt-4o)
62
+ */
63
+ model?: string;
64
+ /**
65
+ * Provider to use (default: openai)
66
+ */
67
+ provider?: string;
68
+ /**
69
+ * Whether to include detailed explanations
70
+ */
71
+ includeDetailedExplanations?: boolean;
72
+ }
73
+ /**
74
+ * Optimizes AI instructions by analyzing and fixing common issues
75
+ *
76
+ * This is a meta-feature that uses AI (via the gateway router) to improve AI instructions.
77
+ * It takes poorly-written instructions and returns:
78
+ * 1. Analysis of problems
79
+ * 2. Fixed, production-ready instructions
80
+ * 3. Detailed breakdown of components
81
+ * 4. List of changes made and why
82
+ *
83
+ * @param gateway - AI Gateway instance (uses router, not direct provider calls)
84
+ * @param originalInstructions - The instructions to optimize
85
+ * @param options - Optimization options
86
+ * @returns Optimization result with fixed instructions and analysis
87
+ */
88
+ export declare function optimizeInstructions(gateway: AIGateway, originalInstructions: string, options?: OptimizeInstructionsOptions): Promise<InstructionOptimizationResult>;
89
+ /**
90
+ * Utility: Extract only the fixed instructions text
91
+ *
92
+ * @param result - Optimization result
93
+ * @returns Just the complete fixed instructions text
94
+ */
95
+ export declare function getFixedInstructions(result: InstructionOptimizationResult): string;
96
+ /**
97
+ * Utility: Get a summary of changes made
98
+ *
99
+ * @param result - Optimization result
100
+ * @returns Human-readable summary of changes
101
+ */
102
+ export declare function getChangesSummary(result: InstructionOptimizationResult): string;
103
+ /**
104
+ * Utility: Validate that fixed instructions preserve all tokens
105
+ *
106
+ * @param originalInstructions - Original instructions
107
+ * @param result - Optimization result
108
+ * @returns Object with validation status and any missing tokens
109
+ */
110
+ export declare function validateTokenPreservation(originalInstructions: string, result: InstructionOptimizationResult): {
111
+ valid: boolean;
112
+ missingTokens: string[];
113
+ };
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Instruction Optimizer Feature
3
+ *
4
+ * Uses AI to analyze and fix poorly-written instructions.
5
+ * This is a meta-feature that uses the AI Gateway (via router) to improve AI instructions.
6
+ */
7
+ /**
8
+ * The meta-instructions used to fix other instructions
9
+ * Loaded from instructions-audit.md
10
+ */
11
+ const INSTRUCTION_OPTIMIZER_INSTRUCTIONS = `You are an AI instruction optimizer. Your task is to analyze and fix poorly-written AI instructions.
12
+
13
+ You will receive instructions that may have issues like:
14
+ - Vague or unclear task descriptions
15
+ - Missing output format specifications
16
+ - Contradictory requirements
17
+ - Poor structure or organization
18
+ - Missing critical rules for JSON-only responses
19
+
20
+ Your response must be ONLY a valid JSON object with this exact structure:
21
+
22
+ {
23
+ "analysis": {
24
+ "problems_found": [
25
+ "<string> Description of each problem identified"
26
+ ],
27
+ "missing_elements": [
28
+ "<string> What critical elements are missing"
29
+ ],
30
+ "clarity_score": <number 1-10> How clear the original instructions were
31
+ },
32
+ "fixed_instructions": {
33
+ "complete_text": "<string> The complete fixed instructions ready to use as-is. This should be a fully self-contained instruction set that needs NO composition or assembly. Preserve all {{tokens}} exactly as they appear.",
34
+ "breakdown": {
35
+ "core_task": "<string> The main task/objective extracted",
36
+ "task_description": "<string> What the AI should do",
37
+ "output_requirements": "<string> Required output format and structure",
38
+ "constraints": [
39
+ "<string> Each constraint or rule"
40
+ ],
41
+ "schemas": [
42
+ {
43
+ "type": "<string> Schema type/name",
44
+ "schema": <object> The actual schema object,
45
+ "when_to_use": "<string> When this schema applies"
46
+ }
47
+ ],
48
+ "tokens_preserved": [
49
+ "<string> List of all {{tokens}} found and preserved"
50
+ ]
51
+ }
52
+ },
53
+ "changes_made": [
54
+ {
55
+ "change_type": "<string> Type of change (clarification|addition|restructure|correction)",
56
+ "original": "<string> What the original said (or 'missing' if added)",
57
+ "fixed": "<string> What it was changed to",
58
+ "reason": "<string> Why this change was necessary"
59
+ }
60
+ ],
61
+ "quality_improvements": {
62
+ "before_score": <number 1-10>,
63
+ "after_score": <number 1-10>,
64
+ "summary": "<string> Brief summary of overall improvements"
65
+ }
66
+ }
67
+
68
+ CRITICAL RULES:
69
+ - Your ENTIRE response must be parseable JSON
70
+ - Do NOT write conversational text outside the JSON
71
+ - Response must START with { and END with }
72
+ - The "complete_text" field must contain fully usable instructions that need NO further assembly
73
+ - Preserve ALL template tokens exactly: {{taskDescription}}, {{input}}, {{role}}, etc.
74
+ - Do NOT resolve or replace tokens - keep them as placeholders
75
+ - If instructions mention JSON output, ensure complete JSON enforcement rules are included
76
+ - If schemas are mentioned, extract and structure them properly
77
+
78
+ INSTRUCTION FIXING GUIDELINES:
79
+
80
+ 1. CLARITY: Make task objectives crystal clear
81
+ 2. COMPLETENESS: Add missing critical elements (output format, constraints, error handling)
82
+ 3. STRUCTURE: Organize logically (task → requirements → constraints → schemas)
83
+ 4. JSON ENFORCEMENT: If JSON output is required, add strict enforcement rules:
84
+ - "Your ENTIRE response must be parseable JSON"
85
+ - "Do NOT write conversational text"
86
+ - "Response must START with { and END with }"
87
+ - "FORBIDDEN: 'I'm sorry', 'Please provide', 'Sure!', etc."
88
+ 5. TOKENS: Preserve all {{token}} placeholders exactly as written
89
+ 6. SCHEMAS: Extract any schema definitions into proper structure
90
+ 7. EXAMPLES: Add examples if they would improve clarity
91
+
92
+ If the instructions are already well-written, explain that in the analysis and make only minor improvements.`;
93
+ /**
94
+ * Optimizes AI instructions by analyzing and fixing common issues
95
+ *
96
+ * This is a meta-feature that uses AI (via the gateway router) to improve AI instructions.
97
+ * It takes poorly-written instructions and returns:
98
+ * 1. Analysis of problems
99
+ * 2. Fixed, production-ready instructions
100
+ * 3. Detailed breakdown of components
101
+ * 4. List of changes made and why
102
+ *
103
+ * @param gateway - AI Gateway instance (uses router, not direct provider calls)
104
+ * @param originalInstructions - The instructions to optimize
105
+ * @param options - Optimization options
106
+ * @returns Optimization result with fixed instructions and analysis
107
+ */
108
+ export async function optimizeInstructions(gateway, originalInstructions, options = {}) {
109
+ // Get internal system action config (instruction optimization)
110
+ const internalConfig = gateway.config?.internalSystemActions?.instructionOptimization;
111
+ const defaultEngine = gateway.config?.defaultEngine || 'openai';
112
+ const defaultModel = internalConfig?.model || 'gpt-4o';
113
+ const defaultProvider = internalConfig?.engine || defaultEngine;
114
+ const { agentId = 'instruction-optimizer', targetUseCase, enforceJsonOutput, model = defaultModel, // Use internal config default if not provided
115
+ provider = defaultProvider, // Use internal config default if not provided
116
+ includeDetailedExplanations = true } = options;
117
+ // Build context based on target use case
118
+ let additionalContext = '';
119
+ if (targetUseCase === 'json-extraction') {
120
+ additionalContext = '\n\nTarget Use Case: These instructions will be used for JSON extraction tasks. Ensure strict JSON output enforcement and empty result handling are included.';
121
+ }
122
+ else if (targetUseCase === 'chat') {
123
+ additionalContext = '\n\nTarget Use Case: These instructions will be used for conversational AI. Ensure natural, helpful responses are encouraged while maintaining clarity.';
124
+ }
125
+ else if (targetUseCase === 'reasoning') {
126
+ additionalContext = '\n\nTarget Use Case: These instructions will be used for reasoning tasks. Ensure step-by-step thinking is encouraged and output includes reasoning process.';
127
+ }
128
+ if (enforceJsonOutput) {
129
+ additionalContext += '\n\nIMPORTANT: The fixed instructions MUST include strict JSON-only output enforcement rules.';
130
+ }
131
+ // Create the optimization request - uses gateway.invoke() which goes through router
132
+ // Use internal system action config for temperature and maxTokens if available
133
+ const optimizationRequest = {
134
+ jobId: `optimize-instructions-${Date.now()}`,
135
+ agentId,
136
+ instructions: INSTRUCTION_OPTIMIZER_INSTRUCTIONS + additionalContext,
137
+ input: originalInstructions,
138
+ config: {
139
+ model,
140
+ provider,
141
+ temperature: internalConfig?.temperature ?? 0.3, // Use internal config or default
142
+ maxTokens: internalConfig?.maxTokens ?? 4000 // Use internal config or default
143
+ },
144
+ // Use JSON output type to ensure we get structured response
145
+ primaryObjectType: {
146
+ type: 'instruction-optimization',
147
+ schema: {
148
+ analysis: {
149
+ type: 'object',
150
+ properties: {
151
+ problems_found: {
152
+ type: 'array',
153
+ items: { type: 'string' }
154
+ },
155
+ missing_elements: {
156
+ type: 'array',
157
+ items: { type: 'string' }
158
+ },
159
+ clarity_score: { type: 'number' }
160
+ },
161
+ required: ['problems_found', 'missing_elements', 'clarity_score']
162
+ },
163
+ fixed_instructions: {
164
+ type: 'object',
165
+ properties: {
166
+ complete_text: { type: 'string' },
167
+ breakdown: {
168
+ type: 'object',
169
+ properties: {
170
+ core_task: { type: 'string' },
171
+ task_description: { type: 'string' },
172
+ output_requirements: { type: 'string' },
173
+ constraints: {
174
+ type: 'array',
175
+ items: { type: 'string' }
176
+ },
177
+ schemas: {
178
+ type: 'array',
179
+ items: {
180
+ type: 'object',
181
+ properties: {
182
+ type: { type: 'string' },
183
+ schema: { type: 'object' },
184
+ when_to_use: { type: 'string' }
185
+ }
186
+ }
187
+ },
188
+ tokens_preserved: {
189
+ type: 'array',
190
+ items: { type: 'string' }
191
+ }
192
+ },
193
+ required: ['core_task', 'task_description', 'output_requirements', 'constraints', 'schemas', 'tokens_preserved']
194
+ }
195
+ },
196
+ required: ['complete_text', 'breakdown']
197
+ },
198
+ changes_made: {
199
+ type: 'array',
200
+ items: {
201
+ type: 'object',
202
+ properties: {
203
+ change_type: { type: 'string' },
204
+ original: { type: 'string' },
205
+ fixed: { type: 'string' },
206
+ reason: { type: 'string' }
207
+ },
208
+ required: ['change_type', 'original', 'fixed', 'reason']
209
+ }
210
+ },
211
+ quality_improvements: {
212
+ type: 'object',
213
+ properties: {
214
+ before_score: { type: 'number' },
215
+ after_score: { type: 'number' },
216
+ summary: { type: 'string' }
217
+ },
218
+ required: ['before_score', 'after_score', 'summary']
219
+ }
220
+ },
221
+ whenToUse: 'Always use this schema for instruction optimization results',
222
+ description: 'Result of instruction optimization with analysis and fixes'
223
+ }
224
+ };
225
+ // Call the gateway - this goes through the router, not direct provider calls
226
+ const response = await gateway.invoke(optimizationRequest);
227
+ // Check for errors
228
+ if (!response.parsedContent) {
229
+ throw new Error(`Instruction optimization failed: Response missing parsedContent. Content: ${response.content?.substring(0, 200)}`);
230
+ }
231
+ // Parse the result
232
+ const result = response.parsedContent;
233
+ if (!result || !result.fixed_instructions || !result.fixed_instructions.complete_text) {
234
+ throw new Error('Invalid optimization result: missing fixed instructions');
235
+ }
236
+ return result;
237
+ }
238
+ /**
239
+ * Utility: Extract only the fixed instructions text
240
+ *
241
+ * @param result - Optimization result
242
+ * @returns Just the complete fixed instructions text
243
+ */
244
+ export function getFixedInstructions(result) {
245
+ return result.fixed_instructions.complete_text;
246
+ }
247
+ /**
248
+ * Utility: Get a summary of changes made
249
+ *
250
+ * @param result - Optimization result
251
+ * @returns Human-readable summary of changes
252
+ */
253
+ export function getChangesSummary(result) {
254
+ const summary = [
255
+ `Quality improved from ${result.quality_improvements.before_score}/10 to ${result.quality_improvements.after_score}/10`,
256
+ `\n${result.quality_improvements.summary}`,
257
+ `\nProblems fixed: ${result.analysis.problems_found.length}`,
258
+ `Missing elements added: ${result.analysis.missing_elements.length}`,
259
+ `Total changes: ${result.changes_made.length}`
260
+ ];
261
+ if (result.fixed_instructions.breakdown.tokens_preserved.length > 0) {
262
+ summary.push(`\nTokens preserved: ${result.fixed_instructions.breakdown.tokens_preserved.join(', ')}`);
263
+ }
264
+ return summary.join('\n');
265
+ }
266
+ /**
267
+ * Utility: Validate that fixed instructions preserve all tokens
268
+ *
269
+ * @param originalInstructions - Original instructions
270
+ * @param result - Optimization result
271
+ * @returns Object with validation status and any missing tokens
272
+ */
273
+ export function validateTokenPreservation(originalInstructions, result) {
274
+ // Extract tokens from original (matches {{anything}})
275
+ const tokenRegex = /\{\{([^}]+)\}\}/g;
276
+ const originalTokens = new Set();
277
+ let match;
278
+ while ((match = tokenRegex.exec(originalInstructions)) !== null) {
279
+ originalTokens.add(match[0]); // Store full token with braces
280
+ }
281
+ // Check if all tokens are preserved in fixed instructions
282
+ const fixedText = result.fixed_instructions.complete_text;
283
+ const missingTokens = [];
284
+ for (const token of originalTokens) {
285
+ if (!fixedText.includes(token)) {
286
+ missingTokens.push(token);
287
+ }
288
+ }
289
+ return {
290
+ valid: missingTokens.length === 0,
291
+ missingTokens
292
+ };
293
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Instructions Parser Module
3
+ *
4
+ * Handles template rendering for instruction content using Rendrix (@x12i/rendrix).
5
+ * Separated from instruction resolution to keep concerns clean.
6
+ */
7
+ import type { TemplateRenderOptions } from '@x12i/rendrix';
8
+ export interface TemplateVariables {
9
+ workingMemory?: Record<string, any>;
10
+ shortTermMemory?: Record<string, any>;
11
+ experienceMemory?: Record<string, any>;
12
+ knowledgeMemory?: Record<string, any>;
13
+ [key: string]: any;
14
+ }
15
+ export interface RenderedInstruction {
16
+ text: string;
17
+ templateVariables: TemplateVariables;
18
+ renderTime: number;
19
+ }
20
+ /**
21
+ * Renders instruction templates with variables using Rendrix (@x12i/rendrix)
22
+ */
23
+ export declare function renderInstructionTemplate(template: string, variables?: TemplateVariables, templateRenderOptions?: TemplateRenderOptions): Promise<RenderedInstruction>;
24
+ /**
25
+ * Checks if a template contains variables that need rendering
26
+ */
27
+ export declare function hasTemplateVariables(template: string): boolean;
28
+ /**
29
+ * Extracts variable names from a template
30
+ */
31
+ export declare function extractTemplateVariables(template: string): string[];
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Instructions Parser Module
3
+ *
4
+ * Handles template rendering for instruction content using Rendrix (@x12i/rendrix).
5
+ * Separated from instruction resolution to keep concerns clean.
6
+ */
7
+ import { parseTemplate } from './template-parser.js';
8
+ /**
9
+ * Renders instruction templates with variables using Rendrix (@x12i/rendrix)
10
+ */
11
+ export async function renderInstructionTemplate(template, variables = {}, templateRenderOptions) {
12
+ const startTime = Date.now();
13
+ // Extract memory contexts for Rendrix
14
+ // parseTemplate expects: (template, workingMemory, shortTermMemory?, experienceMemory?, knowledgeMemory?)
15
+ const workingMemory = variables.workingMemory || {};
16
+ const shortTermMemory = variables.shortTermMemory || {};
17
+ const experienceMemory = variables.experienceMemory || {};
18
+ const knowledgeMemory = variables.knowledgeMemory || {};
19
+ // Render template using Rendrix
20
+ // Pass memory contexts as separate parameters, not as a combined object
21
+ const renderedText = await parseTemplate(template, workingMemory, undefined, // taskConfig removed - no longer used
22
+ shortTermMemory, experienceMemory, knowledgeMemory, templateRenderOptions);
23
+ // Combine all memory contexts for return value (for metadata)
24
+ const combinedVariables = {
25
+ ...variables,
26
+ workingMemory,
27
+ shortTermMemory,
28
+ experienceMemory,
29
+ knowledgeMemory
30
+ };
31
+ const renderTime = Date.now() - startTime;
32
+ return {
33
+ text: renderedText,
34
+ templateVariables: combinedVariables,
35
+ renderTime
36
+ };
37
+ }
38
+ /**
39
+ * Checks if a template contains variables that need rendering
40
+ */
41
+ export function hasTemplateVariables(template) {
42
+ // Check for double-brace variables like {{variable}}
43
+ return /\{\{[^}]+\}\}/g.test(template);
44
+ }
45
+ /**
46
+ * Extracts variable names from a template
47
+ */
48
+ export function extractTemplateVariables(template) {
49
+ const matches = template.match(/\{\{([^}]+)\}\}/g);
50
+ if (!matches)
51
+ return [];
52
+ return matches.map(match => {
53
+ // Remove {{ and }} and trim whitespace
54
+ return match.slice(2, -2).trim();
55
+ }).filter((value, index, array) => array.indexOf(value) === index); // Remove duplicates
56
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Logger Factory
3
+ *
4
+ * Creates and configures logxer instances for the gateway
5
+ */
6
+ import { type Logxer } from '@x12i/logxer';
7
+ /**
8
+ * Creates a logger instance based on configuration
9
+ *
10
+ * @param config - Logger configuration
11
+ * @returns Configured logger or no-op logger if logging is disabled
12
+ */
13
+ export declare function createGatewayLogger(config: {
14
+ enableLogging: boolean;
15
+ packageName?: string;
16
+ customLogger?: Logxer;
17
+ }): Logxer;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Logger Factory
3
+ *
4
+ * Creates and configures logxer instances for the gateway
5
+ */
6
+ import { createLogxer } from '@x12i/logxer';
7
+ /**
8
+ * Creates a logger instance based on configuration
9
+ *
10
+ * @param config - Logger configuration
11
+ * @returns Configured logger or no-op logger if logging is disabled
12
+ */
13
+ export function createGatewayLogger(config) {
14
+ if (config.customLogger) {
15
+ return config.customLogger;
16
+ }
17
+ if (!config.enableLogging) {
18
+ return createNoOpLogger();
19
+ }
20
+ return createLogxer({
21
+ packageName: config.packageName || 'AI_GATEWAY',
22
+ envPrefix: config.packageName || 'AI_GATEWAY',
23
+ debugNamespace: 'ai-gateway'
24
+ }, {
25
+ logLevel: 'info',
26
+ logFormat: 'json'
27
+ });
28
+ }
29
+ function createNoOpLogger() {
30
+ const noop = () => { };
31
+ return {
32
+ verbose: noop,
33
+ debug: noop,
34
+ info: noop,
35
+ warn: noop,
36
+ error: noop,
37
+ success: noop,
38
+ isLevelEnabled: () => false,
39
+ getConfig: () => ({}),
40
+ shadow: {}
41
+ };
42
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Message Builder
3
+ * Direct message construction without request-builder package dependency
4
+ * Handles flex-md format exclusively
5
+ */
6
+ import type { ChatRequest, AIRequest } from './types.js';
7
+ import type { TemplateRenderOptions } from '@x12i/rendrix';
8
+ import type { Logxer } from '@x12i/logxer';
9
+ type Request = ChatRequest | AIRequest;
10
+ export interface MessageBuilderConfig {
11
+ defaultInstructionsBlocks: Record<string, any>;
12
+ /** Flat block overrides from gateway `instructionsBlocks` (merged at init). */
13
+ instructionsBlockOverrides: Record<string, string>;
14
+ logger: Logxer;
15
+ /** From packaged defaults + gateway `templateRendering`; merged per request with `templateRenderOptions`. */
16
+ templateRendering?: TemplateRenderOptions;
17
+ }
18
+ export interface BuildMessagesOptions {
19
+ useSystemContextFallback?: boolean;
20
+ includeInputRecognition?: boolean;
21
+ includeReinforcement?: boolean;
22
+ parsedSnapshot?: any;
23
+ shortTermMemory?: Record<string, any>;
24
+ experienceMemory?: Record<string, any>;
25
+ knowledgeMemory?: Record<string, any>;
26
+ }
27
+ export interface BuiltMessages {
28
+ messages: Array<{
29
+ role: string;
30
+ content: string;
31
+ }>;
32
+ metadata?: {
33
+ usingSystemContext?: boolean;
34
+ hasObjectTypes?: boolean;
35
+ };
36
+ }
37
+ /**
38
+ * Main function to build messages
39
+ */
40
+ export declare function buildMessages(request: Request, config: MessageBuilderConfig, options?: BuildMessagesOptions): Promise<BuiltMessages>;
41
+ export {};