@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,97 @@
1
+ /**
2
+ * Type definitions for Response Analyzer
3
+ */
4
+ /**
5
+ * Object type definition for matching against response objects
6
+ */
7
+ export interface ObjectTypeDefinition {
8
+ /**
9
+ * Unique identifier for the type
10
+ */
11
+ id: string;
12
+ /**
13
+ * Human-readable name
14
+ */
15
+ name: string;
16
+ /**
17
+ * Properties that must be present for a match
18
+ */
19
+ requiredProperties: string[];
20
+ /**
21
+ * Properties that boost confidence if present
22
+ */
23
+ optionalProperties?: string[];
24
+ /**
25
+ * Priority weight (higher = more important)
26
+ * Used to break ties when confidence is equal
27
+ * @default 1
28
+ */
29
+ priority?: number;
30
+ }
31
+ /**
32
+ * Configuration for ResponseAnalyzer
33
+ */
34
+ export interface ResponseAnalyzerConfig {
35
+ /**
36
+ * Object type definitions to match against
37
+ */
38
+ objectTypeDefinitions?: ObjectTypeDefinition[];
39
+ /**
40
+ * Enable format type detection for text responses
41
+ * @default true
42
+ */
43
+ enableFormatDetection?: boolean;
44
+ /**
45
+ * Minimum confidence threshold for object type matching
46
+ * Types below this threshold are filtered out
47
+ * @default 0.5
48
+ */
49
+ minConfidenceThreshold?: number;
50
+ }
51
+ /**
52
+ * Matched object type with confidence score
53
+ */
54
+ export interface MatchedObjectType {
55
+ /**
56
+ * The matched type definition
57
+ */
58
+ type: ObjectTypeDefinition;
59
+ /**
60
+ * Confidence score (0-1)
61
+ */
62
+ confidence: number;
63
+ }
64
+ /**
65
+ * Detected format type with confidence score
66
+ */
67
+ export interface DetectedFormatType {
68
+ /**
69
+ * Format type identifier
70
+ */
71
+ formatType: string;
72
+ /**
73
+ * Confidence score (0-1)
74
+ */
75
+ confidence: number;
76
+ }
77
+ /**
78
+ * Analysis result containing all detected information
79
+ */
80
+ export interface AnalysisResult {
81
+ /**
82
+ * Content type classification
83
+ */
84
+ contentType: 'object' | 'text' | 'empty';
85
+ /**
86
+ * Best matching object type (highest confidence)
87
+ */
88
+ bestObjectType?: MatchedObjectType;
89
+ /**
90
+ * All matching object types (sorted by confidence)
91
+ */
92
+ allObjectTypes?: MatchedObjectType[];
93
+ /**
94
+ * Detected format type (for text responses)
95
+ */
96
+ formatType?: DetectedFormatType;
97
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Type definitions for Response Analyzer
3
+ */
4
+ export {};
@@ -0,0 +1,11 @@
1
+ export type GatewayFallbackFixResult = {
2
+ fixed: true;
3
+ jsonText: string;
4
+ fixApplied: 'extract-fenced-json' | 'extract-balanced-json' | 'strip-to-first-json';
5
+ confidence: number;
6
+ warnings?: string[];
7
+ } | {
8
+ fixed: false;
9
+ warnings?: string[];
10
+ };
11
+ export declare function tryFixGatewayResponseToJsonText(raw: string): GatewayFallbackFixResult;
@@ -0,0 +1,123 @@
1
+ function tryParseJson(text) {
2
+ try {
3
+ return JSON.parse(text);
4
+ }
5
+ catch {
6
+ return undefined;
7
+ }
8
+ }
9
+ function extractFirstFencedBlock(text) {
10
+ // Supports ```json ... ``` and ```markdown ... ``` (and unlabeled ``` ... ```)
11
+ const re = /```(?:json|markdown)?\s*\n?([\s\S]*?)\n?```/i;
12
+ const match = text.match(re);
13
+ return match?.[1]?.trim() || undefined;
14
+ }
15
+ function extractBalancedJsonSubstring(text) {
16
+ // Finds first balanced {...} or [...] substring while respecting JSON strings.
17
+ const s = text;
18
+ const startObj = s.indexOf('{');
19
+ const startArr = s.indexOf('[');
20
+ let start = -1;
21
+ let openChar = '';
22
+ let closeChar = '';
23
+ if (startObj === -1 && startArr === -1)
24
+ return undefined;
25
+ if (startObj !== -1 && (startArr === -1 || startObj < startArr)) {
26
+ start = startObj;
27
+ openChar = '{';
28
+ closeChar = '}';
29
+ }
30
+ else {
31
+ start = startArr;
32
+ openChar = '[';
33
+ closeChar = ']';
34
+ }
35
+ let depth = 0;
36
+ let inString = false;
37
+ let escape = false;
38
+ for (let i = start; i < s.length; i++) {
39
+ const ch = s[i];
40
+ if (inString) {
41
+ if (escape) {
42
+ escape = false;
43
+ continue;
44
+ }
45
+ if (ch === '\\') {
46
+ escape = true;
47
+ continue;
48
+ }
49
+ if (ch === '"') {
50
+ inString = false;
51
+ }
52
+ continue;
53
+ }
54
+ if (ch === '"') {
55
+ inString = true;
56
+ continue;
57
+ }
58
+ if (ch === openChar)
59
+ depth++;
60
+ if (ch === closeChar)
61
+ depth--;
62
+ if (depth === 0) {
63
+ const candidate = s.slice(start, i + 1).trim();
64
+ return candidate.length > 0 ? candidate : undefined;
65
+ }
66
+ }
67
+ return undefined;
68
+ }
69
+ function stripToFirstJsonLike(text) {
70
+ const s = text.trim();
71
+ const firstBrace = s.indexOf('{');
72
+ const firstBracket = s.indexOf('[');
73
+ if (firstBrace === -1 && firstBracket === -1)
74
+ return undefined;
75
+ const start = firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket) ? firstBrace : firstBracket;
76
+ const stripped = s.slice(start).trim();
77
+ return stripped.length > 0 ? stripped : undefined;
78
+ }
79
+ export function tryFixGatewayResponseToJsonText(raw) {
80
+ const warnings = [];
81
+ const input = raw ?? '';
82
+ if (!input || !input.trim()) {
83
+ return { fixed: false, warnings: ['empty-input'] };
84
+ }
85
+ // 0) Already valid JSON
86
+ const trimmed = input.trim();
87
+ if (tryParseJson(trimmed) !== undefined) {
88
+ return {
89
+ fixed: true,
90
+ jsonText: trimmed,
91
+ fixApplied: 'strip-to-first-json',
92
+ confidence: 0.95,
93
+ warnings: ['input-already-valid-json']
94
+ };
95
+ }
96
+ // 1) Fenced block extraction
97
+ const fenced = extractFirstFencedBlock(input);
98
+ if (fenced) {
99
+ if (tryParseJson(fenced) !== undefined) {
100
+ return { fixed: true, jsonText: fenced, fixApplied: 'extract-fenced-json', confidence: 0.7 };
101
+ }
102
+ warnings.push('fenced-block-found-but-not-json');
103
+ }
104
+ // 2) Balanced substring extraction
105
+ const balanced = extractBalancedJsonSubstring(input);
106
+ if (balanced) {
107
+ if (tryParseJson(balanced) !== undefined) {
108
+ return { fixed: true, jsonText: balanced, fixApplied: 'extract-balanced-json', confidence: 0.55 };
109
+ }
110
+ warnings.push('balanced-json-substring-found-but-not-json');
111
+ }
112
+ // 3) Strip leading prose to first { or [
113
+ const stripped = stripToFirstJsonLike(input);
114
+ if (stripped) {
115
+ // It might still have trailing junk; try balanced extraction again on stripped first.
116
+ const strippedBalanced = extractBalancedJsonSubstring(stripped) ?? stripped;
117
+ if (tryParseJson(strippedBalanced) !== undefined) {
118
+ return { fixed: true, jsonText: strippedBalanced, fixApplied: 'strip-to-first-json', confidence: 0.4 };
119
+ }
120
+ warnings.push('stripped-to-first-jsonlike-but-not-json');
121
+ }
122
+ return { fixed: false, warnings: warnings.length ? warnings : undefined };
123
+ }
@@ -0,0 +1,52 @@
1
+ import type { Logxer } from '@x12i/logxer';
2
+ import type { Activix } from '@x12i/activix';
3
+ export type ActivixQueryableClient = {
4
+ getJobActivities(input: {
5
+ jobId: string;
6
+ graphId?: string;
7
+ nodeId?: string;
8
+ limit?: number;
9
+ }): Promise<{
10
+ jobId: string;
11
+ graphRun?: unknown;
12
+ activities: unknown[];
13
+ }>;
14
+ };
15
+ export type LogxerQueryableClient = {
16
+ getJobLogs(input: {
17
+ jobId: string;
18
+ graphId?: string;
19
+ nodeId?: string;
20
+ limit?: number;
21
+ }): Promise<{
22
+ jobId: string;
23
+ lines: Array<{
24
+ ts?: number | string;
25
+ level?: 'debug' | 'info' | 'warn' | 'error';
26
+ scope?: string;
27
+ packageName?: string;
28
+ nodeId?: string;
29
+ message: string;
30
+ data?: unknown;
31
+ }>;
32
+ }>;
33
+ };
34
+ export type PackageRuntimeObjects = {
35
+ name: string;
36
+ activixClient?: ActivixQueryableClient;
37
+ logxerClient?: LogxerQueryableClient;
38
+ };
39
+ export type RuntimeObjects = {
40
+ lastJobId?: string;
41
+ activixClient?: ActivixQueryableClient;
42
+ logxerClient?: LogxerQueryableClient;
43
+ packagesRuntimeObjects: PackageRuntimeObjects[];
44
+ };
45
+ export type RuntimeObservabilityMode = 'debug' | 'prod';
46
+ export declare let runtimeObjects: RuntimeObjects | undefined;
47
+ export declare function setGatewayLastJobId(jobId: string | undefined): void;
48
+ export declare function setGatewayRuntimeClients(input: {
49
+ activix?: Activix;
50
+ logger?: Logxer;
51
+ }): void;
52
+ export declare function getRuntimeObservabilityMode(): RuntimeObservabilityMode;
@@ -0,0 +1,46 @@
1
+ export let runtimeObjects = createRuntimeObjectsForMode();
2
+ export function setGatewayLastJobId(jobId) {
3
+ const objects = ensureRuntimeObjectsForCurrentMode();
4
+ if (!objects)
5
+ return;
6
+ objects.lastJobId = jobId;
7
+ }
8
+ export function setGatewayRuntimeClients(input) {
9
+ const objects = ensureRuntimeObjectsForCurrentMode();
10
+ if (!objects)
11
+ return;
12
+ objects.activixClient = input.activix ? asActivixQueryableClient(input.activix) : undefined;
13
+ objects.logxerClient = input.logger ? asLogxerQueryableClient(input.logger) : undefined;
14
+ objects.packagesRuntimeObjects = [];
15
+ }
16
+ export function getRuntimeObservabilityMode() {
17
+ const rawMode = process.env.mode ?? process.env.MODE;
18
+ return rawMode === 'prod' ? 'prod' : 'debug';
19
+ }
20
+ function ensureRuntimeObjectsForCurrentMode() {
21
+ if (getRuntimeObservabilityMode() === 'prod') {
22
+ runtimeObjects = undefined;
23
+ return undefined;
24
+ }
25
+ runtimeObjects ??= createRuntimeObjects();
26
+ return runtimeObjects;
27
+ }
28
+ function createRuntimeObjectsForMode() {
29
+ return getRuntimeObservabilityMode() === 'debug' ? createRuntimeObjects() : undefined;
30
+ }
31
+ function createRuntimeObjects() {
32
+ return {
33
+ lastJobId: undefined,
34
+ activixClient: undefined,
35
+ logxerClient: undefined,
36
+ packagesRuntimeObjects: []
37
+ };
38
+ }
39
+ function asActivixQueryableClient(activix) {
40
+ const candidate = activix;
41
+ return typeof candidate.getJobActivities === 'function' ? candidate : undefined;
42
+ }
43
+ function asLogxerQueryableClient(logger) {
44
+ const candidate = logger;
45
+ return typeof candidate.getJobLogs === 'function' ? candidate : undefined;
46
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Template Parser
3
+ *
4
+ * Uses @x12i/rendrix (v4+) to parse templates with workingMemory.
5
+ * TemplateResolutionError from the parser is rethrown; other errors fall back to the raw template.
6
+ */
7
+ import type { TemplateRenderOptions } from '@x12i/rendrix';
8
+ /**
9
+ * Task configuration type for template rendering
10
+ * @deprecated taskConfig is no longer used by Rendrix 3.0.0+
11
+ * Kept for backward compatibility only - will be ignored
12
+ */
13
+ export interface TaskConfig {
14
+ includeThoughts?: boolean;
15
+ }
16
+ /**
17
+ * Short-term memory type - flexible key-value storage
18
+ */
19
+ export interface ShortTermMemory {
20
+ [key: string]: string | number | boolean | object | object[];
21
+ }
22
+ /**
23
+ * Experience memory type - structured storage for learned experiences
24
+ */
25
+ export interface ExperienceMemory {
26
+ knowHows?: object | object[] | string[] | string;
27
+ narratives?: object | object[] | string[] | string;
28
+ experiences?: object | object[] | string[] | string;
29
+ insights?: object | object[] | string[] | string;
30
+ learnings?: object | object[] | string[] | string;
31
+ lessons?: object | object[] | string[] | string;
32
+ frameworks?: object | object[] | string[] | string;
33
+ tools?: object | object[] | string[] | string;
34
+ }
35
+ /**
36
+ * Knowledge memory type - flexible key-value storage for reference data
37
+ */
38
+ export interface KnowledgeMemory {
39
+ [key: string]: string | number | boolean | object | object[];
40
+ }
41
+ /**
42
+ * Parses a template string using Rendrix with all memory contexts
43
+ *
44
+ * @param template - Template string to parse
45
+ * @param workingMemory - Working memory object for variable substitution (required for rendering)
46
+ * @param taskConfig - @deprecated Task configuration flags - no longer used by Rendrix 3.0.0+ (kept for backward compatibility)
47
+ * @param shortTermMemory - Short-term memory for session-specific overrides (optional)
48
+ * @param experienceMemory - Experience memory for learned knowledge (optional)
49
+ * @param knowledgeMemory - Knowledge memory for reference data (optional)
50
+ * @param templateRenderOptions - Passed to Rendrix `render` (v4+): templateId, subPathSearch, silentMissingMustTokens
51
+ * @returns Parsed template string
52
+ * @throws {Error} When the parser throws TemplateResolutionError (v4 MUST path missing after merge)
53
+ */
54
+ export declare function parseTemplate(template: string, workingMemory?: unknown, taskConfig?: TaskConfig, shortTermMemory?: ShortTermMemory, experienceMemory?: ExperienceMemory, knowledgeMemory?: KnowledgeMemory, templateRenderOptions?: TemplateRenderOptions): Promise<string>;
55
+ /**
56
+ * Checks if Rendrix (@x12i/rendrix) is available
57
+ */
58
+ export declare function isParserAvailable(): boolean;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Template Parser
3
+ *
4
+ * Uses @x12i/rendrix (v4+) to parse templates with workingMemory.
5
+ * TemplateResolutionError from the parser is rethrown; other errors fall back to the raw template.
6
+ */
7
+ let rendrixModule = null;
8
+ let parserLoadPromise = null;
9
+ async function loadRendrix() {
10
+ if (rendrixModule !== null || parserLoadPromise) {
11
+ if (parserLoadPromise)
12
+ await parserLoadPromise;
13
+ return;
14
+ }
15
+ parserLoadPromise = (async () => {
16
+ try {
17
+ rendrixModule = await import('@x12i/rendrix');
18
+ }
19
+ catch {
20
+ rendrixModule = null;
21
+ }
22
+ finally {
23
+ parserLoadPromise = null;
24
+ }
25
+ })();
26
+ await parserLoadPromise;
27
+ }
28
+ /**
29
+ * Parses a template string using Rendrix with all memory contexts
30
+ *
31
+ * @param template - Template string to parse
32
+ * @param workingMemory - Working memory object for variable substitution (required for rendering)
33
+ * @param taskConfig - @deprecated Task configuration flags - no longer used by Rendrix 3.0.0+ (kept for backward compatibility)
34
+ * @param shortTermMemory - Short-term memory for session-specific overrides (optional)
35
+ * @param experienceMemory - Experience memory for learned knowledge (optional)
36
+ * @param knowledgeMemory - Knowledge memory for reference data (optional)
37
+ * @param templateRenderOptions - Passed to Rendrix `render` (v4+): templateId, subPathSearch, silentMissingMustTokens
38
+ * @returns Parsed template string
39
+ * @throws {Error} When the parser throws TemplateResolutionError (v4 MUST path missing after merge)
40
+ */
41
+ export async function parseTemplate(template, workingMemory, taskConfig, shortTermMemory, experienceMemory, knowledgeMemory, templateRenderOptions) {
42
+ // If no template or empty, return as-is
43
+ if (!template || typeof template !== 'string') {
44
+ return template || '';
45
+ }
46
+ // If no workingMemory, return template as-is (workingMemory is required for Rendrix)
47
+ if (!workingMemory) {
48
+ return template;
49
+ }
50
+ await loadRendrix();
51
+ if (!rendrixModule) {
52
+ return template;
53
+ }
54
+ try {
55
+ const api = typeof rendrixModule.render === 'function'
56
+ ? rendrixModule
57
+ : rendrixModule.default || rendrixModule;
58
+ if (typeof api.render === 'function') {
59
+ return await api.render(template, workingMemory, shortTermMemory, experienceMemory, knowledgeMemory, undefined, // functionsMap
60
+ undefined, // choiceOptions
61
+ undefined, // filesContent
62
+ templateRenderOptions);
63
+ }
64
+ if (typeof api.parse === 'function') {
65
+ return await api.parse(template, workingMemory);
66
+ }
67
+ else if (typeof api === 'function') {
68
+ const parser = new api();
69
+ if (typeof parser.parse === 'function') {
70
+ return await parser.parse(template, workingMemory);
71
+ }
72
+ }
73
+ return template;
74
+ }
75
+ catch (error) {
76
+ // @x12i/rendrix v4+: missing MUST paths throw TemplateResolutionError.
77
+ if (error instanceof Error &&
78
+ error.name === 'TemplateResolutionError') {
79
+ throw error;
80
+ }
81
+ const err = error instanceof Error ? error : new Error(String(error));
82
+ console.warn('Template parsing failed, using template as-is:', {
83
+ error: err.message,
84
+ templateLength: template.length,
85
+ hasWorkingMemory: !!workingMemory,
86
+ hasTaskConfig: !!taskConfig,
87
+ hasShortTermMemory: !!shortTermMemory,
88
+ hasExperienceMemory: !!experienceMemory,
89
+ hasKnowledgeMemory: !!knowledgeMemory
90
+ });
91
+ return template;
92
+ }
93
+ }
94
+ /**
95
+ * Checks if Rendrix (@x12i/rendrix) is available
96
+ */
97
+ export function isParserAvailable() {
98
+ return rendrixModule !== null;
99
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Merge @x12i/rendrix TemplateRenderOptions from gateway defaults and per-request overrides.
3
+ */
4
+ import type { TemplateRenderOptions } from '@x12i/rendrix';
5
+ /**
6
+ * Deep-merge template render options. Request/gateway overrides win per field.
7
+ * For `subPathSearch`, `roots` on the override replace the base list when present.
8
+ */
9
+ export declare function mergeTemplateRenderOptions(base?: TemplateRenderOptions, override?: TemplateRenderOptions): TemplateRenderOptions | undefined;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Merge @x12i/rendrix TemplateRenderOptions from gateway defaults and per-request overrides.
3
+ */
4
+ function hasMeaningfulOptions(o) {
5
+ if (o.templateId !== undefined)
6
+ return true;
7
+ if (o.silentMissingMustTokens !== undefined)
8
+ return true;
9
+ if (o.subPathSearch !== undefined) {
10
+ const s = o.subPathSearch;
11
+ return (s.enabled !== undefined ||
12
+ (Array.isArray(s.roots) && s.roots.length > 0));
13
+ }
14
+ return false;
15
+ }
16
+ /**
17
+ * Deep-merge template render options. Request/gateway overrides win per field.
18
+ * For `subPathSearch`, `roots` on the override replace the base list when present.
19
+ */
20
+ export function mergeTemplateRenderOptions(base, override) {
21
+ if (!base && !override)
22
+ return undefined;
23
+ if (!base) {
24
+ const o = { ...override };
25
+ return hasMeaningfulOptions(o) ? o : undefined;
26
+ }
27
+ if (!override) {
28
+ const o = { ...base };
29
+ return hasMeaningfulOptions(o) ? o : undefined;
30
+ }
31
+ const merged = { ...base, ...override };
32
+ if (base.subPathSearch || override.subPathSearch) {
33
+ merged.subPathSearch = {
34
+ ...(base.subPathSearch ?? {}),
35
+ ...(override.subPathSearch ?? {}),
36
+ roots: override.subPathSearch?.roots ?? base.subPathSearch?.roots
37
+ };
38
+ }
39
+ return hasMeaningfulOptions(merged) ? merged : undefined;
40
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Troubleshooting Helper Toolbox
3
+ *
4
+ * Utility functions to diagnose and test AI Gateway issues
5
+ * Based on TROUBLESHOOTING.md guide
6
+ */
7
+ import type { AIRequest, ChatRequest, EnhancedLLMResponse } from './types.js';
8
+ /**
9
+ * Converts JSON Schema to simple, human-readable format for LLM instructions
10
+ *
11
+ * Supports both formats:
12
+ * - JSON Schema format: { "type": "object", "properties": {...} }
13
+ * - Simple format: { "emails": ["<string> description"] }
14
+ *
15
+ * If schema is already in simple format, returns it as-is.
16
+ * If schema is in JSON Schema format, converts it to simple format.
17
+ *
18
+ * Simple format example:
19
+ * {
20
+ * "emails": [
21
+ * "<string> A valid email address extracted from the input text"
22
+ * ]
23
+ * }
24
+ *
25
+ * Format rules:
26
+ * - Arrays: Show as array with single example item containing type hint + description
27
+ * - Objects: Show nested structure recursively
28
+ * - Primitives: Show as type hint with description
29
+ * - Required fields: Implicit (just present in structure)
30
+ *
31
+ * @param schema - Schema object (JSON Schema or simple format)
32
+ * @returns Schema in simple format
33
+ */
34
+ export declare function convertSchemaToSimpleFormat(schema: Record<string, unknown>): Record<string, unknown>;
35
+ export interface ValidationResult {
36
+ valid: boolean;
37
+ errors: string[];
38
+ warnings: string[];
39
+ }
40
+ export interface DiagnosticInfo {
41
+ request: {
42
+ hasJobId: boolean;
43
+ hasAgentId: boolean;
44
+ hasInstructions: boolean;
45
+ hasPrompt: boolean;
46
+ hasWorkingMemory: boolean;
47
+ hasConfig: boolean;
48
+ hasModel: boolean;
49
+ hasProvider: boolean;
50
+ };
51
+ response?: {
52
+ hasContent: boolean;
53
+ isJSON: boolean;
54
+ hasParsedContent: boolean;
55
+ contentType: string;
56
+ validationPassed?: boolean;
57
+ validationErrors?: string[];
58
+ };
59
+ }
60
+ /**
61
+ * Validates AIRequest structure
62
+ */
63
+ export declare function validateAIRequest(request: Partial<AIRequest>): ValidationResult;
64
+ /**
65
+ * Validates JSON string
66
+ */
67
+ export declare function validateJSON(jsonString: string): ValidationResult;
68
+ /**
69
+ * Extracts JSON from text (handles markdown code blocks, etc.)
70
+ */
71
+ export declare function extractJSON(text: string): {
72
+ json: string | null;
73
+ method: string;
74
+ };
75
+ /**
76
+ * Validates response structure
77
+ */
78
+ export declare function validateResponse(response: Partial<EnhancedLLMResponse>): ValidationResult;
79
+ /**
80
+ * Collects comprehensive diagnostic information
81
+ */
82
+ export declare function diagnoseRequest(request: Partial<AIRequest | ChatRequest>): DiagnosticInfo;
83
+ /**
84
+ * Diagnoses response issues
85
+ */
86
+ export declare function diagnoseResponse(response: Partial<EnhancedLLMResponse>): DiagnosticInfo['response'];
87
+ /**
88
+ * Tests if a provider/model combination supports JSON mode
89
+ */
90
+ export declare function supportsJSONMode(provider?: string, model?: string): {
91
+ supported: boolean;
92
+ notes: string;
93
+ };
94
+ /**
95
+ * Creates a test AIRequest with minimal valid structure
96
+ */
97
+ export declare function createTestAIRequest(overrides?: Partial<AIRequest>): AIRequest;
98
+ /**
99
+ * Creates test cases for validation
100
+ */
101
+ export declare function createValidationTestCases(): Array<{
102
+ name: string;
103
+ request: Partial<AIRequest>;
104
+ shouldFail: boolean;
105
+ expectedErrors?: string[];
106
+ }>;
107
+ /**
108
+ * Runs all validation tests and returns results
109
+ */
110
+ export declare function runValidationTests(): Array<{
111
+ name: string;
112
+ passed: boolean;
113
+ errors: string[];
114
+ warnings: string[];
115
+ }>;
116
+ /**
117
+ * Formats diagnostic information for display
118
+ */
119
+ export declare function formatDiagnostic(diagnostic: DiagnosticInfo): string;
120
+ /**
121
+ * Quick validation helper - throws if invalid
122
+ */
123
+ export declare function assertValidAIRequest(request: Partial<AIRequest>): void;