ai-workflows 1.1.0 → 2.0.0

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 (55) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/.turbo/turbo-test.log +104 -0
  3. package/README.md +285 -24
  4. package/dist/context.d.ts +26 -0
  5. package/dist/context.d.ts.map +1 -0
  6. package/dist/context.js +84 -0
  7. package/dist/context.js.map +1 -0
  8. package/dist/every.d.ts +67 -0
  9. package/dist/every.d.ts.map +1 -0
  10. package/dist/every.js +268 -0
  11. package/dist/every.js.map +1 -0
  12. package/dist/index.d.ts +68 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +72 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/on.d.ts +49 -0
  17. package/dist/on.d.ts.map +1 -0
  18. package/dist/on.js +80 -0
  19. package/dist/on.js.map +1 -0
  20. package/dist/send.d.ts +59 -0
  21. package/dist/send.d.ts.map +1 -0
  22. package/dist/send.js +112 -0
  23. package/dist/send.js.map +1 -0
  24. package/dist/types.d.ts +229 -0
  25. package/dist/types.d.ts.map +1 -0
  26. package/dist/types.js +5 -0
  27. package/dist/types.js.map +1 -0
  28. package/dist/workflow.d.ts +79 -0
  29. package/dist/workflow.d.ts.map +1 -0
  30. package/dist/workflow.js +456 -0
  31. package/dist/workflow.js.map +1 -0
  32. package/package.json +25 -70
  33. package/src/context.ts +108 -0
  34. package/src/every.ts +299 -0
  35. package/src/index.ts +106 -0
  36. package/src/on.ts +100 -0
  37. package/src/send.ts +131 -0
  38. package/src/types.ts +244 -0
  39. package/src/workflow.ts +569 -0
  40. package/test/context.test.ts +151 -0
  41. package/test/every.test.ts +361 -0
  42. package/test/on.test.ts +100 -0
  43. package/test/send.test.ts +118 -0
  44. package/test/workflow.test.ts +288 -0
  45. package/tsconfig.json +9 -0
  46. package/vitest.config.ts +8 -0
  47. package/LICENSE +0 -21
  48. package/dist/scripts/generate-types.d.ts +0 -1
  49. package/dist/scripts/generate-types.js +0 -57
  50. package/dist/src/ai-proxy.d.ts +0 -5
  51. package/dist/src/ai-proxy.js +0 -94
  52. package/dist/src/index.d.ts +0 -9
  53. package/dist/src/index.js +0 -11
  54. package/dist/src/index.test.d.ts +0 -1
  55. package/dist/src/index.test.js +0 -35
@@ -0,0 +1,288 @@
1
+ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'
2
+ import { Workflow, createTestContext, parseEvent } from '../src/workflow.js'
3
+ import { clearEventHandlers } from '../src/on.js'
4
+ import { clearScheduleHandlers } from '../src/every.js'
5
+
6
+ describe('Workflow - unified $ API', () => {
7
+ beforeEach(() => {
8
+ clearEventHandlers()
9
+ clearScheduleHandlers()
10
+ vi.useFakeTimers()
11
+ })
12
+
13
+ afterEach(() => {
14
+ vi.useRealTimers()
15
+ })
16
+
17
+ describe('Workflow()', () => {
18
+ it('should create a workflow with $ context', () => {
19
+ const workflow = Workflow($ => {
20
+ // Just accessing $ to verify it works
21
+ expect($).toBeDefined()
22
+ expect($.on).toBeDefined()
23
+ expect($.every).toBeDefined()
24
+ expect($.send).toBeDefined()
25
+ expect($.log).toBeDefined()
26
+ expect($.get).toBeDefined()
27
+ expect($.set).toBeDefined()
28
+ expect($.getState).toBeDefined()
29
+ })
30
+
31
+ expect(workflow).toBeDefined()
32
+ expect(workflow.$).toBeDefined()
33
+ expect(workflow.send).toBeDefined()
34
+ expect(workflow.start).toBeDefined()
35
+ expect(workflow.stop).toBeDefined()
36
+ })
37
+
38
+ it('should capture event handlers registered via $.on', () => {
39
+ const workflow = Workflow($ => {
40
+ $.on.Customer.created(() => {})
41
+ $.on.Order.completed(() => {})
42
+ })
43
+
44
+ expect(workflow.definition.events).toHaveLength(2)
45
+ expect(workflow.definition.events[0]?.noun).toBe('Customer')
46
+ expect(workflow.definition.events[0]?.event).toBe('created')
47
+ expect(workflow.definition.events[1]?.noun).toBe('Order')
48
+ expect(workflow.definition.events[1]?.event).toBe('completed')
49
+ })
50
+
51
+ it('should capture schedule handlers registered via $.every', () => {
52
+ const workflow = Workflow($ => {
53
+ $.every.hour(() => {})
54
+ $.every.Monday.at9am(() => {})
55
+ })
56
+
57
+ expect(workflow.definition.schedules).toHaveLength(2)
58
+ })
59
+
60
+ it('should capture function source code', () => {
61
+ const workflow = Workflow($ => {
62
+ $.on.Test.event(async (data, ctx) => {
63
+ ctx.log('Test event', data)
64
+ })
65
+ })
66
+
67
+ // Source code is captured (variable names may be minified)
68
+ expect(workflow.definition.events[0]?.source).toBeDefined()
69
+ expect(workflow.definition.events[0]?.source.length).toBeGreaterThan(0)
70
+ expect(workflow.definition.events[0]?.source).toContain('Test event')
71
+ })
72
+
73
+ it('should deliver events to registered handlers', async () => {
74
+ const handler = vi.fn()
75
+
76
+ const workflow = Workflow($ => {
77
+ $.on.Customer.created(handler)
78
+ })
79
+
80
+ await workflow.start()
81
+ await workflow.send('Customer.created', { id: '123', name: 'John' })
82
+
83
+ expect(handler).toHaveBeenCalledTimes(1)
84
+ expect(handler).toHaveBeenCalledWith(
85
+ { id: '123', name: 'John' },
86
+ expect.objectContaining({
87
+ send: expect.any(Function),
88
+ log: expect.any(Function),
89
+ })
90
+ )
91
+ })
92
+
93
+ it('should allow chained event sending from handlers', async () => {
94
+ const welcomeHandler = vi.fn()
95
+
96
+ const workflow = Workflow($ => {
97
+ $.on.Customer.created(async (customer, $) => {
98
+ await $.send('Email.welcome', { to: customer.email })
99
+ })
100
+
101
+ $.on.Email.welcome(welcomeHandler)
102
+ })
103
+
104
+ await workflow.start()
105
+ await workflow.send('Customer.created', { name: 'John', email: 'john@example.com' })
106
+
107
+ expect(welcomeHandler).toHaveBeenCalledWith(
108
+ { to: 'john@example.com' },
109
+ expect.anything()
110
+ )
111
+ })
112
+
113
+ it('should track events in state history', async () => {
114
+ const workflow = Workflow($ => {
115
+ $.on.Test.event(() => {})
116
+ })
117
+
118
+ await workflow.start()
119
+ await workflow.send('Test.event', { data: 'test' })
120
+
121
+ expect(workflow.state.history).toHaveLength(1)
122
+ expect(workflow.state.history[0]).toMatchObject({
123
+ type: 'event',
124
+ name: 'Test.event',
125
+ data: { data: 'test' },
126
+ })
127
+ })
128
+
129
+ it('should trigger schedule handlers', async () => {
130
+ const handler = vi.fn()
131
+
132
+ const workflow = Workflow($ => {
133
+ $.every.seconds(1)(handler)
134
+ })
135
+
136
+ await workflow.start()
137
+ await vi.advanceTimersByTimeAsync(1000)
138
+
139
+ expect(handler).toHaveBeenCalledTimes(1)
140
+
141
+ await vi.advanceTimersByTimeAsync(1000)
142
+ expect(handler).toHaveBeenCalledTimes(2)
143
+
144
+ await workflow.stop()
145
+ })
146
+
147
+ it('should stop schedule handlers on stop', async () => {
148
+ const handler = vi.fn()
149
+
150
+ const workflow = Workflow($ => {
151
+ $.every.seconds(1)(handler)
152
+ })
153
+
154
+ await workflow.start()
155
+ await vi.advanceTimersByTimeAsync(1000)
156
+ expect(handler).toHaveBeenCalledTimes(1)
157
+
158
+ await workflow.stop()
159
+ await vi.advanceTimersByTimeAsync(5000)
160
+ expect(handler).toHaveBeenCalledTimes(1)
161
+ })
162
+
163
+ it('should support $.set and $.get for context data', async () => {
164
+ const workflow = Workflow($ => {
165
+ $.on.Test.set(async (data, $) => {
166
+ $.set('value', data.value)
167
+ })
168
+
169
+ $.on.Test.get(async (_, $) => {
170
+ const value = $.get<number>('value')
171
+ $.log('Got value', value)
172
+ })
173
+ })
174
+
175
+ await workflow.start()
176
+ await workflow.send('Test.set', { value: 42 })
177
+
178
+ expect(workflow.state.context.value).toBe(42)
179
+ expect(workflow.$.get('value')).toBe(42)
180
+ })
181
+
182
+ it('should use initial context from options', () => {
183
+ const workflow = Workflow(
184
+ $ => {},
185
+ { context: { counter: 100 } }
186
+ )
187
+
188
+ expect(workflow.state.context.counter).toBe(100)
189
+ })
190
+ })
191
+
192
+ describe('parseEvent', () => {
193
+ it('should parse valid event strings', () => {
194
+ expect(parseEvent('Customer.created')).toEqual({
195
+ noun: 'Customer',
196
+ event: 'created',
197
+ })
198
+ })
199
+
200
+ it('should return null for invalid event strings', () => {
201
+ expect(parseEvent('invalid')).toBeNull()
202
+ expect(parseEvent('too.many.parts')).toBeNull()
203
+ expect(parseEvent('')).toBeNull()
204
+ })
205
+ })
206
+
207
+ describe('createTestContext', () => {
208
+ it('should create a $ context for testing', () => {
209
+ const $ = createTestContext()
210
+
211
+ expect($.send).toBeDefined()
212
+ expect($.on).toBeDefined()
213
+ expect($.every).toBeDefined()
214
+ expect($.log).toBeDefined()
215
+ expect($.get).toBeDefined()
216
+ expect($.set).toBeDefined()
217
+ expect($.getState).toBeDefined()
218
+ expect($.emittedEvents).toBeDefined()
219
+ })
220
+
221
+ it('should track emitted events', async () => {
222
+ const $ = createTestContext()
223
+
224
+ await $.send('Test.event1', { a: 1 })
225
+ await $.send('Test.event2', { b: 2 })
226
+
227
+ expect($.emittedEvents).toHaveLength(2)
228
+ expect($.emittedEvents[0]).toEqual({ event: 'Test.event1', data: { a: 1 } })
229
+ expect($.emittedEvents[1]).toEqual({ event: 'Test.event2', data: { b: 2 } })
230
+ })
231
+
232
+ it('should support get/set', () => {
233
+ const $ = createTestContext()
234
+
235
+ $.set('key', 'value')
236
+ expect($.get('key')).toBe('value')
237
+ })
238
+ })
239
+
240
+ describe('$.every patterns', () => {
241
+ it('should support $.every.hour', () => {
242
+ const workflow = Workflow($ => {
243
+ $.every.hour(() => {})
244
+ })
245
+
246
+ expect(workflow.definition.schedules[0]?.interval).toEqual({
247
+ type: 'cron',
248
+ expression: '0 * * * *',
249
+ natural: 'hour',
250
+ })
251
+ })
252
+
253
+ it('should support $.every.Monday.at9am', () => {
254
+ const workflow = Workflow($ => {
255
+ $.every.Monday.at9am(() => {})
256
+ })
257
+
258
+ expect(workflow.definition.schedules[0]?.interval).toEqual({
259
+ type: 'cron',
260
+ expression: '0 9 * * 1',
261
+ natural: 'Monday.at9am',
262
+ })
263
+ })
264
+
265
+ it('should support $.every.minutes(30)', () => {
266
+ const workflow = Workflow($ => {
267
+ $.every.minutes(30)(() => {})
268
+ })
269
+
270
+ expect(workflow.definition.schedules[0]?.interval).toEqual({
271
+ type: 'minute',
272
+ value: 30,
273
+ natural: '30 minutes',
274
+ })
275
+ })
276
+
277
+ it('should support $.every("natural language")', () => {
278
+ const workflow = Workflow($ => {
279
+ $.every('first Monday of the month', () => {})
280
+ })
281
+
282
+ expect(workflow.definition.schedules[0]?.interval).toEqual({
283
+ type: 'natural',
284
+ description: 'first Monday of the month',
285
+ })
286
+ })
287
+ })
288
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
9
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ include: ['test/**/*.test.ts'],
7
+ },
8
+ })
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 AI Primitives
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1 +0,0 @@
1
- export {};
@@ -1,57 +0,0 @@
1
- import { readFileSync, writeFileSync, readdirSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname, resolve } from 'node:path';
4
- import matter from 'gray-matter';
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- const aiDir = resolve(process.cwd(), 'ai');
8
- const outputFile = resolve(process.cwd(), 'src/ai-types.d.ts');
9
- /**
10
- * Converts an MDX output type definition to a TypeScript type
11
- * Handles enum types (separated by |) and string types
12
- */
13
- function convertOutputTypeToTS(type) {
14
- if (type.includes('|')) {
15
- // Handle enum types (e.g., "Article | BlogPosting | Thing")
16
- return type.split('|').map(t => `'${t.trim()}'`).join(' | ');
17
- }
18
- return 'string';
19
- }
20
- /**
21
- * Generates TypeScript type definitions from MDX files
22
- */
23
- function generateTypes() {
24
- const mdxFiles = readdirSync(aiDir).filter(file => file.endsWith('.mdx'));
25
- let typeDefinitions = `// Generated TypeScript definitions for AI methods
26
- // DO NOT EDIT DIRECTLY - Generated from MDX files in ai/
27
-
28
- declare const ai: {
29
- `;
30
- for (const file of mdxFiles) {
31
- const methodName = file.replace('.mdx', '');
32
- const content = readFileSync(resolve(aiDir, file), 'utf-8');
33
- const { data: frontmatter } = matter(content);
34
- if (!frontmatter.output?.type) {
35
- console.warn(`Warning: ${file} is missing output type definition`);
36
- continue;
37
- }
38
- const tsType = convertOutputTypeToTS(frontmatter.output.type);
39
- const description = frontmatter.output.description || 'No description provided';
40
- typeDefinitions += ` /**
41
- * ${description}
42
- * @param input The input data for the AI operation
43
- * @returns A promise that resolves to the generated output
44
- */
45
- ${methodName}(input: unknown): Promise<${tsType}>;
46
-
47
- `;
48
- }
49
- typeDefinitions += `}
50
-
51
- export { ai }
52
- `;
53
- writeFileSync(outputFile, typeDefinitions);
54
- console.log(`Generated type definitions at ${outputFile}`);
55
- }
56
- // Run the generator
57
- generateTypes();
@@ -1,5 +0,0 @@
1
- /**
2
- * The ai object is a Proxy that dynamically loads MDX files for each method call
3
- * Example: ai.summarize(ticket) will load ai/summarize.mdx and use its configuration
4
- */
5
- export declare const ai: {};
@@ -1,94 +0,0 @@
1
- import { readFileSync, existsSync } from 'fs';
2
- import path from 'path';
3
- import matter from 'gray-matter';
4
- import { z } from 'zod';
5
- import { OpenAI } from 'openai';
6
- const aiBasePath = path.resolve(process.cwd(), 'ai');
7
- const openai = new OpenAI({
8
- apiKey: process.env.OPENAI_API_KEY
9
- });
10
- // Schema for required MDX frontmatter
11
- const frontmatterSchema = z.object({
12
- model: z.string(),
13
- system: z.string(),
14
- output: z.object({
15
- type: z.string(),
16
- description: z.string()
17
- })
18
- });
19
- /**
20
- * Creates a Zod schema from an output definition in MDX frontmatter
21
- * Handles enum types (separated by |) and string types with descriptions
22
- * @param outputDef - The output definition from MDX frontmatter
23
- * @returns A Zod schema for validating the output
24
- */
25
- function createZodSchemaFromOutput(outputDef) {
26
- const { type, description } = outputDef;
27
- // Create schema based on output type
28
- const schema = type.includes('|')
29
- ? z.object({
30
- type: z.enum(type.split('|').map(t => t.trim())),
31
- description: z.string()
32
- })
33
- : z.object({
34
- type: z.string(),
35
- description: z.string()
36
- });
37
- return schema.describe(description);
38
- }
39
- /**
40
- * The ai object is a Proxy that dynamically loads MDX files for each method call
41
- * Example: ai.summarize(ticket) will load ai/summarize.mdx and use its configuration
42
- */
43
- export const ai = new Proxy({}, {
44
- get(_target, methodName) {
45
- return async (input) => {
46
- try {
47
- // Check if MDX file exists
48
- const mdxFile = path.join(aiBasePath, `${methodName}.mdx`);
49
- if (!existsSync(mdxFile)) {
50
- throw new Error(`No MDX file found for ai.${methodName}(). Create ${methodName}.mdx in the ai/ directory.`);
51
- }
52
- // Load and parse the MDX file
53
- const fileContent = readFileSync(mdxFile, 'utf-8');
54
- const { data: rawFrontmatter, content } = matter(fileContent);
55
- // Validate frontmatter against schema
56
- const frontmatter = frontmatterSchema.parse(rawFrontmatter);
57
- // Create Zod schema from output definition
58
- const outputSchema = createZodSchemaFromOutput(frontmatter.output);
59
- // Generate response using OpenAI
60
- const completion = await openai.chat.completions.create({
61
- model: frontmatter.model,
62
- messages: [
63
- { role: 'system', content: frontmatter.system },
64
- { role: 'user', content: `${content}\n\nInput: ${JSON.stringify(input, null, 2)}` }
65
- ],
66
- response_format: { type: 'json_object' },
67
- temperature: 0.7, // Add some creativity while maintaining structure
68
- });
69
- // Parse and validate the response
70
- let result;
71
- try {
72
- result = JSON.parse(completion.choices[0].message.content || '{}');
73
- }
74
- catch (error) {
75
- // Narrow error type for proper handling
76
- const parseError = error;
77
- throw new Error(`Failed to parse OpenAI response as JSON: ${parseError.message}`);
78
- }
79
- // Validate against our schema and return
80
- return outputSchema.parse(result);
81
- }
82
- catch (error) {
83
- // Enhance error messages for different types of failures
84
- if (error instanceof z.ZodError) {
85
- throw new Error(`Schema validation failed in ai.${methodName}(): ${error.errors.map(e => e.message).join(', ')}`);
86
- }
87
- else if (error instanceof Error) {
88
- throw new Error(`Error in ai.${methodName}(): ${error.message}`);
89
- }
90
- throw error;
91
- }
92
- };
93
- }
94
- });
@@ -1,9 +0,0 @@
1
- import { ai } from './ai-proxy.js';
2
- export { ai };
3
- /**
4
- * A placeholder function that adds two numbers
5
- * @param a First number
6
- * @param b Second number
7
- * @returns The sum of a and b
8
- */
9
- export declare function add(a: number, b: number): number;
package/dist/src/index.js DELETED
@@ -1,11 +0,0 @@
1
- import { ai } from './ai-proxy.js';
2
- export { ai };
3
- /**
4
- * A placeholder function that adds two numbers
5
- * @param a First number
6
- * @param b Second number
7
- * @returns The sum of a and b
8
- */
9
- export function add(a, b) {
10
- return a + b;
11
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,35 +0,0 @@
1
- import { describe, it, expect, beforeAll } from '@jest/globals';
2
- import { add, ai } from './index.js';
3
- import { mkdir, writeFile } from 'fs/promises';
4
- import path from 'path';
5
- describe('add', () => {
6
- it('should add two numbers correctly', () => {
7
- expect(add(2, 3)).toBe(5);
8
- expect(add(-1, 1)).toBe(0);
9
- expect(add(0, 0)).toBe(0);
10
- });
11
- });
12
- describe('ai', () => {
13
- beforeAll(async () => {
14
- // Create ai directory and test MDX file
15
- await mkdir(path.resolve(process.cwd(), 'ai'), { recursive: true });
16
- await writeFile(path.resolve(process.cwd(), 'ai/test.mdx'), `---
17
- model: gpt-3.5-turbo
18
- system: Test system prompt
19
- output:
20
- type: Article | BlogPosting
21
- description: Test description
22
- ---
23
-
24
- # Test MDX
25
-
26
- Test content`);
27
- });
28
- it('should handle AI method calls correctly', async () => {
29
- const result = await ai.test({ input: 'test' });
30
- expect(result).toEqual({
31
- type: 'Article',
32
- description: 'Test description'
33
- });
34
- });
35
- });