jsfe 0.1.1 → 0.4.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.
package/README.md CHANGED
@@ -15,170 +15,373 @@ npm i jsfe
15
15
  *For detailed tutorials, step-by-step examples, and comprehensive workflow patterns, see the **[User Guide](JavaScript%20Flow%20Engine.md)**.*
16
16
 
17
17
  ## Usage
18
- \`\`\`ts
18
+
19
+ ```typescript
19
20
  import { WorkflowEngine } from "jsfe";
21
+
22
+ // 1. Create the engine
20
23
  const engine = new WorkflowEngine(
21
- hostLogger: Logger, // logger instance like winston - supporting .info/.debug/.warn/.error methods
22
- aiCallback: AiCallbackFunction, // host provided access to AI fetch function aiFetcher(systemInstructions, userMessage) -> response string
23
- flowsMenu: FlowDefinition[], // host defined available flows
24
- toolsRegistry: ToolDefinition[], // host defined tools registry
25
- APPROVED_FUNCTIONS: ApprovedFunctions, // Optional host provided safe functions map
26
- globalVariables?: Record<string, unknown> // Optional global variables shared across all new flows
27
- validateOnInit: boolean = true, // Optional validate all flows an enggine initialization
28
- language?: string, // Optional language code
29
- messageRegistry?: MessageRegistry, // Optional override all engine internationalized messages
30
- guidanceConfig?: GuidanceConfig, // Optional overide default internationalized guidance prompts
24
+ hostLogger, // Your logging instance
25
+ aiCallback, // Your AI communication function
26
+ flowsMenu, // Array of flow definitions
27
+ toolsRegistry, // Array of tool definitions
28
+ APPROVED_FUNCTIONS, // Pre-approved local functions
29
+ globalVariables, // Optional: Session-wide variables
30
+ validateOnInit, // Optional: Enable pre-flight validation (default: true)
31
+ language, // Optional: User's preferred language
32
+ messageRegistry, // Optional: Custom message templates
33
+ guidanceConfig // Optional: User assistance configuration
31
34
  );
32
35
 
33
- \`\`\`
36
+ // 2. Initialize a session for each user
37
+ const sessionContext = engine.initSession(yourLogger, 'user-123', 'session-456');
38
+
39
+ // 3. Process user input and assistant responses
40
+ const result = await engine.updateActivity(contextEntry, sessionContext);
41
+ ```
34
42
 
35
- /*
36
- ==========================================
37
- ENHANCED FLOW ENGINE ARCHITECTURE OVERVIEW
38
- ==========================================
43
+ ### Session Management
39
44
 
40
- MAJOR DESIGN ENHANCEMENT: Stack-of-Stacks Architecture for Flow Interruption/Resumption
45
+ - Each user requires a unique session context via `initSession(logger, userId, sessionId)`
46
+ - The `EngineSessionContext` object should be persisted by your application
47
+ - Pass the same session context to `updateActivity` for conversation continuity
41
48
 
42
- This Flow Engine implements a sophisticated "stack-of-stacks" architecture that allows flows to be
43
- suspended and resumed, enabling users to naturally interrupt one workflow to handle another task,
44
- then return to their original workflow seamlessly.
49
+ ### Context Entry Types
45
50
 
46
- ==========================================
47
- CORE ARCHITECTURE COMPONENTS
48
- ==========================================
51
+ - User input: `contextEntry.role = 'user'` - analyzed and may trigger flow execution
52
+ - Assistant response: `contextEntry.role = 'assistant'` - added to context for awareness
49
53
 
50
- 1. STACK-OF-STACKS DESIGN:
51
- - Multiple independent flow execution stacks
54
+ ### ContextEntry Structure
55
+
56
+ ```typescript
57
+ interface ContextEntry {
58
+ role: 'user' | 'assistant' | 'system' | 'tool'; // Message role type
59
+ content: string | Record<string, unknown>; // Message content (text, object, etc.)
60
+ timestamp: number; // Unix timestamp in milliseconds
61
+ 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
63
+ metadata?: Record<string, unknown>; // Optional: Additional context data
64
+ }
65
+ ```
66
+
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
+ ## Architecture Overview
88
+
89
+ ### Stack-of-Stacks Design
90
+
91
+ The Flow Engine implements a sophisticated "stack-of-stacks" architecture that allows flows to be suspended and resumed, enabling users to naturally interrupt one workflow to handle another task, then return to their original workflow seamlessly.
92
+
93
+ #### Core Components
94
+
95
+ 1. **Multiple Independent Flow Execution Stacks**
52
96
  - Active stack index tracks current execution context
53
97
  - Automatic stack switching for flow interruption/resumption
54
98
  - Proper isolation between different workflow contexts
55
99
 
56
- 2. FLOW FRAME STRUCTURE:
100
+ 2. **Flow Frame Structure (Runtime Execution Context)**
57
101
  Each flow execution maintains a complete context frame:
58
- - flowName, flowId, flowVersion: Flow identity and versioning
59
- - flowStepsStack: Remaining steps (reversed for efficient pop operations)
60
- - contextStack: Complete history of inputs and responses
61
- - inputStack: Current input context for step execution
62
- - variables: Unified flat variable storage (shared across sub-flows)
63
- - transaction: Comprehensive transaction management and audit trail
64
- - userId, startTime: User context and timing metadata
65
-
66
- 3. HELPER FUNCTION ARCHITECTURE:
102
+ ```typescript
103
+ interface FlowFrame {
104
+ flowName: string; // Human-readable flow name (from FlowDefinition.name)
105
+ flowId: string; // Unique flow identifier (from FlowDefinition.id)
106
+ flowVersion: string; // Flow version for compatibility (from FlowDefinition.version)
107
+ flowStepsStack: FlowStep[]; // Remaining steps (reversed for efficient pop)
108
+ contextStack: ContextEntry[]; // Complete interaction history with role info
109
+ inputStack: unknown[]; // Current input context for step execution
110
+ variables: Record<string, unknown>; // Unified variable storage (shared across sub-flows)
111
+ transaction: TransactionObj; // Comprehensive transaction and audit tracking
112
+ userId: string; // User identifier for this flow session
113
+ startTime: number; // Flow start timestamp for timing analysis
114
+ pendingVariable?: string; // Variable name awaiting user input (SAY-GET steps)
115
+ lastSayMessage?: string; // Last SAY step output for context
116
+ pendingInterruption?: Record<string, unknown>; // Interruption state management
117
+ accumulatedMessages?: string[]; // Accumulated SAY messages for batching
118
+ parentTransaction?: string; // Parent transaction ID for sub-flow tracking
119
+ justResumed?: boolean; // Flag indicating flow was just resumed
120
+ }
121
+ ```
122
+
123
+ **Technical Implementation Details:**
124
+ - **Flow Identity**: `flowName`, `flowId`, `flowVersion` are copied from the FlowDefinition
125
+ - **Dynamic Properties**: Flow `prompt`, `description`, and localized prompts are accessed dynamically from FlowDefinition
126
+ - **flowStepsStack**: Steps stored in reverse order for efficient pop operations
127
+ - **contextStack**: Enhanced with role information for complete conversation context
128
+ - **variables**: Flat storage shared across sub-flows for seamless data passing
129
+ - **accumulatedMessages**: SAY steps are batched for efficient output
130
+ - **justResumed**: Helps engine provide appropriate resumption messages
131
+ ```
132
+
133
+ 3. **Helper Function Architecture**
67
134
  All stack operations go through centralized helper functions:
68
- - initializeFlowStacks(engine): Ensures proper structure
69
- - getCurrentStack(engine): Gets currently active stack
70
- - getCurrentStackLength(engine): Safe length checking
71
- - pushToCurrentStack(engine, frame): Adds flow to active stack
72
- - popFromCurrentStack(engine): Removes flow from active stack
73
- - createNewStack(engine): Creates new stack for interruptions
74
- - switchToPreviousStack(engine): Returns to previous context
75
-
76
- ==========================================
77
- DATA STRUCTURES & PROPERTIES
78
- ==========================================
79
-
80
- FLOW FRAME PROPERTIES:
81
- {
82
- flowName: string, // Human-readable flow name
83
- flowId: string, // Unique flow identifier
84
- flowVersion: string, // Flow version for compatibility
85
- flowStepsStack: [...], // Remaining steps (reversed)
86
- contextStack: [...], // Complete interaction history
87
- inputStack: [...], // Current input context
88
- variables: {}, // Unified variable storage
89
- transaction: TransactionObj, // Audit and transaction tracking
90
- userId: string, // User identifier
91
- startTime: number, // Flow start timestamp
92
- pendingVariable: string, // Variable awaiting user input
93
- lastSayMessage: string, // Last SAY step output
94
- pendingInterruption: {} // Interruption state management
95
- }
135
+ - `initializeFlowStacks(engine)`: Ensures proper structure
136
+ - `getCurrentStack(engine)`: Gets currently active stack
137
+ - `pushToCurrentStack(engine, frame)`: Adds flow to active stack
138
+ - `popFromCurrentStack(engine)`: Removes flow from active stack
139
+
140
+ 4. **Tool Definition Structure (Runtime Integration Context)**
141
+ Tools provide external capabilities with comprehensive security and validation:
142
+ ```typescript
143
+ interface ToolDefinition {
144
+ id: string; // Unique tool identifier
145
+ name: string; // Human-readable tool name
146
+ description: string; // Tool functionality description
147
+
148
+ parameters?: { // OpenAI Function Calling Standard schema
149
+ type: string; // Parameter type structure
150
+ properties?: Record<string, PropertySchema>; // Parameter validation rules
151
+ required?: string[]; // Required parameter names
152
+ additionalProperties?: boolean; // Additional parameter handling
153
+ };
154
+
155
+ implementation?: { // Execution configuration
156
+ type: 'local' | 'http'; // Implementation type
157
+ function?: string; // Local function name (APPROVED_FUNCTIONS)
158
+ url?: string; // HTTP endpoint with {param} placeholders
159
+ method?: HttpMethod; // HTTP method
160
+ pathParams?: string[]; // URL parameter substitution
161
+ queryParams?: string[]; // Query string parameters
162
+ responseMapping?: MappingConfig; // Response transformation config
163
+ timeout?: number; // Request timeout
164
+ retries?: number; // Retry attempts
165
+ };
166
+
167
+ security?: { // Security controls
168
+ rateLimit?: { // Rate limiting configuration
169
+ requests: number; // Max requests per window
170
+ window: number; // Time window in milliseconds
171
+ };
172
+ };
173
+ apiKey?: string; // Authentication token
174
+ riskLevel?: 'low' | 'medium' | 'high'; // Security classification
175
+ }
176
+ ```
177
+
178
+ **Technical Implementation Details:**
179
+ - **Parameter Validation**: JSON Schema validation with ajv for type safety
180
+ - **Local Function Execution**: Secure execution through APPROVED_FUNCTIONS registry
181
+ - **HTTP Integration**: Full REST API support with authentication and retries
182
+ - **Response Mapping**: Declarative transformation without code injection
183
+ - **Security Controls**: Rate limiting, risk classification, audit logging
184
+ - **Error Handling**: Automatic retry logic and graceful degradation
185
+
186
+ 5. **Response Mapping Configuration (MappingConfig Interface)**
187
+ The comprehensive response mapping system supports multiple transformation types:
188
+ ```typescript
189
+ export type MappingConfig =
190
+ | JsonPathMappingConfig
191
+ | ObjectMappingConfig
192
+ | ArrayMappingConfig
193
+ | TemplateMappingConfig
194
+ | ConditionalMappingConfig
195
+ | PathConfig
196
+ | string
197
+ | Record<string, unknown>;
198
+
199
+ // JSONPath-based field extraction and transformation
200
+ export type JsonPathMappingConfig = {
201
+ type: 'jsonPath';
202
+ mappings: Record<string, {
203
+ path: string; // JSONPath expression for data extraction
204
+ transform?: ValueTransformConfig; // Optional value transformation
205
+ fallback?: unknown; // Fallback value if path not found
206
+ }>;
207
+ strict?: boolean; // Strict mode validation
208
+ };
209
+
210
+ // Object structure mapping with nested support
211
+ export type ObjectMappingConfig = {
212
+ type: 'object';
213
+ mappings: Record<string, string | PathConfig | MappingConfig | object>;
214
+ strict?: boolean; // Strict mode validation
215
+ };
216
+
217
+ // Array processing with filtering, sorting, and pagination
218
+ export type ArrayMappingConfig = {
219
+ type: 'array';
220
+ source?: string; // Source array path
221
+ filter?: ConditionConfig; // Filtering conditions
222
+ itemMapping?: MappingConfig; // Per-item transformation
223
+ sort?: { field: string; order?: 'asc' | 'desc' }; // Sorting configuration
224
+ offset?: number; // Pagination offset
225
+ limit?: number; // Pagination limit
226
+ fallback?: unknown[]; // Fallback array if source not found
227
+ };
228
+
229
+ // Template-based string generation with variable substitution
230
+ export type TemplateMappingConfig = {
231
+ type: 'template';
232
+ template: string; // Template string with {{variable}} placeholders
233
+ dataPath?: string; // Optional path to resolve template data from
234
+ };
235
+
236
+ // Conditional logic-based mapping selection
237
+ export type ConditionalMappingConfig = {
238
+ type: 'conditional';
239
+ conditions: Array<{
240
+ if: ConditionConfig; // Condition evaluation
241
+ then: MappingConfig; // Mapping to apply if condition true
242
+ }>;
243
+ else?: MappingConfig; // Default mapping if no conditions match
244
+ };
245
+
246
+ // Path-based value extraction with transformation
247
+ export type PathConfig = {
248
+ path: string; // Data path for extraction
249
+ transform?: ValueTransformConfig; // Optional value transformation
250
+ fallback?: unknown; // Fallback value if path not found
251
+ };
252
+
253
+ // Comprehensive value transformation system with 25+ transform types
254
+ export interface ValueTransformConfig {
255
+ type: 'parseInt' | 'parseFloat' | 'toLowerCase' | 'toUpperCase' | 'trim' |
256
+ 'replace' | 'concat' | 'regex' | 'date' | 'default' | 'conditional' |
257
+ 'substring' | 'split' | 'join' | 'abs' | 'round' | 'floor' | 'ceil' |
258
+ 'template' | 'sum' | 'average' | 'count' | 'min' | 'max' | 'multiply' |
259
+ 'divide' | 'percentage' | 'add' | 'subtract' | 'currentYear' |
260
+ 'yearDifference' | 'handlebars' | 'custom';
261
+
262
+ // Common transformation parameters
263
+ fallback?: unknown; // Default value for failed transforms
264
+ prefix?: string; // String prefix for concat operations
265
+ suffix?: string; // String suffix for concat operations
266
+ pattern?: string; // Regex pattern for replace/match operations
267
+ replacement?: string; // Replacement string for regex operations
268
+ template?: string; // Template string for template transforms
269
+ value?: unknown; // Static value for default transforms
270
+
271
+ // Mathematical operation parameters
272
+ precision?: number; // Decimal precision for rounding operations
273
+ divisor?: number; // Divisor for division/percentage operations
274
+ multiplier?: number; // Multiplier for multiplication operations
275
+ addend?: number; // Value to add for addition operations
276
+ subtrahend?: number; // Value to subtract for subtraction operations
277
+
278
+ // Array and aggregation parameters
279
+ field?: string; // Field name for array aggregations
280
+ delimiter?: string; // Delimiter for join/split operations
281
+ index?: number; // Array index for element selection
282
+
283
+ // Conditional and date parameters
284
+ condition?: ConditionConfig; // Condition for conditional transforms
285
+ fromYear?: number; // Start year for year difference calculations
286
+ dataPath?: string; // Path for accessing context data
287
+ }
288
+
289
+ // Flexible condition evaluation system
290
+ export interface ConditionConfig {
291
+ field: string; // Field path for evaluation
292
+ operator: 'equals' | 'eq' | 'notEquals' | 'ne' | 'contains' | 'exists' |
293
+ 'notExists' | 'greaterThan' | 'gt' | 'lessThan' | 'lt' |
294
+ 'greaterThanOrEqual' | 'gte' | 'lessThanOrEqual' | 'lte' |
295
+ 'startsWith' | 'endsWith' | 'matches' | 'in' | 'hasLength' |
296
+ 'isArray' | 'isObject' | 'isString' | 'isNumber';
297
+ value?: unknown; // Comparison value for operators
298
+ }
299
+ ```
300
+
301
+ **Response Mapping Technical Features:**
302
+ - **Type Safety**: Full TypeScript interface definitions with validation
303
+ - **Declarative Configuration**: No code injection - pure JSON configuration
304
+ - **Comprehensive Transforms**: 25+ built-in transformation types
305
+ - **Mathematical Operations**: Arithmetic, statistical, and precision control
306
+ - **Date Processing**: Dynamic date calculations and formatting
307
+ - **Template System**: Handlebars-style variable substitution with array iteration
308
+ - **Conditional Logic**: Complex branching and filtering capabilities
309
+ - **Array Processing**: Filtering, sorting, pagination, and aggregation
310
+ - **Path Resolution**: JSONPath support with fallback handling
311
+ - **Security**: Complete input sanitization and validation
312
+
313
+ ## Features & Capabilities
314
+
315
+ ### Flow Execution Modes
316
+ - ✅ **Linear Flow Execution** - Sequential step processing
317
+ - ✅ **Sub-Flow Calls** - Nested workflow execution
318
+ - ✅ **Flow Interruption** - Suspend current flow for new task
319
+ - ✅ **Flow Resumption** - Return to previously suspended flows
320
+ - ✅ **Flow Replacement** - Replace current flow with new flow
321
+ - ✅ **Flow Reboot** - Nuclear option: clear all flows and restart
322
+
323
+ ### Step Types
324
+ - ✅ **SAY** - Non-blocking output messages (accumulated)
325
+ - ✅ **SAY-GET** - Blocking output with user input request
326
+ - ✅ **SET** - Variable assignment with interpolation support
327
+ - ✅ **CALL-TOOL** - External tool execution with error handling
328
+ - ✅ **FLOW** - Sub-flow execution with multiple call types
329
+ - ✅ **SWITCH** - Enhanced conditional branching with expressions
330
+
331
+ ### Expression Template System
332
+
333
+ The engine supports safe JavaScript expressions within `{{}}` templates:
96
334
 
97
- ========================================
98
- SUPPORTED FEATURES & CAPABILITIES
99
- ========================================
100
-
101
- FLOW EXECUTION MODES:
102
- ✅ Linear Flow Execution - Sequential step processing
103
- ✅ Sub-Flow Calls - Nested workflow execution
104
- ✅ Flow Interruption - Suspend current flow for new task
105
- ✅ Flow Resumption - Return to previously suspended flows
106
- ✅ Flow Replacement - Replace current flow with new flow
107
- ✅ Flow Reboot - Nuclear option: clear all flows and restart
108
-
109
- CALL TYPE BEHAVIORS:
110
- ✅ "call" (default) - Normal sub-flow, preserves parent on stack
111
- ✅ "replace" - Replace current flow with new flow
112
- ✅ "reboot" - Clear entire stack and start fresh (emergency recovery)
113
-
114
- STEP TYPE SUPPORT:
115
- ✅ SAY - Non-blocking output messages (accumulated)
116
- ✅ SAY-GET - Blocking output with user input request
117
- ✅ SET - Variable assignment with interpolation support
118
- ✅ CALL-TOOL - External tool execution with error handling
119
- ✅ FLOW - Sub-flow execution with multiple call types
120
- ✅ SWITCH - Enhanced conditional branching with expressions
121
-
122
- ADVANCED SWITCH CONDITIONS:
123
- ✅ Exact Value Matching - Traditional switch behavior
124
- ✅ Expression Evaluation - Dynamic condition evaluation using safe JavaScript expressions
125
- ✅ Mixed Branches - Combine exact matches with conditions
126
- ✅ Secure Evaluation - No eval(), no code injection, safe expression parsing
127
- ✅ Expression Templates - {{variable + otherVar}} and {{complex.expression > threshold}} support
128
-
129
- EXPRESSION TEMPLATE SYSTEM:
130
- The engine supports safe JavaScript expressions within {{}} templates:
131
- - Simple variables: {{userName}}, {{account.balance}}
132
- - Arithmetic: {{amount + fee}}, {{price * quantity}}
133
- - Comparisons: {{age >= 18}}, {{status === 'active'}}
134
- - Logical: {{isAdmin && hasAccess}}, {{retryCount < maxRetries}}
135
- - Complex: {{user.permissions.includes('admin') && creditScore > 700}}
136
-
137
- SAFE METHOD CALLS:
138
- The engine includes comprehensive security controls that allow only pre-approved methods:
335
+ ```javascript
336
+ // Simple variables
337
+ {{userName}}, {{account.balance}}
139
338
 
140
- **String Methods:**
141
- Case conversion: toLowerCase(), toUpperCase()
142
- ✅ Whitespace: trim(), padStart(), padEnd()
143
- ✅ Access: charAt(), charCodeAt(), indexOf(), lastIndexOf()
144
- ✅ Extraction: substring(), substr(), slice(), split()
145
- ✅ Search: includes(), startsWith(), endsWith(), match(), search()
146
- ✅ Manipulation: replace(), repeat(), concat()
147
- ✅ Utility: toString(), valueOf(), length, localeCompare(), normalize()
339
+ // Arithmetic
340
+ {{amount + fee}}, {{price * quantity}}
148
341
 
149
- **Array Methods:**
150
- Inspection: length, includes(), indexOf(), lastIndexOf()
151
- ✅ Extraction: slice(), join()
152
- ✅ Conversion: toString(), valueOf()
342
+ // Comparisons
343
+ {{age >= 18}}, {{status === 'active'}}
153
344
 
154
- **Math Methods:**
155
- Basic: abs(), ceil(), floor(), round()
156
- ✅ Comparison: max(), min()
157
- Advanced: pow(), sqrt(), random()
345
+ // Logical operations
346
+ {{isAdmin && hasAccess}}, {{retryCount < maxRetries}}
347
+
348
+ // Complex expressions
349
+ {{user.permissions.includes('admin') && creditScore > 700}}
350
+ ```
351
+
352
+ ### Safe Method Calls
158
353
 
159
- **Examples:**
354
+ **String Methods:**
160
355
  ```javascript
161
- // String processing
356
+ // Case conversion
162
357
  {{userInput.toLowerCase().trim()}}
358
+
359
+ // Email validation
163
360
  {{email.includes('@') && email.length > 5}}
361
+
362
+ // Text processing
164
363
  {{text.substring(0, 10).padEnd(15, '...')}}
364
+ ```
165
365
 
166
- // Array operations
366
+ **Array Methods:**
367
+ ```javascript
368
+ // Length and content checks
167
369
  {{items.length > 0 && items.includes('premium')}}
168
- {{categories.slice(0, 3).join(', ')}}
169
370
 
170
- // Mathematical operations
171
- {{Math.round(price * 1.08)}} // Tax calculation
172
- {{Math.max(balance, 0)}} // Ensure non-negative
371
+ // Array manipulation
372
+ {{categories.slice(0, 3).join(', ')}}
173
373
  ```
174
374
 
175
- SAFE FUNCTIONS:
176
- ✅ **Built-in Functions:** parseInt(), parseFloat(), isNaN(), isFinite()
177
- **Type Conversion:** String(), Number(), Boolean() (non-constructor forms)
178
- ✅ **URI Encoding:** encodeURIComponent(), decodeURIComponent(), encodeURI(), decodeURI()
179
- ✅ **User-Defined Functions:** Any functions registered in the APPROVED_FUNCTIONS registry
375
+ **Math Methods:**
376
+ ```javascript
377
+ // Tax calculation
378
+ {{Math.round(price * 1.08)}}
379
+
380
+ // Ensure non-negative
381
+ {{Math.max(balance, 0)}}
382
+ ```
180
383
 
181
- **Examples:**
384
+ **Safe Functions:**
182
385
  ```javascript
183
386
  // Type conversion and validation
184
387
  {{Number(input) > 0 && !isNaN(Number(input))}}
@@ -189,422 +392,51 @@ SAFE FUNCTIONS:
189
392
 
190
393
  // User-defined approved functions
191
394
  {{currentTime()}} // If registered as approved function
192
- {{extractCryptoFromInput(userMessage)}} // If registered as approved function to provide Custom business logic
395
+ {{extractCryptoFromInput(userMessage)}} // Custom business logic
193
396
  ```
194
397
 
195
- INTELLIGENT ERROR HANDLING:
196
- ✅ Smart Default OnFail - Context-aware error recovery
197
- ✅ Financial Operation Protection - Special handling for sensitive flows
198
- ✅ Network Error Recovery - Intelligent retry and messaging
199
- ✅ Graceful Degradation - Maintain user experience during failures
200
- ✅ Transaction Rollback - Proper cleanup on critical failures
201
-
202
- FLOW CONTROL COMMANDS:
203
- ✅ Universal Commands - Work in any flow context
204
- ✅ "cancel"/"abort" - Exit current flow
205
- ✅ "help" - Context-sensitive help messages
206
- ✅ "status" - Current flow state information
398
+ ## Demo/Test Mode: Flow Matching Without AI
207
399
 
208
-
209
- INTENT INTERRUPTION SYSTEM:
210
- ✅ AI-Powered Intent Detection - Recognize new workflow requests (when `aiCallback` is provided)
211
- ✅ Fallback Flow Matching - If `aiCallback` is `null`, the engine will match the user input to a flow by id or name (case-insensitive), and if no exact match is found, will attempt a partial match. This allows demos and tests to run without requiring a real AI function.
212
- ✅ Three-Tier Intent Strength - Weak/Medium/Strong intent classification
213
- ✅ Financial Flow Protection - Require explicit confirmation
214
- ✅ Graceful Interruption - Preserve context while switching
215
- ✅ Smart Resume Logic - Automatic return to suspended flows
216
-
217
- ---
218
-
219
- ## ⚡️ Demo/Test Mode: Flow Matching Without AI
220
-
221
- For demos, tests, or developer convenience, you can now set `aiCallback` to `null` when constructing the engine. In this mode, intent detection will:
400
+ For demos, tests, or developer convenience, you can set `aiCallback` to `null` when constructing the engine. In this mode, intent detection will:
222
401
 
223
402
  1. **Match by Flow Name or ID (case-insensitive):**
224
- - If the user input exactly matches a flow's `name` or `id`, that flow is activated.
403
+ - If the user input exactly matches a flow's `name` or `id`, that flow is activated.
225
404
  2. **Partial Match Fallback:**
226
- - If no exact match is found, the engine will look for a flow whose `name` or `id` contains the input (case-insensitive).
405
+ - If no exact match is found, the engine will look for a flow whose `name` or `id` contains the input (case-insensitive).
227
406
  3. **No Match:**
228
- - If no match is found, no flow is activated.
407
+ - If no match is found, no flow is activated.
229
408
 
230
409
  This makes it easy to run demos and tests without requiring a real AI intent detection function. In production, always provide a real `aiCallback` for robust intent detection.
231
410
 
232
- ========================================
233
- SECURITY & COMPLIANCE FEATURES
234
- ========================================
235
-
236
- EXPRESSION SECURITY:
237
- ✅ Safe Expression Evaluation - No eval(), no code injection, allowlist-based safe method calls
238
- ✅ Safe Method Allowlist - Only pre-approved string, array, and math methods allowed
239
- ✅ Safe Function Registry - Built-in safe functions + user-defined approved functions
240
- ✅ Pattern-Based Security - Block dangerous operations (constructors, eval, etc.)
241
- ✅ Variable Path Validation - Secure nested property access
242
- ✅ Input Sanitization - Clean and validate all user inputs
243
-
244
- TRANSACTION MANAGEMENT:
245
- ✅ Comprehensive Audit Trail - Every action logged
246
- ✅ Transaction State Tracking - Success/failure/pending states
247
- ✅ Error Recovery Logging - Detailed failure analysis
248
- ✅ User Context Isolation - Prevent cross-user data leaks
249
-
250
- RATE LIMITING & VALIDATION:
251
- ✅ Per-User Rate Limiting - Prevent abuse
252
- ✅ JSON Schema Validation - Type-safe parameter handling
253
- ✅ Input Size Limits - Prevent memory exhaustion
254
- ✅ Timeout Management - Prevent hanging operations
255
-
256
- ========================================
257
- INTEGRATION CAPABILITIES
258
- ========================================
259
-
260
- REST API SUPPORT:
261
- ✅ HTTP Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
262
- ✅ Content Types: JSON, Form-data, URL-encoded, XML/SOAP, Plain text, Multipart
263
- ✅ Authentication: Bearer tokens, Basic auth, API keys, HMAC signatures
264
- ✅ Parameter Handling: Path params, Query params, Request body, Headers
265
- ✅ Advanced Features: Retries with exponential backoff, Timeouts, Rate limiting
266
- ✅ Response Handling: JSON, XML, Text with automatic content-type detection
267
- ✅ DECLARATIVE RESPONSE MAPPING: Secure, generic transformation without code injection
268
- ✅ Error Handling: Status-based retry logic, Detailed error messages
269
- ✅ Security: Input sanitization, Credential management, Audit logging
270
-
271
- DECLARATIVE RESPONSE MAPPING SYSTEM:
272
- The engine supports completely generic response transformation through declarative
273
- JSON configuration, eliminating the need for users to inject code. This maintains
274
- complete engine security while supporting complex API response handling.
275
-
276
- MAPPING TYPES SUPPORTED:
277
-
278
- 1. JSONPATH MAPPING - Extract and transform specific fields:
279
- {
280
- responseMapping: {
281
- type: "jsonPath",
282
- mappings: {
283
- "output_field": {
284
- path: "api.response.field[0].value",
285
- transform: { type: "parseInt", fallback: 0 },
286
- fallback: "$args.inputField"
287
- }
288
- }
289
- }
290
- }
411
+ ## Security & Compliance
291
412
 
292
- 2. OBJECT MAPPING - Restructure response objects:
293
- {
294
- responseMapping: {
295
- type: "object",
296
- mappings: {
297
- "user_name": "name",
298
- "contact": {
299
- "email": "email",
300
- "phone": "phone"
301
- },
302
- "metadata": {
303
- "processed": true,
304
- "timestamp": "{{new Date().toISOString()}}"
305
- }
306
- }
307
- }
308
- }
309
-
310
- 3. ARRAY MAPPING - Filter and transform arrays:
311
- {
312
- responseMapping: {
313
- type: "array",
314
- source: "results",
315
- limit: 10,
316
- filter: { field: "status", operator: "equals", value: "active" },
317
- itemMapping: {
318
- type: "object",
319
- mappings: { "id": "id", "name": "name" }
320
- }
321
- }
322
- }
413
+ ### Expression Security
414
+ - ✅ **Safe Expression Evaluation** - No eval(), no code injection
415
+ - ✅ **Safe Method Allowlist** - Only pre-approved methods allowed
416
+ - **Pattern-Based Security** - Block dangerous operations
417
+ - ✅ **Variable Path Validation** - Secure nested property access
323
418
 
324
- 4. TEMPLATE MAPPING - String interpolation:
325
- {
326
- responseMapping: {
327
- type: "template",
328
- template: "User {{name}} ({{email}}) from {$args.source}"
329
- }
330
- }
419
+ ### Transaction Management
420
+ - ✅ **Comprehensive Audit Trail** - Every action logged
421
+ - ✅ **Transaction State Tracking** - Success/failure/pending states
422
+ - ✅ **Error Recovery Logging** - Detailed failure analysis
423
+ - ✅ **User Context Isolation** - Prevent cross-user data leaks
331
424
 
332
- 5. CONDITIONAL MAPPING - Different mapping based on response structure:
333
- {
334
- responseMapping: {
335
- type: "conditional",
336
- conditions: [
337
- {
338
- if: { field: "status", operator: "equals", value: "success" },
339
- then: { type: "object", mappings: { "result": "data" } }
340
- }
341
- ],
342
- else: { type: "object", mappings: { "error": "message" } }
343
- }
344
- }
425
+ ## Integration Capabilities
345
426
 
346
- VALUE TRANSFORMATIONS SUPPORTED:
347
- - parseInt, parseFloat: Number conversion
348
- - toLowerCase, toUpperCase, trim: String manipulation
349
- - replace: Regex replacement
350
- - concat: Add prefix/suffix
351
- - regex: Extract with regex groups
352
- - date: Convert to ISO date string
353
- - default: Fallback values
354
-
355
- SECURITY & BEST PRACTICES:
356
- - No code injection possible - all transformations are declarative
357
- - Secure path traversal with validation
358
- - Fallback handling for missing data
359
- - Type coercion with validation
360
- - Error handling with graceful degradation
361
-
362
- ========================================
363
- IMPLEMENTATION NOTES & BEST PRACTICES
364
- ========================================
365
-
366
- PROPER USAGE PATTERNS:
367
- 1. Always use helper functions for stack operations
368
- 2. Never directly access flowStacks arrays
369
- 3. Maintain transaction state consistency
370
- 4. Use proper error handling with smart defaults
371
- 5. Implement comprehensive logging for debugging
372
-
373
- ========================================
374
- 🚀 ENHANCED TRANSFORMATION CAPABILITIES
375
- ========================================
376
-
377
- The JavaScript Flow Engine now includes a comprehensive suite of mathematical, temporal,
378
- and template processing enhancements that enable sophisticated data transformations
379
- without code injection risks.
380
-
381
- MATHEMATICAL OPERATIONS:
382
- ✅ `add` - Addition with precision control: `{ type: "add", addend: 10, precision: 2 }`
383
- ✅ `subtract` - Subtraction with precision control: `{ type: "subtract", subtrahend: 5, precision: 2 }`
384
- ✅ `multiply` - Multiplication: `{ type: "multiply", multiplier: 1.08, precision: 2 }`
385
- ✅ `divide` - Division with zero protection: `{ type: "divide", divisor: 100, precision: 2 }`
386
- ✅ `percentage` - Percentage calculation: `{ type: "percentage", divisor: 1000, precision: 1 }`
387
- ✅ `abs`, `round`, `floor`, `ceil` - Mathematical functions
388
-
389
- DATE-BASED CALCULATIONS:
390
- ✅ `currentYear` - Get current year: `{ type: "currentYear" }`
391
- ✅ `yearDifference` - Calculate age/duration: `{ type: "yearDifference" }` (current year - value)
392
- ✅ Dynamic age calculations, time-based transformations
393
-
394
- ARRAY AGGREGATIONS:
395
- ✅ `sum` - Sum array values: `{ type: "sum", field: "budget" }` (for object arrays)
396
- ✅ `average` - Calculate mean: `{ type: "average", field: "employees", precision: 1 }`
397
- ✅ `count` - Count non-null values: `{ type: "count", field: "active" }`
398
- ✅ `min` - Find minimum: `{ type: "min", field: "price" }`
399
- ✅ `max` - Find maximum: `{ type: "max", field: "score" }`
400
-
401
- ENHANCED TEMPLATE SYSTEM:
402
- ✅ **Array Length Access**: `{{array.length}}` automatically supported
403
- ✅ **Handlebars-Style Iteration**: `{{#each items}}...{{/each}}` with full nesting
404
- ✅ **Context Variables**: `{{@index}}` (current index), `{{@last}}` (is last item)
405
- ✅ **Conditional Rendering**: `{{#unless @last}}separator{{/unless}}`
406
- ✅ **Nested Property Access**: `{{item.nested.property}}`
407
-
408
- REAL-WORLD EXAMPLES:
409
-
410
- **Age Calculation:**
411
- ```json
412
- {
413
- "path": "user.birthYear",
414
- "transform": { "type": "yearDifference" }
415
- }
416
- ```
417
- Input: `2015` → Output: `10` (automatically calculated as 2025 - 2015)
427
+ ### REST API Support
428
+ - ✅ **HTTP Methods:** GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
429
+ - ✅ **Content Types:** JSON, Form-data, URL-encoded, XML/SOAP, Plain text, Multipart
430
+ - **Authentication:** Bearer tokens, Basic auth, API keys, HMAC signatures
431
+ - **Parameter Handling:** Path params, Query params, Request body, Headers
432
+ - **Advanced Features:** Retries with exponential backoff, Timeouts, Rate limiting
418
433
 
419
- **Financial Aggregations:**
420
- ```json
421
- {
422
- "path": "departments",
423
- "transform": {
424
- "type": "sum",
425
- "field": "budget",
426
- "precision": 0
427
- }
428
- }
429
- ```
430
- Input: `[{budget: 8500000}, {budget: 3200000}]` → Output: `11700000`
434
+ ### Declarative Response Mapping
431
435
 
432
- **Complex Template with Arrays:**
433
- ```json
434
- {
435
- "type": "template",
436
- "template": "Operating in {{locations.length}} locations: {{#each locations}}{{city}}, {{country}} ({{employees}} employees){{#unless @last}}; {{/unless}}{{/each}}"
437
- }
438
- ```
439
- Input: Array of locations → Output: `"Operating in 3 locations: San Francisco, USA (150 employees); London, UK (60 employees); Toronto, Canada (40 employees)"`
436
+ The engine supports completely generic response transformation through declarative JSON configuration:
440
437
 
441
- **Percentage Calculations:**
442
- ```json
443
- {
444
- "path": "completedProjects",
445
- "transform": {
446
- "type": "percentage",
447
- "divisor": "{{totalProjects}}",
448
- "precision": 1
449
- }
450
- }
451
- ```
452
- Input: `19` completed, `30` total → Output: `63.3` (percentage)
453
-
454
- CONTRIBUTORS: Areas for Future Enhancement
455
- ✅ **Current Coverage**: Mathematical, temporal, aggregation, template processing
456
- ⚠️ **Missing Operations**: Trigonometric functions (sin, cos, tan)
457
- ⚠️ **Missing Date Functions**: Date formatting, timezone conversions, date arithmetic
458
- ⚠️ **Missing String Functions**: Advanced regex operations, locale-specific formatting
459
- ⚠️ **Missing Array Functions**: Complex filtering, sorting, grouping operations
460
- ⚠️ **Missing Template Features**: Nested loops, advanced conditionals, custom helpers
461
-
462
- ========================================
463
- 📋 COMPREHENSIVE FEATURE MATRIX FOR CONTRIBUTORS
464
- ========================================
465
-
466
- This section provides a complete overview of implemented features and identifies
467
- areas where contributors can add value. All features maintain the engine's security
468
- model (no code injection, declarative-only transformations).
469
-
470
- FLOW EXECUTION ENGINE:
471
- ✅ **Stack-of-stacks architecture** - Complete with interruption/resumption
472
- ✅ **Flow frame management** - Variables, context, transaction tracking
473
- ✅ **Step types** - SAY, SAY-GET, SET, CALL-TOOL, FLOW, SWITCH
474
- ✅ **Expression evaluation** - Safe JavaScript expressions with allowlist
475
- ✅ **Error handling** - Smart defaults, financial protection, graceful degradation
476
- ✅ **Intent detection** - AI-powered + fallback flow matching
477
- ✅ **Universal commands** - help, status, cancel, exit
478
-
479
- TRANSFORMATION SYSTEM:
480
- ✅ **Basic types** - parseInt, parseFloat, toLowerCase, toUpperCase, trim
481
- ✅ **String operations** - replace, concat, regex, substring, split, join
482
- ✅ **Mathematical** - add, subtract, multiply, divide, percentage, abs, round, floor, ceil
483
- ✅ **Date/Time** - currentYear, yearDifference, ISO date conversion
484
- ✅ **Array aggregations** - sum, average, count, min, max (with field targeting)
485
- ✅ **Conditional logic** - Multi-branch conditions with operators
486
- ✅ **Template processing** - Simple placeholders + Handlebars-style iteration
487
- ✅ **Default/fallback** - Robust null handling
488
-
489
- RESPONSE MAPPING SYSTEM:
490
- ✅ **JSONPath mapping** - Deep object extraction with transformations
491
- ✅ **Object mapping** - Restructuring and field remapping
492
- ✅ **Array mapping** - Filtering, limiting, item transformation
493
- ✅ **Template mapping** - String interpolation with complex iteration
494
- ✅ **Conditional mapping** - Response-structure-based branching
495
-
496
- REST API INTEGRATION:
497
- ✅ **HTTP methods** - GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
498
- ✅ **Content types** - JSON, form-data, URL-encoded, XML/SOAP, text, multipart
499
- ✅ **Authentication** - Bearer, Basic, API keys, HMAC signatures
500
- ✅ **Parameters** - Path params, query params, body, headers
501
- ✅ **Advanced features** - Retries, timeouts, rate limiting
502
- ✅ **Response handling** - Auto content-type detection, declarative mapping
503
-
504
- SECURITY & COMPLIANCE:
505
- ✅ **Expression security** - Safe evaluation, method allowlist, no eval()
506
- ✅ **Transaction management** - Audit trails, state tracking, recovery
507
- ✅ **Rate limiting** - Per-user controls, abuse prevention
508
- ✅ **Input validation** - JSON Schema, size limits, sanitization
509
- ✅ **Credential management** - Secure token handling, audit logging
510
-
511
- AREAS FOR CONTRIBUTOR ENHANCEMENT (very liberal AI based 🫣 ):
512
-
513
- 🔢 **MATHEMATICAL EXTENSIONS:**
514
- ⚠️ Trigonometric functions (sin, cos, tan, asin, acos, atan)
515
- ⚠️ Logarithmic functions (log, log10, ln)
516
- ⚠️ Statistical functions (median, mode, standard deviation)
517
- ⚠️ Financial functions (compound interest, NPV, IRR)
518
-
519
- 📅 **DATE/TIME ENHANCEMENTS:**
520
- ⚠️ Date formatting with locale support (MM/DD/YYYY, DD-MM-YYYY)
521
- ⚠️ Timezone conversions and handling
522
- ⚠️ Date arithmetic (add days, subtract months, etc.)
523
- ⚠️ Relative date calculations (next Monday, last quarter)
524
- ⚠️ Duration calculations (time between dates)
525
-
526
- 🔤 **STRING PROCESSING EXPANSIONS:**
527
- ⚠️ Advanced regex operations (lookahead, lookbehind)
528
- ⚠️ Locale-specific formatting (currency, numbers)
529
- ⚠️ String similarity and distance algorithms
530
- ⚠️ Text normalization and cleaning utilities
531
- ⚠️ Encoding/decoding beyond URI (Base64, hex)
532
-
533
- 🔗 **ARRAY OPERATION ENHANCEMENTS:**
534
- ⚠️ Complex filtering with multiple conditions
535
- ⚠️ Sorting with custom comparators
536
- ⚠️ Grouping and partitioning operations
537
- ⚠️ Set operations (union, intersection, difference)
538
- ⚠️ Array flattening and nested operations
539
-
540
- 🎨 **TEMPLATE SYSTEM EXTENSIONS:**
541
- ⚠️ Nested loop support (each within each)
542
- ⚠️ Advanced conditionals (if/else if/else blocks)
543
- ⚠️ Custom helper functions (user-defined template functions)
544
- ⚠️ Template caching and optimization
545
- ⚠️ Internationalization and localization support
546
-
547
- 🔧 **INTEGRATION CAPABILITIES:**
548
- ⚠️ Database connectivity (with secure query building)
549
- ⚠️ File system operations (secure read/write)
550
- ⚠️ Message queue integration (Kafka, RabbitMQ, SQS)
551
- ⚠️ Real-time capabilities (WebSocket, Server-Sent Events)
552
- ⚠️ Monitoring and metrics collection
553
-
554
- ⚡ **PERFORMANCE OPTIMIZATIONS:**
555
- ⚠️ Expression caching and compilation
556
- ⚠️ Lazy evaluation for expensive operations
557
- ⚠️ Memory usage optimization for large datasets
558
- ⚠️ Parallel processing for independent operations
559
- ⚠️ Streaming processing for large arrays
560
-
561
- IMPLEMENTATION GUIDELINES FOR CONTRIBUTORS:
562
- 1. **Security First**: All new features must maintain no-code-injection principle
563
- 2. **Declarative Design**: Use JSON configuration, not executable code
564
- 3. **Error Handling**: Implement comprehensive fallbacks and validation
565
- 4. **Testing**: Add to the 40+ test comprehensive test suite
566
- 5. **Documentation**: Update both README.md and User Guide
567
- 6. **Type Safety**: Maintain TypeScript compliance with proper interfaces
568
- 7. **Performance**: Consider memory and computational impact
569
-
570
- CURRENT TEST COVERAGE:
571
- ✅ **40 Comprehensive Test Scenarios** - 100% pass rate validated
572
- ✅ **Flow execution patterns** - Linear, nested, interrupted, resumed
573
- ✅ **Mathematical transformations** - All operations with edge cases
574
- ✅ **Template processing** - Simple and complex Handlebars-style
575
- ✅ **API integrations** - HTTP methods, auth, error handling
576
- ✅ **Error scenarios** - Network failures, invalid data, timeouts
577
- ✅ **Security validation** - Expression safety, input sanitization
578
-
579
- ========================================
580
-
581
- - OpenAI Function Calling Standard schemas
582
- - JSON Schema validation with ajv
583
- - Secure function registry
584
- - Comprehensive error handling & transaction management
585
- - Audit logging for compliance
586
- - Rate limiting and input validation
587
- - COMPREHENSIVE REST API SUPPORT with all common conventions:
588
-
589
- REST API FEATURES SUPPORTED:
590
- ✅ HTTP Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
591
- ✅ Content Types: JSON, Form-data, URL-encoded, XML/SOAP, Plain text, Multipart
592
- ✅ Authentication: Bearer tokens, Basic auth, API keys, HMAC signatures
593
- ✅ Parameter Handling: Path params, Query params, Request body, Headers
594
- ✅ Advanced Features: Retries with exponential backoff, Timeouts, Rate limiting
595
- ✅ Response Handling: JSON, XML, Text with automatic content-type detection
596
- ✅ DECLARATIVE RESPONSE MAPPING: Secure, generic transformation without code injection
597
- ✅ Error Handling: Status-based retry logic, Detailed error messages
598
- ✅ Security: Input sanitization, Credential management, Audit logging
599
-
600
- DECLARATIVE RESPONSE MAPPING SYSTEM:
601
- The engine now supports completely generic response transformation through declarative
602
- JSON configuration, eliminating the need for users to inject code. This maintains
603
- complete engine security while supporting complex API response handling.
604
-
605
- MAPPING TYPES SUPPORTED:
606
-
607
- 1. JSONPATH MAPPING - Extract and transform specific fields:
438
+ #### JSONPath Mapping
439
+ ```javascript
608
440
  {
609
441
  responseMapping: {
610
442
  type: "jsonPath",
@@ -617,8 +449,10 @@ MAPPING TYPES SUPPORTED:
617
449
  }
618
450
  }
619
451
  }
452
+ ```
620
453
 
621
- 2. OBJECT MAPPING - Restructure response objects:
454
+ #### Object Mapping
455
+ ```javascript
622
456
  {
623
457
  responseMapping: {
624
458
  type: "object",
@@ -635,62 +469,47 @@ MAPPING TYPES SUPPORTED:
635
469
  }
636
470
  }
637
471
  }
472
+ ```
638
473
 
639
- 3. ARRAY MAPPING - Filter and transform arrays:
640
- {
641
- responseMapping: {
642
- type: "array",
643
- source: "results",
644
- limit: 10,
645
- filter: { field: "status", operator: "equals", value: "active" },
646
- itemMapping: {
647
- type: "object",
648
- mappings: { "id": "id", "name": "name" }
649
- }
650
- }
651
- }
652
-
653
- 4. TEMPLATE MAPPING - String interpolation:
474
+ #### Template Mapping
475
+ ```javascript
654
476
  {
655
477
  responseMapping: {
656
478
  type: "template",
657
- template: "User {{name}} ({{email}}) from {$args.source}"
479
+ template: "User {{name}} ({{email}}) from {{$args.source}}"
658
480
  }
659
481
  }
482
+ ```
660
483
 
661
- 5. CONDITIONAL MAPPING - Different mapping based on response structure:
662
- {
663
- responseMapping: {
664
- type: "conditional",
665
- conditions: [
666
- {
667
- if: { field: "status", operator: "equals", value: "success" },
668
- then: { type: "object", mappings: { "result": "data" } }
669
- }
670
- ],
671
- else: { type: "object", mappings: { "error": "message" } }
672
- }
673
- }
484
+ ## Core Features
485
+
486
+ - **OpenAI Function Calling Standard** schemas
487
+ - **JSON Schema validation** with ajv
488
+ - **Secure function registry**
489
+ - **Comprehensive error handling** & transaction management
490
+ - **Audit logging** for compliance
491
+ - **Rate limiting** and input validation
492
+
493
+ ## Value Transformations
494
+
495
+ ### Supported Transforms
496
+ - **Number conversion:** parseInt, parseFloat
497
+ - **String manipulation:** toLowerCase, toUpperCase, trim
498
+ - **Text processing:** replace (regex), concat (prefix/suffix)
499
+ - **Date handling:** Convert to ISO date string
500
+ - **Fallback values:** Default handling for missing data
674
501
 
675
- VALUE TRANSFORMATIONS SUPPORTED:
676
- - parseInt, parseFloat: Number conversion
677
- - toLowerCase, toUpperCase, trim: String manipulation
678
- - replace: Regex replacement
679
- - concat: Add prefix/suffix
680
- - regex: Extract with regex groups
681
- - date: Convert to ISO date string
682
- - default: Fallback values
683
-
684
- SECURITY & BEST PRACTICES:
685
- - No code injection possible - all transformations are declarative
686
- - Secure path traversal with validation
687
- - Fallback handling for missing data
688
- - Type coercion with validation
689
- - Error handling with graceful degradation
690
-
691
- EXAMPLE TOOL CONFIGURATIONS:
692
-
693
- 1. SIMPLE GET REQUEST:
502
+ ### Security & Best Practices
503
+ - No code injection possible - all transformations are declarative
504
+ - Secure path traversal with validation
505
+ - Fallback handling for missing data
506
+ - Type coercion with validation
507
+ - Error handling with graceful degradation
508
+
509
+ ## Example Tool Configurations
510
+
511
+ ### Simple GET Request
512
+ ```javascript
694
513
  {
695
514
  implementation: {
696
515
  type: "http",
@@ -698,8 +517,10 @@ EXAMPLE TOOL CONFIGURATIONS:
698
517
  method: "GET"
699
518
  }
700
519
  }
520
+ ```
701
521
 
702
- 2. AUTHENTICATED POST WITH JSON:
522
+ ### Authenticated POST with JSON
523
+ ```javascript
703
524
  {
704
525
  implementation: {
705
526
  type: "http",
@@ -709,8 +530,10 @@ EXAMPLE TOOL CONFIGURATIONS:
709
530
  },
710
531
  apiKey: "your-bearer-token"
711
532
  }
533
+ ```
712
534
 
713
- 3. PATH PARAMETERS WITH RESPONSE MAPPING:
535
+ ### Path Parameters with Response Mapping
536
+ ```javascript
714
537
  {
715
538
  implementation: {
716
539
  type: "http",
@@ -727,57 +550,4 @@ EXAMPLE TOOL CONFIGURATIONS:
727
550
  }
728
551
  }
729
552
  }
730
-
731
- 4. COMPLEX API WITH ARRAY PROCESSING:
732
- {
733
- implementation: {
734
- type: "http",
735
- url: "https://api.example.com/search",
736
- method: "GET",
737
- responseMapping: {
738
- type: "array",
739
- source: "results",
740
- limit: 5,
741
- filter: { field: "active", operator: "equals", value: true },
742
- itemMapping: {
743
- type: "object",
744
- mappings: {
745
- "id": "id",
746
- "title": "name",
747
- "snippet": {
748
- path: "description",
749
- transform: { type: "regex", pattern: "^(.{100})", group: 1 }
750
- }
751
- }
752
- }
753
- }
754
- }
755
- }
756
-
757
- 5. WEATHER API WITH DECLARATIVE MAPPING:
758
- {
759
- implementation: {
760
- type: "http",
761
- url: "https://wttr.in/{city}",
762
- pathParams: ["city"],
763
- customQuery: "format=j1",
764
- responseMapping: {
765
- type: "jsonPath",
766
- mappings: {
767
- "location.name": {
768
- path: "nearest_area[0].areaName[0].value",
769
- fallback: "$args.city"
770
- },
771
- "current.temp_c": {
772
- path: "current_condition[0].temp_C",
773
- transform: { type: "parseInt", fallback: 0 }
774
- },
775
- "current.condition": {
776
- path: "current_condition[0].weatherDesc[0].value",
777
- fallback: "Unknown"
778
- }
779
- }
780
- }
781
- }
782
- }
783
- */
553
+ ```