@exagent/agent 0.1.1 → 0.1.2

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,1816 @@
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(path) {
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(path).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(path);
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/runtime.ts
1359
+ import { ExagentClient, ExagentRegistry } from "@exagent/sdk";
1360
+ var AgentRuntime = class {
1361
+ config;
1362
+ client;
1363
+ llm;
1364
+ strategy;
1365
+ executor;
1366
+ riskManager;
1367
+ marketData;
1368
+ vaultManager;
1369
+ isRunning = false;
1370
+ configHash;
1371
+ lastVaultCheck = 0;
1372
+ VAULT_CHECK_INTERVAL = 3e5;
1373
+ // Check vault status every 5 minutes
1374
+ constructor(config) {
1375
+ this.config = config;
1376
+ }
1377
+ /**
1378
+ * Initialize the agent runtime
1379
+ */
1380
+ async initialize() {
1381
+ console.log(`Initializing agent: ${this.config.name} (ID: ${this.config.agentId})`);
1382
+ this.client = new ExagentClient({
1383
+ privateKey: this.config.privateKey,
1384
+ network: this.config.network
1385
+ });
1386
+ console.log(`Wallet: ${this.client.address}`);
1387
+ const agent = await this.client.registry.getAgent(BigInt(this.config.agentId));
1388
+ if (!agent) {
1389
+ throw new Error(`Agent ID ${this.config.agentId} not found on-chain. Please register first.`);
1390
+ }
1391
+ console.log(`Agent verified: ${agent.name}`);
1392
+ await this.ensureWalletLinked();
1393
+ console.log(`Initializing LLM: ${this.config.llm.provider}`);
1394
+ this.llm = await createLLMAdapter(this.config.llm);
1395
+ const llmMeta = this.llm.getMetadata();
1396
+ console.log(`LLM ready: ${llmMeta.provider} (${llmMeta.model})`);
1397
+ await this.syncConfigHash();
1398
+ this.strategy = await loadStrategy();
1399
+ this.executor = new TradeExecutor(this.client, this.config);
1400
+ this.riskManager = new RiskManager(this.config.trading);
1401
+ this.marketData = new MarketDataService(this.getRpcUrl());
1402
+ await this.initializeVaultManager();
1403
+ console.log("Agent initialized successfully");
1404
+ }
1405
+ /**
1406
+ * Initialize the vault manager based on config
1407
+ */
1408
+ async initializeVaultManager() {
1409
+ const vaultConfig = this.config.vault || { policy: "disabled", preferVaultTrading: false };
1410
+ this.vaultManager = new VaultManager({
1411
+ agentId: BigInt(this.config.agentId),
1412
+ agentName: this.config.name,
1413
+ network: this.config.network,
1414
+ walletKey: this.config.privateKey,
1415
+ vaultConfig
1416
+ });
1417
+ console.log(`Vault policy: ${vaultConfig.policy}`);
1418
+ const status = await this.vaultManager.getVaultStatus();
1419
+ if (status.hasVault) {
1420
+ console.log(`Vault exists: ${status.vaultAddress}`);
1421
+ console.log(`Vault TVL: ${Number(status.totalAssets) / 1e6} USDC`);
1422
+ } else {
1423
+ console.log("No vault exists for this agent");
1424
+ if (vaultConfig.policy === "auto_when_qualified") {
1425
+ if (status.canCreateVault) {
1426
+ console.log("Agent is qualified to create vault - will attempt on next check");
1427
+ } else {
1428
+ console.log(`Cannot create vault yet: ${status.cannotCreateReason}`);
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Ensure the current wallet is linked to the agent
1435
+ */
1436
+ async ensureWalletLinked() {
1437
+ const agentId = BigInt(this.config.agentId);
1438
+ const address = this.client.address;
1439
+ const isLinked = await this.client.registry.isLinkedWallet(agentId, address);
1440
+ if (!isLinked) {
1441
+ console.log("Wallet not linked, linking now...");
1442
+ const agent = await this.client.registry.getAgent(agentId);
1443
+ if (agent?.owner.toLowerCase() !== address.toLowerCase()) {
1444
+ throw new Error(
1445
+ `Cannot link wallet: ${address} is not the owner of agent ${this.config.agentId}. Owner is ${agent?.owner}`
1446
+ );
1447
+ }
1448
+ await this.client.registry.linkOwnWallet(agentId);
1449
+ console.log("Wallet linked successfully");
1450
+ } else {
1451
+ console.log("Wallet already linked");
1452
+ }
1453
+ }
1454
+ /**
1455
+ * Sync the LLM config hash to chain for epoch tracking
1456
+ * This ensures trades are attributed to the correct config epoch
1457
+ */
1458
+ async syncConfigHash() {
1459
+ const agentId = BigInt(this.config.agentId);
1460
+ const llmMeta = this.llm.getMetadata();
1461
+ this.configHash = ExagentRegistry.calculateConfigHash(llmMeta.provider, llmMeta.model);
1462
+ console.log(`Config hash: ${this.configHash}`);
1463
+ const onChainHash = await this.client.registry.getConfigHash(agentId);
1464
+ if (onChainHash !== this.configHash) {
1465
+ console.log("Config changed, updating on-chain...");
1466
+ await this.client.registry.updateConfig(agentId, this.configHash);
1467
+ const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
1468
+ console.log(`Config updated, new epoch started: ${newEpoch}`);
1469
+ } else {
1470
+ const currentEpoch = await this.client.registry.getCurrentEpoch(agentId);
1471
+ console.log(`Config hash matches on-chain (epoch ${currentEpoch})`);
1472
+ }
1473
+ }
1474
+ /**
1475
+ * Get the current config hash (for trade execution)
1476
+ */
1477
+ getConfigHash() {
1478
+ return this.configHash;
1479
+ }
1480
+ /**
1481
+ * Start the trading loop
1482
+ */
1483
+ async run() {
1484
+ if (this.isRunning) {
1485
+ throw new Error("Agent is already running");
1486
+ }
1487
+ this.isRunning = true;
1488
+ console.log("Starting trading loop...");
1489
+ console.log(`Interval: ${this.config.trading.tradingIntervalMs}ms`);
1490
+ while (this.isRunning) {
1491
+ try {
1492
+ await this.runCycle();
1493
+ } catch (error) {
1494
+ console.error("Error in trading cycle:", error);
1495
+ }
1496
+ await this.sleep(this.config.trading.tradingIntervalMs);
1497
+ }
1498
+ }
1499
+ /**
1500
+ * Run a single trading cycle
1501
+ */
1502
+ async runCycle() {
1503
+ console.log(`
1504
+ --- Trading Cycle: ${(/* @__PURE__ */ new Date()).toISOString()} ---`);
1505
+ await this.checkVaultAutoCreation();
1506
+ const tokens = this.config.allowedTokens || this.getDefaultTokens();
1507
+ const marketData = await this.marketData.fetchMarketData(this.client.address, tokens);
1508
+ console.log(`Portfolio value: $${marketData.portfolioValue.toFixed(2)}`);
1509
+ const signals = await this.strategy(marketData, this.llm, this.config);
1510
+ console.log(`Strategy generated ${signals.length} signals`);
1511
+ const filteredSignals = this.riskManager.filterSignals(signals, marketData);
1512
+ console.log(`${filteredSignals.length} signals passed risk checks`);
1513
+ if (filteredSignals.length > 0) {
1514
+ const results = await this.executor.executeAll(filteredSignals);
1515
+ for (const result of results) {
1516
+ if (result.success) {
1517
+ console.log(`Trade executed: ${result.signal.action} - ${result.txHash}`);
1518
+ } else {
1519
+ console.warn(`Trade failed: ${result.error}`);
1520
+ }
1521
+ }
1522
+ }
1523
+ }
1524
+ /**
1525
+ * Check for vault auto-creation based on policy
1526
+ */
1527
+ async checkVaultAutoCreation() {
1528
+ const now = Date.now();
1529
+ if (now - this.lastVaultCheck < this.VAULT_CHECK_INTERVAL) {
1530
+ return;
1531
+ }
1532
+ this.lastVaultCheck = now;
1533
+ const result = await this.vaultManager.checkAndAutoCreateVault();
1534
+ switch (result.action) {
1535
+ case "created":
1536
+ console.log(`\u{1F389} Vault created automatically: ${result.vaultAddress}`);
1537
+ break;
1538
+ case "already_exists":
1539
+ break;
1540
+ case "skipped":
1541
+ break;
1542
+ case "not_qualified":
1543
+ console.log(`Vault auto-creation pending: ${result.reason}`);
1544
+ break;
1545
+ }
1546
+ }
1547
+ /**
1548
+ * Stop the trading loop
1549
+ */
1550
+ stop() {
1551
+ console.log("Stopping agent...");
1552
+ this.isRunning = false;
1553
+ }
1554
+ /**
1555
+ * Get RPC URL based on network
1556
+ */
1557
+ getRpcUrl() {
1558
+ if (this.config.network === "mainnet") {
1559
+ return "https://mainnet.base.org";
1560
+ }
1561
+ return "https://sepolia.base.org";
1562
+ }
1563
+ /**
1564
+ * Default tokens to track
1565
+ */
1566
+ getDefaultTokens() {
1567
+ if (this.config.network === "mainnet") {
1568
+ return [
1569
+ "0x4200000000000000000000000000000000000006",
1570
+ // WETH
1571
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
1572
+ // USDC
1573
+ ];
1574
+ }
1575
+ return [
1576
+ "0x4200000000000000000000000000000000000006"
1577
+ // WETH
1578
+ ];
1579
+ }
1580
+ sleep(ms) {
1581
+ return new Promise((resolve) => setTimeout(resolve, ms));
1582
+ }
1583
+ /**
1584
+ * Get current status
1585
+ */
1586
+ getStatus() {
1587
+ const vaultConfig = this.config.vault || { policy: "disabled" };
1588
+ return {
1589
+ isRunning: this.isRunning,
1590
+ agentId: Number(this.config.agentId),
1591
+ wallet: this.client?.address || "not initialized",
1592
+ llm: {
1593
+ provider: this.config.llm.provider,
1594
+ model: this.config.llm.model || "default"
1595
+ },
1596
+ configHash: this.configHash || "not initialized",
1597
+ risk: this.riskManager?.getStatus() || { dailyPnL: 0, dailyLossLimit: 0, isLimitHit: false },
1598
+ vault: {
1599
+ policy: vaultConfig.policy,
1600
+ hasVault: false,
1601
+ // Updated async via getVaultStatus
1602
+ vaultAddress: null
1603
+ }
1604
+ };
1605
+ }
1606
+ /**
1607
+ * Get detailed vault status (async)
1608
+ */
1609
+ async getVaultStatus() {
1610
+ if (!this.vaultManager) {
1611
+ return null;
1612
+ }
1613
+ return this.vaultManager.getVaultStatus();
1614
+ }
1615
+ /**
1616
+ * Manually trigger vault creation (for 'manual' policy)
1617
+ */
1618
+ async createVault() {
1619
+ if (!this.vaultManager) {
1620
+ return { success: false, error: "Vault manager not initialized" };
1621
+ }
1622
+ const policy = this.config.vault?.policy || "disabled";
1623
+ if (policy === "disabled") {
1624
+ return { success: false, error: "Vault creation is disabled by policy" };
1625
+ }
1626
+ return this.vaultManager.createVault();
1627
+ }
1628
+ };
1629
+
1630
+ // src/types.ts
1631
+ import { z } from "zod";
1632
+ var WalletSetupSchema = z.enum(["generate", "provide"]);
1633
+ var LLMProviderSchema = z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama", "custom"]);
1634
+ var LLMConfigSchema = z.object({
1635
+ provider: LLMProviderSchema,
1636
+ model: z.string().optional(),
1637
+ apiKey: z.string().optional(),
1638
+ endpoint: z.string().url().optional(),
1639
+ temperature: z.number().min(0).max(2).default(0.7),
1640
+ maxTokens: z.number().positive().default(4096)
1641
+ });
1642
+ var RiskUniverseSchema = z.enum(["core", "established", "derivatives", "emerging", "frontier"]);
1643
+ var TradingConfigSchema = z.object({
1644
+ timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
1645
+ maxPositionSizeBps: z.number().min(100).max(1e4).default(1e3),
1646
+ // 1-100%
1647
+ maxDailyLossBps: z.number().min(0).max(1e4).default(500),
1648
+ // 0-100%
1649
+ maxConcurrentPositions: z.number().min(1).max(100).default(5),
1650
+ tradingIntervalMs: z.number().min(1e3).default(6e4)
1651
+ // minimum 1 second
1652
+ });
1653
+ var VaultPolicySchema = z.enum([
1654
+ "disabled",
1655
+ // Never create a vault - trade with agent's own capital only
1656
+ "manual",
1657
+ // Only create vault when explicitly directed by owner
1658
+ "auto_when_qualified"
1659
+ // Automatically create vault when requirements are met
1660
+ ]);
1661
+ var VaultConfigSchema = z.object({
1662
+ // Policy for vault creation (asked during deployment)
1663
+ policy: VaultPolicySchema.default("manual"),
1664
+ // Default vault name (auto-generated from agent name if not set)
1665
+ defaultName: z.string().optional(),
1666
+ // Default vault symbol (auto-generated if not set)
1667
+ defaultSymbol: z.string().optional(),
1668
+ // Fee recipient for vault fees (default: agent wallet)
1669
+ feeRecipient: z.string().optional(),
1670
+ // When vault exists, trade through vault instead of direct trading
1671
+ // This pools depositors' capital with the agent's trades
1672
+ preferVaultTrading: z.boolean().default(true)
1673
+ });
1674
+ var WalletConfigSchema = z.object({
1675
+ setup: WalletSetupSchema.default("provide")
1676
+ }).optional();
1677
+ var AgentConfigSchema = z.object({
1678
+ // Identity (from on-chain registration)
1679
+ agentId: z.union([z.number().positive(), z.string()]),
1680
+ name: z.string().min(3).max(32),
1681
+ // Network
1682
+ network: z.enum(["mainnet", "testnet"]).default("testnet"),
1683
+ // Wallet setup preference
1684
+ wallet: WalletConfigSchema,
1685
+ // LLM
1686
+ llm: LLMConfigSchema,
1687
+ // Trading parameters
1688
+ riskUniverse: RiskUniverseSchema.default("established"),
1689
+ trading: TradingConfigSchema.default({}),
1690
+ // Vault configuration (copy trading)
1691
+ vault: VaultConfigSchema.default({}),
1692
+ // Allowed tokens (addresses)
1693
+ allowedTokens: z.array(z.string()).optional()
1694
+ });
1695
+
1696
+ // src/config.ts
1697
+ import { readFileSync, existsSync as existsSync2 } from "fs";
1698
+ import { join as join2 } from "path";
1699
+ import { config as loadEnv } from "dotenv";
1700
+ function loadConfig(configPath) {
1701
+ loadEnv();
1702
+ const configFile = configPath || process.env.EXAGENT_CONFIG || "agent-config.json";
1703
+ const fullPath = configFile.startsWith("/") ? configFile : join2(process.cwd(), configFile);
1704
+ if (!existsSync2(fullPath)) {
1705
+ throw new Error(`Config file not found: ${fullPath}`);
1706
+ }
1707
+ const rawConfig = JSON.parse(readFileSync(fullPath, "utf-8"));
1708
+ const config = AgentConfigSchema.parse(rawConfig);
1709
+ const privateKey = process.env.EXAGENT_PRIVATE_KEY;
1710
+ if (!privateKey) {
1711
+ throw new Error("EXAGENT_PRIVATE_KEY not set in environment");
1712
+ }
1713
+ if (!privateKey.startsWith("0x") || privateKey.length !== 66) {
1714
+ throw new Error("EXAGENT_PRIVATE_KEY must be a valid 32-byte hex string starting with 0x");
1715
+ }
1716
+ const llmConfig = { ...config.llm };
1717
+ if (process.env.OPENAI_API_KEY && config.llm.provider === "openai") {
1718
+ llmConfig.apiKey = process.env.OPENAI_API_KEY;
1719
+ }
1720
+ if (process.env.ANTHROPIC_API_KEY && config.llm.provider === "anthropic") {
1721
+ llmConfig.apiKey = process.env.ANTHROPIC_API_KEY;
1722
+ }
1723
+ if (process.env.GOOGLE_AI_API_KEY && config.llm.provider === "google") {
1724
+ llmConfig.apiKey = process.env.GOOGLE_AI_API_KEY;
1725
+ }
1726
+ if (process.env.EXAGENT_LLM_URL) {
1727
+ llmConfig.endpoint = process.env.EXAGENT_LLM_URL;
1728
+ }
1729
+ if (process.env.EXAGENT_LLM_MODEL) {
1730
+ llmConfig.model = process.env.EXAGENT_LLM_MODEL;
1731
+ }
1732
+ const network = process.env.EXAGENT_NETWORK || config.network;
1733
+ return {
1734
+ ...config,
1735
+ llm: llmConfig,
1736
+ network,
1737
+ privateKey
1738
+ };
1739
+ }
1740
+ function validateConfig(config) {
1741
+ if (!config.privateKey) {
1742
+ throw new Error("Private key is required");
1743
+ }
1744
+ if (config.llm.provider !== "ollama" && !config.llm.apiKey) {
1745
+ throw new Error(`API key required for ${config.llm.provider} provider`);
1746
+ }
1747
+ if (config.llm.provider === "ollama" && !config.llm.endpoint) {
1748
+ config.llm.endpoint = "http://localhost:11434";
1749
+ }
1750
+ if (config.llm.provider === "custom" && !config.llm.endpoint) {
1751
+ throw new Error("Endpoint required for custom LLM provider");
1752
+ }
1753
+ if (!config.agentId || Number(config.agentId) <= 0) {
1754
+ throw new Error("Valid agent ID required");
1755
+ }
1756
+ }
1757
+ function createSampleConfig(agentId, name) {
1758
+ return {
1759
+ agentId,
1760
+ name,
1761
+ network: "testnet",
1762
+ llm: {
1763
+ provider: "openai",
1764
+ model: "gpt-4.1",
1765
+ temperature: 0.7,
1766
+ maxTokens: 4096
1767
+ },
1768
+ riskUniverse: "established",
1769
+ trading: {
1770
+ timeHorizon: "swing",
1771
+ maxPositionSizeBps: 1e3,
1772
+ maxDailyLossBps: 500,
1773
+ maxConcurrentPositions: 5,
1774
+ tradingIntervalMs: 6e4
1775
+ },
1776
+ vault: {
1777
+ // Default to manual - user must explicitly enable auto-creation
1778
+ policy: "manual",
1779
+ // Will use agent name for vault name if not set
1780
+ preferVaultTrading: true
1781
+ }
1782
+ };
1783
+ }
1784
+
1785
+ export {
1786
+ BaseLLMAdapter,
1787
+ OpenAIAdapter,
1788
+ AnthropicAdapter,
1789
+ GoogleAdapter,
1790
+ DeepSeekAdapter,
1791
+ MistralAdapter,
1792
+ GroqAdapter,
1793
+ TogetherAdapter,
1794
+ OllamaAdapter,
1795
+ createLLMAdapter,
1796
+ loadStrategy,
1797
+ validateStrategy,
1798
+ STRATEGY_TEMPLATES,
1799
+ getStrategyTemplate,
1800
+ getAllStrategyTemplates,
1801
+ TradeExecutor,
1802
+ RiskManager,
1803
+ MarketDataService,
1804
+ VaultManager,
1805
+ AgentRuntime,
1806
+ LLMProviderSchema,
1807
+ LLMConfigSchema,
1808
+ RiskUniverseSchema,
1809
+ TradingConfigSchema,
1810
+ VaultPolicySchema,
1811
+ VaultConfigSchema,
1812
+ AgentConfigSchema,
1813
+ loadConfig,
1814
+ validateConfig,
1815
+ createSampleConfig
1816
+ };