@stacklink/sdk 0.4.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,893 @@
1
+ export const stacklinkBillingContractVersion = 'stacklink-billing-v1';
2
+ export const stacklinkPricingCatalogVersion = 'stacklink-pricing-v1';
3
+ export const customerAgreementVersion = 'stacklink-pricing-2026-10';
4
+ export const previousResourceAgreementVersion = 'stacklink-resources-2026-10';
5
+ export const stagingCallAgreementVersion = 'stacklink-calls-2026-10';
6
+ export const resourceAgreementVersion = 'stacklink-calls-2026-10-01';
7
+ export const resourceAgreementVersions = [previousResourceAgreementVersion, stagingCallAgreementVersion, resourceAgreementVersion];
8
+ export function isResourceAgreement(version) {
9
+ return resourceAgreementVersions.some((entry) => entry === version);
10
+ }
11
+ export function usesMemoryCallAllowance(version) {
12
+ return version === stagingCallAgreementVersion || version === resourceAgreementVersion;
13
+ }
14
+ export const selfServePlanKeys = ['pro', 'growth'];
15
+ export const previousSelfServePlanKeys = ['developer', 'growth', 'business'];
16
+ export function isCustomerAgreement(version) {
17
+ return version === customerAgreementVersion || isResourceAgreement(version);
18
+ }
19
+ export const trialPolicy = { days: 30, standardOperations: 50_000, managedCreditMicros: 1000000n };
20
+ export const premiumRuntimeUnitSeconds = 10;
21
+ export const premiumRuntimeUnitMs = premiumRuntimeUnitSeconds * 1000;
22
+ export const tokenBillingBlockSize = 1000;
23
+ export const byteBillingBlockSize = 1024 * 1024;
24
+ export const richContentBillingBlocks = {
25
+ normalizedCharacters: 100_000,
26
+ pages: 10,
27
+ spreadsheetRows: 5_000,
28
+ slides: 10,
29
+ mediaSeconds: 300,
30
+ images: 1,
31
+ };
32
+ export const sandboxPremiumMultipliers = {
33
+ standard: 1,
34
+ medium: 2,
35
+ large: 3,
36
+ };
37
+ export const billingContract = {
38
+ version: stacklinkBillingContractVersion,
39
+ standardMeterName: 'standard_ops',
40
+ premiumMeterName: 'premium_ops',
41
+ premiumRuntimeUnitSeconds,
42
+ sandboxMultipliers: sandboxPremiumMultipliers,
43
+ meters: {
44
+ standard_ops: {
45
+ label: 'Standard ops',
46
+ description: 'Normal Stacklink API, MCP, provider tool, trigger, webhook, knowledge, and connection work.',
47
+ },
48
+ premium_ops: {
49
+ label: 'Premium ops',
50
+ description: 'Stacklink-paid variable infra work such as workbench runtime, web search, LLM helpers, OCR, extraction, and heavy compute.',
51
+ },
52
+ },
53
+ };
54
+ export const billingOperationPolicyCatalog = {
55
+ 'platform.health.read': 'free',
56
+ 'platform.readiness.read': 'free',
57
+ 'platform.worker.bookkeeping': 'free',
58
+ 'billing.plans.read': 'rate_limit_only',
59
+ 'billing.summary.read': 'rate_limit_only',
60
+ 'billing.usage.read': 'rate_limit_only',
61
+ 'billing.usage_events.read': 'rate_limit_only',
62
+ 'billing.checkout.create': 'rate_limit_only',
63
+ 'billing.portal.create': 'rate_limit_only',
64
+ 'billing.invoices.read': 'rate_limit_only',
65
+ 'billing.webhook.receive': 'free',
66
+ 'api_key.lifecycle': 'rate_limit_only',
67
+ 'project.read': 'rate_limit_only',
68
+ 'project.lifecycle': 'rate_limit_only',
69
+ 'provider.catalog.read': 'rate_limit_only',
70
+ 'provider.tool_schema.read': 'rate_limit_only',
71
+ 'provider.auth_config.read': 'rate_limit_only',
72
+ 'provider.auth_config.lifecycle': 'standard_ops',
73
+ 'connection.read': 'rate_limit_only',
74
+ 'provider.connection.lifecycle': 'standard_ops',
75
+ 'provider.tool.execution': 'standard_ops',
76
+ 'session.read': 'rate_limit_only',
77
+ 'session.lifecycle': 'rate_limit_only',
78
+ 'session.event_stream.read': 'rate_limit_only',
79
+ 'tool.discovery': 'rate_limit_only',
80
+ 'tool.execution.read': 'rate_limit_only',
81
+ 'mcp.tool.call': 'standard_ops',
82
+ 'mcp.server.request': 'rate_limit_only',
83
+ 'trigger.subscription.read': 'rate_limit_only',
84
+ 'trigger.subscription.lifecycle': 'standard_ops',
85
+ 'trigger.event.process': 'standard_ops',
86
+ 'trigger.worker.run': 'free',
87
+ 'webhook.endpoint.read': 'rate_limit_only',
88
+ 'webhook.endpoint.lifecycle': 'standard_ops',
89
+ 'webhook.delivery': 'standard_ops',
90
+ 'log.read': 'rate_limit_only',
91
+ 'artifact.read': 'rate_limit_only',
92
+ 'knowledge.pack.lifecycle': 'standard_ops',
93
+ 'knowledge.pack.read': 'rate_limit_only',
94
+ 'knowledge.lookup': 'standard_ops',
95
+ 'knowledge.search': 'standard_ops',
96
+ 'knowledge.verify.heavy': 'premium_ops',
97
+ 'compliance.rule.lookup': 'standard_ops',
98
+ 'compliance.rule.calculation': 'standard_ops',
99
+ 'workbench.metadata.read': 'rate_limit_only',
100
+ 'workbench.artifact.read': 'rate_limit_only',
101
+ 'workbench.artifact.write': 'premium_ops',
102
+ 'workbench.budget.lifecycle': 'rate_limit_only',
103
+ 'workbench.runtime': 'premium_ops',
104
+ 'workbench.code_execution': 'premium_ops',
105
+ 'workbench.model_call.stacklink_paid': 'premium_ops',
106
+ 'workbench.web_search.stacklink_paid': 'premium_ops',
107
+ 'model.call.stacklink_paid': 'premium_ops',
108
+ 'model.call.customer_owned': 'standard_ops',
109
+ 'memory.read': 'standard_ops',
110
+ 'memory.manage': 'standard_ops',
111
+ 'memory.delete': 'standard_ops',
112
+ 'memory.write.indexed': 'premium_ops',
113
+ 'memory.search.vector': 'premium_ops',
114
+ 'memory.context': 'premium_ops',
115
+ 'memory.extraction': 'premium_ops',
116
+ 'memory.graph': 'premium_ops',
117
+ 'memory.profile.rebuild': 'premium_ops',
118
+ 'memory.export': 'premium_ops',
119
+ 'memory.dashboard.read': 'rate_limit_only',
120
+ };
121
+ export const freeCallBillingDescriptor = billingDescriptor('free', 'call', 'fixed');
122
+ export const standardCallBillingDescriptor = billingDescriptor('standard', 'call', 'fixed');
123
+ export const premiumCallBillingDescriptor = billingDescriptor('premium', 'call', 'fixed');
124
+ export const premiumTokenBlockBillingDescriptor = billingDescriptor('premium', 'token_block', 'tokens');
125
+ export const premiumByteBlockBillingDescriptor = billingDescriptor('premium', 'byte_block', 'bytes');
126
+ export const billingResourceKeys = ['tool_calls', 'delivered_events', 'memory_calls', 'memory_input_tokens', 'memory_retrievals', 'workbench_standard', 'workbench_medium', 'workbench_large', 'workbench_ready_standard', 'workbench_ready_medium', 'workbench_ready_large', 'ai_model_usage'];
127
+ export const resourceBudgetKinds = ['tool-calls', 'delivered-events', 'memory', 'workbench', 'ai'];
128
+ /** Funding is separate from the accepted resource rates and subscription price. */
129
+ export const prepaidFundingVersion = 'stacklink-credits-2026-11-04';
130
+ export const creditPurchaseLimits = { presetsCents: [2000, 5000, 10000], minimumCents: 1000, maximumCents: 200000 };
131
+ export function isBillingResourceKey(value) {
132
+ return billingResourceKeys.some((key) => key === value);
133
+ }
134
+ /** Quantities and rates are retained until the complete resource line is rounded. */
135
+ export function resourceChargeMicros(quantity, terms) {
136
+ if (!Number.isSafeInteger(quantity) || quantity < 0)
137
+ throw new Error('Resource quantity must be a nonnegative safe integer.');
138
+ const numerator = BigInt(Math.max(0, quantity - terms.included)) * BigInt(terms.priceMicros);
139
+ return (numerator + BigInt(terms.unitQuantity) - 1n) / BigInt(terms.unitQuantity);
140
+ }
141
+ export function resourceKeysForAgreement(version) {
142
+ return resourceTermsForPlan('pro', false, version).map((row) => row.key);
143
+ }
144
+ export function resourceDimensions(key) {
145
+ if (key === 'ai_model_usage')
146
+ return aiResourceTerms(0);
147
+ const readySize = workbenchReadyResourceSize(key);
148
+ if (readySize)
149
+ return workbenchReadyResourceTerms(resourceTermsForPlan('pro')).find(row => row.key === key);
150
+ return resourceTermsForPlan('pro', false, key === 'memory_input_tokens' || key === 'memory_retrievals' ? previousResourceAgreementVersion : resourceAgreementVersion).find((row) => row.key === key);
151
+ }
152
+ /** An additive AI offer: existing tool, Memory and Workbench agreements do not change. */
153
+ export const aiRateCardVersion = 'stacklink-ai-2026-10-23';
154
+ export function aiResourceTerms(includedMicros) {
155
+ if (!Number.isSafeInteger(includedMicros) || includedMicros < 0)
156
+ throw new Error('Invalid AI allowance.');
157
+ return { key: 'ai_model_usage', label: 'AI usage', budgetKind: 'ai', unit: 'microdollars',
158
+ included: includedMicros, priceMicros: '1', unitQuantity: 1, rateVersion: aiRateCardVersion, testOnly: false };
159
+ }
160
+ export function audioTranscriptionRateSnapshot(at = new Date()) {
161
+ return { version: 'stacklink-audio-2026-10-29', provider: 'elevenlabs', model: 'scribe_v2',
162
+ currency: 'USD', providerMicrosPerHour: 220000, markupBps: 5000, effectiveAt: at.toISOString() };
163
+ }
164
+ export function audioTranscriptionPrice(rate, durationMs) {
165
+ if (!Number.isSafeInteger(durationMs) || durationMs < 100 || durationMs > 1_800_000)
166
+ throw new Error('Audio duration is outside the supported range.');
167
+ const numerator = BigInt(durationMs) * BigInt(rate.providerMicrosPerHour);
168
+ const providerMicros = (numerator + 3600000n - 1n) / 3600000n;
169
+ // Apply markup to the unrounded duration amount; round only the final ledger unit.
170
+ const denominator = 3600000n * 10000n;
171
+ const customerMicros = Number((numerator * BigInt(10_000 + rate.markupBps) + denominator - 1n) / denominator);
172
+ return { providerMicros, customerMicros };
173
+ }
174
+ /** Published provider rates; expanded catalog checked 31 October 2026. No model-name inference. */
175
+ export function modelRateSnapshot(provider, model, at = new Date()) {
176
+ const base = { version: aiRateCardVersion, model, effectiveAt: at.toISOString(), markupBps: 5000 };
177
+ if (provider === 'openai' && model === 'gpt-4.1-mini')
178
+ return { ...base, provider, tier: 'standard',
179
+ inputMicrosPerMillion: 400_000, cachedInputMicrosPerMillion: 100_000, outputMicrosPerMillion: 1_600_000 };
180
+ if (provider === 'openai' && model === 'gpt-5.4-mini')
181
+ return { ...base, provider, tier: 'standard',
182
+ inputMicrosPerMillion: 750_000, cachedInputMicrosPerMillion: 75_000, outputMicrosPerMillion: 4_500_000 };
183
+ if (provider === 'deepseek' && model === 'deepseek-v4-pro') {
184
+ // The launch calendar covers the remainder of 2026, after the final Chinese
185
+ // public holiday. Do not silently apply that calendar to another year.
186
+ if (at < new Date('2026-10-23T00:00:00Z') || at >= new Date('2027-01-01T00:00:00Z'))
187
+ throw new Error('DeepSeek pricing calendar requires review.');
188
+ const hour = at.getUTCHours();
189
+ const peak = at.getUTCDay() >= 1 && at.getUTCDay() <= 5 && (hour >= 1 && hour < 4 || hour >= 6 && hour < 10);
190
+ return { ...base, provider, tier: peak ? 'peak' : 'off_peak',
191
+ inputMicrosPerMillion: peak ? 1_320_000 : 660_000, cachedInputMicrosPerMillion: peak ? 44_000 : 22_000,
192
+ outputMicrosPerMillion: peak ? 3_960_000 : 1_980_000 };
193
+ }
194
+ const expanded = { ...base, version: 'stacklink-ai-2026-10-30', tier: 'standard' };
195
+ // Standard direct-provider APIs only. No batch, priority, regional premium,
196
+ // hosted tools or explicit cache storage is selected by this rate card.
197
+ if (provider === 'openai' && model === 'gpt-6-astra')
198
+ return { ...expanded, provider,
199
+ inputMicrosPerMillion: 10_000_000, cachedInputMicrosPerMillion: 1_000_000, cacheWriteMicrosPerMillion: 12_500_000, outputMicrosPerMillion: 50_000_000,
200
+ longContext: { minimumInputTokens: 272_001, inputMicrosPerMillion: 20_000_000, cachedInputMicrosPerMillion: 2_000_000,
201
+ cacheWriteMicrosPerMillion: 25_000_000, outputMicrosPerMillion: 75_000_000 } };
202
+ if (provider === 'openai' && model === 'gpt-6.1-sol')
203
+ return { ...expanded, provider,
204
+ inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 100_000, cacheWriteMicrosPerMillion: 2_500_000, outputMicrosPerMillion: 10_000_000,
205
+ longContext: { minimumInputTokens: 272_001, inputMicrosPerMillion: 4_000_000, cachedInputMicrosPerMillion: 200_000,
206
+ cacheWriteMicrosPerMillion: 5_000_000, outputMicrosPerMillion: 15_000_000 } };
207
+ if (provider === 'openai' && model === 'gpt-6.1-terra')
208
+ return { ...expanded, provider,
209
+ inputMicrosPerMillion: 1_000_000, cachedInputMicrosPerMillion: 50_000, cacheWriteMicrosPerMillion: 1_250_000, outputMicrosPerMillion: 5_000_000,
210
+ longContext: { minimumInputTokens: 272_001, inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 100_000,
211
+ cacheWriteMicrosPerMillion: 2_500_000, outputMicrosPerMillion: 7_500_000 } };
212
+ if (provider === 'openai' && model === 'gpt-6-luna')
213
+ return { ...expanded, provider,
214
+ inputMicrosPerMillion: 100_000, cachedInputMicrosPerMillion: 10_000, cacheWriteMicrosPerMillion: 125_000, outputMicrosPerMillion: 500_000,
215
+ longContext: { minimumInputTokens: 272_001, inputMicrosPerMillion: 200_000, cachedInputMicrosPerMillion: 20_000,
216
+ cacheWriteMicrosPerMillion: 250_000, outputMicrosPerMillion: 750_000 } };
217
+ if (provider === 'anthropic' && model === 'claude-opus-5-5')
218
+ return { ...expanded, provider,
219
+ inputMicrosPerMillion: 4_000_000, cachedInputMicrosPerMillion: 200_000, cacheWriteMicrosPerMillion: 5_000_000, outputMicrosPerMillion: 20_000_000 };
220
+ if (provider === 'anthropic' && model === 'claude-sonnet-5-5')
221
+ return { ...expanded, provider,
222
+ inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 100_000,
223
+ cacheWriteMicrosPerMillion: 2_500_000, outputMicrosPerMillion: 10_000_000 };
224
+ if (provider === 'anthropic' && model === 'claude-haiku-5-5')
225
+ return { ...expanded, provider,
226
+ inputMicrosPerMillion: 100_000, cachedInputMicrosPerMillion: 10_000,
227
+ cacheWriteMicrosPerMillion: 125_000, outputMicrosPerMillion: 500_000,
228
+ longContext: { minimumInputTokens: 100_001, inputMicrosPerMillion: 500_000,
229
+ cachedInputMicrosPerMillion: 50_000, cacheWriteMicrosPerMillion: 625_000, outputMicrosPerMillion: 2_500_000 } };
230
+ if (provider === 'gemini' && model === 'gemini-3.5-flash-lite')
231
+ return { ...expanded, provider,
232
+ inputMicrosPerMillion: 300_000, cachedInputMicrosPerMillion: 30_000, outputMicrosPerMillion: 2_500_000 };
233
+ if (provider === 'gemini' && model === 'gemini-3.8-flash') {
234
+ const promotion = at < new Date('2027-01-01T00:00:00Z');
235
+ return { ...expanded, provider, inputMicrosPerMillion: promotion ? 750_000 : 1_500_000,
236
+ cachedInputMicrosPerMillion: promotion ? 75_000 : 150_000, outputMicrosPerMillion: promotion ? 3_750_000 : 7_500_000 };
237
+ }
238
+ if (provider === 'qwen' && model === 'qwen3.8-flash')
239
+ return { ...expanded, provider,
240
+ inputMicrosPerMillion: 150_000, cachedInputMicrosPerMillion: 16_000, outputMicrosPerMillion: 470_000 };
241
+ if (provider === 'qwen' && model === 'qwen3.8-max')
242
+ return { ...expanded, provider,
243
+ inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 250_000, outputMicrosPerMillion: 6_000_000 };
244
+ if (provider === 'kimi' && model === 'kimi-k3.1-pro')
245
+ return { ...expanded, provider,
246
+ inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 200_000,
247
+ cacheWriteMicrosPerMillion: 2_000_000, outputMicrosPerMillion: 10_000_000 };
248
+ if (provider === 'kimi' && model === 'kimi-k3.1-pro-highspeed')
249
+ return { ...expanded, provider,
250
+ inputMicrosPerMillion: 4_000_000, cachedInputMicrosPerMillion: 200_000,
251
+ cacheWriteMicrosPerMillion: 4_000_000, outputMicrosPerMillion: 20_000_000 };
252
+ if (provider === 'zai' && model === 'glm-5.3')
253
+ return { ...expanded, provider,
254
+ inputMicrosPerMillion: 1_400_000, cachedInputMicrosPerMillion: 260_000, outputMicrosPerMillion: 4_400_000 };
255
+ if (provider === 'zai' && model === 'glm-5.3-flashx')
256
+ return { ...expanded, provider,
257
+ inputMicrosPerMillion: 370_000, cachedInputMicrosPerMillion: 75_000, outputMicrosPerMillion: 1_250_000 };
258
+ if (provider === 'zai' && model === 'glm-5.3-flash')
259
+ return { ...expanded, provider,
260
+ inputMicrosPerMillion: 150_000, cachedInputMicrosPerMillion: 30_000, outputMicrosPerMillion: 500_000 };
261
+ if (provider === 'xai' && model === 'grok-4.7')
262
+ return { ...expanded, provider,
263
+ inputMicrosPerMillion: 2_000_000, cachedInputMicrosPerMillion: 500_000, outputMicrosPerMillion: 6_000_000,
264
+ longContext: { minimumInputTokens: 200_000, inputMicrosPerMillion: 4_000_000,
265
+ cachedInputMicrosPerMillion: 1_000_000, outputMicrosPerMillion: 12_000_000 } };
266
+ throw new Error('This model does not have an approved customer rate.');
267
+ }
268
+ export function nativeSearchRateSnapshot(provider, model, at = new Date()) {
269
+ if (provider === 'deepseek' && model === 'deepseek-v4-pro')
270
+ return {
271
+ version: 'stacklink-native-search-2026-10-27', provider, tool: 'web_search', effectiveAt: at.toISOString(),
272
+ // Hosted server searches become billable at 00:00 Beijing, 1 November.
273
+ providerMicrosPerRequest: at < new Date('2026-10-31T16:00:00Z') ? 0 : 750, markupBps: 1500,
274
+ };
275
+ if (provider !== 'openai' || !['gpt-4.1-mini', 'gpt-5.4-mini'].includes(model))
276
+ throw new Error('This model has no verified native search rate and spending bound.');
277
+ return { version: 'stacklink-native-search-2026-10-27', provider, tool: 'web_search',
278
+ providerMicrosPerRequest: 10_000, markupBps: 1500 };
279
+ }
280
+ export function nativeSearchUsagePrice(rate, requests) {
281
+ if (!Number.isSafeInteger(requests) || requests < 0)
282
+ throw new Error('Provider search usage is invalid.');
283
+ const providerMicros = BigInt(requests) * BigInt(rate.providerMicrosPerRequest);
284
+ const customerMicros = (providerMicros * BigInt(10_000 + rate.markupBps) + 9999n) / 10000n;
285
+ if (customerMicros > 2147483647n)
286
+ throw new Error('Search usage exceeds the supported per-call amount.');
287
+ return { providerMicros, customerMicros: Number(customerMicros) };
288
+ }
289
+ export function modelUsagePrice(rate, usage) {
290
+ for (const value of Object.values(usage))
291
+ if (!Number.isSafeInteger(value) || value < 0)
292
+ throw new Error('Provider token usage is invalid.');
293
+ const writes = usage.cacheWriteTokens ?? 0;
294
+ if (usage.cachedInputTokens + writes > usage.inputTokens)
295
+ throw new Error('Cached tokens exceed total input.');
296
+ const band = rate.longContext && usage.inputTokens >= rate.longContext.minimumInputTokens ? rate.longContext : rate;
297
+ if (writes && band.cacheWriteMicrosPerMillion === undefined)
298
+ throw new Error('The cache write tariff is unavailable.');
299
+ // Reasoning is already part of outputTokens. Round once, after all dimensions
300
+ // and markup; do not round each token category to cents.
301
+ const numerator = BigInt(usage.inputTokens - usage.cachedInputTokens - writes) * BigInt(band.inputMicrosPerMillion)
302
+ + BigInt(usage.cachedInputTokens) * BigInt(band.cachedInputMicrosPerMillion)
303
+ + BigInt(writes) * BigInt(band.cacheWriteMicrosPerMillion ?? 0)
304
+ + BigInt(usage.outputTokens) * BigInt(band.outputMicrosPerMillion);
305
+ const providerMicros = (numerator + 999999n) / 1000000n;
306
+ const customerMicros = (numerator * BigInt(10_000 + rate.markupBps) + 9999999999n) / 10000000000n;
307
+ if (customerMicros > 2147483647n)
308
+ throw new Error('The model request exceeds the supported per-call amount.');
309
+ return { providerMicros, customerMicros: Number(customerMicros) };
310
+ }
311
+ /** Reserve the most expensive supported input treatment, including cache creation. */
312
+ export function modelUsageReservation(rate, inputTokens, outputTokens) {
313
+ const band = rate.longContext && inputTokens >= rate.longContext.minimumInputTokens ? rate.longContext : rate;
314
+ const { longContext: _bands, ...singleBand } = rate;
315
+ return modelUsagePrice({ ...singleBand, ...band, inputMicrosPerMillion: Math.max(band.inputMicrosPerMillion, band.cacheWriteMicrosPerMillion ?? 0) }, { inputTokens, outputTokens, cachedInputTokens: 0 });
316
+ }
317
+ export function workbenchReadyResourceSize(key) {
318
+ if (key === 'workbench_ready_standard')
319
+ return 'standard';
320
+ if (key === 'workbench_ready_medium')
321
+ return 'medium';
322
+ if (key === 'workbench_ready_large')
323
+ return 'large';
324
+ return undefined;
325
+ }
326
+ /** Retention is an explicitly purchased resource. It never borrows included execution minutes. */
327
+ export function workbenchReadyResourceTerms(activeTerms) {
328
+ return ['standard', 'medium', 'large'].flatMap(size => {
329
+ const active = activeTerms.find(row => row.key === `workbench_${size}`);
330
+ return active ? [{ ...active, key: `workbench_ready_${size}`,
331
+ label: `${size === 'standard' ? 'Standard' : size === 'medium' ? 'Medium' : 'Large'} Workbench keep ready`,
332
+ included: 0, rateVersion: `${active.rateVersion}:keep-ready-2026-10-22` }] : [];
333
+ });
334
+ }
335
+ export function resourceTermsForPlan(planKey, trial = false, version = resourceAgreementVersion) {
336
+ const previous = version === previousResourceAgreementVersion;
337
+ const growth = planKey === 'growth';
338
+ const term = (key, label, budgetKind, unit, included, priceMicros, unitQuantity, testOnly = false) => ({ key, label, budgetKind, unit, included, priceMicros: String(priceMicros), unitQuantity, rateVersion: version, testOnly });
339
+ return [
340
+ term('tool_calls', 'Tool calls', 'tool-calls', 'calls', trial ? 100_000 : growth ? previous ? 2_000_000 : 1_500_000 : previous ? 200_000 : 100_000, growth ? 300_000 : 500_000, 1_000),
341
+ term('delivered_events', 'Delivered events', 'delivered-events', 'events', trial ? 10_000 : growth ? previous ? 250_000 : 100_000 : previous ? 50_000 : 30_000, growth ? 750_000 : 1_000_000, 1_000),
342
+ ...(previous ? [term('memory_input_tokens', 'Memory input tokens', 'memory', 'tokens', trial ? 100_000 : 1_000_000, 10_000_000, 1_000_000),
343
+ term('memory_retrievals', 'Memory retrievals', 'memory', 'retrievals', trial ? 1_000 : 10_000, 100_000, 1_000)] : [
344
+ term('memory_calls', 'Memory calls', 'memory', 'calls', trial ? 1_000 : growth ? 50_000 : 25_000, 1_000_000, 1_000),
345
+ ]),
346
+ // Approved production prices. Earlier agreements retain their test-only terms.
347
+ term('workbench_standard', 'Standard Workbench', 'workbench', 'milliseconds', (trial ? 30 : previous ? 60 : 0) * 60_000, previous ? 120_000 : 6_000, 60_000, version !== resourceAgreementVersion),
348
+ term('workbench_medium', 'Medium Workbench', 'workbench', 'milliseconds', 0, previous ? 240_000 : 9_960, 60_000, version !== resourceAgreementVersion),
349
+ term('workbench_large', 'Large Workbench', 'workbench', 'milliseconds', 0, previous ? 360_000 : 18_360, 60_000, version !== resourceAgreementVersion),
350
+ ];
351
+ }
352
+ export function resourceCountersFromJson(value) {
353
+ if (!isBillingRecord(value))
354
+ return {};
355
+ const result = {};
356
+ for (const key of billingResourceKeys) {
357
+ const row = value[key];
358
+ if (row === undefined)
359
+ continue;
360
+ const dimensions = resourceDimensions(key);
361
+ if (!isBillingRecord(row) || row.credited !== undefined && (!Number.isSafeInteger(row.credited) || Number(row.credited) < 0 || Number(row.credited) > Number(row.included)) || row.key !== key || !Number.isSafeInteger(row.used) || !Number.isSafeInteger(row.reserved)
362
+ || !Number.isSafeInteger(row.included) || !Number.isSafeInteger(row.unitQuantity) || Number(row.unitQuantity) < 1
363
+ || typeof row.priceMicros !== 'string' || BigInt(row.priceMicros) < 0n || Number(row.used) < 0 || Number(row.reserved) < 0
364
+ || Number(row.included) < 0 || row.budgetKind !== dimensions.budgetKind || row.unit !== dimensions.unit
365
+ || row.includedUsed !== undefined && (!Number.isSafeInteger(row.includedUsed) || Number(row.includedUsed) < 0)
366
+ || row.includedReserved !== undefined && (!Number.isSafeInteger(row.includedReserved) || Number(row.includedReserved) < 0)
367
+ || row.chargedMicros !== undefined && (typeof row.chargedMicros !== 'string' || BigInt(row.chargedMicros) < 0n)
368
+ || typeof row.label !== 'string' || typeof row.rateVersion !== 'string' || !row.rateVersion
369
+ || typeof row.testOnly !== 'boolean')
370
+ throw new Error('Stored resource accounting is invalid.');
371
+ result[key] = row;
372
+ }
373
+ return result;
374
+ }
375
+ /** Older counters are converted while holding the workspace admission lock. */
376
+ export function resourceIncludedAllocation(row) {
377
+ const used = row.includedUsed ?? Math.min(row.included, row.used);
378
+ const reserved = row.includedReserved ?? Math.min(Math.max(0, row.included - used), row.reserved);
379
+ return { used, reserved, available: Math.max(0, row.included - used - reserved) };
380
+ }
381
+ export function resourceBudgetAmounts(counters, kind) {
382
+ let usedCents = 0;
383
+ let committedCents = 0;
384
+ for (const row of Object.values(counters)) {
385
+ if (row.budgetKind !== kind)
386
+ continue;
387
+ usedCents += microsToCents(resourceChargeMicros(row.used, row));
388
+ committedCents += microsToCents(resourceChargeMicros(row.used + row.reserved, row));
389
+ }
390
+ return { usedCents, reservedCents: committedCents - usedCents };
391
+ }
392
+ export const billingPlanCatalog = [
393
+ {
394
+ key: 'free',
395
+ displayName: 'Free',
396
+ monthlyPriceCents: 0,
397
+ annualPriceCents: null,
398
+ standardOpsIncluded: 20_000,
399
+ premiumOpsIncluded: 1_000,
400
+ standardOveragePerThousandCents: 0,
401
+ premiumOveragePerThousandCents: 0,
402
+ rateLimitPerMinute: 120,
403
+ logRetentionDays: 30,
404
+ projectsIncluded: 2,
405
+ metadata: { overagePolicy: 'hard_cap' },
406
+ },
407
+ {
408
+ key: 'builder',
409
+ displayName: 'Builder',
410
+ monthlyPriceCents: 900,
411
+ annualPriceCents: 8_000,
412
+ standardOpsIncluded: 200_000,
413
+ premiumOpsIncluded: 10_000,
414
+ standardOveragePerThousandCents: 29,
415
+ premiumOveragePerThousandCents: 87,
416
+ rateLimitPerMinute: 600,
417
+ logRetentionDays: 60,
418
+ projectsIncluded: 5,
419
+ metadata: { overagePolicy: 'soft_meter' },
420
+ },
421
+ {
422
+ key: 'startup',
423
+ displayName: 'Startup',
424
+ monthlyPriceCents: 4_900,
425
+ annualPriceCents: 49_000,
426
+ standardOpsIncluded: 1_000_000,
427
+ premiumOpsIncluded: 50_000,
428
+ standardOveragePerThousandCents: 25,
429
+ premiumOveragePerThousandCents: 75,
430
+ rateLimitPerMinute: 1_800,
431
+ logRetentionDays: 90,
432
+ projectsIncluded: 10,
433
+ metadata: { overagePolicy: 'soft_meter' },
434
+ },
435
+ {
436
+ key: 'scale',
437
+ displayName: 'Scale',
438
+ monthlyPriceCents: 19_900,
439
+ annualPriceCents: 199_000,
440
+ standardOpsIncluded: 5_000_000,
441
+ premiumOpsIncluded: 250_000,
442
+ standardOveragePerThousandCents: 20,
443
+ premiumOveragePerThousandCents: 60,
444
+ rateLimitPerMinute: 6_000,
445
+ logRetentionDays: 180,
446
+ projectsIncluded: 25,
447
+ metadata: { overagePolicy: 'soft_meter' },
448
+ },
449
+ {
450
+ key: 'pro', displayName: 'Pro', monthlyPriceCents: 3000, annualPriceCents: null,
451
+ standardOpsIncluded: 100_000, premiumOpsIncluded: 0, standardOveragePerThousandCents: 50, premiumOveragePerThousandCents: 0,
452
+ rateLimitPerMinute: 300, logRetentionDays: 60, projectsIncluded: 2,
453
+ metadata: { agreementVersion: resourceAgreementVersion, description: 'Build and launch production integrations', supportLabel: 'Email', overagePolicy: 'budget' },
454
+ },
455
+ {
456
+ key: 'developer', displayName: 'Developer', monthlyPriceCents: 2900, annualPriceCents: 31320,
457
+ standardOpsIncluded: 50_000, premiumOpsIncluded: 0, standardOveragePerThousandCents: 50, premiumOveragePerThousandCents: 0,
458
+ rateLimitPerMinute: 600, logRetentionDays: 30, projectsIncluded: 2,
459
+ metadata: { agreementVersion: customerAgreementVersion, description: 'Developers and small production applications', supportLabel: 'Standard email', overagePolicy: 'budget' },
460
+ },
461
+ {
462
+ key: 'growth', displayName: 'Growth', monthlyPriceCents: 20000, annualPriceCents: null,
463
+ standardOpsIncluded: 1_500_000, premiumOpsIncluded: 0, standardOveragePerThousandCents: 30, premiumOveragePerThousandCents: 0,
464
+ rateLimitPerMinute: 1800, logRetentionDays: 120, projectsIncluded: 10,
465
+ metadata: { agreementVersion: resourceAgreementVersion, description: 'Growing products and startups', supportLabel: 'Email', overagePolicy: 'budget' },
466
+ },
467
+ {
468
+ key: 'business', displayName: 'Business', monthlyPriceCents: 50000, annualPriceCents: 540000,
469
+ standardOpsIncluded: 1_000_000, premiumOpsIncluded: 0, standardOveragePerThousandCents: 30, premiumOveragePerThousandCents: 0,
470
+ rateLimitPerMinute: 6000, logRetentionDays: 90, projectsIncluded: 25,
471
+ metadata: { agreementVersion: customerAgreementVersion, description: 'Larger production deployments', supportLabel: 'Priority email, business hours', overagePolicy: 'budget' },
472
+ },
473
+ {
474
+ key: 'enterprise',
475
+ displayName: 'Enterprise',
476
+ monthlyPriceCents: 0,
477
+ annualPriceCents: null,
478
+ standardOpsIncluded: 50_000_000,
479
+ premiumOpsIncluded: 1_000_000,
480
+ standardOveragePerThousandCents: 0,
481
+ premiumOveragePerThousandCents: 0,
482
+ rateLimitPerMinute: 0,
483
+ logRetentionDays: 365,
484
+ projectsIncluded: null,
485
+ metadata: { overagePolicy: 'custom', customLimits: true },
486
+ },
487
+ ];
488
+ export const billingBaseRateCatalog = [
489
+ {
490
+ key: 'standard_ops_included',
491
+ productArea: 'platform',
492
+ unit: 'operation',
493
+ basePriceMicros: 0n,
494
+ currency: 'USD',
495
+ publicLabel: 'Standard operation',
496
+ publicUnitLabel: 'operation',
497
+ publicNotes: ['Included with the project plan unless a more specific pricing rule applies.'],
498
+ publicVisible: true,
499
+ enabled: true,
500
+ metadata: { source: 'default_pricing_catalog' },
501
+ },
502
+ {
503
+ key: 'premium_ops_included',
504
+ productArea: 'platform',
505
+ unit: 'operation',
506
+ basePriceMicros: 0n,
507
+ currency: 'USD',
508
+ publicLabel: 'Premium operation',
509
+ publicUnitLabel: 'operation',
510
+ publicNotes: ['Included with the project plan unless a more specific pricing rule applies.'],
511
+ publicVisible: true,
512
+ enabled: true,
513
+ metadata: { source: 'default_pricing_catalog' },
514
+ },
515
+ {
516
+ key: 'remote_mcp_standard_call',
517
+ productArea: 'provider',
518
+ unit: '1000_calls',
519
+ basePriceMicros: 100000n,
520
+ currency: 'USD',
521
+ publicLabel: 'Remote MCP tool call',
522
+ publicUnitLabel: '1,000 successful tool calls',
523
+ publicNotes: ['Billed only after successful tool execution. Provider-specific rules may override this rate.'],
524
+ publicVisible: true,
525
+ enabled: true,
526
+ metadata: { source: 'default_pricing_catalog' },
527
+ },
528
+ {
529
+ key: 'knowledge_search_standard',
530
+ productArea: 'knowledge',
531
+ unit: '1000_calls',
532
+ basePriceMicros: 400000n,
533
+ currency: 'USD',
534
+ publicLabel: 'Knowledge search',
535
+ publicUnitLabel: '1,000 searches',
536
+ publicNotes: ['Knowledge lookup, search, verification, and indexing can have separate rules.'],
537
+ publicVisible: true,
538
+ enabled: true,
539
+ metadata: { source: 'default_pricing_catalog' },
540
+ },
541
+ {
542
+ key: 'model_input_tokens_default',
543
+ productArea: 'model',
544
+ unit: '1m_input_tokens',
545
+ basePriceMicros: 0n,
546
+ currency: 'USD',
547
+ publicLabel: 'Model input tokens',
548
+ publicUnitLabel: '1M input tokens',
549
+ publicNotes: ['Stacklink Models will publish model-specific token rates.'],
550
+ publicVisible: true,
551
+ enabled: true,
552
+ metadata: { source: 'default_pricing_catalog' },
553
+ },
554
+ {
555
+ key: 'model_output_tokens_default',
556
+ productArea: 'model',
557
+ unit: '1m_output_tokens',
558
+ basePriceMicros: 0n,
559
+ currency: 'USD',
560
+ publicLabel: 'Model output tokens',
561
+ publicUnitLabel: '1M output tokens',
562
+ publicNotes: ['Stacklink Models will publish model-specific token rates.'],
563
+ publicVisible: true,
564
+ enabled: true,
565
+ metadata: { source: 'default_pricing_catalog' },
566
+ },
567
+ ];
568
+ export const pricingRuleCatalog = [
569
+ {
570
+ key: 'standard_ops_default',
571
+ scope: 'global',
572
+ operationClass: 'standard',
573
+ baseRateKey: 'standard_ops_included',
574
+ markupBasis: 'none',
575
+ markupBps: 0,
576
+ priority: 100_000,
577
+ currency: 'USD',
578
+ publicLabel: 'Standard operations',
579
+ publicDescription: 'Standard Stacklink work is included with the project plan unless a more specific pricing rule applies.',
580
+ publicUnitLabel: 'operation',
581
+ publicNotes: ['Included plan limits and overage rules still apply.'],
582
+ publicVisible: true,
583
+ enabled: true,
584
+ version: stacklinkPricingCatalogVersion,
585
+ metadata: { source: 'default_pricing_catalog' },
586
+ },
587
+ {
588
+ key: 'premium_ops_default',
589
+ scope: 'global',
590
+ operationClass: 'premium',
591
+ baseRateKey: 'premium_ops_included',
592
+ markupBasis: 'none',
593
+ markupBps: 0,
594
+ priority: 100_001,
595
+ currency: 'USD',
596
+ publicLabel: 'Premium operations',
597
+ publicDescription: 'Premium Stacklink work is included with the project plan unless a more specific pricing rule applies.',
598
+ publicUnitLabel: 'operation',
599
+ publicNotes: ['Included plan limits and overage rules still apply.'],
600
+ publicVisible: true,
601
+ enabled: true,
602
+ version: stacklinkPricingCatalogVersion,
603
+ metadata: { source: 'default_pricing_catalog' },
604
+ },
605
+ {
606
+ key: 'free_ops_default',
607
+ scope: 'global',
608
+ operationClass: 'free',
609
+ baseRateKey: 'standard_ops_included',
610
+ markupBasis: 'none',
611
+ markupBps: 0,
612
+ priority: 100_002,
613
+ currency: 'USD',
614
+ publicLabel: 'Free operations',
615
+ publicDescription: 'Free Stacklink operations do not count toward metered usage.',
616
+ publicUnitLabel: 'operation',
617
+ publicNotes: ['No usage charge applies.'],
618
+ publicVisible: true,
619
+ enabled: true,
620
+ version: stacklinkPricingCatalogVersion,
621
+ metadata: { source: 'default_pricing_catalog' },
622
+ },
623
+ ];
624
+ export const defaultBillingPlanKey = 'free';
625
+ export function billingPlanByKey(key, agreementVersion = resourceAgreementVersion) {
626
+ const plan = billingPlanCatalog.find((entry) => entry.key === key);
627
+ if (plan && agreementVersion === previousResourceAgreementVersion && (key === 'pro' || key === 'growth'))
628
+ return { ...plan,
629
+ monthlyPriceCents: key === 'pro' ? 2900 : 19900, standardOpsIncluded: key === 'pro' ? 200_000 : 2_000_000,
630
+ rateLimitPerMinute: key === 'pro' ? 600 : 1800, logRetentionDays: key === 'pro' ? 30 : 60,
631
+ metadata: { ...plan.metadata, agreementVersion } };
632
+ if (key === 'growth' && agreementVersion === customerAgreementVersion && plan)
633
+ return { ...plan, monthlyPriceCents: 20_000, annualPriceCents: 216_000,
634
+ standardOpsIncluded: 500_000, logRetentionDays: 60, standardOveragePerThousandCents: 40, metadata: { ...plan.metadata, agreementVersion } };
635
+ return plan;
636
+ }
637
+ export function serializeBillingPlanDefinition(plan) {
638
+ return {
639
+ key: plan.key,
640
+ displayName: plan.displayName,
641
+ monthlyPriceCents: plan.monthlyPriceCents,
642
+ annualPriceCents: plan.annualPriceCents ?? null,
643
+ standardOpsIncluded: plan.standardOpsIncluded,
644
+ premiumOpsIncluded: plan.premiumOpsIncluded,
645
+ standardOveragePerThousandCents: plan.standardOveragePerThousandCents,
646
+ premiumOveragePerThousandCents: plan.premiumOveragePerThousandCents,
647
+ rateLimitPerMinute: plan.rateLimitPerMinute,
648
+ logRetentionDays: plan.logRetentionDays,
649
+ projectsIncluded: plan.projectsIncluded,
650
+ description: typeof plan.metadata.description === 'string' ? plan.metadata.description : null,
651
+ supportLabel: typeof plan.metadata.supportLabel === 'string' ? plan.metadata.supportLabel : null,
652
+ selfServe: plan.key !== 'enterprise',
653
+ metadata: plan.metadata,
654
+ resources: selfServePlanKeys.some((key) => key === plan.key) ? resourceTermsForPlan(plan.key) : [],
655
+ availableIntervals: selfServePlanKeys.some((key) => key === plan.key) ? ['monthly'] : [],
656
+ };
657
+ }
658
+ export function serializeBillingContract() {
659
+ return {
660
+ version: billingContract.version,
661
+ standardMeterName: billingContract.standardMeterName,
662
+ premiumMeterName: billingContract.premiumMeterName,
663
+ premiumRuntimeUnitSeconds: billingContract.premiumRuntimeUnitSeconds,
664
+ sandboxMultipliers: { ...billingContract.sandboxMultipliers },
665
+ meters: {
666
+ standard_ops: { ...billingContract.meters.standard_ops },
667
+ premium_ops: { ...billingContract.meters.premium_ops },
668
+ },
669
+ };
670
+ }
671
+ export function billingPolicyForOperation(operation) {
672
+ return billingOperationPolicyCatalog[operation];
673
+ }
674
+ export function publicBillingSummaryForPolicy(policy, agreementVersion) {
675
+ if (isResourceAgreement(agreementVersion) && policy === 'standard_ops')
676
+ return {
677
+ policy, operationClass: 'standard', meterName: 'tool_calls', label: 'Tool calls',
678
+ description: 'One successful external toolkit execution counts as one tool call. Connections, configuration, browsing and automatic retries do not add tool calls. Events, Memory and Workbench have their own resource allowances.',
679
+ };
680
+ if (policy === 'free') {
681
+ return {
682
+ policy,
683
+ operationClass: 'free',
684
+ meterName: null,
685
+ label: 'No usage charge',
686
+ description: 'This operation does not count toward metered usage.',
687
+ };
688
+ }
689
+ if (policy === 'rate_limit_only') {
690
+ return {
691
+ policy,
692
+ operationClass: null,
693
+ meterName: null,
694
+ label: 'Rate limit only',
695
+ description: 'This operation is protected by auth and rate limits, but does not count toward metered usage.',
696
+ };
697
+ }
698
+ if (policy === 'premium_ops') {
699
+ return {
700
+ policy,
701
+ operationClass: 'premium',
702
+ meterName: billingContract.premiumMeterName,
703
+ label: 'Counts as premium ops',
704
+ description: billingContract.meters.premium_ops.description,
705
+ };
706
+ }
707
+ return {
708
+ policy,
709
+ operationClass: 'standard',
710
+ meterName: billingContract.standardMeterName,
711
+ label: 'Included as standard ops',
712
+ description: billingContract.meters.standard_ops.description,
713
+ };
714
+ }
715
+ export function publicBillingSummaryForDescriptor(billing) {
716
+ if (billing.class === 'free')
717
+ return publicBillingSummaryForPolicy('free');
718
+ if (billing.class === 'premium')
719
+ return publicBillingSummaryForPolicy('premium_ops');
720
+ return publicBillingSummaryForPolicy('standard_ops');
721
+ }
722
+ export function serializeBillingBaseRateDefinition(rate) {
723
+ return {
724
+ key: rate.key,
725
+ productArea: rate.productArea,
726
+ unit: rate.unit,
727
+ basePriceMicros: rate.basePriceMicros.toString(),
728
+ currency: rate.currency,
729
+ publicLabel: rate.publicLabel,
730
+ publicUnitLabel: rate.publicUnitLabel,
731
+ publicNotes: rate.publicNotes,
732
+ publicVisible: rate.publicVisible,
733
+ enabled: rate.enabled,
734
+ metadata: rate.metadata,
735
+ };
736
+ }
737
+ export function formatPricingPriceText(input) {
738
+ if (input.billingModel === 'free')
739
+ return 'Free';
740
+ if (input.priceMicros === 0n)
741
+ return 'Included with plan';
742
+ return `${formatCurrencyFromMicros(input.priceMicros, input.currency)} per ${input.unitLabel}`;
743
+ }
744
+ export function billingDescriptor(operationClass, unit, quantitySource, multiplier) {
745
+ return {
746
+ class: operationClass,
747
+ unit,
748
+ quantitySource,
749
+ ...(multiplier === undefined ? {} : { multiplier }),
750
+ version: stacklinkBillingContractVersion,
751
+ };
752
+ }
753
+ export function runtimeBillingDescriptorForSandboxSize(sandboxSize) {
754
+ const normalized = sandboxSize === 'medium' || sandboxSize === 'large' ? sandboxSize : 'standard';
755
+ return billingDescriptor('premium', 'runtime_10s', 'duration_ms', sandboxPremiumMultipliers[normalized]);
756
+ }
757
+ export function billingDescriptorFromUnknown(value) {
758
+ if (!isBillingRecord(value))
759
+ return undefined;
760
+ if (!isUsageOperationClass(value.class) || !isBillingUnit(value.unit) || !isQuantitySource(value.quantitySource)) {
761
+ return undefined;
762
+ }
763
+ const multiplier = value.multiplier === undefined ? undefined : billingMultiplier(value.multiplier);
764
+ if (value.multiplier !== undefined && multiplier === undefined)
765
+ return undefined;
766
+ if (value.version !== stacklinkBillingContractVersion)
767
+ return undefined;
768
+ return {
769
+ class: value.class,
770
+ unit: value.unit,
771
+ quantitySource: value.quantitySource,
772
+ ...(multiplier === undefined ? {} : { multiplier }),
773
+ version: stacklinkBillingContractVersion,
774
+ };
775
+ }
776
+ export function calculateMeteredOps(input) {
777
+ const multiplier = input.billing.multiplier ?? 1;
778
+ const baseQuantity = billingBaseQuantity(input);
779
+ return {
780
+ operationClass: input.billing.class,
781
+ quantity: Math.max(1, baseQuantity * multiplier),
782
+ baseQuantity,
783
+ billing: input.billing,
784
+ };
785
+ }
786
+ /**
787
+ * Returns one transparent customer quantity for a normalized rich-content
788
+ * item. The largest typed dimension wins so the same content is not charged
789
+ * once for its text and again for its pages or duration.
790
+ */
791
+ export function calculateRichContentPremiumQuantity(input) {
792
+ return Math.max(1, unitsFromNumber(input.normalizedCharacters, richContentBillingBlocks.normalizedCharacters), unitsFromNumber(input.pages, richContentBillingBlocks.pages), unitsFromNumber(input.spreadsheetRows, richContentBillingBlocks.spreadsheetRows), unitsFromNumber(input.slides, richContentBillingBlocks.slides), unitsFromNumber(input.mediaSeconds, richContentBillingBlocks.mediaSeconds), unitsFromNumber(input.images, richContentBillingBlocks.images));
793
+ }
794
+ export function calculateOverageCents(overage, overagePerThousandCents) {
795
+ if (overage <= 0 || overagePerThousandCents <= 0)
796
+ return 0;
797
+ return Math.ceil((overage * overagePerThousandCents) / 1000);
798
+ }
799
+ function billingBaseQuantity(input) {
800
+ if (input.billing.unit === 'call') {
801
+ return positiveInteger(input.fixedQuantity) ?? 1;
802
+ }
803
+ if (input.billing.unit === 'runtime_10s') {
804
+ return unitsFromNumber(input.durationMs, premiumRuntimeUnitMs);
805
+ }
806
+ if (input.billing.unit === 'token_block') {
807
+ return unitsFromNumber(input.tokenCount, tokenBillingBlockSize);
808
+ }
809
+ return unitsFromBytes(input.byteCount, byteBillingBlockSize);
810
+ }
811
+ function unitsFromNumber(value, unitSize) {
812
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
813
+ return 1;
814
+ return Math.max(1, Math.ceil(value / unitSize));
815
+ }
816
+ function unitsFromBytes(value, unitSize) {
817
+ if (typeof value === 'bigint') {
818
+ if (value <= 0n)
819
+ return 1;
820
+ return Number((value + BigInt(unitSize) - 1n) / BigInt(unitSize));
821
+ }
822
+ return unitsFromNumber(value, unitSize);
823
+ }
824
+ function positiveInteger(value) {
825
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;
826
+ }
827
+ function isBillingRecord(value) {
828
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
829
+ }
830
+ function isUsageOperationClass(value) {
831
+ return value === 'standard' || value === 'premium' || value === 'free';
832
+ }
833
+ function isBillingUnit(value) {
834
+ return value === 'call' || value === 'runtime_10s' || value === 'token_block' || value === 'byte_block';
835
+ }
836
+ function isQuantitySource(value) {
837
+ return value === 'fixed' || value === 'duration_ms' || value === 'tokens' || value === 'bytes';
838
+ }
839
+ function billingMultiplier(value) {
840
+ if (value === 1 || value === 2 || value === 3)
841
+ return value;
842
+ return undefined;
843
+ }
844
+ function formatCurrencyFromMicros(value, currency) {
845
+ const sign = value < 0n ? '-' : '';
846
+ const absolute = value < 0n ? -value : value;
847
+ const whole = absolute / 1000000n;
848
+ const fractional = absolute % 1000000n;
849
+ const cents = (fractional + 5000n) / 10000n;
850
+ const normalizedWhole = cents >= 100n ? whole + 1n : whole;
851
+ const normalizedCents = cents >= 100n ? cents - 100n : cents;
852
+ const symbol = currency === 'USD' ? '$' : `${currency} `;
853
+ return `${sign}${symbol}${normalizedWhole.toString()}.${normalizedCents.toString().padStart(2, '0')}`;
854
+ }
855
+ /** Integer micro-dollars are retained until a complete invoice line is rounded. */
856
+ export function microsToCents(micros) {
857
+ if (micros < 0n)
858
+ throw new Error('Billing amounts cannot be negative.');
859
+ const cents = (micros + 9999n) / 10000n;
860
+ if (cents > BigInt(Number.MAX_SAFE_INTEGER))
861
+ throw new Error('Billing amount exceeds supported range.');
862
+ return Number(cents);
863
+ }
864
+ export function standardChargeMicros(used, included, ratePerThousandCents) {
865
+ return BigInt(Math.max(0, used - included)) * BigInt(ratePerThousandCents) * 10n;
866
+ }
867
+ /** Anchor each boundary to the original day, including January 31 and leap years. */
868
+ export function billingMonthBoundary(anchor, months) {
869
+ const first = new Date(Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + months, 1, anchor.getUTCHours(), anchor.getUTCMinutes(), anchor.getUTCSeconds(), anchor.getUTCMilliseconds()));
870
+ const lastDay = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();
871
+ first.setUTCDate(Math.min(anchor.getUTCDate(), lastDay));
872
+ return first;
873
+ }
874
+ export function allowancePeriod(anchor, now, paidEnd) {
875
+ let months = Math.max(0, (now.getUTCFullYear() - anchor.getUTCFullYear()) * 12 + now.getUTCMonth() - anchor.getUTCMonth());
876
+ if (billingMonthBoundary(anchor, months) > now)
877
+ months = Math.max(0, months - 1);
878
+ const periodStart = billingMonthBoundary(anchor, months);
879
+ const next = billingMonthBoundary(anchor, months + 1);
880
+ return { periodStart, periodEnd: paidEnd && paidEnd < next ? paidEnd : next };
881
+ }
882
+ export const stagingManagedRateCard = {
883
+ version: 'staging-test-2026-09',
884
+ testOnly: true,
885
+ // Deliberately test-only: these are not supplier costs or approved production rates.
886
+ unitMicros: { call: 10000n, runtime_10s: 20000n, token_block: 10000n, byte_block: 1000n },
887
+ };
888
+ /** The current self-service upgrade. Legacy agreement migrations retain their
889
+ * explicit renewal flow; price comparisons must not change negotiated terms. */
890
+ export function billingPlanChangeTiming(from, to) {
891
+ return from === 'pro' && to === 'growth' ? 'immediate' : 'renewal';
892
+ }
893
+ //# sourceMappingURL=billing-plans.js.map