pr_01m47d24b0e6n91zwymwxg0vpx/packages/contracts/src/billing.ts

486 lines18,738 bytesCodeBlame
1import type { User, Viewer } from "./identity";
2import type { RepoPath } from "./repos";
3import type { Result } from "./result";
4
5/** Millionths of a US dollar in one dollar: the unit money is held in. */
6export const MICROS_PER_DOLLAR = 1_000_000;
7
8/** Whether workspaces are charged for agents at all, and with real money. */
9export type BillingStatus = {
10 /**
11 * False when no card processor is configured: nothing is charged, and who
12 * may run agents is decided some other way.
13 */
14 enabled: boolean;
15 /** False while the card processor is in its test mode, where cards are not real. */
16 live: boolean;
17 /**
18 * True while g1t is being built out: runs are recorded with what they
19 * cost, but nothing is charged and no credit is needed. Not forever.
20 */
21 free?: boolean;
22};
23
24/** A workspace's standing. */
25export type BillingAccount = {
26 workspace: string;
27 /**
28 * Credit left, in millionths of a dollar. Can dip below zero by the cost
29 * of the runs that were under way when it ran out.
30 */
31 balanceMicros: number;
32 status: BillingStatus;
33 /** What is added to a run's cost, in percent. */
34 marginPercent: number;
35 /** What a run on the workspace's own model provider is charged instead. */
36 orchestrationFeeMicros: number;
37 /** The card charged near the limit and when a month closes, if one is saved. */
38 card?: { brand: string; last4: string; expMonth: number; expYear: number } | null;
39};
40
41/** One line of a workspace's statement. */
42export type LedgerEntry = {
43 id: string;
44 /** Credit bought with a card, or an agent's run. */
45 kind: "top_up" | "usage";
46 /** Positive for credit added, negative for usage. */
47 amountMicros: number;
48 description: string;
49 /** For usage: the repository and pull request the agent worked on. */
50 repo: string | null;
51 number: number | null;
52 /** For usage: `implement`, `review` or `update`. */
53 task: string | null;
54 /** For usage: the model, by its public name. */
55 model: string | null;
56 /** For usage: who paid the model provider. */
57 billedTo: "g1t" | "workspace";
58 /** For a top-up: the username of whoever paid. */
59 createdBy: string | null;
60 /** RFC 3339. */
61 createdAt: string;
62 /** The workspace the line belongs to, which tells an enterprise's lines apart. */
63 workspace?: string | null;
64};
65
66/** What lets a sandbox, and nothing else, report what its run cost. */
67export type RunTicket = { runId: string; token: string };
68
69/**
70 * What agents cost, charged to the workspace they worked for. A workspace
71 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
72 * no agent starts.
73 */
74/**
75 * The free allowance on g1t's hosted models for a workspace not otherwise
76 * open to them: a few dollars of model cost each, out of one pool, until a
77 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
78 */
79/** How an account is charged. Standard unless g1t set otherwise in sudo. */
80export type Terms = {
81 kind: "standard" | "comped" | "custom";
82 discountPercent: number;
83 ceilingMicros: number | null;
84 note: string;
85 until: string | null;
86 setBy: string | null;
87 setAt: string | null;
88};
89
90/**
91 * Who pays: a workspace's own account, or an enterprise's, which pays for
92 * several workspaces with one bill and one limit.
93 */
94export type PayingAccount = {
95 id: string;
96 kind: "workspace" | "enterprise";
97 name: string;
98 terms: Terms;
99 workspaces: string[];
100 /** Where an enterprise's invoices go. */
101 billingEmail?: string | null;
102 /** An enterprise's invoices, newest first. */
103 invoices?: EnterpriseInvoice[];
104 createdAt: string;
105};
106
107export type AccountSummary = {
108 account: PayingAccount;
109 limit: Limit;
110 chargedMicros: number;
111 costMicros: number;
112 paidMicros: number;
113 /** The same figures for each of the account's workspaces that has any. */
114 byWorkspace: WorkspaceFigures[];
115 /** The last six months, oldest first. */
116 months?: MonthFigures[];
117};
118
119/** One workspace's share of an `AccountSummary`. */
120export type WorkspaceFigures = { workspace: string; chargedMicros: number; costMicros: number; paidMicros: number };
121
122export type StripeStatus = {
123 /** `test` or `live`, from the key; `off` without one. */
124 mode: "test" | "live" | "off" | string;
125 webhook: { url: string; endpointId: string; events: string[]; createdBy: string; createdAt: string } | null;
126 recentEvents: { id: string; kind: string; outcome: string; receivedAt: string }[];
127 error: string | null;
128};
129
130/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
131export type EnterpriseInvoice = {
132 invoiceId: string;
133 hostedUrl: string | null;
134 amountMicros: number;
135 status: "open" | "paid" | "overdue" | "void" | string;
136 period: string;
137 lines: { workspace: string; amountMicros: number }[];
138 createdAt: string;
139};
140
141/** A workspace's invoice: monthly, or when charged near its limit. Itemised, in Stripe's billing page. */
142export type WorkspaceInvoice = {
143 invoiceId: string;
144 workspace: string;
145 reason: "month" | "threshold" | string;
146 period: string;
147 amountMicros: number;
148 status: "paid" | "open" | "failed" | "void" | string;
149 hostedUrl: string | null;
150 pdfUrl: string | null;
151 lines: { description: string; amountMicros: number }[];
152 createdAt: string;
153};
154
155export type MonthFigures = { month: string; chargedMicros: number; costMicros: number; paidMicros: number };
156
157export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend";
158
159/** Why a workspace is worth reaching out to. */
160export type Signal = {
161 workspace: string;
162 kind: SignalKind;
163 detail: string;
164 valueMicros: number;
165 stage: string | null;
166 owner: string | null;
167};
168
169export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
170
171export type SalesRecord = {
172 workspace: string;
173 stage: SalesStage | string;
174 owner: string | null;
175 nextStep: string | null;
176 nextAt: string | null;
177 notes: { id: string; text: string; by: string; createdAt: string }[];
178 updatedAt: string | null;
179};
180
181export type Overview = {
182 month: string;
183 months: MonthFigures[];
184 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
185 payingWorkspaces: number;
186 stopped: number;
187 nearCeiling: number;
188 declined: number;
189 openInvoicesMicros: number;
190 followUpsDue: number;
191};
192
193/** A customer's Stripe billing page, for staff to send them. */
194export type BillingLink = {
195 /** One-time and short-lived, signed in already. */
196 portalUrl: string;
197 /** The page's sign-in, which does not expire: the customer signs in by email. */
198 loginUrl: string | null;
199 customerEmail: string | null;
200 expiresNote: string;
201};
202
203export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
204
205export type AccountDetail = {
206 summary: AccountSummary;
207 workspaces: Limit[];
208 ledger: LedgerEntry[];
209 audit: AdminAction[];
210};
211
212/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
213export interface BillingAdminApi {
214 accounts(query?: string): Promise<AccountSummary[]>;
215 account(id: string): Promise<Result<AccountDetail>>;
216 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
217 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
218 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
219 credit(workspace: string, amountMicros: number, note: string, by: string): Promise<Result<LedgerEntry>>;
220 /** The workspace's Stripe billing page, to send to the customer. Logged. */
221 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
222 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
223 stripe(setup?: boolean, by?: string): Promise<StripeStatus>;
224 /** Where an enterprise's invoices go; makes its Stripe customer. */
225 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
226 /** Sends an enterprise its invoice now, for what its workspaces owe. */
227 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
228 /** Exactly these workspaces' accounts, such as one page of the list. */
229 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
230 /** Every workspace worth reaching out to, most urgent first. */
231 signals(): Promise<Signal[]>;
232 /** The business at a glance. */
233 overview(): Promise<Overview>;
234 /** A workspace's sales record. */
235 sales(workspace: string): Promise<SalesRecord>;
236 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
237 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
238 /** A workspace's invoices from g1t, for staff. */
239 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
240}
241
242/** How much a workspace has earned g1t's trust with money. */
243export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
244
245/**
246 * How far a workspace's unpaid usage has gone this month, and where its
247 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
248 * requests. Usage counts at its cost to g1t or its charge, whichever is
249 * more, so it counts while g1t is free too.
250 */
251export type Limit = {
252 workspace: string;
253 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
254 account: string;
255 accountName: string;
256 trust: Trust;
257 exposureMicros: number;
258 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
259 ceilingMicros: number | null;
260 trustCeilingMicros: number | null;
261 spendLimitMicros: number | null;
262 state: "ok" | "warning" | "stopped";
263 message: string | null;
264 /** Charged this month: what the spend limit is measured against. */
265 spentMicros?: number;
266 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
267 defaultSpendLimit?: boolean;
268 /** The most owners may set their own limit to; past it, they contact g1t. */
269 availableMicros?: number | null;
270 /** How the ceiling grows from here, in a sentence. */
271 growth?: string | null;
272};
273
274/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
275export type Price = {
276 meter: "sandbox_second" | "build_second" | "app_requests" | "app_cpu" | "app_month" | string;
277 title: string;
278 unit: string;
279 costMicros: number;
280 markupPercent: number;
281 priceMicros: number;
282 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
283 source: "list" | "cloudflare" | string;
284 checkedAt: string | null;
285 updatedAt: string;
286};
287
288export type PriceChange = {
289 meter: string;
290 oldCostMicros: number;
291 newCostMicros: number;
292 markupPercent: number;
293 reason: string;
294 createdAt: string;
295};
296
297export type PriceBook = { prices: Price[]; changes: PriceChange[]; modelMarginPercent: number };
298
299export type Trial = {
300 open: boolean;
301 usedMicros: number;
302 limitMicros: number;
303 endsAt: string | null;
304 /** Why it is closed: `off`, `ended`, `used` (this workspace's) or `pool` (everyone's). */
305 reason: "off" | "ended" | "used" | "pool" | null;
306};
307
308/**
309 * A paid feature a workspace turns on with a monthly plan, as Cloudflare's
310 * Workers for Platforms or Vercel's Pro are bought. Never free: neither
311 * `free` nor the model allowance covers it. Mirrors `Feature` in
312 * `crates/contracts/src/billing.rs`.
313 */
314export type Feature = "deployments";
315
316/** What the Deployments plan includes each month. Mirrors `deployments_allowance`. */
317export const DEPLOYMENTS_ALLOWANCE = {
318 apps: 10,
319 requests: 1_000_000,
320 cpuMs: 3_000_000,
321 /** What Cloudflare charges g1t past that, in millionths of a dollar. */
322 microsPerAppMonth: 20_000,
323 microsPerMillionRequests: 300_000,
324 microsPerMillionCpuMs: 20_000,
325 /** One second of a build's sandbox; builds are charged, not included. */
326 microsPerBuildSecond: 21,
327} as const;
328
329export type FeaturePlan = {
330 feature: Feature;
331 title: string;
332 /** Charged every month while the plan is on, in cents. */
333 monthlyCents: number;
334 /** What the price includes, one line each. */
335 includes: string[];
336 /** How usage past the allowance is charged. */
337 overage: string;
338};
339
340export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
341
342export type Subscription = {
343 feature: Feature;
344 status: SubscriptionStatus;
345 /** RFC 3339: when the period paid for ends. */
346 periodEnd: string | null;
347 startedBy: string;
348 startedAt: string;
349};
350
351/** A feature as a workspace sees it. */
352export type FeatureState = {
353 plan: FeaturePlan;
354 subscription: Subscription | null;
355 /** Whether the feature works for the workspace now. */
356 on: boolean;
357};
358
359export interface BillingApi {
360 status(): Promise<BillingStatus>;
361 /** Members of the workspace only. */
362 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
363 /** Newest first. Members of the workspace only. */
364 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
365 /** What the workspace's agents cost since `since`, broken down. Members only. */
366 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
367 /**
368 * Starts a card payment for credit and returns the page to send the
369 * person to. Owners only. The payment's id comes back to `returnUrl` as
370 * `session`.
371 */
372 checkout(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
373 /**
374 * Stripe's hosted billing page for the workspace: card, invoices, billing
375 * email and address. g1t never handles card numbers. Owners only.
376 */
377 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
378 /** Credits a payment once the processor says it was made. Safe to repeat. */
379 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
380 /**
381 * Whether a workspace may start an agent now, asked before anything is
382 * opened for it. A failure, with the reason to show, when it has no credit.
383 */
384 canStart(workspace: string): Promise<Result<boolean>>;
385 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
386 trial(workspace: string, exempt: string[]): Promise<Trial>;
387 /**
388 * Asks whether a workspace may start an agent and opens the run it will be
389 * charged for. Null when billing is off; a failure when there is no credit.
390 */
391 /** Every paid feature and the workspace's plan for each. Members only. */
392 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
393 /**
394 * Starts the card page for a feature's monthly plan. Owners only. The
395 * page's id comes back to `returnUrl` as `session`.
396 */
397 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
398 /** Turns the feature on once the plan is paid for. Safe to repeat. */
399 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
400 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
401 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
402 /** Whether a feature works for a workspace now; a failure with the reason when not. */
403 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
404 /**
405 * Usage past a plan's allowance, charged from credit at cost plus the
406 * margin, once per `reference`. False if it was charged before.
407 */
408 chargeFeature(charge: {
409 workspace: string;
410 feature: Feature;
411 costMicros: number;
412 description: string;
413 repo?: string | null;
414 reference: string;
415 }): Promise<Result<boolean>>;
416 /**
417 * Usage this month to be charged later (app traffic past a plan), so the
418 * workspace's limit counts it now. Replaces the last report.
419 */
420 notePending(workspace: string, source: "deployments", costMicros: number): Promise<boolean>;
421 /** Every metered price and the recent changes. Public. */
422 prices(): Promise<PriceBook>;
423 /** A workspace's limit, for its members. */
424 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
425 /** The same, for the services that enforce it. */
426 checkLimit(workspace: string): Promise<Result<Limit>>;
427 /**
428 * The owners' own monthly limit, up to what is available; null goes back
429 * to the default, and `useFullLimit` uses everything available. Owners only.
430 */
431 setSpendLimit(actor: User, workspace: string, spendLimitMicros: number | null, useFullLimit?: boolean): Promise<Result<Limit>>;
432 /** The workspace's invoices from g1t, newest first. Members only. */
433 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
434 /**
435 * How long a sandbox ran for a workspace, reported when it stops. Its
436 * cost is always recorded; seconds past the month's free minutes are
437 * charged. False if `reference` was recorded before.
438 */
439 recordSandbox(usage: {
440 workspace: string;
441 seconds: number;
442 description: string;
443 repo?: string | null;
444 reference: string;
445 }): Promise<Result<boolean>>;
446 startRun(run: {
447 workspace: string;
448 repo: RepoPath;
449 number: number;
450 task: string;
451 model: string;
452 /** `workspace` when the run uses the workspace's own model provider. */
453 billedTo?: "g1t" | "workspace";
454 /** The model session's id, so the run can be settled at AI Gateway's price. */
455 session?: string | null;
456 }): Promise<Result<RunTicket | null>>;
457}
458
459
460/** One slice of usage: what it was for, what it cost, how many runs. */
461export type UsageSlice = { key: string; micros: number; runs: number };
462
463/** What a workspace's agents cost over a period. */
464export type Usage = {
465 since: string;
466 /** Charged, including g1t's margin. */
467 spentMicros: number;
468 /** What g1t's model provider charged, before the margin. */
469 costMicros: number;
470 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
471 providerMicros: number;
472 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
473 usedMicros: number;
474 /** g1t charges nothing for now; the slices then measure usage at cost. */
475 free: boolean;
476 runs: number;
477 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
478 byDay: UsageSlice[];
479 byTask: UsageSlice[];
480 byRepo: UsageSlice[];
481 /** Keyed `namespace/name#number`. */
482 byPull: UsageSlice[];
483 byModel: UsageSlice[];
484 /** Credit bought in the period. */
485 addedMicros: number;
486};