this a repo that acts as a template for creating servelerless agents with cloudflare kv. It has scheduled jobs but also interacts with incoming webhooks. It has actions, which provide context for the llm. A user may message the llm on telegram and ask for financial data using /finan and the llm will respoond with a message geenrated using the data. scheduled jobs can also run actions. finan example action: /**
Financial Analysis Action
This action analyzes trending cryptocurrency pools on the Base network using the GeckoTerminal API.
It provides financial metrics and technical analysis including:
Market stats (FDV, Volume, Price Change)
Technical indicators (RSI, MACD, Momentum)
Volume trends
Trigger: Messages containing "/finan" or can set schedule in ./src/jobs/
*/
import { Action } from './base';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
// Get technical analysis for top performer
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
Assistant
User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Format the data for the LLM
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
/**
Fetches trending pools from GeckoTerminal API
Returns array of pool data or empty array if fetch fails
*/
private async fetchTrendingPools() {
try {
const response = await fetch(${this.GECKOTERMINAL_BASE_URL}/networks/base/trending_pools?page=1&duration=24h);
const data = await response.json();
return data.data || [];
} catch (error) {
Logger.error('Error fetching trending pools:', error);
return [];
}
}
/**
Finds the top performing pool based on 24h price change
*/
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
/**
Fetches and calculates technical indicators for a given pool
// Only calculate metrics if we have enough data
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
} catch (error) {
Logger.error('Error calculating technicals:', error);
return {} as TechnicalAnalysis;
}
}
/**
Calculates RSI using 14-period lookback
*/
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
code
let gains = 0;
code
let losses = 0;
// Calculate initial average gain and loss
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
// Calculate RSI using smoothed averages
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
[task]
Look through the codebase and understand the intent. embodying the persona and knowledge of a cf worker and TS expert, suggest a way to make the codebase more elegant and fit for purpose. remember users will fork this codebase to use as a template for their own agents, with its own actions etc. We want to keep it as modular as possible with all functionality in core. only things user should have to change is index.ts, adding their own actions, and character.json. If you think this could be done more elegantly without losing its capability, suggest the new codebase design with code changes and directory structure. make it elegant, simple, and lean, minimise duplicate code but not at the cost of capability (responding to webhooks, running scheduled jobs, hooking in actions if needed)
your changes must be easy to read and follow, so i can implement them, explain how it is more elegant, with less code and still maintains a good template.
I'll analyze the codebase and suggest improvements to make it more elegant while maintaining its core functionality. Here's my proposed restructuring:
Core Architectural Changes
code
/src
/core
/base
action.ts # Base action class
client.ts # Base client class for platforms
memory.ts # Memory management
/clients
telegram.ts
farcaster.ts
twitter.ts
agent.ts # Simplified agent class
types.ts
logger.ts
/actions # User-defined actions
index.ts # Action registry
/config
[Redacted Person]
/platform # Platform-specific handlers
webhook.ts # Combined webhook handler
index.ts # Main entry
Platform-specific logic is isolated in client classes
Core agent functionality is platform-agnostic
Actions are completely decoupled from platforms
Reduced Duplication:
Common client functionality in base class
Unified webhook handling
Centralized message transformation
Easier Extension:
New platforms just need to implement PlatformClient
Actions are self-contained and don't need platform knowledge
Clear interfaces for all components
Simpler User Experience:
Users only need to:
Add new actions in /actions
Configure character.json
Set environment variables
Implementation Notes
Move all platform initialization logic to client classes
Use dependency injection for better testing
Make memory system pluggable for different storage backends
Keep action system but make it more modular
The key improvement is the abstraction of platform-specific code into client classes while maintaining a clean core agent that handles the main logic. This makes the code more maintainable and easier to extend while keeping all the current functionality.
The template remains powerful but becomes more focused and easier to understand. Users can still add their own actions and scheduled jobs, but the core system is more elegant and has clearer boundaries.
Would you like me to expand on any particular aspect of these changes?
I apprecite you want to centralise api calls, but this will not work, as some data comes form api, but needs headers, cookies, or scrapes a webpage. check these example actions i mad ethat show you this:
/**
Financial Analysis Action
This action analyzes trending cryptocurrency pools on the Base network using the GeckoTerminal API.
It provides financial metrics and technical analysis including:
Market stats (FDV, Volume, Price Change)
Technical indicators (RSI, MACD, Momentum)
Volume trends
Trigger: Messages containing "/finan" or can set schedule in ./src/jobs/
*/
import { Action } from './base';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
// Get technical analysis for top performer
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
// Format the data for the LLM
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
/**
Fetches trending pools from GeckoTerminal API
Returns array of pool data or empty array if fetch fails
*/
private async fetchTrendingPools() {
try {
const response = await fetch(${this.GECKOTERMINAL_BASE_URL}/networks/base/trending_pools?page=1&duration=24h);
const data = await response.json();
return data.data || [];
} catch (error) {
Logger.error('Error fetching trending pools:', error);
return [];
}
}
/**
Finds the top performing pool based on 24h price change
*/
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
/**
Fetches and calculates technical indicators for a given pool
// Only calculate metrics if we have enough data
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
} catch (error) {
Logger.error('Error calculating technicals:', error);
return {} as TechnicalAnalysis;
}
}
/**
Calculates RSI using 14-period lookback
*/
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
code
let gains = 0;
code
let losses = 0;
// Calculate initial average gain and loss
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
// Calculate RSI using smoothed averages
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
if (!flowsData) {
return {
text: "Could not fetch ETF flows data.",
shouldSendMessage: true,
context: "Error fetching ETF data."
};
}
return {
text: flowsData,
shouldSendMessage: true,
context: `You are a cryptocurrency market analyst. Create a concise and brief analysis of the ETF flows data for both BTC and ETH ETFs. Focus on significant inflows/outflows and their potential market impact. Keep the response under 300 characters. No emojis. Use a professional tone. Include total flows for both BTC and ETH.`
};
} catch (error) {
Logger.error('Failed to analyze ETF flows:', error);
return {
text: "Sorry, I encountered an error while analyzing ETF flows.",
shouldSendMessage: true,
context: "Error occurred during ETF analysis."
};
}
}
/**
Fetches and analyzes ETF flows data
Can be called directly by scheduled jobs
*/
async getETFFlowsAnalysis(): Promise<string | null> {
try {
const [btcData, ethData] = await Promise.all([
this.fetchETFData('btc'),
this.fetchETFData('eth')
]);
const response = await fetch(urls[type]);
const text = await response.text();
// Split into lines
const lines = text.split('\n');
// Find the ticker line first (contains IBIT/FBTC for BTC or EETH/BRRR for ETH)
const tickerLine = type === 'btc'
? lines.find(line => line.includes('IBIT') || line.includes('FBTC'))
: lines.find(line => line.includes('ETHA') || line.includes('FETH'));
if (!tickerLine) {
Logger.error(`No ticker line found for ${type}`);
return null;
}
// Extract tickers
const tickers = tickerLine.split('|')
.map(t => t.trim())
.filter(Boolean);
// Find the first data line after the ticker line
let dataStartIndex = lines.indexOf(tickerLine);
let latestDataLine = '';
// Look for the first line with a date after the ticker line
for (let i = dataStartIndex; i < lines.length; i++) {
const line = lines[i];
if (line.includes('|')) {
const cells = line.split('|').map(cell => cell.trim());
// Check if this is a data line (has a date)
if (cells[1]?.match(/\d{2}\s+Dec\s+2024/)) {
latestDataLine = line;
break;
}
}
}
if (!latestDataLine) {
Logger.error(`No data line found for ${type}`);
return null;
}
// Parse the data line
const cells = latestDataLine.split('|').map(cell => cell.trim()).filter(Boolean);
const date = cells[0];
const flows: { [key: string]: number } = {};
let total = 0;
// Process each flow value
for (let i = 1; i < cells.length - 1; i++) {
let value = cells[i];
if (value === '-') continue;
// Remove commas and handle parentheses for negative numbers
value = value.replace(/,/g, '');
const flow = value.startsWith('(')
? -parseFloat(value.slice(1, -1))
: parseFloat(value);
if (!isNaN(flow)) {
// Map the column index to the correct ticker
const tickerIndex = i - 1;
if (tickerIndex < tickers.length) {
flows[tickers[tickerIndex]] = flow;
total += flow;
}
}
}
// Use the last cell as total if it's a valid number
const lastCell = cells[cells.length - 1];
if (lastCell && lastCell !== '-') {
const parsedTotal = parseFloat(lastCell.replace(/,/g, ''));
if (!isNaN(parsedTotal)) {
total = parsedTotal;
}
}
return { date, flows, total };
} catch (error) {
Logger.error(`Error fetching ${type} ETF data:`, error);
return null;
}
}
import { Logger } from '../core/logger';
import type { Env } from '../core/types';
export class SaraDataAction {
private env: Env;
code
setEnv(env: Env) {
this.env = env;
}
// Placeholder for future data gathering methods
async getMarketData(): Promise<string | null> {
// TODO: Implement real data gathering
Logger.info('SARA market data gathering not yet implemented');
return null;
}
async getEconomicData(): Promise<string | null> {
// TODO: Implement real data gathering
Logger.info('SARA economic data gathering not yet implemented');
return null;
}
}
[task]
rethink your approach. think from an elegant but simple and easy to read perspective. this prioritises suers who want to use the template, their ability to understand how to use it, and its elegant directory and code design. Dont sacrifice any current capability. make the scheduler and jobs elegant to define a new job in the jobs dir, but without the need for the other file. same for actions base and index. most logic should be in core.
You're right. Let me propose a more elegant and user-friendly restructuring that maintains all capabilities while making it simpler to understand and extend.
Here's the refined structure:
code
/src
/core
agent.ts # Core agent logic
memory.ts # Memory management
logger.ts # Logging utilities
types.ts # Shared types
platforms.ts # Platform client implementations
scheduler.ts # Simplified scheduler
/actions # User-defined actions
base.ts # Action base class
financial.ts # Example action
etf.ts # Example action
/jobs # Each file is a standalone job
market-update.ts # Example job
daily-stats.ts # Example job
/config
character.json # Agent personality
index.ts # Main entry
This structure maintains all current capabilities while making it much more intuitive for users to extend and modify the agent. The core functionality remains robust but is better organized, and adding new features becomes more straightforward.
Would you like me to elaborate on any part of this design?
constructor() {
super('macro', 'Analyzes global macro economic data');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/macro') ?? false;
}
private cleanTable(rawTable: string): EconomicData[] {
const lines = rawTable.split('\n');
const data: EconomicData[] = [];
// Find the start of the data table
const tableStartIndex = lines.findIndex(line => line.includes('| Country |'));
if (tableStartIndex === -1) return [];
// Skip the header and separator rows
let currentLine = tableStartIndex + 2;
// Process data rows
while (currentLine < lines.length) {
const line = lines[currentLine];
if (!line.includes('|') || line.includes('Trading Economics provides')) break;
const columns = line.split('|').map(col => col.trim());
if (columns.length < 10) {
currentLine++;
continue;
}
// Remove URLs and brackets from country name
const countryMatch = columns[1].match(/\[(.*?)\]/);
if (!countryMatch) {
currentLine++;
continue;
}
const country = countryMatch[1];
// Convert string values to numbers, removing brackets and URLs
const cleanNumber = (str: string) => {
const match = str.match(/\[(.*?)\]/);
if (!match) return NaN;
return parseFloat(match[1]);
};
data.push({
country,
gdp: cleanNumber(columns[2]),
gdpGrowth: cleanNumber(columns[3]),
interestRate: cleanNumber(columns[4]),
inflationRate: cleanNumber(columns[5]),
joblessRate: cleanNumber(columns[6]),
govBudget: cleanNumber(columns[7]),
debtToGdp: cleanNumber(columns[8]),
currentAccount: cleanNumber(columns[9]),
population: cleanNumber(columns[10])
});
currentLine++;
}
return data;
}
private formatMacroData(data: EconomicData[]): string {
return data.map(country =>
`${country.country}:\n` +
`• GDP: $${country.gdp}B\n` +
`• GDP Growth: ${country.gdpGrowth}%\n` +
`• Interest Rate: ${country.interestRate}%\n` +
`• Inflation: ${country.inflationRate}%\n` +
`• Unemployment: ${country.joblessRate}%\n` +
`• Debt/GDP: ${country.debtToGdp}%\n` +
(country.currentAccount ? `• Current Account: ${country.currentAccount}%\n` : '') +
`• Population: ${country.population}M`
).join('\n\n');
}
async getMacroAnalysis(): Promise<string | null> {
try {
const response = await fetch(this.MACRO_URL);
if (!response.ok) {
throw new Error(`Failed to fetch macro data: ${response.statusText}`);
}
const rawText = await response.text();
const economicData = this.cleanTable(rawText);
if (economicData.length === 0) {
return null;
}
return this.formatMacroData(economicData);
} catch (error) {
Logger.error('Error getting macro analysis:', error);
return null;
}
}
async getRawMacroData(): Promise<string | null> {
return await this.getMacroAnalysis();
}
async execute(message: Message): Promise<ActionResult> {
try {
Logger.info('Starting macro economic analysis');
const macroData = await this.getMacroAnalysis();
if (!macroData) {
return {
text: "Could not fetch macro economic data.",
shouldSendMessage: true,
context: "Error fetching macro data."
};
}
// Ensure data fits within Telegram's limit (4096 chars)
const truncatedData = macroData.length > 2000 ? macroData.slice(0, 1997) + '...' : macroData;
return {
shouldSendMessage: true,
context: `You are a macro economic analyst. Analyze this global economic data and provide insights:
Please provide:
1. Overview of global economic conditions
2. Notable trends in GDP growth and inflation
3. Concerns or risks in specific regions
4. Comparison between major economies
5. Recommendations for economic outlook
Focus on key insights that would be relevant for investment and policy decisions.
Keep the response concise and under 2000 characters.
Data:
${truncatedData}`,
text: "Analyzing global economic data..."
};
} catch (error) {
Logger.error('Failed to analyze macro economic data:', error);
return {
text: "Sorry, I encountered an error while analyzing the economic data.",
shouldSendMessage: true,
context: "Error occurred during macro analysis."
};
}
}