Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async function example1_fetchAndAnalyzeMention() {
console.log(`\nThread has ${thread.replies.length + 1} posts`);

// Analyze with Grok
const analysis = await grok.analyzeAndDecide(mention.post.text, thread);
const analysis = await grok.analyzeAndDecide(mention.post.text, thread, mention.post.id);

console.log(`\nGrok's Decision:`);
console.log(` Action: ${analysis.action.type}`);
Expand Down Expand Up @@ -139,7 +139,7 @@ async function example5_batchProcessMentions() {
const thread = await xClient.fetchThread(conversationId);

if (thread) {
const analysis = await grok.analyzeAndDecide(mention.post.text, thread);
const analysis = await grok.analyzeAndDecide(mention.post.text, thread, mention.post.id);
console.log(` → Action: ${analysis.action.type} (${(analysis.confidence * 100).toFixed(0)}% confidence)`);

// In a real scenario, you might execute the action here
Expand Down
23 changes: 18 additions & 5 deletions src/services/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { GrokService } from '../services/grok.js';
import { AgentConfig, Mention, AgentAction } from '../types/index.js';

export class AutonomousAgent {
private static readonly MAX_PROCESSED_MENTIONS = 1000;

private xClient: XAPIClient;
private grokService: GrokService;
private config: AgentConfig;
Expand Down Expand Up @@ -90,10 +92,20 @@ export class AutonomousAgent {

console.log(`\n📬 [${new Date().toLocaleTimeString()}] Found ${newMentions.length} new mention(s)!\n`);

// Process each mention
for (const mention of newMentions) {
await this.processMention(mention);
this.processedMentions.add(mention.post.id);
// Process oldest first: X API returns newest-first, so iterate in reverse
for (let i = newMentions.length - 1; i >= 0; i--) {
await this.processMention(newMentions[i]);
this.processedMentions.add(newMentions[i].post.id);
}

// Prune oldest entries if Set grows too large
if (this.processedMentions.size > AutonomousAgent.MAX_PROCESSED_MENTIONS) {
const iter = this.processedMentions.values();
while (this.processedMentions.size > AutonomousAgent.MAX_PROCESSED_MENTIONS) {
const { value, done } = iter.next();
if (done) break;
this.processedMentions.delete(value);
}
}
} catch (error) {
console.error('❌ Error in processing loop:', error);
Expand Down Expand Up @@ -129,7 +141,8 @@ export class AutonomousAgent {
console.log('\n🤖 Analyzing with Grok AI...');
const analysis = await this.grokService.analyzeAndDecide(
mention.post.text,
thread
thread,
mention.post.id
);

console.log(` Action: ${analysis.action.type.toUpperCase()}`);
Expand Down
19 changes: 10 additions & 9 deletions src/services/grok.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ export class GrokService {
* Analyze a mention and thread context to determine appropriate action
* @param mention - The text content of the mention to analyze
* @param thread - The thread context including root post and replies
* @param mentionPostId - The ID of the specific mention post to target in replies
* @returns Analysis with recommended action
*/
async analyzeAndDecide(mention: string, thread: XThread): Promise<GrokAnalysis> {
async analyzeAndDecide(mention: string, thread: XThread, mentionPostId: string): Promise<GrokAnalysis> {
if (this.simulationMode) {
return this.simulateAnalysis(mention, thread);
return this.simulateAnalysis(mention, thread, mentionPostId);
}

try {
Expand Down Expand Up @@ -58,15 +59,15 @@ export class GrokService {
throw new Error(`Grok API error: ${response.status}`);
}

const data: any = await response.json();
const data = await response.json() as { choices: Array<{ message?: { content?: string } }> };
const analysisText = data.choices[0]?.message?.content || '';

// Use the root post ID from the thread, not the mention text
return this.parseGrokResponse(analysisText, thread.root_post.id);
// Use the specific mention post ID for targeted replies
return this.parseGrokResponse(analysisText, mentionPostId);
} catch (error) {
console.error('Error calling Grok API:', error);
// Fallback to simulation
return this.simulateAnalysis(mention, thread);
return this.simulateAnalysis(mention, thread, mentionPostId);
}
}

Expand Down Expand Up @@ -145,7 +146,7 @@ export class GrokService {
/**
* Simulate Grok analysis for testing
*/
private simulateAnalysis(mention: string, thread: XThread): GrokAnalysis {
private simulateAnalysis(mention: string, thread: XThread, mentionPostId: string): GrokAnalysis {
console.log('🤖 Simulated Grok Analysis:');
console.log(` Analyzing: "${mention}"`);

Expand All @@ -159,7 +160,7 @@ export class GrokService {
const analysis: GrokAnalysis = {
action: {
type: 'reply',
target_post_id: thread.root_post.id,
target_post_id: mentionPostId,
content: 'Thanks for reaching out! I\'ve analyzed your question and here\'s my insight: Based on the context, I\'d recommend exploring this topic further. Let me know if you need more specific information!',
reasoning: 'Detected a question, providing helpful response',
},
Expand All @@ -174,7 +175,7 @@ export class GrokService {
const analysis: GrokAnalysis = {
action: {
type: 'analyze',
target_post_id: thread.root_post.id,
target_post_id: mentionPostId,
reasoning: 'No clear action needed, just acknowledgment',
},
confidence: 0.7,
Expand Down
46 changes: 32 additions & 14 deletions src/services/xapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import { XPost, XThread, Mention, XAPIConfig } from '../types/index.js';

export class XAPIClient {
private static readonly DEFAULT_MAX_MENTIONS = 10;

private config: XAPIConfig;
private lastMentionId: string | null = null;
private simulationMode: boolean = false;
Expand Down Expand Up @@ -44,8 +46,16 @@ export class XAPIClient {
throw new Error('Failed to get user ID from response');
}

const params = new URLSearchParams({
max_results: XAPIClient.DEFAULT_MAX_MENTIONS.toString(),
expansions: 'author_id',
'tweet.fields': 'created_at,conversation_id,in_reply_to_user_id,referenced_tweets',
});
if (this.lastMentionId) {
params.set('since_id', this.lastMentionId);
}
const mentionsResponse = await this.makeXAPIRequest(
`https://api.twitter.com/2/users/${userId}/mentions?max_results=10&expansions=author_id&tweet.fields=created_at,conversation_id,in_reply_to_user_id,referenced_tweets`,
`https://api.twitter.com/2/users/${userId}/mentions?${params.toString()}`,
'GET'
);

Expand Down Expand Up @@ -77,7 +87,12 @@ export class XAPIClient {
'GET'
);

return this.parseThread(response.data || []);
if (!Array.isArray(response.data)) {
console.warn('Unexpected response shape from X API (thread): data is not an array');
return null;
}

return this.parseThread(response.data);
} catch (error) {
console.error('Error fetching thread:', error);
return null;
Expand Down Expand Up @@ -127,7 +142,10 @@ export class XAPIClient {
'GET'
);

return (response.data || []).map((tweet: any) => this.parsePost(tweet));
if (!Array.isArray(response.data)) {
return [];
}
return response.data.map((tweet: { [key: string]: unknown }) => this.parsePost(tweet));
} catch (error) {
console.error('Error searching tweets:', error);
return [];
Expand Down Expand Up @@ -160,28 +178,28 @@ export class XAPIClient {
return response.json();
}

private parseMentions(tweets: any[]): Mention[] {
private parseMentions(tweets: { created_at: string; [key: string]: unknown }[]): Mention[] {
return tweets.map((tweet) => ({
post: this.parsePost(tweet),
mentioned_at: new Date(tweet.created_at),
processed: false,
}));
}

private parsePost(tweet: any): XPost {
private parsePost(tweet: { [key: string]: unknown }): XPost {
return {
id: tweet.id,
text: tweet.text,
author_id: tweet.author_id,
author_username: tweet.username || 'unknown',
created_at: tweet.created_at,
conversation_id: tweet.conversation_id,
in_reply_to_user_id: tweet.in_reply_to_user_id,
referenced_tweets: tweet.referenced_tweets,
id: tweet.id as string,
text: tweet.text as string,
author_id: tweet.author_id as string,
author_username: (tweet.username as string) || 'unknown',
created_at: tweet.created_at as string,
conversation_id: tweet.conversation_id as string | undefined,
in_reply_to_user_id: tweet.in_reply_to_user_id as string | undefined,
referenced_tweets: tweet.referenced_tweets as Array<{ type: string; id: string }> | undefined,
};
}

private parseThread(tweets: any[]): XThread | null {
private parseThread(tweets: { created_at: string; [key: string]: unknown }[]): XThread | null {
if (tweets.length === 0) return null;

const sorted = tweets.sort((a, b) =>
Expand Down