g1t/packages/contracts/src/billing.ts

955 lines39,016 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";
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}
550
551/** How much a workspace has earned g1t's trust with money. */
552export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
553
554/**
555 * How far a workspace's unpaid usage has gone this month, and where its
556 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
557 * requests. Usage counts at its cost to g1t or its charge, whichever is
558 * more, so it counts while g1t is free too.
559 */
560export type Limit = {
561 workspace: string;
562 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
563 account: string;
564 accountName: string;
565 trust: Trust;
566 exposureMicros: number;
567 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
568 ceilingMicros: number | null;
569 trustCeilingMicros: number | null;
570 spendLimitMicros: number | null;
571 state: "ok" | "warning" | "stopped";
572 message: string | null;
573 /** Charged this month: what the spend limit is measured against. */
574 spentMicros?: number;
575 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
576 defaultSpendLimit?: boolean;
577 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
578 availableMicros?: number | null;
579 /** How the ceiling grows from here, in a sentence. */
580 growth?: string | null;
581 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
582 prepaidMicros?: number;
583 /** The highest ceiling the workspace has had. */
584 maxCeilingMicros?: number | null;
585 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
586 raiseOnceMicros?: number | null;
587 /** When the one-time raise was used. */
588 raisedAt?: string | null;
589 /** A paid workspace's first billing cycle, on the starting ceiling. */
590 firstMonth?: boolean;
591};
592
593/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
594export type Price = {
595 meter:
596 | "sandbox_second"
597 | "build_second"
598 | "app_requests"
599 | "app_cpu"
600 | "app_month"
601 | "custom_domain_month"
602 | "private_storage"
603 | "embedding_tokens"
604 | "scan_cpu"
605 | "scan_rows"
606 | string;
607 title: string;
608 unit: string;
609 costMicros: number;
610 markupPercent: number;
611 priceMicros: number;
612 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
613 source: "list" | "cloudflare" | string;
614 checkedAt: string | null;
615 updatedAt: string;
616};
617
618export type PriceChange = {
619 meter: string;
620 oldCostMicros: number;
621 newCostMicros: number;
622 markupPercent: number;
623 /** The markup before, when the change was to the markup rather than the cost. */
624 oldMarkupPercent?: number;
625 reason: string;
626 createdAt: string;
627};
628
629export type PriceBook = {
630 prices: Price[];
631 changes: PriceChange[];
632 modelMarginPercent: number;
633 /** Every plan, as sold now. */
634 plans?: FeaturePlan[];
635 /** What is free, and the capped budgets that pay for it. */
636 free?: FreeTier | null;
637};
638
639/** One kind of meter's usage this month, from `usage_meters`. */
640export type MeterUsage = {
641 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
642 key: string;
643 label: string;
644 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
645 micros: number;
646 /** How much, when it is known: `12 runs`, `41 build minutes`. */
647 quantity?: string | null;
648};
649
650/** What g1t gives without a plan; each is paid for by a capped budget. */
651export type FreeTier = {
652 /** Each new workspace's trial credit, once. */
653 trialWorkspaceMicros: number;
654 /** Trial grants each month, in all; new trials wait when it is spent. */
655 trialMonthlyPoolMicros: number;
656 /** g1t's open-source pool each month, and any one repository's share. */
657 ossPoolMicros: number;
658 ossRepoMicros: number;
659 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
660 freePrivateStorageBytes: number;
661 /** Days of audit log, the same on every plan. */
662 auditRetentionDays: number;
663 /** The smallest amount a card is charged when a month closes; less carries over. */
664 minChargeMicros: number;
665 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
666 gitOperationsIncluded?: number;
667 /** A new paid workspace's ceiling in its first month. */
668 paidStartCeilingMicros?: number;
669 /** The most a one-click goodwill credit can cost g1t. */
670 overageForgiveCostMicros?: number;
671};
672
673/**
674 * A workspace's trial credit: one grant per workspace, made the first time
675 * it uses something, out of a pool that resets each calendar month. Mirrors
676 * `Trial` in `crates/contracts/src/billing.rs`.
677 */
678export type Trial = {
679 open: boolean;
680 usedMicros: number;
681 limitMicros: number;
682 /** No longer used: trials do not end on a date. */
683 endsAt: string | null;
684 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
685 reason: "off" | "ended" | "used" | "pool" | null;
686 /** Whether the workspace has its grant already. */
687 granted?: boolean;
688 /** With `pool`: when new trials start again, the first of next month. */
689 waitsUntil?: string | null;
690};
691
692/**
693 * What a workspace pays a monthly price for: the g1t plan (`plan`). Deployments
694 * are part of it; `has_feature` for `deployments` answers whether the workspace
695 * has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
696 */
697export type Feature = "plan" | "deployments";
698
699/**
700 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
701 * billing's price book cannot be read. Not an allowance: on the plan every
702 * unit is metered from the first, at cost plus 20%, and drawn from the
703 * plan's included usage first. Projects, previews and the apps behind them
704 * are not metered at all. Mirrors `deployment_costs`.
705 */
706export const DEPLOYMENT_COSTS = {
707 microsPerMillionRequests: 300_000,
708 microsPerMillionCpuMs: 20_000,
709 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
710 microsPerBuildSecond: 15,
711 /** One custom domain for a month. */
712 microsPerDomainMonth: 100_000,
713} as const;
714
715export type FeaturePlan = {
716 feature: Feature;
717 title: string;
718 /** Charged every month while the plan is on, in cents. */
719 monthlyCents: number;
720 /** What the price includes, one line each. */
721 includes: string[];
722 /** How usage past the allowance is charged. */
723 overage: string;
724};
725
726export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
727
728export type Subscription = {
729 feature: Feature;
730 status: SubscriptionStatus;
731 /** RFC 3339: when the period paid for ends. */
732 periodEnd: string | null;
733 startedBy: string;
734 startedAt: string;
735};
736
737/** A feature as a workspace sees it. */
738export type FeatureState = {
739 plan: FeaturePlan;
740 subscription: Subscription | null;
741 /** Whether the feature works for the workspace now. */
742 on: boolean;
743 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
744 included?: boolean;
745};
746
747export interface BillingApi {
748 status(): Promise<BillingStatus>;
749 /** Members of the workspace only. */
750 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
751 /** Newest first. Members of the workspace only. */
752 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
753 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
754 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
755 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
756 statementEntries(
757 workspace: string,
758 viewer: Viewer,
759 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
760 ): Promise<Result<LedgerEntry[]>>;
761 /** What the workspace's agents cost since `since`, broken down. Members only. */
762 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
763 /**
764 * Prepays usage ($25 at least) and returns the page to send the person to:
765 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
766 * The payment's id comes back to `returnUrl` as `session`.
767 */
768 checkout(
769 actor: User,
770 workspace: string,
771 amountCents: number,
772 returnUrl: string,
773 method?: "card" | "bank_transfer",
774 ): Promise<Result<{ url: string }>>;
775 /**
776 * Stripe's hosted billing page for the workspace: card, invoices, billing
777 * email and address. g1t never handles card numbers. Owners only.
778 */
779 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
780 /** Credits a payment once the processor says it was made. Safe to repeat. */
781 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
782 /**
783 * Whether a workspace may start an agent now, asked before anything is
784 * opened for it. A failure, with the reason to show, when it has no credit.
785 */
786 canStart(workspace: string): Promise<Result<boolean>>;
787 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
788 trial(workspace: string, exempt: string[]): Promise<Trial>;
789 /**
790 * Asks whether a workspace may start an agent and opens the run it will be
791 * charged for. Null when billing is off; a failure when there is no credit.
792 */
793 /** Every paid feature and the workspace's plan for each. Members only. */
794 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
795 /**
796 * Starts the card page for a feature's monthly plan. Owners only. The
797 * page's id comes back to `returnUrl` as `session`.
798 */
799 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
800 /** Turns the feature on once the plan is paid for. Safe to repeat. */
801 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
802 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
803 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
804 /** Whether a feature works for a workspace now; a failure with the reason when not. */
805 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
806 /**
807 * Usage past a plan's allowance, charged from credit at cost plus the
808 * margin, once per `reference`. False if it was charged before.
809 */
810 chargeFeature(charge: {
811 workspace: string;
812 feature: Feature;
813 costMicros: number;
814 description: string;
815 repo?: string | null;
816 reference: string;
817 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
818 buildSeconds?: number | null;
819 }): Promise<Result<boolean>>;
820 /**
821 * What a source cost g1t so far this month, so the workspace's limit
822 * counts it now. Replaces the last report. Billing charges `context`
823 * and `security` itself once the month is over; `deployments` charges
824 * its own.
825 */
826 notePending(
827 workspace: string,
828 source: "deployments" | "domains" | "context" | "security",
829 costMicros: number,
830 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
831 detail?: string | null,
832 ): Promise<boolean>;
833 /**
834 * This month's usage, one line per kind of meter, at what it is charged
835 * before the plan's included usage or a pool paid for it. Members only.
836 */
837 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
838 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
839 entitlements(workspace: string): Promise<Entitlements>;
840 /**
841 * Holds a start's estimated cost before the work starts. A failure's code says why not:
842 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
843 */
844 reserve(reservation: {
845 workspace: string;
846 repo: RepoPath;
847 public: boolean;
848 kind: ComputeKind;
849 /** The most the work is expected to cost g1t, before the margin. */
850 estimateMicros: number;
851 }): Promise<Result<ReservationHeld>>;
852 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
853 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
854 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
855 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
856 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
857 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
858 /** An owner asks for a higher limit, or for help with usage past what was meant. */
859 requestLimit(
860 actor: User,
861 workspace: string,
862 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
863 ): Promise<Result<LimitRequest>>;
864 /** The workspace's requests and their answers, newest first. Members only. */
865 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
866 /**
867 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
868 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
869 */
870 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
871 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
872 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
873 /** Every metered price and the recent changes. Public. */
874 prices(): Promise<PriceBook>;
875 /** A workspace's limit, for its members. */
876 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
877 /** The same, for the services that enforce it. */
878 checkLimit(workspace: string): Promise<Result<Limit>>;
879 /**
880 * The owners' own monthly limit, up to what is available; null goes back
881 * to the default, and `useFullLimit` uses everything available. Owners only.
882 */
883 setSpendLimit(
884 actor: User,
885 workspace: string,
886 spendLimitMicros: number | null,
887 useFullLimit?: boolean,
888 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
889 raiseOnce?: boolean,
890 ): Promise<Result<Limit>>;
891 /** The workspace's invoices from g1t, newest first. Members only. */
892 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
893 /**
894 * How long a sandbox ran for a workspace, reported when it stops. Its
895 * cost is recorded and every second is charged, from the first. False if
896 * `reference` was recorded before.
897 */
898 recordSandbox(usage: {
899 workspace: string;
900 seconds: number;
901 description: string;
902 repo?: string | null;
903 reference: string;
904 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
905 kind?: ComputeKind | null;
906 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
907 cpuSeconds?: number | null;
908 /** The reservation it started under, settled with this cost. */
909 reservationId?: string | null;
910 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
911 selfHosted?: boolean;
912 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
913 instance?: string | null;
914 }): Promise<Result<boolean>>;
915 startRun(run: {
916 workspace: string;
917 repo: RepoPath;
918 number: number;
919 task: string;
920 model: string;
921 /** `workspace` when the run uses the workspace's own model provider. */
922 billedTo?: "g1t" | "workspace";
923 /** The model session's id, so the run can be settled at AI Gateway's price. */
924 session?: string | null;
925 }): Promise<Result<RunTicket | null>>;
926}
927
928
929/** One slice of usage: what it was for, what it cost, how many runs. */
930export type UsageSlice = { key: string; micros: number; runs: number };
931
932/** What a workspace's agents cost over a period. */
933export type Usage = {
934 since: string;
935 /** Charged, including g1t's margin. */
936 spentMicros: number;
937 /** What g1t's model provider charged, before the margin. */
938 costMicros: number;
939 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
940 providerMicros: number;
941 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
942 usedMicros: number;
943 /** g1t charges nothing for now; the slices then measure usage at cost. */
944 free: boolean;
945 runs: number;
946 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
947 byDay: UsageSlice[];
948 byTask: UsageSlice[];
949 byRepo: UsageSlice[];
950 /** Keyed `namespace/name#number`. */
951 byPull: UsageSlice[];
952 byModel: UsageSlice[];
953 /** Credit bought in the period. */
954 addedMicros: number;
955};