@exagent/agent 0.1.8 → 0.1.9

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