@hivetechs/hive-ai
Version:
Real-time streaming AI consensus platform with HTTP+SSE MCP integration for Claude Code, VS Code, Cursor, and Windsurf - powered by OpenRouter's unified API
320 lines (277 loc) โข 14 kB
JavaScript
/**
* Credit Tracking Tool
* Specialized tool for monitoring and displaying credit usage and purchases
*/
import { z } from 'zod';
import { LicenseGate } from '../../core/license-gate.js';
export const creditTrackerToolName = 'credit_tracker';
export const creditTrackerToolDescription = 'Track your bonus credits, usage history, and purchase recommendations';
export const CreditTrackerSchema = z.object({
action: z.enum(['balance', 'history', 'projections', 'recommendations']).default('balance').describe('What credit information to display'),
period: z.enum(['week', 'month', 'quarter', 'all']).default('month').describe('Time period for history and projections')
});
export async function runCreditTrackerTool(args) {
try {
const licenseGate = LicenseGate.getInstance();
const subscription = await licenseGate.getSubscriptionDetails();
const usage = await licenseGate.getUsageStatistics();
let content = '';
switch (args.action) {
case 'balance':
content = generateCreditBalance(subscription, usage);
break;
case 'history':
content = generateCreditHistory(usage, args.period);
break;
case 'projections':
content = generateCreditProjections(subscription, usage, args.period);
break;
case 'recommendations':
content = generateCreditRecommendations(subscription, usage);
break;
default:
content = generateCreditBalance(subscription, usage);
}
return {
credit_info: content,
message: content
};
}
catch (error) {
return {
error: `Failed to get credit information: ${error instanceof Error ? error.message : 'Unknown error'}`,
message: 'โ **ERROR** - Unable to retrieve credit information.'
};
}
}
function generateCreditBalance(subscription, usage) {
const currentTier = subscription.tier || 'free';
const creditsRemaining = usage.credits_remaining || 0;
let content = `# ๐ณ Credit Balance Overview
## Current Status
**Tier**: ${currentTier.charAt(0).toUpperCase() + currentTier.slice(1)}
**Bonus Credits**: ${creditsRemaining} available
`;
if (currentTier === 'free') {
content += `## โน๏ธ Free Tier Notice
Bonus credits are not available on the free tier. When you reach your limits:
- **Daily**: ${subscription.daily_limit || 5} conversations
- **Monthly**: ${subscription.monthly_limit || 100} conversations
You'll need to wait for limits to reset or upgrade to a paid plan.
### ๐ Unlock Credits with Upgrade
Start your **7-day FREE trial** to get:
- Unlimited conversations during trial
- Bonus credits system after trial
- No interruptions when hitting limits
Use: \`upgrade_subscription tier:basic\``;
}
else {
// Paid tier - show credit details
content += `## ๐ฐ Credit Value
- **Cost per credit**: ~10ยข (average from credit packs)
- **Credit value**: $${(creditsRemaining * 0.10).toFixed(2)} worth of conversations
- **Never expire**: Credits roll over each month
## ๐ How Credits Work
1. **Automatic usage** when you hit daily/monthly limits
2. **Used before blocking** - seamless conversation continuation
3. **Shared across devices** - available on all your devices
4. **Stack with purchases** - multiple credit packs combine
## ๐ Current Usage vs. Limits
- **Daily**: ${usage.daily_used || 0}/${subscription.daily_limit || 0} (${Math.round(((usage.daily_used || 0) / (subscription.daily_limit || 1)) * 100)}%)
- **Monthly**: ${usage.monthly_used || 0}/${subscription.monthly_limit || 0} (${Math.round(((usage.monthly_used || 0) / (subscription.monthly_limit || 1)) * 100)}%)
${creditsRemaining > 0 ?
`โ
**You have ${creditsRemaining} credits** ready for when you need them!` :
`โ ๏ธ **No credits remaining** - consider purchasing credits before hitting limits`}
## Quick Actions
- **Purchase credits**: \`purchase_credits pack:value\`
- **View usage trends**: \`credit_tracker action:history\`
- **Get recommendations**: \`credit_tracker action:recommendations\`
- **See projections**: \`credit_tracker action:projections\``;
}
return content;
}
function generateCreditHistory(usage, period) {
// In a real implementation, this would pull historical credit usage data
// For now, we'll provide a template structure
return `# ๐ Credit Usage History (${period.toUpperCase()})
## Recent Credit Activity
*Note: Detailed credit history requires backend integration*
### This ${period.charAt(0).toUpperCase() + period.slice(1)}
- **Credits used**: Tracking not yet available
- **Credits purchased**: Tracking not yet available
- **Credits remaining**: ${usage.credits_remaining || 0}
## Usage Patterns
When historical data is available, you'll see:
- Daily credit consumption trends
- Peak usage times and days
- Credit efficiency metrics
- Subscription vs. credit cost analysis
## Enable Detailed Tracking
To get comprehensive credit history:
1. Ensure you're on a paid plan
2. Backend analytics will track all credit transactions
3. Usage patterns will be analyzed for optimization
**Current Status**: Basic tracking active
**Detailed History**: Coming soon with full backend integration
## Alternative Tracking
For now, you can monitor credits with:
- \`usage_display\` - Current credit balance
- \`credit_tracker action:balance\` - Detailed credit status
- \`check_subscription detailed:true\` - Full account overview`;
}
function generateCreditProjections(subscription, usage, period) {
const currentTier = subscription.tier || 'free';
if (currentTier === 'free') {
return `# ๐ฎ Credit Projections
## Free Tier Notice
Credit projections are not available on the free tier since credits aren't included.
### Upgrade to Access Projections
With a paid plan, you'll get:
- **Usage trend analysis** based on your conversation patterns
- **Credit consumption forecasts** for the next month/quarter
- **Smart purchase recommendations** to avoid running out
- **Cost optimization suggestions** (credits vs. plan upgrades)
๐ **Start your free trial**: \`upgrade_subscription tier:basic\``;
}
// For paid tiers, provide basic projections
const dailyUsed = usage.daily_used || 0;
const monthlyUsed = usage.monthly_used || 0;
const dailyLimit = subscription.daily_limit || 0;
const monthlyLimit = subscription.monthly_limit || 0;
const creditsRemaining = usage.credits_remaining || 0;
// Calculate average daily usage (if we have monthly data)
const daysInMonth = new Date().getDate(); // Days elapsed this month
const avgDailyUsage = daysInMonth > 0 ? monthlyUsed / daysInMonth : dailyUsed;
// Project how many days until limits are regularly hit
const daysUntilDailyLimit = dailyLimit > 0 && avgDailyUsage > 0 ?
Math.ceil(dailyLimit / avgDailyUsage) : Infinity;
// Estimate credit consumption if current usage continues
const projectedMonthlyOverage = Math.max(0, (avgDailyUsage * 30) - monthlyLimit);
const projectedCreditsNeeded = Math.ceil(projectedMonthlyOverage);
return `# ๐ฎ Credit Usage Projections (${period.toUpperCase()})
## Usage Analysis
**Current daily average**: ${avgDailyUsage.toFixed(1)} conversations
**Monthly pace**: ${(avgDailyUsage * 30).toFixed(0)} conversations
**Current credits**: ${creditsRemaining}
## Projections Based on Current Usage
### ${period === 'week' ? 'Next Week' : period === 'month' ? 'Next Month' : 'Next Quarter'}
${projectedCreditsNeeded > 0 ?
`- **Estimated credit usage**: ${projectedCreditsNeeded} credits
- **Current credit buffer**: ${creditsRemaining >= projectedCreditsNeeded ? 'โ
Sufficient' : 'โ ๏ธ May need more'}
- **Recommended action**: ${creditsRemaining < projectedCreditsNeeded ? 'Purchase credits soon' : 'Credits sufficient for current usage'}` :
`- **Estimated credit usage**: 0 credits (staying within limits)
- **Current credit buffer**: ${creditsRemaining} credits (good buffer)
- **Recommended action**: Continue current usage patterns`}
## Smart Recommendations
${projectedCreditsNeeded > creditsRemaining ?
`๐ **Consider purchasing**: ${Math.ceil((projectedCreditsNeeded - creditsRemaining) / 25)} credit pack(s)
๐ก **Alternative**: Upgrade to ${subscription.tier === 'basic' ? 'Standard' : subscription.tier === 'standard' ? 'Premium' : 'Team'} tier for higher limits` :
`โ
**You're all set** for the next ${period}
๐ก **Tip**: Monitor usage with \`usage_display\` to stay on track`}
## Accuracy Note
Projections are based on recent usage patterns and may vary with:
- Changes in conversation frequency
- Different types of usage (consensus vs. single model)
- Seasonal usage variations
**Refine projections**: Use \`credit_tracker action:history\` to analyze trends`;
}
function generateCreditRecommendations(subscription, usage) {
const currentTier = subscription.tier || 'free';
const creditsRemaining = usage.credits_remaining || 0;
const dailyUsed = usage.daily_used || 0;
const monthlyUsed = usage.monthly_used || 0;
const dailyLimit = subscription.daily_limit || 0;
const monthlyLimit = subscription.monthly_limit || 0;
if (currentTier === 'free') {
return `# ๐ก Credit Recommendations
## Free Tier - No Credits Available
You're currently on the free tier, which doesn't include bonus credits.
### When You Hit Limits
- **Daily**: ${dailyLimit} conversations
- **Monthly**: ${monthlyLimit} conversations
- **Result**: Conversations stop until limits reset
### Recommended Solutions
1. **๐ Upgrade to Basic ($5/month)**
- 10x more conversations (50 daily, 1,000 monthly)
- Bonus credits system unlocked
- Multi-model consensus pipeline
- Start with 7-day FREE trial
2. **โฐ Time-based Management**
- Spread conversations throughout the day
- Plan important queries for early in the day
- Use \`usage_display\` to monitor limits
3. **๐ฏ Optimize Usage**
- Use free tools (provider config, testing) without limits
- Save premium features for most important queries
**Best recommendation**: Start your free trial with \`upgrade_subscription tier:basic\``;
}
// For paid tiers
const dailyUsageRate = dailyLimit > 0 ? (dailyUsed / dailyLimit) : 0;
const monthlyUsageRate = monthlyLimit > 0 ? (monthlyUsed / monthlyLimit) : 0;
const maxUsageRate = Math.max(dailyUsageRate, monthlyUsageRate);
let recommendations = `# ๐ก Smart Credit Recommendations
## Current Status Analysis
- **Tier**: ${currentTier.charAt(0).toUpperCase() + currentTier.slice(1)}
- **Credits**: ${creditsRemaining} remaining
- **Usage rate**: ${Math.round(maxUsageRate * 100)}% of limits
`;
if (maxUsageRate < 0.5) {
// Low usage
recommendations += `## ๐ You're in Great Shape!
Your usage is well within limits. Current recommendations:
โ
**No immediate action needed**
- Your current credits (${creditsRemaining}) provide good buffer
- Usage patterns suggest you rarely hit limits
๐ก **Optimization Tips**:
- Continue current usage patterns
- Consider credits as insurance for busy periods
- Monitor monthly trends for seasonal changes
๐ฏ **Future Planning**:
- If usage increases significantly, reassess in 30 days
- Credits are most valuable during high-activity periods`;
}
else if (maxUsageRate < 0.75) {
// Moderate usage
recommendations += `## โ๏ธ Moderate Usage Detected
You're using a good portion of your limits. Recommendations:
${creditsRemaining >= 25 ? 'โ
' : 'โ ๏ธ'} **Credit buffer**: ${creditsRemaining >= 25 ? 'Good' : 'Low'} (${creditsRemaining} credits)
๐ณ **Credit Strategy**:
${creditsRemaining < 25 ?
'- **Buy 1 Value Pack (75 credits)** for $7\n - Best value at 9.3ยข per credit\n - Provides 3-month buffer at current usage' :
'- Current credits should cover occasional overages\n - Monitor usage trends for 2-3 weeks'}
๐ **Alternative**: Consider upgrading to ${getNextTierName(currentTier)} for higher limits`;
}
else {
// High usage
recommendations += `## ๐จ High Usage - Action Recommended
You're approaching or hitting limits regularly. Priority recommendations:
${creditsRemaining >= 50 ? 'โ
' : 'โ'} **Credit emergency buffer**: ${creditsRemaining >= 50 ? 'Adequate' : 'Critical'} (${creditsRemaining} credits)
๐ฏ **Immediate Actions**:
${creditsRemaining < 50 ?
'1. **URGENT**: Buy Power Pack (200 credits) for $15\n - Prevents conversation interruptions\n - 7.5ยข per credit (best value)\n - 4-6 month supply at current usage\n\n2. **Consider upgrading** to ' + getNextTierName(currentTier) + ' tier\n - Higher limits reduce credit dependency\n - Better long-term value for heavy usage' :
'1. **Monitor closely** - you may need credits soon\n2. **Consider upgrading** to ' + getNextTierName(currentTier) + ' tier\n - Higher limits = fewer credit needs\n - Better value for heavy usage patterns'}
๐ฐ **Cost Analysis**:
- **Credits**: ~$10-15/month at current usage
- **Upgrade**: Higher tier might be more economical`;
}
recommendations += `
## Quick Actions
- **Check usage**: \`usage_display\`
- **Buy credits**: \`purchase_credits pack:value\`
- **Compare upgrades**: \`upgrade_subscription\`
- **View projections**: \`credit_tracker action:projections\`
## Questions?
Run \`freemium_help topic:credits\` for detailed credit system explanation`;
return recommendations;
}
function getNextTierName(currentTier) {
const tiers = {
free: 'Basic',
basic: 'Standard',
standard: 'Premium',
premium: 'Team',
team: 'Enterprise'
};
return tiers[currentTier] || 'Higher';
}
//# sourceMappingURL=credit-tracker.js.map