Wallet (Telephony Balance)
Audience: Engineering · Where in app: sidebar wallet pill; Packages → Wallet · Since: 2026-07
The "wallet" is not a new balance — it reuses SubscriptionModel.remaining_purchased_ai_credits (purchased AI-credit add-ons, 1 credit = $0.01). It funds telephony (number purchase, monthly rental, per-call Twilio cost), Agent K sell-side provider charges (per-step debits at call time incl. the LinkedIn/Unipile monthly seat renewal — see Agent K), and doubles as the overflow pool for AI usage.
Semantics
| Balance | Purpose | Cycle behavior |
|---|---|---|
remaining_ai_credits | Plan credits — AI-only, never touched by telephony | Reset to the plan allotment on renewal |
remaining_purchased_ai_credits | The wallet — telephony and AI fallback | Carries over — renewal jobs reset plan credits only |
- AI draw-down (
AITokensCreditJob) spends plan credits first, then falls into the wallet. A window whose net usage is negative (refund / cost adjustment) charges nothing and is carried inSubscriptionModel.ai_credits_carry, netted against later windows — see AI credits. - Telephony and Agent K debits come only from the wallet. The balance may go negative (burst / mid-call) — carried forward and paid down by the next top-up; the UI renders negative balances in red rather than clamping.
- Agent K debits go through
AgentKWalletService+lib/agentKPricing.js(super-admin sell prices, settings rowagent_k_provider_pricing; idempotentai_credit_logsrows; unpriced steps free; failed provider calls unbilled).
Signup grants and the welcome wallet
Commits 8a9076a89, 75d3c5119.
backend/app/lib/signupWalletGrant.js — amounts hardcoded in SIGNUP_GRANT_CREDITS (no admin setting):
| Grant | Credits | Lands in | Ledger source |
|---|---|---|---|
| New agency | 2000 ($20) | agencies.wallet_credits | agency_signup_grant |
| Agency's own site | 500 ($5) | own site's sub-account subscription | agency_self_account_signup_grant (AppSumo: moved from the agency wallet, agency_self_account_signup_transfer) |
| Direct customer | 1000 ($10) | company subscription | direct_customer_signup_grant |
- The $20 fires wherever an agency is created (
createSelfServeAgency,_createSelfServeAgencyWithoutCompany,_convertCompanyToAgency); never for AppSumo agencies. - The $10 fires from the
SubscriptionModelpost-save hook on the company's first subscription, only for companies created by signup (companies.signup_wallet_grant_pending: true, set inAuthController.createSignupCompany; cleared for AppSumo). Agency sub-accounts never get it; a converted direct customer keeps it and gets no $5. - One grant per company:
companies.signup_wallet_granted_atis claimed atomically and released if crediting fails. No email-verification or per-email check. - Welcome wallet (signups from 2026-11-11):
createSignupCompanyimmediately creates a wallet-only subscription (welcome_wallet: true,subscription_type: 'free',auto_payment: false,expiry_date: now, no package) so the $10 pays for onboarding training. The paywall,getActiveSubscriptionand the app's "active subscription" ignore it. Not created for certification-invite signups (welcome_wallet: !invite.code) or thefor_agencycompany of an "I'm an agency" signup. - Carry-over:
absorbWelcomeWallet(post-save hook on any new active subscription) marks the welcome walletinactiveand moves its balance — negative included — onto the new subscription (welcome_wallet_carry_over). Becoming an agency's own site instead leaves exactly $5: the excess is taken back, never below zero (agency_self_account_welcome_adjust). /user/mereturnscompany.welcome_wallet_credits/welcome_wallet_spendable; the sidebar pill tooltip reads "Welcome credit — covers your AI training and testing; what is left carries over when you subscribe" (or "…usable once you subscribe or start your trial" for older signups).
AppSumo's monthly allowance is a separate mechanism — see AppSumo Licensing.
Low-credit emails
Reworked in AITokensCreditJob:
- "Running low" (
ai-credits-low.html) fires once per allocation at theLOW_CREDITS_WARN_ATthreshold, guarded bySubscriptionModel.ai_credits_low_notified_at(stamped only after the mail is queued; cleared on a new grant). Suppressed when auto-recharge is on — a recharge would re-arm the warning and turn it into a recurring mail. - "Depleted" is deliberately NOT suppressed by auto-recharge: hitting zero with it enabled means the recharge itself failed (declined/missing card).
- Only one of the two sends in a given pass, never both.
Client wallet-low emails, wallet-only billing, AI spend guard
All new since the 2026-09-30 sync (af524c2cc, 78b06c863).
CompanyWalletLowJob(every 30 min): emails the client owner "Your wallet balance is running low" below the threshold (the client's ownbalance_auto_recharge.threshold_credits, else 500 = $5) and "Your wallet is empty" at ≤ $0; once each per dip (wallet_low_notified_at/wallet_empty_notified_at, stamped before sending, cleared on recovery). Agency clients also mail the agency owner ("<client>'s wallet is running low / empty",agency/client-wallet-low.html). Skipped when auto-recharge really covers the client (_autoRechargeCovers: card + active balance addon, or agency-funded with enough agency wallet, and nolast_failed_at). First run baselines every already-low client without mailing (settingcompany_wallet_low_baselined). Playgrounds and archived companies skipped. Twin ofAgencyWalletLowJob.- Wallet-only AI billing (
lib/walletOnlyBilling.js):companies.ai_credits_wallet_only === true→ plan AI-credit grants are written and then zeroed with their own ledger row, so all AI falls through to the wallet; an agency "Add AI Credits" transfer is redirected into the wallet. Rollout in testing: only via the super-admin togglePUT /company/admin/:company_id/wallet-only(list:GET /company/admin/wallet-only/companies) untilPOST /company/admin/wallet-only/backfill(apply) sets settingwallet_only_billing_auto— after that new companies, and existing ones on first wallet funding, flip automatically. No schema default on purpose (absent = not switched). - AI spend guard (
lib/aiSpendGuard.js, settings keyai_spend_guard, super-adminGET/PUT /admin/ai-spend-guard):spendable = plan + wallet − unbilled usage(ms-ai/unbilled-usage, wallet part × agency markup); allowed while above the floor (default −100 credits = −$1). Modesoff(default) /watch(recordsai_spend_guard_eventsonly) /on(callers pause AI). Fails open; 60 s caches. Callers: ms-aisrc/ai-spend/interceptor viaGET /internal/ai-spend/check/:company_id+/internal/ai-spend/mode, plus ms-comm and backend jobs. Tenant side:GET /ai-spend/status→AiPausedBanner.vue("Your AI is paused — your wallet is out of money…", owners/members only, re-checked every minute while paused);AiPausedNoticeJob(every 10 min, modeononly) emails the company once per pause (subscription/ai-paused.html, plusagency/ai-paused.htmlto the agency owner), stampai_paused_notified_at. - Agency wallet markup on AI (
d08f03d7d):AITokensCreditJobmultiplies the wallet-funded part of an agency client's AI usage bywalletMarkupMultiplier(plan credits stay 1×), recordingwallet_multiplier,plan_used_credits,wallet_debit_credits,charged_credits,agency_margin_creditson the ledger row — the same multiplier telephony and Agent K debits use. For such clients (agency sells wallet through its Stripe), buying a balance add-on on the platform is refused 409agency_wallet_topup("Wallet top-ups for this account are billed by your agency") — they top up viaPOST /client-billing/wallet/top-up, which returns{card_required: true}without a Connect card (ad7f179bc;AddOns.vuethen routes to Plan payment card).settings/billing/CardManagement.vuehides platform cards while/client-billingreturnswallet_via_agency(shown again once the plan has expired). See Agency client billing.
Wallet-low bars (25e2eb2b6)
lib/walletLowStatus.js — the in-app twin of CompanyWalletLowJob's rule, borrowing its _thresholdFor and _autoRechargeCovers: low = balance below the threshold, wallet ever used (read-only version of _walletEverUsed — nothing stamped), and auto-recharge won't cover it. days_left = balance ÷ average daily wallet debits over USAGE_WINDOW_DAYS (7) from ai_credit_logs (null with no spend, when empty, or when over 30 days — 7c5872c17). The UI phrases it "enough for about N days at (your) current usage".
Route (walletLowRoutes.js, passport) | What |
|---|---|
GET /wallet-low/status | Signed-in company: { low, empty, balance_credits, threshold_credits, days_left, contact_agency }. contact_agency = agency client (not the agency's own account) whose owner has no stripe_detail.customer_id — same own-card test as BalanceAutoRechargeJob._resolveBillingUser. Never fails (errors → low: false). |
GET /agencies/client-wallets/low | Agency's low/empty clients, most urgent first (archived, playground and the agency's own account excluded). Needs agency.subscription_payments, else []; non-agency users 403. |
Frontend: components/CompanyWalletLowBanner.vue in AppLayout (owners/members only; hidden when empty — AiPausedBanner takes over at $0; "Add funds" → /packages/wallet, or "Contact <agency>" copy when contact_agency); components/agency/AgencyClientWalletLowBanner.vue in AgencyLayout (one client named with Top up → TransferCreditsModal, several rolled into one bar with Review wallets → client list ?wallets=review). The bar's ✕ opens Remind me later (3 → 7 → 14 days, then stops) / Don't show again; either moves an AgencyWalletLowNotice into the sidebar account menu (bell on the account row, Show bar). A client newly at $0 breaks a snooze once, never "Don't show again". State is per agency in this browser only (useAgencyWalletLow, localStorage kk_agency_wallet_low_bar:<agencyId>). The client list also mounts AgencyLowWalletsPanel.vue ("N clients need a wallet top-up", per-row Top up, collapsible — localStorage agency-low-wallets-collapsed) and badges rows "Wallet empty" / "Wallet $X". Both refetch every 5 min and on focus; the company bar also re-checks when the subscription balance changes (immediately on a top-up, at most every 30 s while spending). Spec: test/wallet-low-status.spec.js.
Sales Replies mailbox seat (7b92facf3)
Connecting a Nox Sales Replies mailbox (Gmail/Outlook via Unipile) is billed like the Agent K LinkedIn seat, at the same super-admin unipile price (lib/agentKPricing, Admin → Agent K "Unipile account (LinkedIn or mailbox)"; code default $0, agency markup applies):
- Wallet checked before the connect link is issued (
WALLET_EMPTY, "Add funds to your wallet to connect a mailbox."). - Charged once per Unipile account on connect (
nox_mailbox_connect); renewed monthly bySalesRepliesMailboxFeeJob(schedular, hourly) fromnox_accounts.sales.next_fee_at(nox_mailbox_renewal). Unpaid → mailbox released withstatus_detail: 'renewal_unpaid'and an agency-branded email to the owner. - Reconnect reuses the same Unipile account — no new seat or charge. The status endpoint returns
{accounts, fee_usd};NoxEmailCardshows the fee and next charge only whenfee_usd > 0. - Wallet labels "Sales Replies · mailbox connected" / "Sales Replies · mailbox monthly". Mailbox and LinkedIn seats can't be priced separately.
AI-scrape gating
backend/app/lib/aiCredits.js — the single combined-balance rule (remaining_ai_credits + remaining_purchased_ai_credits > 0, active subscription required). Used by AutoScrapeJob (skip scheduled re-crawls for unfunded companies) and CompanyWebsiteController.scrape (reject manual "Add Website" scrapes with NO_CREDITS_MESSAGE); mirrors the balance test CompanyController applies for the UI so the scraper and the UI give the same verdict.
Gates
GET /internal/telephony/wallet/:company_id returns both flags:
has_telephony: wallet > 0— premium gate for buy/rental/calls.ai_available: plan > 0 || wallet > 0— AI falls back to the wallet.- Plus
markup_percent(see below) so ms-ai gates number purchase on the marked-up price and the frontend shows final prices.
Backend endpoints
backend/app/controllers/TelephonyWalletController.js, routes in
backend/app/routes/internalTelephonyRoutes.js, ms-ai → backend auth via apiKeyAuth (BACKEND_API_KEY):
| Route | What |
|---|---|
GET /internal/telephony/wallet/:company_id | Balance + gate flags + markup_percent |
POST /internal/telephony/debit | Idempotent debit: reserves idempotency_key (unique index on ai_credit_logs) before the $inc, so the 10-min call sweep / rental cron never double-charge |
POST /internal/telephony/notify | Rental suspend_warning (day 0/3/6) / released emails — backend owns templates + billing-user resolution |
Markup. credits in the debit body is the raw Twilio cost; the wallet is charged base × (1 + markup% / 100) with sub-cent precision (deliberately not rounded to a whole cent). Markup comes from the settings key telephony_markup_percent (default 0); margin_credits is recorded on the ledger row for revenue reporting.
Billing-user resolution (_resolveBillingUser): sub-account owner if they have their own card → agency owner → subscription owner. Notify emails are best-effort — a mail failure never fails the request.
Crons
| Cron | Where / schedule | What |
|---|---|---|
number-rental:meter-due | ms-ai src/elevenlabs/number-rental.scheduler.ts, daily 06:00 UTC | Monthly number rental; idempotent on (number, period), catches up missed days |
twilio-call-cost:meter | ms-ai, every 10 min | Sweeps each company subaccount's completed calls; idempotent on CallSid |
number-rental:suspension-sweep | ms-ai, every 15 min | Suspend → warn (day 0/3/6 via /notify) → release after 7 days |
BalanceAutoRechargeJob | backend scheduler, every minute | Tops up the wallet from the saved card when below balance_auto_recharge.threshold_credits |
Kill switch for all ms-ai rental crons: NUMBER_RENTAL_CRON_ENABLED=false. Bring-your-own Twilio numbers are never metered. The suspension sweep intentionally runs slower than auto-recharge so a healthy card tops up before anything suspends.
Telephony charges are recorded in ms-ai cost-tracking via recordFlatUsdCharge (same mechanism as Agent K provider usage, separate providers for reconciliation) — see cost-tracking.
Auto-recharge
SubscriptionModel.balance_auto_recharge subdoc: { enabled, prompted, threshold_credits, addon_id, source, amount_credits, last_recharge_at, last_failed_at, agency_short_notified_at }. Two kinds, told apart by source:
card(default) — the tenant's own setup viaSubscriptionController(enabling requires an addon selected); re-buysaddon_idon the card. Purchases with no card on file return a clear 402 (payment error, not a 500).agency_wallet— set by the agency on its client form;BalanceAutoRechargeJobmovesamount_creditsout of the agency wallet (10-min cooldown). Read-only to the client (403 unless it takes over with its own card + addon). See Managing Companies → agency-funded auto-recharge.
Usage statement (per-activity lines)
Merged with wallet-fixes-latest (d08f03d7d, frontend af3e4f0d). The Wallet page shows one statement — every call / chat / AI task as a single OUT line with a View breakdown, plus money in and other charges — instead of one row per ledger entry. Display data only: nothing here moves money; balance, hourly AI debit and GET /subscription/wallet-transactions are unchanged.
- Attribution. Every AI call made for an activity carries
X-Activity-Id(lib/activityId.js; same rules in ms-aisrc/cost-tracking/activity-id.tsand ms-commhelpers/ActivityIdHelper.js— keep the three in step). Kinds:web_chat,whatsapp,web_voice,phone_in/phone_out,sms,session_analysis,recording,transcript_translate,nox_chat/nox_voice/nox_brief,training,agent_k,lead_intel,elabs; unattributable work →unattributed:<day>("Other AI usage"). WalletActivityRollupJob(every 5 min, Redis lock): readsai_credit_logsfrom a saved cursor (wallet_activity_rollup_cursor, first passWALLET_ACTIVITY_STARTor 24h back, 2-min settle lag). Hourlyai_tokens_credit_jobrows are split per activity via ms-aiGET /internal/activity-usagefor that exact billed window; immediate wallet charges (phone line, Agent K, lead intel) go to the activity named inmetadata.activity_id/call_sid. Each ledger row is applied once via a uniquewallet_activity_applied.ledger_idmarker written before the totals move. ms-ai down → pass stops and retries; after 6 5xx or a final 4xx the row's amount goes to that day's unattributed line.WALLET_ACTIVITY_ROLLUP=falsedisables it — deploy ms-ai first (needs/activity-usage).WalletActivityRepairJob(03:19 UTC daily): re-sums lines touched in the last two days from their markers.- Models:
wallet_activities(company_id,activity_id,kind,ai_credits,wallet_credits,total_credits,event_count,started_at,last_event_at; TTL 180 d),wallet_activity_applied(TTL 190 d). - Endpoints (
WalletActivityController):GET /subscription/wallet-statement?skip&limit&type=all|usage|credits|charges&include_small,GET /subscription/wallet-activities,GET /subscription/wallet-activities/:activity_id(breakdown). Customer credits only, never provider cost. Ledger history older than the first marker is shown as the raw ledger. - Gate: settings key
wallet_activities(isUsageViewEnabled): absent = on for everyone;{ enabled: false }hides it (optionally keepingcompany_ids); acompany_idslist alone limits it to those. Off → endpoints answer{ enabled: false }andWallet.vuefalls back to the plain "Wallet transactions" ledger. - Frontend:
components/packages/WalletUsage.vue(filter Everything / Calls, chats & AI usage / Top-ups & transfers / Other charges, "Show items under 1¢", tiles + pending credits not yet billed by the hourly job). scripts/reconcile-activity-billing.jsis a local-dev reconciliation script only.
Other merge changes: AICreditAuditHelper.record gained idempotency_key + retries (a duplicate-key insert counts as written); AITokensCreditJob writes its ledger row keyed ai-job:<sub>:<window end> with 3 retries, since the debit has already landed.
Realtime refresh
helpers/RealtimeHelper.js (b060de28d) sends id-only socket pings so open dashboards refetch instead of waiting for a reload: wallet-updated (every AICreditAuditHelper.record ledger row, agency-paid client top-ups, certification/admin grants) and company-settings-updated (Stripe webhook for the owning company/agency, Connect client subscription updates, SubscriptionExpireJob / SubscriptionExpireRetryJob / TrailExpireJob, admin agency edit). Company events go to the company room (settings also to widget:<company_id>); agencies have no room, so agency events go to each owner/staff user:<id> room. The notifyCompanyChanged middleware fires companyChanged after any 2xx on admin feature toggles and agency client-billing routes (id from :_id/:id/:company_id/body). Best-effort, never throws. Frontend (App.vue, 0c066828): wallet-updated reloads the subscription (company) or /user/me (agency); company-settings-updated reloads user + subscription and now also reaches agency users; the AI-paused banner re-checks on subscription reload.
Frontend
- Sidebar pill —
src/components/company/CompanyNavigationSidebar.vue(walletUsd, amber when low). - Low bars —
CompanyWalletLowBanner.vue/AgencyClientWalletLowBanner.vue, see Wallet-low bars. - Wallet page —
src/views/packages/Wallet.vue: the Usage statement above, or (gate off) the plain ledgerGET /subscription/wallet-transactions. Type badges:buy_addon(Top-up),balance_auto_recharge(Auto-recharge),telephony_rental(Number rental),telephony_call(Call),telephony_debit(Telephony), plus Agent K line items:agent_k_apollo_search(lead search),agent_k_apollo_match(contact reveal),agent_k_predictleads(buying signals),agent_k_apify_sos(new businesses),agent_k_unipile_connect(LinkedIn connected),agent_k_unipile_renewal(LinkedIn monthly). Negative balances and debit rows render red. - Tabs —
src/components/packages/PackagesTabs.vue: Wallet / Add-ons / Payment Methods. - Access —
src/composables/useBalanceAccess.jsnow grantscanUseTelephonyandcanSelfServeTopupto everyone, including agency sub-accounts (full self-service; the old agency-funded restriction is lifted).isAgencySubAccountremains only for copy/tab tailoring — subscription & invoices stay agency-owned.
Related
- AI Credits — draw-down order, audit log
- Plans & Subscriptions
- AI Cost-Tracking (Admin) — where telephony/provider charges land