utils/billing/billing_utils library

Classes

AttributionAppState
App state relevant to attribution.
AttributionData
Full attribution data from commit analysis.
AttributionDataSummary
Attribution data summary.
AttributionSettingOverride
Custom attribution overrides from settings.
AttributionSettings
Settings relevant to attribution.
AttributionState
File state map for attribution tracking.
AttributionTexts
Attribution texts for commits and PRs.
AuthTokenSource
Auth token source information.
BillingConfig
Global config relevant to billing.
ModelCosts
Cost structure for a model (per million tokens). @see https://platform.neomage.com/docs/en/about-claude/pricing
OAuthAccountInfo
OAuth account information relevant to billing access checks.
PromptCountMessage
Message structure for counting user prompts.
RawTokenCounts
Raw token counts for cost calculation without a full usage object.
TokenUsageInfo
Token usage from an API response.
TranscriptEntry
Transcript entry for memory access counting.
TranscriptStats
Transcript stats result.

Enums

PrivacyLevel
Privacy level controls how much nonessential network traffic and telemetry the application generates.

Constants

costHaiku35 → const ModelCosts
Pricing for Haiku 3.5: $0.80 input / $4 output per Mtok.
costHaiku45 → const ModelCosts
Pricing for Haiku 4.5: $1 input / $5 output per Mtok.
costTier15_75 → const ModelCosts
Pricing tier for Opus 4/4.1: $15 input / $75 output per Mtok.
costTier30_150 → const ModelCosts
Fast mode pricing for Opus 4.6: $30 input / $150 output per Mtok.
costTier3_15 → const ModelCosts
Standard pricing tier for Sonnet models: $3 input / $15 output per Mtok.
costTier5_25 → const ModelCosts
Pricing tier for Opus 4.5: $5 input / $25 output per Mtok.
memoryAccessToolNames → const Set<String>
Tool names used for memory file access detection.
terminalOutputTags → const List<String>
XML tags that mark terminal output.

Properties

modelCosts Map<ModelShortName, ModelCosts>
Known model cost mappings. @MODEL LAUNCH: Add a pricing entry for the new model below. Costs from https://platform.neomage.com/docs/en/about-claude/pricing
final

Functions

calculateCostFromTokens(String model, RawTokenCounts tokens, {required CanonicalNameResolver getCanonicalName, required DefaultModelResolver getDefaultMainLoopModelSetting, required FastModeChecker isFastModeEnabled, UnknownModelCostFlagged? onUnknownModelCost, AnalyticsLogger? logEvent}) double
Calculate cost from raw token counts without requiring a full TokenUsageInfo object. Useful for side queries (e.g. classifier) that track token counts independently.
calculateUsdCost(String resolvedModel, TokenUsageInfo usage, {required CanonicalNameResolver getCanonicalName, required DefaultModelResolver getDefaultMainLoopModelSetting, required FastModeChecker isFastModeEnabled, UnknownModelCostFlagged? onUnknownModelCost, AnalyticsLogger? logEvent}) double
Calculate the cost of a query in US dollars. If the model's costs are not found, use the default model's costs.
countMemoryFileAccessFromEntries(List<TranscriptEntry> entries, {required MemoryFileAccessChecker isMemoryFileAccess}) int
Count memory file accesses in transcript entries. Uses the same detection conditions as the PostToolUse session file access hooks.
countUserPromptsFromEntries(List<PromptCountMessage> entries) int
Count non-sidechain user messages in transcript entries. Used to calculate the number of "steers" (user prompts - 1).
countUserPromptsInMessages(List<PromptCountMessage> messages) int
Count user messages with visible text content in a list of non-sidechain messages. Excludes tool_result blocks, terminal output, and empty messages.
formatModelPricing(ModelCosts costs) String
Format model costs as a pricing string for display. e.g., "$3/$15 per Mtok"
getAttributionTexts({required String? userType, required bool isUndercover(), required String getClientType(), required String? remoteSessionId, required String? ingressUrl, required bool isRemoteSessionLocal(String, String?), required String getRemoteSessionUrl(String, String?), required String getMainLoopModel(), required String? getPublicModelDisplayName(String), required String getPublicModelName(String), required bool isInternalModelRepoCached(), required AttributionSettings getInitialSettings(), required bool isDisableCoAuthoredBy()}) AttributionTexts
Returns attribution text for commits and PRs based on user settings.
getEnhancedPrAttribution({required AttributionAppState getAppState(), required String? userType, required bool isUndercover(), required String getClientType(), required String? remoteSessionId, required String? ingressUrl, required bool isRemoteSessionLocal(String, String?), required String getRemoteSessionUrl(String, String?), required AttributionSettings getInitialSettings(), required String getCanonicalName(String), required String getMainLoopModel(), required String sanitizeModelName(String), required Future<bool> isInternalModelRepo(), required Future<AttributionData?> getAttributionData(AttributionAppState), required Future<TranscriptStats> getTranscriptStats()}) Future<String>
Get enhanced PR attribution text with Neomage contribution stats.
getEssentialTrafficOnlyReason() String?
Returns the env var name responsible for the current essential-traffic restriction, or null if unrestricted. Used for user-facing "unset X to re-enable" messages.
getModelCostsForModel(String model, TokenUsageInfo usage, {required CanonicalNameResolver getCanonicalName, required DefaultModelResolver getDefaultMainLoopModelSetting, required FastModeChecker isFastModeEnabled, UnknownModelCostFlagged? onUnknownModelCost, AnalyticsLogger? logEvent}) ModelCosts
Get the model costs for a model, handling Opus 4.6 fast mode and unknown models.
getModelPricingString(String model, {required CanonicalNameResolver getCanonicalName}) String?
Get formatted pricing string for a model. Accepts either a short name or full model name. Returns null if model is not found.
getOpus46CostTier({required bool fastMode, required FastModeChecker isFastModeEnabled}) ModelCosts
Get the cost tier for Opus 4.6 based on fast mode.
getPrAttributionData(AttributionAppState appState, {required Future<AttributionData?> calculateCommitAttribution(List<AttributionState>, List<String>)}) Future<AttributionData?>
Get full attribution data from the provided AppState's attribution state. Uses ALL tracked files from the attribution state (not just staged files) because for PR attribution, files may not be staged yet. Returns null if no attribution data is available.
getPrivacyLevel() PrivacyLevel
Get the current privacy level based on environment variables.
hasConsoleBillingAccess({required bool isDisableCostWarnings(), required bool isNeomageAiSubscriber(), required AuthTokenSource getAuthTokenSource(), required bool hasApiKey(), required BillingConfig getGlobalConfig()}) bool
Check if user has Console billing access.
hasNeomageAiBillingAccess({required bool isNeomageAiSubscriber(), required SubscriptionType? getSubscriptionType(), required BillingConfig getGlobalConfig()}) bool
Check if user has Neomage AI billing access.
isBilledAsExtraUsage({required String? model, required bool isFastMode, required bool isOpus1mMerged, required bool isNeomageAiSubscriber(), required bool has1mContext(String)}) bool
Determines if the current request is billed as extra usage.
isEssentialTrafficOnly() bool
True when all nonessential network traffic should be suppressed. Equivalent to the old MAGE_DISABLE_NONESSENTIAL_TRAFFIC check.
isTelemetryDisabled() bool
True when telemetry/analytics should be suppressed. True at both noTelemetry and essentialTraffic levels.
setMockBillingAccessOverride(bool? value) → void
Set or clear the mock billing access override.

Typedefs

AnalyticsLogger = void Function(String eventName, Map<String, dynamic> metadata)
Callback type for analytics logging.
CanonicalNameResolver = ModelShortName Function(String model)
Callback type for resolving canonical model names.
DefaultModelResolver = String Function()
Callback type for resolving the default main-loop model setting.
FastModeChecker = bool Function()
Callback type for checking if fast mode is enabled.
MemoryFileAccessChecker = bool Function(String toolName, dynamic input)
Callback type for checking if a tool invocation accesses a memory file.
ModelShortName = String
Model short name type alias.
SubscriptionType = String
Subscription type.
UnknownModelCostFlagged = void Function()
Callback type for flagging an unknown model cost.