flow-evm-agentkit 0.1.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/.cache/replit/env/latest +59 -0
- package/.cache/replit/env/latest.json +1 -0
- package/.cache/replit/modules/nodejs-20.res +1 -0
- package/.cache/replit/modules/replit-rtld-loader.res +1 -0
- package/.cache/replit/modules/replit.res +1 -0
- package/.cache/replit/modules.stamp +0 -0
- package/.cache/replit/nix/dotreplitenv.json +1 -0
- package/.cache/replit/toolchain.json +1 -0
- package/.env.example +25 -0
- package/LICENSE +22 -0
- package/README.md +421 -0
- package/dist/cli/scaffold.d.ts +8 -0
- package/dist/cli/scaffold.d.ts.map +1 -0
- package/dist/cli/scaffold.js +369 -0
- package/dist/cli/scaffold.js.map +1 -0
- package/dist/config/index.d.ts +7 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +42 -0
- package/dist/config/index.js.map +1 -0
- package/dist/core/agent.d.ts +38 -0
- package/dist/core/agent.d.ts.map +1 -0
- package/dist/core/agent.js +255 -0
- package/dist/core/agent.js.map +1 -0
- package/dist/examples/agent-server.d.ts +2 -0
- package/dist/examples/agent-server.d.ts.map +1 -0
- package/dist/examples/agent-server.js +212 -0
- package/dist/examples/agent-server.js.map +1 -0
- package/dist/examples/trading-agent.d.ts +2 -0
- package/dist/examples/trading-agent.d.ts.map +1 -0
- package/dist/examples/trading-agent.js +95 -0
- package/dist/examples/trading-agent.js.map +1 -0
- package/dist/examples/tx-echo-agent.d.ts +2 -0
- package/dist/examples/tx-echo-agent.d.ts.map +1 -0
- package/dist/examples/tx-echo-agent.js +67 -0
- package/dist/examples/tx-echo-agent.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -0
- package/dist/logger/index.d.ts +8 -0
- package/dist/logger/index.d.ts.map +1 -0
- package/dist/logger/index.js +49 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/modules/executor.d.ts +21 -0
- package/dist/modules/executor.d.ts.map +1 -0
- package/dist/modules/executor.js +205 -0
- package/dist/modules/executor.js.map +1 -0
- package/dist/modules/knowledge.d.ts +19 -0
- package/dist/modules/knowledge.d.ts.map +1 -0
- package/dist/modules/knowledge.js +208 -0
- package/dist/modules/knowledge.js.map +1 -0
- package/dist/modules/observer.d.ts +26 -0
- package/dist/modules/observer.d.ts.map +1 -0
- package/dist/modules/observer.js +184 -0
- package/dist/modules/observer.js.map +1 -0
- package/dist/modules/planner.d.ts +15 -0
- package/dist/modules/planner.d.ts.map +1 -0
- package/dist/modules/planner.js +179 -0
- package/dist/modules/planner.js.map +1 -0
- package/dist/types/index.d.ts +67 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +67 -0
@@ -0,0 +1,208 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.Knowledge = void 0;
|
4
|
+
const chromadb_1 = require("chromadb");
|
5
|
+
const redis_1 = require("redis");
|
6
|
+
const logger_1 = require("../logger");
|
7
|
+
const uuid_1 = require("uuid");
|
8
|
+
class Knowledge {
|
9
|
+
chroma = null;
|
10
|
+
chromaCollection = null;
|
11
|
+
redis = null;
|
12
|
+
config;
|
13
|
+
logger;
|
14
|
+
memoryCache = new Map();
|
15
|
+
constructor(config) {
|
16
|
+
this.config = config;
|
17
|
+
this.logger = logger_1.Logger.get();
|
18
|
+
}
|
19
|
+
async initialize() {
|
20
|
+
this.logger.info('Initializing Knowledge module...');
|
21
|
+
// Initialize ChromaDB if available
|
22
|
+
try {
|
23
|
+
this.chroma = new chromadb_1.ChromaClient({
|
24
|
+
path: process.env.CHROMA_HOST || 'http://localhost:8000'
|
25
|
+
});
|
26
|
+
this.chromaCollection = await this.chroma.getOrCreateCollection({
|
27
|
+
name: `${this.config.name}-memories`
|
28
|
+
});
|
29
|
+
this.logger.info('ChromaDB initialized successfully');
|
30
|
+
}
|
31
|
+
catch (error) {
|
32
|
+
this.logger.warn('ChromaDB not available, using in-memory storage:', error);
|
33
|
+
}
|
34
|
+
// Initialize Redis if available
|
35
|
+
try {
|
36
|
+
if (process.env.REDIS_URL) {
|
37
|
+
this.redis = (0, redis_1.createClient)({
|
38
|
+
url: process.env.REDIS_URL
|
39
|
+
});
|
40
|
+
await this.redis.connect();
|
41
|
+
this.logger.info('Redis connected successfully');
|
42
|
+
}
|
43
|
+
}
|
44
|
+
catch (error) {
|
45
|
+
this.logger.warn('Redis not available, using in-memory cache:', error);
|
46
|
+
}
|
47
|
+
}
|
48
|
+
async storeMemory(content, metadata = {}) {
|
49
|
+
const memory = {
|
50
|
+
id: (0, uuid_1.v4)(),
|
51
|
+
content,
|
52
|
+
metadata: {
|
53
|
+
...metadata,
|
54
|
+
agent: this.config.name
|
55
|
+
},
|
56
|
+
timestamp: new Date()
|
57
|
+
};
|
58
|
+
// Store in cache
|
59
|
+
this.memoryCache.set(memory.id, memory);
|
60
|
+
// Store in ChromaDB with embeddings
|
61
|
+
if (this.chromaCollection) {
|
62
|
+
try {
|
63
|
+
await this.chromaCollection.add({
|
64
|
+
ids: [memory.id],
|
65
|
+
documents: [content],
|
66
|
+
metadatas: [memory.metadata]
|
67
|
+
});
|
68
|
+
}
|
69
|
+
catch (error) {
|
70
|
+
this.logger.error('Failed to store memory in ChromaDB:', error);
|
71
|
+
}
|
72
|
+
}
|
73
|
+
// Store in Redis
|
74
|
+
if (this.redis) {
|
75
|
+
try {
|
76
|
+
await this.redis.setEx(`memory:${memory.id}`, 60 * 60 * 24 * 7, // 7 days TTL
|
77
|
+
JSON.stringify(memory));
|
78
|
+
}
|
79
|
+
catch (error) {
|
80
|
+
this.logger.error('Failed to store memory in Redis:', error);
|
81
|
+
}
|
82
|
+
}
|
83
|
+
this.logger.debug(`Stored memory: ${memory.id}`);
|
84
|
+
return memory.id;
|
85
|
+
}
|
86
|
+
async retrieveMemory(id) {
|
87
|
+
// Check cache first
|
88
|
+
if (this.memoryCache.has(id)) {
|
89
|
+
return this.memoryCache.get(id);
|
90
|
+
}
|
91
|
+
// Check Redis
|
92
|
+
if (this.redis) {
|
93
|
+
try {
|
94
|
+
const redisData = await this.redis.get(`memory:${id}`);
|
95
|
+
if (redisData) {
|
96
|
+
const memory = JSON.parse(redisData);
|
97
|
+
this.memoryCache.set(id, memory);
|
98
|
+
return memory;
|
99
|
+
}
|
100
|
+
}
|
101
|
+
catch (error) {
|
102
|
+
this.logger.error('Failed to retrieve memory from Redis:', error);
|
103
|
+
}
|
104
|
+
}
|
105
|
+
return null;
|
106
|
+
}
|
107
|
+
async searchMemories(query, limit = 10) {
|
108
|
+
if (this.chromaCollection) {
|
109
|
+
try {
|
110
|
+
const results = await this.chromaCollection.query({
|
111
|
+
queryTexts: [query],
|
112
|
+
nResults: limit
|
113
|
+
});
|
114
|
+
const memories = [];
|
115
|
+
if (results.ids && results.documents && results.metadatas) {
|
116
|
+
for (let i = 0; i < results.ids[0].length; i++) {
|
117
|
+
const id = results.ids[0][i];
|
118
|
+
const content = results.documents[0][i];
|
119
|
+
const metadata = results.metadatas[0][i];
|
120
|
+
memories.push({
|
121
|
+
id,
|
122
|
+
content: content || '',
|
123
|
+
metadata: metadata || {},
|
124
|
+
timestamp: new Date(typeof metadata?.timestamp === 'string' || typeof metadata?.timestamp === 'number'
|
125
|
+
? metadata.timestamp
|
126
|
+
: Date.now())
|
127
|
+
});
|
128
|
+
}
|
129
|
+
}
|
130
|
+
return memories;
|
131
|
+
}
|
132
|
+
catch (error) {
|
133
|
+
this.logger.error('Failed to search memories in ChromaDB:', error);
|
134
|
+
}
|
135
|
+
}
|
136
|
+
// Fallback to simple text search in cache
|
137
|
+
const cacheResults = [];
|
138
|
+
for (const memory of this.memoryCache.values()) {
|
139
|
+
if (memory.content.toLowerCase().includes(query.toLowerCase())) {
|
140
|
+
cacheResults.push(memory);
|
141
|
+
}
|
142
|
+
}
|
143
|
+
return cacheResults.slice(0, limit);
|
144
|
+
}
|
145
|
+
async getRecentMemories(limit = 10) {
|
146
|
+
const allMemories = Array.from(this.memoryCache.values());
|
147
|
+
return allMemories
|
148
|
+
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
|
149
|
+
.slice(0, limit);
|
150
|
+
}
|
151
|
+
async deleteMemory(id) {
|
152
|
+
try {
|
153
|
+
// Delete from cache
|
154
|
+
this.memoryCache.delete(id);
|
155
|
+
// Delete from ChromaDB
|
156
|
+
if (this.chromaCollection) {
|
157
|
+
await this.chromaCollection.delete({
|
158
|
+
ids: [id]
|
159
|
+
});
|
160
|
+
}
|
161
|
+
// Delete from Redis
|
162
|
+
if (this.redis) {
|
163
|
+
await this.redis.del(`memory:${id}`);
|
164
|
+
}
|
165
|
+
this.logger.debug(`Deleted memory: ${id}`);
|
166
|
+
return true;
|
167
|
+
}
|
168
|
+
catch (error) {
|
169
|
+
this.logger.error('Failed to delete memory:', error);
|
170
|
+
return false;
|
171
|
+
}
|
172
|
+
}
|
173
|
+
async clearAllMemories() {
|
174
|
+
try {
|
175
|
+
// Clear cache
|
176
|
+
this.memoryCache.clear();
|
177
|
+
// Clear ChromaDB collection
|
178
|
+
if (this.chromaCollection) {
|
179
|
+
await this.chroma?.deleteCollection({
|
180
|
+
name: `${this.config.name}-memories`
|
181
|
+
});
|
182
|
+
// Recreate collection
|
183
|
+
this.chromaCollection = await this.chroma?.getOrCreateCollection({
|
184
|
+
name: `${this.config.name}-memories`
|
185
|
+
}) || null;
|
186
|
+
}
|
187
|
+
// Clear Redis keys
|
188
|
+
if (this.redis) {
|
189
|
+
const keys = await this.redis.keys('memory:*');
|
190
|
+
if (keys.length > 0) {
|
191
|
+
await this.redis.del(keys);
|
192
|
+
}
|
193
|
+
}
|
194
|
+
this.logger.info('Cleared all memories');
|
195
|
+
}
|
196
|
+
catch (error) {
|
197
|
+
this.logger.error('Failed to clear memories:', error);
|
198
|
+
}
|
199
|
+
}
|
200
|
+
async close() {
|
201
|
+
if (this.redis) {
|
202
|
+
await this.redis.disconnect();
|
203
|
+
}
|
204
|
+
// ChromaDB doesn't need explicit cleanup
|
205
|
+
}
|
206
|
+
}
|
207
|
+
exports.Knowledge = Knowledge;
|
208
|
+
//# sourceMappingURL=knowledge.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"knowledge.js","sourceRoot":"","sources":["../../src/modules/knowledge.ts"],"names":[],"mappings":";;;AACA,uCAAoD;AACpD,iCAAsD;AACtD,sCAAmC;AAEnC,+BAAoC;AAEpC,MAAa,SAAS;IACZ,MAAM,GAAwB,IAAI,CAAC;IACnC,gBAAgB,GAAsB,IAAI,CAAC;IAC3C,KAAK,GAA2B,IAAI,CAAC;IACrC,MAAM,CAAc;IACpB,MAAM,CAAM;IACZ,WAAW,GAA6B,IAAI,GAAG,EAAE,CAAC;IAE1D,YAAY,MAAmB;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,eAAM,CAAC,GAAG,EAAE,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,UAAU;QACd,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;QAErD,mCAAmC;QACnC,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,GAAG,IAAI,uBAAY,CAAC;gBAC7B,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,uBAAuB;aACzD,CAAC,CAAC;YAEH,IAAI,CAAC,gBAAgB,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC;gBAC9D,IAAI,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,WAAW;aACrC,CAAC,CAAC;YAEH,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kDAAkD,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,CAAC;YACH,CAAC;YAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;QACxD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;QAChC,CAAC;QACD,yCAAyC;IAC3C,CAAC;CACF;AAnOD,8BAmOC"}
|
@@ -0,0 +1,26 @@
|
|
1
|
+
import { Hash, Address } from 'viem';
|
2
|
+
import { EventEmitter } from 'events';
|
3
|
+
import { AgentConfig, EventFilter } from '../types';
|
4
|
+
export declare class Observer extends EventEmitter {
|
5
|
+
private client;
|
6
|
+
private config;
|
7
|
+
private logger;
|
8
|
+
private isRunning;
|
9
|
+
private eventFilters;
|
10
|
+
private lastProcessedBlock;
|
11
|
+
constructor(config: AgentConfig);
|
12
|
+
start(): Promise<void>;
|
13
|
+
stop(): Promise<void>;
|
14
|
+
addEventFilter(id: string, filter: EventFilter): void;
|
15
|
+
removeEventFilter(id: string): void;
|
16
|
+
private pollForNewBlocks;
|
17
|
+
private processBlockRange;
|
18
|
+
private processBlock;
|
19
|
+
private processTransaction;
|
20
|
+
private processLogsForBlock;
|
21
|
+
private emitAgentEvent;
|
22
|
+
private sleep;
|
23
|
+
subscribeToContract(address: Address, topics?: (Hash | Hash[] | null)[]): Promise<string>;
|
24
|
+
subscribeToTokenTransfers(tokenAddress?: Address): Promise<string>;
|
25
|
+
}
|
26
|
+
//# sourceMappingURL=observer.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"observer.d.ts","sourceRoot":"","sources":["../../src/modules/observer.ts"],"names":[],"mappings":"AACA,OAAO,EAAqD,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACxF,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAc,MAAM,UAAU,CAAC;AAGhE,qBAAa,QAAS,SAAQ,YAAY;IACxC,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,SAAS,CAAkB;IACnC,OAAO,CAAC,YAAY,CAAuC;IAC3D,OAAO,CAAC,kBAAkB,CAAc;gBAE5B,MAAM,EAAE,WAAW;IA+BzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAmBtB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAM3B,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI;IAKrD,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;YAKrB,gBAAgB;YAkBhB,iBAAiB;YAQjB,YAAY;YA6BZ,kBAAkB;YASlB,mBAAmB;IAuBjC,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,KAAK;IAKP,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IASzF,yBAAyB,CAAC,YAAY,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;CAUzE"}
|
@@ -0,0 +1,184 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.Observer = void 0;
|
4
|
+
const viem_1 = require("viem");
|
5
|
+
const events_1 = require("events");
|
6
|
+
const logger_1 = require("../logger");
|
7
|
+
const uuid_1 = require("uuid");
|
8
|
+
class Observer extends events_1.EventEmitter {
|
9
|
+
client;
|
10
|
+
config;
|
11
|
+
logger;
|
12
|
+
isRunning = false;
|
13
|
+
eventFilters = new Map();
|
14
|
+
lastProcessedBlock = 0n;
|
15
|
+
constructor(config) {
|
16
|
+
super();
|
17
|
+
this.config = config;
|
18
|
+
this.logger = logger_1.Logger.get();
|
19
|
+
// Define Flow EVM chain
|
20
|
+
const flowEvm = {
|
21
|
+
id: 747,
|
22
|
+
name: 'Flow EVM',
|
23
|
+
network: 'flow-evm',
|
24
|
+
nativeCurrency: {
|
25
|
+
decimals: 18,
|
26
|
+
name: 'Flow',
|
27
|
+
symbol: 'FLOW',
|
28
|
+
},
|
29
|
+
rpcUrls: {
|
30
|
+
default: {
|
31
|
+
http: [config.flowRpcUrl],
|
32
|
+
},
|
33
|
+
public: {
|
34
|
+
http: [config.flowRpcUrl],
|
35
|
+
},
|
36
|
+
},
|
37
|
+
};
|
38
|
+
this.client = (0, viem_1.createPublicClient)({
|
39
|
+
chain: flowEvm,
|
40
|
+
transport: (0, viem_1.http)(config.flowRpcUrl)
|
41
|
+
});
|
42
|
+
}
|
43
|
+
async start() {
|
44
|
+
this.logger.info('Starting Flow EVM Observer...');
|
45
|
+
this.isRunning = true;
|
46
|
+
try {
|
47
|
+
// Get the latest block to start from
|
48
|
+
this.lastProcessedBlock = await this.client.getBlockNumber();
|
49
|
+
this.logger.info(`Starting observation from block: ${this.lastProcessedBlock}`);
|
50
|
+
// Start polling for new blocks
|
51
|
+
this.pollForNewBlocks();
|
52
|
+
this.emit('started');
|
53
|
+
}
|
54
|
+
catch (error) {
|
55
|
+
this.logger.error('Failed to start observer:', error);
|
56
|
+
throw error;
|
57
|
+
}
|
58
|
+
}
|
59
|
+
async stop() {
|
60
|
+
this.logger.info('Stopping Flow EVM Observer...');
|
61
|
+
this.isRunning = false;
|
62
|
+
this.emit('stopped');
|
63
|
+
}
|
64
|
+
addEventFilter(id, filter) {
|
65
|
+
this.eventFilters.set(id, filter);
|
66
|
+
this.logger.info(`Added event filter: ${id}`, filter);
|
67
|
+
}
|
68
|
+
removeEventFilter(id) {
|
69
|
+
this.eventFilters.delete(id);
|
70
|
+
this.logger.info(`Removed event filter: ${id}`);
|
71
|
+
}
|
72
|
+
async pollForNewBlocks() {
|
73
|
+
while (this.isRunning) {
|
74
|
+
try {
|
75
|
+
const currentBlock = await this.client.getBlockNumber();
|
76
|
+
if (currentBlock > this.lastProcessedBlock) {
|
77
|
+
await this.processBlockRange(this.lastProcessedBlock + 1n, currentBlock);
|
78
|
+
this.lastProcessedBlock = currentBlock;
|
79
|
+
}
|
80
|
+
await this.sleep(this.config.pollingInterval || 5000);
|
81
|
+
}
|
82
|
+
catch (error) {
|
83
|
+
this.logger.error('Error in block polling:', error);
|
84
|
+
await this.sleep(5000); // Wait before retrying
|
85
|
+
}
|
86
|
+
}
|
87
|
+
}
|
88
|
+
async processBlockRange(fromBlock, toBlock) {
|
89
|
+
this.logger.debug(`Processing blocks ${fromBlock} to ${toBlock}`);
|
90
|
+
for (let blockNumber = fromBlock; blockNumber <= toBlock; blockNumber++) {
|
91
|
+
await this.processBlock(blockNumber);
|
92
|
+
}
|
93
|
+
}
|
94
|
+
async processBlock(blockNumber) {
|
95
|
+
try {
|
96
|
+
const block = await this.client.getBlock({
|
97
|
+
blockNumber,
|
98
|
+
includeTransactions: true
|
99
|
+
});
|
100
|
+
// Emit block event
|
101
|
+
this.emitAgentEvent('block', {
|
102
|
+
block,
|
103
|
+
blockNumber,
|
104
|
+
timestamp: new Date(Number(block.timestamp) * 1000)
|
105
|
+
});
|
106
|
+
// Process transactions in the block
|
107
|
+
if (block.transactions) {
|
108
|
+
for (const tx of block.transactions) {
|
109
|
+
await this.processTransaction(tx, block);
|
110
|
+
}
|
111
|
+
}
|
112
|
+
// Process logs based on event filters
|
113
|
+
await this.processLogsForBlock(blockNumber);
|
114
|
+
}
|
115
|
+
catch (error) {
|
116
|
+
this.logger.error(`Error processing block ${blockNumber}:`, error);
|
117
|
+
}
|
118
|
+
}
|
119
|
+
async processTransaction(tx, block) {
|
120
|
+
// Emit transaction event
|
121
|
+
this.emitAgentEvent('transaction', {
|
122
|
+
transaction: tx,
|
123
|
+
block,
|
124
|
+
timestamp: new Date(Number(block.timestamp) * 1000)
|
125
|
+
});
|
126
|
+
}
|
127
|
+
async processLogsForBlock(blockNumber) {
|
128
|
+
for (const [filterId, filter] of this.eventFilters) {
|
129
|
+
try {
|
130
|
+
const logs = await this.client.getLogs({
|
131
|
+
...filter,
|
132
|
+
fromBlock: blockNumber,
|
133
|
+
toBlock: blockNumber
|
134
|
+
});
|
135
|
+
for (const log of logs) {
|
136
|
+
this.emitAgentEvent('log', {
|
137
|
+
log,
|
138
|
+
filterId,
|
139
|
+
blockNumber,
|
140
|
+
timestamp: new Date()
|
141
|
+
});
|
142
|
+
}
|
143
|
+
}
|
144
|
+
catch (error) {
|
145
|
+
this.logger.error(`Error processing logs for filter ${filterId}:`, error);
|
146
|
+
}
|
147
|
+
}
|
148
|
+
}
|
149
|
+
emitAgentEvent(type, data) {
|
150
|
+
const event = {
|
151
|
+
id: (0, uuid_1.v4)(),
|
152
|
+
type,
|
153
|
+
timestamp: new Date(),
|
154
|
+
data,
|
155
|
+
processed: false
|
156
|
+
};
|
157
|
+
this.emit('event', event);
|
158
|
+
this.emit(type, event);
|
159
|
+
}
|
160
|
+
sleep(ms) {
|
161
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
162
|
+
}
|
163
|
+
// Utility methods for specific event subscriptions
|
164
|
+
async subscribeToContract(address, topics) {
|
165
|
+
const filterId = (0, uuid_1.v4)();
|
166
|
+
this.addEventFilter(filterId, {
|
167
|
+
address,
|
168
|
+
topics
|
169
|
+
});
|
170
|
+
return filterId;
|
171
|
+
}
|
172
|
+
async subscribeToTokenTransfers(tokenAddress) {
|
173
|
+
const filterId = (0, uuid_1.v4)();
|
174
|
+
this.addEventFilter(filterId, {
|
175
|
+
address: tokenAddress,
|
176
|
+
topics: [
|
177
|
+
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' // Transfer event signature
|
178
|
+
]
|
179
|
+
});
|
180
|
+
return filterId;
|
181
|
+
}
|
182
|
+
}
|
183
|
+
exports.Observer = Observer;
|
184
|
+
//# sourceMappingURL=observer.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"observer.js","sourceRoot":"","sources":["../../src/modules/observer.ts"],"names":[],"mappings":";;;AACA,+BAAwF;AACxF,mCAAsC;AACtC,sCAAmC;AAEnC,+BAAoC;AAEpC,MAAa,QAAS,SAAQ,qBAAY;IAChC,MAAM,CAAM;IACZ,MAAM,CAAc;IACpB,MAAM,CAAM;IACZ,SAAS,GAAY,KAAK,CAAC;IAC3B,YAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;IACnD,kBAAkB,GAAW,EAAE,CAAC;IAExC,YAAY,MAAmB;QAC7B,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,eAAM,CAAC,GAAG,EAAE,CAAC;QAE3B,wBAAwB;QACxB,MAAM,OAAO,GAAG;YACd,EAAE,EAAE,GAAG;YACP,IAAI,EAAE,UAAU;YAChB,OAAO,EAAE,UAAU;YACnB,cAAc,EAAE;gBACd,QAAQ,EAAE,EAAE;gBACZ,IAAI,EAAE,MAAM;gBACZ,MAAM,EAAE,MAAM;aACf;YACD,OAAO,EAAE;gBACP,OAAO,EAAE;oBACP,IAAI,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC;iBAC1B;gBACD,MAAM,EAAE;oBACN,IAAI,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC;iBAC1B;aACF;SACO,CAAC;QAEX,IAAI,CAAC,MAAM,GAAG,IAAA,yBAAkB,EAAC;YAC/B,KAAK,EAAE,OAAO;YACd,SAAS,EAAE,IAAA,WAAI,EAAC,MAAM,CAAC,UAAU,CAAC;SACnC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,+BAA+B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|
+
private config;
|
5
|
+
private logger;
|
6
|
+
private outputParser;
|
7
|
+
constructor(config: AgentConfig);
|
8
|
+
plan(input: PlannerInput): Promise<PlannerOutput>;
|
9
|
+
private llmPlan;
|
10
|
+
private ruleBasedPlan;
|
11
|
+
evaluateGoalCompletion(goal: AgentGoal, taskHistory: AgentTask[]): Promise<boolean>;
|
12
|
+
private llmEvaluateGoal;
|
13
|
+
private ruleBasedEvaluateGoal;
|
14
|
+
}
|
15
|
+
//# sourceMappingURL=planner.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"planner.d.ts","sourceRoot":"","sources":["../../src/modules/planner.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE1F,qBAAa,OAAO;IAClB,OAAO,CAAC,GAAG,CAA2B;IACtC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,YAAY,CAAmB;gBAE3B,MAAM,EAAE,WAAW;IAgBzB,IAAI,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC;YAQzC,OAAO;YA8DP,aAAa;IA4CrB,sBAAsB,CAAC,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;YAQ3E,eAAe;YAiCf,qBAAqB;CAWpC"}
|
@@ -0,0 +1,179 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.Planner = void 0;
|
4
|
+
const openai_1 = require("@langchain/openai");
|
5
|
+
const prompts_1 = require("@langchain/core/prompts");
|
6
|
+
const output_parsers_1 = require("@langchain/core/output_parsers");
|
7
|
+
const logger_1 = require("../logger");
|
8
|
+
class Planner {
|
9
|
+
llm = null;
|
10
|
+
config;
|
11
|
+
logger;
|
12
|
+
outputParser;
|
13
|
+
constructor(config) {
|
14
|
+
this.config = config;
|
15
|
+
this.logger = logger_1.Logger.get();
|
16
|
+
this.outputParser = new output_parsers_1.JsonOutputParser();
|
17
|
+
if (config.openaiApiKey) {
|
18
|
+
this.llm = new openai_1.ChatOpenAI({
|
19
|
+
openAIApiKey: config.openaiApiKey,
|
20
|
+
modelName: 'gpt-3.5-turbo',
|
21
|
+
temperature: 0.1
|
22
|
+
});
|
23
|
+
}
|
24
|
+
else {
|
25
|
+
this.logger.warn('No OpenAI API key provided. Planner will use rule-based fallback.');
|
26
|
+
}
|
27
|
+
}
|
28
|
+
async plan(input) {
|
29
|
+
if (this.llm) {
|
30
|
+
return await this.llmPlan(input);
|
31
|
+
}
|
32
|
+
else {
|
33
|
+
return await this.ruleBasedPlan(input);
|
34
|
+
}
|
35
|
+
}
|
36
|
+
async llmPlan(input) {
|
37
|
+
try {
|
38
|
+
const prompt = prompts_1.PromptTemplate.fromTemplate(`
|
39
|
+
You are an autonomous agent operating on Flow EVM blockchain. Your task is to analyze the current situation and decide on the next action.
|
40
|
+
|
41
|
+
## Current Goals:
|
42
|
+
{goals}
|
43
|
+
|
44
|
+
## Task History (last 10 tasks):
|
45
|
+
{taskHistory}
|
46
|
+
|
47
|
+
## Current Context:
|
48
|
+
{currentContext}
|
49
|
+
|
50
|
+
## Available Actions:
|
51
|
+
{availableActions}
|
52
|
+
|
53
|
+
Based on the above information, decide on the next action to take. Consider:
|
54
|
+
1. Which goals are not yet completed
|
55
|
+
2. What actions have been tried recently and their outcomes
|
56
|
+
3. The current blockchain state and context
|
57
|
+
4. Available resources and constraints
|
58
|
+
|
59
|
+
Respond with a JSON object containing:
|
60
|
+
- nextAction: The action to take (must be one of the available actions)
|
61
|
+
- reasoning: Why this action was chosen
|
62
|
+
- parameters: Object with parameters for the action
|
63
|
+
- confidence: Number between 0 and 1 indicating confidence in this decision
|
64
|
+
|
65
|
+
Example response:
|
66
|
+
{{
|
67
|
+
"nextAction": "transfer_flow",
|
68
|
+
"reasoning": "User requested to send FLOW tokens to address 0x123...",
|
69
|
+
"parameters": {{"to": "0x123...", "amount": "1.0"}},
|
70
|
+
"confidence": 0.9
|
71
|
+
}}
|
72
|
+
`);
|
73
|
+
const formattedPrompt = await prompt.format({
|
74
|
+
goals: JSON.stringify(input.goals, null, 2),
|
75
|
+
taskHistory: JSON.stringify(input.taskHistory.slice(-10), null, 2),
|
76
|
+
currentContext: JSON.stringify(input.currentContext, null, 2),
|
77
|
+
availableActions: input.availableActions.join(', ')
|
78
|
+
});
|
79
|
+
const response = await this.llm.invoke(formattedPrompt);
|
80
|
+
const parsed = await this.outputParser.parse(response.content);
|
81
|
+
this.logger.info('LLM planning completed:', parsed);
|
82
|
+
return {
|
83
|
+
nextAction: parsed.nextAction,
|
84
|
+
reasoning: parsed.reasoning,
|
85
|
+
parameters: parsed.parameters || {},
|
86
|
+
confidence: parsed.confidence || 0.5
|
87
|
+
};
|
88
|
+
}
|
89
|
+
catch (error) {
|
90
|
+
this.logger.error('LLM planning failed, falling back to rule-based:', error);
|
91
|
+
return await this.ruleBasedPlan(input);
|
92
|
+
}
|
93
|
+
}
|
94
|
+
async ruleBasedPlan(input) {
|
95
|
+
this.logger.info('Using rule-based planning');
|
96
|
+
// Simple rule-based planning logic
|
97
|
+
const incompleteGoals = input.goals.filter(goal => !goal.completed);
|
98
|
+
if (incompleteGoals.length === 0) {
|
99
|
+
return {
|
100
|
+
nextAction: 'observe',
|
101
|
+
reasoning: 'No incomplete goals, continuing observation',
|
102
|
+
parameters: {},
|
103
|
+
confidence: 0.8
|
104
|
+
};
|
105
|
+
}
|
106
|
+
// Find the oldest incomplete goal
|
107
|
+
const oldestGoal = incompleteGoals.reduce((oldest, current) => current.createdAt < oldest.createdAt ? current : oldest);
|
108
|
+
// Simple action mapping based on goal description
|
109
|
+
let nextAction = 'observe';
|
110
|
+
let parameters = {};
|
111
|
+
let reasoning = `Working on goal: ${oldestGoal.description}`;
|
112
|
+
if (oldestGoal.description.toLowerCase().includes('transfer')) {
|
113
|
+
nextAction = 'transfer_flow';
|
114
|
+
reasoning = 'Goal involves transferring tokens';
|
115
|
+
}
|
116
|
+
else if (oldestGoal.description.toLowerCase().includes('balance')) {
|
117
|
+
nextAction = 'check_balance';
|
118
|
+
reasoning = 'Goal involves checking balances';
|
119
|
+
}
|
120
|
+
else if (oldestGoal.description.toLowerCase().includes('deploy')) {
|
121
|
+
nextAction = 'deploy_contract';
|
122
|
+
reasoning = 'Goal involves deploying a contract';
|
123
|
+
}
|
124
|
+
return {
|
125
|
+
nextAction,
|
126
|
+
reasoning,
|
127
|
+
parameters,
|
128
|
+
confidence: 0.6
|
129
|
+
};
|
130
|
+
}
|
131
|
+
async evaluateGoalCompletion(goal, taskHistory) {
|
132
|
+
if (this.llm) {
|
133
|
+
return await this.llmEvaluateGoal(goal, taskHistory);
|
134
|
+
}
|
135
|
+
else {
|
136
|
+
return await this.ruleBasedEvaluateGoal(goal, taskHistory);
|
137
|
+
}
|
138
|
+
}
|
139
|
+
async llmEvaluateGoal(goal, taskHistory) {
|
140
|
+
try {
|
141
|
+
const prompt = prompts_1.PromptTemplate.fromTemplate(`
|
142
|
+
Evaluate whether the following goal has been completed based on the task history:
|
143
|
+
|
144
|
+
## Goal:
|
145
|
+
{goal}
|
146
|
+
|
147
|
+
## Recent Task History:
|
148
|
+
{taskHistory}
|
149
|
+
|
150
|
+
Respond with a JSON object:
|
151
|
+
{{
|
152
|
+
"completed": true/false,
|
153
|
+
"reasoning": "explanation of why the goal is/isn't completed"
|
154
|
+
}}
|
155
|
+
`);
|
156
|
+
const formattedPrompt = await prompt.format({
|
157
|
+
goal: JSON.stringify(goal, null, 2),
|
158
|
+
taskHistory: JSON.stringify(taskHistory.slice(-5), null, 2)
|
159
|
+
});
|
160
|
+
const response = await this.llm.invoke(formattedPrompt);
|
161
|
+
const parsed = await this.outputParser.parse(response.content);
|
162
|
+
return parsed.completed;
|
163
|
+
}
|
164
|
+
catch (error) {
|
165
|
+
this.logger.error('LLM goal evaluation failed:', error);
|
166
|
+
return false;
|
167
|
+
}
|
168
|
+
}
|
169
|
+
async ruleBasedEvaluateGoal(goal, taskHistory) {
|
170
|
+
// Simple rule: if there's a successful task related to the goal in recent history
|
171
|
+
const recentSuccessfulTasks = taskHistory
|
172
|
+
.filter(task => task.status === 'completed')
|
173
|
+
.slice(-5);
|
174
|
+
return recentSuccessfulTasks.some(task => task.description.toLowerCase().includes(goal.description.toLowerCase()) ||
|
175
|
+
goal.description.toLowerCase().includes(task.type));
|
176
|
+
}
|
177
|
+
}
|
178
|
+
exports.Planner = Planner;
|
179
|
+
//# sourceMappingURL=planner.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"planner.js","sourceRoot":"","sources":["../../src/modules/planner.ts"],"names":[],"mappings":";;;AACA,8CAA+C;AAC/C,qDAAyD;AACzD,mEAAkE;AAClE,sCAAmC;AAGnC,MAAa,OAAO;IACV,GAAG,GAAsB,IAAI,CAAC;IAC9B,MAAM,CAAc;IACpB,MAAM,CAAM;IACZ,YAAY,CAAmB;IAEvC,YAAY,MAAmB;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,eAAM,CAAC,GAAG,EAAE,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,IAAI,iCAAgB,EAAE,CAAC;QAE3C,IAAI,MAAM,CAAC,YAAY,EAAE,CAAC;YACxB,IAAI,CAAC,GAAG,GAAG,IAAI,mBAAU,CAAC;gBACxB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,SAAS,EAAE,eAAe;gBAC1B,WAAW,EAAE,GAAG;aACjB,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;QACxF,CAAC;IACH,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,KAAmB;QAC5B,IAAI,IAAI,CAAC,GAAG,EAAE,CAA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