@exagent/agent 0.1.8 → 0.1.10
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/dist/chunk-7GQXIIL2.mjs +2725 -0
- package/dist/chunk-CKSCA3O7.mjs +2686 -0
- package/dist/cli.js +63 -16
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +9 -2
- package/dist/index.d.ts +9 -2
- package/dist/index.js +63 -16
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,2725 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/llm/base.ts
|
|
9
|
+
var BaseLLMAdapter = class {
|
|
10
|
+
config;
|
|
11
|
+
constructor(config) {
|
|
12
|
+
this.config = config;
|
|
13
|
+
}
|
|
14
|
+
getMetadata() {
|
|
15
|
+
return {
|
|
16
|
+
provider: this.config.provider,
|
|
17
|
+
model: this.config.model || "unknown",
|
|
18
|
+
isLocal: this.config.provider === "ollama"
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Format model name for display
|
|
23
|
+
*/
|
|
24
|
+
getDisplayModel() {
|
|
25
|
+
if (this.config.provider === "ollama") {
|
|
26
|
+
return `Local (${this.config.model || "ollama"})`;
|
|
27
|
+
}
|
|
28
|
+
return this.config.model || this.config.provider;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/llm/openai.ts
|
|
33
|
+
import OpenAI from "openai";
|
|
34
|
+
var OpenAIAdapter = class extends BaseLLMAdapter {
|
|
35
|
+
client;
|
|
36
|
+
constructor(config) {
|
|
37
|
+
super(config);
|
|
38
|
+
if (!config.apiKey && !config.endpoint) {
|
|
39
|
+
throw new Error("OpenAI API key or custom endpoint required");
|
|
40
|
+
}
|
|
41
|
+
this.client = new OpenAI({
|
|
42
|
+
apiKey: config.apiKey || "not-needed-for-custom",
|
|
43
|
+
baseURL: config.endpoint
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async chat(messages) {
|
|
47
|
+
try {
|
|
48
|
+
const response = await this.client.chat.completions.create({
|
|
49
|
+
model: this.config.model || "gpt-4.1",
|
|
50
|
+
messages: messages.map((m) => ({
|
|
51
|
+
role: m.role,
|
|
52
|
+
content: m.content
|
|
53
|
+
})),
|
|
54
|
+
temperature: this.config.temperature,
|
|
55
|
+
max_tokens: this.config.maxTokens
|
|
56
|
+
});
|
|
57
|
+
const choice = response.choices[0];
|
|
58
|
+
if (!choice || !choice.message) {
|
|
59
|
+
throw new Error("No response from OpenAI");
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
content: choice.message.content || "",
|
|
63
|
+
usage: response.usage ? {
|
|
64
|
+
promptTokens: response.usage.prompt_tokens,
|
|
65
|
+
completionTokens: response.usage.completion_tokens,
|
|
66
|
+
totalTokens: response.usage.total_tokens
|
|
67
|
+
} : void 0
|
|
68
|
+
};
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error instanceof OpenAI.APIError) {
|
|
71
|
+
throw new Error(`OpenAI API error: ${error.message}`);
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/llm/anthropic.ts
|
|
79
|
+
var AnthropicAdapter = class extends BaseLLMAdapter {
|
|
80
|
+
apiKey;
|
|
81
|
+
baseUrl;
|
|
82
|
+
constructor(config) {
|
|
83
|
+
super(config);
|
|
84
|
+
if (!config.apiKey) {
|
|
85
|
+
throw new Error("Anthropic API key required");
|
|
86
|
+
}
|
|
87
|
+
this.apiKey = config.apiKey;
|
|
88
|
+
this.baseUrl = config.endpoint || "https://api.anthropic.com";
|
|
89
|
+
}
|
|
90
|
+
async chat(messages) {
|
|
91
|
+
const systemMessage = messages.find((m) => m.role === "system");
|
|
92
|
+
const chatMessages = messages.filter((m) => m.role !== "system");
|
|
93
|
+
const body = {
|
|
94
|
+
model: this.config.model || "claude-opus-4-5-20251101",
|
|
95
|
+
max_tokens: this.config.maxTokens || 4096,
|
|
96
|
+
temperature: this.config.temperature,
|
|
97
|
+
system: systemMessage?.content,
|
|
98
|
+
messages: chatMessages.map((m) => ({
|
|
99
|
+
role: m.role,
|
|
100
|
+
content: m.content
|
|
101
|
+
}))
|
|
102
|
+
};
|
|
103
|
+
const response = await fetch(`${this.baseUrl}/v1/messages`, {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers: {
|
|
106
|
+
"Content-Type": "application/json",
|
|
107
|
+
"x-api-key": this.apiKey,
|
|
108
|
+
"anthropic-version": "2023-06-01"
|
|
109
|
+
},
|
|
110
|
+
body: JSON.stringify(body)
|
|
111
|
+
});
|
|
112
|
+
if (!response.ok) {
|
|
113
|
+
const error = await response.text();
|
|
114
|
+
throw new Error(`Anthropic API error: ${response.status} - ${error}`);
|
|
115
|
+
}
|
|
116
|
+
const data = await response.json();
|
|
117
|
+
const content = data.content?.map(
|
|
118
|
+
(block) => block.type === "text" ? block.text : ""
|
|
119
|
+
).join("") || "";
|
|
120
|
+
return {
|
|
121
|
+
content,
|
|
122
|
+
usage: data.usage ? {
|
|
123
|
+
promptTokens: data.usage.input_tokens,
|
|
124
|
+
completionTokens: data.usage.output_tokens,
|
|
125
|
+
totalTokens: data.usage.input_tokens + data.usage.output_tokens
|
|
126
|
+
} : void 0
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// src/llm/google.ts
|
|
132
|
+
var GoogleAdapter = class extends BaseLLMAdapter {
|
|
133
|
+
apiKey;
|
|
134
|
+
baseUrl;
|
|
135
|
+
constructor(config) {
|
|
136
|
+
super(config);
|
|
137
|
+
if (!config.apiKey) {
|
|
138
|
+
throw new Error("Google AI API key required");
|
|
139
|
+
}
|
|
140
|
+
this.apiKey = config.apiKey;
|
|
141
|
+
this.baseUrl = config.endpoint || "https://generativelanguage.googleapis.com/v1beta";
|
|
142
|
+
}
|
|
143
|
+
async chat(messages) {
|
|
144
|
+
const model = this.config.model || "gemini-2.5-flash";
|
|
145
|
+
const systemMessage = messages.find((m) => m.role === "system");
|
|
146
|
+
const chatMessages = messages.filter((m) => m.role !== "system");
|
|
147
|
+
const contents = chatMessages.map((m) => ({
|
|
148
|
+
role: m.role === "assistant" ? "model" : "user",
|
|
149
|
+
parts: [{ text: m.content }]
|
|
150
|
+
}));
|
|
151
|
+
const body = {
|
|
152
|
+
contents,
|
|
153
|
+
generationConfig: {
|
|
154
|
+
temperature: this.config.temperature,
|
|
155
|
+
maxOutputTokens: this.config.maxTokens || 4096
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
if (systemMessage) {
|
|
159
|
+
body.systemInstruction = {
|
|
160
|
+
parts: [{ text: systemMessage.content }]
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
const url = `${this.baseUrl}/models/${model}:generateContent?key=${this.apiKey}`;
|
|
164
|
+
const response = await fetch(url, {
|
|
165
|
+
method: "POST",
|
|
166
|
+
headers: {
|
|
167
|
+
"Content-Type": "application/json"
|
|
168
|
+
},
|
|
169
|
+
body: JSON.stringify(body)
|
|
170
|
+
});
|
|
171
|
+
if (!response.ok) {
|
|
172
|
+
const error = await response.text();
|
|
173
|
+
throw new Error(`Google AI API error: ${response.status} - ${error}`);
|
|
174
|
+
}
|
|
175
|
+
const data = await response.json();
|
|
176
|
+
const candidate = data.candidates?.[0];
|
|
177
|
+
if (!candidate?.content?.parts) {
|
|
178
|
+
throw new Error("No response from Google AI");
|
|
179
|
+
}
|
|
180
|
+
const content = candidate.content.parts.map((part) => part.text || "").join("");
|
|
181
|
+
const usageMetadata = data.usageMetadata;
|
|
182
|
+
return {
|
|
183
|
+
content,
|
|
184
|
+
usage: usageMetadata ? {
|
|
185
|
+
promptTokens: usageMetadata.promptTokenCount || 0,
|
|
186
|
+
completionTokens: usageMetadata.candidatesTokenCount || 0,
|
|
187
|
+
totalTokens: usageMetadata.totalTokenCount || 0
|
|
188
|
+
} : void 0
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// src/llm/deepseek.ts
|
|
194
|
+
import OpenAI2 from "openai";
|
|
195
|
+
var DeepSeekAdapter = class extends BaseLLMAdapter {
|
|
196
|
+
client;
|
|
197
|
+
constructor(config) {
|
|
198
|
+
super(config);
|
|
199
|
+
if (!config.apiKey) {
|
|
200
|
+
throw new Error("DeepSeek API key required");
|
|
201
|
+
}
|
|
202
|
+
this.client = new OpenAI2({
|
|
203
|
+
apiKey: config.apiKey,
|
|
204
|
+
baseURL: config.endpoint || "https://api.deepseek.com/v1"
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
async chat(messages) {
|
|
208
|
+
try {
|
|
209
|
+
const response = await this.client.chat.completions.create({
|
|
210
|
+
model: this.config.model || "deepseek-chat",
|
|
211
|
+
messages: messages.map((m) => ({
|
|
212
|
+
role: m.role,
|
|
213
|
+
content: m.content
|
|
214
|
+
})),
|
|
215
|
+
temperature: this.config.temperature,
|
|
216
|
+
max_tokens: this.config.maxTokens
|
|
217
|
+
});
|
|
218
|
+
const choice = response.choices[0];
|
|
219
|
+
if (!choice || !choice.message) {
|
|
220
|
+
throw new Error("No response from DeepSeek");
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
content: choice.message.content || "",
|
|
224
|
+
usage: response.usage ? {
|
|
225
|
+
promptTokens: response.usage.prompt_tokens,
|
|
226
|
+
completionTokens: response.usage.completion_tokens,
|
|
227
|
+
totalTokens: response.usage.total_tokens
|
|
228
|
+
} : void 0
|
|
229
|
+
};
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (error instanceof OpenAI2.APIError) {
|
|
232
|
+
throw new Error(`DeepSeek API error: ${error.message}`);
|
|
233
|
+
}
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// src/llm/mistral.ts
|
|
240
|
+
var MistralAdapter = class extends BaseLLMAdapter {
|
|
241
|
+
apiKey;
|
|
242
|
+
baseUrl;
|
|
243
|
+
constructor(config) {
|
|
244
|
+
super(config);
|
|
245
|
+
if (!config.apiKey) {
|
|
246
|
+
throw new Error("Mistral API key required");
|
|
247
|
+
}
|
|
248
|
+
this.apiKey = config.apiKey;
|
|
249
|
+
this.baseUrl = config.endpoint || "https://api.mistral.ai/v1";
|
|
250
|
+
}
|
|
251
|
+
async chat(messages) {
|
|
252
|
+
const body = {
|
|
253
|
+
model: this.config.model || "mistral-large-latest",
|
|
254
|
+
messages: messages.map((m) => ({
|
|
255
|
+
role: m.role,
|
|
256
|
+
content: m.content
|
|
257
|
+
})),
|
|
258
|
+
temperature: this.config.temperature,
|
|
259
|
+
max_tokens: this.config.maxTokens
|
|
260
|
+
};
|
|
261
|
+
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
262
|
+
method: "POST",
|
|
263
|
+
headers: {
|
|
264
|
+
"Content-Type": "application/json",
|
|
265
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
266
|
+
},
|
|
267
|
+
body: JSON.stringify(body)
|
|
268
|
+
});
|
|
269
|
+
if (!response.ok) {
|
|
270
|
+
const error = await response.text();
|
|
271
|
+
throw new Error(`Mistral API error: ${response.status} - ${error}`);
|
|
272
|
+
}
|
|
273
|
+
const data = await response.json();
|
|
274
|
+
const choice = data.choices?.[0];
|
|
275
|
+
if (!choice || !choice.message) {
|
|
276
|
+
throw new Error("No response from Mistral");
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
content: choice.message.content || "",
|
|
280
|
+
usage: data.usage ? {
|
|
281
|
+
promptTokens: data.usage.prompt_tokens,
|
|
282
|
+
completionTokens: data.usage.completion_tokens,
|
|
283
|
+
totalTokens: data.usage.total_tokens
|
|
284
|
+
} : void 0
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// src/llm/groq.ts
|
|
290
|
+
import OpenAI3 from "openai";
|
|
291
|
+
var GroqAdapter = class extends BaseLLMAdapter {
|
|
292
|
+
client;
|
|
293
|
+
constructor(config) {
|
|
294
|
+
super(config);
|
|
295
|
+
if (!config.apiKey) {
|
|
296
|
+
throw new Error("Groq API key required");
|
|
297
|
+
}
|
|
298
|
+
this.client = new OpenAI3({
|
|
299
|
+
apiKey: config.apiKey,
|
|
300
|
+
baseURL: config.endpoint || "https://api.groq.com/openai/v1"
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
async chat(messages) {
|
|
304
|
+
try {
|
|
305
|
+
const response = await this.client.chat.completions.create({
|
|
306
|
+
model: this.config.model || "llama-3.1-70b-versatile",
|
|
307
|
+
messages: messages.map((m) => ({
|
|
308
|
+
role: m.role,
|
|
309
|
+
content: m.content
|
|
310
|
+
})),
|
|
311
|
+
temperature: this.config.temperature,
|
|
312
|
+
max_tokens: this.config.maxTokens
|
|
313
|
+
});
|
|
314
|
+
const choice = response.choices[0];
|
|
315
|
+
if (!choice || !choice.message) {
|
|
316
|
+
throw new Error("No response from Groq");
|
|
317
|
+
}
|
|
318
|
+
return {
|
|
319
|
+
content: choice.message.content || "",
|
|
320
|
+
usage: response.usage ? {
|
|
321
|
+
promptTokens: response.usage.prompt_tokens,
|
|
322
|
+
completionTokens: response.usage.completion_tokens,
|
|
323
|
+
totalTokens: response.usage.total_tokens
|
|
324
|
+
} : void 0
|
|
325
|
+
};
|
|
326
|
+
} catch (error) {
|
|
327
|
+
if (error instanceof OpenAI3.APIError) {
|
|
328
|
+
throw new Error(`Groq API error: ${error.message}`);
|
|
329
|
+
}
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
// src/llm/together.ts
|
|
336
|
+
import OpenAI4 from "openai";
|
|
337
|
+
var TogetherAdapter = class extends BaseLLMAdapter {
|
|
338
|
+
client;
|
|
339
|
+
constructor(config) {
|
|
340
|
+
super(config);
|
|
341
|
+
if (!config.apiKey) {
|
|
342
|
+
throw new Error("Together AI API key required");
|
|
343
|
+
}
|
|
344
|
+
this.client = new OpenAI4({
|
|
345
|
+
apiKey: config.apiKey,
|
|
346
|
+
baseURL: config.endpoint || "https://api.together.xyz/v1"
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
async chat(messages) {
|
|
350
|
+
try {
|
|
351
|
+
const response = await this.client.chat.completions.create({
|
|
352
|
+
model: this.config.model || "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
|
|
353
|
+
messages: messages.map((m) => ({
|
|
354
|
+
role: m.role,
|
|
355
|
+
content: m.content
|
|
356
|
+
})),
|
|
357
|
+
temperature: this.config.temperature,
|
|
358
|
+
max_tokens: this.config.maxTokens
|
|
359
|
+
});
|
|
360
|
+
const choice = response.choices[0];
|
|
361
|
+
if (!choice || !choice.message) {
|
|
362
|
+
throw new Error("No response from Together AI");
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
content: choice.message.content || "",
|
|
366
|
+
usage: response.usage ? {
|
|
367
|
+
promptTokens: response.usage.prompt_tokens,
|
|
368
|
+
completionTokens: response.usage.completion_tokens,
|
|
369
|
+
totalTokens: response.usage.total_tokens
|
|
370
|
+
} : void 0
|
|
371
|
+
};
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error instanceof OpenAI4.APIError) {
|
|
374
|
+
throw new Error(`Together AI API error: ${error.message}`);
|
|
375
|
+
}
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
// src/llm/ollama.ts
|
|
382
|
+
var OllamaAdapter = class extends BaseLLMAdapter {
|
|
383
|
+
baseUrl;
|
|
384
|
+
constructor(config) {
|
|
385
|
+
super(config);
|
|
386
|
+
this.baseUrl = config.endpoint || "http://localhost:11434";
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Check if Ollama is running and the model is available
|
|
390
|
+
*/
|
|
391
|
+
async healthCheck() {
|
|
392
|
+
try {
|
|
393
|
+
const response = await fetch(`${this.baseUrl}/api/tags`);
|
|
394
|
+
if (!response.ok) {
|
|
395
|
+
throw new Error("Ollama server not responding");
|
|
396
|
+
}
|
|
397
|
+
const data = await response.json();
|
|
398
|
+
const models = data.models?.map((m) => m.name) || [];
|
|
399
|
+
if (this.config.model && !models.some((m) => m.startsWith(this.config.model))) {
|
|
400
|
+
console.warn(
|
|
401
|
+
`Model "${this.config.model}" not found locally. Available: ${models.join(", ")}`
|
|
402
|
+
);
|
|
403
|
+
console.warn(`Run: ollama pull ${this.config.model}`);
|
|
404
|
+
}
|
|
405
|
+
} catch (error) {
|
|
406
|
+
throw new Error(
|
|
407
|
+
`Cannot connect to Ollama at ${this.baseUrl}. Make sure Ollama is running (ollama serve) or install it from https://ollama.com`
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
async chat(messages) {
|
|
412
|
+
const body = {
|
|
413
|
+
model: this.config.model || "llama3.2",
|
|
414
|
+
messages: messages.map((m) => ({
|
|
415
|
+
role: m.role,
|
|
416
|
+
content: m.content
|
|
417
|
+
})),
|
|
418
|
+
stream: false,
|
|
419
|
+
options: {
|
|
420
|
+
temperature: this.config.temperature,
|
|
421
|
+
num_predict: this.config.maxTokens
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
const response = await fetch(`${this.baseUrl}/api/chat`, {
|
|
425
|
+
method: "POST",
|
|
426
|
+
headers: {
|
|
427
|
+
"Content-Type": "application/json"
|
|
428
|
+
},
|
|
429
|
+
body: JSON.stringify(body)
|
|
430
|
+
});
|
|
431
|
+
if (!response.ok) {
|
|
432
|
+
const error = await response.text();
|
|
433
|
+
throw new Error(`Ollama API error: ${response.status} - ${error}`);
|
|
434
|
+
}
|
|
435
|
+
const data = await response.json();
|
|
436
|
+
return {
|
|
437
|
+
content: data.message?.content || "",
|
|
438
|
+
usage: data.eval_count ? {
|
|
439
|
+
promptTokens: data.prompt_eval_count || 0,
|
|
440
|
+
completionTokens: data.eval_count,
|
|
441
|
+
totalTokens: (data.prompt_eval_count || 0) + data.eval_count
|
|
442
|
+
} : void 0
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
getMetadata() {
|
|
446
|
+
return {
|
|
447
|
+
provider: "ollama",
|
|
448
|
+
model: this.config.model || "llama3.2",
|
|
449
|
+
isLocal: true
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// src/llm/adapter.ts
|
|
455
|
+
async function createLLMAdapter(config) {
|
|
456
|
+
switch (config.provider) {
|
|
457
|
+
case "openai":
|
|
458
|
+
return new OpenAIAdapter(config);
|
|
459
|
+
case "anthropic":
|
|
460
|
+
return new AnthropicAdapter(config);
|
|
461
|
+
case "google":
|
|
462
|
+
return new GoogleAdapter(config);
|
|
463
|
+
case "deepseek":
|
|
464
|
+
return new DeepSeekAdapter(config);
|
|
465
|
+
case "mistral":
|
|
466
|
+
return new MistralAdapter(config);
|
|
467
|
+
case "groq":
|
|
468
|
+
return new GroqAdapter(config);
|
|
469
|
+
case "together":
|
|
470
|
+
return new TogetherAdapter(config);
|
|
471
|
+
case "ollama":
|
|
472
|
+
const adapter = new OllamaAdapter(config);
|
|
473
|
+
await adapter.healthCheck();
|
|
474
|
+
return adapter;
|
|
475
|
+
case "custom":
|
|
476
|
+
return new OpenAIAdapter({
|
|
477
|
+
...config,
|
|
478
|
+
endpoint: config.endpoint
|
|
479
|
+
});
|
|
480
|
+
default:
|
|
481
|
+
throw new Error(`Unsupported LLM provider: ${config.provider}`);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/strategy/loader.ts
|
|
486
|
+
import { existsSync } from "fs";
|
|
487
|
+
import { join } from "path";
|
|
488
|
+
import { spawn } from "child_process";
|
|
489
|
+
async function loadStrategy(strategyPath) {
|
|
490
|
+
const basePath = strategyPath || process.env.EXAGENT_STRATEGY || "strategy";
|
|
491
|
+
const tsPath = basePath.endsWith(".ts") || basePath.endsWith(".js") ? basePath : `${basePath}.ts`;
|
|
492
|
+
const jsPath = basePath.endsWith(".ts") || basePath.endsWith(".js") ? basePath.replace(".ts", ".js") : `${basePath}.js`;
|
|
493
|
+
const fullTsPath = tsPath.startsWith("/") ? tsPath : join(process.cwd(), tsPath);
|
|
494
|
+
const fullJsPath = jsPath.startsWith("/") ? jsPath : join(process.cwd(), jsPath);
|
|
495
|
+
if (existsSync(fullTsPath) && fullTsPath.endsWith(".ts")) {
|
|
496
|
+
try {
|
|
497
|
+
const module = await loadTypeScriptModule(fullTsPath);
|
|
498
|
+
if (typeof module.generateSignals !== "function") {
|
|
499
|
+
throw new Error("Strategy must export a generateSignals function");
|
|
500
|
+
}
|
|
501
|
+
console.log(`Loaded custom strategy from ${tsPath}`);
|
|
502
|
+
return module.generateSignals;
|
|
503
|
+
} catch (error) {
|
|
504
|
+
console.error(`Failed to load strategy from ${tsPath}:`, error);
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (existsSync(fullJsPath)) {
|
|
509
|
+
try {
|
|
510
|
+
const module = await import(fullJsPath);
|
|
511
|
+
if (typeof module.generateSignals !== "function") {
|
|
512
|
+
throw new Error("Strategy must export a generateSignals function");
|
|
513
|
+
}
|
|
514
|
+
console.log(`Loaded custom strategy from ${jsPath}`);
|
|
515
|
+
return module.generateSignals;
|
|
516
|
+
} catch (error) {
|
|
517
|
+
console.error(`Failed to load strategy from ${jsPath}:`, error);
|
|
518
|
+
throw error;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
console.log("No custom strategy found, using default (hold) strategy");
|
|
522
|
+
return defaultStrategy;
|
|
523
|
+
}
|
|
524
|
+
async function loadTypeScriptModule(path2) {
|
|
525
|
+
try {
|
|
526
|
+
const tsxPath = __require.resolve("tsx");
|
|
527
|
+
const { pathToFileURL } = await import("url");
|
|
528
|
+
const result = await new Promise((resolve, reject) => {
|
|
529
|
+
const child = spawn(
|
|
530
|
+
process.execPath,
|
|
531
|
+
[
|
|
532
|
+
"--import",
|
|
533
|
+
"tsx/esm",
|
|
534
|
+
"-e",
|
|
535
|
+
`import('${pathToFileURL(path2).href}').then(m => console.log(JSON.stringify({ exports: Object.keys(m) }))).catch(e => console.error('ERROR:', e.message))`
|
|
536
|
+
],
|
|
537
|
+
{
|
|
538
|
+
cwd: process.cwd(),
|
|
539
|
+
env: process.env,
|
|
540
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
541
|
+
}
|
|
542
|
+
);
|
|
543
|
+
let stdout = "";
|
|
544
|
+
let stderr = "";
|
|
545
|
+
child.stdout.on("data", (data) => stdout += data.toString());
|
|
546
|
+
child.stderr.on("data", (data) => stderr += data.toString());
|
|
547
|
+
child.on("close", (code) => {
|
|
548
|
+
if (code !== 0 || stderr.includes("ERROR:")) {
|
|
549
|
+
reject(new Error(`Failed to load TypeScript: ${stderr || "Unknown error"}`));
|
|
550
|
+
} else {
|
|
551
|
+
resolve(stdout);
|
|
552
|
+
}
|
|
553
|
+
});
|
|
554
|
+
});
|
|
555
|
+
const tsx = await import("tsx/esm/api");
|
|
556
|
+
const unregister = tsx.register();
|
|
557
|
+
try {
|
|
558
|
+
const module = await import(path2);
|
|
559
|
+
return module;
|
|
560
|
+
} finally {
|
|
561
|
+
unregister();
|
|
562
|
+
}
|
|
563
|
+
} catch (error) {
|
|
564
|
+
if (error.code === "MODULE_NOT_FOUND" || error.message.includes("Cannot find module")) {
|
|
565
|
+
throw new Error(
|
|
566
|
+
`Cannot load TypeScript strategy. Please either:
|
|
567
|
+
1. Rename your strategy.ts to strategy.js (remove type annotations)
|
|
568
|
+
2. Or compile it: npx tsc strategy.ts --outDir . --esModuleInterop
|
|
569
|
+
3. Or install tsx: npm install tsx`
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
throw error;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
var defaultStrategy = async (_marketData, _llm, _config) => {
|
|
576
|
+
return [];
|
|
577
|
+
};
|
|
578
|
+
function validateStrategy(fn) {
|
|
579
|
+
return typeof fn === "function";
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/strategy/templates.ts
|
|
583
|
+
var STRATEGY_TEMPLATES = [
|
|
584
|
+
{
|
|
585
|
+
id: "momentum",
|
|
586
|
+
name: "Momentum Trader",
|
|
587
|
+
description: "Follows price trends and momentum indicators. Buys assets with strong upward momentum.",
|
|
588
|
+
riskLevel: "medium",
|
|
589
|
+
riskWarnings: [
|
|
590
|
+
"Momentum strategies can suffer significant losses during trend reversals",
|
|
591
|
+
"High volatility markets may generate false signals",
|
|
592
|
+
"Past performance does not guarantee future results",
|
|
593
|
+
"This strategy may underperform in sideways markets"
|
|
594
|
+
],
|
|
595
|
+
systemPrompt: `You are an AI trading analyst specializing in momentum trading strategies.
|
|
596
|
+
|
|
597
|
+
Your role is to analyze market data and identify momentum-based trading opportunities.
|
|
598
|
+
|
|
599
|
+
IMPORTANT CONSTRAINTS:
|
|
600
|
+
- Only recommend trades when there is clear momentum evidence
|
|
601
|
+
- Always consider risk/reward ratios
|
|
602
|
+
- Never recommend more than the configured position size limits
|
|
603
|
+
- Be conservative with confidence scores
|
|
604
|
+
|
|
605
|
+
When analyzing data, look for:
|
|
606
|
+
1. Price trends (higher highs, higher lows for uptrends)
|
|
607
|
+
2. Volume confirmation (increasing volume on moves)
|
|
608
|
+
3. Relative strength vs market benchmarks
|
|
609
|
+
|
|
610
|
+
Respond with JSON in this format:
|
|
611
|
+
{
|
|
612
|
+
"analysis": "Brief market analysis",
|
|
613
|
+
"signals": [
|
|
614
|
+
{
|
|
615
|
+
"action": "buy" | "sell" | "hold",
|
|
616
|
+
"tokenIn": "0x...",
|
|
617
|
+
"tokenOut": "0x...",
|
|
618
|
+
"percentage": 0-100,
|
|
619
|
+
"confidence": 0-1,
|
|
620
|
+
"reasoning": "Why this trade"
|
|
621
|
+
}
|
|
622
|
+
]
|
|
623
|
+
}`,
|
|
624
|
+
exampleCode: `import { StrategyFunction, MarketData, TradeSignal, LLMAdapter, AgentConfig } from '@exagent/agent';
|
|
625
|
+
|
|
626
|
+
export const generateSignals: StrategyFunction = async (
|
|
627
|
+
marketData: MarketData,
|
|
628
|
+
llm: LLMAdapter,
|
|
629
|
+
config: AgentConfig
|
|
630
|
+
): Promise<TradeSignal[]> => {
|
|
631
|
+
const response = await llm.chat([
|
|
632
|
+
{ role: 'system', content: MOMENTUM_SYSTEM_PROMPT },
|
|
633
|
+
{ role: 'user', content: JSON.stringify({
|
|
634
|
+
prices: marketData.prices,
|
|
635
|
+
balances: formatBalances(marketData.balances),
|
|
636
|
+
portfolioValue: marketData.portfolioValue,
|
|
637
|
+
})}
|
|
638
|
+
]);
|
|
639
|
+
|
|
640
|
+
// Parse LLM response and convert to TradeSignals
|
|
641
|
+
const parsed = JSON.parse(response.content);
|
|
642
|
+
return parsed.signals.map(convertToTradeSignal);
|
|
643
|
+
};`
|
|
644
|
+
},
|
|
645
|
+
{
|
|
646
|
+
id: "value",
|
|
647
|
+
name: "Value Investor",
|
|
648
|
+
description: "Looks for undervalued assets based on fundamentals. Takes long-term positions.",
|
|
649
|
+
riskLevel: "low",
|
|
650
|
+
riskWarnings: [
|
|
651
|
+
"Value traps can result in prolonged losses",
|
|
652
|
+
"Requires patience - may underperform for extended periods",
|
|
653
|
+
"Fundamental analysis may not apply well to all crypto assets",
|
|
654
|
+
"Market sentiment can override fundamentals for long periods"
|
|
655
|
+
],
|
|
656
|
+
systemPrompt: `You are an AI trading analyst specializing in value investing.
|
|
657
|
+
|
|
658
|
+
Your role is to identify undervalued assets with strong fundamentals.
|
|
659
|
+
|
|
660
|
+
IMPORTANT CONSTRAINTS:
|
|
661
|
+
- Focus on long-term value, not short-term price movements
|
|
662
|
+
- Only recommend assets with clear value propositions
|
|
663
|
+
- Consider protocol revenue, TVL, active users, developer activity
|
|
664
|
+
- Be very selective - quality over quantity
|
|
665
|
+
|
|
666
|
+
When analyzing, consider:
|
|
667
|
+
1. Protocol fundamentals (revenue, TVL, user growth)
|
|
668
|
+
2. Token economics (supply schedule, utility)
|
|
669
|
+
3. Competitive positioning
|
|
670
|
+
4. Valuation relative to peers
|
|
671
|
+
|
|
672
|
+
Respond with JSON in this format:
|
|
673
|
+
{
|
|
674
|
+
"analysis": "Brief fundamental analysis",
|
|
675
|
+
"signals": [
|
|
676
|
+
{
|
|
677
|
+
"action": "buy" | "sell" | "hold",
|
|
678
|
+
"tokenIn": "0x...",
|
|
679
|
+
"tokenOut": "0x...",
|
|
680
|
+
"percentage": 0-100,
|
|
681
|
+
"confidence": 0-1,
|
|
682
|
+
"reasoning": "Fundamental thesis"
|
|
683
|
+
}
|
|
684
|
+
]
|
|
685
|
+
}`,
|
|
686
|
+
exampleCode: `import { StrategyFunction } from '@exagent/agent';
|
|
687
|
+
|
|
688
|
+
export const generateSignals: StrategyFunction = async (marketData, llm, config) => {
|
|
689
|
+
// Value strategy runs less frequently
|
|
690
|
+
const response = await llm.chat([
|
|
691
|
+
{ role: 'system', content: VALUE_SYSTEM_PROMPT },
|
|
692
|
+
{ role: 'user', content: JSON.stringify(marketData) }
|
|
693
|
+
]);
|
|
694
|
+
|
|
695
|
+
return parseSignals(response.content);
|
|
696
|
+
};`
|
|
697
|
+
},
|
|
698
|
+
{
|
|
699
|
+
id: "arbitrage",
|
|
700
|
+
name: "Arbitrage Hunter",
|
|
701
|
+
description: "Looks for price discrepancies across DEXs. Requires fast execution.",
|
|
702
|
+
riskLevel: "high",
|
|
703
|
+
riskWarnings: [
|
|
704
|
+
"Arbitrage opportunities are highly competitive - professional bots dominate",
|
|
705
|
+
"Slippage and gas costs can eliminate profits",
|
|
706
|
+
"MEV bots may front-run your transactions",
|
|
707
|
+
"Requires very fast execution and may not be profitable with standard infrastructure",
|
|
708
|
+
"This strategy is generally NOT recommended for beginners"
|
|
709
|
+
],
|
|
710
|
+
systemPrompt: `You are an AI trading analyst specializing in arbitrage detection.
|
|
711
|
+
|
|
712
|
+
Your role is to identify price discrepancies that may offer arbitrage opportunities.
|
|
713
|
+
|
|
714
|
+
IMPORTANT CONSTRAINTS:
|
|
715
|
+
- Account for gas costs in all calculations
|
|
716
|
+
- Account for slippage (assume 0.3% minimum)
|
|
717
|
+
- Only flag opportunities with >1% net profit potential
|
|
718
|
+
- Consider MEV risk - assume some profit extraction
|
|
719
|
+
|
|
720
|
+
This is an advanced strategy with high competition.
|
|
721
|
+
|
|
722
|
+
Respond with JSON in this format:
|
|
723
|
+
{
|
|
724
|
+
"opportunities": [
|
|
725
|
+
{
|
|
726
|
+
"description": "What the arbitrage is",
|
|
727
|
+
"expectedProfit": "Net profit after costs",
|
|
728
|
+
"confidence": 0-1,
|
|
729
|
+
"warning": "Risks specific to this opportunity"
|
|
730
|
+
}
|
|
731
|
+
]
|
|
732
|
+
}`,
|
|
733
|
+
exampleCode: `// Note: Pure arbitrage requires specialized infrastructure
|
|
734
|
+
// This template is for educational purposes
|
|
735
|
+
|
|
736
|
+
import { StrategyFunction } from '@exagent/agent';
|
|
737
|
+
|
|
738
|
+
export const generateSignals: StrategyFunction = async (marketData, llm, config) => {
|
|
739
|
+
// Arbitrage requires real-time price feeds from multiple sources
|
|
740
|
+
// Standard LLM-based analysis is too slow for most arbitrage
|
|
741
|
+
console.warn('Arbitrage strategy requires specialized infrastructure');
|
|
742
|
+
return [];
|
|
743
|
+
};`
|
|
744
|
+
},
|
|
745
|
+
{
|
|
746
|
+
id: "custom",
|
|
747
|
+
name: "Custom Strategy",
|
|
748
|
+
description: "Build your own strategy from scratch. Full control over logic and prompts.",
|
|
749
|
+
riskLevel: "extreme",
|
|
750
|
+
riskWarnings: [
|
|
751
|
+
"Custom strategies have no guardrails - you are fully responsible",
|
|
752
|
+
"LLMs can hallucinate or make errors - always validate outputs",
|
|
753
|
+
"Test thoroughly on testnet before using real funds",
|
|
754
|
+
"Consider edge cases: what happens if the LLM returns invalid JSON?",
|
|
755
|
+
"Your prompts and strategy logic are your competitive advantage - protect them",
|
|
756
|
+
"Agents may not behave exactly as expected based on your prompts"
|
|
757
|
+
],
|
|
758
|
+
systemPrompt: `// Define your own system prompt here
|
|
759
|
+
|
|
760
|
+
You are a trading AI. Analyze the market data and provide trading signals.
|
|
761
|
+
|
|
762
|
+
// Add your specific instructions, constraints, and output format.
|
|
763
|
+
|
|
764
|
+
Respond with JSON:
|
|
765
|
+
{
|
|
766
|
+
"signals": []
|
|
767
|
+
}`,
|
|
768
|
+
exampleCode: `import { StrategyFunction, MarketData, TradeSignal, LLMAdapter, AgentConfig } from '@exagent/agent';
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Custom Strategy Template
|
|
772
|
+
*
|
|
773
|
+
* Customize this file with your own trading logic and prompts.
|
|
774
|
+
* Your prompts are YOUR intellectual property - we don't store them.
|
|
775
|
+
*/
|
|
776
|
+
export const generateSignals: StrategyFunction = async (
|
|
777
|
+
marketData: MarketData,
|
|
778
|
+
llm: LLMAdapter,
|
|
779
|
+
config: AgentConfig
|
|
780
|
+
): Promise<TradeSignal[]> => {
|
|
781
|
+
// Your custom system prompt (this is your secret sauce)
|
|
782
|
+
const systemPrompt = \`
|
|
783
|
+
Your custom instructions here...
|
|
784
|
+
\`;
|
|
785
|
+
|
|
786
|
+
// Call the LLM with your prompt
|
|
787
|
+
const response = await llm.chat([
|
|
788
|
+
{ role: 'system', content: systemPrompt },
|
|
789
|
+
{ role: 'user', content: JSON.stringify(marketData) }
|
|
790
|
+
]);
|
|
791
|
+
|
|
792
|
+
// Parse and return signals
|
|
793
|
+
// IMPORTANT: Validate LLM output before using
|
|
794
|
+
try {
|
|
795
|
+
const parsed = JSON.parse(response.content);
|
|
796
|
+
return parsed.signals || [];
|
|
797
|
+
} catch (e) {
|
|
798
|
+
console.error('Failed to parse LLM response:', e);
|
|
799
|
+
return []; // Safe fallback: no trades
|
|
800
|
+
}
|
|
801
|
+
};`
|
|
802
|
+
}
|
|
803
|
+
];
|
|
804
|
+
function getStrategyTemplate(id) {
|
|
805
|
+
return STRATEGY_TEMPLATES.find((t) => t.id === id);
|
|
806
|
+
}
|
|
807
|
+
function getAllStrategyTemplates() {
|
|
808
|
+
return STRATEGY_TEMPLATES;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/trading/executor.ts
|
|
812
|
+
var TradeExecutor = class {
|
|
813
|
+
client;
|
|
814
|
+
config;
|
|
815
|
+
constructor(client, config) {
|
|
816
|
+
this.client = client;
|
|
817
|
+
this.config = config;
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Execute a single trade signal
|
|
821
|
+
*/
|
|
822
|
+
async execute(signal) {
|
|
823
|
+
if (signal.action === "hold") {
|
|
824
|
+
return { success: true };
|
|
825
|
+
}
|
|
826
|
+
try {
|
|
827
|
+
console.log(`Executing ${signal.action}: ${signal.tokenIn} -> ${signal.tokenOut}`);
|
|
828
|
+
console.log(`Amount: ${signal.amountIn.toString()}, Confidence: ${signal.confidence}`);
|
|
829
|
+
if (!this.validateSignal(signal)) {
|
|
830
|
+
return { success: false, error: "Signal exceeds position limits" };
|
|
831
|
+
}
|
|
832
|
+
const result = await this.client.trade({
|
|
833
|
+
tokenIn: signal.tokenIn,
|
|
834
|
+
tokenOut: signal.tokenOut,
|
|
835
|
+
amountIn: signal.amountIn,
|
|
836
|
+
maxSlippageBps: 100
|
|
837
|
+
// 1% default slippage
|
|
838
|
+
});
|
|
839
|
+
console.log(`Trade executed: ${result.hash}`);
|
|
840
|
+
return { success: true, txHash: result.hash };
|
|
841
|
+
} catch (error) {
|
|
842
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
843
|
+
console.error(`Trade failed: ${message}`);
|
|
844
|
+
return { success: false, error: message };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Execute multiple trade signals
|
|
849
|
+
* Returns results for each signal
|
|
850
|
+
*/
|
|
851
|
+
async executeAll(signals) {
|
|
852
|
+
const results = [];
|
|
853
|
+
for (const signal of signals) {
|
|
854
|
+
const result = await this.execute(signal);
|
|
855
|
+
results.push({ signal, ...result });
|
|
856
|
+
if (signals.indexOf(signal) < signals.length - 1) {
|
|
857
|
+
await this.delay(1e3);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
return results;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Validate a signal against config limits
|
|
864
|
+
*/
|
|
865
|
+
validateSignal(signal) {
|
|
866
|
+
if (signal.confidence < 0.5) {
|
|
867
|
+
console.warn(`Signal confidence ${signal.confidence} below threshold (0.5)`);
|
|
868
|
+
return false;
|
|
869
|
+
}
|
|
870
|
+
return true;
|
|
871
|
+
}
|
|
872
|
+
delay(ms) {
|
|
873
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
// src/trading/risk.ts
|
|
878
|
+
var RiskManager = class {
|
|
879
|
+
config;
|
|
880
|
+
dailyPnL = 0;
|
|
881
|
+
lastResetDate = "";
|
|
882
|
+
constructor(config) {
|
|
883
|
+
this.config = config;
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Filter signals through risk checks
|
|
887
|
+
* Returns only signals that pass all guardrails
|
|
888
|
+
*/
|
|
889
|
+
filterSignals(signals, marketData) {
|
|
890
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
891
|
+
if (today !== this.lastResetDate) {
|
|
892
|
+
this.dailyPnL = 0;
|
|
893
|
+
this.lastResetDate = today;
|
|
894
|
+
}
|
|
895
|
+
if (this.isDailyLossLimitHit(marketData.portfolioValue)) {
|
|
896
|
+
console.warn("Daily loss limit reached - no new trades");
|
|
897
|
+
return [];
|
|
898
|
+
}
|
|
899
|
+
return signals.filter((signal) => this.validateSignal(signal, marketData));
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Validate individual signal against risk limits
|
|
903
|
+
*/
|
|
904
|
+
validateSignal(signal, marketData) {
|
|
905
|
+
if (signal.action === "hold") {
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
const signalValue = this.estimateSignalValue(signal, marketData);
|
|
909
|
+
const maxPositionValue = marketData.portfolioValue * this.config.maxPositionSizeBps / 1e4;
|
|
910
|
+
if (signalValue > maxPositionValue) {
|
|
911
|
+
console.warn(
|
|
912
|
+
`Signal exceeds position limit: ${signalValue.toFixed(2)} > ${maxPositionValue.toFixed(2)}`
|
|
913
|
+
);
|
|
914
|
+
return false;
|
|
915
|
+
}
|
|
916
|
+
if (signal.confidence < 0.5) {
|
|
917
|
+
console.warn(`Signal confidence too low: ${signal.confidence}`);
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Check if daily loss limit has been hit
|
|
924
|
+
*/
|
|
925
|
+
isDailyLossLimitHit(portfolioValue) {
|
|
926
|
+
const maxLoss = portfolioValue * this.config.maxDailyLossBps / 1e4;
|
|
927
|
+
return this.dailyPnL < -maxLoss;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Estimate USD value of a trade signal
|
|
931
|
+
*/
|
|
932
|
+
estimateSignalValue(signal, marketData) {
|
|
933
|
+
const price = marketData.prices[signal.tokenIn] || 0;
|
|
934
|
+
const amount = Number(signal.amountIn) / 1e18;
|
|
935
|
+
return amount * price;
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Update daily PnL after a trade
|
|
939
|
+
*/
|
|
940
|
+
updatePnL(pnl) {
|
|
941
|
+
this.dailyPnL += pnl;
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Get current risk status
|
|
945
|
+
*/
|
|
946
|
+
getStatus() {
|
|
947
|
+
return {
|
|
948
|
+
dailyPnL: this.dailyPnL,
|
|
949
|
+
dailyLossLimit: this.config.maxDailyLossBps / 100,
|
|
950
|
+
// As percentage
|
|
951
|
+
isLimitHit: this.dailyPnL < -(this.config.maxDailyLossBps / 100)
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
};
|
|
955
|
+
|
|
956
|
+
// src/trading/market.ts
|
|
957
|
+
import { createPublicClient, http, erc20Abi } from "viem";
|
|
958
|
+
var NATIVE_ETH = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
959
|
+
var USDC_DECIMALS = {
|
|
960
|
+
"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": 6,
|
|
961
|
+
// USDC on Base
|
|
962
|
+
"0xd9aaec86b65d86f6a7b5b1b0c42ffa531710b6ca": 6
|
|
963
|
+
// USDbC on Base
|
|
964
|
+
};
|
|
965
|
+
var MarketDataService = class {
|
|
966
|
+
rpcUrl;
|
|
967
|
+
client;
|
|
968
|
+
constructor(rpcUrl) {
|
|
969
|
+
this.rpcUrl = rpcUrl;
|
|
970
|
+
this.client = createPublicClient({
|
|
971
|
+
transport: http(rpcUrl)
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Fetch current market data for the agent
|
|
976
|
+
*/
|
|
977
|
+
async fetchMarketData(walletAddress, tokenAddresses) {
|
|
978
|
+
const prices = await this.fetchPrices(tokenAddresses);
|
|
979
|
+
const balances = await this.fetchBalances(walletAddress, tokenAddresses);
|
|
980
|
+
const portfolioValue = this.calculatePortfolioValue(balances, prices);
|
|
981
|
+
return {
|
|
982
|
+
timestamp: Date.now(),
|
|
983
|
+
prices,
|
|
984
|
+
balances,
|
|
985
|
+
portfolioValue
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
/**
|
|
989
|
+
* Fetch token prices from price oracle
|
|
990
|
+
*/
|
|
991
|
+
async fetchPrices(tokenAddresses) {
|
|
992
|
+
const prices = {};
|
|
993
|
+
const knownPrices = {
|
|
994
|
+
// Native ETH (sentinel address)
|
|
995
|
+
[NATIVE_ETH.toLowerCase()]: 3500,
|
|
996
|
+
// WETH
|
|
997
|
+
"0x4200000000000000000000000000000000000006": 3500,
|
|
998
|
+
// USDC
|
|
999
|
+
"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": 1,
|
|
1000
|
+
// USDbC (bridged USDC)
|
|
1001
|
+
"0xd9aaec86b65d86f6a7b5b1b0c42ffa531710b6ca": 1
|
|
1002
|
+
};
|
|
1003
|
+
prices[NATIVE_ETH.toLowerCase()] = knownPrices[NATIVE_ETH.toLowerCase()];
|
|
1004
|
+
for (const address of tokenAddresses) {
|
|
1005
|
+
prices[address.toLowerCase()] = knownPrices[address.toLowerCase()] || 0;
|
|
1006
|
+
}
|
|
1007
|
+
return prices;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Fetch real on-chain balances: native ETH + ERC-20 tokens
|
|
1011
|
+
*/
|
|
1012
|
+
async fetchBalances(walletAddress, tokenAddresses) {
|
|
1013
|
+
const balances = {};
|
|
1014
|
+
const wallet = walletAddress;
|
|
1015
|
+
try {
|
|
1016
|
+
const nativeBalance = await this.client.getBalance({ address: wallet });
|
|
1017
|
+
balances[NATIVE_ETH.toLowerCase()] = nativeBalance;
|
|
1018
|
+
const erc20Promises = tokenAddresses.map(async (tokenAddress) => {
|
|
1019
|
+
try {
|
|
1020
|
+
const balance = await this.client.readContract({
|
|
1021
|
+
address: tokenAddress,
|
|
1022
|
+
abi: erc20Abi,
|
|
1023
|
+
functionName: "balanceOf",
|
|
1024
|
+
args: [wallet]
|
|
1025
|
+
});
|
|
1026
|
+
return { address: tokenAddress.toLowerCase(), balance };
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
return { address: tokenAddress.toLowerCase(), balance: 0n };
|
|
1029
|
+
}
|
|
1030
|
+
});
|
|
1031
|
+
const results = await Promise.all(erc20Promises);
|
|
1032
|
+
for (const { address, balance } of results) {
|
|
1033
|
+
balances[address] = balance;
|
|
1034
|
+
}
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
console.error("MarketData: Failed to fetch balances:", error instanceof Error ? error.message : error);
|
|
1037
|
+
balances[NATIVE_ETH.toLowerCase()] = 0n;
|
|
1038
|
+
for (const address of tokenAddresses) {
|
|
1039
|
+
balances[address.toLowerCase()] = 0n;
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
return balances;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Calculate total portfolio value in USD
|
|
1046
|
+
*/
|
|
1047
|
+
calculatePortfolioValue(balances, prices) {
|
|
1048
|
+
let total = 0;
|
|
1049
|
+
for (const [address, balance] of Object.entries(balances)) {
|
|
1050
|
+
const price = prices[address.toLowerCase()] || 0;
|
|
1051
|
+
const decimals = USDC_DECIMALS[address.toLowerCase()] || 18;
|
|
1052
|
+
const amount = Number(balance) / Math.pow(10, decimals);
|
|
1053
|
+
total += amount * price;
|
|
1054
|
+
}
|
|
1055
|
+
return total;
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
|
|
1059
|
+
// src/vault/manager.ts
|
|
1060
|
+
import { createPublicClient as createPublicClient2, createWalletClient, http as http2 } from "viem";
|
|
1061
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
1062
|
+
import { baseSepolia, base } from "viem/chains";
|
|
1063
|
+
var ADDRESSES = {
|
|
1064
|
+
testnet: {
|
|
1065
|
+
vaultFactory: "0x5c099daaE33801a907Bb57011c6749655b55dc75",
|
|
1066
|
+
registry: "0xCF48C341e3FebeCA5ECB7eb2535f61A2Ba855d9C",
|
|
1067
|
+
usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
1068
|
+
},
|
|
1069
|
+
mainnet: {
|
|
1070
|
+
vaultFactory: "0x0000000000000000000000000000000000000000",
|
|
1071
|
+
// TODO: Deploy
|
|
1072
|
+
registry: "0x0000000000000000000000000000000000000000",
|
|
1073
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
1074
|
+
// Base mainnet USDC
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
var VAULT_FACTORY_ABI = [
|
|
1078
|
+
{
|
|
1079
|
+
type: "function",
|
|
1080
|
+
name: "vaults",
|
|
1081
|
+
inputs: [{ name: "agentId", type: "uint256" }, { name: "asset", type: "address" }],
|
|
1082
|
+
outputs: [{ type: "address" }],
|
|
1083
|
+
stateMutability: "view"
|
|
1084
|
+
},
|
|
1085
|
+
{
|
|
1086
|
+
type: "function",
|
|
1087
|
+
name: "canCreateVault",
|
|
1088
|
+
inputs: [{ name: "creator", type: "address" }],
|
|
1089
|
+
outputs: [{ name: "canCreate", type: "bool" }, { name: "reason", type: "string" }],
|
|
1090
|
+
stateMutability: "view"
|
|
1091
|
+
},
|
|
1092
|
+
{
|
|
1093
|
+
type: "function",
|
|
1094
|
+
name: "createVault",
|
|
1095
|
+
inputs: [
|
|
1096
|
+
{ name: "agentId", type: "uint256" },
|
|
1097
|
+
{ name: "asset", type: "address" },
|
|
1098
|
+
{ name: "name", type: "string" },
|
|
1099
|
+
{ name: "symbol", type: "string" },
|
|
1100
|
+
{ name: "feeRecipient", type: "address" }
|
|
1101
|
+
],
|
|
1102
|
+
outputs: [{ type: "address" }],
|
|
1103
|
+
stateMutability: "nonpayable"
|
|
1104
|
+
},
|
|
1105
|
+
{
|
|
1106
|
+
type: "function",
|
|
1107
|
+
name: "minimumVeEXARequired",
|
|
1108
|
+
inputs: [],
|
|
1109
|
+
outputs: [{ type: "uint256" }],
|
|
1110
|
+
stateMutability: "view"
|
|
1111
|
+
},
|
|
1112
|
+
{
|
|
1113
|
+
type: "function",
|
|
1114
|
+
name: "eXABurnFee",
|
|
1115
|
+
inputs: [],
|
|
1116
|
+
outputs: [{ type: "uint256" }],
|
|
1117
|
+
stateMutability: "view"
|
|
1118
|
+
}
|
|
1119
|
+
];
|
|
1120
|
+
var VAULT_ABI = [
|
|
1121
|
+
{
|
|
1122
|
+
type: "function",
|
|
1123
|
+
name: "totalAssets",
|
|
1124
|
+
inputs: [],
|
|
1125
|
+
outputs: [{ type: "uint256" }],
|
|
1126
|
+
stateMutability: "view"
|
|
1127
|
+
},
|
|
1128
|
+
{
|
|
1129
|
+
type: "function",
|
|
1130
|
+
name: "executeTrade",
|
|
1131
|
+
inputs: [
|
|
1132
|
+
{ name: "tokenIn", type: "address" },
|
|
1133
|
+
{ name: "tokenOut", type: "address" },
|
|
1134
|
+
{ name: "amountIn", type: "uint256" },
|
|
1135
|
+
{ name: "minAmountOut", type: "uint256" },
|
|
1136
|
+
{ name: "aggregator", type: "address" },
|
|
1137
|
+
{ name: "swapData", type: "bytes" },
|
|
1138
|
+
{ name: "deadline", type: "uint256" }
|
|
1139
|
+
],
|
|
1140
|
+
outputs: [{ type: "uint256" }],
|
|
1141
|
+
stateMutability: "nonpayable"
|
|
1142
|
+
}
|
|
1143
|
+
];
|
|
1144
|
+
var VaultManager = class {
|
|
1145
|
+
config;
|
|
1146
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1147
|
+
publicClient;
|
|
1148
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1149
|
+
walletClient;
|
|
1150
|
+
addresses;
|
|
1151
|
+
account;
|
|
1152
|
+
chain;
|
|
1153
|
+
cachedVaultAddress = null;
|
|
1154
|
+
lastVaultCheck = 0;
|
|
1155
|
+
VAULT_CACHE_TTL = 6e4;
|
|
1156
|
+
// 1 minute
|
|
1157
|
+
constructor(config) {
|
|
1158
|
+
this.config = config;
|
|
1159
|
+
this.addresses = ADDRESSES[config.network];
|
|
1160
|
+
this.account = privateKeyToAccount(config.walletKey);
|
|
1161
|
+
this.chain = config.network === "mainnet" ? base : baseSepolia;
|
|
1162
|
+
const rpcUrl = config.network === "mainnet" ? "https://mainnet.base.org" : "https://sepolia.base.org";
|
|
1163
|
+
this.publicClient = createPublicClient2({
|
|
1164
|
+
chain: this.chain,
|
|
1165
|
+
transport: http2(rpcUrl)
|
|
1166
|
+
});
|
|
1167
|
+
this.walletClient = createWalletClient({
|
|
1168
|
+
account: this.account,
|
|
1169
|
+
chain: this.chain,
|
|
1170
|
+
transport: http2(rpcUrl)
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Get the agent's vault policy
|
|
1175
|
+
*/
|
|
1176
|
+
get policy() {
|
|
1177
|
+
return this.config.vaultConfig.policy;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Check if vault trading is preferred when a vault exists
|
|
1181
|
+
*/
|
|
1182
|
+
get preferVaultTrading() {
|
|
1183
|
+
return this.config.vaultConfig.preferVaultTrading;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Get comprehensive vault status
|
|
1187
|
+
*/
|
|
1188
|
+
async getVaultStatus() {
|
|
1189
|
+
const vaultAddress = await this.getVaultAddress();
|
|
1190
|
+
const hasVault = vaultAddress !== null;
|
|
1191
|
+
let totalAssets = BigInt(0);
|
|
1192
|
+
if (hasVault && vaultAddress) {
|
|
1193
|
+
try {
|
|
1194
|
+
totalAssets = await this.publicClient.readContract({
|
|
1195
|
+
address: vaultAddress,
|
|
1196
|
+
abi: VAULT_ABI,
|
|
1197
|
+
functionName: "totalAssets"
|
|
1198
|
+
});
|
|
1199
|
+
} catch {
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
const [canCreateResult, requirements] = await Promise.all([
|
|
1203
|
+
this.publicClient.readContract({
|
|
1204
|
+
address: this.addresses.vaultFactory,
|
|
1205
|
+
abi: VAULT_FACTORY_ABI,
|
|
1206
|
+
functionName: "canCreateVault",
|
|
1207
|
+
args: [this.account.address]
|
|
1208
|
+
}),
|
|
1209
|
+
this.getRequirements()
|
|
1210
|
+
]);
|
|
1211
|
+
return {
|
|
1212
|
+
hasVault,
|
|
1213
|
+
vaultAddress,
|
|
1214
|
+
totalAssets,
|
|
1215
|
+
canCreateVault: canCreateResult[0],
|
|
1216
|
+
cannotCreateReason: canCreateResult[0] ? null : canCreateResult[1],
|
|
1217
|
+
requirementsMet: canCreateResult[0] || requirements.isBypassed,
|
|
1218
|
+
requirements
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Get vault creation requirements
|
|
1223
|
+
*/
|
|
1224
|
+
async getRequirements() {
|
|
1225
|
+
const [veXARequired, burnFee] = await Promise.all([
|
|
1226
|
+
this.publicClient.readContract({
|
|
1227
|
+
address: this.addresses.vaultFactory,
|
|
1228
|
+
abi: VAULT_FACTORY_ABI,
|
|
1229
|
+
functionName: "minimumVeEXARequired"
|
|
1230
|
+
}),
|
|
1231
|
+
this.publicClient.readContract({
|
|
1232
|
+
address: this.addresses.vaultFactory,
|
|
1233
|
+
abi: VAULT_FACTORY_ABI,
|
|
1234
|
+
functionName: "eXABurnFee"
|
|
1235
|
+
})
|
|
1236
|
+
]);
|
|
1237
|
+
const isBypassed = veXARequired === BigInt(0) && burnFee === BigInt(0);
|
|
1238
|
+
return { veXARequired, burnFee, isBypassed };
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* Get the agent's vault address (cached)
|
|
1242
|
+
*/
|
|
1243
|
+
async getVaultAddress() {
|
|
1244
|
+
const now = Date.now();
|
|
1245
|
+
if (this.cachedVaultAddress && now - this.lastVaultCheck < this.VAULT_CACHE_TTL) {
|
|
1246
|
+
return this.cachedVaultAddress;
|
|
1247
|
+
}
|
|
1248
|
+
const vaultAddress = await this.publicClient.readContract({
|
|
1249
|
+
address: this.addresses.vaultFactory,
|
|
1250
|
+
abi: VAULT_FACTORY_ABI,
|
|
1251
|
+
functionName: "vaults",
|
|
1252
|
+
args: [this.config.agentId, this.addresses.usdc]
|
|
1253
|
+
});
|
|
1254
|
+
this.lastVaultCheck = now;
|
|
1255
|
+
if (vaultAddress === "0x0000000000000000000000000000000000000000") {
|
|
1256
|
+
this.cachedVaultAddress = null;
|
|
1257
|
+
return null;
|
|
1258
|
+
}
|
|
1259
|
+
this.cachedVaultAddress = vaultAddress;
|
|
1260
|
+
return vaultAddress;
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Check if the agent should create a vault based on policy and qualification
|
|
1264
|
+
*/
|
|
1265
|
+
async shouldCreateVault() {
|
|
1266
|
+
if (this.policy === "disabled") {
|
|
1267
|
+
return { should: false, reason: "Vault creation disabled by policy" };
|
|
1268
|
+
}
|
|
1269
|
+
if (this.policy === "manual") {
|
|
1270
|
+
return { should: false, reason: "Vault creation set to manual - waiting for owner instruction" };
|
|
1271
|
+
}
|
|
1272
|
+
const status = await this.getVaultStatus();
|
|
1273
|
+
if (status.hasVault) {
|
|
1274
|
+
return { should: false, reason: "Vault already exists" };
|
|
1275
|
+
}
|
|
1276
|
+
if (!status.canCreateVault) {
|
|
1277
|
+
return { should: false, reason: status.cannotCreateReason || "Requirements not met" };
|
|
1278
|
+
}
|
|
1279
|
+
return { should: true, reason: "Agent is qualified and auto-creation is enabled" };
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Create a vault for the agent
|
|
1283
|
+
* @returns Vault address if successful
|
|
1284
|
+
*/
|
|
1285
|
+
async createVault() {
|
|
1286
|
+
if (this.policy === "disabled") {
|
|
1287
|
+
return { success: false, error: "Vault creation disabled by policy" };
|
|
1288
|
+
}
|
|
1289
|
+
const existingVault = await this.getVaultAddress();
|
|
1290
|
+
if (existingVault) {
|
|
1291
|
+
return { success: false, error: "Vault already exists", vaultAddress: existingVault };
|
|
1292
|
+
}
|
|
1293
|
+
const status = await this.getVaultStatus();
|
|
1294
|
+
if (!status.canCreateVault) {
|
|
1295
|
+
return { success: false, error: status.cannotCreateReason || "Requirements not met" };
|
|
1296
|
+
}
|
|
1297
|
+
const vaultName = this.config.vaultConfig.defaultName || `${this.config.agentName} Trading Vault`;
|
|
1298
|
+
const vaultSymbol = this.config.vaultConfig.defaultSymbol || `ex${this.config.agentName.replace(/[^a-zA-Z]/g, "").slice(0, 4).toUpperCase()}`;
|
|
1299
|
+
const feeRecipient = this.config.vaultConfig.feeRecipient || this.account.address;
|
|
1300
|
+
try {
|
|
1301
|
+
const hash = await this.walletClient.writeContract({
|
|
1302
|
+
address: this.addresses.vaultFactory,
|
|
1303
|
+
abi: VAULT_FACTORY_ABI,
|
|
1304
|
+
functionName: "createVault",
|
|
1305
|
+
args: [
|
|
1306
|
+
this.config.agentId,
|
|
1307
|
+
this.addresses.usdc,
|
|
1308
|
+
vaultName,
|
|
1309
|
+
vaultSymbol,
|
|
1310
|
+
feeRecipient
|
|
1311
|
+
],
|
|
1312
|
+
chain: this.chain,
|
|
1313
|
+
account: this.account
|
|
1314
|
+
});
|
|
1315
|
+
const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
|
|
1316
|
+
if (receipt.status !== "success") {
|
|
1317
|
+
return { success: false, error: "Transaction failed", txHash: hash };
|
|
1318
|
+
}
|
|
1319
|
+
const vaultAddress = await this.getVaultAddress();
|
|
1320
|
+
this.cachedVaultAddress = vaultAddress;
|
|
1321
|
+
return {
|
|
1322
|
+
success: true,
|
|
1323
|
+
vaultAddress,
|
|
1324
|
+
txHash: hash
|
|
1325
|
+
};
|
|
1326
|
+
} catch (error) {
|
|
1327
|
+
return {
|
|
1328
|
+
success: false,
|
|
1329
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Execute a trade through the vault (if it exists and policy allows)
|
|
1335
|
+
* Returns null if should use direct trading instead
|
|
1336
|
+
*/
|
|
1337
|
+
async executeVaultTrade(params) {
|
|
1338
|
+
if (!this.preferVaultTrading) {
|
|
1339
|
+
return null;
|
|
1340
|
+
}
|
|
1341
|
+
const vaultAddress = await this.getVaultAddress();
|
|
1342
|
+
if (!vaultAddress) {
|
|
1343
|
+
return null;
|
|
1344
|
+
}
|
|
1345
|
+
const deadline = params.deadline || BigInt(Math.floor(Date.now() / 1e3) + 3600);
|
|
1346
|
+
try {
|
|
1347
|
+
const hash = await this.walletClient.writeContract({
|
|
1348
|
+
address: vaultAddress,
|
|
1349
|
+
abi: VAULT_ABI,
|
|
1350
|
+
functionName: "executeTrade",
|
|
1351
|
+
args: [
|
|
1352
|
+
params.tokenIn,
|
|
1353
|
+
params.tokenOut,
|
|
1354
|
+
params.amountIn,
|
|
1355
|
+
params.minAmountOut,
|
|
1356
|
+
params.aggregator,
|
|
1357
|
+
params.swapData,
|
|
1358
|
+
deadline
|
|
1359
|
+
],
|
|
1360
|
+
chain: this.chain,
|
|
1361
|
+
account: this.account
|
|
1362
|
+
});
|
|
1363
|
+
return { usedVault: true, txHash: hash };
|
|
1364
|
+
} catch (error) {
|
|
1365
|
+
return {
|
|
1366
|
+
usedVault: true,
|
|
1367
|
+
error: error instanceof Error ? error.message : "Vault trade failed"
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Run the auto-creation check (call this periodically in the agent loop)
|
|
1373
|
+
* Only creates vault if policy is 'auto_when_qualified'
|
|
1374
|
+
*/
|
|
1375
|
+
async checkAndAutoCreateVault() {
|
|
1376
|
+
const shouldCreate = await this.shouldCreateVault();
|
|
1377
|
+
if (!shouldCreate.should) {
|
|
1378
|
+
const status = await this.getVaultStatus();
|
|
1379
|
+
if (status.hasVault) {
|
|
1380
|
+
return { action: "already_exists", vaultAddress: status.vaultAddress, reason: "Vault already exists" };
|
|
1381
|
+
}
|
|
1382
|
+
if (this.policy !== "auto_when_qualified") {
|
|
1383
|
+
return { action: "skipped", reason: shouldCreate.reason };
|
|
1384
|
+
}
|
|
1385
|
+
return { action: "not_qualified", reason: shouldCreate.reason };
|
|
1386
|
+
}
|
|
1387
|
+
const result = await this.createVault();
|
|
1388
|
+
if (result.success) {
|
|
1389
|
+
return {
|
|
1390
|
+
action: "created",
|
|
1391
|
+
vaultAddress: result.vaultAddress,
|
|
1392
|
+
reason: "Vault created automatically"
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
return { action: "not_qualified", reason: result.error || "Creation failed" };
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
|
|
1399
|
+
// src/relay.ts
|
|
1400
|
+
import WebSocket from "ws";
|
|
1401
|
+
import { privateKeyToAccount as privateKeyToAccount2, signMessage } from "viem/accounts";
|
|
1402
|
+
var RelayClient = class {
|
|
1403
|
+
config;
|
|
1404
|
+
ws = null;
|
|
1405
|
+
authenticated = false;
|
|
1406
|
+
authRejected = false;
|
|
1407
|
+
reconnectAttempts = 0;
|
|
1408
|
+
maxReconnectAttempts = 50;
|
|
1409
|
+
reconnectTimer = null;
|
|
1410
|
+
heartbeatTimer = null;
|
|
1411
|
+
stopped = false;
|
|
1412
|
+
constructor(config) {
|
|
1413
|
+
this.config = config;
|
|
1414
|
+
}
|
|
1415
|
+
/**
|
|
1416
|
+
* Connect to the relay server
|
|
1417
|
+
*/
|
|
1418
|
+
async connect() {
|
|
1419
|
+
if (this.stopped) return;
|
|
1420
|
+
const wsUrl = this.config.relay.apiUrl.replace(/^https?:\/\//, (m) => m.includes("https") ? "wss://" : "ws://").replace(/\/$/, "") + "/ws/agent";
|
|
1421
|
+
return new Promise((resolve, reject) => {
|
|
1422
|
+
try {
|
|
1423
|
+
this.ws = new WebSocket(wsUrl);
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
console.error("Relay: Failed to create WebSocket:", error);
|
|
1426
|
+
this.scheduleReconnect();
|
|
1427
|
+
reject(error);
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
const connectTimeout = setTimeout(() => {
|
|
1431
|
+
if (!this.authenticated) {
|
|
1432
|
+
console.error("Relay: Connection timeout");
|
|
1433
|
+
this.ws?.close();
|
|
1434
|
+
this.scheduleReconnect();
|
|
1435
|
+
reject(new Error("Connection timeout"));
|
|
1436
|
+
}
|
|
1437
|
+
}, 15e3);
|
|
1438
|
+
this.ws.on("open", async () => {
|
|
1439
|
+
this.authRejected = false;
|
|
1440
|
+
console.log("Relay: Connected, authenticating...");
|
|
1441
|
+
try {
|
|
1442
|
+
await this.authenticate();
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
console.error("Relay: Authentication failed:", error);
|
|
1445
|
+
this.ws?.close();
|
|
1446
|
+
clearTimeout(connectTimeout);
|
|
1447
|
+
reject(error);
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
this.ws.on("message", (raw) => {
|
|
1451
|
+
try {
|
|
1452
|
+
const data = JSON.parse(raw.toString());
|
|
1453
|
+
this.handleMessage(data);
|
|
1454
|
+
if (data.type === "auth_success") {
|
|
1455
|
+
clearTimeout(connectTimeout);
|
|
1456
|
+
this.authenticated = true;
|
|
1457
|
+
this.reconnectAttempts = 0;
|
|
1458
|
+
this.startHeartbeat();
|
|
1459
|
+
console.log("Relay: Authenticated successfully");
|
|
1460
|
+
resolve();
|
|
1461
|
+
} else if (data.type === "auth_error") {
|
|
1462
|
+
clearTimeout(connectTimeout);
|
|
1463
|
+
this.authRejected = true;
|
|
1464
|
+
console.error(`Relay: Auth rejected: ${data.message}`);
|
|
1465
|
+
reject(new Error(data.message));
|
|
1466
|
+
}
|
|
1467
|
+
} catch {
|
|
1468
|
+
}
|
|
1469
|
+
});
|
|
1470
|
+
this.ws.on("close", (code, reason) => {
|
|
1471
|
+
clearTimeout(connectTimeout);
|
|
1472
|
+
this.authenticated = false;
|
|
1473
|
+
this.stopHeartbeat();
|
|
1474
|
+
if (!this.stopped) {
|
|
1475
|
+
if (!this.authRejected) {
|
|
1476
|
+
console.log(`Relay: Disconnected (${code}: ${reason.toString() || "unknown"})`);
|
|
1477
|
+
}
|
|
1478
|
+
this.scheduleReconnect();
|
|
1479
|
+
}
|
|
1480
|
+
});
|
|
1481
|
+
this.ws.on("error", (error) => {
|
|
1482
|
+
if (!this.stopped) {
|
|
1483
|
+
console.error("Relay: WebSocket error:", error.message);
|
|
1484
|
+
}
|
|
1485
|
+
});
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* Authenticate with the relay server using wallet signature
|
|
1490
|
+
*/
|
|
1491
|
+
async authenticate() {
|
|
1492
|
+
const account = privateKeyToAccount2(this.config.privateKey);
|
|
1493
|
+
const timestamp = Math.floor(Date.now() / 1e3);
|
|
1494
|
+
const message = `ExagentRelay:${this.config.agentId}:${timestamp}`;
|
|
1495
|
+
const signature = await signMessage({
|
|
1496
|
+
message,
|
|
1497
|
+
privateKey: this.config.privateKey
|
|
1498
|
+
});
|
|
1499
|
+
this.send({
|
|
1500
|
+
type: "auth",
|
|
1501
|
+
agentId: this.config.agentId,
|
|
1502
|
+
wallet: account.address,
|
|
1503
|
+
timestamp,
|
|
1504
|
+
signature
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Handle incoming messages from the relay server
|
|
1509
|
+
*/
|
|
1510
|
+
handleMessage(data) {
|
|
1511
|
+
switch (data.type) {
|
|
1512
|
+
case "command":
|
|
1513
|
+
if (data.command && this.config.onCommand) {
|
|
1514
|
+
this.config.onCommand(data.command);
|
|
1515
|
+
}
|
|
1516
|
+
break;
|
|
1517
|
+
case "auth_success":
|
|
1518
|
+
case "auth_error":
|
|
1519
|
+
break;
|
|
1520
|
+
case "error":
|
|
1521
|
+
console.error(`Relay: Server error: ${data.message}`);
|
|
1522
|
+
break;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* Send a status heartbeat
|
|
1527
|
+
*/
|
|
1528
|
+
sendHeartbeat(status) {
|
|
1529
|
+
if (!this.authenticated) return;
|
|
1530
|
+
this.send({
|
|
1531
|
+
type: "heartbeat",
|
|
1532
|
+
agentId: this.config.agentId,
|
|
1533
|
+
status
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
/**
|
|
1537
|
+
* Send a status update (outside of regular heartbeat)
|
|
1538
|
+
*/
|
|
1539
|
+
sendStatusUpdate(status) {
|
|
1540
|
+
if (!this.authenticated) return;
|
|
1541
|
+
this.send({
|
|
1542
|
+
type: "status_update",
|
|
1543
|
+
agentId: this.config.agentId,
|
|
1544
|
+
status
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Send a message to the command center
|
|
1549
|
+
*/
|
|
1550
|
+
sendMessage(messageType, level, title, body, data) {
|
|
1551
|
+
if (!this.authenticated) return;
|
|
1552
|
+
this.send({
|
|
1553
|
+
type: "message",
|
|
1554
|
+
agentId: this.config.agentId,
|
|
1555
|
+
messageType,
|
|
1556
|
+
level,
|
|
1557
|
+
title,
|
|
1558
|
+
body,
|
|
1559
|
+
data
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Send a command execution result
|
|
1564
|
+
*/
|
|
1565
|
+
sendCommandResult(commandId, success, result) {
|
|
1566
|
+
if (!this.authenticated) return;
|
|
1567
|
+
this.send({
|
|
1568
|
+
type: "command_result",
|
|
1569
|
+
agentId: this.config.agentId,
|
|
1570
|
+
commandId,
|
|
1571
|
+
success,
|
|
1572
|
+
result
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* Start the heartbeat timer
|
|
1577
|
+
*/
|
|
1578
|
+
startHeartbeat() {
|
|
1579
|
+
this.stopHeartbeat();
|
|
1580
|
+
const interval = this.config.relay.heartbeatIntervalMs || 3e4;
|
|
1581
|
+
this.heartbeatTimer = setInterval(() => {
|
|
1582
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1583
|
+
this.ws.ping();
|
|
1584
|
+
}
|
|
1585
|
+
}, interval);
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Stop the heartbeat timer
|
|
1589
|
+
*/
|
|
1590
|
+
stopHeartbeat() {
|
|
1591
|
+
if (this.heartbeatTimer) {
|
|
1592
|
+
clearInterval(this.heartbeatTimer);
|
|
1593
|
+
this.heartbeatTimer = null;
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Schedule a reconnection with exponential backoff
|
|
1598
|
+
*/
|
|
1599
|
+
scheduleReconnect() {
|
|
1600
|
+
if (this.stopped) return;
|
|
1601
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
1602
|
+
console.error("Relay: Max reconnection attempts reached. Giving up.");
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
|
|
1606
|
+
this.reconnectAttempts++;
|
|
1607
|
+
console.log(
|
|
1608
|
+
`Relay: Reconnecting in ${delay / 1e3}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
|
|
1609
|
+
);
|
|
1610
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1611
|
+
this.connect().catch(() => {
|
|
1612
|
+
});
|
|
1613
|
+
}, delay);
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* Send a JSON message to the WebSocket
|
|
1617
|
+
*/
|
|
1618
|
+
send(data) {
|
|
1619
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1620
|
+
this.ws.send(JSON.stringify(data));
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Check if connected and authenticated
|
|
1625
|
+
*/
|
|
1626
|
+
get isConnected() {
|
|
1627
|
+
return this.authenticated && this.ws?.readyState === WebSocket.OPEN;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Disconnect and stop reconnecting
|
|
1631
|
+
*/
|
|
1632
|
+
disconnect() {
|
|
1633
|
+
this.stopped = true;
|
|
1634
|
+
this.stopHeartbeat();
|
|
1635
|
+
if (this.reconnectTimer) {
|
|
1636
|
+
clearTimeout(this.reconnectTimer);
|
|
1637
|
+
this.reconnectTimer = null;
|
|
1638
|
+
}
|
|
1639
|
+
if (this.ws) {
|
|
1640
|
+
this.ws.close(1e3, "Agent shutting down");
|
|
1641
|
+
this.ws = null;
|
|
1642
|
+
}
|
|
1643
|
+
this.authenticated = false;
|
|
1644
|
+
console.log("Relay: Disconnected");
|
|
1645
|
+
}
|
|
1646
|
+
};
|
|
1647
|
+
|
|
1648
|
+
// src/runtime.ts
|
|
1649
|
+
import { ExagentClient, ExagentRegistry } from "@exagent/sdk";
|
|
1650
|
+
import { createPublicClient as createPublicClient3, http as http3 } from "viem";
|
|
1651
|
+
import { baseSepolia as baseSepolia2, base as base2 } from "viem/chains";
|
|
1652
|
+
|
|
1653
|
+
// src/browser-open.ts
|
|
1654
|
+
import { exec } from "child_process";
|
|
1655
|
+
function openBrowser(url) {
|
|
1656
|
+
const platform = process.platform;
|
|
1657
|
+
try {
|
|
1658
|
+
if (platform === "darwin") {
|
|
1659
|
+
exec(`open "${url}"`);
|
|
1660
|
+
} else if (platform === "win32") {
|
|
1661
|
+
exec(`start "" "${url}"`);
|
|
1662
|
+
} else {
|
|
1663
|
+
exec(`xdg-open "${url}"`);
|
|
1664
|
+
}
|
|
1665
|
+
} catch {
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
// src/runtime.ts
|
|
1670
|
+
var FUNDS_LOW_THRESHOLD = 5e-3;
|
|
1671
|
+
var AgentRuntime = class {
|
|
1672
|
+
config;
|
|
1673
|
+
client;
|
|
1674
|
+
llm;
|
|
1675
|
+
strategy;
|
|
1676
|
+
executor;
|
|
1677
|
+
riskManager;
|
|
1678
|
+
marketData;
|
|
1679
|
+
vaultManager;
|
|
1680
|
+
relay = null;
|
|
1681
|
+
isRunning = false;
|
|
1682
|
+
mode = "idle";
|
|
1683
|
+
configHash;
|
|
1684
|
+
lastVaultCheck = 0;
|
|
1685
|
+
cycleCount = 0;
|
|
1686
|
+
lastCycleAt = 0;
|
|
1687
|
+
lastPortfolioValue = 0;
|
|
1688
|
+
lastEthBalance = "0";
|
|
1689
|
+
processAlive = true;
|
|
1690
|
+
VAULT_CHECK_INTERVAL = 3e5;
|
|
1691
|
+
// Check vault status every 5 minutes
|
|
1692
|
+
constructor(config) {
|
|
1693
|
+
this.config = config;
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Initialize the agent runtime
|
|
1697
|
+
*/
|
|
1698
|
+
async initialize() {
|
|
1699
|
+
console.log(`Initializing agent: ${this.config.name} (ID: ${this.config.agentId})`);
|
|
1700
|
+
this.client = new ExagentClient({
|
|
1701
|
+
privateKey: this.config.privateKey,
|
|
1702
|
+
network: this.config.network
|
|
1703
|
+
});
|
|
1704
|
+
console.log(`Wallet: ${this.client.address}`);
|
|
1705
|
+
const agent = await this.client.registry.getAgent(BigInt(this.config.agentId));
|
|
1706
|
+
if (!agent) {
|
|
1707
|
+
throw new Error(`Agent ID ${this.config.agentId} not found on-chain. Please register first.`);
|
|
1708
|
+
}
|
|
1709
|
+
console.log(`Agent verified: ${agent.name}`);
|
|
1710
|
+
await this.ensureWalletLinked();
|
|
1711
|
+
console.log(`Initializing LLM: ${this.config.llm.provider}`);
|
|
1712
|
+
this.llm = await createLLMAdapter(this.config.llm);
|
|
1713
|
+
const llmMeta = this.llm.getMetadata();
|
|
1714
|
+
console.log(`LLM ready: ${llmMeta.provider} (${llmMeta.model})`);
|
|
1715
|
+
await this.syncConfigHash();
|
|
1716
|
+
this.strategy = await loadStrategy();
|
|
1717
|
+
this.executor = new TradeExecutor(this.client, this.config);
|
|
1718
|
+
this.riskManager = new RiskManager(this.config.trading);
|
|
1719
|
+
this.marketData = new MarketDataService(this.getRpcUrl());
|
|
1720
|
+
await this.initializeVaultManager();
|
|
1721
|
+
await this.initializeRelay();
|
|
1722
|
+
console.log("Agent initialized successfully");
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Initialize the relay client for command center connectivity
|
|
1726
|
+
*/
|
|
1727
|
+
async initializeRelay() {
|
|
1728
|
+
const relayConfig = this.config.relay;
|
|
1729
|
+
const relayEnabled = process.env.EXAGENT_RELAY_ENABLED !== "false";
|
|
1730
|
+
if (!relayConfig?.enabled || !relayEnabled) {
|
|
1731
|
+
console.log("Relay: Disabled");
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
const apiUrl = process.env.EXAGENT_API_URL || relayConfig.apiUrl;
|
|
1735
|
+
if (!apiUrl) {
|
|
1736
|
+
console.log("Relay: No API URL configured, skipping");
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
this.relay = new RelayClient({
|
|
1740
|
+
agentId: String(this.config.agentId),
|
|
1741
|
+
privateKey: this.config.privateKey,
|
|
1742
|
+
relay: {
|
|
1743
|
+
...relayConfig,
|
|
1744
|
+
apiUrl
|
|
1745
|
+
},
|
|
1746
|
+
onCommand: (cmd) => this.handleCommand(cmd)
|
|
1747
|
+
});
|
|
1748
|
+
try {
|
|
1749
|
+
await this.relay.connect();
|
|
1750
|
+
console.log("Relay: Connected to command center");
|
|
1751
|
+
this.sendRelayStatus();
|
|
1752
|
+
} catch (error) {
|
|
1753
|
+
console.warn(
|
|
1754
|
+
"Relay: Failed to connect (agent will work locally):",
|
|
1755
|
+
error instanceof Error ? error.message : error
|
|
1756
|
+
);
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
/**
|
|
1760
|
+
* Initialize the vault manager based on config
|
|
1761
|
+
*/
|
|
1762
|
+
async initializeVaultManager() {
|
|
1763
|
+
const vaultConfig = this.config.vault || { policy: "disabled", preferVaultTrading: false };
|
|
1764
|
+
this.vaultManager = new VaultManager({
|
|
1765
|
+
agentId: BigInt(this.config.agentId),
|
|
1766
|
+
agentName: this.config.name,
|
|
1767
|
+
network: this.config.network,
|
|
1768
|
+
walletKey: this.config.privateKey,
|
|
1769
|
+
vaultConfig
|
|
1770
|
+
});
|
|
1771
|
+
console.log(`Vault policy: ${vaultConfig.policy}`);
|
|
1772
|
+
const status = await this.vaultManager.getVaultStatus();
|
|
1773
|
+
if (status.hasVault) {
|
|
1774
|
+
console.log(`Vault exists: ${status.vaultAddress}`);
|
|
1775
|
+
console.log(`Vault TVL: ${Number(status.totalAssets) / 1e6} USDC`);
|
|
1776
|
+
} else {
|
|
1777
|
+
console.log("No vault exists for this agent");
|
|
1778
|
+
if (vaultConfig.policy === "auto_when_qualified") {
|
|
1779
|
+
if (status.canCreateVault) {
|
|
1780
|
+
console.log("Agent is qualified to create vault - will attempt on next check");
|
|
1781
|
+
} else {
|
|
1782
|
+
console.log(`Cannot create vault yet: ${status.cannotCreateReason}`);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* Ensure the current wallet is linked to the agent.
|
|
1789
|
+
* If the trading wallet differs from the owner, enters a recovery loop
|
|
1790
|
+
* that waits for the owner to link it from the website.
|
|
1791
|
+
*/
|
|
1792
|
+
async ensureWalletLinked() {
|
|
1793
|
+
const agentId = BigInt(this.config.agentId);
|
|
1794
|
+
const address = this.client.address;
|
|
1795
|
+
const isLinked = await this.client.registry.isLinkedWallet(agentId, address);
|
|
1796
|
+
if (!isLinked) {
|
|
1797
|
+
console.log("Wallet not linked, linking now...");
|
|
1798
|
+
const agent = await this.client.registry.getAgent(agentId);
|
|
1799
|
+
if (agent?.owner.toLowerCase() !== address.toLowerCase()) {
|
|
1800
|
+
const ccUrl = `https://exagent.io/agents/${encodeURIComponent(this.config.name)}/command-center`;
|
|
1801
|
+
const nonce = await this.client.registry.getNonce(address);
|
|
1802
|
+
const linkMessage = ExagentRegistry.generateLinkMessage(
|
|
1803
|
+
address,
|
|
1804
|
+
agentId,
|
|
1805
|
+
nonce
|
|
1806
|
+
);
|
|
1807
|
+
const linkSignature = await this.client.signMessage({ raw: linkMessage });
|
|
1808
|
+
console.log("");
|
|
1809
|
+
console.log("=== WALLET LINKING REQUIRED ===");
|
|
1810
|
+
console.log("");
|
|
1811
|
+
console.log(" Your trading wallet needs to be linked to your agent.");
|
|
1812
|
+
console.log(" Open the command center and paste the values below.");
|
|
1813
|
+
console.log("");
|
|
1814
|
+
console.log(` Command Center: ${ccUrl}`);
|
|
1815
|
+
console.log("");
|
|
1816
|
+
console.log(" \u2500\u2500 Copy these two values \u2500\u2500");
|
|
1817
|
+
console.log("");
|
|
1818
|
+
console.log(` Wallet: ${address}`);
|
|
1819
|
+
console.log(` Signature: ${linkSignature}`);
|
|
1820
|
+
console.log("");
|
|
1821
|
+
openBrowser(ccUrl);
|
|
1822
|
+
console.log(" Waiting for wallet to be linked... (checking every 15s)");
|
|
1823
|
+
console.log(" Press Ctrl+C to exit.");
|
|
1824
|
+
console.log("");
|
|
1825
|
+
while (true) {
|
|
1826
|
+
await this.sleep(15e3);
|
|
1827
|
+
const linked = await this.client.registry.isLinkedWallet(agentId, address);
|
|
1828
|
+
if (linked) {
|
|
1829
|
+
console.log(" Wallet linked! Continuing setup...");
|
|
1830
|
+
console.log("");
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
process.stdout.write(".");
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
await this.client.registry.linkOwnWallet(agentId);
|
|
1837
|
+
console.log("Wallet linked successfully");
|
|
1838
|
+
} else {
|
|
1839
|
+
console.log("Wallet already linked");
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Sync the LLM config hash to chain for epoch tracking.
|
|
1844
|
+
* If the wallet has insufficient gas, enters a recovery loop
|
|
1845
|
+
* that waits for the user to fund the wallet.
|
|
1846
|
+
*/
|
|
1847
|
+
async syncConfigHash() {
|
|
1848
|
+
const agentId = BigInt(this.config.agentId);
|
|
1849
|
+
const llmMeta = this.llm.getMetadata();
|
|
1850
|
+
this.configHash = ExagentRegistry.calculateConfigHash(llmMeta.provider, llmMeta.model);
|
|
1851
|
+
console.log(`Config hash: ${this.configHash}`);
|
|
1852
|
+
const onChainHash = await this.client.registry.getConfigHash(agentId);
|
|
1853
|
+
if (onChainHash !== this.configHash) {
|
|
1854
|
+
console.log("Config changed, updating on-chain...");
|
|
1855
|
+
try {
|
|
1856
|
+
await this.client.registry.updateConfig(agentId, this.configHash);
|
|
1857
|
+
const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
|
|
1858
|
+
console.log(`Config updated, new epoch started: ${newEpoch}`);
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1861
|
+
if (message.includes("insufficient funds") || message.includes("gas") || message.includes("intrinsic gas too low") || message.includes("exceeds the balance")) {
|
|
1862
|
+
const ccUrl = `https://exagent.io/agents/${encodeURIComponent(this.config.name)}/command-center`;
|
|
1863
|
+
const chain = this.config.network === "mainnet" ? base2 : baseSepolia2;
|
|
1864
|
+
const publicClientInstance = createPublicClient3({
|
|
1865
|
+
chain,
|
|
1866
|
+
transport: http3(this.getRpcUrl())
|
|
1867
|
+
});
|
|
1868
|
+
console.log("");
|
|
1869
|
+
console.log("=== ETH NEEDED FOR GAS ===");
|
|
1870
|
+
console.log("");
|
|
1871
|
+
console.log(` Wallet: ${this.client.address}`);
|
|
1872
|
+
console.log(" Your wallet needs ETH to pay for transaction gas.");
|
|
1873
|
+
console.log(" Opening the command center to fund your wallet...");
|
|
1874
|
+
console.log(` ${ccUrl}`);
|
|
1875
|
+
console.log("");
|
|
1876
|
+
openBrowser(ccUrl);
|
|
1877
|
+
console.log(" Waiting for ETH... (checking every 15s)");
|
|
1878
|
+
console.log(" Press Ctrl+C to exit.");
|
|
1879
|
+
console.log("");
|
|
1880
|
+
while (true) {
|
|
1881
|
+
await this.sleep(15e3);
|
|
1882
|
+
const balance = await publicClientInstance.getBalance({
|
|
1883
|
+
address: this.client.address
|
|
1884
|
+
});
|
|
1885
|
+
if (balance > BigInt(0)) {
|
|
1886
|
+
console.log(" ETH detected! Retrying config update...");
|
|
1887
|
+
console.log("");
|
|
1888
|
+
await this.client.registry.updateConfig(agentId, this.configHash);
|
|
1889
|
+
const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
|
|
1890
|
+
console.log(`Config updated, new epoch started: ${newEpoch}`);
|
|
1891
|
+
return;
|
|
1892
|
+
}
|
|
1893
|
+
process.stdout.write(".");
|
|
1894
|
+
}
|
|
1895
|
+
} else {
|
|
1896
|
+
throw error;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
} else {
|
|
1900
|
+
const currentEpoch = await this.client.registry.getCurrentEpoch(agentId);
|
|
1901
|
+
console.log(`Config hash matches on-chain (epoch ${currentEpoch})`);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Get the current config hash (for trade execution)
|
|
1906
|
+
*/
|
|
1907
|
+
getConfigHash() {
|
|
1908
|
+
return this.configHash;
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Start the agent in daemon mode.
|
|
1912
|
+
* The agent enters idle mode and waits for commands from the command center.
|
|
1913
|
+
* Trading begins only when a start_trading command is received.
|
|
1914
|
+
*
|
|
1915
|
+
* If relay is not configured, falls back to immediate trading mode.
|
|
1916
|
+
*/
|
|
1917
|
+
async run() {
|
|
1918
|
+
this.processAlive = true;
|
|
1919
|
+
if (this.relay) {
|
|
1920
|
+
console.log("");
|
|
1921
|
+
console.log("Agent is in IDLE mode. Waiting for commands from command center.");
|
|
1922
|
+
console.log("Visit https://exagent.io to start trading from the dashboard.");
|
|
1923
|
+
console.log("");
|
|
1924
|
+
this.mode = "idle";
|
|
1925
|
+
this.sendRelayStatus();
|
|
1926
|
+
this.relay.sendMessage(
|
|
1927
|
+
"system",
|
|
1928
|
+
"success",
|
|
1929
|
+
"Agent Connected",
|
|
1930
|
+
`${this.config.name} is online and waiting for commands.`,
|
|
1931
|
+
{ wallet: this.client.address }
|
|
1932
|
+
);
|
|
1933
|
+
while (this.processAlive) {
|
|
1934
|
+
if (this.mode === "trading" && this.isRunning) {
|
|
1935
|
+
try {
|
|
1936
|
+
await this.runCycle();
|
|
1937
|
+
} catch (error) {
|
|
1938
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1939
|
+
console.error("Error in trading cycle:", message);
|
|
1940
|
+
this.relay?.sendMessage(
|
|
1941
|
+
"system",
|
|
1942
|
+
"error",
|
|
1943
|
+
"Cycle Error",
|
|
1944
|
+
message
|
|
1945
|
+
);
|
|
1946
|
+
}
|
|
1947
|
+
await this.sleep(this.config.trading.tradingIntervalMs);
|
|
1948
|
+
} else {
|
|
1949
|
+
this.sendRelayStatus();
|
|
1950
|
+
await this.sleep(3e4);
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
} else {
|
|
1954
|
+
if (this.isRunning) {
|
|
1955
|
+
throw new Error("Agent is already running");
|
|
1956
|
+
}
|
|
1957
|
+
this.isRunning = true;
|
|
1958
|
+
this.mode = "trading";
|
|
1959
|
+
console.log("Starting trading loop...");
|
|
1960
|
+
console.log(`Interval: ${this.config.trading.tradingIntervalMs}ms`);
|
|
1961
|
+
while (this.isRunning) {
|
|
1962
|
+
try {
|
|
1963
|
+
await this.runCycle();
|
|
1964
|
+
} catch (error) {
|
|
1965
|
+
console.error("Error in trading cycle:", error);
|
|
1966
|
+
}
|
|
1967
|
+
await this.sleep(this.config.trading.tradingIntervalMs);
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
/**
|
|
1972
|
+
* Handle a command from the command center
|
|
1973
|
+
*/
|
|
1974
|
+
async handleCommand(cmd) {
|
|
1975
|
+
console.log(`Command received: ${cmd.type}`);
|
|
1976
|
+
try {
|
|
1977
|
+
switch (cmd.type) {
|
|
1978
|
+
case "start_trading":
|
|
1979
|
+
if (this.mode === "trading") {
|
|
1980
|
+
this.relay?.sendCommandResult(cmd.id, true, "Already trading");
|
|
1981
|
+
return;
|
|
1982
|
+
}
|
|
1983
|
+
this.mode = "trading";
|
|
1984
|
+
this.isRunning = true;
|
|
1985
|
+
console.log("Trading started via command center");
|
|
1986
|
+
this.relay?.sendCommandResult(cmd.id, true, "Trading started");
|
|
1987
|
+
this.relay?.sendMessage(
|
|
1988
|
+
"system",
|
|
1989
|
+
"success",
|
|
1990
|
+
"Trading Started",
|
|
1991
|
+
"Agent is now actively trading."
|
|
1992
|
+
);
|
|
1993
|
+
this.sendRelayStatus();
|
|
1994
|
+
break;
|
|
1995
|
+
case "stop_trading":
|
|
1996
|
+
if (this.mode === "idle") {
|
|
1997
|
+
this.relay?.sendCommandResult(cmd.id, true, "Already idle");
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
this.mode = "idle";
|
|
2001
|
+
this.isRunning = false;
|
|
2002
|
+
console.log("Trading stopped via command center");
|
|
2003
|
+
this.relay?.sendCommandResult(cmd.id, true, "Trading stopped");
|
|
2004
|
+
this.relay?.sendMessage(
|
|
2005
|
+
"system",
|
|
2006
|
+
"info",
|
|
2007
|
+
"Trading Stopped",
|
|
2008
|
+
"Agent is now idle. Send start_trading to resume."
|
|
2009
|
+
);
|
|
2010
|
+
this.sendRelayStatus();
|
|
2011
|
+
break;
|
|
2012
|
+
case "update_risk_params": {
|
|
2013
|
+
const params = cmd.params || {};
|
|
2014
|
+
if (params.maxPositionSizeBps !== void 0) {
|
|
2015
|
+
this.config.trading.maxPositionSizeBps = Number(params.maxPositionSizeBps);
|
|
2016
|
+
}
|
|
2017
|
+
if (params.maxDailyLossBps !== void 0) {
|
|
2018
|
+
this.config.trading.maxDailyLossBps = Number(params.maxDailyLossBps);
|
|
2019
|
+
}
|
|
2020
|
+
this.riskManager = new RiskManager(this.config.trading);
|
|
2021
|
+
console.log("Risk params updated via command center");
|
|
2022
|
+
this.relay?.sendCommandResult(cmd.id, true, "Risk params updated");
|
|
2023
|
+
this.relay?.sendMessage(
|
|
2024
|
+
"config_updated",
|
|
2025
|
+
"info",
|
|
2026
|
+
"Risk Parameters Updated",
|
|
2027
|
+
`Max position: ${this.config.trading.maxPositionSizeBps / 100}%, Max daily loss: ${this.config.trading.maxDailyLossBps / 100}%`
|
|
2028
|
+
);
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
case "update_trading_interval": {
|
|
2032
|
+
const intervalMs = Number(cmd.params?.intervalMs);
|
|
2033
|
+
if (intervalMs && intervalMs >= 1e3) {
|
|
2034
|
+
this.config.trading.tradingIntervalMs = intervalMs;
|
|
2035
|
+
console.log(`Trading interval updated to ${intervalMs}ms`);
|
|
2036
|
+
this.relay?.sendCommandResult(cmd.id, true, `Interval set to ${intervalMs}ms`);
|
|
2037
|
+
} else {
|
|
2038
|
+
this.relay?.sendCommandResult(cmd.id, false, "Invalid interval (minimum 1000ms)");
|
|
2039
|
+
}
|
|
2040
|
+
break;
|
|
2041
|
+
}
|
|
2042
|
+
case "create_vault": {
|
|
2043
|
+
const result = await this.createVault();
|
|
2044
|
+
this.relay?.sendCommandResult(
|
|
2045
|
+
cmd.id,
|
|
2046
|
+
result.success,
|
|
2047
|
+
result.success ? `Vault created: ${result.vaultAddress}` : result.error
|
|
2048
|
+
);
|
|
2049
|
+
if (result.success) {
|
|
2050
|
+
this.relay?.sendMessage(
|
|
2051
|
+
"vault_created",
|
|
2052
|
+
"success",
|
|
2053
|
+
"Vault Created",
|
|
2054
|
+
`Vault deployed at ${result.vaultAddress}`,
|
|
2055
|
+
{ vaultAddress: result.vaultAddress }
|
|
2056
|
+
);
|
|
2057
|
+
}
|
|
2058
|
+
break;
|
|
2059
|
+
}
|
|
2060
|
+
case "refresh_status":
|
|
2061
|
+
this.sendRelayStatus();
|
|
2062
|
+
this.relay?.sendCommandResult(cmd.id, true, "Status refreshed");
|
|
2063
|
+
break;
|
|
2064
|
+
case "shutdown":
|
|
2065
|
+
console.log("Shutdown requested via command center");
|
|
2066
|
+
this.relay?.sendCommandResult(cmd.id, true, "Shutting down");
|
|
2067
|
+
this.relay?.sendMessage(
|
|
2068
|
+
"system",
|
|
2069
|
+
"info",
|
|
2070
|
+
"Shutting Down",
|
|
2071
|
+
"Agent is shutting down. Restart manually to reconnect."
|
|
2072
|
+
);
|
|
2073
|
+
await this.sleep(1e3);
|
|
2074
|
+
this.stop();
|
|
2075
|
+
break;
|
|
2076
|
+
default:
|
|
2077
|
+
console.warn(`Unknown command: ${cmd.type}`);
|
|
2078
|
+
this.relay?.sendCommandResult(cmd.id, false, `Unknown command: ${cmd.type}`);
|
|
2079
|
+
}
|
|
2080
|
+
} catch (error) {
|
|
2081
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2082
|
+
console.error(`Command ${cmd.type} failed:`, message);
|
|
2083
|
+
this.relay?.sendCommandResult(cmd.id, false, message);
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Send current status to the relay
|
|
2088
|
+
*/
|
|
2089
|
+
sendRelayStatus() {
|
|
2090
|
+
if (!this.relay) return;
|
|
2091
|
+
const vaultConfig = this.config.vault || { policy: "disabled" };
|
|
2092
|
+
const status = {
|
|
2093
|
+
mode: this.mode,
|
|
2094
|
+
agentId: String(this.config.agentId),
|
|
2095
|
+
wallet: this.client?.address,
|
|
2096
|
+
cycleCount: this.cycleCount,
|
|
2097
|
+
lastCycleAt: this.lastCycleAt,
|
|
2098
|
+
tradingIntervalMs: this.config.trading.tradingIntervalMs,
|
|
2099
|
+
portfolioValue: this.lastPortfolioValue,
|
|
2100
|
+
ethBalance: this.lastEthBalance,
|
|
2101
|
+
llm: {
|
|
2102
|
+
provider: this.config.llm.provider,
|
|
2103
|
+
model: this.config.llm.model || "default"
|
|
2104
|
+
},
|
|
2105
|
+
risk: this.riskManager?.getStatus() || {
|
|
2106
|
+
dailyPnL: 0,
|
|
2107
|
+
dailyLossLimit: 0,
|
|
2108
|
+
isLimitHit: false
|
|
2109
|
+
},
|
|
2110
|
+
vault: {
|
|
2111
|
+
policy: vaultConfig.policy,
|
|
2112
|
+
hasVault: false,
|
|
2113
|
+
vaultAddress: null
|
|
2114
|
+
}
|
|
2115
|
+
};
|
|
2116
|
+
this.relay.sendHeartbeat(status);
|
|
2117
|
+
}
|
|
2118
|
+
/**
|
|
2119
|
+
* Run a single trading cycle
|
|
2120
|
+
*/
|
|
2121
|
+
async runCycle() {
|
|
2122
|
+
console.log(`
|
|
2123
|
+
--- Trading Cycle: ${(/* @__PURE__ */ new Date()).toISOString()} ---`);
|
|
2124
|
+
this.cycleCount++;
|
|
2125
|
+
this.lastCycleAt = Date.now();
|
|
2126
|
+
await this.checkVaultAutoCreation();
|
|
2127
|
+
const tokens = this.config.allowedTokens || this.getDefaultTokens();
|
|
2128
|
+
const marketData = await this.marketData.fetchMarketData(this.client.address, tokens);
|
|
2129
|
+
console.log(`Portfolio value: $${marketData.portfolioValue.toFixed(2)}`);
|
|
2130
|
+
this.lastPortfolioValue = marketData.portfolioValue;
|
|
2131
|
+
const nativeEthBal = marketData.balances[NATIVE_ETH.toLowerCase()] || BigInt(0);
|
|
2132
|
+
this.lastEthBalance = (Number(nativeEthBal) / 1e18).toFixed(6);
|
|
2133
|
+
this.checkFundsLow(marketData);
|
|
2134
|
+
let signals;
|
|
2135
|
+
try {
|
|
2136
|
+
signals = await this.strategy(marketData, this.llm, this.config);
|
|
2137
|
+
} catch (error) {
|
|
2138
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2139
|
+
console.error("LLM/strategy error:", message);
|
|
2140
|
+
this.relay?.sendMessage(
|
|
2141
|
+
"llm_error",
|
|
2142
|
+
"error",
|
|
2143
|
+
"Strategy Error",
|
|
2144
|
+
message
|
|
2145
|
+
);
|
|
2146
|
+
return;
|
|
2147
|
+
}
|
|
2148
|
+
console.log(`Strategy generated ${signals.length} signals`);
|
|
2149
|
+
const filteredSignals = this.riskManager.filterSignals(signals, marketData);
|
|
2150
|
+
console.log(`${filteredSignals.length} signals passed risk checks`);
|
|
2151
|
+
if (this.riskManager.getStatus().isLimitHit) {
|
|
2152
|
+
this.relay?.sendMessage(
|
|
2153
|
+
"risk_limit_hit",
|
|
2154
|
+
"warning",
|
|
2155
|
+
"Risk Limit Hit",
|
|
2156
|
+
`Daily loss limit reached: ${this.riskManager.getStatus().dailyPnL.toFixed(2)}`
|
|
2157
|
+
);
|
|
2158
|
+
}
|
|
2159
|
+
if (filteredSignals.length > 0) {
|
|
2160
|
+
const results = await this.executor.executeAll(filteredSignals);
|
|
2161
|
+
for (const result of results) {
|
|
2162
|
+
if (result.success) {
|
|
2163
|
+
console.log(`Trade executed: ${result.signal.action} - ${result.txHash}`);
|
|
2164
|
+
this.relay?.sendMessage(
|
|
2165
|
+
"trade_executed",
|
|
2166
|
+
"success",
|
|
2167
|
+
"Trade Executed",
|
|
2168
|
+
`${result.signal.action.toUpperCase()}: ${result.signal.reasoning || "No reason provided"}`,
|
|
2169
|
+
{
|
|
2170
|
+
action: result.signal.action,
|
|
2171
|
+
txHash: result.txHash,
|
|
2172
|
+
tokenIn: result.signal.tokenIn,
|
|
2173
|
+
tokenOut: result.signal.tokenOut
|
|
2174
|
+
}
|
|
2175
|
+
);
|
|
2176
|
+
} else {
|
|
2177
|
+
console.warn(`Trade failed: ${result.error}`);
|
|
2178
|
+
this.relay?.sendMessage(
|
|
2179
|
+
"trade_failed",
|
|
2180
|
+
"error",
|
|
2181
|
+
"Trade Failed",
|
|
2182
|
+
result.error || "Unknown error",
|
|
2183
|
+
{ action: result.signal.action }
|
|
2184
|
+
);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
this.sendRelayStatus();
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* Check if ETH balance is below threshold and notify
|
|
2192
|
+
*/
|
|
2193
|
+
checkFundsLow(marketData) {
|
|
2194
|
+
if (!this.relay) return;
|
|
2195
|
+
const ethBalance = marketData.balances[NATIVE_ETH.toLowerCase()] || BigInt(0);
|
|
2196
|
+
const ethAmount = Number(ethBalance) / 1e18;
|
|
2197
|
+
if (ethAmount < FUNDS_LOW_THRESHOLD) {
|
|
2198
|
+
this.relay.sendMessage(
|
|
2199
|
+
"funds_low",
|
|
2200
|
+
"warning",
|
|
2201
|
+
"Low Funds",
|
|
2202
|
+
`ETH balance is ${ethAmount.toFixed(6)} ETH. Fund your trading wallet to continue trading.`,
|
|
2203
|
+
{
|
|
2204
|
+
ethBalance: ethAmount.toFixed(6),
|
|
2205
|
+
wallet: this.client.address,
|
|
2206
|
+
threshold: FUNDS_LOW_THRESHOLD
|
|
2207
|
+
}
|
|
2208
|
+
);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
/**
|
|
2212
|
+
* Check for vault auto-creation based on policy
|
|
2213
|
+
*/
|
|
2214
|
+
async checkVaultAutoCreation() {
|
|
2215
|
+
const now = Date.now();
|
|
2216
|
+
if (now - this.lastVaultCheck < this.VAULT_CHECK_INTERVAL) {
|
|
2217
|
+
return;
|
|
2218
|
+
}
|
|
2219
|
+
this.lastVaultCheck = now;
|
|
2220
|
+
const result = await this.vaultManager.checkAndAutoCreateVault();
|
|
2221
|
+
switch (result.action) {
|
|
2222
|
+
case "created":
|
|
2223
|
+
console.log(`Vault created automatically: ${result.vaultAddress}`);
|
|
2224
|
+
this.relay?.sendMessage(
|
|
2225
|
+
"vault_created",
|
|
2226
|
+
"success",
|
|
2227
|
+
"Vault Auto-Created",
|
|
2228
|
+
`Vault deployed at ${result.vaultAddress}`,
|
|
2229
|
+
{ vaultAddress: result.vaultAddress }
|
|
2230
|
+
);
|
|
2231
|
+
break;
|
|
2232
|
+
case "already_exists":
|
|
2233
|
+
break;
|
|
2234
|
+
case "skipped":
|
|
2235
|
+
break;
|
|
2236
|
+
case "not_qualified":
|
|
2237
|
+
console.log(`Vault auto-creation pending: ${result.reason}`);
|
|
2238
|
+
break;
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
/**
|
|
2242
|
+
* Stop the agent process completely
|
|
2243
|
+
*/
|
|
2244
|
+
stop() {
|
|
2245
|
+
console.log("Stopping agent...");
|
|
2246
|
+
this.isRunning = false;
|
|
2247
|
+
this.processAlive = false;
|
|
2248
|
+
this.mode = "idle";
|
|
2249
|
+
if (this.relay) {
|
|
2250
|
+
this.relay.disconnect();
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
/**
|
|
2254
|
+
* Get RPC URL based on network
|
|
2255
|
+
*/
|
|
2256
|
+
getRpcUrl() {
|
|
2257
|
+
if (this.config.network === "mainnet") {
|
|
2258
|
+
return "https://mainnet.base.org";
|
|
2259
|
+
}
|
|
2260
|
+
return "https://sepolia.base.org";
|
|
2261
|
+
}
|
|
2262
|
+
/**
|
|
2263
|
+
* Default tokens to track
|
|
2264
|
+
*/
|
|
2265
|
+
getDefaultTokens() {
|
|
2266
|
+
if (this.config.network === "mainnet") {
|
|
2267
|
+
return [
|
|
2268
|
+
"0x4200000000000000000000000000000000000006",
|
|
2269
|
+
// WETH
|
|
2270
|
+
"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
2271
|
+
// USDC
|
|
2272
|
+
];
|
|
2273
|
+
}
|
|
2274
|
+
return [
|
|
2275
|
+
"0x4200000000000000000000000000000000000006"
|
|
2276
|
+
// WETH
|
|
2277
|
+
];
|
|
2278
|
+
}
|
|
2279
|
+
sleep(ms) {
|
|
2280
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2281
|
+
}
|
|
2282
|
+
/**
|
|
2283
|
+
* Get current status
|
|
2284
|
+
*/
|
|
2285
|
+
getStatus() {
|
|
2286
|
+
const vaultConfig = this.config.vault || { policy: "disabled" };
|
|
2287
|
+
return {
|
|
2288
|
+
isRunning: this.isRunning,
|
|
2289
|
+
mode: this.mode,
|
|
2290
|
+
agentId: Number(this.config.agentId),
|
|
2291
|
+
wallet: this.client?.address || "not initialized",
|
|
2292
|
+
llm: {
|
|
2293
|
+
provider: this.config.llm.provider,
|
|
2294
|
+
model: this.config.llm.model || "default"
|
|
2295
|
+
},
|
|
2296
|
+
configHash: this.configHash || "not initialized",
|
|
2297
|
+
risk: this.riskManager?.getStatus() || { dailyPnL: 0, dailyLossLimit: 0, isLimitHit: false },
|
|
2298
|
+
vault: {
|
|
2299
|
+
policy: vaultConfig.policy,
|
|
2300
|
+
hasVault: false,
|
|
2301
|
+
// Updated async via getVaultStatus
|
|
2302
|
+
vaultAddress: null
|
|
2303
|
+
},
|
|
2304
|
+
relay: {
|
|
2305
|
+
connected: this.relay?.isConnected || false
|
|
2306
|
+
},
|
|
2307
|
+
cycleCount: this.cycleCount
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
/**
|
|
2311
|
+
* Get detailed vault status (async)
|
|
2312
|
+
*/
|
|
2313
|
+
async getVaultStatus() {
|
|
2314
|
+
if (!this.vaultManager) {
|
|
2315
|
+
return null;
|
|
2316
|
+
}
|
|
2317
|
+
return this.vaultManager.getVaultStatus();
|
|
2318
|
+
}
|
|
2319
|
+
/**
|
|
2320
|
+
* Manually trigger vault creation (for 'manual' policy)
|
|
2321
|
+
*/
|
|
2322
|
+
async createVault() {
|
|
2323
|
+
if (!this.vaultManager) {
|
|
2324
|
+
return { success: false, error: "Vault manager not initialized" };
|
|
2325
|
+
}
|
|
2326
|
+
const policy = this.config.vault?.policy || "disabled";
|
|
2327
|
+
if (policy === "disabled") {
|
|
2328
|
+
return { success: false, error: "Vault creation is disabled by policy" };
|
|
2329
|
+
}
|
|
2330
|
+
return this.vaultManager.createVault();
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
|
|
2334
|
+
// src/types.ts
|
|
2335
|
+
import { z } from "zod";
|
|
2336
|
+
var WalletSetupSchema = z.enum(["generate", "provide"]);
|
|
2337
|
+
var LLMProviderSchema = z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama", "custom"]);
|
|
2338
|
+
var LLMConfigSchema = z.object({
|
|
2339
|
+
provider: LLMProviderSchema,
|
|
2340
|
+
model: z.string().optional(),
|
|
2341
|
+
apiKey: z.string().optional(),
|
|
2342
|
+
endpoint: z.string().url().optional(),
|
|
2343
|
+
temperature: z.number().min(0).max(2).default(0.7),
|
|
2344
|
+
maxTokens: z.number().positive().default(4096)
|
|
2345
|
+
});
|
|
2346
|
+
var RiskUniverseSchema = z.enum(["core", "established", "derivatives", "emerging", "frontier"]);
|
|
2347
|
+
var TradingConfigSchema = z.object({
|
|
2348
|
+
timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
|
|
2349
|
+
maxPositionSizeBps: z.number().min(100).max(1e4).default(1e3),
|
|
2350
|
+
// 1-100%
|
|
2351
|
+
maxDailyLossBps: z.number().min(0).max(1e4).default(500),
|
|
2352
|
+
// 0-100%
|
|
2353
|
+
maxConcurrentPositions: z.number().min(1).max(100).default(5),
|
|
2354
|
+
tradingIntervalMs: z.number().min(1e3).default(6e4)
|
|
2355
|
+
// minimum 1 second
|
|
2356
|
+
});
|
|
2357
|
+
var VaultPolicySchema = z.enum([
|
|
2358
|
+
"disabled",
|
|
2359
|
+
// Never create a vault - trade with agent's own capital only
|
|
2360
|
+
"manual",
|
|
2361
|
+
// Only create vault when explicitly directed by owner
|
|
2362
|
+
"auto_when_qualified"
|
|
2363
|
+
// Automatically create vault when requirements are met
|
|
2364
|
+
]);
|
|
2365
|
+
var VaultConfigSchema = z.object({
|
|
2366
|
+
// Policy for vault creation (asked during deployment)
|
|
2367
|
+
policy: VaultPolicySchema.default("manual"),
|
|
2368
|
+
// Default vault name (auto-generated from agent name if not set)
|
|
2369
|
+
defaultName: z.string().optional(),
|
|
2370
|
+
// Default vault symbol (auto-generated if not set)
|
|
2371
|
+
defaultSymbol: z.string().optional(),
|
|
2372
|
+
// Fee recipient for vault fees (default: agent wallet)
|
|
2373
|
+
feeRecipient: z.string().optional(),
|
|
2374
|
+
// When vault exists, trade through vault instead of direct trading
|
|
2375
|
+
// This pools depositors' capital with the agent's trades
|
|
2376
|
+
preferVaultTrading: z.boolean().default(true)
|
|
2377
|
+
});
|
|
2378
|
+
var WalletConfigSchema = z.object({
|
|
2379
|
+
setup: WalletSetupSchema.default("provide")
|
|
2380
|
+
}).optional();
|
|
2381
|
+
var RelayConfigSchema = z.object({
|
|
2382
|
+
enabled: z.boolean().default(false),
|
|
2383
|
+
apiUrl: z.string().url(),
|
|
2384
|
+
heartbeatIntervalMs: z.number().min(5e3).default(3e4)
|
|
2385
|
+
}).optional();
|
|
2386
|
+
var AgentConfigSchema = z.object({
|
|
2387
|
+
// Identity (from on-chain registration)
|
|
2388
|
+
agentId: z.union([z.number().positive(), z.string()]),
|
|
2389
|
+
name: z.string().min(3).max(32),
|
|
2390
|
+
// Network
|
|
2391
|
+
network: z.enum(["mainnet", "testnet"]).default("testnet"),
|
|
2392
|
+
// Wallet setup preference
|
|
2393
|
+
wallet: WalletConfigSchema,
|
|
2394
|
+
// LLM
|
|
2395
|
+
llm: LLMConfigSchema,
|
|
2396
|
+
// Trading parameters
|
|
2397
|
+
riskUniverse: RiskUniverseSchema.default("established"),
|
|
2398
|
+
trading: TradingConfigSchema.default({}),
|
|
2399
|
+
// Vault configuration (copy trading)
|
|
2400
|
+
vault: VaultConfigSchema.default({}),
|
|
2401
|
+
// Relay configuration (command center)
|
|
2402
|
+
relay: RelayConfigSchema,
|
|
2403
|
+
// Allowed tokens (addresses)
|
|
2404
|
+
allowedTokens: z.array(z.string()).optional()
|
|
2405
|
+
});
|
|
2406
|
+
|
|
2407
|
+
// src/config.ts
|
|
2408
|
+
import { readFileSync, existsSync as existsSync2 } from "fs";
|
|
2409
|
+
import { join as join2 } from "path";
|
|
2410
|
+
import { config as loadEnv } from "dotenv";
|
|
2411
|
+
function loadConfig(configPath) {
|
|
2412
|
+
loadEnv();
|
|
2413
|
+
const configFile = configPath || process.env.EXAGENT_CONFIG || "agent-config.json";
|
|
2414
|
+
const fullPath = configFile.startsWith("/") ? configFile : join2(process.cwd(), configFile);
|
|
2415
|
+
if (!existsSync2(fullPath)) {
|
|
2416
|
+
throw new Error(`Config file not found: ${fullPath}`);
|
|
2417
|
+
}
|
|
2418
|
+
const rawConfig = JSON.parse(readFileSync(fullPath, "utf-8"));
|
|
2419
|
+
const config = AgentConfigSchema.parse(rawConfig);
|
|
2420
|
+
const privateKey = process.env.EXAGENT_PRIVATE_KEY;
|
|
2421
|
+
if (privateKey && (!privateKey.startsWith("0x") || privateKey.length !== 66)) {
|
|
2422
|
+
throw new Error("EXAGENT_PRIVATE_KEY must be a valid 32-byte hex string starting with 0x");
|
|
2423
|
+
}
|
|
2424
|
+
const llmConfig = { ...config.llm };
|
|
2425
|
+
if (process.env.OPENAI_API_KEY && config.llm.provider === "openai") {
|
|
2426
|
+
llmConfig.apiKey = process.env.OPENAI_API_KEY;
|
|
2427
|
+
}
|
|
2428
|
+
if (process.env.ANTHROPIC_API_KEY && config.llm.provider === "anthropic") {
|
|
2429
|
+
llmConfig.apiKey = process.env.ANTHROPIC_API_KEY;
|
|
2430
|
+
}
|
|
2431
|
+
if (process.env.GOOGLE_AI_API_KEY && config.llm.provider === "google") {
|
|
2432
|
+
llmConfig.apiKey = process.env.GOOGLE_AI_API_KEY;
|
|
2433
|
+
}
|
|
2434
|
+
if (process.env.DEEPSEEK_API_KEY && config.llm.provider === "deepseek") {
|
|
2435
|
+
llmConfig.apiKey = process.env.DEEPSEEK_API_KEY;
|
|
2436
|
+
}
|
|
2437
|
+
if (process.env.MISTRAL_API_KEY && config.llm.provider === "mistral") {
|
|
2438
|
+
llmConfig.apiKey = process.env.MISTRAL_API_KEY;
|
|
2439
|
+
}
|
|
2440
|
+
if (process.env.GROQ_API_KEY && config.llm.provider === "groq") {
|
|
2441
|
+
llmConfig.apiKey = process.env.GROQ_API_KEY;
|
|
2442
|
+
}
|
|
2443
|
+
if (process.env.TOGETHER_API_KEY && config.llm.provider === "together") {
|
|
2444
|
+
llmConfig.apiKey = process.env.TOGETHER_API_KEY;
|
|
2445
|
+
}
|
|
2446
|
+
if (process.env.EXAGENT_LLM_URL) {
|
|
2447
|
+
llmConfig.endpoint = process.env.EXAGENT_LLM_URL;
|
|
2448
|
+
}
|
|
2449
|
+
if (process.env.EXAGENT_LLM_MODEL) {
|
|
2450
|
+
llmConfig.model = process.env.EXAGENT_LLM_MODEL;
|
|
2451
|
+
}
|
|
2452
|
+
const network = process.env.EXAGENT_NETWORK || config.network;
|
|
2453
|
+
return {
|
|
2454
|
+
...config,
|
|
2455
|
+
llm: llmConfig,
|
|
2456
|
+
network,
|
|
2457
|
+
privateKey: privateKey || ""
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
function validateConfig(config) {
|
|
2461
|
+
if (!config.privateKey) {
|
|
2462
|
+
throw new Error("Private key is required");
|
|
2463
|
+
}
|
|
2464
|
+
if (config.llm.provider !== "ollama" && !config.llm.apiKey) {
|
|
2465
|
+
throw new Error(`API key required for ${config.llm.provider} provider`);
|
|
2466
|
+
}
|
|
2467
|
+
if (config.llm.provider === "ollama" && !config.llm.endpoint) {
|
|
2468
|
+
config.llm.endpoint = "http://localhost:11434";
|
|
2469
|
+
}
|
|
2470
|
+
if (config.llm.provider === "custom" && !config.llm.endpoint) {
|
|
2471
|
+
throw new Error("Endpoint required for custom LLM provider");
|
|
2472
|
+
}
|
|
2473
|
+
if (!config.agentId || Number(config.agentId) <= 0) {
|
|
2474
|
+
throw new Error("Valid agent ID required");
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
function createSampleConfig(agentId, name) {
|
|
2478
|
+
return {
|
|
2479
|
+
agentId,
|
|
2480
|
+
name,
|
|
2481
|
+
network: "testnet",
|
|
2482
|
+
llm: {
|
|
2483
|
+
provider: "openai",
|
|
2484
|
+
model: "gpt-4.1",
|
|
2485
|
+
temperature: 0.7,
|
|
2486
|
+
maxTokens: 4096
|
|
2487
|
+
},
|
|
2488
|
+
riskUniverse: "established",
|
|
2489
|
+
trading: {
|
|
2490
|
+
timeHorizon: "swing",
|
|
2491
|
+
maxPositionSizeBps: 1e3,
|
|
2492
|
+
maxDailyLossBps: 500,
|
|
2493
|
+
maxConcurrentPositions: 5,
|
|
2494
|
+
tradingIntervalMs: 6e4
|
|
2495
|
+
},
|
|
2496
|
+
vault: {
|
|
2497
|
+
// Default to manual - user must explicitly enable auto-creation
|
|
2498
|
+
policy: "manual",
|
|
2499
|
+
// Will use agent name for vault name if not set
|
|
2500
|
+
preferVaultTrading: true
|
|
2501
|
+
}
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
// src/secure-env.ts
|
|
2506
|
+
import * as crypto from "crypto";
|
|
2507
|
+
import * as fs from "fs";
|
|
2508
|
+
import * as path from "path";
|
|
2509
|
+
var ALGORITHM = "aes-256-gcm";
|
|
2510
|
+
var PBKDF2_ITERATIONS = 1e5;
|
|
2511
|
+
var SALT_LENGTH = 32;
|
|
2512
|
+
var IV_LENGTH = 16;
|
|
2513
|
+
var KEY_LENGTH = 32;
|
|
2514
|
+
var SENSITIVE_PATTERNS = [
|
|
2515
|
+
/PRIVATE_KEY$/i,
|
|
2516
|
+
/_API_KEY$/i,
|
|
2517
|
+
/API_KEY$/i,
|
|
2518
|
+
/_SECRET$/i,
|
|
2519
|
+
/^OPENAI_API_KEY$/i,
|
|
2520
|
+
/^ANTHROPIC_API_KEY$/i,
|
|
2521
|
+
/^GOOGLE_AI_API_KEY$/i,
|
|
2522
|
+
/^DEEPSEEK_API_KEY$/i,
|
|
2523
|
+
/^MISTRAL_API_KEY$/i,
|
|
2524
|
+
/^GROQ_API_KEY$/i,
|
|
2525
|
+
/^TOGETHER_API_KEY$/i
|
|
2526
|
+
];
|
|
2527
|
+
function isSensitiveKey(key) {
|
|
2528
|
+
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(key));
|
|
2529
|
+
}
|
|
2530
|
+
function deriveKey(passphrase, salt) {
|
|
2531
|
+
return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
|
|
2532
|
+
}
|
|
2533
|
+
function encryptValue(value, key) {
|
|
2534
|
+
const iv = crypto.randomBytes(IV_LENGTH);
|
|
2535
|
+
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
|
2536
|
+
let encrypted = cipher.update(value, "utf8", "hex");
|
|
2537
|
+
encrypted += cipher.final("hex");
|
|
2538
|
+
const tag = cipher.getAuthTag();
|
|
2539
|
+
return {
|
|
2540
|
+
iv: iv.toString("hex"),
|
|
2541
|
+
encrypted,
|
|
2542
|
+
tag: tag.toString("hex")
|
|
2543
|
+
};
|
|
2544
|
+
}
|
|
2545
|
+
function decryptValue(encrypted, key, iv, tag) {
|
|
2546
|
+
const decipher = crypto.createDecipheriv(
|
|
2547
|
+
ALGORITHM,
|
|
2548
|
+
key,
|
|
2549
|
+
Buffer.from(iv, "hex")
|
|
2550
|
+
);
|
|
2551
|
+
decipher.setAuthTag(Buffer.from(tag, "hex"));
|
|
2552
|
+
let decrypted = decipher.update(encrypted, "hex", "utf8");
|
|
2553
|
+
decrypted += decipher.final("utf8");
|
|
2554
|
+
return decrypted;
|
|
2555
|
+
}
|
|
2556
|
+
function parseEnvFile(content) {
|
|
2557
|
+
const entries = [];
|
|
2558
|
+
for (const line of content.split("\n")) {
|
|
2559
|
+
const trimmed = line.trim();
|
|
2560
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2561
|
+
const eqIndex = trimmed.indexOf("=");
|
|
2562
|
+
if (eqIndex === -1) continue;
|
|
2563
|
+
const key = trimmed.slice(0, eqIndex).trim();
|
|
2564
|
+
let value = trimmed.slice(eqIndex + 1).trim();
|
|
2565
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
2566
|
+
value = value.slice(1, -1);
|
|
2567
|
+
}
|
|
2568
|
+
if (key && value) {
|
|
2569
|
+
entries.push({ key, value });
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
return entries;
|
|
2573
|
+
}
|
|
2574
|
+
function encryptEnvFile(envPath, passphrase, deleteOriginal = false) {
|
|
2575
|
+
if (!fs.existsSync(envPath)) {
|
|
2576
|
+
throw new Error(`File not found: ${envPath}`);
|
|
2577
|
+
}
|
|
2578
|
+
const content = fs.readFileSync(envPath, "utf-8");
|
|
2579
|
+
const entries = parseEnvFile(content);
|
|
2580
|
+
if (entries.length === 0) {
|
|
2581
|
+
throw new Error("No environment variables found in file");
|
|
2582
|
+
}
|
|
2583
|
+
const salt = crypto.randomBytes(SALT_LENGTH);
|
|
2584
|
+
const key = deriveKey(passphrase, salt);
|
|
2585
|
+
const encryptedEntries = entries.map(({ key: envKey, value }) => {
|
|
2586
|
+
if (isSensitiveKey(envKey)) {
|
|
2587
|
+
const { iv, encrypted, tag } = encryptValue(value, key);
|
|
2588
|
+
return {
|
|
2589
|
+
key: envKey,
|
|
2590
|
+
value: encrypted,
|
|
2591
|
+
encrypted: true,
|
|
2592
|
+
iv,
|
|
2593
|
+
tag
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
return {
|
|
2597
|
+
key: envKey,
|
|
2598
|
+
value,
|
|
2599
|
+
encrypted: false
|
|
2600
|
+
};
|
|
2601
|
+
});
|
|
2602
|
+
const encryptedEnv = {
|
|
2603
|
+
version: 1,
|
|
2604
|
+
salt: salt.toString("hex"),
|
|
2605
|
+
entries: encryptedEntries
|
|
2606
|
+
};
|
|
2607
|
+
const encPath = envPath + ".enc";
|
|
2608
|
+
fs.writeFileSync(encPath, JSON.stringify(encryptedEnv, null, 2), { mode: 384 });
|
|
2609
|
+
if (deleteOriginal) {
|
|
2610
|
+
fs.unlinkSync(envPath);
|
|
2611
|
+
}
|
|
2612
|
+
const sensitiveCount = encryptedEntries.filter((e) => e.encrypted).length;
|
|
2613
|
+
const plainCount = encryptedEntries.filter((e) => !e.encrypted).length;
|
|
2614
|
+
console.log(
|
|
2615
|
+
`Encrypted ${sensitiveCount} sensitive values (${plainCount} non-sensitive kept as plaintext)`
|
|
2616
|
+
);
|
|
2617
|
+
return encPath;
|
|
2618
|
+
}
|
|
2619
|
+
function decryptEnvFile(encPath, passphrase) {
|
|
2620
|
+
if (!fs.existsSync(encPath)) {
|
|
2621
|
+
throw new Error(`Encrypted env file not found: ${encPath}`);
|
|
2622
|
+
}
|
|
2623
|
+
const content = JSON.parse(fs.readFileSync(encPath, "utf-8"));
|
|
2624
|
+
if (content.version !== 1) {
|
|
2625
|
+
throw new Error(`Unsupported encrypted env version: ${content.version}`);
|
|
2626
|
+
}
|
|
2627
|
+
const salt = Buffer.from(content.salt, "hex");
|
|
2628
|
+
const key = deriveKey(passphrase, salt);
|
|
2629
|
+
const result = {};
|
|
2630
|
+
for (const entry of content.entries) {
|
|
2631
|
+
if (entry.encrypted) {
|
|
2632
|
+
if (!entry.iv || !entry.tag) {
|
|
2633
|
+
throw new Error(`Missing encryption metadata for ${entry.key}`);
|
|
2634
|
+
}
|
|
2635
|
+
try {
|
|
2636
|
+
result[entry.key] = decryptValue(entry.value, key, entry.iv, entry.tag);
|
|
2637
|
+
} catch {
|
|
2638
|
+
throw new Error(
|
|
2639
|
+
`Failed to decrypt ${entry.key}. Wrong passphrase or corrupted data.`
|
|
2640
|
+
);
|
|
2641
|
+
}
|
|
2642
|
+
} else {
|
|
2643
|
+
result[entry.key] = entry.value;
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
return result;
|
|
2647
|
+
}
|
|
2648
|
+
function loadSecureEnv(basePath, passphrase) {
|
|
2649
|
+
const encPath = path.join(basePath, ".env.enc");
|
|
2650
|
+
const envPath = path.join(basePath, ".env");
|
|
2651
|
+
if (fs.existsSync(encPath)) {
|
|
2652
|
+
if (!passphrase) {
|
|
2653
|
+
passphrase = process.env.EXAGENT_PASSPHRASE;
|
|
2654
|
+
}
|
|
2655
|
+
if (!passphrase) {
|
|
2656
|
+
console.warn("");
|
|
2657
|
+
console.warn("WARNING: Found .env.enc but no passphrase provided.");
|
|
2658
|
+
console.warn(" Set EXAGENT_PASSPHRASE environment variable or");
|
|
2659
|
+
console.warn(" pass --passphrase when running the agent.");
|
|
2660
|
+
console.warn(" Falling back to plaintext .env file.");
|
|
2661
|
+
console.warn("");
|
|
2662
|
+
} else {
|
|
2663
|
+
const vars = decryptEnvFile(encPath, passphrase);
|
|
2664
|
+
for (const [key, value] of Object.entries(vars)) {
|
|
2665
|
+
process.env[key] = value;
|
|
2666
|
+
}
|
|
2667
|
+
return true;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
if (fs.existsSync(envPath)) {
|
|
2671
|
+
const content = fs.readFileSync(envPath, "utf-8");
|
|
2672
|
+
const entries = parseEnvFile(content);
|
|
2673
|
+
const sensitiveKeys = entries.filter(({ key }) => isSensitiveKey(key)).map(({ key }) => key);
|
|
2674
|
+
if (sensitiveKeys.length > 0) {
|
|
2675
|
+
console.warn("");
|
|
2676
|
+
console.warn("WARNING: Sensitive values stored in plaintext .env file:");
|
|
2677
|
+
for (const key of sensitiveKeys) {
|
|
2678
|
+
console.warn(` - ${key}`);
|
|
2679
|
+
}
|
|
2680
|
+
console.warn("");
|
|
2681
|
+
console.warn(' Run "npx @exagent/agent encrypt" to secure your keys.');
|
|
2682
|
+
console.warn("");
|
|
2683
|
+
}
|
|
2684
|
+
return false;
|
|
2685
|
+
}
|
|
2686
|
+
return false;
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
export {
|
|
2690
|
+
BaseLLMAdapter,
|
|
2691
|
+
OpenAIAdapter,
|
|
2692
|
+
AnthropicAdapter,
|
|
2693
|
+
GoogleAdapter,
|
|
2694
|
+
DeepSeekAdapter,
|
|
2695
|
+
MistralAdapter,
|
|
2696
|
+
GroqAdapter,
|
|
2697
|
+
TogetherAdapter,
|
|
2698
|
+
OllamaAdapter,
|
|
2699
|
+
createLLMAdapter,
|
|
2700
|
+
loadStrategy,
|
|
2701
|
+
validateStrategy,
|
|
2702
|
+
STRATEGY_TEMPLATES,
|
|
2703
|
+
getStrategyTemplate,
|
|
2704
|
+
getAllStrategyTemplates,
|
|
2705
|
+
TradeExecutor,
|
|
2706
|
+
RiskManager,
|
|
2707
|
+
MarketDataService,
|
|
2708
|
+
VaultManager,
|
|
2709
|
+
RelayClient,
|
|
2710
|
+
AgentRuntime,
|
|
2711
|
+
LLMProviderSchema,
|
|
2712
|
+
LLMConfigSchema,
|
|
2713
|
+
RiskUniverseSchema,
|
|
2714
|
+
TradingConfigSchema,
|
|
2715
|
+
VaultPolicySchema,
|
|
2716
|
+
VaultConfigSchema,
|
|
2717
|
+
RelayConfigSchema,
|
|
2718
|
+
AgentConfigSchema,
|
|
2719
|
+
loadConfig,
|
|
2720
|
+
validateConfig,
|
|
2721
|
+
createSampleConfig,
|
|
2722
|
+
encryptEnvFile,
|
|
2723
|
+
decryptEnvFile,
|
|
2724
|
+
loadSecureEnv
|
|
2725
|
+
};
|