@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
JavaScript
/**
* 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