@exagent/agent 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2853 @@
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/market.ts
878
+ import { createPublicClient, http, erc20Abi } from "viem";
879
+ var NATIVE_ETH = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
880
+ var TOKEN_DECIMALS = {
881
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": 6,
882
+ // USDC (Base Mainnet)
883
+ "0xd9aaec86b65d86f6a7b5b1b0c42ffa531710b6ca": 6,
884
+ // USDbC (Base Mainnet)
885
+ "0x4200000000000000000000000000000000000006": 18,
886
+ // WETH
887
+ "0x50c5725949a6f0c72e6c4a641f24049a917db0cb": 18,
888
+ // DAI
889
+ "0x2ae3f1ec7f1f5012cfeab0185bfc7aa3cf0dec22": 18,
890
+ // cbETH
891
+ [NATIVE_ETH.toLowerCase()]: 18,
892
+ // Native ETH
893
+ // Base Sepolia
894
+ "0x036cbd53842c5426634e7929541ec2318f3dcf7e": 6
895
+ // USDC testnet
896
+ };
897
+ function getTokenDecimals(address) {
898
+ const decimals = TOKEN_DECIMALS[address.toLowerCase()];
899
+ if (decimals === void 0) {
900
+ console.warn(`Unknown token decimals for ${address}, defaulting to 18. THIS MAY BE WRONG.`);
901
+ return 18;
902
+ }
903
+ return decimals;
904
+ }
905
+ var TOKEN_TO_COINGECKO = {
906
+ "0x4200000000000000000000000000000000000006": "ethereum",
907
+ // WETH
908
+ [NATIVE_ETH.toLowerCase()]: "ethereum",
909
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": "usd-coin",
910
+ // USDC
911
+ "0xd9aaec86b65d86f6a7b5b1b0c42ffa531710b6ca": "usd-coin",
912
+ // USDbC
913
+ "0x2ae3f1ec7f1f5012cfeab0185bfc7aa3cf0dec22": "coinbase-wrapped-staked-eth",
914
+ // cbETH
915
+ "0x50c5725949a6f0c72e6c4a641f24049a917db0cb": "dai"
916
+ // DAI
917
+ };
918
+ var STABLECOIN_IDS = /* @__PURE__ */ new Set(["usd-coin", "dai"]);
919
+ var PRICE_STALENESS_MS = 6e4;
920
+ var MarketDataService = class {
921
+ rpcUrl;
922
+ client;
923
+ /** Cached prices from last fetch */
924
+ cachedPrices = {};
925
+ /** Timestamp of last successful price fetch */
926
+ lastPriceFetchAt = 0;
927
+ constructor(rpcUrl) {
928
+ this.rpcUrl = rpcUrl;
929
+ this.client = createPublicClient({
930
+ transport: http(rpcUrl)
931
+ });
932
+ }
933
+ /**
934
+ * Fetch current market data for the agent
935
+ */
936
+ async fetchMarketData(walletAddress, tokenAddresses) {
937
+ const prices = await this.fetchPrices(tokenAddresses);
938
+ const balances = await this.fetchBalances(walletAddress, tokenAddresses);
939
+ const portfolioValue = this.calculatePortfolioValue(balances, prices);
940
+ return {
941
+ timestamp: Date.now(),
942
+ prices,
943
+ balances,
944
+ portfolioValue
945
+ };
946
+ }
947
+ /**
948
+ * Check if cached prices are still fresh
949
+ */
950
+ get pricesAreFresh() {
951
+ return Date.now() - this.lastPriceFetchAt < PRICE_STALENESS_MS;
952
+ }
953
+ /**
954
+ * Fetch token prices from CoinGecko free API
955
+ * Returns cached prices if still fresh (<60s old)
956
+ */
957
+ async fetchPrices(tokenAddresses) {
958
+ if (this.pricesAreFresh && Object.keys(this.cachedPrices).length > 0) {
959
+ const prices2 = { ...this.cachedPrices };
960
+ for (const addr of tokenAddresses) {
961
+ const cgId = TOKEN_TO_COINGECKO[addr.toLowerCase()];
962
+ if (cgId && STABLECOIN_IDS.has(cgId) && !prices2[addr.toLowerCase()]) {
963
+ prices2[addr.toLowerCase()] = 1;
964
+ }
965
+ }
966
+ return prices2;
967
+ }
968
+ const prices = {};
969
+ const idsToFetch = /* @__PURE__ */ new Set();
970
+ for (const addr of tokenAddresses) {
971
+ const cgId = TOKEN_TO_COINGECKO[addr.toLowerCase()];
972
+ if (cgId && !STABLECOIN_IDS.has(cgId)) {
973
+ idsToFetch.add(cgId);
974
+ }
975
+ }
976
+ idsToFetch.add("ethereum");
977
+ if (idsToFetch.size > 0) {
978
+ try {
979
+ const ids = Array.from(idsToFetch).join(",");
980
+ const response = await fetch(
981
+ `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`,
982
+ { signal: AbortSignal.timeout(5e3) }
983
+ );
984
+ if (response.ok) {
985
+ const data = await response.json();
986
+ for (const [cgId, priceData] of Object.entries(data)) {
987
+ const usdPrice = priceData.usd;
988
+ for (const [addr, id] of Object.entries(TOKEN_TO_COINGECKO)) {
989
+ if (id === cgId) {
990
+ prices[addr.toLowerCase()] = usdPrice;
991
+ }
992
+ }
993
+ }
994
+ this.lastPriceFetchAt = Date.now();
995
+ } else {
996
+ console.warn(`CoinGecko API returned ${response.status}, using cached prices`);
997
+ }
998
+ } catch (error) {
999
+ console.warn("Failed to fetch prices from CoinGecko:", error instanceof Error ? error.message : error);
1000
+ }
1001
+ }
1002
+ for (const addr of tokenAddresses) {
1003
+ const cgId = TOKEN_TO_COINGECKO[addr.toLowerCase()];
1004
+ if (cgId && STABLECOIN_IDS.has(cgId)) {
1005
+ prices[addr.toLowerCase()] = 1;
1006
+ }
1007
+ }
1008
+ if (Object.keys(prices).length > 0) {
1009
+ this.cachedPrices = prices;
1010
+ }
1011
+ if (Object.keys(prices).length === 0 && Object.keys(this.cachedPrices).length > 0) {
1012
+ console.warn("Using cached prices (last successful fetch was stale)");
1013
+ return { ...this.cachedPrices };
1014
+ }
1015
+ for (const addr of tokenAddresses) {
1016
+ if (!prices[addr.toLowerCase()]) {
1017
+ console.warn(`No price available for ${addr}, using 0`);
1018
+ prices[addr.toLowerCase()] = 0;
1019
+ }
1020
+ }
1021
+ return prices;
1022
+ }
1023
+ /**
1024
+ * Fetch real on-chain balances: native ETH + ERC-20 tokens
1025
+ */
1026
+ async fetchBalances(walletAddress, tokenAddresses) {
1027
+ const balances = {};
1028
+ const wallet = walletAddress;
1029
+ try {
1030
+ const nativeBalance = await this.client.getBalance({ address: wallet });
1031
+ balances[NATIVE_ETH.toLowerCase()] = nativeBalance;
1032
+ const erc20Promises = tokenAddresses.map(async (tokenAddress) => {
1033
+ try {
1034
+ const balance = await this.client.readContract({
1035
+ address: tokenAddress,
1036
+ abi: erc20Abi,
1037
+ functionName: "balanceOf",
1038
+ args: [wallet]
1039
+ });
1040
+ return { address: tokenAddress.toLowerCase(), balance };
1041
+ } catch (error) {
1042
+ return { address: tokenAddress.toLowerCase(), balance: 0n };
1043
+ }
1044
+ });
1045
+ const results = await Promise.all(erc20Promises);
1046
+ for (const { address, balance } of results) {
1047
+ balances[address] = balance;
1048
+ }
1049
+ } catch (error) {
1050
+ console.error("MarketData: Failed to fetch balances:", error instanceof Error ? error.message : error);
1051
+ balances[NATIVE_ETH.toLowerCase()] = 0n;
1052
+ for (const address of tokenAddresses) {
1053
+ balances[address.toLowerCase()] = 0n;
1054
+ }
1055
+ }
1056
+ return balances;
1057
+ }
1058
+ /**
1059
+ * Calculate total portfolio value in USD
1060
+ */
1061
+ calculatePortfolioValue(balances, prices) {
1062
+ let total = 0;
1063
+ for (const [address, balance] of Object.entries(balances)) {
1064
+ const price = prices[address.toLowerCase()] || 0;
1065
+ const decimals = getTokenDecimals(address);
1066
+ const amount = Number(balance) / Math.pow(10, decimals);
1067
+ total += amount * price;
1068
+ }
1069
+ return total;
1070
+ }
1071
+ };
1072
+
1073
+ // src/trading/risk.ts
1074
+ var RiskManager = class {
1075
+ config;
1076
+ dailyPnL = 0;
1077
+ lastResetDate = "";
1078
+ constructor(config) {
1079
+ this.config = config;
1080
+ }
1081
+ /**
1082
+ * Filter signals through risk checks
1083
+ * Returns only signals that pass all guardrails
1084
+ */
1085
+ filterSignals(signals, marketData) {
1086
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1087
+ if (today !== this.lastResetDate) {
1088
+ this.dailyPnL = 0;
1089
+ this.lastResetDate = today;
1090
+ }
1091
+ if (this.isDailyLossLimitHit(marketData.portfolioValue)) {
1092
+ console.warn("Daily loss limit reached - no new trades");
1093
+ return [];
1094
+ }
1095
+ return signals.filter((signal) => this.validateSignal(signal, marketData));
1096
+ }
1097
+ /**
1098
+ * Validate individual signal against risk limits
1099
+ */
1100
+ validateSignal(signal, marketData) {
1101
+ if (signal.action === "hold") {
1102
+ return true;
1103
+ }
1104
+ const signalValue = this.estimateSignalValue(signal, marketData);
1105
+ const maxPositionValue = marketData.portfolioValue * this.config.maxPositionSizeBps / 1e4;
1106
+ if (signalValue > maxPositionValue) {
1107
+ console.warn(
1108
+ `Signal exceeds position limit: ${signalValue.toFixed(2)} > ${maxPositionValue.toFixed(2)}`
1109
+ );
1110
+ return false;
1111
+ }
1112
+ if (signal.confidence < 0.5) {
1113
+ console.warn(`Signal confidence too low: ${signal.confidence}`);
1114
+ return false;
1115
+ }
1116
+ return true;
1117
+ }
1118
+ /**
1119
+ * Check if daily loss limit has been hit
1120
+ */
1121
+ isDailyLossLimitHit(portfolioValue) {
1122
+ const maxLoss = portfolioValue * this.config.maxDailyLossBps / 1e4;
1123
+ return this.dailyPnL < -maxLoss;
1124
+ }
1125
+ /**
1126
+ * Estimate USD value of a trade signal
1127
+ */
1128
+ estimateSignalValue(signal, marketData) {
1129
+ const price = marketData.prices[signal.tokenIn.toLowerCase()] || 0;
1130
+ const tokenDecimals = getTokenDecimals(signal.tokenIn);
1131
+ const amount = Number(signal.amountIn) / Math.pow(10, tokenDecimals);
1132
+ return amount * price;
1133
+ }
1134
+ /**
1135
+ * Update daily PnL after a trade
1136
+ */
1137
+ updatePnL(pnl) {
1138
+ this.dailyPnL += pnl;
1139
+ }
1140
+ /**
1141
+ * Get current risk status
1142
+ * @param portfolioValue - Current portfolio value in USD (needed for accurate loss limit)
1143
+ */
1144
+ getStatus(portfolioValue) {
1145
+ const pv = portfolioValue || 0;
1146
+ const maxLossUSD = pv * this.config.maxDailyLossBps / 1e4;
1147
+ return {
1148
+ dailyPnL: this.dailyPnL,
1149
+ dailyLossLimit: maxLossUSD,
1150
+ isLimitHit: pv > 0 ? this.dailyPnL < -maxLossUSD : false
1151
+ };
1152
+ }
1153
+ };
1154
+
1155
+ // src/vault/manager.ts
1156
+ import { createPublicClient as createPublicClient2, createWalletClient, http as http2 } from "viem";
1157
+ import { privateKeyToAccount } from "viem/accounts";
1158
+ import { baseSepolia, base } from "viem/chains";
1159
+ var ADDRESSES = {
1160
+ testnet: {
1161
+ vaultFactory: "0x5c099daaE33801a907Bb57011c6749655b55dc75",
1162
+ registry: "0xCF48C341e3FebeCA5ECB7eb2535f61A2Ba855d9C",
1163
+ usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
1164
+ },
1165
+ mainnet: {
1166
+ vaultFactory: process.env.EXAGENT_VAULT_FACTORY_ADDRESS || "0x0000000000000000000000000000000000000000",
1167
+ registry: process.env.EXAGENT_REGISTRY_ADDRESS || "0x0000000000000000000000000000000000000000",
1168
+ usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
1169
+ // Base mainnet USDC
1170
+ }
1171
+ };
1172
+ var VAULT_FACTORY_ABI = [
1173
+ {
1174
+ type: "function",
1175
+ name: "vaults",
1176
+ inputs: [{ name: "agentId", type: "uint256" }, { name: "asset", type: "address" }],
1177
+ outputs: [{ type: "address" }],
1178
+ stateMutability: "view"
1179
+ },
1180
+ {
1181
+ type: "function",
1182
+ name: "canCreateVault",
1183
+ inputs: [{ name: "creator", type: "address" }],
1184
+ outputs: [{ name: "canCreate", type: "bool" }, { name: "reason", type: "string" }],
1185
+ stateMutability: "view"
1186
+ },
1187
+ {
1188
+ type: "function",
1189
+ name: "createVault",
1190
+ inputs: [
1191
+ { name: "agentId", type: "uint256" },
1192
+ { name: "asset", type: "address" },
1193
+ { name: "seedAmount", type: "uint256" },
1194
+ { name: "name", type: "string" },
1195
+ { name: "symbol", type: "string" },
1196
+ { name: "feeRecipient", type: "address" }
1197
+ ],
1198
+ outputs: [{ type: "address" }],
1199
+ stateMutability: "nonpayable"
1200
+ },
1201
+ {
1202
+ type: "function",
1203
+ name: "minimumVeEXARequired",
1204
+ inputs: [],
1205
+ outputs: [{ type: "uint256" }],
1206
+ stateMutability: "view"
1207
+ }
1208
+ ];
1209
+ var VAULT_ABI = [
1210
+ {
1211
+ type: "function",
1212
+ name: "totalAssets",
1213
+ inputs: [],
1214
+ outputs: [{ type: "uint256" }],
1215
+ stateMutability: "view"
1216
+ },
1217
+ {
1218
+ type: "function",
1219
+ name: "executeTrade",
1220
+ inputs: [
1221
+ { name: "tokenIn", type: "address" },
1222
+ { name: "tokenOut", type: "address" },
1223
+ { name: "amountIn", type: "uint256" },
1224
+ { name: "minAmountOut", type: "uint256" },
1225
+ { name: "aggregator", type: "address" },
1226
+ { name: "swapData", type: "bytes" },
1227
+ { name: "deadline", type: "uint256" }
1228
+ ],
1229
+ outputs: [{ type: "uint256" }],
1230
+ stateMutability: "nonpayable"
1231
+ }
1232
+ ];
1233
+ var VaultManager = class {
1234
+ config;
1235
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1236
+ publicClient;
1237
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1238
+ walletClient;
1239
+ addresses;
1240
+ account;
1241
+ chain;
1242
+ cachedVaultAddress = null;
1243
+ lastVaultCheck = 0;
1244
+ VAULT_CACHE_TTL = 6e4;
1245
+ // 1 minute
1246
+ enabled = true;
1247
+ constructor(config) {
1248
+ this.config = config;
1249
+ this.addresses = ADDRESSES[config.network];
1250
+ this.account = privateKeyToAccount(config.walletKey);
1251
+ this.chain = config.network === "mainnet" ? base : baseSepolia;
1252
+ const rpcUrl = config.network === "mainnet" ? "https://mainnet.base.org" : "https://sepolia.base.org";
1253
+ this.publicClient = createPublicClient2({
1254
+ chain: this.chain,
1255
+ transport: http2(rpcUrl)
1256
+ });
1257
+ this.walletClient = createWalletClient({
1258
+ account: this.account,
1259
+ chain: this.chain,
1260
+ transport: http2(rpcUrl)
1261
+ });
1262
+ if (this.addresses.vaultFactory === "0x0000000000000000000000000000000000000000") {
1263
+ console.warn("VaultFactory address is zero \u2014 vault operations will be disabled");
1264
+ this.enabled = false;
1265
+ }
1266
+ }
1267
+ /**
1268
+ * Get the agent's vault policy
1269
+ */
1270
+ get policy() {
1271
+ return this.config.vaultConfig.policy;
1272
+ }
1273
+ /**
1274
+ * Check if vault trading is preferred when a vault exists
1275
+ */
1276
+ get preferVaultTrading() {
1277
+ return this.config.vaultConfig.preferVaultTrading;
1278
+ }
1279
+ /**
1280
+ * Get comprehensive vault status
1281
+ */
1282
+ async getVaultStatus() {
1283
+ if (!this.enabled) {
1284
+ return {
1285
+ hasVault: false,
1286
+ vaultAddress: null,
1287
+ totalAssets: BigInt(0),
1288
+ canCreateVault: false,
1289
+ cannotCreateReason: "Vault operations disabled (contract address not set)",
1290
+ requirementsMet: false,
1291
+ requirements: { veXARequired: BigInt(0), isBypassed: false }
1292
+ };
1293
+ }
1294
+ const vaultAddress = await this.getVaultAddress();
1295
+ const hasVault = vaultAddress !== null;
1296
+ let totalAssets = BigInt(0);
1297
+ if (hasVault && vaultAddress) {
1298
+ try {
1299
+ totalAssets = await this.publicClient.readContract({
1300
+ address: vaultAddress,
1301
+ abi: VAULT_ABI,
1302
+ functionName: "totalAssets"
1303
+ });
1304
+ } catch {
1305
+ }
1306
+ }
1307
+ const [canCreateResult, requirements] = await Promise.all([
1308
+ this.publicClient.readContract({
1309
+ address: this.addresses.vaultFactory,
1310
+ abi: VAULT_FACTORY_ABI,
1311
+ functionName: "canCreateVault",
1312
+ args: [this.account.address]
1313
+ }),
1314
+ this.getRequirements()
1315
+ ]);
1316
+ return {
1317
+ hasVault,
1318
+ vaultAddress,
1319
+ totalAssets,
1320
+ canCreateVault: canCreateResult[0],
1321
+ cannotCreateReason: canCreateResult[0] ? null : canCreateResult[1],
1322
+ requirementsMet: canCreateResult[0] || requirements.isBypassed,
1323
+ requirements
1324
+ };
1325
+ }
1326
+ /**
1327
+ * Get vault creation requirements
1328
+ * Note: No burnFee on mainnet — vault creation requires USDC seed instead
1329
+ */
1330
+ async getRequirements() {
1331
+ const veXARequired = await this.publicClient.readContract({
1332
+ address: this.addresses.vaultFactory,
1333
+ abi: VAULT_FACTORY_ABI,
1334
+ functionName: "minimumVeEXARequired"
1335
+ });
1336
+ const isBypassed = veXARequired === BigInt(0);
1337
+ return { veXARequired, isBypassed };
1338
+ }
1339
+ /**
1340
+ * Get the agent's vault address (cached)
1341
+ */
1342
+ async getVaultAddress() {
1343
+ const now = Date.now();
1344
+ if (this.cachedVaultAddress && now - this.lastVaultCheck < this.VAULT_CACHE_TTL) {
1345
+ return this.cachedVaultAddress;
1346
+ }
1347
+ const vaultAddress = await this.publicClient.readContract({
1348
+ address: this.addresses.vaultFactory,
1349
+ abi: VAULT_FACTORY_ABI,
1350
+ functionName: "vaults",
1351
+ args: [this.config.agentId, this.addresses.usdc]
1352
+ });
1353
+ this.lastVaultCheck = now;
1354
+ if (vaultAddress === "0x0000000000000000000000000000000000000000") {
1355
+ this.cachedVaultAddress = null;
1356
+ return null;
1357
+ }
1358
+ this.cachedVaultAddress = vaultAddress;
1359
+ return vaultAddress;
1360
+ }
1361
+ /**
1362
+ * Check if the agent should create a vault based on policy and qualification
1363
+ */
1364
+ async shouldCreateVault() {
1365
+ if (this.policy === "disabled") {
1366
+ return { should: false, reason: "Vault creation disabled by policy" };
1367
+ }
1368
+ if (this.policy === "manual") {
1369
+ return { should: false, reason: "Vault creation set to manual - waiting for owner instruction" };
1370
+ }
1371
+ const status = await this.getVaultStatus();
1372
+ if (status.hasVault) {
1373
+ return { should: false, reason: "Vault already exists" };
1374
+ }
1375
+ if (!status.canCreateVault) {
1376
+ return { should: false, reason: status.cannotCreateReason || "Requirements not met" };
1377
+ }
1378
+ return { should: true, reason: "Agent is qualified and auto-creation is enabled" };
1379
+ }
1380
+ /**
1381
+ * Create a vault for the agent
1382
+ * @param seedAmount - USDC seed amount in raw units (default: 100e6 = 100 USDC)
1383
+ * @returns Vault address if successful
1384
+ */
1385
+ async createVault(seedAmount) {
1386
+ if (!this.enabled) {
1387
+ return { success: false, error: "Vault operations disabled (contract address not set)" };
1388
+ }
1389
+ if (this.policy === "disabled") {
1390
+ return { success: false, error: "Vault creation disabled by policy" };
1391
+ }
1392
+ const existingVault = await this.getVaultAddress();
1393
+ if (existingVault) {
1394
+ return { success: false, error: "Vault already exists", vaultAddress: existingVault };
1395
+ }
1396
+ const status = await this.getVaultStatus();
1397
+ if (!status.canCreateVault) {
1398
+ return { success: false, error: status.cannotCreateReason || "Requirements not met" };
1399
+ }
1400
+ const seed = seedAmount || BigInt(1e8);
1401
+ const vaultName = this.config.vaultConfig.defaultName || `${this.config.agentName} Trading Vault`;
1402
+ const vaultSymbol = this.config.vaultConfig.defaultSymbol || `ex${this.config.agentName.replace(/[^a-zA-Z]/g, "").slice(0, 4).toUpperCase()}`;
1403
+ const feeRecipient = this.config.vaultConfig.feeRecipient || this.account.address;
1404
+ try {
1405
+ const hash = await this.walletClient.writeContract({
1406
+ address: this.addresses.vaultFactory,
1407
+ abi: VAULT_FACTORY_ABI,
1408
+ functionName: "createVault",
1409
+ args: [
1410
+ this.config.agentId,
1411
+ this.addresses.usdc,
1412
+ seed,
1413
+ vaultName,
1414
+ vaultSymbol,
1415
+ feeRecipient
1416
+ ],
1417
+ chain: this.chain,
1418
+ account: this.account
1419
+ });
1420
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1421
+ if (receipt.status !== "success") {
1422
+ return { success: false, error: "Transaction failed", txHash: hash };
1423
+ }
1424
+ const vaultAddress = await this.getVaultAddress();
1425
+ this.cachedVaultAddress = vaultAddress;
1426
+ return {
1427
+ success: true,
1428
+ vaultAddress,
1429
+ txHash: hash
1430
+ };
1431
+ } catch (error) {
1432
+ return {
1433
+ success: false,
1434
+ error: error instanceof Error ? error.message : "Unknown error"
1435
+ };
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Execute a trade through the vault (if it exists and policy allows)
1440
+ * Returns null if should use direct trading instead
1441
+ */
1442
+ async executeVaultTrade(params) {
1443
+ if (!this.preferVaultTrading) {
1444
+ return null;
1445
+ }
1446
+ const vaultAddress = await this.getVaultAddress();
1447
+ if (!vaultAddress) {
1448
+ return null;
1449
+ }
1450
+ const deadline = params.deadline || BigInt(Math.floor(Date.now() / 1e3) + 3600);
1451
+ try {
1452
+ const hash = await this.walletClient.writeContract({
1453
+ address: vaultAddress,
1454
+ abi: VAULT_ABI,
1455
+ functionName: "executeTrade",
1456
+ args: [
1457
+ params.tokenIn,
1458
+ params.tokenOut,
1459
+ params.amountIn,
1460
+ params.minAmountOut,
1461
+ params.aggregator,
1462
+ params.swapData,
1463
+ deadline
1464
+ ],
1465
+ chain: this.chain,
1466
+ account: this.account
1467
+ });
1468
+ return { usedVault: true, txHash: hash };
1469
+ } catch (error) {
1470
+ return {
1471
+ usedVault: true,
1472
+ error: error instanceof Error ? error.message : "Vault trade failed"
1473
+ };
1474
+ }
1475
+ }
1476
+ /**
1477
+ * Run the auto-creation check (call this periodically in the agent loop)
1478
+ * Only creates vault if policy is 'auto_when_qualified'
1479
+ */
1480
+ async checkAndAutoCreateVault() {
1481
+ const shouldCreate = await this.shouldCreateVault();
1482
+ if (!shouldCreate.should) {
1483
+ const status = await this.getVaultStatus();
1484
+ if (status.hasVault) {
1485
+ return { action: "already_exists", vaultAddress: status.vaultAddress, reason: "Vault already exists" };
1486
+ }
1487
+ if (this.policy !== "auto_when_qualified") {
1488
+ return { action: "skipped", reason: shouldCreate.reason };
1489
+ }
1490
+ return { action: "not_qualified", reason: shouldCreate.reason };
1491
+ }
1492
+ const result = await this.createVault();
1493
+ if (result.success) {
1494
+ return {
1495
+ action: "created",
1496
+ vaultAddress: result.vaultAddress,
1497
+ reason: "Vault created automatically"
1498
+ };
1499
+ }
1500
+ return { action: "not_qualified", reason: result.error || "Creation failed" };
1501
+ }
1502
+ };
1503
+
1504
+ // src/relay.ts
1505
+ import WebSocket from "ws";
1506
+ import { privateKeyToAccount as privateKeyToAccount2, signMessage } from "viem/accounts";
1507
+ var RelayClient = class {
1508
+ config;
1509
+ ws = null;
1510
+ authenticated = false;
1511
+ authRejected = false;
1512
+ reconnectAttempts = 0;
1513
+ maxReconnectAttempts = 50;
1514
+ reconnectTimer = null;
1515
+ heartbeatTimer = null;
1516
+ stopped = false;
1517
+ constructor(config) {
1518
+ this.config = config;
1519
+ }
1520
+ /**
1521
+ * Connect to the relay server
1522
+ */
1523
+ async connect() {
1524
+ if (this.stopped) return;
1525
+ const wsUrl = this.config.relay.apiUrl.replace(/^https?:\/\//, (m) => m.includes("https") ? "wss://" : "ws://").replace(/\/$/, "") + "/ws/agent";
1526
+ return new Promise((resolve, reject) => {
1527
+ try {
1528
+ this.ws = new WebSocket(wsUrl);
1529
+ } catch (error) {
1530
+ console.error("Relay: Failed to create WebSocket:", error);
1531
+ this.scheduleReconnect();
1532
+ reject(error);
1533
+ return;
1534
+ }
1535
+ const connectTimeout = setTimeout(() => {
1536
+ if (!this.authenticated) {
1537
+ console.error("Relay: Connection timeout");
1538
+ this.ws?.close();
1539
+ this.scheduleReconnect();
1540
+ reject(new Error("Connection timeout"));
1541
+ }
1542
+ }, 15e3);
1543
+ this.ws.on("open", async () => {
1544
+ this.authRejected = false;
1545
+ console.log("Relay: Connected, authenticating...");
1546
+ try {
1547
+ await this.authenticate();
1548
+ } catch (error) {
1549
+ console.error("Relay: Authentication failed:", error);
1550
+ this.ws?.close();
1551
+ clearTimeout(connectTimeout);
1552
+ reject(error);
1553
+ }
1554
+ });
1555
+ this.ws.on("message", (raw) => {
1556
+ try {
1557
+ const data = JSON.parse(raw.toString());
1558
+ this.handleMessage(data);
1559
+ if (data.type === "auth_success") {
1560
+ clearTimeout(connectTimeout);
1561
+ this.authenticated = true;
1562
+ this.reconnectAttempts = 0;
1563
+ this.startHeartbeat();
1564
+ console.log("Relay: Authenticated successfully");
1565
+ resolve();
1566
+ } else if (data.type === "auth_error") {
1567
+ clearTimeout(connectTimeout);
1568
+ this.authRejected = true;
1569
+ console.error(`Relay: Auth rejected: ${data.message}`);
1570
+ reject(new Error(data.message));
1571
+ }
1572
+ } catch {
1573
+ }
1574
+ });
1575
+ this.ws.on("close", (code, reason) => {
1576
+ clearTimeout(connectTimeout);
1577
+ this.authenticated = false;
1578
+ this.stopHeartbeat();
1579
+ if (!this.stopped) {
1580
+ if (!this.authRejected) {
1581
+ console.log(`Relay: Disconnected (${code}: ${reason.toString() || "unknown"})`);
1582
+ }
1583
+ this.scheduleReconnect();
1584
+ }
1585
+ });
1586
+ this.ws.on("error", (error) => {
1587
+ if (!this.stopped) {
1588
+ console.error("Relay: WebSocket error:", error.message);
1589
+ }
1590
+ });
1591
+ });
1592
+ }
1593
+ /**
1594
+ * Authenticate with the relay server using wallet signature
1595
+ */
1596
+ async authenticate() {
1597
+ const account = privateKeyToAccount2(this.config.privateKey);
1598
+ const timestamp = Math.floor(Date.now() / 1e3);
1599
+ const message = `ExagentRelay:${this.config.agentId}:${timestamp}`;
1600
+ const signature = await signMessage({
1601
+ message,
1602
+ privateKey: this.config.privateKey
1603
+ });
1604
+ this.send({
1605
+ type: "auth",
1606
+ agentId: this.config.agentId,
1607
+ wallet: account.address,
1608
+ timestamp,
1609
+ signature
1610
+ });
1611
+ }
1612
+ /**
1613
+ * Handle incoming messages from the relay server
1614
+ */
1615
+ handleMessage(data) {
1616
+ switch (data.type) {
1617
+ case "command":
1618
+ if (data.command && this.config.onCommand) {
1619
+ this.config.onCommand(data.command);
1620
+ }
1621
+ break;
1622
+ case "auth_success":
1623
+ case "auth_error":
1624
+ break;
1625
+ case "error":
1626
+ console.error(`Relay: Server error: ${data.message}`);
1627
+ break;
1628
+ }
1629
+ }
1630
+ /**
1631
+ * Send a status heartbeat
1632
+ */
1633
+ sendHeartbeat(status) {
1634
+ if (!this.authenticated) return;
1635
+ this.send({
1636
+ type: "heartbeat",
1637
+ agentId: this.config.agentId,
1638
+ status
1639
+ });
1640
+ }
1641
+ /**
1642
+ * Send a status update (outside of regular heartbeat)
1643
+ */
1644
+ sendStatusUpdate(status) {
1645
+ if (!this.authenticated) return;
1646
+ this.send({
1647
+ type: "status_update",
1648
+ agentId: this.config.agentId,
1649
+ status
1650
+ });
1651
+ }
1652
+ /**
1653
+ * Send a message to the command center
1654
+ */
1655
+ sendMessage(messageType, level, title, body, data) {
1656
+ if (!this.authenticated) return;
1657
+ this.send({
1658
+ type: "message",
1659
+ agentId: this.config.agentId,
1660
+ messageType,
1661
+ level,
1662
+ title,
1663
+ body,
1664
+ data
1665
+ });
1666
+ }
1667
+ /**
1668
+ * Send a command execution result
1669
+ */
1670
+ sendCommandResult(commandId, success, result) {
1671
+ if (!this.authenticated) return;
1672
+ this.send({
1673
+ type: "command_result",
1674
+ agentId: this.config.agentId,
1675
+ commandId,
1676
+ success,
1677
+ result
1678
+ });
1679
+ }
1680
+ /**
1681
+ * Start the heartbeat timer
1682
+ */
1683
+ startHeartbeat() {
1684
+ this.stopHeartbeat();
1685
+ const interval = this.config.relay.heartbeatIntervalMs || 3e4;
1686
+ this.heartbeatTimer = setInterval(() => {
1687
+ if (this.ws?.readyState === WebSocket.OPEN) {
1688
+ this.ws.ping();
1689
+ }
1690
+ }, interval);
1691
+ }
1692
+ /**
1693
+ * Stop the heartbeat timer
1694
+ */
1695
+ stopHeartbeat() {
1696
+ if (this.heartbeatTimer) {
1697
+ clearInterval(this.heartbeatTimer);
1698
+ this.heartbeatTimer = null;
1699
+ }
1700
+ }
1701
+ /**
1702
+ * Schedule a reconnection with exponential backoff
1703
+ */
1704
+ scheduleReconnect() {
1705
+ if (this.stopped) return;
1706
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1707
+ console.error("Relay: Max reconnection attempts reached. Giving up.");
1708
+ return;
1709
+ }
1710
+ const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1711
+ this.reconnectAttempts++;
1712
+ console.log(
1713
+ `Relay: Reconnecting in ${delay / 1e3}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
1714
+ );
1715
+ this.reconnectTimer = setTimeout(() => {
1716
+ this.connect().catch(() => {
1717
+ });
1718
+ }, delay);
1719
+ }
1720
+ /**
1721
+ * Send a JSON message to the WebSocket
1722
+ */
1723
+ send(data) {
1724
+ if (this.ws?.readyState === WebSocket.OPEN) {
1725
+ this.ws.send(JSON.stringify(data));
1726
+ }
1727
+ }
1728
+ /**
1729
+ * Check if connected and authenticated
1730
+ */
1731
+ get isConnected() {
1732
+ return this.authenticated && this.ws?.readyState === WebSocket.OPEN;
1733
+ }
1734
+ /**
1735
+ * Disconnect and stop reconnecting
1736
+ */
1737
+ disconnect() {
1738
+ this.stopped = true;
1739
+ this.stopHeartbeat();
1740
+ if (this.reconnectTimer) {
1741
+ clearTimeout(this.reconnectTimer);
1742
+ this.reconnectTimer = null;
1743
+ }
1744
+ if (this.ws) {
1745
+ this.ws.close(1e3, "Agent shutting down");
1746
+ this.ws = null;
1747
+ }
1748
+ this.authenticated = false;
1749
+ console.log("Relay: Disconnected");
1750
+ }
1751
+ };
1752
+
1753
+ // src/runtime.ts
1754
+ import { ExagentClient, ExagentRegistry } from "@exagent/sdk";
1755
+ import { createPublicClient as createPublicClient3, http as http3 } from "viem";
1756
+ import { baseSepolia as baseSepolia2, base as base2 } from "viem/chains";
1757
+
1758
+ // src/browser-open.ts
1759
+ import { exec } from "child_process";
1760
+ function openBrowser(url) {
1761
+ const platform = process.platform;
1762
+ try {
1763
+ if (platform === "darwin") {
1764
+ exec(`open "${url}"`);
1765
+ } else if (platform === "win32") {
1766
+ exec(`start "" "${url}"`);
1767
+ } else {
1768
+ exec(`xdg-open "${url}"`);
1769
+ }
1770
+ } catch {
1771
+ }
1772
+ }
1773
+
1774
+ // src/runtime.ts
1775
+ var FUNDS_LOW_THRESHOLD = 5e-3;
1776
+ var AgentRuntime = class {
1777
+ config;
1778
+ client;
1779
+ llm;
1780
+ strategy;
1781
+ executor;
1782
+ riskManager;
1783
+ marketData;
1784
+ vaultManager;
1785
+ relay = null;
1786
+ isRunning = false;
1787
+ mode = "idle";
1788
+ configHash;
1789
+ lastVaultCheck = 0;
1790
+ cycleCount = 0;
1791
+ lastCycleAt = 0;
1792
+ lastPortfolioValue = 0;
1793
+ lastEthBalance = "0";
1794
+ processAlive = true;
1795
+ VAULT_CHECK_INTERVAL = 3e5;
1796
+ // Check vault status every 5 minutes
1797
+ constructor(config) {
1798
+ this.config = config;
1799
+ }
1800
+ /**
1801
+ * Initialize the agent runtime
1802
+ */
1803
+ async initialize() {
1804
+ console.log(`Initializing agent: ${this.config.name} (ID: ${this.config.agentId})`);
1805
+ this.client = new ExagentClient({
1806
+ privateKey: this.config.privateKey,
1807
+ network: this.config.network
1808
+ });
1809
+ console.log(`Wallet: ${this.client.address}`);
1810
+ const agent = await this.client.registry.getAgent(BigInt(this.config.agentId));
1811
+ if (!agent) {
1812
+ throw new Error(`Agent ID ${this.config.agentId} not found on-chain. Please register first.`);
1813
+ }
1814
+ console.log(`Agent verified: ${agent.name}`);
1815
+ await this.ensureWalletLinked();
1816
+ console.log(`Initializing LLM: ${this.config.llm.provider}`);
1817
+ this.llm = await createLLMAdapter(this.config.llm);
1818
+ const llmMeta = this.llm.getMetadata();
1819
+ console.log(`LLM ready: ${llmMeta.provider} (${llmMeta.model})`);
1820
+ await this.syncConfigHash();
1821
+ this.strategy = await loadStrategy();
1822
+ this.executor = new TradeExecutor(this.client, this.config);
1823
+ this.riskManager = new RiskManager(this.config.trading);
1824
+ this.marketData = new MarketDataService(this.getRpcUrl());
1825
+ await this.initializeVaultManager();
1826
+ await this.initializeRelay();
1827
+ console.log("Agent initialized successfully");
1828
+ }
1829
+ /**
1830
+ * Initialize the relay client for command center connectivity
1831
+ */
1832
+ async initializeRelay() {
1833
+ const relayConfig = this.config.relay;
1834
+ const relayEnabled = process.env.EXAGENT_RELAY_ENABLED !== "false";
1835
+ if (!relayConfig?.enabled || !relayEnabled) {
1836
+ console.log("Relay: Disabled");
1837
+ return;
1838
+ }
1839
+ const apiUrl = process.env.EXAGENT_API_URL || relayConfig.apiUrl;
1840
+ if (!apiUrl) {
1841
+ console.log("Relay: No API URL configured, skipping");
1842
+ return;
1843
+ }
1844
+ this.relay = new RelayClient({
1845
+ agentId: String(this.config.agentId),
1846
+ privateKey: this.config.privateKey,
1847
+ relay: {
1848
+ ...relayConfig,
1849
+ apiUrl
1850
+ },
1851
+ onCommand: (cmd) => this.handleCommand(cmd)
1852
+ });
1853
+ try {
1854
+ await this.relay.connect();
1855
+ console.log("Relay: Connected to command center");
1856
+ this.sendRelayStatus();
1857
+ } catch (error) {
1858
+ console.warn(
1859
+ "Relay: Failed to connect (agent will work locally):",
1860
+ error instanceof Error ? error.message : error
1861
+ );
1862
+ }
1863
+ }
1864
+ /**
1865
+ * Initialize the vault manager based on config
1866
+ */
1867
+ async initializeVaultManager() {
1868
+ const vaultConfig = this.config.vault || { policy: "disabled", preferVaultTrading: false };
1869
+ this.vaultManager = new VaultManager({
1870
+ agentId: BigInt(this.config.agentId),
1871
+ agentName: this.config.name,
1872
+ network: this.config.network,
1873
+ walletKey: this.config.privateKey,
1874
+ vaultConfig
1875
+ });
1876
+ console.log(`Vault policy: ${vaultConfig.policy}`);
1877
+ const status = await this.vaultManager.getVaultStatus();
1878
+ if (status.hasVault) {
1879
+ console.log(`Vault exists: ${status.vaultAddress}`);
1880
+ console.log(`Vault TVL: ${Number(status.totalAssets) / 1e6} USDC`);
1881
+ } else {
1882
+ console.log("No vault exists for this agent");
1883
+ if (vaultConfig.policy === "auto_when_qualified") {
1884
+ if (status.canCreateVault) {
1885
+ console.log("Agent is qualified to create vault - will attempt on next check");
1886
+ } else {
1887
+ console.log(`Cannot create vault yet: ${status.cannotCreateReason}`);
1888
+ }
1889
+ }
1890
+ }
1891
+ }
1892
+ /**
1893
+ * Ensure the current wallet is linked to the agent.
1894
+ * If the trading wallet differs from the owner, enters a recovery loop
1895
+ * that waits for the owner to link it from the website.
1896
+ */
1897
+ async ensureWalletLinked() {
1898
+ const agentId = BigInt(this.config.agentId);
1899
+ const address = this.client.address;
1900
+ const isLinked = await this.client.registry.isLinkedWallet(agentId, address);
1901
+ if (!isLinked) {
1902
+ console.log("Wallet not linked, linking now...");
1903
+ const agent = await this.client.registry.getAgent(agentId);
1904
+ if (agent?.owner.toLowerCase() !== address.toLowerCase()) {
1905
+ const ccUrl = `https://exagent.io/agents/${encodeURIComponent(this.config.name)}/command-center`;
1906
+ const nonce = await this.client.registry.getNonce(address);
1907
+ const linkMessage = ExagentRegistry.generateLinkMessage(
1908
+ address,
1909
+ agentId,
1910
+ nonce
1911
+ );
1912
+ const linkSignature = await this.client.signMessage({ raw: linkMessage });
1913
+ console.log("");
1914
+ console.log("=== WALLET LINKING REQUIRED ===");
1915
+ console.log("");
1916
+ console.log(" Your trading wallet needs to be linked to your agent.");
1917
+ console.log(" Open the command center and paste the values below.");
1918
+ console.log("");
1919
+ console.log(` Command Center: ${ccUrl}`);
1920
+ console.log("");
1921
+ console.log(" \u2500\u2500 Copy these two values \u2500\u2500");
1922
+ console.log("");
1923
+ console.log(` Wallet: ${address}`);
1924
+ console.log(` Signature: ${linkSignature}`);
1925
+ console.log("");
1926
+ openBrowser(ccUrl);
1927
+ console.log(" Waiting for wallet to be linked... (checking every 15s)");
1928
+ console.log(" Press Ctrl+C to exit.");
1929
+ console.log("");
1930
+ while (true) {
1931
+ await this.sleep(15e3);
1932
+ const linked = await this.client.registry.isLinkedWallet(agentId, address);
1933
+ if (linked) {
1934
+ console.log(" Wallet linked! Continuing setup...");
1935
+ console.log("");
1936
+ return;
1937
+ }
1938
+ process.stdout.write(".");
1939
+ }
1940
+ }
1941
+ await this.client.registry.linkOwnWallet(agentId);
1942
+ console.log("Wallet linked successfully");
1943
+ } else {
1944
+ console.log("Wallet already linked");
1945
+ }
1946
+ }
1947
+ /**
1948
+ * Sync the LLM config hash to chain for epoch tracking.
1949
+ * If the wallet has insufficient gas, enters a recovery loop
1950
+ * that waits for the user to fund the wallet.
1951
+ */
1952
+ async syncConfigHash() {
1953
+ const agentId = BigInt(this.config.agentId);
1954
+ const llmMeta = this.llm.getMetadata();
1955
+ this.configHash = ExagentRegistry.calculateConfigHash(llmMeta.provider, llmMeta.model);
1956
+ console.log(`Config hash: ${this.configHash}`);
1957
+ const onChainHash = await this.client.registry.getConfigHash(agentId);
1958
+ if (onChainHash !== this.configHash) {
1959
+ console.log("Config changed, updating on-chain...");
1960
+ try {
1961
+ await this.client.registry.updateConfig(agentId, this.configHash);
1962
+ const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
1963
+ console.log(`Config updated, new epoch started: ${newEpoch}`);
1964
+ } catch (error) {
1965
+ const message = error instanceof Error ? error.message : String(error);
1966
+ if (message.includes("insufficient funds") || message.includes("gas") || message.includes("intrinsic gas too low") || message.includes("exceeds the balance")) {
1967
+ const ccUrl = `https://exagent.io/agents/${encodeURIComponent(this.config.name)}/command-center`;
1968
+ const chain = this.config.network === "mainnet" ? base2 : baseSepolia2;
1969
+ const publicClientInstance = createPublicClient3({
1970
+ chain,
1971
+ transport: http3(this.getRpcUrl())
1972
+ });
1973
+ console.log("");
1974
+ console.log("=== ETH NEEDED FOR GAS ===");
1975
+ console.log("");
1976
+ console.log(` Wallet: ${this.client.address}`);
1977
+ console.log(" Your wallet needs ETH to pay for transaction gas.");
1978
+ console.log(" Opening the command center to fund your wallet...");
1979
+ console.log(` ${ccUrl}`);
1980
+ console.log("");
1981
+ openBrowser(ccUrl);
1982
+ console.log(" Waiting for ETH... (checking every 15s)");
1983
+ console.log(" Press Ctrl+C to exit.");
1984
+ console.log("");
1985
+ while (true) {
1986
+ await this.sleep(15e3);
1987
+ const balance = await publicClientInstance.getBalance({
1988
+ address: this.client.address
1989
+ });
1990
+ if (balance > BigInt(0)) {
1991
+ console.log(" ETH detected! Retrying config update...");
1992
+ console.log("");
1993
+ await this.client.registry.updateConfig(agentId, this.configHash);
1994
+ const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
1995
+ console.log(`Config updated, new epoch started: ${newEpoch}`);
1996
+ return;
1997
+ }
1998
+ process.stdout.write(".");
1999
+ }
2000
+ } else {
2001
+ throw error;
2002
+ }
2003
+ }
2004
+ } else {
2005
+ const currentEpoch = await this.client.registry.getCurrentEpoch(agentId);
2006
+ console.log(`Config hash matches on-chain (epoch ${currentEpoch})`);
2007
+ }
2008
+ }
2009
+ /**
2010
+ * Get the current config hash (for trade execution)
2011
+ */
2012
+ getConfigHash() {
2013
+ return this.configHash;
2014
+ }
2015
+ /**
2016
+ * Start the agent in daemon mode.
2017
+ * The agent enters idle mode and waits for commands from the command center.
2018
+ * Trading begins only when a start_trading command is received.
2019
+ *
2020
+ * If relay is not configured, falls back to immediate trading mode.
2021
+ */
2022
+ async run() {
2023
+ this.processAlive = true;
2024
+ if (this.relay) {
2025
+ console.log("");
2026
+ console.log("Agent is in IDLE mode. Waiting for commands from command center.");
2027
+ console.log("Visit https://exagent.io to start trading from the dashboard.");
2028
+ console.log("");
2029
+ this.mode = "idle";
2030
+ this.sendRelayStatus();
2031
+ this.relay.sendMessage(
2032
+ "system",
2033
+ "success",
2034
+ "Agent Connected",
2035
+ `${this.config.name} is online and waiting for commands.`,
2036
+ { wallet: this.client.address }
2037
+ );
2038
+ while (this.processAlive) {
2039
+ if (this.mode === "trading" && this.isRunning) {
2040
+ try {
2041
+ await this.runCycle();
2042
+ } catch (error) {
2043
+ const message = error instanceof Error ? error.message : String(error);
2044
+ console.error("Error in trading cycle:", message);
2045
+ this.relay?.sendMessage(
2046
+ "system",
2047
+ "error",
2048
+ "Cycle Error",
2049
+ message
2050
+ );
2051
+ }
2052
+ await this.sleep(this.config.trading.tradingIntervalMs);
2053
+ } else {
2054
+ this.sendRelayStatus();
2055
+ await this.sleep(3e4);
2056
+ }
2057
+ }
2058
+ } else {
2059
+ if (this.isRunning) {
2060
+ throw new Error("Agent is already running");
2061
+ }
2062
+ this.isRunning = true;
2063
+ this.mode = "trading";
2064
+ console.log("Starting trading loop...");
2065
+ console.log(`Interval: ${this.config.trading.tradingIntervalMs}ms`);
2066
+ while (this.isRunning) {
2067
+ try {
2068
+ await this.runCycle();
2069
+ } catch (error) {
2070
+ console.error("Error in trading cycle:", error);
2071
+ }
2072
+ await this.sleep(this.config.trading.tradingIntervalMs);
2073
+ }
2074
+ }
2075
+ }
2076
+ /**
2077
+ * Handle a command from the command center
2078
+ */
2079
+ async handleCommand(cmd) {
2080
+ console.log(`Command received: ${cmd.type}`);
2081
+ try {
2082
+ switch (cmd.type) {
2083
+ case "start_trading":
2084
+ if (this.mode === "trading") {
2085
+ this.relay?.sendCommandResult(cmd.id, true, "Already trading");
2086
+ return;
2087
+ }
2088
+ this.mode = "trading";
2089
+ this.isRunning = true;
2090
+ console.log("Trading started via command center");
2091
+ this.relay?.sendCommandResult(cmd.id, true, "Trading started");
2092
+ this.relay?.sendMessage(
2093
+ "system",
2094
+ "success",
2095
+ "Trading Started",
2096
+ "Agent is now actively trading."
2097
+ );
2098
+ this.sendRelayStatus();
2099
+ break;
2100
+ case "stop_trading":
2101
+ if (this.mode === "idle") {
2102
+ this.relay?.sendCommandResult(cmd.id, true, "Already idle");
2103
+ return;
2104
+ }
2105
+ this.mode = "idle";
2106
+ this.isRunning = false;
2107
+ console.log("Trading stopped via command center");
2108
+ this.relay?.sendCommandResult(cmd.id, true, "Trading stopped");
2109
+ this.relay?.sendMessage(
2110
+ "system",
2111
+ "info",
2112
+ "Trading Stopped",
2113
+ "Agent is now idle. Send start_trading to resume."
2114
+ );
2115
+ this.sendRelayStatus();
2116
+ break;
2117
+ case "update_risk_params": {
2118
+ const params = cmd.params || {};
2119
+ let updated = false;
2120
+ if (params.maxPositionSizeBps !== void 0) {
2121
+ const value = Number(params.maxPositionSizeBps);
2122
+ if (isNaN(value) || value < 100 || value > 1e4) {
2123
+ this.relay?.sendCommandResult(cmd.id, false, "maxPositionSizeBps must be 100-10000");
2124
+ break;
2125
+ }
2126
+ this.config.trading.maxPositionSizeBps = value;
2127
+ updated = true;
2128
+ }
2129
+ if (params.maxDailyLossBps !== void 0) {
2130
+ const value = Number(params.maxDailyLossBps);
2131
+ if (isNaN(value) || value < 50 || value > 5e3) {
2132
+ this.relay?.sendCommandResult(cmd.id, false, "maxDailyLossBps must be 50-5000");
2133
+ break;
2134
+ }
2135
+ this.config.trading.maxDailyLossBps = value;
2136
+ updated = true;
2137
+ }
2138
+ if (updated) {
2139
+ this.riskManager = new RiskManager(this.config.trading);
2140
+ console.log("Risk params updated via command center");
2141
+ this.relay?.sendCommandResult(cmd.id, true, "Risk parameters updated");
2142
+ this.relay?.sendMessage(
2143
+ "config_updated",
2144
+ "info",
2145
+ "Risk Parameters Updated",
2146
+ `Max position: ${this.config.trading.maxPositionSizeBps / 100}%, Max daily loss: ${this.config.trading.maxDailyLossBps / 100}%`
2147
+ );
2148
+ } else {
2149
+ this.relay?.sendCommandResult(cmd.id, false, "No valid parameters provided");
2150
+ }
2151
+ break;
2152
+ }
2153
+ case "update_trading_interval": {
2154
+ const intervalMs = Number(cmd.params?.intervalMs);
2155
+ if (intervalMs && intervalMs >= 1e3) {
2156
+ this.config.trading.tradingIntervalMs = intervalMs;
2157
+ console.log(`Trading interval updated to ${intervalMs}ms`);
2158
+ this.relay?.sendCommandResult(cmd.id, true, `Interval set to ${intervalMs}ms`);
2159
+ } else {
2160
+ this.relay?.sendCommandResult(cmd.id, false, "Invalid interval (minimum 1000ms)");
2161
+ }
2162
+ break;
2163
+ }
2164
+ case "create_vault": {
2165
+ const result = await this.createVault();
2166
+ this.relay?.sendCommandResult(
2167
+ cmd.id,
2168
+ result.success,
2169
+ result.success ? `Vault created: ${result.vaultAddress}` : result.error
2170
+ );
2171
+ if (result.success) {
2172
+ this.relay?.sendMessage(
2173
+ "vault_created",
2174
+ "success",
2175
+ "Vault Created",
2176
+ `Vault deployed at ${result.vaultAddress}`,
2177
+ { vaultAddress: result.vaultAddress }
2178
+ );
2179
+ }
2180
+ break;
2181
+ }
2182
+ case "refresh_status":
2183
+ this.sendRelayStatus();
2184
+ this.relay?.sendCommandResult(cmd.id, true, "Status refreshed");
2185
+ break;
2186
+ case "shutdown":
2187
+ console.log("Shutdown requested via command center");
2188
+ this.relay?.sendCommandResult(cmd.id, true, "Shutting down");
2189
+ this.relay?.sendMessage(
2190
+ "system",
2191
+ "info",
2192
+ "Shutting Down",
2193
+ "Agent is shutting down. Restart manually to reconnect."
2194
+ );
2195
+ await this.sleep(1e3);
2196
+ this.stop();
2197
+ break;
2198
+ default:
2199
+ console.warn(`Unknown command: ${cmd.type}`);
2200
+ this.relay?.sendCommandResult(cmd.id, false, `Unknown command: ${cmd.type}`);
2201
+ }
2202
+ } catch (error) {
2203
+ const message = error instanceof Error ? error.message : String(error);
2204
+ console.error(`Command ${cmd.type} failed:`, message);
2205
+ this.relay?.sendCommandResult(cmd.id, false, message);
2206
+ }
2207
+ }
2208
+ /**
2209
+ * Send current status to the relay
2210
+ */
2211
+ sendRelayStatus() {
2212
+ if (!this.relay) return;
2213
+ const vaultConfig = this.config.vault || { policy: "disabled" };
2214
+ const status = {
2215
+ mode: this.mode,
2216
+ agentId: String(this.config.agentId),
2217
+ wallet: this.client?.address,
2218
+ cycleCount: this.cycleCount,
2219
+ lastCycleAt: this.lastCycleAt,
2220
+ tradingIntervalMs: this.config.trading.tradingIntervalMs,
2221
+ portfolioValue: this.lastPortfolioValue,
2222
+ ethBalance: this.lastEthBalance,
2223
+ llm: {
2224
+ provider: this.config.llm.provider,
2225
+ model: this.config.llm.model || "default"
2226
+ },
2227
+ risk: this.riskManager?.getStatus(this.lastPortfolioValue) || {
2228
+ dailyPnL: 0,
2229
+ dailyLossLimit: 0,
2230
+ isLimitHit: false
2231
+ },
2232
+ vault: {
2233
+ policy: vaultConfig.policy,
2234
+ hasVault: false,
2235
+ vaultAddress: null
2236
+ }
2237
+ };
2238
+ this.relay.sendHeartbeat(status);
2239
+ }
2240
+ /**
2241
+ * Run a single trading cycle
2242
+ */
2243
+ async runCycle() {
2244
+ console.log(`
2245
+ --- Trading Cycle: ${(/* @__PURE__ */ new Date()).toISOString()} ---`);
2246
+ this.cycleCount++;
2247
+ this.lastCycleAt = Date.now();
2248
+ await this.checkVaultAutoCreation();
2249
+ const tokens = this.config.allowedTokens || this.getDefaultTokens();
2250
+ const marketData = await this.marketData.fetchMarketData(this.client.address, tokens);
2251
+ console.log(`Portfolio value: $${marketData.portfolioValue.toFixed(2)}`);
2252
+ this.lastPortfolioValue = marketData.portfolioValue;
2253
+ const nativeEthBal = marketData.balances[NATIVE_ETH.toLowerCase()] || BigInt(0);
2254
+ this.lastEthBalance = (Number(nativeEthBal) / 1e18).toFixed(6);
2255
+ this.checkFundsLow(marketData);
2256
+ let signals;
2257
+ try {
2258
+ signals = await this.strategy(marketData, this.llm, this.config);
2259
+ } catch (error) {
2260
+ const message = error instanceof Error ? error.message : String(error);
2261
+ console.error("LLM/strategy error:", message);
2262
+ this.relay?.sendMessage(
2263
+ "llm_error",
2264
+ "error",
2265
+ "Strategy Error",
2266
+ message
2267
+ );
2268
+ return;
2269
+ }
2270
+ console.log(`Strategy generated ${signals.length} signals`);
2271
+ const filteredSignals = this.riskManager.filterSignals(signals, marketData);
2272
+ console.log(`${filteredSignals.length} signals passed risk checks`);
2273
+ if (this.riskManager.getStatus(marketData.portfolioValue).isLimitHit) {
2274
+ this.relay?.sendMessage(
2275
+ "risk_limit_hit",
2276
+ "warning",
2277
+ "Risk Limit Hit",
2278
+ `Daily loss limit reached: $${this.riskManager.getStatus(marketData.portfolioValue).dailyPnL.toFixed(2)}`
2279
+ );
2280
+ }
2281
+ if (filteredSignals.length > 0) {
2282
+ const results = await this.executor.executeAll(filteredSignals);
2283
+ for (const result of results) {
2284
+ if (result.success) {
2285
+ console.log(`Trade executed: ${result.signal.action} - ${result.txHash}`);
2286
+ const feeCostBps = 5;
2287
+ const signalPrice = marketData.prices[result.signal.tokenIn.toLowerCase()] || 0;
2288
+ const tokenDecimals = result.signal.tokenIn.toLowerCase() === "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913" ? 6 : 18;
2289
+ const amountUSD = Number(result.signal.amountIn) / Math.pow(10, tokenDecimals) * signalPrice;
2290
+ const feeCostUSD = amountUSD * feeCostBps / 1e4;
2291
+ this.riskManager.updatePnL(-feeCostUSD);
2292
+ this.relay?.sendMessage(
2293
+ "trade_executed",
2294
+ "success",
2295
+ "Trade Executed",
2296
+ `${result.signal.action.toUpperCase()}: ${result.signal.reasoning || "No reason provided"}`,
2297
+ {
2298
+ action: result.signal.action,
2299
+ txHash: result.txHash,
2300
+ tokenIn: result.signal.tokenIn,
2301
+ tokenOut: result.signal.tokenOut
2302
+ }
2303
+ );
2304
+ } else {
2305
+ console.warn(`Trade failed: ${result.error}`);
2306
+ this.relay?.sendMessage(
2307
+ "trade_failed",
2308
+ "error",
2309
+ "Trade Failed",
2310
+ result.error || "Unknown error",
2311
+ { action: result.signal.action }
2312
+ );
2313
+ }
2314
+ }
2315
+ }
2316
+ this.sendRelayStatus();
2317
+ }
2318
+ /**
2319
+ * Check if ETH balance is below threshold and notify
2320
+ */
2321
+ checkFundsLow(marketData) {
2322
+ if (!this.relay) return;
2323
+ const ethBalance = marketData.balances[NATIVE_ETH.toLowerCase()] || BigInt(0);
2324
+ const ethAmount = Number(ethBalance) / 1e18;
2325
+ if (ethAmount < FUNDS_LOW_THRESHOLD) {
2326
+ this.relay.sendMessage(
2327
+ "funds_low",
2328
+ "warning",
2329
+ "Low Funds",
2330
+ `ETH balance is ${ethAmount.toFixed(6)} ETH. Fund your trading wallet to continue trading.`,
2331
+ {
2332
+ ethBalance: ethAmount.toFixed(6),
2333
+ wallet: this.client.address,
2334
+ threshold: FUNDS_LOW_THRESHOLD
2335
+ }
2336
+ );
2337
+ }
2338
+ }
2339
+ /**
2340
+ * Check for vault auto-creation based on policy
2341
+ */
2342
+ async checkVaultAutoCreation() {
2343
+ const now = Date.now();
2344
+ if (now - this.lastVaultCheck < this.VAULT_CHECK_INTERVAL) {
2345
+ return;
2346
+ }
2347
+ this.lastVaultCheck = now;
2348
+ const result = await this.vaultManager.checkAndAutoCreateVault();
2349
+ switch (result.action) {
2350
+ case "created":
2351
+ console.log(`Vault created automatically: ${result.vaultAddress}`);
2352
+ this.relay?.sendMessage(
2353
+ "vault_created",
2354
+ "success",
2355
+ "Vault Auto-Created",
2356
+ `Vault deployed at ${result.vaultAddress}`,
2357
+ { vaultAddress: result.vaultAddress }
2358
+ );
2359
+ break;
2360
+ case "already_exists":
2361
+ break;
2362
+ case "skipped":
2363
+ break;
2364
+ case "not_qualified":
2365
+ console.log(`Vault auto-creation pending: ${result.reason}`);
2366
+ break;
2367
+ }
2368
+ }
2369
+ /**
2370
+ * Stop the agent process completely
2371
+ */
2372
+ stop() {
2373
+ console.log("Stopping agent...");
2374
+ this.isRunning = false;
2375
+ this.processAlive = false;
2376
+ this.mode = "idle";
2377
+ if (this.relay) {
2378
+ this.relay.disconnect();
2379
+ }
2380
+ }
2381
+ /**
2382
+ * Get RPC URL based on network
2383
+ */
2384
+ getRpcUrl() {
2385
+ if (this.config.network === "mainnet") {
2386
+ return "https://mainnet.base.org";
2387
+ }
2388
+ return "https://sepolia.base.org";
2389
+ }
2390
+ /**
2391
+ * Default tokens to track
2392
+ */
2393
+ getDefaultTokens() {
2394
+ if (this.config.network === "mainnet") {
2395
+ return [
2396
+ "0x4200000000000000000000000000000000000006",
2397
+ // WETH
2398
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
2399
+ // USDC
2400
+ ];
2401
+ }
2402
+ return [
2403
+ "0x4200000000000000000000000000000000000006"
2404
+ // WETH
2405
+ ];
2406
+ }
2407
+ sleep(ms) {
2408
+ return new Promise((resolve) => setTimeout(resolve, ms));
2409
+ }
2410
+ /**
2411
+ * Get current status
2412
+ */
2413
+ getStatus() {
2414
+ const vaultConfig = this.config.vault || { policy: "disabled" };
2415
+ return {
2416
+ isRunning: this.isRunning,
2417
+ mode: this.mode,
2418
+ agentId: Number(this.config.agentId),
2419
+ wallet: this.client?.address || "not initialized",
2420
+ llm: {
2421
+ provider: this.config.llm.provider,
2422
+ model: this.config.llm.model || "default"
2423
+ },
2424
+ configHash: this.configHash || "not initialized",
2425
+ risk: this.riskManager?.getStatus(this.lastPortfolioValue) || { dailyPnL: 0, dailyLossLimit: 0, isLimitHit: false },
2426
+ vault: {
2427
+ policy: vaultConfig.policy,
2428
+ hasVault: false,
2429
+ // Updated async via getVaultStatus
2430
+ vaultAddress: null
2431
+ },
2432
+ relay: {
2433
+ connected: this.relay?.isConnected || false
2434
+ },
2435
+ cycleCount: this.cycleCount
2436
+ };
2437
+ }
2438
+ /**
2439
+ * Get detailed vault status (async)
2440
+ */
2441
+ async getVaultStatus() {
2442
+ if (!this.vaultManager) {
2443
+ return null;
2444
+ }
2445
+ return this.vaultManager.getVaultStatus();
2446
+ }
2447
+ /**
2448
+ * Manually trigger vault creation (for 'manual' policy)
2449
+ */
2450
+ async createVault() {
2451
+ if (!this.vaultManager) {
2452
+ return { success: false, error: "Vault manager not initialized" };
2453
+ }
2454
+ const policy = this.config.vault?.policy || "disabled";
2455
+ if (policy === "disabled") {
2456
+ return { success: false, error: "Vault creation is disabled by policy" };
2457
+ }
2458
+ return this.vaultManager.createVault();
2459
+ }
2460
+ };
2461
+
2462
+ // src/types.ts
2463
+ import { z } from "zod";
2464
+ var WalletSetupSchema = z.enum(["generate", "provide"]);
2465
+ var LLMProviderSchema = z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama", "custom"]);
2466
+ var LLMConfigSchema = z.object({
2467
+ provider: LLMProviderSchema,
2468
+ model: z.string().optional(),
2469
+ apiKey: z.string().optional(),
2470
+ endpoint: z.string().url().optional(),
2471
+ temperature: z.number().min(0).max(2).default(0.7),
2472
+ maxTokens: z.number().positive().default(4096)
2473
+ });
2474
+ var RiskUniverseSchema = z.enum(["core", "established", "derivatives", "emerging", "frontier"]);
2475
+ var TradingConfigSchema = z.object({
2476
+ timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
2477
+ maxPositionSizeBps: z.number().min(100).max(1e4).default(1e3),
2478
+ // 1-100%
2479
+ maxDailyLossBps: z.number().min(0).max(1e4).default(500),
2480
+ // 0-100%
2481
+ maxConcurrentPositions: z.number().min(1).max(100).default(5),
2482
+ tradingIntervalMs: z.number().min(1e3).default(6e4)
2483
+ // minimum 1 second
2484
+ });
2485
+ var VaultPolicySchema = z.enum([
2486
+ "disabled",
2487
+ // Never create a vault - trade with agent's own capital only
2488
+ "manual",
2489
+ // Only create vault when explicitly directed by owner
2490
+ "auto_when_qualified"
2491
+ // Automatically create vault when requirements are met
2492
+ ]);
2493
+ var VaultConfigSchema = z.object({
2494
+ // Policy for vault creation (asked during deployment)
2495
+ policy: VaultPolicySchema.default("manual"),
2496
+ // Default vault name (auto-generated from agent name if not set)
2497
+ defaultName: z.string().optional(),
2498
+ // Default vault symbol (auto-generated if not set)
2499
+ defaultSymbol: z.string().optional(),
2500
+ // Fee recipient for vault fees (default: agent wallet)
2501
+ feeRecipient: z.string().optional(),
2502
+ // When vault exists, trade through vault instead of direct trading
2503
+ // This pools depositors' capital with the agent's trades
2504
+ preferVaultTrading: z.boolean().default(true)
2505
+ });
2506
+ var WalletConfigSchema = z.object({
2507
+ setup: WalletSetupSchema.default("provide")
2508
+ }).optional();
2509
+ var RelayConfigSchema = z.object({
2510
+ enabled: z.boolean().default(false),
2511
+ apiUrl: z.string().url(),
2512
+ heartbeatIntervalMs: z.number().min(5e3).default(3e4)
2513
+ }).optional();
2514
+ var AgentConfigSchema = z.object({
2515
+ // Identity (from on-chain registration)
2516
+ agentId: z.union([z.number().positive(), z.string()]),
2517
+ name: z.string().min(3).max(32),
2518
+ // Network
2519
+ network: z.enum(["mainnet", "testnet"]).default("testnet"),
2520
+ // Wallet setup preference
2521
+ wallet: WalletConfigSchema,
2522
+ // LLM
2523
+ llm: LLMConfigSchema,
2524
+ // Trading parameters
2525
+ riskUniverse: RiskUniverseSchema.default("established"),
2526
+ trading: TradingConfigSchema.default({}),
2527
+ // Vault configuration (copy trading)
2528
+ vault: VaultConfigSchema.default({}),
2529
+ // Relay configuration (command center)
2530
+ relay: RelayConfigSchema,
2531
+ // Allowed tokens (addresses)
2532
+ allowedTokens: z.array(z.string()).optional()
2533
+ });
2534
+
2535
+ // src/config.ts
2536
+ import { readFileSync, existsSync as existsSync2 } from "fs";
2537
+ import { join as join2 } from "path";
2538
+ import { config as loadEnv } from "dotenv";
2539
+ function loadConfig(configPath) {
2540
+ loadEnv();
2541
+ const configFile = configPath || process.env.EXAGENT_CONFIG || "agent-config.json";
2542
+ const fullPath = configFile.startsWith("/") ? configFile : join2(process.cwd(), configFile);
2543
+ if (!existsSync2(fullPath)) {
2544
+ throw new Error(`Config file not found: ${fullPath}`);
2545
+ }
2546
+ const rawConfig = JSON.parse(readFileSync(fullPath, "utf-8"));
2547
+ const config = AgentConfigSchema.parse(rawConfig);
2548
+ const privateKey = process.env.EXAGENT_PRIVATE_KEY;
2549
+ if (privateKey && (!privateKey.startsWith("0x") || privateKey.length !== 66)) {
2550
+ throw new Error("EXAGENT_PRIVATE_KEY must be a valid 32-byte hex string starting with 0x");
2551
+ }
2552
+ const llmConfig = { ...config.llm };
2553
+ if (process.env.OPENAI_API_KEY && config.llm.provider === "openai") {
2554
+ llmConfig.apiKey = process.env.OPENAI_API_KEY;
2555
+ }
2556
+ if (process.env.ANTHROPIC_API_KEY && config.llm.provider === "anthropic") {
2557
+ llmConfig.apiKey = process.env.ANTHROPIC_API_KEY;
2558
+ }
2559
+ if (process.env.GOOGLE_AI_API_KEY && config.llm.provider === "google") {
2560
+ llmConfig.apiKey = process.env.GOOGLE_AI_API_KEY;
2561
+ }
2562
+ if (process.env.DEEPSEEK_API_KEY && config.llm.provider === "deepseek") {
2563
+ llmConfig.apiKey = process.env.DEEPSEEK_API_KEY;
2564
+ }
2565
+ if (process.env.MISTRAL_API_KEY && config.llm.provider === "mistral") {
2566
+ llmConfig.apiKey = process.env.MISTRAL_API_KEY;
2567
+ }
2568
+ if (process.env.GROQ_API_KEY && config.llm.provider === "groq") {
2569
+ llmConfig.apiKey = process.env.GROQ_API_KEY;
2570
+ }
2571
+ if (process.env.TOGETHER_API_KEY && config.llm.provider === "together") {
2572
+ llmConfig.apiKey = process.env.TOGETHER_API_KEY;
2573
+ }
2574
+ if (process.env.EXAGENT_LLM_URL) {
2575
+ llmConfig.endpoint = process.env.EXAGENT_LLM_URL;
2576
+ }
2577
+ if (process.env.EXAGENT_LLM_MODEL) {
2578
+ llmConfig.model = process.env.EXAGENT_LLM_MODEL;
2579
+ }
2580
+ const network = process.env.EXAGENT_NETWORK || config.network;
2581
+ return {
2582
+ ...config,
2583
+ llm: llmConfig,
2584
+ network,
2585
+ privateKey: privateKey || ""
2586
+ };
2587
+ }
2588
+ function validateConfig(config) {
2589
+ if (!config.privateKey) {
2590
+ throw new Error("Private key is required");
2591
+ }
2592
+ if (config.llm.provider !== "ollama" && !config.llm.apiKey) {
2593
+ throw new Error(`API key required for ${config.llm.provider} provider`);
2594
+ }
2595
+ if (config.llm.provider === "ollama" && !config.llm.endpoint) {
2596
+ config.llm.endpoint = "http://localhost:11434";
2597
+ }
2598
+ if (config.llm.provider === "custom" && !config.llm.endpoint) {
2599
+ throw new Error("Endpoint required for custom LLM provider");
2600
+ }
2601
+ if (!config.agentId || Number(config.agentId) <= 0) {
2602
+ throw new Error("Valid agent ID required");
2603
+ }
2604
+ }
2605
+ function createSampleConfig(agentId, name) {
2606
+ return {
2607
+ agentId,
2608
+ name,
2609
+ network: "testnet",
2610
+ llm: {
2611
+ provider: "openai",
2612
+ model: "gpt-4.1",
2613
+ temperature: 0.7,
2614
+ maxTokens: 4096
2615
+ },
2616
+ riskUniverse: "established",
2617
+ trading: {
2618
+ timeHorizon: "swing",
2619
+ maxPositionSizeBps: 1e3,
2620
+ maxDailyLossBps: 500,
2621
+ maxConcurrentPositions: 5,
2622
+ tradingIntervalMs: 6e4
2623
+ },
2624
+ vault: {
2625
+ // Default to manual - user must explicitly enable auto-creation
2626
+ policy: "manual",
2627
+ // Will use agent name for vault name if not set
2628
+ preferVaultTrading: true
2629
+ }
2630
+ };
2631
+ }
2632
+
2633
+ // src/secure-env.ts
2634
+ import * as crypto from "crypto";
2635
+ import * as fs from "fs";
2636
+ import * as path from "path";
2637
+ var ALGORITHM = "aes-256-gcm";
2638
+ var PBKDF2_ITERATIONS = 1e5;
2639
+ var SALT_LENGTH = 32;
2640
+ var IV_LENGTH = 16;
2641
+ var KEY_LENGTH = 32;
2642
+ var SENSITIVE_PATTERNS = [
2643
+ /PRIVATE_KEY$/i,
2644
+ /_API_KEY$/i,
2645
+ /API_KEY$/i,
2646
+ /_SECRET$/i,
2647
+ /^OPENAI_API_KEY$/i,
2648
+ /^ANTHROPIC_API_KEY$/i,
2649
+ /^GOOGLE_AI_API_KEY$/i,
2650
+ /^DEEPSEEK_API_KEY$/i,
2651
+ /^MISTRAL_API_KEY$/i,
2652
+ /^GROQ_API_KEY$/i,
2653
+ /^TOGETHER_API_KEY$/i
2654
+ ];
2655
+ function isSensitiveKey(key) {
2656
+ return SENSITIVE_PATTERNS.some((pattern) => pattern.test(key));
2657
+ }
2658
+ function deriveKey(passphrase, salt) {
2659
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
2660
+ }
2661
+ function encryptValue(value, key) {
2662
+ const iv = crypto.randomBytes(IV_LENGTH);
2663
+ const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
2664
+ let encrypted = cipher.update(value, "utf8", "hex");
2665
+ encrypted += cipher.final("hex");
2666
+ const tag = cipher.getAuthTag();
2667
+ return {
2668
+ iv: iv.toString("hex"),
2669
+ encrypted,
2670
+ tag: tag.toString("hex")
2671
+ };
2672
+ }
2673
+ function decryptValue(encrypted, key, iv, tag) {
2674
+ const decipher = crypto.createDecipheriv(
2675
+ ALGORITHM,
2676
+ key,
2677
+ Buffer.from(iv, "hex")
2678
+ );
2679
+ decipher.setAuthTag(Buffer.from(tag, "hex"));
2680
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
2681
+ decrypted += decipher.final("utf8");
2682
+ return decrypted;
2683
+ }
2684
+ function parseEnvFile(content) {
2685
+ const entries = [];
2686
+ for (const line of content.split("\n")) {
2687
+ const trimmed = line.trim();
2688
+ if (!trimmed || trimmed.startsWith("#")) continue;
2689
+ const eqIndex = trimmed.indexOf("=");
2690
+ if (eqIndex === -1) continue;
2691
+ const key = trimmed.slice(0, eqIndex).trim();
2692
+ let value = trimmed.slice(eqIndex + 1).trim();
2693
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
2694
+ value = value.slice(1, -1);
2695
+ }
2696
+ if (key && value) {
2697
+ entries.push({ key, value });
2698
+ }
2699
+ }
2700
+ return entries;
2701
+ }
2702
+ function encryptEnvFile(envPath, passphrase, deleteOriginal = false) {
2703
+ if (!fs.existsSync(envPath)) {
2704
+ throw new Error(`File not found: ${envPath}`);
2705
+ }
2706
+ const content = fs.readFileSync(envPath, "utf-8");
2707
+ const entries = parseEnvFile(content);
2708
+ if (entries.length === 0) {
2709
+ throw new Error("No environment variables found in file");
2710
+ }
2711
+ const salt = crypto.randomBytes(SALT_LENGTH);
2712
+ const key = deriveKey(passphrase, salt);
2713
+ const encryptedEntries = entries.map(({ key: envKey, value }) => {
2714
+ if (isSensitiveKey(envKey)) {
2715
+ const { iv, encrypted, tag } = encryptValue(value, key);
2716
+ return {
2717
+ key: envKey,
2718
+ value: encrypted,
2719
+ encrypted: true,
2720
+ iv,
2721
+ tag
2722
+ };
2723
+ }
2724
+ return {
2725
+ key: envKey,
2726
+ value,
2727
+ encrypted: false
2728
+ };
2729
+ });
2730
+ const encryptedEnv = {
2731
+ version: 1,
2732
+ salt: salt.toString("hex"),
2733
+ entries: encryptedEntries
2734
+ };
2735
+ const encPath = envPath + ".enc";
2736
+ fs.writeFileSync(encPath, JSON.stringify(encryptedEnv, null, 2), { mode: 384 });
2737
+ if (deleteOriginal) {
2738
+ fs.unlinkSync(envPath);
2739
+ }
2740
+ const sensitiveCount = encryptedEntries.filter((e) => e.encrypted).length;
2741
+ const plainCount = encryptedEntries.filter((e) => !e.encrypted).length;
2742
+ console.log(
2743
+ `Encrypted ${sensitiveCount} sensitive values (${plainCount} non-sensitive kept as plaintext)`
2744
+ );
2745
+ return encPath;
2746
+ }
2747
+ function decryptEnvFile(encPath, passphrase) {
2748
+ if (!fs.existsSync(encPath)) {
2749
+ throw new Error(`Encrypted env file not found: ${encPath}`);
2750
+ }
2751
+ const content = JSON.parse(fs.readFileSync(encPath, "utf-8"));
2752
+ if (content.version !== 1) {
2753
+ throw new Error(`Unsupported encrypted env version: ${content.version}`);
2754
+ }
2755
+ const salt = Buffer.from(content.salt, "hex");
2756
+ const key = deriveKey(passphrase, salt);
2757
+ const result = {};
2758
+ for (const entry of content.entries) {
2759
+ if (entry.encrypted) {
2760
+ if (!entry.iv || !entry.tag) {
2761
+ throw new Error(`Missing encryption metadata for ${entry.key}`);
2762
+ }
2763
+ try {
2764
+ result[entry.key] = decryptValue(entry.value, key, entry.iv, entry.tag);
2765
+ } catch {
2766
+ throw new Error(
2767
+ `Failed to decrypt ${entry.key}. Wrong passphrase or corrupted data.`
2768
+ );
2769
+ }
2770
+ } else {
2771
+ result[entry.key] = entry.value;
2772
+ }
2773
+ }
2774
+ return result;
2775
+ }
2776
+ function loadSecureEnv(basePath, passphrase) {
2777
+ const encPath = path.join(basePath, ".env.enc");
2778
+ const envPath = path.join(basePath, ".env");
2779
+ if (fs.existsSync(encPath)) {
2780
+ if (!passphrase) {
2781
+ passphrase = process.env.EXAGENT_PASSPHRASE;
2782
+ }
2783
+ if (!passphrase) {
2784
+ console.warn("");
2785
+ console.warn("WARNING: Found .env.enc but no passphrase provided.");
2786
+ console.warn(" Set EXAGENT_PASSPHRASE environment variable or");
2787
+ console.warn(" pass --passphrase when running the agent.");
2788
+ console.warn(" Falling back to plaintext .env file.");
2789
+ console.warn("");
2790
+ } else {
2791
+ const vars = decryptEnvFile(encPath, passphrase);
2792
+ for (const [key, value] of Object.entries(vars)) {
2793
+ process.env[key] = value;
2794
+ }
2795
+ return true;
2796
+ }
2797
+ }
2798
+ if (fs.existsSync(envPath)) {
2799
+ const content = fs.readFileSync(envPath, "utf-8");
2800
+ const entries = parseEnvFile(content);
2801
+ const sensitiveKeys = entries.filter(({ key }) => isSensitiveKey(key)).map(({ key }) => key);
2802
+ if (sensitiveKeys.length > 0) {
2803
+ console.warn("");
2804
+ console.warn("WARNING: Sensitive values stored in plaintext .env file:");
2805
+ for (const key of sensitiveKeys) {
2806
+ console.warn(` - ${key}`);
2807
+ }
2808
+ console.warn("");
2809
+ console.warn(' Run "npx @exagent/agent encrypt" to secure your keys.');
2810
+ console.warn("");
2811
+ }
2812
+ return false;
2813
+ }
2814
+ return false;
2815
+ }
2816
+
2817
+ export {
2818
+ BaseLLMAdapter,
2819
+ OpenAIAdapter,
2820
+ AnthropicAdapter,
2821
+ GoogleAdapter,
2822
+ DeepSeekAdapter,
2823
+ MistralAdapter,
2824
+ GroqAdapter,
2825
+ TogetherAdapter,
2826
+ OllamaAdapter,
2827
+ createLLMAdapter,
2828
+ loadStrategy,
2829
+ validateStrategy,
2830
+ STRATEGY_TEMPLATES,
2831
+ getStrategyTemplate,
2832
+ getAllStrategyTemplates,
2833
+ TradeExecutor,
2834
+ MarketDataService,
2835
+ RiskManager,
2836
+ VaultManager,
2837
+ RelayClient,
2838
+ AgentRuntime,
2839
+ LLMProviderSchema,
2840
+ LLMConfigSchema,
2841
+ RiskUniverseSchema,
2842
+ TradingConfigSchema,
2843
+ VaultPolicySchema,
2844
+ VaultConfigSchema,
2845
+ RelayConfigSchema,
2846
+ AgentConfigSchema,
2847
+ loadConfig,
2848
+ validateConfig,
2849
+ createSampleConfig,
2850
+ encryptEnvFile,
2851
+ decryptEnvFile,
2852
+ loadSecureEnv
2853
+ };