UNPKG

@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

464 lines โ€ข 22.6 kB
/** * Subscription Management Tools * Provides user-facing tools for managing hive-tools subscriptions, usage tracking, and upgrades */ import { z } from 'zod'; import { LicenseGate } from '../../core/license-gate.js'; // Schema definitions for subscription management tools export const CheckSubscriptionSchema = z.object({ detailed: z.boolean().default(false).describe('Show detailed usage breakdown and history') }); export const ViewUsageStatsSchema = z.object({ period: z.enum(['day', 'week', 'month', 'all']).default('month').describe('Time period for usage statistics'), format: z.enum(['summary', 'detailed', 'chart']).default('summary').describe('Output format for statistics') }); export const UpgradeSubscriptionSchema = z.object({ tier: z.enum(['basic', 'standard', 'premium', 'team']).describe('Target subscription tier to upgrade to'), billing: z.enum(['monthly', 'yearly']).default('monthly').describe('Billing frequency') }); export const PurchaseCreditsSchema = z.object({ pack: z.enum(['starter', 'value', 'power']).describe('Credit pack to purchase (25, 75, or 200 credits)'), quantity: z.number().min(1).max(10).default(1).describe('Number of credit packs to purchase') }); export const ManageAccountSchema = z.object({ action: z.enum(['view', 'update_email', 'change_password', 'view_devices', 'remove_device']).describe('Account management action'), email: z.string().email().optional().describe('New email address (for update_email action)'), device_id: z.string().optional().describe('Device ID to remove (for remove_device action)') }); // Tool exports export const checkSubscriptionToolName = 'check_subscription'; export const checkSubscriptionToolDescription = 'Check your current hive-tools subscription status, limits, and usage'; export const viewUsageStatsToolName = 'view_usage_stats'; export const viewUsageStatsToolDescription = 'View detailed usage statistics and conversation history'; export const upgradeSubscriptionToolName = 'upgrade_subscription'; export const upgradeSubscriptionToolDescription = 'Upgrade your hive-tools subscription to a higher tier'; export const purchaseCreditsToolName = 'purchase_credits'; export const purchaseCreditsToolDescription = 'Purchase additional consensus credits for extra conversations'; export const manageAccountToolName = 'manage_account'; export const manageAccountToolDescription = 'Manage your hive-tools account settings and devices'; // Implementation functions export async function runCheckSubscriptionTool(args) { try { const licenseGate = LicenseGate.getInstance(); const license = await licenseGate.checkFeatureAccess('subscription_status'); if (!license.valid) { return { subscription: { tier: 'free', status: 'No subscription configured', daily_limit: 10, monthly_limit: 100, trial_remaining: null }, usage: { daily_used: 0, monthly_used: 0, daily_percentage: 0, monthly_percentage: 0 }, actions: { can_upgrade: true, upgrade_recommended: false, next_reset: 'Tomorrow', checkout_url: process.env.HIVE_CHECKOUT_URL || 'https://hivetechs.io/pricing' }, message: '๐Ÿ“‹ **FREE TIER** - You are currently using the free tier of hive-tools.\n\n' + '**Current Limits:**\n' + 'โ€ข Daily: 5 conversations\n' + 'โ€ข Monthly: 100 conversations\n\n' + '**Available Features:**\n' + 'โ€ข โœ… Basic AI chat with single models\n' + 'โ€ข โœ… Provider configuration and testing\n' + 'โ€ข โŒ Multi-model consensus pipeline (Premium)\n' + 'โ€ข โŒ Advanced analytics and benchmarking (Premium)\n' + 'โ€ข โŒ Cost tracking and optimization (Premium)\n\n' + '**Upgrade Options:**\n' + 'โ€ข **Basic ($5/month)**: 50 daily, 1,000 monthly conversations\n' + 'โ€ข **Standard ($10/month)**: 100 daily, 2,000 monthly conversations\n' + 'โ€ข **Premium ($20/month)**: 200 daily, 4,000 monthly conversations\n\n' + '๐Ÿš€ **Start your 7-day FREE trial with unlimited access!**\n' + 'Use `upgrade_subscription` to get started.' }; } // Get detailed subscription info for paid users const subscriptionData = await licenseGate.getSubscriptionDetails(); const usageData = await licenseGate.getUsageStatistics(); const daily_percentage = Math.round((usageData.daily_used / subscriptionData.daily_limit) * 100); const monthly_percentage = Math.round((usageData.monthly_used / subscriptionData.monthly_limit) * 100); let status_message = ''; let upgrade_recommended = false; // Generate status message based on usage if (daily_percentage >= 90 || monthly_percentage >= 90) { status_message = '๐Ÿšจ **APPROACHING LIMITS** - Consider upgrading soon to avoid interruptions.'; upgrade_recommended = true; } else if (daily_percentage >= 75 || monthly_percentage >= 75) { status_message = 'โš ๏ธ **HIGH USAGE** - You\'re using your subscription heavily this period.'; upgrade_recommended = true; } else if (daily_percentage >= 50 || monthly_percentage >= 50) { status_message = '๐Ÿ“Š **MODERATE USAGE** - You\'re on track with your current plan.'; } else { status_message = 'โœ… **GOOD STATUS** - Plenty of conversations remaining this period.'; } const result = { subscription: { tier: subscriptionData.tier, status: subscriptionData.status, daily_limit: subscriptionData.daily_limit, monthly_limit: subscriptionData.monthly_limit, expires_at: subscriptionData.expires_at, trial_remaining: subscriptionData.trial_days_remaining }, usage: { daily_used: usageData.daily_used, monthly_used: usageData.monthly_used, daily_percentage, monthly_percentage, credits_remaining: usageData.credits_remaining || 0 }, actions: { can_upgrade: subscriptionData.tier !== 'premium' && subscriptionData.tier !== 'team', upgrade_recommended, next_reset: getNextResetTime(), checkout_url: generateCheckoutUrl(subscriptionData.tier) }, message: generateSubscriptionMessage(subscriptionData, usageData, status_message, args.detailed) }; return result; } catch (error) { return { error: `Failed to check subscription: ${error instanceof Error ? error.message : 'Unknown error'}`, message: 'โŒ **ERROR** - Unable to retrieve subscription information. Please check your internet connection and try again.' }; } } export async function runViewUsageStatsTool(args) { try { const licenseGate = LicenseGate.getInstance(); const usageData = await licenseGate.getUsageStatistics(args.period); if (args.format === 'chart') { return generateUsageChart(usageData, args.period); } else if (args.format === 'detailed') { return generateDetailedUsageReport(usageData, args.period); } else { return generateUsageSummary(usageData, args.period); } } catch (error) { return { error: `Failed to get usage statistics: ${error instanceof Error ? error.message : 'Unknown error'}`, message: 'โŒ **ERROR** - Unable to retrieve usage statistics.' }; } } export async function runUpgradeSubscriptionTool(args) { try { const licenseGate = LicenseGate.getInstance(); const currentSubscription = await licenseGate.getSubscriptionDetails(); // Generate checkout URL for the requested tier const checkoutUrl = generateUpgradeCheckoutUrl(args.tier, args.billing); // Calculate savings for yearly billing const monthlyPricing = { basic: 5, standard: 10, premium: 20, team: 50 }; const yearlyPricing = { basic: 50, // 2 months free standard: 100, // 2 months free premium: 200, // 2 months free team: 500 // 2 months free }; const monthly_cost = monthlyPricing[args.tier]; const yearly_cost = yearlyPricing[args.tier]; const yearly_savings = (monthly_cost * 12) - yearly_cost; const tierLimits = { basic: { daily: 50, monthly: 1000 }, standard: { daily: 100, monthly: 2000 }, premium: { daily: 200, monthly: 4000 }, team: { daily: 600, monthly: 12000 } }; const limits = tierLimits[args.tier]; return { upgrade: { from_tier: currentSubscription.tier, to_tier: args.tier, billing: args.billing, cost: args.billing === 'yearly' ? yearly_cost : monthly_cost, savings: args.billing === 'yearly' ? yearly_savings : 0, checkout_url: checkoutUrl }, new_limits: { daily_conversations: limits.daily, monthly_conversations: limits.monthly }, message: generateUpgradeMessage(currentSubscription.tier, args.tier, args.billing, monthly_cost, yearly_cost, yearly_savings, limits, checkoutUrl) }; } catch (error) { return { error: `Failed to generate upgrade: ${error instanceof Error ? error.message : 'Unknown error'}`, message: 'โŒ **ERROR** - Unable to generate upgrade options.' }; } } export async function runPurchaseCreditssTool(args) { try { const creditPacks = { starter: { credits: 25, price: 3, value_per_credit: 0.12, paddle_product: 'credits_starter' }, value: { credits: 75, price: 7, value_per_credit: 0.093, paddle_product: 'credits_value' }, power: { credits: 200, price: 15, value_per_credit: 0.075, paddle_product: 'credits_power' } }; const pack = creditPacks[args.pack]; const total_credits = pack.credits * args.quantity; const total_cost = pack.price * args.quantity; const checkout_url = `${process.env.HIVE_CHECKOUT_BASE_URL || 'https://hivetechs.io/checkout'}?product=${pack.paddle_product}&quantity=${args.quantity}&source=hive-tools`; return { credit_purchase: { pack_type: args.pack, quantity: args.quantity, credits_per_pack: pack.credits, total_credits, cost_per_pack: pack.price, total_cost, value_per_credit: pack.value_per_credit, checkout_url }, message: generateCreditPurchaseMessage(args.pack, args.quantity, pack, total_credits, total_cost, checkout_url) }; } catch (error) { return { error: `Failed to generate credit purchase: ${error instanceof Error ? error.message : 'Unknown error'}`, message: 'โŒ **ERROR** - Unable to generate credit purchase options.' }; } } export async function runManageAccountTool(args) { try { const licenseGate = LicenseGate.getInstance(); switch (args.action) { case 'view': const accountData = await licenseGate.getAccountDetails(); return { account: accountData, message: generateAccountViewMessage(accountData) }; case 'view_devices': const devices = await licenseGate.getRegisteredDevices(); return { devices, message: generateDevicesViewMessage(devices) }; case 'update_email': if (!args.email) { return { error: 'Email address is required for update_email action', message: 'โŒ **ERROR** - Please provide a new email address.' }; } const updateResult = await licenseGate.updateEmail(args.email); return { success: updateResult.success, message: updateResult.success ? `โœ… **EMAIL UPDATED** - Your email has been changed to ${args.email}. Please check your email for verification.` : `โŒ **UPDATE FAILED** - ${updateResult.error}` }; case 'remove_device': if (!args.device_id) { return { error: 'Device ID is required for remove_device action', message: 'โŒ **ERROR** - Please provide a device ID to remove.' }; } const removeResult = await licenseGate.removeDevice(args.device_id); return { success: removeResult.success, message: removeResult.success ? `โœ… **DEVICE REMOVED** - Device ${args.device_id} has been removed from your account.` : `โŒ **REMOVAL FAILED** - ${removeResult.error}` }; default: return { error: 'Unsupported account action', message: 'โŒ **ERROR** - Unsupported account management action.' }; } } catch (error) { return { error: `Failed to manage account: ${error instanceof Error ? error.message : 'Unknown error'}`, message: 'โŒ **ERROR** - Unable to manage account settings.' }; } } // Helper functions for message generation and data formatting function generateSubscriptionMessage(subscription, usage, status, detailed) { const tier_display = subscription.tier.charAt(0).toUpperCase() + subscription.tier.slice(1); let message = `๐Ÿ“‹ **${tier_display.toUpperCase()} TIER** - ${status}\n\n`; message += `**Current Usage:**\n`; message += `โ€ข Daily: ${usage.daily_used}/${subscription.daily_limit} conversations (${Math.round((usage.daily_used / subscription.daily_limit) * 100)}%)\n`; message += `โ€ข Monthly: ${usage.monthly_used}/${subscription.monthly_limit} conversations (${Math.round((usage.monthly_used / subscription.monthly_limit) * 100)}%)\n`; if (usage.credits_remaining > 0) { message += `โ€ข Bonus Credits: ${usage.credits_remaining} available\n`; } if (subscription.trial_days_remaining > 0) { message += `\n๐ŸŽฏ **TRIAL STATUS**: ${subscription.trial_days_remaining} days remaining\n`; } if (detailed) { message += `\n**Account Details:**\n`; message += `โ€ข Tier: ${tier_display}\n`; message += `โ€ข Status: ${subscription.status}\n`; message += `โ€ข Next Billing: ${new Date(subscription.expires_at).toLocaleDateString()}\n`; message += `\n**Available Features:**\n`; if (subscription.tier === 'free') { message += `โ€ข โœ… Basic AI chat with single models\n`; message += `โ€ข โœ… Provider configuration and testing\n`; message += `โ€ข โŒ Multi-model consensus pipeline\n`; message += `โ€ข โŒ Advanced analytics and benchmarking\n`; } else { message += `โ€ข โœ… Multi-model consensus pipeline\n`; message += `โ€ข โœ… Advanced analytics and benchmarking\n`; message += `โ€ข โœ… Cost tracking and optimization\n`; message += `โ€ข โœ… Priority support\n`; } } message += `\n๐Ÿ’ก **Quick Actions:**\n`; message += `โ€ข Check usage: \`view_usage_stats\`\n`; message += `โ€ข Buy credits: \`purchase_credits\`\n`; message += `โ€ข Upgrade plan: \`upgrade_subscription\`\n`; return message; } function generateUsageSummary(usage, period) { // Implementation for usage summary return { period, summary: `Usage summary for ${period}`, message: `๐Ÿ“Š **USAGE SUMMARY** - ${period.toUpperCase()}\n\nDetailed usage statistics would be displayed here.` }; } function generateDetailedUsageReport(usage, period) { // Implementation for detailed usage report return { period, detailed: true, message: `๐Ÿ“ˆ **DETAILED USAGE REPORT** - ${period.toUpperCase()}\n\nComprehensive usage analytics would be displayed here.` }; } function generateUsageChart(usage, period) { // Implementation for usage chart return { period, chart: true, message: `๐Ÿ“Š **USAGE CHART** - ${period.toUpperCase()}\n\nVisual usage chart would be displayed here.` }; } function generateUpgradeMessage(from, to, billing, monthly, yearly, savings, limits, url) { let message = `๐Ÿš€ **UPGRADE TO ${to.toUpperCase()}**\n\n`; message += `**Upgrade Summary:**\n`; message += `โ€ข From: ${from.charAt(0).toUpperCase() + from.slice(1)} tier\n`; message += `โ€ข To: ${to.charAt(0).toUpperCase() + to.slice(1)} tier\n`; message += `โ€ข Billing: ${billing.charAt(0).toUpperCase() + billing.slice(1)}\n`; if (billing === 'yearly') { message += `โ€ข Cost: $${yearly}/year (Save $${savings}!)\n`; } else { message += `โ€ข Cost: $${monthly}/month\n`; } message += `\n**New Limits:**\n`; message += `โ€ข Daily: ${limits.daily} conversations\n`; message += `โ€ข Monthly: ${limits.monthly} conversations\n`; message += `\n**What You Get:**\n`; message += `โ€ข โœ… Multi-model consensus pipeline\n`; message += `โ€ข โœ… Advanced analytics and cost tracking\n`; message += `โ€ข โœ… Performance benchmarking\n`; message += `โ€ข โœ… Priority support\n`; message += `โ€ข โœ… All current and future premium features\n`; if (billing === 'yearly') { message += `\n๐Ÿ’ฐ **YEARLY SAVINGS**: Pay yearly and save $${savings} (2 months free!)\n`; } message += `\n๐Ÿ›’ **Ready to upgrade?**\n`; message += `Click here to complete your upgrade: ${url}\n`; return message; } function generateCreditPurchaseMessage(pack, quantity, packData, totalCredits, totalCost, url) { const packName = pack.charAt(0).toUpperCase() + pack.slice(1); let message = `๐Ÿ’ณ **PURCHASE ${packName.toUpperCase()} CREDITS**\n\n`; message += `**Credit Pack Details:**\n`; message += `โ€ข Pack: ${packName} (${packData.credits} credits)\n`; message += `โ€ข Quantity: ${quantity} pack${quantity > 1 ? 's' : ''}\n`; message += `โ€ข Total Credits: ${totalCredits}\n`; message += `โ€ข Total Cost: $${totalCost}\n`; message += `โ€ข Value: ${(packData.value_per_credit * 100).toFixed(1)}ยข per credit\n`; message += `\n**How Credits Work:**\n`; message += `โ€ข Credits never expire\n`; message += `โ€ข Used only after daily/monthly limits reached\n`; message += `โ€ข Available across all your devices\n`; message += `โ€ข Stack with multiple purchases\n`; message += `\n๐Ÿ›’ **Ready to purchase?**\n`; message += `Complete your purchase: ${url}\n`; return message; } function generateAccountViewMessage(account) { let message = `๐Ÿ‘ค **ACCOUNT INFORMATION**\n\n`; message += `**Account Details:**\n`; message += `โ€ข Email: ${account.email}\n`; message += `โ€ข User ID: ${account.user_id}\n`; message += `โ€ข Member Since: ${new Date(account.created_at).toLocaleDateString()}\n`; message += `โ€ข Account Status: ${account.status}\n`; message += `\n**Subscription:**\n`; message += `โ€ข Current Tier: ${account.subscription_tier}\n`; message += `โ€ข Max Devices: ${account.max_devices}\n`; message += `โ€ข Active Devices: ${account.active_devices}\n`; message += `\n**Account Actions:**\n`; message += `โ€ข View devices: \`manage_account action:view_devices\`\n`; message += `โ€ข Update email: \`manage_account action:update_email email:new@email.com\`\n`; message += `โ€ข Remove device: \`manage_account action:remove_device device_id:DEVICE_ID\`\n`; return message; } function generateDevicesViewMessage(devices) { let message = `๐Ÿ–ฅ๏ธ **REGISTERED DEVICES**\n\n`; if (devices.length === 0) { message += `No devices registered to your account.\n`; } else { message += `**Active Devices (${devices.length}):**\n`; devices.forEach((device, index) => { message += `\n${index + 1}. **${device.device_name || 'Unnamed Device'}**\n`; message += ` โ€ข ID: ${device.id}\n`; message += ` โ€ข OS: ${device.os_type} ${device.os_version}\n`; message += ` โ€ข Last Active: ${new Date(device.last_active).toLocaleDateString()}\n`; message += ` โ€ข Registered: ${new Date(device.first_registered).toLocaleDateString()}\n`; }); message += `\n**Device Management:**\n`; message += `โ€ข Remove device: \`manage_account action:remove_device device_id:DEVICE_ID\`\n`; message += `โ€ข Maximum devices allowed: Based on your subscription tier\n`; } return message; } function getNextResetTime() { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); return tomorrow.toLocaleDateString(); } function generateCheckoutUrl(tier) { return `${process.env.HIVE_CHECKOUT_BASE_URL || 'https://hivetechs.io/checkout'}?tier=${tier}&source=hive-tools`; } function generateUpgradeCheckoutUrl(tier, billing) { // Use Paddle checkout - custom website integration const baseUrl = process.env.HIVE_CHECKOUT_BASE_URL || 'https://hivetechs.io/checkout'; const params = new URLSearchParams({ tier, billing, source: 'hive-tools' }); return `${baseUrl}?${params.toString()}`; } //# sourceMappingURL=subscription-management.js.map