@ai.ntellect/core 0.0.22 → 0.0.23

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/.env.example ADDED
@@ -0,0 +1,2 @@
1
+ OPENAI_API_KEY=
2
+ REDIS_URL=
package/.mocharc.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extension": ["ts"],
3
+ "spec": "test/**/*.test.ts",
4
+ "require": "ts-node/register"
5
+ }
@@ -0,0 +1,48 @@
1
+ import { ActionQueueManager } from "../../services/queue";
2
+ import {
3
+ ActionSchema,
4
+ ProcessPromptCallbacks,
5
+ QueueItem,
6
+ QueueResult,
7
+ } from "../../types";
8
+
9
+ export class ActionHandler {
10
+ async executeActions(
11
+ predefinedActions: QueueItem[],
12
+ tools: ActionSchema[],
13
+ callbacks?: ProcessPromptCallbacks
14
+ ) {
15
+ try {
16
+ const queueManager = new ActionQueueManager(tools, {
17
+ onActionStart: callbacks?.onActionStart,
18
+ onActionComplete: callbacks?.onActionComplete,
19
+ onQueueComplete: callbacks?.onQueueComplete,
20
+ onConfirmationRequired: async (message) => {
21
+ if (callbacks?.onConfirmationRequired) {
22
+ return await callbacks.onConfirmationRequired(message);
23
+ }
24
+ return false;
25
+ },
26
+ });
27
+
28
+ queueManager.addToQueue(predefinedActions);
29
+
30
+ if (callbacks?.onQueueStart) {
31
+ callbacks.onQueueStart(predefinedActions);
32
+ }
33
+
34
+ const results = await queueManager.processQueue();
35
+ return { type: "success", data: results || [] };
36
+ } catch (error) {
37
+ console.error("Error processing prompt:", error);
38
+ throw error;
39
+ }
40
+ }
41
+
42
+ hasNonPrepareActions(actions: QueueResult[]): boolean {
43
+ return (
44
+ Array.isArray(actions) &&
45
+ actions.some((action) => action.name?.split("-")[0] !== "prepare")
46
+ );
47
+ }
48
+ }
@@ -0,0 +1,37 @@
1
+ import EventEmitter from "events";
2
+
3
+ export class ConfirmationHandler {
4
+ private readonly CONFIRMATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5
+
6
+ constructor(private readonly eventEmitter: EventEmitter) {}
7
+
8
+ async handleConfirmationRequest(message: string): Promise<boolean> {
9
+ return new Promise((resolve) => {
10
+ const confirmationId = Date.now().toString();
11
+ const handleConfirmation = (data: any) => {
12
+ if (data.confirmationId === confirmationId) {
13
+ this.eventEmitter.removeListener(
14
+ "confirmation-response",
15
+ handleConfirmation
16
+ );
17
+ resolve(data.confirmed);
18
+ }
19
+ };
20
+
21
+ this.eventEmitter.once("confirmation-response", handleConfirmation);
22
+ this.eventEmitter.emit("orchestrator-update", {
23
+ type: "confirmation-required",
24
+ id: confirmationId,
25
+ message,
26
+ });
27
+
28
+ setTimeout(() => {
29
+ this.eventEmitter.removeListener(
30
+ "confirmation-response",
31
+ handleConfirmation
32
+ );
33
+ resolve(false);
34
+ }, this.CONFIRMATION_TIMEOUT);
35
+ });
36
+ }
37
+ }
@@ -0,0 +1,35 @@
1
+ import EventEmitter from "events";
2
+ import { IEventHandler, QueueItem, QueueResult } from "../../types";
3
+
4
+ export class EventHandler implements IEventHandler {
5
+ constructor(private readonly eventEmitter: EventEmitter) {}
6
+
7
+ emitQueueStart(actions: QueueItem[]) {
8
+ this.eventEmitter.emit("orchestrator-update", {
9
+ type: "queue-start",
10
+ actions,
11
+ });
12
+ }
13
+
14
+ emitActionStart(action: QueueItem) {
15
+ this.eventEmitter.emit("orchestrator-update", {
16
+ type: "action-start",
17
+ action: action.name,
18
+ args: action.parameters,
19
+ });
20
+ }
21
+
22
+ emitActionComplete(action: QueueResult) {
23
+ this.eventEmitter.emit("orchestrator-update", {
24
+ type: "action-complete",
25
+ action: action.name,
26
+ result: action.result,
27
+ });
28
+ }
29
+
30
+ emitQueueComplete() {
31
+ this.eventEmitter.emit("orchestrator-update", {
32
+ type: "queue-complete",
33
+ });
34
+ }
35
+ }
package/agent/index.ts ADDED
@@ -0,0 +1,119 @@
1
+ import EventEmitter from "events";
2
+ import { Orchestrator } from "../llm/orchestrator";
3
+ import { Summarizer } from "../llm/synthesizer";
4
+ import { MemoryCache } from "../memory";
5
+ import { ActionSchema, AgentEvent, MemoryScope, User } from "../types";
6
+ import { QueueItemTransformer } from "../utils/queue-item-transformer";
7
+ import { ActionHandler } from "./handlers/ActionHandler";
8
+
9
+ export class Agent {
10
+ private readonly SIMILARITY_THRESHOLD = 95;
11
+ private readonly MAX_RESULTS = 1;
12
+ private readonly actionHandler: ActionHandler;
13
+
14
+ constructor(
15
+ private readonly user: User,
16
+ private readonly dependencies: {
17
+ orchestrator: Orchestrator;
18
+ memoryCache: MemoryCache;
19
+ eventEmitter: EventEmitter;
20
+ },
21
+ private readonly stream: boolean = true
22
+ ) {
23
+ this.actionHandler = new ActionHandler();
24
+ }
25
+
26
+ async start(
27
+ prompt: string,
28
+ contextualizedPrompt: string,
29
+ events: AgentEvent
30
+ ): Promise<any> {
31
+ const request = await this.dependencies.orchestrator.process(
32
+ contextualizedPrompt
33
+ );
34
+
35
+ events.onMessage?.(request);
36
+
37
+ if (request.actions.length > 0) {
38
+ return this.handleActions(
39
+ {
40
+ initialPrompt: prompt,
41
+ actions: request.actions,
42
+ },
43
+ events
44
+ );
45
+ }
46
+ }
47
+
48
+ private async handleActions(
49
+ {
50
+ initialPrompt,
51
+ actions,
52
+ }: {
53
+ initialPrompt: string;
54
+ actions: ActionSchema[];
55
+ },
56
+ events: AgentEvent
57
+ ) {
58
+ const similarActions = await this.findSimilarActions(initialPrompt);
59
+ const predefinedActions = this.transformActions(actions, similarActions);
60
+ const callbacks = {
61
+ onQueueStart: events.onQueueStart,
62
+ onActionStart: events.onActionStart,
63
+ onActionComplete: events.onActionComplete,
64
+ onQueueComplete: events.onQueueComplete,
65
+ onConfirmationRequired: events.onConfirmationRequired,
66
+ };
67
+
68
+ const actionsResult = await this.actionHandler.executeActions(
69
+ predefinedActions,
70
+ this.dependencies.orchestrator.tools,
71
+ callbacks
72
+ );
73
+
74
+ if (!this.actionHandler.hasNonPrepareActions(actionsResult.data)) {
75
+ return {
76
+ data: actionsResult.data,
77
+ initialPrompt,
78
+ };
79
+ }
80
+
81
+ return this.handleActionResults({ ...actionsResult, initialPrompt });
82
+ }
83
+
84
+ private async findSimilarActions(prompt: string) {
85
+ return this.dependencies.memoryCache.findBestMatches(prompt, {
86
+ similarityThreshold: this.SIMILARITY_THRESHOLD,
87
+ maxResults: this.MAX_RESULTS,
88
+ userId: this.user.id,
89
+ scope: MemoryScope.USER,
90
+ });
91
+ }
92
+
93
+ private transformActions(actions: ActionSchema[], similarActions: any[]) {
94
+ let predefinedActions =
95
+ QueueItemTransformer.transformActionsToQueueItems(actions) || [];
96
+
97
+ if (similarActions?.length > 0) {
98
+ predefinedActions =
99
+ QueueItemTransformer.transformFromSimilarActions(similarActions) || [];
100
+ }
101
+
102
+ return predefinedActions;
103
+ }
104
+
105
+ private async handleActionResults(actionsResult: {
106
+ data: any;
107
+ initialPrompt: string;
108
+ }) {
109
+ const summarizer = new Summarizer();
110
+ const summaryData = JSON.stringify({
111
+ result: actionsResult.data,
112
+ initialPrompt: actionsResult.initialPrompt,
113
+ });
114
+
115
+ return this.stream
116
+ ? (await summarizer.streamProcess(summaryData)).toDataStreamResponse()
117
+ : await summarizer.process(summaryData);
118
+ }
119
+ }
@@ -0,0 +1,57 @@
1
+ import { openai } from "@ai-sdk/openai";
2
+ import { generateObject } from "ai";
3
+ import { z } from "zod";
4
+ import { ActionSchema, Agent } from "../../types";
5
+ import { orchestratorContext } from "./context";
6
+
7
+ export class Orchestrator implements Agent {
8
+ private readonly model = openai("gpt-4o-mini");
9
+ public tools: ActionSchema[];
10
+
11
+ constructor(tools: ActionSchema[]) {
12
+ this.tools = tools;
13
+ }
14
+
15
+ async process(prompt: string): Promise<any> {
16
+ try {
17
+ const response = await generateObject({
18
+ model: this.model,
19
+ schema: z.object({
20
+ actions: z.array(
21
+ z.object({
22
+ name: z.string(),
23
+ parameters: z.object({
24
+ name: z.string(),
25
+ value: z.string(),
26
+ }),
27
+ })
28
+ ),
29
+ answer: z.string(),
30
+ }),
31
+ prompt: prompt,
32
+ system: orchestratorContext.compose(this.tools),
33
+ });
34
+
35
+ const validatedResponse = {
36
+ ...response.object,
37
+ actions: response.object.actions.map((action) => ({
38
+ ...action,
39
+ parameters: action.parameters || {},
40
+ })),
41
+ };
42
+
43
+ console.dir(validatedResponse, { depth: null });
44
+
45
+ return validatedResponse;
46
+ } catch (error: any) {
47
+ if (error) {
48
+ console.log("Error in Orchestrator", error.message);
49
+ console.dir(error.value, { depth: null });
50
+ return {
51
+ ...error.value,
52
+ };
53
+ }
54
+ // throw error;
55
+ }
56
+ }
57
+ }
@@ -12,7 +12,7 @@ export class Summarizer implements Agent {
12
12
  onFinish?: (event: any) => void
13
13
  ): Promise<
14
14
  | {
15
- actions: { name: string; reasoning: string }[];
15
+ actions: { name: string; result: string; why: string }[];
16
16
  response: string;
17
17
  }
18
18
  | StreamTextResult<Record<string, any>>
@@ -24,7 +24,8 @@ export class Summarizer implements Agent {
24
24
  actions: z.array(
25
25
  z.object({
26
26
  name: z.string(),
27
- reasoning: z.string(),
27
+ result: z.string(),
28
+ why: z.string(),
28
29
  })
29
30
  ),
30
31
  response: z.string(),
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@ai.ntellect/core",
3
- "version": "0.0.22",
3
+ "version": "0.0.23",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
7
  "build": "rm -rf dist && tsc",
8
- "test": "echo \"Error: no test specified\" && exit 1"
8
+ "test": "mocha --require ts-node/register",
9
+ "test:watch": "mocha --require ts-node/register 'test/**/*.test.ts' --watch"
9
10
  },
10
11
  "keywords": [],
11
12
  "author": "Lorcann Rauzduel",
@@ -17,6 +18,13 @@
17
18
  "zod": "^3.24.1"
18
19
  },
19
20
  "devDependencies": {
21
+ "@jest/globals": "^29.7.0",
22
+ "@types/chai": "^4.3.20",
23
+ "@types/mocha": "^10.0.0",
24
+ "chai": "^4.5.0",
25
+ "mocha": "^10.0.0",
26
+ "ts-node": "^10.9.0",
27
+ "tsconfig-paths": "^4.2.0",
20
28
  "typescript": "^5.7.2"
21
29
  },
22
30
  "repository": {
package/services/queue.ts CHANGED
@@ -38,7 +38,7 @@ export class ActionQueueManager {
38
38
  }
39
39
 
40
40
  this.isProcessing = true;
41
- const actionPromises = [];
41
+ const actionPromises: Promise<QueueResult>[] = [];
42
42
 
43
43
  for (const action of this.queue) {
44
44
  const actionConfig = this.actions.find((a) => a.name === action.name);
@@ -115,7 +115,6 @@ export class ActionQueueManager {
115
115
  error: `Action '${action.name}' not found in actions list`,
116
116
  };
117
117
  }
118
-
119
118
  const actionArgs = action.parameters.reduce<Record<string, string>>(
120
119
  (acc: Record<string, string>, arg: QueueItemParameter) => {
121
120
  acc[arg.name] = arg.value;
@@ -123,25 +122,27 @@ export class ActionQueueManager {
123
122
  },
124
123
  {}
125
124
  );
126
-
127
- console.log(`Executing ${action.name} with args:`, actionArgs);
128
-
129
125
  try {
130
126
  const result = await actionConfig.execute(actionArgs);
131
- return {
127
+ const actionResult = {
132
128
  name: action.name,
133
129
  parameters: actionArgs,
134
130
  result,
135
131
  error: null,
136
132
  };
133
+ console.log("Action executed successfully: ", action.name);
134
+ console.dir(actionResult, { depth: null });
135
+ return actionResult;
137
136
  } catch (error) {
138
- console.error(`Error executing action ${action.name}:`, error);
139
- return {
137
+ const actionResult = {
140
138
  name: action.name,
141
139
  parameters: actionArgs,
142
140
  result: null,
143
141
  error: (error as Error).message || "Unknown error occurred",
144
142
  };
143
+ console.log("Action failed: ", action.name);
144
+ console.dir(actionResult, { depth: null });
145
+ return actionResult;
145
146
  }
146
147
  }
147
148
  }
@@ -0,0 +1,47 @@
1
+ import { expect } from "chai";
2
+ import { z } from "zod";
3
+ import { Orchestrator } from "../../llm/orchestrator";
4
+ import { ActionSchema } from "../../types";
5
+
6
+ describe("Orchestrator", () => {
7
+ let orchestrator: Orchestrator;
8
+
9
+ const mockAction: ActionSchema = {
10
+ name: "prepare-transaction",
11
+ description: "Prepare a transfer transaction",
12
+ parameters: z.object({
13
+ walletAddress: z.string(),
14
+ amount: z.string(),
15
+ networkId: z.string(),
16
+ }),
17
+ execute: async ({ walletAddress, amount, networkId }) => {
18
+ return { walletAddress, amount, networkId };
19
+ },
20
+ };
21
+
22
+ beforeEach(() => {
23
+ orchestrator = new Orchestrator([mockAction]);
24
+ });
25
+
26
+ it("should process a prompt and return just the answer", async function () {
27
+ this.timeout(10000);
28
+
29
+ const prompt = "Hello how are you?";
30
+ const result = await orchestrator.process(prompt);
31
+
32
+ expect(result).to.have.property("answer").that.is.a("string");
33
+ });
34
+
35
+ it("should process a prompt and return valid actions", async function () {
36
+ this.timeout(10000);
37
+
38
+ const prompt = "Send 0.1 ETH to 0x123...456 on ethereum";
39
+ const result = await orchestrator.process(prompt);
40
+ console.dir(result, { depth: null });
41
+ expect(result).to.have.property("actions").that.is.an("array");
42
+ expect(result).to.have.property("answer").that.is.a("string");
43
+ expect(result.actions[0])
44
+ .to.have.property("parameters")
45
+ .that.is.an("object");
46
+ });
47
+ });
@@ -0,0 +1,31 @@
1
+ // import { expect } from "chai";
2
+ // import { Summarizer } from "../../llm/synthesizer";
3
+
4
+ // describe("Synthesizer", () => {
5
+ // let synthesizer: Summarizer;
6
+
7
+ // beforeEach(() => {
8
+ // synthesizer = new Summarizer();
9
+ // });
10
+
11
+ // it("should process results and return a summary", async function () {
12
+ // this.timeout(10000);
13
+
14
+ // const mockResults = JSON.stringify({
15
+ // result: [
16
+ // {
17
+ // name: "prepare-transaction",
18
+ // result: {
19
+ // to: "0x123...456",
20
+ // value: "0.1",
21
+ // chain: { id: 1, name: "ethereum" },
22
+ // },
23
+ // },
24
+ // ],
25
+ // initialPrompt: "Send 0.1 ETH to 0x123...456 on ethereum",
26
+ // });
27
+
28
+ // const result = await synthesizer.process(mockResults);
29
+ // expect(result).to.have.property("response").that.is.a("string");
30
+ // });
31
+ // });
@@ -0,0 +1,44 @@
1
+ // import { expect } from "chai";
2
+ // import { z } from "zod";
3
+ // import { ActionQueueManager } from "../../services/queue";
4
+ // import { ActionSchema } from "../../types";
5
+
6
+ // describe("ActionQueueManager", () => {
7
+ // let queueManager: ActionQueueManager;
8
+
9
+ // const mockAction: ActionSchema = {
10
+ // name: "prepare-transaction",
11
+ // description: "Prepare a transfer transaction",
12
+ // parameters: z.object({
13
+ // walletAddress: z.string(),
14
+ // amount: z.string(),
15
+ // networkId: z.string(),
16
+ // }),
17
+ // execute: async ({ walletAddress, amount, networkId }) => {
18
+ // return { walletAddress, amount, networkId };
19
+ // },
20
+ // };
21
+
22
+ // beforeEach(() => {
23
+ // queueManager = new ActionQueueManager([mockAction]);
24
+ // });
25
+
26
+ // it("should process queue items correctly", async () => {
27
+ // const queueItem = {
28
+ // name: "prepare-transaction",
29
+ // parameters: [
30
+ // { name: "walletAddress", value: "0x123...456" },
31
+ // { name: "amount", value: "0.1" },
32
+ // { name: "networkId", value: "1" },
33
+ // ],
34
+ // };
35
+
36
+ // queueManager.addToQueue([queueItem]);
37
+ // const results = await queueManager.processQueue();
38
+
39
+ // expect(results).to.exist;
40
+ // expect(results!).to.be.an("array");
41
+ // expect(results![0]).to.have.property("name", "prepare-transaction");
42
+ // expect(results![0]).to.have.property("result").that.is.an("object");
43
+ // });
44
+ // });
package/tsconfig.json CHANGED
@@ -1,112 +1,16 @@
1
1
  {
2
2
  "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "moduleResolution": "node",
6
+ "lib": ["ES2020"],
7
+ "declaration": true,
3
8
  "outDir": "./dist",
4
- /* Visit https://aka.ms/tsconfig to read more about this file */
5
-
6
- /* Projects */
7
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
8
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
9
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
10
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
11
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
12
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
13
-
14
- /* Language and Environment */
15
- "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
16
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
17
- // "jsx": "preserve", /* Specify what JSX code is generated. */
18
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
-
28
- /* Modules */
29
- "module": "commonjs" /* Specify what module code is generated. */,
30
- // "rootDir": "./", /* Specify the root folder within your source files. */
31
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
32
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40
- // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
41
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
- // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
45
- // "resolveJsonModule": true, /* Enable importing .json files. */
46
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
-
49
- /* JavaScript Support */
50
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
-
54
- /* Emit */
55
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
56
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
57
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
59
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
62
- // "outDir": "./", /* Specify an output folder for all emitted files. */
63
- // "removeComments": true, /* Disable emitting comments. */
64
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
65
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
- // "newLine": "crlf", /* Set the newline character for emitting files. */
71
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
-
77
- /* Interop Constraints */
78
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
81
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
82
- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
83
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
84
- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
85
-
86
- /* Type Checking */
87
- "strict": true /* Enable all strict type-checking options. */,
88
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
89
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
90
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
91
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
92
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
93
- // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
94
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
95
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
96
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
97
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
98
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
99
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
100
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
101
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
102
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
103
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
104
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
105
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
106
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
107
-
108
- /* Completeness */
109
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
110
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
111
- }
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true
13
+ },
14
+ "include": ["src/**/*", "test/**/*"],
15
+ "exclude": ["node_modules", "dist"]
112
16
  }
package/types.ts CHANGED
@@ -17,6 +17,22 @@ export interface QueueItem {
17
17
  parameters: QueueItemParameter[];
18
18
  }
19
19
 
20
+ export interface IEventHandler {
21
+ emitQueueStart(actions: QueueItem[]): void;
22
+ emitActionStart(action: QueueItem): void;
23
+ emitActionComplete(action: QueueResult): void;
24
+ emitQueueComplete(): void;
25
+ }
26
+
27
+ export type AgentEvent = {
28
+ onMessage?: (data: any) => void;
29
+ onQueueStart?: (actions: QueueItem[]) => void;
30
+ onActionStart?: (action: QueueItem) => void;
31
+ onActionComplete?: (action: QueueResult) => void;
32
+ onQueueComplete?: (actions: QueueResult[]) => void;
33
+ onConfirmationRequired?: (message: string) => Promise<boolean>;
34
+ };
35
+
20
36
  export interface QueueResult {
21
37
  name: string;
22
38
  parameters: Record<string, string>;
@@ -1,33 +0,0 @@
1
- import { openai } from "@ai-sdk/openai";
2
- import { generateObject } from "ai";
3
- import { z } from "zod";
4
- import { ActionSchema, Agent } from "../../types";
5
- import { orchestratorContext } from "./context";
6
-
7
- export class Orchestrator implements Agent {
8
- private readonly model = openai("gpt-4o-mini");
9
- public tools: ActionSchema[];
10
-
11
- constructor(tools: ActionSchema[]) {
12
- this.tools = tools;
13
- }
14
-
15
- async process(prompt: string): Promise<any> {
16
- const response = await generateObject({
17
- model: this.model,
18
- schema: z.object({
19
- actions: z.array(
20
- z.object({
21
- name: z.string(),
22
- parameters: z.record(z.string(), z.any()),
23
- })
24
- ),
25
- answer: z.string(),
26
- }),
27
- prompt: prompt,
28
- system: orchestratorContext.compose(this.tools),
29
- });
30
-
31
- return response.object;
32
- }
33
- }
package/workflow/index.ts DELETED
@@ -1,253 +0,0 @@
1
- import EventEmitter from "events";
2
- import { Orchestrator } from "../agents/orchestrator";
3
- import { Summarizer } from "../agents/synthesizer";
4
- import { MemoryCache } from "../memory";
5
- import { ActionQueueManager } from "../services/queue";
6
- import {
7
- ActionSchema,
8
- MemoryScope,
9
- MemoryType,
10
- ProcessPromptCallbacks,
11
- QueueItem,
12
- QueueResult,
13
- User,
14
- } from "../types";
15
- import { QueueItemTransformer } from "../utils/queue-item-transformer";
16
-
17
- export class Workflow {
18
- private readonly CONFIRMATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
19
- private readonly SIMILARITY_THRESHOLD = 95;
20
- private readonly MAX_RESULTS = 1;
21
-
22
- constructor(
23
- private readonly user: User,
24
- private readonly dependencies: {
25
- orchestrator: Orchestrator;
26
- memoryCache: MemoryCache;
27
- eventEmitter: EventEmitter;
28
- }
29
- ) {}
30
-
31
- async start(prompt: string, contextualizedPrompt: string): Promise<any> {
32
- const request = await this.dependencies.orchestrator.process(
33
- contextualizedPrompt
34
- );
35
-
36
- this.dependencies.eventEmitter.emit("orchestrator-update", {
37
- type: "on-message",
38
- data: request,
39
- });
40
-
41
- if (request.actions.length > 0) {
42
- return this.handleActions({
43
- initialPrompt: prompt,
44
- actions: request.actions,
45
- });
46
- }
47
- }
48
-
49
- private async handleActions({
50
- initialPrompt,
51
- actions,
52
- }: {
53
- initialPrompt: string;
54
- actions: ActionSchema[];
55
- }) {
56
- let predefinedActions: any[] = actions;
57
- console.log("\n🔍 Predefined actions:", predefinedActions);
58
- const similarActions = await this.dependencies.memoryCache.findBestMatches(
59
- initialPrompt,
60
- {
61
- similarityThreshold: this.SIMILARITY_THRESHOLD,
62
- maxResults: this.MAX_RESULTS,
63
- userId: this.user.id,
64
- scope: MemoryScope.USER,
65
- }
66
- );
67
-
68
- console.log("\n🔍 Similar actions:", similarActions);
69
-
70
- predefinedActions =
71
- QueueItemTransformer.transformActionsToQueueItems(predefinedActions) ||
72
- [];
73
- console.log("\n🔍 Transformed predefined actions:", predefinedActions);
74
- if (similarActions && similarActions.length > 0) {
75
- predefinedActions =
76
- QueueItemTransformer.transformFromSimilarActions(similarActions) || [];
77
- console.log("\n🔍 Transformed similar actions:", predefinedActions);
78
- }
79
- console.log("\n🔍 Final actions:", predefinedActions);
80
- const callbacks = this.createCallbacks(initialPrompt, similarActions);
81
-
82
- console.log("\n🔍 Queue prepared");
83
- const actionsResult = await this.executeActions(
84
- predefinedActions,
85
- this.dependencies.orchestrator.tools,
86
- callbacks
87
- );
88
-
89
- console.log("\n🔍 Actions result:", actionsResult);
90
- return this.handleActionResults({
91
- ...actionsResult,
92
- initialPrompt,
93
- });
94
- }
95
-
96
- private async executeActions(
97
- predefinedActions: QueueItem[],
98
- tools: ActionSchema[],
99
- callbacks?: ProcessPromptCallbacks
100
- ) {
101
- try {
102
- const queueManager = new ActionQueueManager(tools, {
103
- onActionStart: callbacks?.onActionStart,
104
- onActionComplete: callbacks?.onActionComplete,
105
- onQueueComplete: callbacks?.onQueueComplete,
106
- onConfirmationRequired: async (message) => {
107
- if (callbacks?.onConfirmationRequired) {
108
- return await callbacks.onConfirmationRequired(message);
109
- }
110
- return false;
111
- },
112
- });
113
-
114
- queueManager.addToQueue(predefinedActions);
115
-
116
- if (callbacks?.onQueueStart) {
117
- callbacks.onQueueStart(predefinedActions);
118
- }
119
-
120
- console.log("Processing queue...");
121
- const results = await queueManager.processQueue();
122
-
123
- console.log("Queue completed:");
124
- console.dir(results, { depth: null });
125
-
126
- return {
127
- type: "success",
128
- data: results || [],
129
- };
130
- } catch (error) {
131
- console.error("Error processing prompt:", error);
132
- throw error;
133
- }
134
- }
135
-
136
- private createCallbacks(
137
- prompt: string,
138
- similarActions: any[]
139
- ): ProcessPromptCallbacks {
140
- return {
141
- onQueueStart: async (actions: QueueItem[]) => {
142
- console.dir(actions, { depth: null });
143
- this.dependencies.eventEmitter.emit("orchestrator-update", {
144
- type: "queue-start",
145
- actions,
146
- });
147
- },
148
- onActionStart: (action: QueueItem) => {
149
- this.dependencies.eventEmitter.emit("orchestrator-update", {
150
- type: "action-start",
151
- action: action.name,
152
- args: action.parameters,
153
- });
154
- },
155
- onActionComplete: (action: QueueResult) => {
156
- this.dependencies.eventEmitter.emit("orchestrator-update", {
157
- type: "action-complete",
158
- action: action.name,
159
- result: action.result,
160
- });
161
- },
162
- onQueueComplete: async (actions: QueueResult[]) => {
163
- if (!similarActions.length) {
164
- await this.saveToMemory(prompt, actions);
165
- }
166
- this.dependencies.eventEmitter.emit("orchestrator-update", {
167
- type: "queue-complete",
168
- });
169
- },
170
- onConfirmationRequired: this.handleConfirmationRequest.bind(this),
171
- };
172
- }
173
-
174
- private async handleConfirmationRequest(message: string): Promise<boolean> {
175
- return new Promise((resolve) => {
176
- const confirmationId = Date.now().toString();
177
-
178
- const handleConfirmation = (data: any) => {
179
- if (data.confirmationId === confirmationId) {
180
- this.dependencies.eventEmitter.removeListener(
181
- "confirmation-response",
182
- handleConfirmation
183
- );
184
- resolve(data.confirmed);
185
- }
186
- };
187
-
188
- this.dependencies.eventEmitter.once(
189
- "confirmation-response",
190
- handleConfirmation
191
- );
192
-
193
- this.dependencies.eventEmitter.emit("orchestrator-update", {
194
- type: "confirmation-required",
195
- id: confirmationId,
196
- message,
197
- });
198
-
199
- setTimeout(() => {
200
- this.dependencies.eventEmitter.removeListener(
201
- "confirmation-response",
202
- handleConfirmation
203
- );
204
- resolve(false);
205
- }, this.CONFIRMATION_TIMEOUT);
206
- });
207
- }
208
-
209
- private async saveToMemory(
210
- prompt: string,
211
- actions: QueueResult[]
212
- ): Promise<void> {
213
- console.log("\n🔍 Creating memory...");
214
- await this.dependencies.memoryCache.createMemory({
215
- content: prompt,
216
- userId: this.user.id,
217
- scope: MemoryScope.USER,
218
- type: MemoryType.ACTION,
219
- data: actions,
220
- });
221
- }
222
-
223
- private async handleActionResults(
224
- actionsResult: {
225
- data: any;
226
- initialPrompt: string;
227
- },
228
- stream: boolean = true
229
- ) {
230
- if (!this.hasNonPrepareActions(actionsResult.data)) {
231
- return;
232
- }
233
-
234
- const summarizer = new Summarizer();
235
- const summaryData = JSON.stringify({
236
- result: actionsResult.data,
237
- initialPrompt: actionsResult.initialPrompt,
238
- });
239
-
240
- return stream
241
- ? (await summarizer.streamProcess(summaryData)).toDataStreamResponse()
242
- : await summarizer.process(summaryData);
243
- }
244
-
245
- private hasNonPrepareActions(actions: QueueResult[]): boolean {
246
- return (
247
- Array.isArray(actions) &&
248
- actions.some(
249
- (action: QueueResult) => action.name?.split("-")[0] !== "prepare"
250
- )
251
- );
252
- }
253
- }
File without changes
File without changes