@ai.ntellect/core 0.4.1 → 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.
@@ -0,0 +1,491 @@
1
+ import { configDotenv } from "dotenv";
2
+ import EventEmitter from "events";
3
+ import {
4
+ mergeState,
5
+ Node,
6
+ Persistence,
7
+ RealTimeNotifier,
8
+ SharedState,
9
+ WorkflowDefinition,
10
+ } from "../types";
11
+
12
+ configDotenv();
13
+
14
+ /**
15
+ * Represents a directed worflow structure capable of executing nodes in sequence or parallel.
16
+ * The worflow can handle state management, event emissions, and conditional execution paths.
17
+ *
18
+ * @template T - The type of data stored in the worflow's context
19
+ */
20
+ export class Workflow<T> {
21
+ /** Stores global context data accessible to all nodes */
22
+ public globalContext: Map<string, any>;
23
+
24
+ /** Event emitter for handling worflow-wide events */
25
+ private eventEmitter: EventEmitter;
26
+
27
+ /** Map of all nodes in the worflow */
28
+ public nodes: Map<string, Node<T>>;
29
+
30
+ /** Set of nodes that have been executed */
31
+ public executedNodes: Set<string>;
32
+
33
+ /** Name identifier for the worflow */
34
+ public name: string;
35
+
36
+ /** Optional persistence layer for saving worflow state */
37
+ private persistence: Persistence<T> | null;
38
+
39
+ /** Optional notifier for real-time updates */
40
+ private notifier: RealTimeNotifier | null;
41
+
42
+ /**
43
+ * Creates a new Workflow instance.
44
+ *
45
+ * @param {WorkflowDefinition<T>} [definition] - Initial worflow structure and configuration
46
+ * @param {Object} [config] - Additional configuration options
47
+ * @param {boolean} [config.autoDetectCycles] - Whether to check for cycles during initialization
48
+ * @throws {Error} If cycles are detected when autoDetectCycles is true
49
+ */
50
+ constructor(
51
+ definition?: WorkflowDefinition<T>,
52
+ config?: { autoDetectCycles?: boolean }
53
+ ) {
54
+ this.name = definition?.name || "anonymous";
55
+ this.eventEmitter = new EventEmitter();
56
+ this.globalContext = new Map();
57
+ this.nodes = new Map();
58
+ this.executedNodes = new Set();
59
+ this.persistence = null;
60
+ this.notifier = null;
61
+
62
+ if (definition) {
63
+ this.loadFromDefinition(definition);
64
+ }
65
+
66
+ if (config?.autoDetectCycles && this.checkForCycles()) {
67
+ throw new Error("Cycle detected in the worflow");
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Adds a value to the global context.
73
+ * @param {string} key - The key to store the value under
74
+ * @param {any} value - The value to store
75
+ */
76
+ addToContext(key: string, value: any): void {
77
+ this.globalContext.set(key, value);
78
+ }
79
+
80
+ /**
81
+ * Retrieves a value from the global context.
82
+ * @param {string} key - The key to retrieve
83
+ * @returns {any} The stored value, or undefined if not found
84
+ */
85
+ getContext(key: string): any {
86
+ return this.globalContext.get(key);
87
+ }
88
+
89
+ /**
90
+ * Removes a value from the global context.
91
+ * @param {string} key - The key to remove
92
+ */
93
+ removeFromContext(key: string): void {
94
+ this.globalContext.delete(key);
95
+ }
96
+
97
+ /**
98
+ * Sets the persistence layer for the worflow.
99
+ * @param {Persistence<T>} persistence - The persistence implementation
100
+ */
101
+ setPersistence(persistence: Persistence<T>): void {
102
+ this.persistence = persistence;
103
+ }
104
+
105
+ /**
106
+ * Sets the real-time notifier for the worflow.
107
+ * @param {RealTimeNotifier} notifier - The notifier implementation
108
+ */
109
+ setNotifier(notifier: RealTimeNotifier): void {
110
+ this.notifier = notifier;
111
+ }
112
+
113
+ /**
114
+ * Loads a worflow structure from a definition object.
115
+ * @private
116
+ * @param {WorkflowDefinition<T>} definition - The worflow definition
117
+ */
118
+ private loadFromDefinition(definition: WorkflowDefinition<T>): void {
119
+ Object.entries(definition.nodes).forEach(([_, nodeConfig]) => {
120
+ this.addNode(nodeConfig, {
121
+ condition: nodeConfig.condition,
122
+ next: nodeConfig.next,
123
+ });
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Recursively checks if a node is part of a cycle.
129
+ * @private
130
+ * @param {string} nodeName - The name of the node to check
131
+ * @param {Set<string>} visited - Set of visited nodes
132
+ * @param {Set<string>} recStack - Set of nodes in the current recursion stack
133
+ * @returns {boolean} True if a cycle is detected, false otherwise
134
+ */
135
+ private isCyclic(
136
+ nodeName: string,
137
+ visited: Set<string>,
138
+ recStack: Set<string>
139
+ ): boolean {
140
+ if (!visited.has(nodeName)) {
141
+ visited.add(nodeName);
142
+ recStack.add(nodeName);
143
+
144
+ const currentNode = this.nodes.get(nodeName);
145
+ if (currentNode?.next) {
146
+ for (const nextNode of currentNode.next) {
147
+ if (
148
+ !visited.has(nextNode) &&
149
+ this.isCyclic(nextNode, visited, recStack)
150
+ ) {
151
+ return true;
152
+ } else if (recStack.has(nextNode)) {
153
+ return true;
154
+ }
155
+ }
156
+ }
157
+ }
158
+ recStack.delete(nodeName);
159
+ return false;
160
+ }
161
+
162
+ /**
163
+ * Checks if the worflow contains any cycles.
164
+ * @returns {boolean} True if cycles are detected, false otherwise
165
+ */
166
+ public checkForCycles(): boolean {
167
+ const visited = new Set<string>();
168
+ const recStack = new Set<string>();
169
+
170
+ for (const nodeName of this.nodes.keys()) {
171
+ if (this.isCyclic(nodeName, visited, recStack)) {
172
+ return true;
173
+ }
174
+ }
175
+ return false;
176
+ }
177
+
178
+ /**
179
+ * Adds a new node to the worflow.
180
+ * @param {Node<T>} node - The node to add
181
+ * @param {Object} options - Node configuration options
182
+ * @param {Function} [options.condition] - Condition function for node execution
183
+ * @param {string[]} [options.next] - Array of next node names
184
+ * @param {string[]} [options.events] - Array of event names to listen for
185
+ */
186
+ addNode(
187
+ node: Node<T>,
188
+ {
189
+ condition,
190
+ next,
191
+ events,
192
+ }: {
193
+ condition?: (state: SharedState<T>) => boolean;
194
+ next?: string[];
195
+ events?: string[];
196
+ }
197
+ ): void {
198
+ node.next = next;
199
+ node.condition = condition;
200
+
201
+ if (events) {
202
+ events.forEach((event) => {
203
+ this.eventEmitter.on(event, async (data) => {
204
+ console.log(`Event "${event}" received by node "${node.name}"`);
205
+ const state = data.state || {};
206
+ await this.execute(state, node.name);
207
+ });
208
+ });
209
+ }
210
+
211
+ this.nodes.set(node.name, node);
212
+ }
213
+
214
+ /**
215
+ * Emits an event to the worflow's event emitter.
216
+ * @param {string} eventName - Name of the event to emit
217
+ * @param {any} data - Data to pass with the event
218
+ */
219
+ public emit(eventName: string, data: any): void {
220
+ console.log(`Event "${eventName}" emitted with data:`, data);
221
+ this.eventEmitter.emit(eventName, data);
222
+ }
223
+
224
+ /**
225
+ * Adds a subworflow as a node in the current worflow.
226
+ * @param {Workflow<T>} subWorkflow - The subworflow to add
227
+ * @param {string} entryNode - The entry node name in the subworflow
228
+ * @param {string} name - The name for the subworflow node
229
+ */
230
+ addSubWorkflow(
231
+ subWorkflow: Workflow<T>,
232
+ entryNode: string,
233
+ name: string
234
+ ): void {
235
+ const subWorkflowNode: Node<T> = {
236
+ name,
237
+ execute: async (state) => {
238
+ console.log(`Executing subworflow: ${name}`);
239
+ await subWorkflow.execute(state, entryNode);
240
+ return state;
241
+ },
242
+ };
243
+ this.nodes.set(name, subWorkflowNode);
244
+ }
245
+
246
+ /**
247
+ * Executes the worflow starting from a specific node.
248
+ * @param {SharedState<T>} state - The initial state
249
+ * @param {string} startNode - The name of the starting node
250
+ * @param {Function} [onStream] - Callback for streaming state updates
251
+ * @param {Function} [onError] - Callback for handling errors
252
+ */
253
+ async execute(
254
+ state: SharedState<T>,
255
+ startNode: string,
256
+ onStream?: (state: SharedState<T>) => void,
257
+ onError?: (error: Error, nodeName: string, state: SharedState<T>) => void
258
+ ): Promise<void> {
259
+ let currentNodeName = startNode;
260
+
261
+ while (currentNodeName) {
262
+ this.executedNodes.add(currentNodeName);
263
+
264
+ const currentNode = this.nodes.get(currentNodeName);
265
+ if (!currentNode) throw new Error(`Node ${currentNodeName} not found.`);
266
+
267
+ if (currentNode.condition && !currentNode.condition(state)) {
268
+ console.log(
269
+ `Condition for node "${currentNodeName}" not met. Ending Workflow.`
270
+ );
271
+ break;
272
+ }
273
+
274
+ try {
275
+ if (this.notifier) {
276
+ this.notifier.notify("nodeExecutionStarted", {
277
+ worflow: this.name,
278
+ node: currentNodeName,
279
+ });
280
+ }
281
+
282
+ console.log(`Executing node: ${currentNodeName}`);
283
+ const newState = await currentNode.execute(state);
284
+ Object.assign(state, mergeState(state, newState));
285
+
286
+ if (onStream) onStream(state);
287
+
288
+ if (this.persistence) {
289
+ await this.persistence.saveState(this.name, state, currentNodeName);
290
+ }
291
+
292
+ if (this.notifier) {
293
+ await this.notifier.notify("nodeExecutionCompleted", {
294
+ worflow: this.name,
295
+ node: currentNodeName,
296
+ state,
297
+ });
298
+ }
299
+ } catch (error) {
300
+ console.error(`Error in node ${currentNodeName}:`, error);
301
+ if (onError) onError(error as Error, currentNodeName, state);
302
+ if (this.notifier) {
303
+ this.notifier.notify("nodeExecutionFailed", {
304
+ worflow: this.name,
305
+ node: currentNodeName,
306
+ state,
307
+ error,
308
+ });
309
+ }
310
+ break;
311
+ }
312
+
313
+ const nextNodes = currentNode.next || [];
314
+ if (nextNodes.length > 1) {
315
+ await Promise.all(
316
+ nextNodes.map((nextNode) =>
317
+ this.execute(state, nextNode, onStream, onError)
318
+ )
319
+ );
320
+ break;
321
+ } else {
322
+ currentNodeName = nextNodes[0] || "";
323
+ }
324
+ }
325
+
326
+ console.log(`Workflow completed for node: ${startNode}`);
327
+ }
328
+
329
+ /**
330
+ * Executes multiple nodes in parallel with a concurrency limit.
331
+ * @param {SharedState<T>} state - The shared state
332
+ * @param {string[]} nodeNames - Array of node names to execute
333
+ * @param {number} [concurrencyLimit=5] - Maximum number of concurrent executions
334
+ * @param {Function} [onStream] - Callback for streaming state updates
335
+ * @param {Function} [onError] - Callback for handling errors
336
+ */
337
+ async executeParallel(
338
+ state: SharedState<T>,
339
+ nodeNames: string[],
340
+ concurrencyLimit: number = 5,
341
+ onStream?: (state: SharedState<T>) => void,
342
+ onError?: (error: Error, nodeName: string, state: SharedState<T>) => void
343
+ ): Promise<void> {
344
+ console.log(`Executing nodes in parallel: ${nodeNames.join(", ")}`);
345
+
346
+ const executeWithLimit = async (nodeName: string) => {
347
+ await this.execute(state, nodeName, onStream, onError);
348
+ };
349
+
350
+ const chunks = [];
351
+ for (let i = 0; i < nodeNames.length; i += concurrencyLimit) {
352
+ chunks.push(nodeNames.slice(i, i + concurrencyLimit));
353
+ }
354
+
355
+ for (const chunk of chunks) {
356
+ await Promise.all(chunk.map(executeWithLimit));
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Updates the worflow structure with a new definition.
362
+ * @param {WorkflowDefinition<T>} definition - The new worflow definition
363
+ */
364
+ updateWorkflow(definition: WorkflowDefinition<T>): void {
365
+ Object.entries(definition.nodes).forEach(([_, nodeConfig]) => {
366
+ if (this.nodes.has(nodeConfig.name)) {
367
+ const existingNode = this.nodes.get(nodeConfig.name)!;
368
+ existingNode.next = nodeConfig.next || existingNode.next;
369
+ existingNode.condition = nodeConfig.condition || existingNode.condition;
370
+ } else {
371
+ this.addNode(nodeConfig, {
372
+ condition: nodeConfig.condition,
373
+ next: nodeConfig.next,
374
+ });
375
+ }
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Replace the worflow with a new definition.
381
+ * @param {WorkflowDefinition<T>} definition - The new worflow definition
382
+ */
383
+ replaceWorkflow(definition: WorkflowDefinition<T>): void {
384
+ this.nodes.clear();
385
+ this.loadFromDefinition(definition);
386
+ }
387
+
388
+ /**
389
+ * Generates a visual representation of the worflow using Mermaid diagram syntax.
390
+ * The diagram shows all nodes and their connections, with special highlighting for:
391
+ * - Entry nodes (green)
392
+ * - Event nodes (yellow)
393
+ * - Conditional nodes (orange)
394
+ *
395
+ * @param {string} [title] - Optional title for the diagram
396
+ * @returns {string} Mermaid diagram syntax representing the worflow
397
+ */
398
+ generateMermaidDiagram(title?: string): string {
399
+ const lines: string[] = ["worflow TD"];
400
+
401
+ if (title) {
402
+ lines.push(` subworflow ${title}`);
403
+ }
404
+
405
+ // Add nodes with styling
406
+ this.nodes.forEach((node, nodeName) => {
407
+ const hasEvents = node.events && node.events.length > 0;
408
+ const hasCondition = !!node.condition;
409
+
410
+ // Style nodes based on their properties
411
+ let style = "";
412
+ if (hasEvents) {
413
+ style = "style " + nodeName + " fill:#FFD700,stroke:#DAA520"; // Yellow for event nodes
414
+ } else if (hasCondition) {
415
+ style = "style " + nodeName + " fill:#FFA500,stroke:#FF8C00"; // Orange for conditional nodes
416
+ }
417
+
418
+ // Add node definition
419
+ lines.push(` ${nodeName}[${nodeName}]`);
420
+ if (style) {
421
+ lines.push(` ${style}`);
422
+ }
423
+ });
424
+
425
+ // Add connections
426
+ this.nodes.forEach((node, nodeName) => {
427
+ if (node.next) {
428
+ node.next.forEach((nextNode) => {
429
+ let connectionStyle = "";
430
+ if (node.condition) {
431
+ connectionStyle = "---|condition|"; // Add label for conditional connections
432
+ } else {
433
+ connectionStyle = "-->"; // Normal connection
434
+ }
435
+ lines.push(` ${nodeName} ${connectionStyle} ${nextNode}`);
436
+ });
437
+ }
438
+
439
+ // Add event connections if any
440
+ if (node.events && node.events.length > 0) {
441
+ node.events.forEach((event) => {
442
+ const eventNodeId = `${event}_event`;
443
+ lines.push(` ${eventNodeId}((${event})):::event`);
444
+ lines.push(` ${eventNodeId} -.->|trigger| ${nodeName}`);
445
+ });
446
+ // Add style class for event nodes
447
+ lines.push(" classDef event fill:#FFD700,stroke:#DAA520");
448
+ }
449
+ });
450
+
451
+ if (title) {
452
+ lines.push(" end");
453
+ }
454
+
455
+ return lines.join("\n");
456
+ }
457
+
458
+ /**
459
+ * Renders the worflow visualization using Mermaid syntax.
460
+ * This method can be used to visualize the worflow structure in supported environments.
461
+ *
462
+ * @param {string} [title] - Optional title for the visualization
463
+ */
464
+ visualize(title?: string): void {
465
+ const diagram = this.generateMermaidDiagram(title);
466
+ console.log(
467
+ "To visualize this worflow, use a Mermaid-compatible renderer with this syntax:"
468
+ );
469
+ console.log("\n```mermaid");
470
+ console.log(diagram);
471
+ console.log("```\n");
472
+ }
473
+
474
+ exportWorkflowToJson<T>(worflow: WorkflowDefinition<T>): string {
475
+ const result = {
476
+ worflowName: worflow.name,
477
+ entryNode: worflow.entryNode,
478
+ nodes: Object.entries(worflow.nodes).reduce((acc, [key, node]) => {
479
+ acc[key] = {
480
+ name: node.name,
481
+ description: node.description || "No description provided",
482
+ execute: node.execute.name,
483
+ condition: node.condition ? node.condition.toString() : "None",
484
+ next: node.next || [],
485
+ };
486
+ return acc;
487
+ }, {} as Record<string, any>),
488
+ };
489
+ return JSON.stringify(result, null, 2);
490
+ }
491
+ }
package/t.ts CHANGED
@@ -1,133 +1,25 @@
1
- export interface NetworkConfig {
2
- name: string;
3
- id?: number;
4
- rpc: string;
5
- explorerUrl: string;
6
- nativeToken: string; // WETH
7
- }
8
- export const networkConfigs: Record<string, NetworkConfig> = {
9
- ethereum: {
10
- name: "Ethereum Mainnet",
11
- id: 1,
12
- rpc: "https://eth.llamarpc.com",
13
- explorerUrl: "https://etherscan.io",
14
- nativeToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
15
- },
16
- polygon: {
17
- name: "Polygon Mainnet",
18
- id: 137,
19
- rpc: "https://polygon.llamarpc.com",
20
- explorerUrl: "https://polygonscan.com",
21
- nativeToken: "0x0000000000000000000000000000000000001010",
22
- },
23
- arbitrum: {
24
- name: "Arbitrum Mainnet",
25
- id: 42161,
26
- rpc: "https://arbitrum.llamarpc.com",
27
- explorerUrl: "https://arbiscan.io",
28
- nativeToken: "0x82af49447d8a07e3bd95bd0d56f35241523fbab1",
29
- },
30
- base: {
31
- name: "Base Mainnet",
32
- id: 8453,
33
- rpc: "https://base.llamarpc.com",
34
- explorerUrl: "https://basescan.org",
35
- nativeToken: "0x4200000000000000000000000000000000000006",
36
- },
37
- solana: {
38
- name: "Solana Mainnet",
39
- rpc: "https://api.mainnet-beta.solana.com",
40
- explorerUrl: "https://solscan.io",
41
- nativeToken: "So11111111111111111111111111111111111111112",
42
- },
43
- sepolia: {
44
- name: "Sepolia Testnet",
45
- id: 11155111,
46
- rpc: "https://sepolia.llamarpc.com",
47
- explorerUrl: "https://sepolia.etherscan.io",
48
- nativeToken: "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14",
49
- },
50
- baseSepolia: {
51
- name: "Base Sepolia Testnet",
52
- id: 84532,
53
- rpc: "https://base-sepolia-rpc.publicnode.com",
54
- explorerUrl: "https://sepolia.basescan.org",
55
- nativeToken: "0x4200000000000000000000000000000000000006",
56
- },
57
- };
58
-
59
- export const getNetworkProvider = (networkName: string) => {
60
- const config = networkConfigs[networkName.toLowerCase()];
61
- if (!config) {
62
- throw new Error(`Network ${networkName} not supported`);
63
- }
64
- return { config };
65
- };
66
-
67
- import { parseEther } from "ethers";
1
+ import { deepseek } from "@ai-sdk/deepseek";
2
+ import { streamObject } from "ai";
3
+ import { configDotenv } from "dotenv";
68
4
  import { z } from "zod";
69
5
 
70
- export type TransactionPrepared = {
71
- to: string;
72
- value: string;
73
- data?: string;
74
- chain: {
75
- id: number;
76
- rpc: string;
77
- };
78
- type: "transfer" | "approve" | "swap";
79
- method?: string;
80
- params?: any[];
81
- };
6
+ configDotenv();
7
+ const model = deepseek("deepseek-chat");
82
8
 
83
- export const prepareEvmTransaction = {
84
- name: "prepare-evm-transaction",
85
- description: "Prepare a transaction for the user to sign.",
86
- parameters: z.object({
87
- walletAddress: z.string(),
88
- amount: z
89
- .string()
90
- .describe("Ask the user for the amount to send, if not specified"),
91
- network: z
92
- .string()
93
- .describe(
94
- "Examples networks: ethereum, arbitrum, base. IMPORTANT: You must respect the network name."
95
- ),
96
- }),
97
- execute: async ({
98
- walletAddress,
99
- amount,
100
- network,
101
- }: {
102
- walletAddress: string;
103
- amount: string;
104
- network: string;
105
- }): Promise<TransactionPrepared> => {
106
- try {
107
- console.log("💰 Preparing transaction", {
108
- to: walletAddress,
109
- amount,
110
- network,
111
- });
112
-
113
- const networkConfig = networkConfigs[network.toLowerCase()];
114
-
115
- if (!networkConfig) {
116
- throw new Error(`Network ${network} not found`);
117
- }
118
-
119
- return {
120
- to: walletAddress,
121
- value: parseEther(amount).toString(),
122
- chain: {
123
- id: networkConfig.id || 0,
124
- rpc: networkConfig.rpc,
125
- },
126
- type: "transfer",
127
- };
128
- } catch (error) {
129
- console.error("💰 Error sending transaction:", error);
130
- throw new Error("An error occurred while sending the transaction");
131
- }
132
- },
9
+ const main = async () => {
10
+ try {
11
+ const result = await streamObject({
12
+ model,
13
+ schema: z.object({
14
+ text: z.string(),
15
+ reason: z.string(),
16
+ }),
17
+ prompt: "Tell me why you are so good",
18
+ });
19
+ } catch (error) {
20
+ console.error("🔄 Start handler error:", error);
21
+ throw error;
22
+ }
133
23
  };
24
+
25
+ main();
package/tsconfig.json CHANGED
@@ -9,7 +9,8 @@
9
9
  "strict": true,
10
10
  "esModuleInterop": true,
11
11
  "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true
12
+ "forceConsistentCasingInFileNames": true,
13
+ "resolveJsonModule": true
13
14
  },
14
15
  "exclude": ["node_modules", "dist", "test"]
15
16
  }