g1t/packages/contracts/src/billing.ts

1,118 lines43,975 bytesCodeBlame
1import type { ComputeKind, Reservation } from "./compute";
2import type { User, Viewer } from "./identity";
3import type { RepoPath } from "./repos";
4import type { Result } from "./result";
5
6/** Millionths of a US dollar in one dollar: the unit money is held in. */
7export const MICROS_PER_DOLLAR = 1_000_000;
8
9/** Whether workspaces are charged for agents at all, and with real money. */
10export type BillingStatus = {
11 /**
12 * False when no card processor is configured: nothing is charged, and who
13 * may run agents is decided some other way.
14 */
15 enabled: boolean;
16 /** False while the card processor is in its test mode, where cards are not real. */
17 live: boolean;
18 /**
19 * True while g1t is being built out: runs are recorded with what they
20 * cost, but nothing is charged and no credit is needed. Not forever.
21 */
22 free?: boolean;
23};
24
25/** A workspace's standing. */
26export type BillingAccount = {
27 workspace: string;
28 /**
29 * Credit left, in millionths of a dollar. Can dip below zero by the cost
30 * of the runs that were under way when it ran out.
31 */
32 balanceMicros: number;
33 status: BillingStatus;
34 /** What is added to a run's cost, in percent. */
35 marginPercent: number;
36 /** The card charged near the limit and when a month closes, if one is saved. */
37 card?: { brand: string; last4: string; expMonth: number; expYear: number } | null;
38};
39
40/** One line of a workspace's statement. */
41export type LedgerEntry = {
42 id: string;
43 /** Credit bought with a card, or an agent's run. */
44 kind: "top_up" | "usage";
45 /** Positive for credit added, negative for usage. */
46 amountMicros: number;
47 description: string;
48 /** For usage: the repository and pull request the agent worked on. */
49 repo: string | null;
50 number: number | null;
51 /** For usage: `implement`, `review` or `update`. */
52 task: string | null;
53 /** For usage: the model, by its public name. */
54 model: string | null;
55 /** For usage: who paid the model provider. */
56 billedTo: "g1t" | "workspace";
57 /** For a top-up: the username of whoever paid. */
58 createdBy: string | null;
59 /** RFC 3339. */
60 createdAt: string;
61 /** The workspace the line belongs to, which tells an enterprise's lines apart. */
62 workspace?: string | null;
63 /** For usage: what the plan's included usage paid of it. `amountMicros` is what is left to pay. */
64 creditMicros?: number;
65 /** For usage: what the workspace's trial credit paid of it. */
66 trialMicros?: number;
67 /** For usage: what g1t's open-source pool paid of it. */
68 ossMicros?: number;
69 /** For usage: what g1t covered itself, such as a trial's last run past its credit. */
70 givenMicros?: number;
71};
72
73/** What lets a sandbox, and nothing else, report what its run cost. */
74export type RunTicket = { runId: string; token: string };
75
76/**
77 * What agents cost, charged to the workspace they worked for. A workspace
78 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
79 * no agent starts.
80 */
81/**
82 * The free allowance on g1t's hosted models for a workspace not otherwise
83 * open to them: a few dollars of model cost each, out of one pool, until a
84 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
85 */
86/** How an account is charged. Standard unless g1t set otherwise in sudo. */
87export type Terms = {
88 kind: "standard" | "comped" | "custom";
89 discountPercent: number;
90 ceilingMicros: number | null;
91 note: string;
92 until: string | null;
93 setBy: string | null;
94 setAt: string | null;
95};
96
97/**
98 * Who pays: a workspace's own account, or an enterprise's, which pays for
99 * several workspaces with one bill and one limit.
100 */
101export type PayingAccount = {
102 id: string;
103 kind: "workspace" | "enterprise";
104 name: string;
105 terms: Terms;
106 workspaces: string[];
107 /** Where an enterprise's invoices go. */
108 billingEmail?: string | null;
109 /** An enterprise's invoices, newest first. */
110 invoices?: EnterpriseInvoice[];
111 createdAt: string;
112 /** What g1t staff set for the account beyond its terms. */
113 allowances?: Allowances;
114};
115
116/** Set per account by g1t staff in sudo, on top of its terms. */
117export type Allowances = {
118 /** The g1t plan without its monthly price; usage is charged as usual. Comped accounts have it anyway. */
119 plan: boolean;
120 /** Each public repository's monthly cap on g1t's open-source pool; null for the default. */
121 ossRepoMicros: number | null;
122 /** Each workspace's trial credit, outside the monthly pool; null for the default. */
123 trialMicros: number | null;
124 /** Agents at once, in place of the plan's (2 in the first month or on the trial, then 10); null for the default. */
125 maxConcurrentAgents?: number | null;
126 /** One run's spend cap, in place of the owners' and the default $2; null for none. */
127 runCapMicros?: number | null;
128 /** What one issue's agents may spend in all, in place of the owners' and the default $10; null for none. */
129 issueCapMicros?: number | null;
130 /** A hold on new compute, with why; null for none. */
131 hold?: string | null;
132};
133
134// --- Entitlements, and compute started under a reservation ------------------
135//
136// Every service that starts compute asks billing first:
137// 1. `entitlements(workspace)`: what it may do at all, its caps, and whether compute is paused.
138// 2. `reserve(...)`: holds the estimate against what may pay for it, so starts at the same moment
139// cannot overshoot together. Answers who pays first, or refuses with a stable code
140// (`not_paid`, `trial_used`, `limit`, `paused`, `oss_pool_empty`) and a message for the owner.
141// 3. `settle(reservationId, actualMicros)`: releases the hold. The charge goes on the ledger the usual way.
142// A reservation never settled lapses after `RESERVATION_HOURS`.
143
144/** A reservation that is never settled stops holding after this long. */
145export const RESERVATION_HOURS = 3;
146/** What a ceiling reads as when there is none (g1t's own workspaces). */
147export const UNLIMITED_MICROS = 1_000_000_000_000_000;
148
149/** What a workspace pays g1t on, as far as compute is concerned. Mirrors `PlanKind`. */
150export type PlanKind = "free" | "paid" | "internal" | "enterprise";
151
152// `ComputeKind` (what compute is for), `PaidBy` (who pays first: credit, trial, oss, on_demand) and
153// `Reservation` are in `./compute`, with the gate that calls `reserve` and `settle`.
154
155/** One level reached: 50, 75, 90 or 100 percent. */
156export type UsageAlert = {
157 /** `included` (the plan's included usage), `spend_limit` or `ceiling`. */
158 meter: "included" | "spend_limit" | "ceiling" | string;
159 level: number;
160 usedMicros: number;
161 limitMicros: number;
162 message: string;
163};
164
165/** An hour's spend well above the workspace's usual: new compute waits for an owner. */
166export type Spike = {
167 id: string;
168 /** `open` (waiting), `continued` (keep going) or `stopped`. */
169 status: "open" | "continued" | "stopped" | string;
170 hourMicros: number;
171 averageMicros: number;
172 detectedAt: string;
173 decidedBy?: string | null;
174 decidedAt?: string | null;
175 /** While continued: until when, unless spend doubles again first. */
176 until?: string | null;
177};
178
179/** What a workspace may do now. Mirrors `Entitlements` in `crates/contracts/src/billing.rs`. */
180export type Entitlements = {
181 workspace: string;
182 plan: PlanKind;
183 /** May start sandboxes, models, deployments and semantic search at all: paid, internal, enterprise, or free with trial credit left. */
184 compute: boolean;
185 /** The one-time trial credit left; 0 if none or used. */
186 trialMicrosLeft: number;
187 /** A card check has been done; the trial and the open-source pool need it. */
188 trialVerified: boolean;
189 /** A paid workspace still in its first billing cycle. */
190 firstMonth: boolean;
191 /** 2 in the first month or on the trial, 10 after; staff can override it. */
192 maxConcurrentAgents: number;
193 /** 60 in the first month or on the trial; otherwise the guardrails' own caps. */
194 maxRunMinutes: number;
195 /** One run's spend cap, $2 by default; staff can override it. */
196 runCapMicros: number;
197 /** Agent spend on one issue in all, $10 by default. */
198 issueCapMicros: number;
199 /** g1t's ceiling on usage not yet paid for; `UNLIMITED_MICROS` for g1t's own; 0 for free. */
200 ceilingMicros: number;
201 /** Usage not yet paid for this month, prepayment taken off. */
202 exposureMicros: number;
203 /** Why new compute is paused, for the owner; null when it is not. */
204 paused: string | null;
205 /** What open reservations hold now. */
206 heldMicros?: number;
207 /** Paid in advance and not used yet. */
208 prepaidMicros?: number;
209 /** The plan's included usage each month, and what of it is used. */
210 includedMicros?: number;
211 includedUsedMicros?: number;
212 /** How far back the audit log can be read and exported: the same on every plan. */
213 auditRetentionDays: number;
214 /** Private repository storage free for every workspace: past it, the plan pays and a free workspace's pushes stop. */
215 freePrivateStorageBytes: number;
216 /** The last daily measure of the workspace's private repositories (a lower bound). */
217 privateStorageBytes: number;
218 /** What g1t's open-source pool paid for the workspace this month. */
219 ossPaidMicros: number;
220 /** Deploy build time this month, every second of it metered. */
221 buildSecondsUsed?: number;
222 /** Git operations this month, and how many are free for every workspace. */
223 gitOperations?: number;
224 gitOperationsIncluded?: number;
225 /** The smallest amount a card is charged when a month closes. */
226 minChargeMicros: number;
227 /** A spend spike waiting for an owner, or decided. */
228 spike?: Spike | null;
229 /** Where usage stands against what is included and the limits, from 50%. */
230 alerts?: UsageAlert[];
231};
232
233/** A hold on a start's estimated cost, as billing answers it (`Reservation` in `./compute`, and more). */
234export type ReservationHeld = Reservation & {
235 /** What is held, at cost; may be less than the estimate for a free workspace's last bit of trial. */
236 heldMicros?: number;
237 /** When the hold lapses if never settled. */
238 expiresAt?: string;
239};
240
241/** A request to g1t: a higher limit, or help with usage past what was meant. */
242export type LimitRequest = {
243 id: string;
244 workspace: string;
245 kind: "limit" | "overage" | string;
246 amountMicros: number;
247 reason: string;
248 expectedMonthlyMicros: number;
249 status: "open" | "approved" | "declined" | string;
250 decidedMicros?: number | null;
251 decidedBy?: string | null;
252 /** The answer, as the owner sees it. */
253 answer?: string | null;
254 createdBy: string;
255 createdAt: string;
256 decidedAt?: string | null;
257};
258
259/** What staff see beside a request. */
260export type WorkspaceHistory = {
261 plan: PlanKind | null;
262 months: MonthFigures[];
263 paidClearedMicros: number;
264 payments: number;
265 disputes: number;
266 declines: number;
267 firstSeen: string | null;
268 ceilingMicros: number | null;
269 maxCeilingMicros: number | null;
270 spendLimitMicros: number | null;
271 lastHourMicros: number;
272 averageHourMicros: number;
273 lastDayMicros: number;
274};
275
276export type LimitRequestReview = { request: LimitRequest; history: WorkspaceHistory };
277
278/** What a one-time goodwill credit comes to: the margin on the overage, always, plus its cost up to the cap. */
279export type Goodwill = {
280 overageMicros: number;
281 marginMicros: number;
282 costMicros: number;
283 creditMicros: number;
284 absorbedMicros: number;
285};
286
287/** A workspace whose month went well past its usual, or hit a spike. */
288export type Overage = {
289 workspace: string;
290 plan: PlanKind;
291 typicalMonthMicros: number;
292 thisMonthMicros: number;
293 costMicros: number;
294 marginMicros: number;
295 spike: Spike | null;
296 topEntries: LedgerEntry[];
297 goodwill: Goodwill;
298 goodwillAvailable: boolean;
299 lastGoodwillAt: string | null;
300 request: LimitRequest | null;
301};
302
303/** One workspace's recent pace. */
304export type Velocity = {
305 workspace: string;
306 plan: PlanKind;
307 lastHourMicros: number;
308 averageHourMicros: number;
309 lastDayMicros: number;
310 thisMonthMicros: number;
311 ratio: number;
312 spike: Spike | null;
313 firstSeen: string | null;
314};
315
316/** g1t's capped budgets for free usage this month. */
317export type Pools = {
318 month: string;
319 trialGrantedMicros: number;
320 trialPoolMicros: number;
321 trialGrants: number;
322 ossUsedMicros: number;
323 ossPoolMicros: number;
324 ossRepoMicros: number;
325};
326
327export type AccountSummary = {
328 account: PayingAccount;
329 limit: Limit;
330 chargedMicros: number;
331 costMicros: number;
332 paidMicros: number;
333 /** The same figures for each of the account's workspaces that has any. */
334 byWorkspace: WorkspaceFigures[];
335 /** The last six months, oldest first. */
336 months?: MonthFigures[];
337};
338
339/** One workspace's share of an `AccountSummary`. */
340export type WorkspaceFigures = { workspace: string; chargedMicros: number; costMicros: number; paidMicros: number };
341
342export type StripeStatus = {
343 /** `test` or `live`, from the key; `off` without one. */
344 mode: "test" | "live" | "off" | string;
345 webhook: { url: string; endpointId: string; events: string[]; createdBy: string; createdAt: string } | null;
346 recentEvents: { id: string; kind: string; outcome: string; receivedAt: string }[];
347 error: string | null;
348};
349
350/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
351export type EnterpriseInvoice = {
352 invoiceId: string;
353 hostedUrl: string | null;
354 amountMicros: number;
355 status: "open" | "paid" | "overdue" | "void" | string;
356 period: string;
357 lines: { workspace: string; amountMicros: number }[];
358 createdAt: string;
359};
360
361/** A workspace's invoice: monthly, or when charged near its limit. Itemised, in Stripe's billing page. */
362export type WorkspaceInvoice = {
363 invoiceId: string;
364 workspace: string;
365 reason: "month" | "threshold" | string;
366 period: string;
367 amountMicros: number;
368 status: "paid" | "open" | "failed" | "void" | string;
369 hostedUrl: string | null;
370 pdfUrl: string | null;
371 lines: { description: string; amountMicros: number }[];
372 createdAt: string;
373};
374
375/** A month of the ledger, grouped by day or project, a line per kind of charge. */
376export type Statement = {
377 month: string;
378 months: string[];
379 groups: {
380 key: string;
381 label: string;
382 /** `coveredMicros`: what the plan's included usage, the trial, the open-source pool or g1t paid, not in `chargedMicros`. */
383 lines: { kind: string; count: number; chargedMicros: number; costMicros: number; coveredMicros?: number }[];
384 chargedMicros: number;
385 }[];
386 totals: {
387 chargedMicros: number;
388 paidMicros: number;
389 costMicros: number;
390 entries: number;
391 /** What paid for usage before it was charged, such as "Paid by g1t's open-source pool". */
392 covered?: { source: "included" | "trial" | "oss_pool" | "given" | string; label: string; micros: number }[];
393 /** Owed when the month closed but under the minimum charge: on the next invoice. */
394 carriedMicros?: number;
395 };
396};
397
398export type MonthFigures = {
399 month: string;
400 /** Usage charged, after what paid for it first. */
401 chargedMicros: number;
402 /** What usage cost g1t: never a workspace's own model provider. */
403 costMicros: number;
404 paidMicros: number;
405 /** The plan's monthly price, paid. */
406 plansMicros?: number;
407 /** What g1t gave at price (internal use, trials, the open-source pool, goodwill, covered). Not margin. */
408 givenMicros?: number;
409};
410
411/** What g1t gave this month from one source. */
412export type GivenFigures = { source: "internal" | "trial" | "oss_pool" | "goodwill" | "covered" | string; label: string; micros: number; costMicros: number };
413
414/** One internal workspace's use this month, and why it is not charged. */
415export type InternalUse = { workspace: string; reason: string; costMicros: number; entries: number };
416
417export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend" | "cost_over_revenue";
418
419/** Why a workspace is worth reaching out to. */
420export type Signal = {
421 workspace: string;
422 kind: SignalKind;
423 detail: string;
424 valueMicros: number;
425 stage: string | null;
426 owner: string | null;
427 nextStep?: string | null;
428 /** When the next step is due, YYYY-MM-DD. */
429 nextAt?: string | null;
430};
431
432/** One invoice g1t has sent, a workspace's or an enterprise's. */
433export type InvoiceSummary = {
434 invoiceId: string;
435 kind: "workspace" | "enterprise";
436 account: string;
437 name: string;
438 reason: string;
439 period: string;
440 amountMicros: number;
441 status: string;
442 hostedUrl: string | null;
443 createdAt: string;
444 paidAt: string | null;
445};
446
447export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
448
449export type SalesRecord = {
450 workspace: string;
451 stage: SalesStage | string;
452 owner: string | null;
453 nextStep: string | null;
454 nextAt: string | null;
455 notes: { id: string; text: string; by: string; createdAt: string }[];
456 updatedAt: string | null;
457};
458
459export type Overview = {
460 month: string;
461 months: MonthFigures[];
462 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
463 payingWorkspaces: number;
464 stopped: number;
465 nearCeiling: number;
466 declined: number;
467 openInvoicesMicros: number;
468 followUpsDue: number;
469 /** g1t's capped budgets for free usage, this month. */
470 pools?: Pools | null;
471 /** Usage charged plus the plan's price paid, this month. */
472 revenueMicros?: number;
473 activePlans?: number;
474 planMrrMicros?: number;
475 /** What g1t gave this month, by source, apart from its margin. */
476 given?: GivenFigures[];
477 /** g1t's own and Flagon's workspaces: what their use cost, and why they are not charged. */
478 internal?: InternalUse[];
479 openRequests?: number;
480 overages?: number;
481 openSpikes?: number;
482};
483
484/** A customer's Stripe billing page, for staff to send them. */
485export type BillingLink = {
486 /** One-time and short-lived, signed in already. */
487 portalUrl: string;
488 /** The page's sign-in, which does not expire: the customer signs in by email. */
489 loginUrl: string | null;
490 customerEmail: string | null;
491 expiresNote: string;
492};
493
494export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
495
496export type AccountDetail = {
497 summary: AccountSummary;
498 workspaces: Limit[];
499 ledger: LedgerEntry[];
500 audit: AdminAction[];
501};
502
503/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
504export interface BillingAdminApi {
505 accounts(query?: string): Promise<AccountSummary[]>;
506 account(id: string): Promise<Result<AccountDetail>>;
507 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
508 /** Team on or off without charge, and the account's share of the pools. Needs a note. */
509 setAllowances(id: string, allowances: Allowances, note: string, by: string): Promise<Result<PayingAccount>>;
510 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
511 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
512 credit(workspace: string, amountMicros: number, note: string, by: string): Promise<Result<LedgerEntry>>;
513 /** The workspace's Stripe billing page, to send to the customer. Logged. */
514 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
515 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
516 stripe(setup?: boolean, by?: string): Promise<StripeStatus>;
517 /** Where an enterprise's invoices go; makes its Stripe customer. */
518 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
519 /** Sends an enterprise its invoice now, for what its workspaces owe. */
520 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
521 /** Exactly these workspaces' accounts, such as one page of the list. */
522 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
523 /** Every workspace worth reaching out to, most urgent first. */
524 signals(): Promise<Signal[]>;
525 /** The business at a glance. */
526 overview(): Promise<Overview>;
527 /** A workspace's sales record. */
528 sales(workspace: string): Promise<SalesRecord>;
529 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
530 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
531 /** A workspace's invoices from g1t, for staff. */
532 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
533 /** Every invoice g1t has sent, newest first. */
534 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
535 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
536 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
537 /** Limit and overage requests, with each workspace's history; `open` by default. */
538 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
539 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
540 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
541 /** The Overages queue. */
542 overages(): Promise<Overage[]>;
543 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. */
544 goodwill(workspace: string, amountMicros: number | null, reason: string, by: string, day?: string | null): Promise<Result<LedgerEntry>>;
545 /** Workspaces spending in the last day, fastest first. */
546 velocity(): Promise<Velocity[]>;
547 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
548 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
549 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
550 costs(days?: number): Promise<CostsReport>;
551 /** The open margin alerts, for the banner on every page. */
552 costAlerts(): Promise<MarginAlert[]>;
553 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
554 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
555 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
556 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
557 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
558 runCosts(by: string): Promise<Result<CostsRun>>;
559}
560
561/** How much a workspace has earned g1t's trust with money. */
562export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
563
564/**
565 * How far a workspace's unpaid usage has gone this month, and where its
566 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
567 * requests. Usage counts at its cost to g1t or its charge, whichever is
568 * more, so it counts while g1t is free too.
569 */
570export type Limit = {
571 workspace: string;
572 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
573 account: string;
574 accountName: string;
575 trust: Trust;
576 exposureMicros: number;
577 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
578 ceilingMicros: number | null;
579 trustCeilingMicros: number | null;
580 spendLimitMicros: number | null;
581 state: "ok" | "warning" | "stopped";
582 message: string | null;
583 /** Charged this month: what the spend limit is measured against. */
584 spentMicros?: number;
585 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
586 defaultSpendLimit?: boolean;
587 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
588 availableMicros?: number | null;
589 /** How the ceiling grows from here, in a sentence. */
590 growth?: string | null;
591 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
592 prepaidMicros?: number;
593 /** The highest ceiling the workspace has had. */
594 maxCeilingMicros?: number | null;
595 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
596 raiseOnceMicros?: number | null;
597 /** When the one-time raise was used. */
598 raisedAt?: string | null;
599 /** A paid workspace's first billing cycle, on the starting ceiling. */
600 firstMonth?: boolean;
601};
602
603/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
604export type Price = {
605 meter:
606 | "sandbox_second"
607 | "build_second"
608 | "app_requests"
609 | "app_cpu"
610 | "app_month"
611 | "custom_domain_month"
612 | "private_storage"
613 | "embedding_tokens"
614 | "scan_cpu"
615 | "scan_rows"
616 | string;
617 title: string;
618 unit: string;
619 costMicros: number;
620 markupPercent: number;
621 priceMicros: number;
622 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
623 source: "list" | "cloudflare" | string;
624 checkedAt: string | null;
625 updatedAt: string;
626};
627
628export type PriceChange = {
629 meter: string;
630 oldCostMicros: number;
631 newCostMicros: number;
632 markupPercent: number;
633 /** The markup before, when the change was to the markup rather than the cost. */
634 oldMarkupPercent?: number;
635 reason: string;
636 createdAt: string;
637 /** When a change still to come takes effect: a rise is announced before it is charged. */
638 effectiveAt?: string;
639};
640
641export type PriceBook = {
642 prices: Price[];
643 changes: PriceChange[];
644 modelMarginPercent: number;
645 /** Every plan, as sold now. */
646 plans?: FeaturePlan[];
647 /** What is free, and the capped budgets that pay for it. */
648 free?: FreeTier | null;
649};
650
651/** One kind of meter's usage this month, from `usage_meters`. */
652export type MeterUsage = {
653 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
654 key: string;
655 label: string;
656 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
657 micros: number;
658 /** How much, when it is known: `12 runs`, `41 build minutes`. */
659 quantity?: string | null;
660};
661
662/** What g1t gives without a plan; each is paid for by a capped budget. */
663export type FreeTier = {
664 /** Each new workspace's trial credit, once. */
665 trialWorkspaceMicros: number;
666 /** Trial grants each month, in all; new trials wait when it is spent. */
667 trialMonthlyPoolMicros: number;
668 /** g1t's open-source pool each month, and any one repository's share. */
669 ossPoolMicros: number;
670 ossRepoMicros: number;
671 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
672 freePrivateStorageBytes: number;
673 /** Days of audit log, the same on every plan. */
674 auditRetentionDays: number;
675 /** The smallest amount a card is charged when a month closes; less carries over. */
676 minChargeMicros: number;
677 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
678 gitOperationsIncluded?: number;
679 /** A new paid workspace's ceiling in its first month. */
680 paidStartCeilingMicros?: number;
681 /** The most a one-click goodwill credit can cost g1t. */
682 overageForgiveCostMicros?: number;
683};
684
685/**
686 * A workspace's trial credit: one grant per workspace, made the first time
687 * it uses something, out of a pool that resets each calendar month. Mirrors
688 * `Trial` in `crates/contracts/src/billing.rs`.
689 */
690export type Trial = {
691 open: boolean;
692 usedMicros: number;
693 limitMicros: number;
694 /** No longer used: trials do not end on a date. */
695 endsAt: string | null;
696 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
697 reason: "off" | "ended" | "used" | "pool" | null;
698 /** Whether the workspace has its grant already. */
699 granted?: boolean;
700 /** With `pool`: when new trials start again, the first of next month. */
701 waitsUntil?: string | null;
702};
703
704/**
705 * What a workspace pays a monthly price for: the g1t plan (`plan`). Deployments
706 * are part of it; `has_feature` for `deployments` answers whether the workspace
707 * has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
708 */
709export type Feature = "plan" | "deployments";
710
711/**
712 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
713 * billing's price book cannot be read. Not an allowance: on the plan every
714 * unit is metered from the first, at cost plus 20%, and drawn from the
715 * plan's included usage first. Projects, previews and the apps behind them
716 * are not metered at all. Mirrors `deployment_costs`.
717 */
718export const DEPLOYMENT_COSTS = {
719 microsPerMillionRequests: 300_000,
720 microsPerMillionCpuMs: 20_000,
721 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
722 microsPerBuildSecond: 15,
723 /** One custom domain for a month. */
724 microsPerDomainMonth: 100_000,
725} as const;
726
727export type FeaturePlan = {
728 feature: Feature;
729 title: string;
730 /** Charged every month while the plan is on, in cents. */
731 monthlyCents: number;
732 /** What the price includes, one line each. */
733 includes: string[];
734 /** How usage past the allowance is charged. */
735 overage: string;
736};
737
738export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
739
740export type Subscription = {
741 feature: Feature;
742 status: SubscriptionStatus;
743 /** RFC 3339: when the period paid for ends. */
744 periodEnd: string | null;
745 startedBy: string;
746 startedAt: string;
747};
748
749/** A feature as a workspace sees it. */
750export type FeatureState = {
751 plan: FeaturePlan;
752 subscription: Subscription | null;
753 /** Whether the feature works for the workspace now. */
754 on: boolean;
755 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
756 included?: boolean;
757};
758
759export interface BillingApi {
760 status(): Promise<BillingStatus>;
761 /** Members of the workspace only. */
762 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
763 /** Newest first. Members of the workspace only. */
764 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
765 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
766 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
767 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
768 statementEntries(
769 workspace: string,
770 viewer: Viewer,
771 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
772 ): Promise<Result<LedgerEntry[]>>;
773 /** What the workspace's agents cost since `since`, broken down. Members only. */
774 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
775 /**
776 * Prepays usage ($25 at least) and returns the page to send the person to:
777 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
778 * The payment's id comes back to `returnUrl` as `session`.
779 */
780 checkout(
781 actor: User,
782 workspace: string,
783 amountCents: number,
784 returnUrl: string,
785 method?: "card" | "bank_transfer",
786 ): Promise<Result<{ url: string }>>;
787 /**
788 * Stripe's hosted billing page for the workspace: card, invoices, billing
789 * email and address. g1t never handles card numbers. Owners only.
790 */
791 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
792 /** Credits a payment once the processor says it was made. Safe to repeat. */
793 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
794 /**
795 * Whether a workspace may start an agent now, asked before anything is
796 * opened for it. A failure, with the reason to show, when it has no credit.
797 */
798 canStart(workspace: string): Promise<Result<boolean>>;
799 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
800 trial(workspace: string, exempt: string[]): Promise<Trial>;
801 /**
802 * Asks whether a workspace may start an agent and opens the run it will be
803 * charged for. Null when billing is off; a failure when there is no credit.
804 */
805 /** Every paid feature and the workspace's plan for each. Members only. */
806 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
807 /**
808 * Starts the card page for a feature's monthly plan. Owners only. The
809 * page's id comes back to `returnUrl` as `session`.
810 */
811 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
812 /** Turns the feature on once the plan is paid for. Safe to repeat. */
813 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
814 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
815 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
816 /** Whether a feature works for a workspace now; a failure with the reason when not. */
817 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
818 /**
819 * Usage past a plan's allowance, charged from credit at cost plus the
820 * margin, once per `reference`. False if it was charged before.
821 */
822 chargeFeature(charge: {
823 workspace: string;
824 feature: Feature;
825 costMicros: number;
826 description: string;
827 repo?: string | null;
828 reference: string;
829 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
830 buildSeconds?: number | null;
831 }): Promise<Result<boolean>>;
832 /**
833 * What a source cost g1t so far this month, so the workspace's limit
834 * counts it now. Replaces the last report. Billing charges `context`
835 * and `security` itself once the month is over; `deployments` charges
836 * its own.
837 */
838 notePending(
839 workspace: string,
840 source: "deployments" | "domains" | "context" | "security",
841 costMicros: number,
842 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
843 detail?: string | null,
844 ): Promise<boolean>;
845 /**
846 * This month's usage, one line per kind of meter, at what it is charged
847 * before the plan's included usage or a pool paid for it. Members only.
848 */
849 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
850 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
851 entitlements(workspace: string): Promise<Entitlements>;
852 /**
853 * Holds a start's estimated cost before the work starts. A failure's code says why not:
854 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
855 */
856 reserve(reservation: {
857 workspace: string;
858 repo: RepoPath;
859 public: boolean;
860 kind: ComputeKind;
861 /** The most the work is expected to cost g1t, before the margin. */
862 estimateMicros: number;
863 }): Promise<Result<ReservationHeld>>;
864 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
865 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
866 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
867 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
868 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
869 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
870 /** An owner asks for a higher limit, or for help with usage past what was meant. */
871 requestLimit(
872 actor: User,
873 workspace: string,
874 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
875 ): Promise<Result<LimitRequest>>;
876 /** The workspace's requests and their answers, newest first. Members only. */
877 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
878 /**
879 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
880 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
881 */
882 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
883 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
884 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
885 /** Every metered price and the recent changes. Public. */
886 prices(): Promise<PriceBook>;
887 /** A workspace's limit, for its members. */
888 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
889 /** The same, for the services that enforce it. */
890 checkLimit(workspace: string): Promise<Result<Limit>>;
891 /**
892 * The owners' own monthly limit, up to what is available; null goes back
893 * to the default, and `useFullLimit` uses everything available. Owners only.
894 */
895 setSpendLimit(
896 actor: User,
897 workspace: string,
898 spendLimitMicros: number | null,
899 useFullLimit?: boolean,
900 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
901 raiseOnce?: boolean,
902 ): Promise<Result<Limit>>;
903 /** The workspace's invoices from g1t, newest first. Members only. */
904 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
905 /**
906 * How long a sandbox ran for a workspace, reported when it stops. Its
907 * cost is recorded and every second is charged, from the first. False if
908 * `reference` was recorded before.
909 */
910 recordSandbox(usage: {
911 workspace: string;
912 seconds: number;
913 description: string;
914 repo?: string | null;
915 reference: string;
916 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
917 kind?: ComputeKind | null;
918 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
919 cpuSeconds?: number | null;
920 /** The reservation it started under, settled with this cost. */
921 reservationId?: string | null;
922 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
923 selfHosted?: boolean;
924 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
925 instance?: string | null;
926 }): Promise<Result<boolean>>;
927 startRun(run: {
928 workspace: string;
929 repo: RepoPath;
930 number: number;
931 task: string;
932 model: string;
933 /** `workspace` when the run uses the workspace's own model provider. */
934 billedTo?: "g1t" | "workspace";
935 /** The model session's id, so the run can be settled at AI Gateway's price. */
936 session?: string | null;
937 }): Promise<Result<RunTicket | null>>;
938}
939
940
941/** One slice of usage: what it was for, what it cost, how many runs. */
942export type UsageSlice = { key: string; micros: number; runs: number };
943
944/** What a workspace's agents cost over a period. */
945export type Usage = {
946 since: string;
947 /** Charged, including g1t's margin. */
948 spentMicros: number;
949 /** What g1t's model provider charged, before the margin. */
950 costMicros: number;
951 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
952 providerMicros: number;
953 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
954 usedMicros: number;
955 /** g1t charges nothing for now; the slices then measure usage at cost. */
956 free: boolean;
957 runs: number;
958 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
959 byDay: UsageSlice[];
960 byTask: UsageSlice[];
961 byRepo: UsageSlice[];
962 /** Keyed `namespace/name#number`. */
963 byPull: UsageSlice[];
964 byModel: UsageSlice[];
965 /** Credit bought in the period. */
966 addedMicros: number;
967};
968
969/** One of g1t's products (a "bucket") on one day. Money in micros. */
970export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
971
972/** One product over the range: what customers were charged at price against what it cost. */
973export type ProductMargin = {
974 bucket: string;
975 title: string;
976 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
977 costMicros: number;
978 cfCostMicros: number;
979 ownCostMicros: number;
980 valueMicros: number;
981 marginMicros: number;
982 marginPercent: number | null;
983 costSource: "cloudflare" | "ledger" | string;
984 /** Running g1t, paid for by the plan. */
985 overhead: boolean;
986};
987
988/** All of g1t: money in (usage and the plan) against every cost. */
989export type OverallMargin = { usageMicros: number; plansMicros: number; costMicros: number; marginMicros: number; marginPercent: number | null };
990
991/** A count, cost or leak that does not add up. */
992export type CostDrift = {
993 bucket: string;
994 title: string;
995 kind: "count" | "cost" | "leak" | string;
996 ours: number;
997 cloudflare: number;
998 deltaPercent: number | null;
999 detail: string;
1000 foundAt: string;
1001};
1002
1003export type MarginAlert = {
1004 id: string;
1005 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1006 /** The product, or the workspace. */
1007 subject: string;
1008 detail: string;
1009 since: string;
1010 openedAt: string;
1011 emailedAt: string | null;
1012};
1013
1014/** A change to a price, measured from what Cloudflare charged. */
1015export type PriceProposal = {
1016 id: string;
1017 meter: string;
1018 title: string;
1019 unit: string;
1020 currentCostMicros: number;
1021 proposedCostMicros: number;
1022 changePercent: number;
1023 markupPercent: number;
1024 reason: string;
1025 source: "keeper" | "reconciler" | string;
1026 /** Far off the current cost: look before approving. */
1027 suspect: boolean;
1028 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1029 createdAt: string;
1030 decidedAt: string | null;
1031 decidedBy: string | null;
1032 note: string | null;
1033 effectiveAt: string | null;
1034};
1035
1036/** One version of one meter's price; never changed once written. */
1037export type PriceVersion = {
1038 id: string;
1039 meter: string;
1040 version: number;
1041 costMicros: number;
1042 markupPercent: number;
1043 priceMicros: number;
1044 effectiveAt: string;
1045 reason: string;
1046 createdBy: string;
1047 appliedAt: string | null;
1048};
1049
1050export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; internal: boolean };
1051
1052export type CostLineSummary = {
1053 product: string;
1054 meter: string;
1055 rawName: string;
1056 unit: string;
1057 source: string;
1058 quantity: number;
1059 costMicros: number;
1060 /** Absent when no mapping claims it. */
1061 bucket: string | null;
1062};
1063
1064export type CostMapping = {
1065 product: string;
1066 meter: string;
1067 bucket: string;
1068 priceMeter: string | null;
1069 ownMeter: string | null;
1070 scaleToOwn: boolean;
1071 driftPercent: number;
1072 note: string;
1073 updatedAt: string;
1074 updatedBy: string;
1075};
1076
1077export type CostMappingInput = {
1078 product: string;
1079 meter: string;
1080 bucket?: string;
1081 priceMeter?: string | null;
1082 ownMeter?: string | null;
1083 scaleToOwn?: boolean;
1084 driftPercent?: number | null;
1085 note?: string;
1086 remove?: boolean;
1087};
1088
1089export type CostSettings = {
1090 autoApply: boolean;
1091 autoApplyPercent: number;
1092 noticeDays: number;
1093 marginFloorPercent: number;
1094 alertDays: number;
1095 minDailyCostMicros: number;
1096 anomalyFactor: number;
1097 anomalyFloorMicros: number;
1098};
1099
1100export type CostsReport = {
1101 configured: boolean;
1102 fetchedAt: string | null;
1103 since: string;
1104 until: string;
1105 days: CostDay[];
1106 products: ProductMargin[];
1107 overall: OverallMargin;
1108 drift: CostDrift[];
1109 alerts: MarginAlert[];
1110 proposals: PriceProposal[];
1111 versions: PriceVersion[];
1112 topWorkspaces: WorkspaceCost[];
1113 lines: CostLineSummary[];
1114 mappings: CostMapping[];
1115 settings: CostSettings;
1116};
1117
1118export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };