Xuda logo Xuda Docs User Guides
/
xuda.io
← All guides AI Credits

Xuda AI Credits API Reference

Source file: xuda-ai-credits-api-reference.md

Xuda AI Credits API Reference

This reference covers the full method surface of Xuda AI Credit Management: the two publicly callable methods that touch the credit balance, the six dashboard methods that read the balance, configure the rules and sell credit packs, and the two operator methods support uses to grant credits and inspect an account. It is written for developers who need to know what is reachable with an API key today, what is reachable only from a signed-in dashboard session, and exactly which parameters each method accepts. Every parameter name, type and required flag below is taken from the shipped method contract.

How To Call These Methods

Every method here is a CPI method. CPI methods are dispatched by name over the Xuda API and MCP layer, and the normal credential for that layer is the account API key. For the transport-level detail, including how requests are framed and how the MCP layer exposes methods, see /api-mcp-integration.

You should know the shape of this surface before you write a line of code. Every method that reads, spends, grants or configures AI credits directly is flagged private. A private method is excluded from the API-key catalog and refused for API-key callers, even for a full-access key, so it is reachable only from an authenticated Xuda dashboard session. That leaves you with:

  • Two methods that are publicly callable and that touch credits indirectly, generate_release_notes and get_site_build_image_modes. These are the real programmatic surface of this feature today. The first is credit-gated before it runs and meters its own token spend against your balance; the second reports whether the account's plan unlocks the two AI image modes.
  • Six methods with user clearance that require a signed-in dashboard session, with the caller identity injected from that session. These are what the credit meter, the AI credits modal and the AI Credit Management screen call. They are documented in full because they define the product's behavior and because any future API tier would expose them.
  • Two operator methods that additionally require a Xuda superuser account.

Do not build against the last eight with an API key. They will be refused.

What The Availability Labels Mean

Every method below carries one explicit availability line. Read it first, because it tells you whether you can call the method from your own code today.

  • Availability: API key means an external developer API key or the MCP layer can call it. Two AI credit methods carry this label.
  • Availability: Dashboard session means a signed-in user in the Xuda dashboard can call it, and an API key cannot. The account identity comes from the session, never from a parameter.
  • Availability: Public endpoint means no authentication at all. No AI credit method currently carries this label.
  • Availability: Operator only means Xuda staff, listed only for completeness. Two AI credit methods carry this label, and both additionally check the caller against the platform's superuser list.

Method Index

Method What It Does
generate_release_notes Writes release notes for a build, refused when the account is over its hard credit limit and metered against the balance when it runs.
get_site_build_image_modes Reports which website-builder image modes the account may use, including the two AI image modes.
get_credit_management Reads the credit rules, live per-scope usage, the granted pool, the model catalog and the profile and member lists.
set_credit_rules Saves the whole credit rules document: caps, freezes, model access and alerts.
get_credit_usage_history Returns daily spend, spend by model and the most recent calls for an account, a profile or a member.
get_account_ai_usage Reports granted credits by source and credits used, for the current billing period or an explicit window.
purchase_ai_credits Charges a saved card for a one-off credit pack and grants it as topup credits.
validate_ai_credit_coupon Prices a pack with a promotion code without charging anything.
ops_add_ai_credits Support tool that grants topup credits to any account and can email the customer.
ops_account_snapshot Full status snapshot for one account, including its lifetime credit block.

generate_release_notes

Generate Release Notes

AI-generates concise, user-facing release notes for a build the developer is about to create, by diffing the app's published programs against the previous release's timestamp to see what changed. It is read only and never writes the release itself. The call is credit-gated before any model work happens: if the account is over its hard limit the method returns { code: -6, insufficient_credits: true } instead of running. On success the tokens it consumed are metered to the caller's account through the normal usage ledger, and the account's live credit meter updates over WebSocket. Returns { notes, changed_count, since_build, version }.

Availability: API key

Parameters

Name Type Required Description
app_id string Yes Unique identifier of the application this request targets.
version string No The proposed version string for the new build, for example 10.99.0.
build_type string No major, minor or patch, the semantic bump for this build.
instructions string No Optional free-text hint from the developer to steer the generated notes.

Notes

  • Microservice: ai_module.
  • Clearance: user_access. The caller must appear on the app's authorized-user list with an access type of user_group, developer or admin.
  • No min_plan gate. Any plan may call it, subject to the credit gate.
  • The credit gate runs before the model does, so a refusal costs nothing. Reaching a hard limit refuses the call; crossing a soft limit lets it through and fires an alert instead.
  • Every successful call writes one ai_usage record carrying the model, the action, the input and output token counts, the first 40 characters of the prompt, and the profile and member it belongs to.
  • Side effect: the recomputed balance is pushed to the account's dashboard over the credits_update WebSocket event, debounced 800 ms.

get_site_build_image_modes

Get Site Build Image Modes

Returns which website-builder image modes the account may use, as { svg, stock, gen_low, gen_high, upgrade, reason }. svg and stock are always true. The two AI image-generation modes, gen_low which uses the img-1 GPT Image Mini model and gen_high which uses img-2 ChatGPT Image Pro, require both a paid membership plan and a non-free AI Workspace credit plan. When they are locked, upgrade is true and reason carries the exact sentence the UI shows. This is the single source of truth for both the builder gate and the mode selector in the UI.

Availability: API key

Parameters

This method takes no parameters. The account is resolved from the session.

Notes

  • Microservice: account_module.
  • Clearance: user, an authenticated Xuda account.
  • No min_plan gate on the method itself. The plan requirement it reports is checked inside the method.
  • Locked on a free membership, reason reads "AI image generation needs a paid website plan and a workspace credit plan. Upgrade to unlock it."
  • Locked on a paid membership with no workspace plan, reason reads "AI image generation needs a workspace credit plan. Add one to unlock it."
  • Read only. It never grants, spends or reserves credits.

get_credit_management

Get Credit Management

Returns the AI credit rules, live per-scope usage, the granted pool, the model catalog, and the profile and member lists that the credit management editor is built from. Response shape: { rules, can_edit, plan, entitlements: { ai_credits, unlimited }, usage_breakdown: { window, pool: { used, remaining }, by_profile, by_user, by_model, by_source }, model_catalog, profiles, members, main_profile_id }. It reports exactly what the enforcement gate enforces, because it routes through the same balance function the gate uses.

Availability: Dashboard session

Parameters

This method takes no parameters.

Notes

  • Microservice: account_module. Clearance: user. No min_plan.
  • Any logged-in account can read it. can_edit comes back true only on Team and above, so a lower plan can see its own numbers but cannot save rules.
  • ai_credits and remaining are null on an unlimited plan, where the unlimited flag is true instead.
  • Read only. It never writes rules and never mints credits.
  • Per-owner scoped usage is cached for 45 seconds, so two reads inside that window can return the same usage figures.

set_credit_rules

Set Credit Rules

Saves the whole credit rules document on the owner's account: the account pool caps, per-profile and per-member caps, per-model and per-action caps, model allow and deny lists, freeze switches and the alert configuration. The server normalizes everything it stores rather than trusting the payload.

Availability: Dashboard session

Parameters

Name Type Required Description
rules object Yes The full credit rules object (pool, per-profile, per-user, per-model and per-source soft and hard caps, model allow/deny, freeze, alerts).

Notes

  • Microservice: account_module. Clearance: user.
  • Plan gate: the method declares min_plan: "pro" in config, but the method body requires Team and refuses anything below it with "Credit management is available on the Team plan." Treat Team as the real gate. A Pro account passes the platform gate and is then refused by the method.
  • Normalization applied on every save: unknown model codes are dropped, percent limits are clamped to 100, percent is downgraded to absolute credits on the model and source scopes, alert thresholds are filtered to 1 to 100, channels are filtered to ws and email, and any rule stored against the MAIN profile is discarded because the main profile is not shareable.
  • Limits can be written as absolute credits or as a percentage of the granted pool. Percent is accepted on the pool, profile and member scopes only, and on an unlimited plan a percent limit resolves to no cap at all.
  • Soft caps alert and let the call through. Hard caps refuse the call before any model work happens, with a scope-specific reason such as "This profile is paused.", "This member is paused." or "This model is not allowed for this profile."
  • When a profile limit and a member limit both apply, the tighter of the two is the one that applies.
  • Side effects: saving clears the per-owner usage cache and rebroadcasts the balance to the dashboard.
  • window: 'monthly' is stored and normalized but nothing reads it. The counting window is always the current billing period.
  • Per-action (source) caps are still evaluated by the gate and previously saved ones survive a save, but the controls for them were removed from the editor.

get_credit_usage_history

Get Credit Usage History

Returns the day by day drill-down behind the Usage history dialog for the whole account, one profile or one member. Response shape: { scope, id, days, total, calls, truncated, series[{day, credits}], by_model[{code, name, credits}], events[] }. Read only and scoped to the calling owner.

Availability: Dashboard session

Parameters

Name Type Required Description
scope string No account (default), profile, or user.
id string No Profile or member id. Required when scope is profile or user.
days number No Window length in days (default 30, capped by the server at 180).

Notes

  • Microservice: account_module. Clearance: user. No min_plan, so any logged-in account can read its own history.
  • Window: default 30 days, server cap 180 days, raw scan window 120 days.
  • The underlying scan stops at 20000 documents. When it hits that cap the response comes back with truncated: true and the oldest calls in the range are not counted.
  • events returns at most the 60 most recent calls, each with the model, the timestamp, the action, who ran it and the credits it cost.
  • The nested selector this method uses on the usage database has no Mango index today, so it runs with the index warning suppressed. Expect it to get slower as an account's history grows.

get_account_ai_usage

Get Account Ai Usage

Reports granted credits by source alongside credits used. With no window it reports the CURRENT billing period, so credits.total - usage.total equals the real remaining balance. With an explicit range it reports raw windowed spend plus the full ledger total. Returns { credits: { <source>: n, total }, usage: { profile, projects, total }, packs, period }. This is what feeds the credit ring in the dashboard header and the charts on Settings > Usage.

Availability: Dashboard session

Parameters

The method is declared with no fields in config, but the implementation accepts an optional window.

Name Type Required Description
year_from number No Start year of an explicit reporting window.
month_from number No Start month of an explicit reporting window.
day_from number No Start day of an explicit reporting window.
year_to number No End year of an explicit reporting window.
month_to number No End month of an explicit reporting window.
day_to number No End day of an explicit reporting window.
ts_from number No Start of an explicit reporting window, as a timestamp, instead of the split date fields.
ts_to number No End of an explicit reporting window, as a timestamp, instead of the split date fields.

Notes

  • Microservice: account_module. Clearance: user. No min_plan.
  • Call it with no window when you want the balance. An explicit window answers a different question: raw spend inside that range, which will not reconcile against the period pool.
  • The credits object is keyed by grant source, so a plan id, daily credit, purchase, admin_grant, boarding and contact connection each appear as their own line alongside total.
  • Read only.

purchase_ai_credits

Purchase AI Credits

Buys a one-off credit pack. It charges the saved card, optionally applies a Stripe promotion code resolved to a percent or fixed discount, and grants the pack as topup credits, which never expire with the billing period. Returns { charge_id, credits, amount_cents, coupon, receipt_url, created_ts }.

Availability: Dashboard session

Parameters

Name Type Required Description
pack_id string Yes The ai_credit_packs id to buy.
card_id string Yes Stripe card or source id to charge.
coupon_code string No Optional Stripe promotion code to discount the charge.

Notes

  • Microservice: stripe_module. Clearance: user. No min_plan, so any plan can buy a pack without changing subscription.
  • Idempotency: the grant is keyed to the Stripe charge id, so a retry never double-grants.
  • The packs are a plain one-time Stripe charge, not a Stripe product or price object. The amount is computed from the pack's configured price.
  • A post-coupon total below 50 cents is refused as under the Stripe minimum.
  • Credits land in the topup pool, which the monthly period reset never touches. Only the plan allowance resets.
  • The pack catalog is configured under the ai_credit_packs key. Where that key is absent from the running config, this method answers "unknown credit pack".
  • Side effect: on success the balance is rebroadcast, so every credit meter on screen updates.

validate_ai_credit_coupon

Validate AI Credit Coupon

Validates a Stripe promotion code against a credit pack and returns the priced result without charging anything. Returns { promo_id, code, percent_off, amount_off, discount_cents, final_cents, base_cents }. This is what the Apply button next to the coupon field calls, so the discounted total can be confirmed inline before the customer commits.

Availability: Dashboard session

Parameters

Name Type Required Description
pack_id string Yes The ai_credit_packs id to price.
coupon_code string Yes Stripe promotion code to validate.

Notes

  • Microservice: stripe_module. Clearance: user. No min_plan.
  • Nothing is charged and no credits are granted. It is safe to call repeatedly while the customer tries codes.
  • Promotion codes resolve to either percent_off or amount_off. Exactly one of the two is populated.
  • Where the ai_credit_packs key is absent from the running config, this method answers "unknown credit pack".
  • Validating a code here does not reserve it. The discount is applied again, independently, when purchase_ai_credits runs.

ops_add_ai_credits

Ops: add AI credits

Support tool that grants AI credits to any account. The credits land as topup, so they survive the period roll, and the grant is written with an ops notification plus a line in the account log. Optionally emails the customer.

Availability: Operator only

Parameters

Name Type Required Description
account_uid string Yes The account to credit.
credits number Yes Positive number, maximum 100000 per grant.
reason string No Free text, recorded in the ops notification and the account log.
notify boolean No When true, sends the customer a banner plus email notification.

Notes

  • Microservice: account_module. Clearance: admin, plus an in-code superuser check against the platform's configured superuser account list. An ordinary admin clearance is not enough.
  • Range: 1 to 100000 credits in a single grant.
  • Idempotency: the grant is keyed on a unique details string, so a repeated identical grant is refused rather than doubled.
  • The grant source is recorded as admin_grant and the credits are tagged as topup, which means they never expire with the billing period.
  • Side effects: an ops notification, an account log line, a rebroadcast balance, and, when notify is true, a customer banner and email.

ops_account_snapshot

Ops: account snapshot

Full status snapshot for one account, used by the support console. Alongside the rest of the account status it carries an entitlements block and a lifetime credits: { max, used, remaining, by_source } block, which is what the credit bar and the Add credits dialog in Admin > Customers are drawn from.

Availability: Operator only

Parameters

Name Type Required Description
account_uid string Yes The account to snapshot.

Notes

  • Microservice: account_module. Clearance: admin, plus the same superuser check as ops_add_ai_credits.
  • Read only. It never grants or spends credits.
  • The credits block it returns is lifetime, not current-period. For a period-accurate balance the account's own get_account_ai_usage with no window is the authoritative read.

The Two Credit Pools

Every account holds credits in two pools, and the distinction decides what survives a billing period.

Pool What goes in it What happens at the period roll
Period The plan allowance minted when a Stripe invoice is paid, and the free daily drip Retired at its real period end. It does not roll over.
Topup Bought packs, support grants, the welcome bonus and referral bonuses Never expires. Only spending removes it.

The balance read sums active grants by source, splits them into the two pools, subtracts the current period's usage and returns granted, used, remaining and an unlimited flag. Everything that gates, meters or displays credits reads that one function, so the enforcement path and the dashboard can never disagree.

Plan Allowances

Membership ladder. The allowance is minted on each paid invoice.

Plan id Name Price / month AI credits per period
free Free 0 30
pro Pro 49 600
team Team 149 1600
agency Agency 399 3500
enterprise_t1 Enterprise T1 1999 10000
enterprise_t2 Enterprise T2 4999 50000
enterprise_t3 Enterprise T3 call unlimited

The free tier is deliberately never minted from an invoice. Its allowance is the daily drip instead. The Enterprise T3 unlimited value resolves to infinity, gets no ledger grant, and can never be gated.

AI Workspace add-on ladder. Its credits stack on top of the membership allowance for every paid membership tier. The Free membership tier does not stack it.

Plan id Name AI credits Storage
free_ai_workspace 30 AI Credits / 15 GB storage 30 15 GB
200_ai_workspace 200 AI Credits / 100 GB storage 200 100 GB
400_ai_workspace 400 AI Credits / 500 GB storage 400 500 GB
600_ai_workspace 800 AI Credits / 1 TB storage 800 1 TB
1500_ai_workspace 1500 AI Credits / 2 TB storage 1500 2 TB
2000_ai_workspace 2500 AI Credits / 3 TB storage 2500 3 TB
3000_ai_workspace 4000 AI Credits / 5 TB storage 4000 5 TB
6000_ai_workspace 10000 AI Credits / 10 TB storage 10000 10 TB

Two of these eight tiers, 200_ai_workspace and 1500_ai_workspace, carry placeholder Stripe price ids and cannot be sold until real prices are minted.

One-off credit packs, the ids purchase_ai_credits and validate_ai_credit_coupon accept:

Pack id Name Credits Price
pack_small Starter 100 10 USD
pack_medium Plus 500 45 USD
pack_large Pro 1200 100 USD

Pack purchase is confirmed on dev. The ai_credit_packs key is configured in the dev config and is absent from the repo's production config, and on a config without it both pack methods answer "unknown credit pack".

Free credits and bonuses. The welcome bonus grants 30 credits as topup at signup. The daily drip grants 1 credit per 24 hours to accounts on free_ai_workspace, tagged as a period credit. Each accepted contact connection grants 1 credit as topup. A support grant is 1 to 100000 credits as topup.

The Model Catalog

Credits are the billing unit for consumption of these nine models. The model_catalog returned by get_credit_management is built from this list, and the codes are what a model allow list, a deny list or a per-model cap is written against.

Code Name Real model Type Input Output
gpt-1 GPT-5 Nano gpt-5-nano text 0.05 0.4
gpt-2 GPT-5.4 Nano gpt-5.4-nano text 0.2 1.25
gpt-3 GPT-5.6 Luna gpt-5.6-luna text 0.2 1.2
gpt-4 GPT-5.6 Terra gpt-5.6-terra text 2 12
gpt-5 GPT-5.6 Sol gpt-5.6-sol text 5 30
img-1 GPT Image Mini gpt-image-1-mini image 2.5 8
img-2 ChatGPT Image Pro gpt-image-2.6-sunburst image 8 30
voice-1 Whisper Speech AI whisper-1 voice 1 1
voice-2 GPT Realtime Voice gpt-realtime-2.1 voice 32 64

The default model is gpt-1. Eight legacy keys are aliased onto the current codes, so older profiles and agents keep pricing correctly with no data migration. Raw cost is computed as (input_tokens * cost.input + output_tokens * cost.output) / 1e6 and that raw figure is then calibrated against the authoritative total from the usage database's own roll-up. The exact token-to-credit conversion factor lives in the CouchDB design document rather than in application config, so there is no single published "one credit equals N tokens" figure to quote.

Errors

Signal Meaning
code: -6 with insufficient_credits: true The credit gate refused the call before any model work happened. Returned by generate_release_notes.
"Credit management is available on the Team plan." set_credit_rules was called below Team.
"unknown credit pack" The pack id is not in the running config's ai_credit_packs. Returned by both pack methods.
Under the Stripe minimum purchase_ai_credits refused a post-coupon total below 50 cents.

The gate's refusal reasons. A hard limit refuses with a scope-specific sentence: "This profile is paused." or "This member is paused." for a freeze, and "This model is not allowed for this profile." or the member equivalent for a blocked model. Pool, profile, member, model and action caps each produce their own scope-specific refusal.

The legacy AI error contract. Callers inside the AI module reach the gate through a thin adapter that preserves the legacy { credit_limit_error, account_id } Error shape and adds scope and block_kind, so existing handlers keep working while newer ones can tell a soft breach from a hard one.

The gate fails open. Any internal error inside the gate is logged and answers "do not block". That is deliberate, so a rules bug cannot take down all AI on an account, but it means credit limits are a budgeting control and not a hard security boundary.

Limits And Defaults

Setting Value
Rule defaults { "window": "lifetime", "alert_thresholds": [80, 100] }
Alert thresholds offered 50, 75, 80, 90, 100 percent
Alert channels ws (in the app) and email
Percent limits Clamped to 100 on save. Allowed on the pool, profile and member scopes only
Usage history window Default 30 days, server cap 180 days, raw scan window 120 days
Usage history scan cap 20000 documents, after which the answer is flagged truncated
Usage history events returned 60
Ops grant 1 to 100000 credits per grant
Scoped usage cache 45 seconds per owner
Balance broadcast debounce 800 ms
Soft-limit WebSocket debounce 800 ms
Hard-limit alert email At most once per scope per day per owner
Credit expiry Period grants retire at their real period end. Topup credits are never expired

Webhooks

The Stripe invoice.paid and invoice.payment_succeeded events are the only events that mint a plan allowance. The handler matches only membership price lines on the paid invoice, closes the previous period, and writes the new grant stamped with the invoice's own period window, idempotent on the invoice id. The plan-change grant that used to live in customer.subscription.updated was removed so an upgrade cannot double-grant, and the proration invoice carries the credits instead.

If a paid membership has no live grant for the current period, the balance read mints it, guarded by three independent checks: a live grant from any membership plan wins, a per-period marker sits on the account, and the ledger refuses duplicates on its own. Free tier accounts, suspended accounts and accounts on billing hold are skipped.

This feature publishes no outbound webhooks of its own.

Live Events

Two WebSocket events reach a signed-in dashboard and neither is available to an API-key caller:

Event When it fires
credits_update The balance changed, whether by a spend, a grant, a purchase or a rules save. Debounced 800 ms so a streaming chat writing many usage rows collapses into one emit.
credit_soft_limit A soft cap was crossed. The call itself still went through.

Scheduled Work

Two hourly crons run on the master and dev hosts only. add_ai_credits_to_active_accounts performs the free daily drip and credits only accounts whose last drip was more than 24 hours ago. archive_expire_ai_credits retires period grants past their period end and leaves topup credits alone.

A Note On The Rest Of The Surface

Beyond the ten methods above, the account, stripe, ai, voice and email modules carry internal functions that meter usage, compute the balance, evaluate the gate and broadcast the result. They are called module to module and by the crons, no external route reaches them, and they are not part of any documented or supported surface. Two support methods that do reach a route, ops_add_ai_credits and ops_account_snapshot, are documented above and are labeled operator only because they require a Xuda superuser account on top of admin clearance.