@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,60 @@
1
+ /**
2
+ * Request Report Generator
3
+ *
4
+ * Generates comprehensive request reports with validation, examples, and structured text information
5
+ */
6
+ import type { AIRequest } from './types.js';
7
+ import type { Logxer } from '@x12i/logxer';
8
+ export interface RequestReport {
9
+ requestId: string;
10
+ timestamp: number;
11
+ validation: {
12
+ instructions?: string;
13
+ rules?: any[];
14
+ automatedCode?: string;
15
+ checklist?: string[];
16
+ };
17
+ examples: {
18
+ count: number;
19
+ normal?: number;
20
+ edge?: number;
21
+ error?: number;
22
+ samples?: Array<{
23
+ input: string;
24
+ output: string;
25
+ metadata?: Record<string, unknown>;
26
+ }>;
27
+ };
28
+ structuredText: {
29
+ available: boolean;
30
+ instructions?: string;
31
+ template?: string;
32
+ guidelines?: string[];
33
+ };
34
+ schema: {
35
+ format: 'simple-format' | 'json-schema';
36
+ fields: Array<{
37
+ name: string;
38
+ type: string;
39
+ required: boolean;
40
+ description?: string;
41
+ }>;
42
+ };
43
+ metadata?: {
44
+ category?: string;
45
+ tags?: string[];
46
+ version?: string;
47
+ };
48
+ integrationHints: {
49
+ useStandardType: boolean;
50
+ recommendedType?: string;
51
+ validationAvailable: boolean;
52
+ structuredTextAvailable: boolean;
53
+ examplesAvailable: boolean;
54
+ };
55
+ }
56
+ /**
57
+ * Generate comprehensive request report
58
+ */
59
+ export declare function generateRequestReport(request: AIRequest, library: any, // ObjectTypesLibrary removed
60
+ logger: Logxer): Promise<RequestReport>;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Request Report Generator
3
+ *
4
+ * Generates comprehensive request reports with validation, examples, and structured text information
5
+ */
6
+ /**
7
+ * Extract validation rules from markdown
8
+ */
9
+ function extractValidationRules(markdown) {
10
+ if (!markdown)
11
+ return [];
12
+ const rules = [];
13
+ // Look for validation rules sections
14
+ const rulesMatch = markdown.match(/## Validation Rules?\n([\s\S]*?)(?=\n##|$)/i);
15
+ if (rulesMatch) {
16
+ const rulesText = rulesMatch[1];
17
+ // Extract list items
18
+ const ruleItems = rulesText.match(/[-*]\s+(.+)/g);
19
+ if (ruleItems) {
20
+ ruleItems.forEach(item => {
21
+ rules.push({ rule: item.replace(/[-*]\s+/, '').trim() });
22
+ });
23
+ }
24
+ }
25
+ return rules;
26
+ }
27
+ /**
28
+ * Extract validation code from markdown
29
+ */
30
+ function extractValidationCode(markdown) {
31
+ if (!markdown)
32
+ return undefined;
33
+ // Look for TypeScript code blocks
34
+ const codeBlockMatch = markdown.match(/```typescript\n([\s\S]*?)\n```/);
35
+ if (codeBlockMatch) {
36
+ return codeBlockMatch[1];
37
+ }
38
+ // Also try JavaScript
39
+ const jsCodeBlockMatch = markdown.match(/```javascript\n([\s\S]*?)\n```/);
40
+ if (jsCodeBlockMatch) {
41
+ return jsCodeBlockMatch[1];
42
+ }
43
+ return undefined;
44
+ }
45
+ /**
46
+ * Extract checklist items from markdown
47
+ */
48
+ function extractChecklist(markdown) {
49
+ if (!markdown)
50
+ return [];
51
+ const checklist = [];
52
+ // Look for checklist section
53
+ const checklistMatch = markdown.match(/## Manual Review Checklist\n([\s\S]*?)(?=\n##|$)/i);
54
+ if (checklistMatch) {
55
+ const checklistText = checklistMatch[1];
56
+ // Extract checklist items (both checked and unchecked)
57
+ const items = checklistText.match(/- \[[ x]\] (.+)/g);
58
+ if (items) {
59
+ items.forEach(item => {
60
+ checklist.push(item.replace(/- \[[ x]\] /, '').trim());
61
+ });
62
+ }
63
+ }
64
+ return checklist;
65
+ }
66
+ /**
67
+ * Extract schema fields from simple format schema
68
+ */
69
+ function extractSchemaFields(schema) {
70
+ const fields = [];
71
+ for (const [key, value] of Object.entries(schema)) {
72
+ if (typeof value === 'string') {
73
+ // Simple format: "field: '<type> Description'"
74
+ const match = value.match(/^<(\w+)>(.*)$/);
75
+ if (match) {
76
+ fields.push({
77
+ name: key,
78
+ type: match[1],
79
+ required: true, // Assume required unless marked optional
80
+ description: match[2].trim() || undefined
81
+ });
82
+ }
83
+ else if (Array.isArray(value)) {
84
+ // Array field: "field: ['<type> Description']"
85
+ fields.push({
86
+ name: key,
87
+ type: 'array',
88
+ required: true,
89
+ description: 'Array field'
90
+ });
91
+ }
92
+ else if (typeof value === 'object' && value !== null) {
93
+ // Nested object
94
+ fields.push({
95
+ name: key,
96
+ type: 'object',
97
+ required: true,
98
+ description: 'Nested object'
99
+ });
100
+ }
101
+ }
102
+ else if (typeof value === 'object' && value !== null) {
103
+ // JSON Schema format
104
+ if (Array.isArray(value)) {
105
+ fields.push({
106
+ name: key,
107
+ type: 'array',
108
+ required: true
109
+ });
110
+ }
111
+ else {
112
+ fields.push({
113
+ name: key,
114
+ type: 'object',
115
+ required: true
116
+ });
117
+ }
118
+ }
119
+ }
120
+ return fields;
121
+ }
122
+ /**
123
+ * Find matching standard type for custom schema
124
+ */
125
+ async function findMatchingStandardType(schema, library // ObjectTypesLibrary removed
126
+ ) {
127
+ // Since ObjectTypesLibrary is removed, we can't match against standard types
128
+ // Return null to indicate no matching standard type found
129
+ return null;
130
+ }
131
+ /**
132
+ * Compare two schemas for structural similarity
133
+ */
134
+ function schemasMatch(schema1, schema2) {
135
+ // Simple structure comparison - compare field names
136
+ const keys1 = Object.keys(schema1).sort();
137
+ const keys2 = Object.keys(schema2).sort();
138
+ // Must have same number of fields
139
+ if (keys1.length !== keys2.length) {
140
+ return false;
141
+ }
142
+ // All field names must match
143
+ return JSON.stringify(keys1) === JSON.stringify(keys2);
144
+ }
145
+ /**
146
+ * Generate comprehensive request report
147
+ */
148
+ export async function generateRequestReport(request, library, // ObjectTypesLibrary removed
149
+ logger) {
150
+ const report = {
151
+ requestId: request.jobId || `req-${Date.now()}`,
152
+ timestamp: Date.now(),
153
+ validation: {},
154
+ examples: { count: 0 },
155
+ structuredText: { available: false },
156
+ schema: {
157
+ format: 'simple-format',
158
+ fields: []
159
+ },
160
+ integrationHints: {
161
+ useStandardType: false,
162
+ validationAvailable: false,
163
+ structuredTextAvailable: false,
164
+ examplesAvailable: false
165
+ }
166
+ };
167
+ // Always use flex-md parsing - no object type processing needed
168
+ return report;
169
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Format Type Detector
3
+ *
4
+ * Detects text format types by analyzing text characteristics:
5
+ * - Sentence length and count
6
+ * - Paragraph count
7
+ * - Bullet points / numbered lists
8
+ * - Technical terms
9
+ * - Word/character count
10
+ * - Structure patterns
11
+ */
12
+ export interface DetectedFormatType {
13
+ formatType: string;
14
+ confidence: number;
15
+ }
16
+ /**
17
+ * Detects format type of text content
18
+ */
19
+ export declare class FormatTypeDetector {
20
+ /**
21
+ * Detects format type from text
22
+ *
23
+ * @param text - Text content to analyze
24
+ * @returns Detected format type with confidence
25
+ */
26
+ detect(text: string): DetectedFormatType | null;
27
+ /**
28
+ * Analyzes text characteristics
29
+ */
30
+ private analyzeCharacteristics;
31
+ /**
32
+ * Applies heuristics to determine format type
33
+ */
34
+ private applyHeuristics;
35
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Format Type Detector
3
+ *
4
+ * Detects text format types by analyzing text characteristics:
5
+ * - Sentence length and count
6
+ * - Paragraph count
7
+ * - Bullet points / numbered lists
8
+ * - Technical terms
9
+ * - Word/character count
10
+ * - Structure patterns
11
+ */
12
+ /**
13
+ * Detects format type of text content
14
+ */
15
+ export class FormatTypeDetector {
16
+ /**
17
+ * Detects format type from text
18
+ *
19
+ * @param text - Text content to analyze
20
+ * @returns Detected format type with confidence
21
+ */
22
+ detect(text) {
23
+ if (!text || typeof text !== 'string' || text.trim().length === 0) {
24
+ return null;
25
+ }
26
+ const trimmed = text.trim();
27
+ const characteristics = this.analyzeCharacteristics(trimmed);
28
+ // Apply heuristics to determine format type
29
+ return this.applyHeuristics(characteristics);
30
+ }
31
+ /**
32
+ * Analyzes text characteristics
33
+ */
34
+ analyzeCharacteristics(text) {
35
+ const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0);
36
+ const paragraphs = text.split(/\n\s*\n/).filter(p => p.trim().length > 0);
37
+ const words = text.split(/\s+/).filter(w => w.length > 0);
38
+ // Detect bullet points (•, -, *, etc.)
39
+ const bulletPattern = /^[\s]*[•\-\*\+]\s+/gm;
40
+ const bullets = text.match(bulletPattern) || [];
41
+ // Detect numbered lists (1., 2., etc.)
42
+ const numberedPattern = /^[\s]*\d+[\.\)]\s+/gm;
43
+ const numbered = text.match(numberedPattern) || [];
44
+ // Simple technical term detection (words with common technical suffixes/patterns)
45
+ const technicalPattern = /\b(api|sdk|json|xml|http|https|sql|regex|async|await|function|class|interface|type|config|param|return)\b/gi;
46
+ const hasTechnicalTerms = technicalPattern.test(text);
47
+ const totalSentenceLength = sentences.reduce((sum, s) => sum + s.length, 0);
48
+ const avgSentenceLength = sentences.length > 0 ? totalSentenceLength / sentences.length : 0;
49
+ return {
50
+ sentenceCount: sentences.length,
51
+ avgSentenceLength,
52
+ paragraphCount: paragraphs.length,
53
+ wordCount: words.length,
54
+ charCount: text.length,
55
+ hasBullets: bullets.length > 0,
56
+ hasNumbered: numbered.length > 0,
57
+ bulletCount: bullets.length,
58
+ numberedCount: numbered.length,
59
+ hasTechnicalTerms
60
+ };
61
+ }
62
+ /**
63
+ * Applies heuristics to determine format type
64
+ */
65
+ applyHeuristics(characteristics) {
66
+ const { sentenceCount, avgSentenceLength, paragraphCount, wordCount, hasBullets, hasNumbered, bulletCount, numberedCount, hasTechnicalTerms } = characteristics;
67
+ // Bulleted list format
68
+ if (hasBullets && bulletCount >= 2) {
69
+ return {
70
+ formatType: 'bulleted',
71
+ confidence: Math.min(0.9, 0.6 + (bulletCount * 0.05))
72
+ };
73
+ }
74
+ // Numbered list format
75
+ if (hasNumbered && numberedCount >= 2) {
76
+ return {
77
+ formatType: 'numbered',
78
+ confidence: Math.min(0.9, 0.6 + (numberedCount * 0.05))
79
+ };
80
+ }
81
+ // Concise format: short sentences, low word count, few paragraphs
82
+ if (avgSentenceLength < 50 && wordCount < 50 && paragraphCount <= 1) {
83
+ return {
84
+ formatType: 'concise',
85
+ confidence: 0.8
86
+ };
87
+ }
88
+ // Explanatory format: multiple paragraphs, longer sentences
89
+ if (paragraphCount >= 2 && avgSentenceLength > 80) {
90
+ return {
91
+ formatType: 'explanatory',
92
+ confidence: 0.75
93
+ };
94
+ }
95
+ // Technical format: technical terms + longer sentences
96
+ if (hasTechnicalTerms && avgSentenceLength > 60) {
97
+ return {
98
+ formatType: 'technical',
99
+ confidence: 0.7
100
+ };
101
+ }
102
+ // Narrative format: multiple sentences, moderate length
103
+ if (sentenceCount >= 3 && avgSentenceLength >= 40 && avgSentenceLength <= 100) {
104
+ return {
105
+ formatType: 'narrative',
106
+ confidence: 0.65
107
+ };
108
+ }
109
+ // Default: plain text
110
+ return {
111
+ formatType: 'plain',
112
+ confidence: 0.5
113
+ };
114
+ }
115
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Response Analyzer Module
3
+ *
4
+ * Exports all public APIs for response analysis
5
+ */
6
+ export { ResponseAnalyzer } from './response-analyzer.js';
7
+ export { ObjectTypeDetector } from './object-type-detector.js';
8
+ export { FormatTypeDetector } from './format-type-detector.js';
9
+ export type { ObjectTypeDefinition, ResponseAnalyzerConfig, MatchedObjectType, DetectedFormatType, AnalysisResult } from './types.js';
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Response Analyzer Module
3
+ *
4
+ * Exports all public APIs for response analysis
5
+ */
6
+ export { ResponseAnalyzer } from './response-analyzer.js';
7
+ export { ObjectTypeDetector } from './object-type-detector.js';
8
+ export { FormatTypeDetector } from './format-type-detector.js';
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Object Type Detector
3
+ *
4
+ * Matches objects against predefined type definitions based on properties.
5
+ * Uses a scoring algorithm to determine the best match.
6
+ */
7
+ import type { ObjectTypeDefinition, MatchedObjectType } from './types.js';
8
+ export interface ObjectTypeDetectorConfig {
9
+ objectTypeDefinitions: ObjectTypeDefinition[];
10
+ minConfidenceThreshold: number;
11
+ }
12
+ /**
13
+ * Detects object types by matching against definitions
14
+ */
15
+ export declare class ObjectTypeDetector {
16
+ private definitions;
17
+ private minThreshold;
18
+ constructor(config: ObjectTypeDetectorConfig);
19
+ /**
20
+ * Detects object types in a parsed content object
21
+ *
22
+ * @param parsedContent - Parsed content (object, array, or null)
23
+ * @returns Array of matched types sorted by confidence
24
+ */
25
+ detect(parsedContent: any): MatchedObjectType[];
26
+ /**
27
+ * Calculates match confidence for an object against a type definition
28
+ *
29
+ * Algorithm:
30
+ * 1. Count required properties present
31
+ * 2. Count optional properties present
32
+ * 3. Calculate base confidence: (required + optional) / total
33
+ * 4. Boost if all required present: +0.2
34
+ * 5. Boost for optional properties: +0.1 * (optional/total)
35
+ * 6. Apply priority weight: confidence * (1 + (priority-1) * 0.1)
36
+ *
37
+ * @param obj - Object to match
38
+ * @param definition - Type definition to match against
39
+ * @returns Confidence score (0-1)
40
+ */
41
+ private calculateMatchConfidence;
42
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Object Type Detector
3
+ *
4
+ * Matches objects against predefined type definitions based on properties.
5
+ * Uses a scoring algorithm to determine the best match.
6
+ */
7
+ /**
8
+ * Detects object types by matching against definitions
9
+ */
10
+ export class ObjectTypeDetector {
11
+ definitions;
12
+ minThreshold;
13
+ constructor(config) {
14
+ this.definitions = config.objectTypeDefinitions;
15
+ this.minThreshold = config.minConfidenceThreshold;
16
+ }
17
+ /**
18
+ * Detects object types in a parsed content object
19
+ *
20
+ * @param parsedContent - Parsed content (object, array, or null)
21
+ * @returns Array of matched types sorted by confidence
22
+ */
23
+ detect(parsedContent) {
24
+ // Only process objects (not arrays or primitives)
25
+ if (!parsedContent || typeof parsedContent !== 'object' || Array.isArray(parsedContent)) {
26
+ return [];
27
+ }
28
+ const matches = [];
29
+ for (const definition of this.definitions) {
30
+ const confidence = this.calculateMatchConfidence(parsedContent, definition);
31
+ if (confidence >= this.minThreshold) {
32
+ matches.push({
33
+ type: definition,
34
+ confidence
35
+ });
36
+ }
37
+ }
38
+ // Sort by confidence (desc), then priority (desc)
39
+ matches.sort((a, b) => {
40
+ if (a.confidence !== b.confidence) {
41
+ return b.confidence - a.confidence;
42
+ }
43
+ const priorityA = a.type.priority || 1;
44
+ const priorityB = b.type.priority || 1;
45
+ return priorityB - priorityA;
46
+ });
47
+ return matches;
48
+ }
49
+ /**
50
+ * Calculates match confidence for an object against a type definition
51
+ *
52
+ * Algorithm:
53
+ * 1. Count required properties present
54
+ * 2. Count optional properties present
55
+ * 3. Calculate base confidence: (required + optional) / total
56
+ * 4. Boost if all required present: +0.2
57
+ * 5. Boost for optional properties: +0.1 * (optional/total)
58
+ * 6. Apply priority weight: confidence * (1 + (priority-1) * 0.1)
59
+ *
60
+ * @param obj - Object to match
61
+ * @param definition - Type definition to match against
62
+ * @returns Confidence score (0-1)
63
+ */
64
+ calculateMatchConfidence(obj, definition) {
65
+ const required = definition.requiredProperties || [];
66
+ const optional = definition.optionalProperties || [];
67
+ const totalProperties = required.length + optional.length;
68
+ if (totalProperties === 0) {
69
+ return 0; // No properties to match
70
+ }
71
+ // Count required properties present
72
+ const requiredPresent = required.filter((prop) => obj.hasOwnProperty(prop) && obj[prop] != null).length;
73
+ // Count optional properties present
74
+ const optionalPresent = optional.filter((prop) => obj.hasOwnProperty(prop) && obj[prop] != null).length;
75
+ // Base confidence: proportion of properties found
76
+ let confidence = (requiredPresent + optionalPresent) / totalProperties;
77
+ // Boost if all required properties are present
78
+ if (requiredPresent === required.length && required.length > 0) {
79
+ confidence += 0.2;
80
+ }
81
+ // Boost for optional properties (bonus for having extras)
82
+ if (optional.length > 0) {
83
+ confidence += 0.1 * (optionalPresent / optional.length);
84
+ }
85
+ // Cap at 1.0
86
+ confidence = Math.min(confidence, 1.0);
87
+ // Apply priority weight
88
+ const priority = definition.priority || 1;
89
+ if (priority > 1) {
90
+ confidence = confidence * (1 + (priority - 1) * 0.1);
91
+ confidence = Math.min(confidence, 1.0); // Cap again
92
+ }
93
+ return confidence;
94
+ }
95
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Response Analyzer
3
+ *
4
+ * Main class that orchestrates object type and format type detection.
5
+ * Analyzes normalized responses and provides enhanced metadata.
6
+ */
7
+ import type { ResponseAnalyzerConfig, AnalysisResult, ObjectTypeDefinition } from './types.js';
8
+ /**
9
+ * Analyzes AI responses to detect object types and format types
10
+ */
11
+ export declare class ResponseAnalyzer {
12
+ private objectDetector?;
13
+ private formatDetector;
14
+ private enableFormatDetection;
15
+ constructor(config?: ResponseAnalyzerConfig);
16
+ /**
17
+ * Analyzes a response and returns enhanced metadata
18
+ *
19
+ * @param rawText - Raw text content from response
20
+ * @param parsedContent - Parsed content (object, array, or null)
21
+ * @returns Analysis result with detected types
22
+ */
23
+ analyze(rawText?: string, parsedContent?: any): AnalysisResult;
24
+ /**
25
+ * Determines the content type of the response
26
+ *
27
+ * @param rawText - Raw text content
28
+ * @param parsedContent - Parsed content
29
+ * @returns Content type classification
30
+ */
31
+ private determineContentType;
32
+ /**
33
+ * Updates object type definitions
34
+ *
35
+ * @param definitions - New object type definitions
36
+ */
37
+ updateObjectTypeDefinitions(definitions: ObjectTypeDefinition[]): void;
38
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Response Analyzer
3
+ *
4
+ * Main class that orchestrates object type and format type detection.
5
+ * Analyzes normalized responses and provides enhanced metadata.
6
+ */
7
+ import { ObjectTypeDetector } from './object-type-detector.js';
8
+ import { FormatTypeDetector } from './format-type-detector.js';
9
+ /**
10
+ * Analyzes AI responses to detect object types and format types
11
+ */
12
+ export class ResponseAnalyzer {
13
+ objectDetector;
14
+ formatDetector;
15
+ enableFormatDetection;
16
+ constructor(config = {}) {
17
+ this.enableFormatDetection = config.enableFormatDetection !== false;
18
+ // Initialize object type detector if definitions provided
19
+ if (config.objectTypeDefinitions && config.objectTypeDefinitions.length > 0) {
20
+ this.objectDetector = new ObjectTypeDetector({
21
+ objectTypeDefinitions: config.objectTypeDefinitions,
22
+ minConfidenceThreshold: config.minConfidenceThreshold || 0.5
23
+ });
24
+ }
25
+ // Initialize format type detector
26
+ this.formatDetector = new FormatTypeDetector();
27
+ }
28
+ /**
29
+ * Analyzes a response and returns enhanced metadata
30
+ *
31
+ * @param rawText - Raw text content from response
32
+ * @param parsedContent - Parsed content (object, array, or null)
33
+ * @returns Analysis result with detected types
34
+ */
35
+ analyze(rawText, parsedContent) {
36
+ // Determine content type
37
+ const contentType = this.determineContentType(rawText, parsedContent);
38
+ const result = {
39
+ contentType
40
+ };
41
+ // Detect object types if content is an object
42
+ if (contentType === 'object' && this.objectDetector && parsedContent) {
43
+ const objectTypes = this.objectDetector.detect(parsedContent);
44
+ if (objectTypes.length > 0) {
45
+ result.bestObjectType = objectTypes[0];
46
+ result.allObjectTypes = objectTypes;
47
+ }
48
+ }
49
+ // Detect format type if content is text and format detection is enabled
50
+ if (contentType === 'text' && this.enableFormatDetection && rawText) {
51
+ const formatType = this.formatDetector.detect(rawText);
52
+ if (formatType) {
53
+ result.formatType = formatType;
54
+ }
55
+ }
56
+ return result;
57
+ }
58
+ /**
59
+ * Determines the content type of the response
60
+ *
61
+ * @param rawText - Raw text content
62
+ * @param parsedContent - Parsed content
63
+ * @returns Content type classification
64
+ */
65
+ determineContentType(rawText, parsedContent) {
66
+ // Empty if no content at all
67
+ if (!rawText && (parsedContent == null || parsedContent === '')) {
68
+ return 'empty';
69
+ }
70
+ // Object if parsed content is a non-array object
71
+ if (parsedContent != null && typeof parsedContent === 'object' && !Array.isArray(parsedContent)) {
72
+ return 'object';
73
+ }
74
+ // Text if we have raw text (or parsed content is a string/array)
75
+ if (rawText && rawText.trim().length > 0) {
76
+ return 'text';
77
+ }
78
+ // Default to empty
79
+ return 'empty';
80
+ }
81
+ /**
82
+ * Updates object type definitions
83
+ *
84
+ * @param definitions - New object type definitions
85
+ */
86
+ updateObjectTypeDefinitions(definitions) {
87
+ if (definitions.length > 0) {
88
+ this.objectDetector = new ObjectTypeDetector({
89
+ objectTypeDefinitions: definitions,
90
+ minConfidenceThreshold: 0.5
91
+ });
92
+ }
93
+ else {
94
+ this.objectDetector = undefined;
95
+ }
96
+ }
97
+ }