jsfe 0.4.0 → 0.6.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 +239 -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,243 @@ 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 ${process.env.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: {...}, variable: "payment_result", }
205
+ ]
206
+ }
207
+ ];
208
+ ```
209
+ #### Referencing Tool Results in Later Steps
210
+ When a CALL-TOOL step finishes, it can store the returned data into a variable you name via the variable property. That variable will hold the entire return object from the tool.
211
+ ```javascript
212
+ Using variable
213
+ {
214
+ "type": "CALL-TOOL",
215
+ "tool": "CreateSupportTicket",
216
+ "variable": "ticket_result",
217
+ "args": {
218
+ "subject": "{{subject}}",
219
+ "description": "{{description}}",
220
+ "customer_email": "{{customer_email}}"
221
+ }
222
+ },
223
+ {
224
+ "type": "SAY",
225
+ "value": "Ticket created: {{ticket_result.ticket.id}} — we'll email updates to {{ticket_result.ticket.customer_email}}."
226
+ }
227
+ ```
228
+ ##### Important:
229
+ Whatever your tool returns becomes the value of the variable you specify.
230
+ Because you get the raw return object, you do not need to use .result in your template paths—just reference the keys the tool returns (ticket_result.ticket.id, ticket_result.ok, etc.).
231
+ If you omit variable, you won’t be able to access the tool’s output later.
232
+
233
+ #### 2. **Tools Registry** - External Integrations
234
+ ```javascript
235
+ const toolsRegistry = [
236
+ {
237
+ id: "PaymentProcessor",
238
+ name: "Process Payment",
239
+ description: "Processes financial transactions securely",
240
+ parameters: { /* OpenAI Function Calling Standard Schema */ },
241
+ implementation: {
242
+ type: "local", // or "http" for REST APIs
243
+ function: "processPayment",
244
+ timeout: 10000
245
+ },
246
+ security: {
247
+ requiresAuth: true,
248
+ auditLevel: "critical",
249
+ dataClassification: "financial"
250
+ }
251
+ }
252
+ ];
253
+ ```
254
+
255
+ #### 3. **Approved Functions Registry** - Secure Local Functions
256
+ ```javascript
257
+ const APPROVED_FUNCTIONS = new Map();
258
+
259
+ // Define secure local functions
260
+ async function processPayment(args) {
261
+ // Secure payment processing logic
262
+ return { transactionId: "...", status: "success" };
263
+ }
264
+
265
+ // Register approved functions
266
+ APPROVED_FUNCTIONS.set('processPayment', processPayment);
267
+ ```
268
+
269
+ #### 4. **Global Variables** - Secure Sharing of Local Data
270
+ ```javascript
271
+ const globalVariables = {
272
+ caller_id: "(555) 123-4567",
273
+ caller_name: "John Doe",
274
+ thread_id: "conversation-123"
275
+ };
41
276
  ```
42
277
 
43
278
  ### Session Management
@@ -59,31 +294,11 @@ interface ContextEntry {
59
294
  content: string | Record<string, unknown>; // Message content (text, object, etc.)
60
295
  timestamp: number; // Unix timestamp in milliseconds
61
296
  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
297
+ toolName?: string; // Optional: Used by the system to record Tool result into the chat context
63
298
  metadata?: Record<string, unknown>; // Optional: Additional context data
64
299
  }
65
300
  ```
66
301
 
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
302
  ## Architecture Overview
88
303
 
89
304
  ### 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.6.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",