jsfe 0.4.0 → 0.5.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 (2) hide show
  1. package/README.md +216 -24
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm i jsfe
16
16
 
17
17
  ## Usage
18
18
 
19
- ```typescript
19
+ ```javascript
20
20
  import { WorkflowEngine } from "jsfe";
21
21
 
22
22
  // 1. Create the engine
@@ -36,8 +36,220 @@ const engine = new WorkflowEngine(
36
36
  // 2. Initialize a session for each user
37
37
  const sessionContext = engine.initSession(yourLogger, 'user-123', 'session-456');
38
38
 
39
- // 3. Process user input and assistant responses
40
- const result = await engine.updateActivity(contextEntry, sessionContext);
39
+ // 3. Plug-in the engine to process User message
40
+ const userEntry = {
41
+ role: 'user',
42
+ content: 'I need help with my account',
43
+ };
44
+ const result = await engine.updateActivity(userEntry, sessionContext);
45
+ if (result) {
46
+ // Intent detected and handled no need to proceed to normal response generation
47
+ return result;
48
+ }
49
+
50
+ // 4. Call your normal Generate reply process as usual
51
+ const reply = await yourConversationalReply(input);
52
+
53
+ // 5. Update the engine's context with the generated reply
54
+ const assistantEntry = {
55
+ role: 'assistant',
56
+ content: 'I can help you with your account. What specific issue are you experiencing?',
57
+ };
58
+ await engine.updateActivity(assistantEntry, sessionContext);
59
+
60
+ // Return the generated reply to the user
61
+ return reply;
62
+ ```
63
+
64
+ ## Engine Initialization Parameters
65
+
66
+ The WorkflowEngine constructor accepts the following parameters in order, each serving a specific purpose in the engine's operation:
67
+
68
+ **1. hostLogger** (Logger | null)
69
+ - **Purpose**: Primary logging interface for the host application
70
+ - **Requirements**: Must support `.debug()`, `.info()`, `.warn()`, `.error()` methods
71
+ - **Usage**: Engine uses this for all operational logging and debugging output
72
+ - **Example**: Winston, or custom logger implementation
73
+ - **Nullable**: Can be `null` to disable host application logging
74
+
75
+ **2. aiCallback** (Function)
76
+ - **Purpose**: AI communication function for intent detection and response generation
77
+ - **Signature**: `async (systemInstruction: string, userMessage: string) => string`
78
+ - **Integration**: Engine calls this function when AI analysis is needed
79
+ - **Requirements**: Must return AI response as string, handle errors gracefully
80
+ - **Details**: See dedicated AI Callback Function section below
81
+
82
+ **3. flowsMenu** (FlowDefinition[])
83
+ - **Purpose**: Array of available workflow definitions
84
+ - **Content**: All workflows that the engine can detect and execute
85
+ - **Validation**: Engine validates flow structure during initialization
86
+ - **Requirements**: Each flow must have valid id, name, description, and steps
87
+
88
+ **4. toolsRegistry** (ToolDefinition[])
89
+ - **Purpose**: Array of external tool definitions for CALL-TOOL steps
90
+ - **Content**: HTTP APIs, local functions, and mock tools available to workflows
91
+ - **Validation**: Parameter schemas validated against OpenAI Function Calling Standard
92
+ - **Security**: Tools define their own security levels and authentication requirements
93
+
94
+ **5. APPROVED_FUNCTIONS** (Map<string, Function>)
95
+ - **Purpose**: Secure registry of pre-approved local JavaScript functions
96
+ - **Security**: Only functions in this map can be executed by local-type tools
97
+ - **Format**: `Map` where keys are function names and values are the actual functions
98
+ - **Validation**: Functions must match tool definitions in toolsRegistry
99
+
100
+ **6. globalVariables** (Record<string, unknown>, optional)
101
+ - **Purpose**: Session-wide variables accessible to all workflows
102
+ - **Scope**: Available to all flows in the session via variable interpolation
103
+ - **Security**: Safe sharing of host application data with workflows
104
+ - **Examples**: User ID, session ID, application configuration, environmental data
105
+
106
+ **7. validateOnInit** (boolean, optional)
107
+ - **Purpose**: Enable comprehensive flow and tool validation during initialization
108
+ - **Default**: `true` - recommended for development and production
109
+ - **Performance**: Set to `false` only in high-performance scenarios with pre-validated flows
110
+ - **Output**: Detailed validation reports with errors, warnings, and success metrics
111
+
112
+ **8. language** (string, optional)
113
+ - **Purpose**: User's preferred language for localized messages and prompts
114
+ - **Format**: ISO language code ('en', 'es', 'fr', 'de', etc.)
115
+ - **Default**: 'en' if not specified
116
+ - **Usage**: Engine selects appropriate prompt_xx properties from flow definitions
117
+
118
+ **9. messageRegistry** (MessageRegistry, optional)
119
+ - **Purpose**: Custom message templates for engine-generated user messages
120
+ - **Format**: Multi-language message registry with customizable system messages
121
+ - **Override**: Allows customization of built-in engine messages
122
+ - **Localization**: Supports multiple languages with fallback to default messages
123
+
124
+ **10. guidanceConfig** (GuidanceConfig, optional)
125
+ - **Purpose**: Configuration for user guidance and help messages
126
+ - **Features**: Controls how and when the engine provides user assistance
127
+ - **Modes**: Append, prepend, template, or none for guidance integration
128
+ - **Context**: Different guidance for general vs. payment/financial workflows
129
+
130
+ ### AI Callback Function
131
+
132
+ The `aiCallback` parameter provides the engine access to your AI system for intent detection and workflow triggering. Here's a minimal implementation example:
133
+
134
+ ```javascript
135
+ // Minimal AI callback implementation
136
+ async function aiCallback(systemInstruction, userMessage) {
137
+ try {
138
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
139
+ method: "POST",
140
+ headers: {
141
+ "Content-Type": "application/json",
142
+ "Authorization": `Bearer ${YOUR_OPENAI_API_KEY}`
143
+ },
144
+ body: JSON.stringify({
145
+ model: "gpt-4o-mini",
146
+ messages: [
147
+ { role: "system", content: systemInstruction },
148
+ { role: "user", content: userMessage }
149
+ ],
150
+ temperature: 0.1,
151
+ max_tokens: 200
152
+ })
153
+ });
154
+
155
+ if (!response.ok) {
156
+ throw new Error(`AI API request failed: ${response.status} ${response.statusText}`);
157
+ }
158
+
159
+ const data = await response.json();
160
+ return data.choices[0].message.content.trim();
161
+
162
+ } catch (error) {
163
+ throw new Error(`AI communication failed: ${error.message}`);
164
+ }
165
+ }
166
+ ```
167
+
168
+ **AI Callback Interface:**
169
+ - **Input**: `systemInstruction` (string), `userMessage` (string)
170
+ - **Output**: AI response as a string
171
+ - **Purpose**: Analyzes user input to detect workflow intents and generate responses
172
+ - **Integration**: The engine calls this function when it needs AI analysis for intent detection
173
+
174
+ **How the Engine Generates Input Arguments:**
175
+ - **`systemInstruction`**: Dynamically generated by the engine based on:
176
+ - Available flow definitions and their descriptions
177
+ - Current session context and active flows
178
+ - Current conversation state and collected variables
179
+ - **`userMessage`**: Intelligently composed by the engine, including:
180
+ - The actual user input/prompt
181
+ - Relevant contextual information from the conversation
182
+ - Session state and variables needed for intent analysis
183
+
184
+ Both parameters are carefully engineered by the engine to work together for optimal intent detection. The engine automatically constructs comprehensive, context-aware prompts that provide the AI with all necessary information for accurate workflow selection and response generation. Your aiCallback implementation only needs to send these pre-constructed arguments to your AI service and return the response.
185
+
186
+ **Alternative AI Services:**
187
+ You can integrate any AI service (Claude, Gemini, local LLMs, etc.) by implementing this same interface. The engine only requires a function that takes system instructions and user input, then returns an AI response.
188
+
189
+ ### Core Registries
190
+
191
+ The engine operates through four primary registries that define its capabilities:
192
+
193
+ #### 1. **Flows Registry** - Workflow Definitions
194
+ ```javascript
195
+ const flowsMenu = [
196
+ {
197
+ id: "payment-workflow",
198
+ name: "ProcessPayment",
199
+ prompt: "Process a payment",
200
+ description: "Handle payment processing with validation",
201
+ steps: [
202
+ { type: "SAY", value: "Let's process your payment." },
203
+ { type: "SAY-GET", variable: "amount", value: "Enter amount:" },
204
+ { type: "CALL-TOOL", tool: "PaymentProcessor", args: {...} }
205
+ ]
206
+ }
207
+ ];
208
+ ```
209
+
210
+ #### 2. **Tools Registry** - External Integrations
211
+ ```javascript
212
+ const toolsRegistry = [
213
+ {
214
+ id: "PaymentProcessor",
215
+ name: "Process Payment",
216
+ description: "Processes financial transactions securely",
217
+ parameters: { /* OpenAI Function Calling Standard Schema */ },
218
+ implementation: {
219
+ type: "local", // or "http" for REST APIs
220
+ function: "processPayment",
221
+ timeout: 10000
222
+ },
223
+ security: {
224
+ requiresAuth: true,
225
+ auditLevel: "critical",
226
+ dataClassification: "financial"
227
+ }
228
+ }
229
+ ];
230
+ ```
231
+
232
+ #### 3. **Approved Functions Registry** - Secure Local Functions
233
+ ```javascript
234
+ const APPROVED_FUNCTIONS = new Map();
235
+
236
+ // Define secure local functions
237
+ async function processPayment(args) {
238
+ // Secure payment processing logic
239
+ return { transactionId: "...", status: "success" };
240
+ }
241
+
242
+ // Register approved functions
243
+ APPROVED_FUNCTIONS.set('processPayment', processPayment);
244
+ ```
245
+
246
+ #### 4. **Global Variables** - Secure Sharing of Local Data
247
+ ```javascript
248
+ const globalVariables = {
249
+ caller_id: "(555) 123-4567",
250
+ caller_name: "John Doe",
251
+ thread_id: "conversation-123"
252
+ };
41
253
  ```
42
254
 
43
255
  ### Session Management
@@ -59,31 +271,11 @@ interface ContextEntry {
59
271
  content: string | Record<string, unknown>; // Message content (text, object, etc.)
60
272
  timestamp: number; // Unix timestamp in milliseconds
61
273
  stepId?: string; // Optional: Used by the system when a Step calls a Tool
62
- toolName?: string; // Optional: Used by the system to record Tool result into the the chat context
274
+ toolName?: string; // Optional: Used by the system to record Tool result into the chat context
63
275
  metadata?: Record<string, unknown>; // Optional: Additional context data
64
276
  }
65
277
  ```
66
278
 
67
- ### Example Usage
68
-
69
- ```typescript
70
- // User message
71
- const userEntry = {
72
- role: 'user',
73
- content: 'I need help with my account',
74
- };
75
- // Process the message
76
- await engine.updateActivity(userEntry, sessionContext);
77
-
78
- // Assistant response
79
- const assistantEntry = {
80
- role: 'assistant',
81
- content: 'I can help you with your account. What specific issue are you experiencing?',
82
- };
83
- // Process the message
84
- await engine.updateActivity(assistantEntry, sessionContext);
85
- ```
86
-
87
279
  ## Architecture Overview
88
280
 
89
281
  ### Stack-of-Stacks Design
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "TypeScript workflow engine for conversational/automation apps: multi-flow orchestration, interrupt/resume, stack-based control, robust errors, and flexible tool/REST integration.",
5
5
  "license": "MIT",
6
6
  "author": "Ron Pinkas",