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