illuma-agents 1.0.38 → 1.0.39

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 (46) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +45 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +2 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +98 -0
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +6 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/cache.cjs +140 -47
  10. package/dist/cjs/messages/cache.cjs.map +1 -1
  11. package/dist/cjs/schemas/validate.cjs +173 -0
  12. package/dist/cjs/schemas/validate.cjs.map +1 -0
  13. package/dist/esm/agents/AgentContext.mjs +45 -2
  14. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  15. package/dist/esm/common/enum.mjs +2 -0
  16. package/dist/esm/common/enum.mjs.map +1 -1
  17. package/dist/esm/graphs/Graph.mjs +98 -0
  18. package/dist/esm/graphs/Graph.mjs.map +1 -1
  19. package/dist/esm/main.mjs +1 -0
  20. package/dist/esm/main.mjs.map +1 -1
  21. package/dist/esm/messages/cache.mjs +140 -47
  22. package/dist/esm/messages/cache.mjs.map +1 -1
  23. package/dist/esm/schemas/validate.mjs +167 -0
  24. package/dist/esm/schemas/validate.mjs.map +1 -0
  25. package/dist/types/agents/AgentContext.d.ts +19 -1
  26. package/dist/types/common/enum.d.ts +2 -0
  27. package/dist/types/graphs/Graph.d.ts +6 -0
  28. package/dist/types/index.d.ts +1 -0
  29. package/dist/types/messages/cache.d.ts +4 -1
  30. package/dist/types/schemas/index.d.ts +1 -0
  31. package/dist/types/schemas/validate.d.ts +36 -0
  32. package/dist/types/types/graph.d.ts +69 -0
  33. package/package.json +2 -2
  34. package/src/agents/AgentContext.test.ts +312 -0
  35. package/src/agents/AgentContext.ts +56 -0
  36. package/src/common/enum.ts +2 -0
  37. package/src/graphs/Graph.ts +150 -0
  38. package/src/index.ts +3 -0
  39. package/src/messages/cache.test.ts +51 -6
  40. package/src/messages/cache.ts +149 -122
  41. package/src/schemas/index.ts +2 -0
  42. package/src/schemas/validate.test.ts +358 -0
  43. package/src/schemas/validate.ts +238 -0
  44. package/src/specs/cache.simple.test.ts +396 -0
  45. package/src/types/graph.test.ts +183 -0
  46. package/src/types/graph.ts +71 -0
@@ -0,0 +1,358 @@
1
+ // src/schemas/validate.test.ts
2
+ import {
3
+ validateStructuredOutput,
4
+ createValidationErrorMessage,
5
+ isValidJsonSchema,
6
+ normalizeJsonSchema,
7
+ } from './validate';
8
+ import type { StructuredOutputConfig } from '@/types';
9
+
10
+ describe('validateStructuredOutput', () => {
11
+ const simpleObjectSchema = {
12
+ type: 'object',
13
+ properties: {
14
+ name: { type: 'string' },
15
+ age: { type: 'number' },
16
+ },
17
+ required: ['name'],
18
+ };
19
+
20
+ describe('basic validation', () => {
21
+ it('should validate a correct object', () => {
22
+ const result = validateStructuredOutput(
23
+ { name: 'John', age: 30 },
24
+ simpleObjectSchema
25
+ );
26
+ expect(result.success).toBe(true);
27
+ expect(result.data).toEqual({ name: 'John', age: 30 });
28
+ expect(result.error).toBeUndefined();
29
+ });
30
+
31
+ it('should validate an object with only required fields', () => {
32
+ const result = validateStructuredOutput(
33
+ { name: 'Jane' },
34
+ simpleObjectSchema
35
+ );
36
+ expect(result.success).toBe(true);
37
+ expect(result.data).toEqual({ name: 'Jane' });
38
+ });
39
+
40
+ it('should fail when required field is missing', () => {
41
+ const result = validateStructuredOutput({ age: 25 }, simpleObjectSchema);
42
+ expect(result.success).toBe(false);
43
+ expect(result.error).toContain('missing required property \'name\'');
44
+ expect(result.raw).toEqual({ age: 25 });
45
+ });
46
+
47
+ it('should fail when type is incorrect', () => {
48
+ const result = validateStructuredOutput(
49
+ { name: 123 },
50
+ simpleObjectSchema
51
+ );
52
+ expect(result.success).toBe(false);
53
+ expect(result.error).toContain('expected string');
54
+ });
55
+ });
56
+
57
+ describe('string input parsing', () => {
58
+ it('should parse valid JSON string input', () => {
59
+ const jsonString = '{"name": "Alice", "age": 28}';
60
+ const result = validateStructuredOutput(jsonString, simpleObjectSchema);
61
+ expect(result.success).toBe(true);
62
+ expect(result.data).toEqual({ name: 'Alice', age: 28 });
63
+ });
64
+
65
+ it('should fail on invalid JSON string', () => {
66
+ const invalidJson = '{ name: "Bob" }'; // Missing quotes around key
67
+ const result = validateStructuredOutput(invalidJson, simpleObjectSchema);
68
+ expect(result.success).toBe(false);
69
+ expect(result.error).toContain('Failed to parse output');
70
+ });
71
+ });
72
+
73
+ describe('type validation', () => {
74
+ it('should validate string type when passed as object property', () => {
75
+ // String values at root level get parsed as JSON first, so test nested
76
+ const schema = {
77
+ type: 'object',
78
+ properties: {
79
+ value: { type: 'string' },
80
+ },
81
+ };
82
+ expect(validateStructuredOutput({ value: 'hello' }, schema).success).toBe(
83
+ true
84
+ );
85
+ expect(validateStructuredOutput({ value: 123 }, schema).success).toBe(
86
+ false
87
+ );
88
+ });
89
+
90
+ it('should validate number type when passed as object property', () => {
91
+ const schema = {
92
+ type: 'object',
93
+ properties: {
94
+ value: { type: 'number' },
95
+ },
96
+ };
97
+ expect(validateStructuredOutput({ value: 42 }, schema).success).toBe(
98
+ true
99
+ );
100
+ expect(validateStructuredOutput({ value: '42' }, schema).success).toBe(
101
+ false
102
+ );
103
+ });
104
+
105
+ it('should validate boolean type when passed as object property', () => {
106
+ const schema = {
107
+ type: 'object',
108
+ properties: {
109
+ value: { type: 'boolean' },
110
+ },
111
+ };
112
+ expect(validateStructuredOutput({ value: true }, schema).success).toBe(
113
+ true
114
+ );
115
+ expect(validateStructuredOutput({ value: false }, schema).success).toBe(
116
+ true
117
+ );
118
+ expect(validateStructuredOutput({ value: 'true' }, schema).success).toBe(
119
+ false
120
+ );
121
+ });
122
+
123
+ it('should validate array type', () => {
124
+ const schema = { type: 'array', items: { type: 'string' } };
125
+ expect(validateStructuredOutput(['a', 'b'], schema).success).toBe(true);
126
+ expect(validateStructuredOutput('not an array', schema).success).toBe(
127
+ false
128
+ );
129
+ });
130
+
131
+ it('should validate object type', () => {
132
+ const schema = { type: 'object' };
133
+ expect(validateStructuredOutput({}, schema).success).toBe(true);
134
+ expect(validateStructuredOutput('not an object', schema).success).toBe(
135
+ false
136
+ );
137
+ });
138
+ });
139
+
140
+ describe('nested object validation', () => {
141
+ const nestedSchema = {
142
+ type: 'object',
143
+ properties: {
144
+ user: {
145
+ type: 'object',
146
+ properties: {
147
+ name: { type: 'string' },
148
+ email: { type: 'string' },
149
+ },
150
+ required: ['name'],
151
+ },
152
+ active: { type: 'boolean' },
153
+ },
154
+ required: ['user'],
155
+ };
156
+
157
+ it('should validate correct nested object', () => {
158
+ const result = validateStructuredOutput(
159
+ { user: { name: 'John', email: 'john@example.com' }, active: true },
160
+ nestedSchema
161
+ );
162
+ expect(result.success).toBe(true);
163
+ });
164
+
165
+ it('should fail on missing nested required field', () => {
166
+ const result = validateStructuredOutput(
167
+ { user: { email: 'john@example.com' } },
168
+ nestedSchema
169
+ );
170
+ expect(result.success).toBe(false);
171
+ expect(result.error).toContain('missing required property \'name\'');
172
+ });
173
+
174
+ it('should fail on incorrect nested type', () => {
175
+ const result = validateStructuredOutput(
176
+ { user: { name: 123 } },
177
+ nestedSchema
178
+ );
179
+ expect(result.success).toBe(false);
180
+ expect(result.error).toContain('expected string');
181
+ });
182
+ });
183
+
184
+ describe('array item validation', () => {
185
+ const arraySchema = {
186
+ type: 'array',
187
+ items: {
188
+ type: 'object',
189
+ properties: {
190
+ id: { type: 'number' },
191
+ value: { type: 'string' },
192
+ },
193
+ required: ['id'],
194
+ },
195
+ };
196
+
197
+ it('should validate correct array items', () => {
198
+ const result = validateStructuredOutput(
199
+ [
200
+ { id: 1, value: 'one' },
201
+ { id: 2, value: 'two' },
202
+ ],
203
+ arraySchema
204
+ );
205
+ expect(result.success).toBe(true);
206
+ });
207
+
208
+ it('should fail on incorrect array item type', () => {
209
+ const result = validateStructuredOutput(
210
+ [{ id: 'not a number', value: 'one' }],
211
+ arraySchema
212
+ );
213
+ expect(result.success).toBe(false);
214
+ expect(result.error).toContain('expected number');
215
+ });
216
+
217
+ it('should fail on missing required field in array item', () => {
218
+ const result = validateStructuredOutput(
219
+ [{ value: 'missing id' }],
220
+ arraySchema
221
+ );
222
+ expect(result.success).toBe(false);
223
+ expect(result.error).toContain('missing required property \'id\'');
224
+ });
225
+ });
226
+
227
+ describe('enum validation', () => {
228
+ it('should validate valid enum value in object property', () => {
229
+ const schema = {
230
+ type: 'object',
231
+ properties: {
232
+ color: { type: 'string', enum: ['red', 'green', 'blue'] },
233
+ },
234
+ };
235
+ const result = validateStructuredOutput({ color: 'red' }, schema);
236
+ expect(result.success).toBe(true);
237
+ });
238
+
239
+ it('should fail on invalid enum value in object property', () => {
240
+ const schema = {
241
+ type: 'object',
242
+ properties: {
243
+ color: { type: 'string', enum: ['red', 'green', 'blue'] },
244
+ },
245
+ };
246
+ const result = validateStructuredOutput({ color: 'yellow' }, schema);
247
+ expect(result.success).toBe(false);
248
+ expect(result.error).toContain('not in enum');
249
+ });
250
+ });
251
+ });
252
+
253
+ describe('createValidationErrorMessage', () => {
254
+ it('should return custom message when provided', () => {
255
+ const result = { success: false, error: 'Some error' };
256
+ const message = createValidationErrorMessage(
257
+ result,
258
+ 'Custom error message'
259
+ );
260
+ expect(message).toBe('Custom error message');
261
+ });
262
+
263
+ it('should create message from error when no custom message', () => {
264
+ const result = { success: false, error: 'Missing required field' };
265
+ const message = createValidationErrorMessage(result);
266
+ expect(message).toContain('Missing required field');
267
+ expect(message).toContain('did not match the expected schema');
268
+ });
269
+ });
270
+
271
+ describe('isValidJsonSchema', () => {
272
+ it('should return true for schema with type', () => {
273
+ expect(isValidJsonSchema({ type: 'object' })).toBe(true);
274
+ expect(isValidJsonSchema({ type: 'string' })).toBe(true);
275
+ });
276
+
277
+ it('should return true for schema with properties', () => {
278
+ expect(
279
+ isValidJsonSchema({ properties: { name: { type: 'string' } } })
280
+ ).toBe(true);
281
+ });
282
+
283
+ it('should return true for schema with $schema', () => {
284
+ expect(
285
+ isValidJsonSchema({ $schema: 'http://json-schema.org/draft-07/schema#' })
286
+ ).toBe(true);
287
+ });
288
+
289
+ it('should return false for non-object values', () => {
290
+ expect(isValidJsonSchema(null)).toBe(false);
291
+ expect(isValidJsonSchema(undefined)).toBe(false);
292
+ expect(isValidJsonSchema('string')).toBe(false);
293
+ expect(isValidJsonSchema(123)).toBe(false);
294
+ });
295
+
296
+ it('should return false for empty object', () => {
297
+ expect(isValidJsonSchema({})).toBe(false);
298
+ });
299
+ });
300
+
301
+ describe('normalizeJsonSchema', () => {
302
+ it('should add type: object when properties exist', () => {
303
+ const schema = { properties: { name: { type: 'string' } } };
304
+ const normalized = normalizeJsonSchema(schema);
305
+ expect(normalized.type).toBe('object');
306
+ });
307
+
308
+ it('should not override existing type', () => {
309
+ const schema = { type: 'array', items: { type: 'string' } };
310
+ const normalized = normalizeJsonSchema(schema);
311
+ expect(normalized.type).toBe('array');
312
+ });
313
+
314
+ it('should add title from config name', () => {
315
+ const schema = { type: 'object' };
316
+ const config: StructuredOutputConfig = { schema: {}, name: 'MySchema' };
317
+ const normalized = normalizeJsonSchema(schema, config);
318
+ expect(normalized.title).toBe('MySchema');
319
+ });
320
+
321
+ it('should not override existing title', () => {
322
+ const schema = { type: 'object', title: 'ExistingTitle' };
323
+ const config: StructuredOutputConfig = { schema: {}, name: 'NewTitle' };
324
+ const normalized = normalizeJsonSchema(schema, config);
325
+ expect(normalized.title).toBe('ExistingTitle');
326
+ });
327
+
328
+ it('should add description from config', () => {
329
+ const schema = { type: 'object' };
330
+ const config: StructuredOutputConfig = {
331
+ schema: {},
332
+ description: 'My description',
333
+ };
334
+ const normalized = normalizeJsonSchema(schema, config);
335
+ expect(normalized.description).toBe('My description');
336
+ });
337
+
338
+ it('should set additionalProperties: false in strict mode', () => {
339
+ const schema = { type: 'object' };
340
+ const config: StructuredOutputConfig = { schema: {}, strict: true };
341
+ const normalized = normalizeJsonSchema(schema, config);
342
+ expect(normalized.additionalProperties).toBe(false);
343
+ });
344
+
345
+ it('should preserve existing additionalProperties value', () => {
346
+ const schema = { type: 'object', additionalProperties: true };
347
+ const config: StructuredOutputConfig = { schema: {}, strict: true };
348
+ const normalized = normalizeJsonSchema(schema, config);
349
+ expect(normalized.additionalProperties).toBe(true);
350
+ });
351
+
352
+ it('should not modify additionalProperties when strict is false', () => {
353
+ const schema = { type: 'object' };
354
+ const config: StructuredOutputConfig = { schema: {}, strict: false };
355
+ const normalized = normalizeJsonSchema(schema, config);
356
+ expect(normalized.additionalProperties).toBeUndefined();
357
+ });
358
+ });
@@ -0,0 +1,238 @@
1
+ // src/schemas/validate.ts
2
+ import { z } from 'zod';
3
+ import type * as t from '@/types';
4
+
5
+ /**
6
+ * Validation result from structured output
7
+ */
8
+ export interface ValidationResult<T = Record<string, unknown>> {
9
+ success: boolean;
10
+ data?: T;
11
+ error?: string;
12
+ raw?: unknown;
13
+ }
14
+
15
+ /**
16
+ * Validates structured output against a JSON Schema.
17
+ *
18
+ * @param output - The output to validate
19
+ * @param schema - JSON Schema to validate against
20
+ * @returns Validation result with success flag and data or error
21
+ */
22
+ export function validateStructuredOutput(
23
+ output: unknown,
24
+ schema: Record<string, unknown>
25
+ ): ValidationResult {
26
+ try {
27
+ // Parse output if it's a string
28
+ const data = typeof output === 'string' ? JSON.parse(output) : output;
29
+
30
+ // Basic JSON Schema validation
31
+ const errors = validateAgainstJsonSchema(data, schema);
32
+
33
+ if (errors.length > 0) {
34
+ return {
35
+ success: false,
36
+ error: `Validation failed: ${errors.join('; ')}`,
37
+ raw: data,
38
+ };
39
+ }
40
+
41
+ return {
42
+ success: true,
43
+ data: data as Record<string, unknown>,
44
+ };
45
+ } catch (e) {
46
+ return {
47
+ success: false,
48
+ error: `Failed to parse output: ${(e as Error).message}`,
49
+ raw: output,
50
+ };
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Validates data against a JSON Schema (simplified implementation).
56
+ * For complex schemas, consider using ajv or similar library.
57
+ */
58
+ function validateAgainstJsonSchema(
59
+ data: unknown,
60
+ schema: Record<string, unknown>,
61
+ path = ''
62
+ ): string[] {
63
+ const errors: string[] = [];
64
+
65
+ if (schema.type === 'object' && typeof data !== 'object') {
66
+ errors.push(`${path || 'root'}: expected object, got ${typeof data}`);
67
+ return errors;
68
+ }
69
+
70
+ if (schema.type === 'array' && !Array.isArray(data)) {
71
+ errors.push(`${path || 'root'}: expected array, got ${typeof data}`);
72
+ return errors;
73
+ }
74
+
75
+ if (schema.type === 'string' && typeof data !== 'string') {
76
+ errors.push(`${path || 'root'}: expected string, got ${typeof data}`);
77
+ return errors;
78
+ }
79
+
80
+ if (schema.type === 'number' && typeof data !== 'number') {
81
+ errors.push(`${path || 'root'}: expected number, got ${typeof data}`);
82
+ return errors;
83
+ }
84
+
85
+ if (schema.type === 'boolean' && typeof data !== 'boolean') {
86
+ errors.push(`${path || 'root'}: expected boolean, got ${typeof data}`);
87
+ return errors;
88
+ }
89
+
90
+ // Validate required properties
91
+ if (
92
+ schema.type === 'object' &&
93
+ Array.isArray(schema.required) &&
94
+ typeof data === 'object' &&
95
+ data !== null
96
+ ) {
97
+ for (const requiredProp of schema.required as string[]) {
98
+ if (!(requiredProp in data)) {
99
+ errors.push(
100
+ `${path || 'root'}: missing required property '${requiredProp}'`
101
+ );
102
+ }
103
+ }
104
+ }
105
+
106
+ // Validate nested properties
107
+ if (
108
+ schema.type === 'object' &&
109
+ schema.properties &&
110
+ typeof data === 'object' &&
111
+ data !== null
112
+ ) {
113
+ const properties = schema.properties as Record<
114
+ string,
115
+ Record<string, unknown>
116
+ >;
117
+ for (const [key, propSchema] of Object.entries(properties)) {
118
+ if (key in data) {
119
+ const nestedErrors = validateAgainstJsonSchema(
120
+ (data as Record<string, unknown>)[key],
121
+ propSchema,
122
+ path ? `${path}.${key}` : key
123
+ );
124
+ errors.push(...nestedErrors);
125
+ }
126
+ }
127
+ }
128
+
129
+ // Validate array items
130
+ if (schema.type === 'array' && schema.items && Array.isArray(data)) {
131
+ const itemSchema = schema.items as Record<string, unknown>;
132
+ for (let i = 0; i < data.length; i++) {
133
+ const nestedErrors = validateAgainstJsonSchema(
134
+ data[i],
135
+ itemSchema,
136
+ `${path || 'root'}[${i}]`
137
+ );
138
+ errors.push(...nestedErrors);
139
+ }
140
+ }
141
+
142
+ // Validate enum values
143
+ if (schema.enum && Array.isArray(schema.enum)) {
144
+ if (!schema.enum.includes(data)) {
145
+ errors.push(
146
+ `${path || 'root'}: value '${data}' not in enum [${(schema.enum as unknown[]).join(', ')}]`
147
+ );
148
+ }
149
+ }
150
+
151
+ return errors;
152
+ }
153
+
154
+ /**
155
+ * Converts a Zod schema to JSON Schema format.
156
+ * This is a simplified converter for common types.
157
+ */
158
+ export function zodToJsonSchema(zodSchema: z.ZodType): Record<string, unknown> {
159
+ // Use the zod-to-json-schema library if available
160
+ // For now, provide a basic implementation
161
+ try {
162
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
163
+ const { zodToJsonSchema: convert } = require('zod-to-json-schema');
164
+ return convert(zodSchema) as Record<string, unknown>;
165
+ } catch {
166
+ // Fallback: return a generic object schema
167
+ return {
168
+ type: 'object',
169
+ additionalProperties: true,
170
+ };
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Creates a structured output error message for retry.
176
+ */
177
+ export function createValidationErrorMessage(
178
+ result: ValidationResult,
179
+ customMessage?: string
180
+ ): string {
181
+ if (customMessage) {
182
+ return customMessage;
183
+ }
184
+
185
+ return `The response did not match the expected schema. Error: ${result.error}. Please try again and ensure your response exactly matches the required format.`;
186
+ }
187
+
188
+ /**
189
+ * Checks if a value is a valid JSON Schema object.
190
+ */
191
+ export function isValidJsonSchema(
192
+ value: unknown
193
+ ): value is Record<string, unknown> {
194
+ if (typeof value !== 'object' || value === null) {
195
+ return false;
196
+ }
197
+
198
+ const schema = value as Record<string, unknown>;
199
+
200
+ // Basic check: must have a type or properties
201
+ return (
202
+ typeof schema.type === 'string' ||
203
+ typeof schema.properties === 'object' ||
204
+ typeof schema.$schema === 'string'
205
+ );
206
+ }
207
+
208
+ /**
209
+ * Normalizes a JSON Schema by adding defaults and cleaning up.
210
+ */
211
+ export function normalizeJsonSchema(
212
+ schema: Record<string, unknown>,
213
+ config?: t.StructuredOutputConfig
214
+ ): Record<string, unknown> {
215
+ const normalized = { ...schema };
216
+
217
+ // Ensure type is set
218
+ if (!normalized.type && normalized.properties) {
219
+ normalized.type = 'object';
220
+ }
221
+
222
+ // Add title from config name
223
+ if (config?.name && !normalized.title) {
224
+ normalized.title = config.name;
225
+ }
226
+
227
+ // Add description from config
228
+ if (config?.description && !normalized.description) {
229
+ normalized.description = config.description;
230
+ }
231
+
232
+ // Enable additionalProperties: false for strict mode
233
+ if (config?.strict !== false && normalized.type === 'object') {
234
+ normalized.additionalProperties = normalized.additionalProperties ?? false;
235
+ }
236
+
237
+ return normalized;
238
+ }