Skip to content

g1t/packages/contracts/src/billing.ts

1,586 lines62,984 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 /** For usage: what the account's discount took off its price. */
72 discountMicros?: number;
73 /** For a credit from g1t, and for what of one expired or was revoked: its kind. */
74 creditKind?: CreditKind;
75};
76
77/**
78 * Why g1t gave a workspace credit. Promotional (a welcome, a referral) and
79 * goodwill (an apology) are given away when spent; a refund gives back
80 * money already paid, and never expires.
81 */
82export type CreditKind = "promotional" | "goodwill" | "refund" | "purchased";
83
84/** One credit g1t gave, with what of it was used: spent before anything paid in advance, the soonest-expiring first. */
85export type CreditGrant = {
86 /** `crd_…`, the grant's ledger reference. */
87 id: string;
88 workspace: string;
89 kind: CreditKind;
90 amountMicros: number;
91 usedMicros: number;
92 /** What can still be spent: nothing once it expired or was revoked. */
93 leftMicros: number;
94 note: string;
95 /** A refund: what it refunds, and the day of it. */
96 refundFor?: string | null;
97 refundDay?: string | null;
98 /** RFC 3339; null never expires. */
99 expiresAt: string | null;
100 createdBy: string;
101 createdAt: string;
102 state: "open" | "used" | "expired" | "revoked";
103 closedAt?: string | null;
104 closedNote?: string | null;
105 closedBy?: string | null;
106 /** What expiring or revoking took off the balance. */
107 closedMicros?: number;
108 /** What it pays for: all usage, or models only (spent first). */
109 scope?: "all" | "models";
110 /** Where it came from. */
111 source?: "staff" | "purchase" | "promo_code" | "upgrade";
112};
113
114/** A workspace's credits from g1t, newest first. */
115export type Credits = { grants: CreditGrant[]; leftMicros: number };
116
117/** One month's credits of one kind: given, spent that month, and taken back unused. */
118export type CreditMonth = {
119 month: string;
120 kind: CreditKind;
121 givenMicros: number;
122 grants: number;
123 usedMicros: number;
124 expiredMicros: number;
125 revokedMicros: number;
126};
127
128/** Every credit g1t gave (at most 200, filtered), the last 12 months by kind, and who gave them. */
129export type AdminCredits = { grants: CreditGrant[]; months: CreditMonth[]; staff: string[] };
130
131/** What a credit from sudo is, past its amount and note. */
132export type CreditOptions = {
133 kind: CreditKind;
134 /** RFC 3339; never for a refund. */
135 expiresAt?: string | null;
136 /** A refund: what it is for, and the day refunded (`YYYY-MM-DD`). */
137 refundFor?: string | null;
138 refundDay?: string | null;
139};
140
141/** What lets a sandbox, and nothing else, report what its run cost. */
142export type RunTicket = { runId: string; token: string };
143
144/**
145 * What agents cost, charged to the workspace they worked for. A workspace
146 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
147 * no agent starts.
148 */
149/**
150 * The free allowance on g1t's hosted models for a workspace not otherwise
151 * open to them: a few dollars of model cost each, out of one pool, until a
152 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
153 */
154/**
155 * How an account is charged. Standard unless g1t set otherwise in sudo:
156 * custom terms are a discount (0 to 100%), a ceiling, or both. A 100%
157 * discount charges nothing and shows the usage at its price. `comped` is
158 * from before discounts and reads as 100%; billing no longer writes it.
159 */
160export type Terms = {
161 kind: "standard" | "comped" | "custom";
162 discountPercent: number;
163 ceilingMicros: number | null;
164 note: string;
165 until: string | null;
166 setBy: string | null;
167 setAt: string | null;
168};
169
170/**
171 * Who pays: a workspace's own account, or an enterprise's, which pays for
172 * several workspaces with one bill and one limit.
173 */
174export type PayingAccount = {
175 id: string;
176 kind: "workspace" | "enterprise";
177 name: string;
178 terms: Terms;
179 workspaces: string[];
180 /** Where an enterprise's invoices go. */
181 billingEmail?: string | null;
182 /** An enterprise's invoices, newest first. */
183 invoices?: EnterpriseInvoice[];
184 createdAt: string;
185 /** What g1t staff set for the account beyond its terms. */
186 allowances?: Allowances;
187};
188
189/** Set per account by g1t staff in sudo, on top of its terms. */
190export type Allowances = {
191 /** The g1t plan without its monthly price; usage is charged as usual. Comped accounts have it anyway. */
192 plan: boolean;
193 /** Each public repository's monthly cap on g1t's open-source pool; null for the default. */
194 ossRepoMicros: number | null;
195 /** Each workspace's trial credit, outside the monthly pool; null for the default. */
196 trialMicros: number | null;
197 /** Agents at once, in place of the plan's (2 in the first month or on the trial, then 10); null for the default. */
198 maxConcurrentAgents?: number | null;
199 /** One run's spend cap, in place of the owners' and the default $2; null for none. */
200 runCapMicros?: number | null;
201 /** What one issue's agents may spend in all, in place of the owners' and the default $10; null for none. */
202 issueCapMicros?: number | null;
203 /** Days of audit log its workspaces keep, in place of the plan's (7 free, 90 on the plan), longer or shorter; null for the plan's. */
204 auditRetentionDays?: number | null;
205 /** A hold on new compute, with why; null for none. */
206 hold?: string | null;
207};
208
209// --- Entitlements, and compute started under a reservation ------------------
210//
211// Every service that starts compute asks billing first:
212// 1. `entitlements(workspace)`: what it may do at all, its caps, and whether compute is paused.
213// 2. `reserve(...)`: holds the estimate against what may pay for it, so starts at the same moment
214// cannot overshoot together. Answers who pays first, or refuses with a stable code
215// (`not_paid`, `trial_used`, `limit`, `paused`, `oss_pool_empty`) and a message for the owner.
216// 3. `settle(reservationId, actualMicros)`: releases the hold. The charge goes on the ledger the usual way.
217// A reservation never settled lapses after `RESERVATION_HOURS`.
218
219/** A reservation that is never settled stops holding after this long. */
220export const RESERVATION_HOURS = 3;
221/** What a ceiling reads as when there is none (g1t's own workspaces). */
222export const UNLIMITED_MICROS = 1_000_000_000_000_000;
223
224/** What a workspace pays g1t on, as far as compute is concerned. Mirrors `PlanKind`. */
225export type PlanKind = "free" | "paid" | "internal" | "enterprise";
226
227// `ComputeKind` (what compute is for), `PaidBy` (who pays first: credit, trial, oss, on_demand) and
228// `Reservation` are in `./compute`, with the gate that calls `reserve` and `settle`.
229
230/** One level reached: 50, 75, 90 or 100 percent. */
231export type UsageAlert = {
232 /** `included` (the plan's included usage), `spend_limit` or `ceiling`. */
233 meter: "included" | "spend_limit" | "ceiling" | string;
234 level: number;
235 usedMicros: number;
236 limitMicros: number;
237 message: string;
238};
239
240/** An hour's spend well above the workspace's usual: new compute waits for an owner. */
241export type Spike = {
242 id: string;
243 /** `open` (waiting), `continued` (keep going) or `stopped`. */
244 status: "open" | "continued" | "stopped" | string;
245 hourMicros: number;
246 averageMicros: number;
247 detectedAt: string;
248 decidedBy?: string | null;
249 decidedAt?: string | null;
250 /** While continued: until when, unless spend doubles again first. */
251 until?: string | null;
252};
253
254/** What a workspace may do now. Mirrors `Entitlements` in `crates/contracts/src/billing.rs`. */
255export type Entitlements = {
256 workspace: string;
257 plan: PlanKind;
258 /** May start sandboxes, models, deployments and semantic search at all: paid, internal, enterprise, or free with trial credit left. */
259 compute: boolean;
260 /** The one-time trial credit left; 0 if none or used. */
261 trialMicrosLeft: number;
262 /** A card check has been done; the trial and the open-source pool need it. */
263 trialVerified: boolean;
264 /** A paid workspace still in its first billing cycle. */
265 firstMonth: boolean;
266 /** 2 in the first month or on the trial, 10 after; staff can override it. */
267 maxConcurrentAgents: number;
268 /** 60 in the first month or on the trial; otherwise the guardrails' own caps. */
269 maxRunMinutes: number;
270 /** One run's spend cap, $2 by default; staff can override it. */
271 runCapMicros: number;
272 /** Agent spend on one issue in all, $10 by default. */
273 issueCapMicros: number;
274 /** g1t's ceiling on usage not yet paid for; `UNLIMITED_MICROS` for g1t's own; 0 for free. */
275 ceilingMicros: number;
276 /** Usage not yet paid for this month, prepayment taken off. */
277 exposureMicros: number;
278 /** Why new compute is paused, for the owner; null when it is not. */
279 paused: string | null;
280 /** What open reservations hold now. */
281 heldMicros?: number;
282 /** Paid in advance and not used yet. */
283 prepaidMicros?: number;
284 /** The plan's included usage each month, and what of it is used. */
285 includedMicros?: number;
286 includedUsedMicros?: number;
287 /** How far back the audit log can be read and exported, and what is kept: the plan's days, or what g1t staff set for the account. */
288 auditRetentionDays: number;
289 /** Whether `auditRetentionDays` is what staff set for the account rather than the plan's. */
290 auditRetentionCustom?: boolean;
291 /** Private repository storage free for every workspace: past it, the plan pays and a free workspace's pushes stop. */
292 freePrivateStorageBytes: number;
293 /** The last daily measure of the workspace's private repositories (a lower bound). */
294 privateStorageBytes: number;
295 /** On a paid plan: package storage past the free amounts is charged, never refused. */
296 hasPlan?: boolean;
297 /** Package storage free for every workspace (public, and private): past it a free workspace's pushes are refused. */
298 packagePublicFreeBytes?: number;
299 packagePrivateFreeBytes?: number;
300 /** What g1t's open-source pool paid for the workspace this month. */
301 ossPaidMicros: number;
302 /** Deploy build time this month, every second of it metered. */
303 buildSecondsUsed?: number;
304 /** Git operations this month, and how many are free for every workspace. */
305 gitOperations?: number;
306 gitOperationsIncluded?: number;
307 /** The smallest amount a card is charged when a month closes. */
308 minChargeMicros: number;
309 /** A spend spike waiting for an owner, or decided. */
310 spike?: Spike | null;
311 /** Where usage stands against what is included and the limits, from 50%. */
312 alerts?: UsageAlert[];
313};
314
315/** A hold on a start's estimated cost, as billing answers it (`Reservation` in `./compute`, and more). */
316export type ReservationHeld = Reservation & {
317 /** What is held, at cost; may be less than the estimate for a free workspace's last bit of trial. */
318 heldMicros?: number;
319 /** When the hold lapses if never settled. */
320 expiresAt?: string;
321};
322
323/** A request to g1t: a higher limit, or help with usage past what was meant. */
324export type LimitRequest = {
325 id: string;
326 workspace: string;
327 kind: "limit" | "overage" | string;
328 amountMicros: number;
329 reason: string;
330 expectedMonthlyMicros: number;
331 status: "open" | "approved" | "declined" | string;
332 decidedMicros?: number | null;
333 decidedBy?: string | null;
334 /** The answer, as the owner sees it. */
335 answer?: string | null;
336 createdBy: string;
337 createdAt: string;
338 decidedAt?: string | null;
339};
340
341/** What staff see beside a request. */
342export type WorkspaceHistory = {
343 plan: PlanKind | null;
344 months: MonthFigures[];
345 paidClearedMicros: number;
346 payments: number;
347 disputes: number;
348 declines: number;
349 firstSeen: string | null;
350 ceilingMicros: number | null;
351 maxCeilingMicros: number | null;
352 spendLimitMicros: number | null;
353 lastHourMicros: number;
354 averageHourMicros: number;
355 lastDayMicros: number;
356};
357
358export type LimitRequestReview = { request: LimitRequest; history: WorkspaceHistory };
359
360/** What a one-time goodwill credit comes to: the margin on the overage, always, plus its cost up to the cap. */
361export type Goodwill = {
362 overageMicros: number;
363 marginMicros: number;
364 costMicros: number;
365 creditMicros: number;
366 absorbedMicros: number;
367};
368
369/** A workspace whose month went well past its usual, or hit a spike. */
370export type Overage = {
371 workspace: string;
372 plan: PlanKind;
373 typicalMonthMicros: number;
374 thisMonthMicros: number;
375 costMicros: number;
376 marginMicros: number;
377 spike: Spike | null;
378 topEntries: LedgerEntry[];
379 goodwill: Goodwill;
380 goodwillAvailable: boolean;
381 lastGoodwillAt: string | null;
382 request: LimitRequest | null;
383};
384
385/** One workspace's recent pace. */
386export type Velocity = {
387 workspace: string;
388 plan: PlanKind;
389 lastHourMicros: number;
390 averageHourMicros: number;
391 lastDayMicros: number;
392 thisMonthMicros: number;
393 ratio: number;
394 spike: Spike | null;
395 firstSeen: string | null;
396};
397
398/** g1t's capped budgets for free usage this month. */
399export type Pools = {
400 month: string;
401 trialGrantedMicros: number;
402 trialPoolMicros: number;
403 trialGrants: number;
404 ossUsedMicros: number;
405 ossPoolMicros: number;
406 ossRepoMicros: number;
407};
408
409export type AccountSummary = {
410 account: PayingAccount;
411 limit: Limit;
412 chargedMicros: number;
413 costMicros: number;
414 paidMicros: number;
415 /** The same figures for each of the account's workspaces that has any. */
416 byWorkspace: WorkspaceFigures[];
417 /** The last six months, oldest first. */
418 months?: MonthFigures[];
419};
420
421/** One workspace's share of an `AccountSummary`. */
422export type WorkspaceFigures = { workspace: string; chargedMicros: number; costMicros: number; paidMicros: number };
423
424export type StripeStatus = {
425 /** `test` or `live`, from the key; `off` without one. */
426 mode: "test" | "live" | "off" | string;
427 /** Whether `STRIPE_WEBHOOK_SECRET` is set, so events can be checked. */
428 secretSet: boolean;
429 /** The destination at billing's address in Stripe, as Stripe has it. */
430 webhook: { url: string; endpointId: string; status: "enabled" | "disabled" | string; events: string[]; createdAt: string } | null;
431 /** Events billing handles that the destination does not send. */
432 missingEvents: string[];
433 recentEvents: { id: string; kind: string; outcome: string; receivedAt: string }[];
434 error: string | null;
435};
436
437/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
438export type EnterpriseInvoice = {
439 invoiceId: string;
440 hostedUrl: string | null;
441 amountMicros: number;
442 status: "open" | "paid" | "overdue" | "void" | string;
443 period: string;
444 lines: { workspace: string; amountMicros: number }[];
445 createdAt: string;
446};
447
448/** A workspace's invoice: monthly, or when charged near its limit. Itemised, in Stripe's billing page. */
449export type WorkspaceInvoice = {
450 invoiceId: string;
451 workspace: string;
452 reason: "month" | "threshold" | string;
453 period: string;
454 amountMicros: number;
455 status: "paid" | "open" | "failed" | "void" | string;
456 hostedUrl: string | null;
457 pdfUrl: string | null;
458 lines: { description: string; amountMicros: number }[];
459 createdAt: string;
460};
461
462/** A month of the ledger, grouped by day or project, a line per kind of charge. */
463export type Statement = {
464 month: string;
465 months: string[];
466 groups: {
467 key: string;
468 label: string;
469 /** `coveredMicros`: what the plan's included usage, the trial, the open-source pool or g1t paid, not in `chargedMicros`. */
470 /** `priceMicros`: usage at its price; `discountMicros`: what the account's discount took off it. */
471 lines: {
472 kind: string;
473 count: number;
474 chargedMicros: number;
475 costMicros: number;
476 coveredMicros?: number;
477 priceMicros?: number;
478 discountMicros?: number;
479 }[];
480 chargedMicros: number;
481 priceMicros?: number;
482 discountMicros?: number;
483 }[];
484 totals: {
485 chargedMicros: number;
486 paidMicros: number;
487 costMicros: number;
488 entries: number;
489 /** Usage at price, and what the discount took off: charged is the price less the discount and what paid for it. */
490 priceMicros?: number;
491 discountMicros?: number;
492 /** The account's discount now, in percent; absent without one. */
493 discountPercent?: number | null;
494 /** What paid for usage before it was charged, such as "Paid by g1t's open-source pool". */
495 covered?: { source: "included" | "trial" | "oss_pool" | "given" | string; label: string; micros: number }[];
496 /** Owed when the month closed but under the minimum charge: on the next invoice. */
497 carriedMicros?: number;
498 };
499};
500
501export type MonthFigures = {
502 month: string;
503 /** Usage charged, after what paid for it first. */
504 chargedMicros: number;
505 /** What usage cost g1t: never a workspace's own model provider. */
506 costMicros: number;
507 paidMicros: number;
508 /** The plan's monthly price, paid. */
509 plansMicros?: number;
510 /** What g1t gave at price (internal use, trials, the open-source pool, goodwill, covered). Not margin. */
511 givenMicros?: number;
512};
513
514/** What g1t gave this month from one source. */
515export type GivenFigures = { source: "internal" | "trial" | "oss_pool" | "goodwill" | "covered" | string; label: string; micros: number; costMicros: number };
516
517/** One internal workspace's use this month, and why it is not charged. */
518export type InternalUse = { workspace: string; reason: string; costMicros: number; entries: number };
519
520export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend" | "cost_over_revenue";
521
522/** Why a workspace is worth reaching out to. */
523export type Signal = {
524 workspace: string;
525 kind: SignalKind;
526 detail: string;
527 valueMicros: number;
528 stage: string | null;
529 owner: string | null;
530 nextStep?: string | null;
531 /** When the next step is due, YYYY-MM-DD. */
532 nextAt?: string | null;
533};
534
535/** One invoice g1t has sent, a workspace's or an enterprise's. */
536export type InvoiceSummary = {
537 invoiceId: string;
538 kind: "workspace" | "enterprise";
539 account: string;
540 name: string;
541 reason: string;
542 period: string;
543 amountMicros: number;
544 status: string;
545 hostedUrl: string | null;
546 createdAt: string;
547 paidAt: string | null;
548};
549
550export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
551
552export type SalesRecord = {
553 workspace: string;
554 stage: SalesStage | string;
555 owner: string | null;
556 nextStep: string | null;
557 nextAt: string | null;
558 notes: { id: string; text: string; by: string; createdAt: string }[];
559 updatedAt: string | null;
560};
561
562export type Overview = {
563 month: string;
564 months: MonthFigures[];
565 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
566 payingWorkspaces: number;
567 stopped: number;
568 nearCeiling: number;
569 declined: number;
570 openInvoicesMicros: number;
571 followUpsDue: number;
572 /** g1t's capped budgets for free usage, this month. */
573 pools?: Pools | null;
574 /** Usage charged plus the plan's price paid, this month. */
575 revenueMicros?: number;
576 activePlans?: number;
577 planMrrMicros?: number;
578 /** What g1t gave this month, by source, apart from its margin. */
579 given?: GivenFigures[];
580 /** g1t's own and Flagon's workspaces: what their use cost, and why they are not charged. */
581 internal?: InternalUse[];
582 openRequests?: number;
583 overages?: number;
584 openSpikes?: number;
585};
586
587/** A customer's Stripe billing page, for staff to send them. */
588export type BillingLink = {
589 /** One-time and short-lived, signed in already. */
590 portalUrl: string;
591 /** The page's sign-in, which does not expire: the customer signs in by email. */
592 loginUrl: string | null;
593 customerEmail: string | null;
594 expiresNote: string;
595};
596
597export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
598
599export type AccountDetail = {
600 summary: AccountSummary;
601 workspaces: Limit[];
602 ledger: LedgerEntry[];
603 audit: AdminAction[];
604};
605
606/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
607export interface BillingAdminApi {
608 accounts(query?: string): Promise<AccountSummary[]>;
609 account(id: string): Promise<Result<AccountDetail>>;
610 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
611 /** Team on or off without charge, and the account's share of the pools. Needs a note. */
612 setAllowances(id: string, allowances: Allowances, note: string, by: string): Promise<Result<PayingAccount>>;
613 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
614 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
615 /** Credit for a workspace: promotional, goodwill or a refund; the owners are emailed. */
616 credit(workspace: string, amountMicros: number, note: string, by: string, options?: CreditOptions): Promise<Result<LedgerEntry>>;
617 /** Every credit g1t gave, filtered, with each month's totals by kind. */
618 credits(filter?: { workspace?: string | null; kind?: CreditKind | null; month?: string | null; by?: string | null }): Promise<AdminCredits>;
619 /** What is left of a credit, taken back, with why. */
620 revokeCredit(id: string, note: string, by: string): Promise<Result<CreditGrant>>;
621 /** A test workspace's billing wiped, to start again as a new customer. Only on Stripe's test key; never comped or enterprise. Logged. */
622 resetBilling(workspace: string, confirm: string, note: string, by: string): Promise<Result<BillingReset>>;
623 /** The workspace's Stripe billing page, to send to the customer. Logged. */
624 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
625 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
626 /** Stripe's state for billing; `fix` enables the destination and adds missing events first. */
627 stripe(fix?: boolean, by?: string): Promise<StripeStatus>;
628 /** Where an enterprise's invoices go; makes its Stripe customer. */
629 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
630 /** Sends an enterprise its invoice now, for what its workspaces owe. */
631 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
632 /** Exactly these workspaces' accounts, such as one page of the list. */
633 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
634 /** Every workspace worth reaching out to, most urgent first. */
635 signals(): Promise<Signal[]>;
636 /** The business at a glance. */
637 overview(): Promise<Overview>;
638 /** A workspace's sales record. */
639 sales(workspace: string): Promise<SalesRecord>;
640 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
641 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
642 /** A workspace's invoices from g1t, for staff. */
643 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
644 /** Every invoice g1t has sent, newest first. */
645 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
646 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
647 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
648 /** Limit and overage requests, with each workspace's history; `open` by default. */
649 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
650 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
651 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
652 /** The Overages queue. */
653 overages(): Promise<Overage[]>;
654 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. */
655 goodwill(workspace: string, amountMicros: number | null, reason: string, by: string, day?: string | null): Promise<Result<LedgerEntry>>;
656 /** Workspaces spending in the last day, fastest first. */
657 velocity(): Promise<Velocity[]>;
658 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
659 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
660 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
661 costs(days?: number): Promise<CostsReport>;
662 /** The open margin alerts, for the banner on every page. */
663 costAlerts(): Promise<MarginAlert[]>;
664 /** g1t's own spend against its caps: the daily breaker and comped budgets. */
665 spendCaps(): Promise<SpendCaps>;
666 /** Lets hosted-model runs start again for the rest of today (UTC); needs a note. */
667 liftBreaker(note: string, by: string): Promise<Result<SpendCaps>>;
668 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
669 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
670 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
671 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
672 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
673 runCosts(by: string): Promise<Result<CostsRun>>;
674}
675
676/** How much a workspace has earned g1t's trust with money. */
677export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
678
679/**
680 * How far a workspace's unpaid usage has gone this month, and where its
681 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
682 * requests. Usage counts at its cost to g1t or its charge, whichever is
683 * more, so it counts while g1t is free too.
684 */
685export type Limit = {
686 workspace: string;
687 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
688 account: string;
689 accountName: string;
690 trust: Trust;
691 exposureMicros: number;
692 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
693 ceilingMicros: number | null;
694 trustCeilingMicros: number | null;
695 spendLimitMicros: number | null;
696 state: "ok" | "warning" | "stopped";
697 message: string | null;
698 /** Charged this month: what the spend limit is measured against. */
699 spentMicros?: number;
700 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
701 defaultSpendLimit?: boolean;
702 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
703 availableMicros?: number | null;
704 /** How the ceiling grows from here, in a sentence. */
705 growth?: string | null;
706 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
707 prepaidMicros?: number;
708 /** The highest ceiling the workspace has had. */
709 maxCeilingMicros?: number | null;
710 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
711 raiseOnceMicros?: number | null;
712 /** When the one-time raise was used. */
713 raisedAt?: string | null;
714 /** A paid workspace's first billing cycle, on the starting ceiling. */
715 firstMonth?: boolean;
716 /** The budget's alerts, in percent of the spend limit: some of 50, 75, 90 and 100. */
717 alertLevels?: number[];
718 /** Whether usage pauses at the spend limit (the default); off, it only alerts. */
719 pauseAtLimit?: boolean;
720 /** An HTTPS address told of each budget alert. */
721 budgetWebhook?: string | null;
722};
723
724/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
725export type Price = {
726 meter:
727 | "sandbox_second"
728 | "build_second"
729 | "app_requests"
730 | "app_cpu"
731 | "app_month"
732 | "custom_domain_month"
733 | "private_storage"
734 | "embedding_tokens"
735 | "scan_cpu"
736 | "scan_rows"
737 | string;
738 title: string;
739 unit: string;
740 costMicros: number;
741 markupPercent: number;
742 priceMicros: number;
743 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
744 source: "list" | "cloudflare" | string;
745 checkedAt: string | null;
746 updatedAt: string;
747};
748
749export type PriceChange = {
750 meter: string;
751 oldCostMicros: number;
752 newCostMicros: number;
753 markupPercent: number;
754 /** The markup before, when the change was to the markup rather than the cost. */
755 oldMarkupPercent?: number;
756 reason: string;
757 createdAt: string;
758 /** When a change still to come takes effect: a rise is announced before it is charged. */
759 effectiveAt?: string;
760};
761
762export type PriceBook = {
763 prices: Price[];
764 changes: PriceChange[];
765 modelMarginPercent: number;
766 /** Every plan, as sold now. */
767 plans?: FeaturePlan[];
768 /** What is free, and the capped budgets that pay for it. */
769 free?: FreeTier | null;
770};
771
772/** One kind of meter's usage this month, from `usage_meters`. */
773export type MeterUsage = {
774 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
775 key: string;
776 label: string;
777 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
778 micros: number;
779 /** How much, when it is known: `12 runs`, `41 build minutes`. */
780 quantity?: string | null;
781};
782
783/** What g1t gives without a plan; each is paid for by a capped budget. */
784export type FreeTier = {
785 /** Each new workspace's trial credit, once. */
786 trialWorkspaceMicros: number;
787 /** Trial grants each month, in all; new trials wait when it is spent. */
788 trialMonthlyPoolMicros: number;
789 /** g1t's open-source pool each month, and any one repository's share. */
790 ossPoolMicros: number;
791 ossRepoMicros: number;
792 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
793 freePrivateStorageBytes: number;
794 /** Days of audit log a free workspace keeps. */
795 auditRetentionDays: number;
796 /** Days of audit log the g1t plan keeps, and g1t's own and enterprise workspaces; longer by arrangement. */
797 planAuditRetentionDays?: number;
798 /** The smallest amount a card is charged when a month closes; less carries over. */
799 minChargeMicros: number;
800 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
801 gitOperationsIncluded?: number;
802 /** A new paid workspace's ceiling in its first month. */
803 paidStartCeilingMicros?: number;
804 /** The most a one-click goodwill credit can cost g1t. */
805 overageForgiveCostMicros?: number;
806};
807
808/**
809 * A workspace's trial credit: one grant per workspace, made the first time
810 * it uses something, out of a pool that resets each calendar month. Mirrors
811 * `Trial` in `crates/contracts/src/billing.rs`.
812 */
813export type Trial = {
814 open: boolean;
815 usedMicros: number;
816 limitMicros: number;
817 /** No longer used: trials do not end on a date. */
818 endsAt: string | null;
819 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
820 reason: "off" | "ended" | "used" | "pool" | null;
821 /** Whether the workspace has its grant already. */
822 granted?: boolean;
823 /** With `pool`: when new trials start again, the first of next month. */
824 waitsUntil?: string | null;
825};
826
827/**
828 * What a workspace pays a monthly price for: the g1t plan (`plan`), and the
829 * Security and quality activation (`security`), sold on its own. Deployments
830 * are part of the plan; `has_feature` for `deployments` answers whether the
831 * workspace has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
832 */
833export type Feature = "plan" | "deployments" | "security";
834
835/**
836 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
837 * billing's price book cannot be read. Not an allowance: on the plan every
838 * unit is metered from the first, at cost plus 20%, and drawn from the
839 * plan's included usage first. Projects, previews and the apps behind them
840 * are not metered at all. Mirrors `deployment_costs`.
841 */
842export const DEPLOYMENT_COSTS = {
843 microsPerMillionRequests: 300_000,
844 microsPerMillionCpuMs: 20_000,
845 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
846 microsPerBuildSecond: 15,
847 /** One custom domain for a month. */
848 microsPerDomainMonth: 100_000,
849} as const;
850
851export type FeaturePlan = {
852 feature: Feature;
853 title: string;
854 /** Charged every month while the plan is on, in cents. */
855 monthlyCents: number;
856 /** What the price includes, one line each. */
857 includes: string[];
858 /** How usage past the allowance is charged. */
859 overage: string;
860};
861
862export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
863
864export type Subscription = {
865 feature: Feature;
866 status: SubscriptionStatus;
867 /** RFC 3339: when the period paid for ends. */
868 periodEnd: string | null;
869 startedBy: string;
870 startedAt: string;
871};
872
873/** A feature as a workspace sees it. */
874export type FeatureState = {
875 plan: FeaturePlan;
876 subscription: Subscription | null;
877 /** Whether the feature works for the workspace now. */
878 on: boolean;
879 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
880 included?: boolean;
881};
882
883export interface BillingApi {
884 status(): Promise<BillingStatus>;
885 /** Members of the workspace only. */
886 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
887 /** Newest first. Members of the workspace only. */
888 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
889 /** Credits from g1t, newest first, with what is left of each. Members only. */
890 credits(workspace: string, viewer: Viewer): Promise<Result<Credits>>;
891 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
892 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
893 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
894 statementEntries(
895 workspace: string,
896 viewer: Viewer,
897 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
898 ): Promise<Result<LedgerEntry[]>>;
899 /** What the workspace's agents cost since `since`, broken down. Members only. */
900 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
901 /**
902 * The model tokens the workspace's runs used, day by day over the last
903 * `days` (42, at most 366), for everyone or for one `person`. Members
904 * only; a member may ask only for themselves, an owner for anyone.
905 */
906 tokenUsage(workspace: string, viewer: User, options?: { person?: string; days?: number }): Promise<Result<TokenUsage>>;
907 /**
908 * What one model answer used, added to its run's count for the day. The
909 * model proxy sends it; for usage views only, as runs are priced from AI
910 * Gateway. False when there was nothing to count.
911 */
912 recordTokens(usage: {
913 workspace: string;
914 /** The model session's id, one per run. */
915 session: string;
916 /** The person the run is for, by username. */
917 person?: string | null;
918 model: string;
919 tier?: "small" | "large" | "frontier" | null;
920 input: number;
921 output: number;
922 cacheRead: number;
923 cacheWrite: number;
924 }): Promise<Result<boolean>>;
925 /**
926 * Prepays usage ($25 at least) and returns the page to send the person to:
927 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
928 * The payment's id comes back to `returnUrl` as `session`.
929 */
930 checkout(
931 actor: User,
932 workspace: string,
933 amountCents: number,
934 returnUrl: string,
935 method?: "card" | "bank_transfer",
936 ): Promise<Result<{ url: string }>>;
937 /**
938 * Stripe's hosted billing page for the workspace: card, invoices, billing
939 * email and address. g1t never handles card numbers. Owners only.
940 */
941 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
942 /** Credits a payment once the processor says it was made. Safe to repeat. */
943 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
944 /**
945 * Whether a workspace may start an agent now, asked before anything is
946 * opened for it. A failure, with the reason to show, when it has no credit.
947 */
948 canStart(workspace: string): Promise<Result<boolean>>;
949 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
950 trial(workspace: string, exempt: string[]): Promise<Trial>;
951 /**
952 * Asks whether a workspace may start an agent and opens the run it will be
953 * charged for. Null when billing is off; a failure when there is no credit.
954 */
955 /** Every paid feature and the workspace's plan for each. Members only. */
956 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
957 /**
958 * Starts the card page for a feature's monthly plan. Owners only. The
959 * page's id comes back to `returnUrl` as `session`.
960 */
961 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
962 /** Turns the feature on once the plan is paid for. Safe to repeat. */
963 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
964 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
965 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
966 /** Whether a feature works for a workspace now; a failure with the reason when not. */
967 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
968 /**
969 * Usage past a plan's allowance, charged from credit at cost plus the
970 * margin, once per `reference`. False if it was charged before.
971 */
972 chargeFeature(charge: {
973 workspace: string;
974 feature: Feature;
975 costMicros: number;
976 description: string;
977 repo?: string | null;
978 reference: string;
979 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
980 buildSeconds?: number | null;
981 }): Promise<Result<boolean>>;
982 /**
983 * What a source cost g1t so far this month, so the workspace's limit
984 * counts it now. Replaces the last report. Billing charges `context`
985 * and `security` itself once the month is over; `deployments` charges
986 * its own.
987 */
988 notePending(
989 workspace: string,
990 source: "deployments" | "domains" | "context" | "security",
991 costMicros: number,
992 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
993 detail?: string | null,
994 ): Promise<boolean>;
995 /**
996 * This month's usage, one line per kind of meter, at what it is charged
997 * before the plan's included usage or a pool paid for it. Members only.
998 */
999 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
1000 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
1001 entitlements(workspace: string): Promise<Entitlements>;
1002 /**
1003 * Holds a start's estimated cost before the work starts. A failure's code says why not:
1004 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
1005 */
1006 reserve(reservation: {
1007 workspace: string;
1008 repo: RepoPath;
1009 public: boolean;
1010 kind: ComputeKind;
1011 /** The most the work is expected to cost g1t, before the margin. */
1012 estimateMicros: number;
1013 }): Promise<Result<ReservationHeld>>;
1014 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
1015 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
1016 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
1017 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
1018 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
1019 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
1020 /** An owner asks for a higher limit, or for help with usage past what was meant. */
1021 requestLimit(
1022 actor: User,
1023 workspace: string,
1024 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
1025 ): Promise<Result<LimitRequest>>;
1026 /** The workspace's requests and their answers, newest first. Members only. */
1027 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
1028 /**
1029 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
1030 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
1031 */
1032 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
1033 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
1034 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
1035 /** Every metered price and the recent changes. Public. */
1036 prices(): Promise<PriceBook>;
1037 /** A workspace's limit, for its members. */
1038 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
1039 /** The same, for the services that enforce it. */
1040 checkLimit(workspace: string): Promise<Result<Limit>>;
1041 /**
1042 * The owners' own monthly limit, up to what is available; null goes back
1043 * to the default, and `useFullLimit` uses everything available. Owners only.
1044 */
1045 setSpendLimit(
1046 actor: User,
1047 workspace: string,
1048 spendLimitMicros: number | null,
1049 useFullLimit?: boolean,
1050 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
1051 raiseOnce?: boolean,
1052 ): Promise<Result<Limit>>;
1053 /** The workspace's invoices from g1t, newest first. Members only. */
1054 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
1055 /**
1056 * How long a sandbox ran for a workspace, reported when it stops. Its
1057 * cost is recorded and every second is charged, from the first. False if
1058 * `reference` was recorded before.
1059 */
1060 recordSandbox(usage: {
1061 workspace: string;
1062 seconds: number;
1063 description: string;
1064 repo?: string | null;
1065 reference: string;
1066 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
1067 kind?: ComputeKind | null;
1068 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
1069 cpuSeconds?: number | null;
1070 /** The reservation it started under, settled with this cost. */
1071 reservationId?: string | null;
1072 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
1073 selfHosted?: boolean;
1074 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
1075 instance?: string | null;
1076 }): Promise<Result<boolean>>;
1077 startRun(run: {
1078 workspace: string;
1079 repo: RepoPath;
1080 number: number;
1081 task: string;
1082 model: string;
1083 /** `workspace` when the run uses the workspace's own model provider. */
1084 billedTo?: "g1t" | "workspace";
1085 /**
1086 * The model session's id: the run is settled at AI Gateway's price by
1087 * it, and on the workspace's own provider its tokens are counted under
1088 * it for the agent rate.
1089 */
1090 session?: string | null;
1091 /** The tier g1t routed the run to: `small`, `large` or `frontier`. */
1092 tier?: "small" | "large" | "frontier" | null;
1093 }): Promise<Result<RunTicket | null>>;
1094 /** Usage over a range of days (`YYYY-MM-DD`, both included), at price, by product, meter, project and day. Members only. */
1095 usageReport(
1096 workspace: string,
1097 viewer: Viewer,
1098 range: { from: string; until: string; products?: string[]; projects?: string[] },
1099 ): Promise<Result<UsageReport>>;
1100 /** The workspace's prepaid AI credit, auto-reload and prices. Members only. */
1101 aiCredit(workspace: string, viewer: Viewer): Promise<Result<AiCredit>>;
1102 /** Stripe's page to buy AI credit ( to ,000, the card fee on its own line). Owners only. The page's id comes back to `returnUrl` as `ai_credit`. */
1103 buyAiCredit(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
1104 /** Credits a purchase once Stripe says it was paid, once. Safe to repeat. */
1105 confirmAiCredit(workspace: string, viewer: Viewer, session: string): Promise<Result<AiCredit>>;
1106 /** Auto-reload's settings. Owners only. */
1107 setAiReload(
1108 actor: User,
1109 workspace: string,
1110 reload: { enabled: boolean; thresholdMicros: number; targetMicros: number; monthlyMaxMicros: number },
1111 ): Promise<Result<AiCredit>>;
1112 /** The monthly budget: the spend limit, its alerts, whether usage pauses at 100%, and a webhook. Owners only. */
1113 setBudget(
1114 actor: User,
1115 workspace: string,
1116 budget: { amountMicros: number | null; alerts: number[]; pauseAtLimit: boolean; webhook: string | null; keepLimit?: boolean },
1117 ): Promise<Result<Limit>>;
1118 /** Invoice details from the Stripe customer, the default payment method, invoices and the next invoice. Members only. */
1119 billingDetails(workspace: string, viewer: Viewer): Promise<Result<BillingDetails>>;
1120 /** Saves invoice details on the Stripe customer; absent fields stay, empty clears. Owners only. */
1121 setBillingDetails(actor: User, workspace: string, details: BillingDetailsInput): Promise<Result<BillingDetails>>;
1122}
1123
1124
1125/** One slice of usage: what it was for, what it cost, how many runs. */
1126export type UsageSlice = { key: string; micros: number; runs: number };
1127
1128/** The model tokens runs used over a window of days. */
1129export type TokenUsage = {
1130 /** `YYYY-MM-DD`, the first day counted. */
1131 since: string;
1132 /** The window's length: 42 unless asked, 366 at most. */
1133 days: number;
1134 /** Null for the whole workspace. */
1135 person: string | null;
1136 totalTokens: number;
1137 inputTokens: number;
1138 outputTokens: number;
1139 cacheReadTokens: number;
1140 cacheWriteTokens: number;
1141 /** What those runs were charged, as `usage` measures it. */
1142 costMicros: number;
1143 /** Days in the window with any tokens. */
1144 activeDays: number;
1145 /** Every day in the window, oldest first, zeros included. */
1146 byDay: { day: string; tokens: number }[];
1147};
1148
1149/** What a workspace's agents cost over a period. */
1150export type Usage = {
1151 since: string;
1152 /** Charged, including g1t's margin. */
1153 spentMicros: number;
1154 /** What g1t's usage came to at price, less what was charged: the plan's included usage, the trial, a pool or a free period paid it. Usage at price is `spentMicros` plus this. */
1155 coveredMicros?: number;
1156 /** What the account's discount took off the price; usage at price is spent + covered + this. */
1157 discountMicros?: number;
1158 /** The account's discount now, in percent; with one, the slices are at price. */
1159 discountPercent?: number | null;
1160 /** Usage at price: spent + covered + discount, from the same ledger lines. The one usage figure every page shows. */
1161 priceMicros?: number;
1162 /** What g1t's model provider charged, before the margin. */
1163 costMicros: number;
1164 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
1165 providerMicros: number;
1166 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
1167 usedMicros: number;
1168 /** g1t charges nothing for now; the slices then measure usage at cost. */
1169 free: boolean;
1170 runs: number;
1171 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
1172 byDay: UsageSlice[];
1173 byTask: UsageSlice[];
1174 byRepo: UsageSlice[];
1175 /** Keyed `namespace/name#number`. */
1176 byPull: UsageSlice[];
1177 byModel: UsageSlice[];
1178 /** Credit bought in the period. */
1179 addedMicros: number;
1180};
1181
1182/** One of g1t's products (a "bucket") on one day. Money in micros. */
1183export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
1184
1185/** One product over the range: what customers were charged at price against what it cost. */
1186export type ProductMargin = {
1187 bucket: string;
1188 title: string;
1189 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
1190 costMicros: number;
1191 cfCostMicros: number;
1192 ownCostMicros: number;
1193 valueMicros: number;
1194 marginMicros: number;
1195 marginPercent: number | null;
1196 costSource: "cloudflare" | "ledger" | string;
1197 /** Running g1t, paid for by the plan. */
1198 overhead: boolean;
1199};
1200
1201/** All of g1t: money in (usage and the plan) against every cost. */
1202export type OverallMargin = {
1203 usageMicros: number;
1204 plansMicros: number;
1205 costMicros: number;
1206 marginMicros: number;
1207 marginPercent: number | null;
1208 /** Of costMicros, what went on usage g1t gave away on purpose: comped workspaces, free periods, the trial and the open-source pool. */
1209 givenMicros?: number;
1210 /** Money in against costMicros - givenMicros. */
1211 soldMarginMicros?: number;
1212 soldMarginPercent?: number | null;
1213 /** Usage sold: usageMicros against what that usage cost, less what was given. */
1214 usageCostMicros?: number;
1215 usageMarginMicros?: number;
1216 usageMarginPercent?: number | null;
1217 /** Running g1t: plansMicros against the platform's cost, less its given share. */
1218 runningCostMicros?: number;
1219 /** Cost no mapping names, less its given share. */
1220 unmappedCostMicros?: number;
1221 /** givenMicros by why. Free is free periods, free allowances and overruns g1t covered. */
1222 givenCompedMicros?: number;
1223 givenFreeMicros?: number;
1224 givenTrialMicros?: number;
1225 givenPoolMicros?: number;
1226 /** What discounts on an account's terms took below cost plus the margin: given, not margin lost. */
1227 givenDiscountMicros?: number;
1228 /** Credits from g1t spent on usage, by kind: given, never money in. Refunds come off money in instead. */
1229 givenCreditPromotionalMicros?: number;
1230 givenCreditGoodwillMicros?: number;
1231 /** Credits over the range: given (every kind), spent on usage, and refunds' money given back. */
1232 creditsGivenMicros?: number;
1233 creditsUsedMicros?: number;
1234 creditsRefundedMicros?: number;
1235 /** costMicros by who g1t pays: Cloudflare's bill (billed, after included allowances) and model providers (tokens, not on Cloudflare's bill). */
1236 /** What the plan's included usage paid for, at price: money in for usage, paid out of plansMicros. */
1237 includedMicros?: number;
1238 cloudflareCostMicros?: number;
1239 modelsCostMicros?: number;
1240};
1241
1242/** A count, cost or leak that does not add up. */
1243export type CostDrift = {
1244 bucket: string;
1245 title: string;
1246 kind: "count" | "cost" | "leak" | string;
1247 ours: number;
1248 cloudflare: number;
1249 deltaPercent: number | null;
1250 detail: string;
1251 foundAt: string;
1252};
1253
1254export type MarginAlert = {
1255 id: string;
1256 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1257 /** The product, or the workspace. */
1258 subject: string;
1259 detail: string;
1260 since: string;
1261 openedAt: string;
1262 emailedAt: string | null;
1263};
1264
1265/** A change to a price, measured from what Cloudflare charged. */
1266export type PriceProposal = {
1267 id: string;
1268 meter: string;
1269 title: string;
1270 unit: string;
1271 currentCostMicros: number;
1272 proposedCostMicros: number;
1273 changePercent: number;
1274 markupPercent: number;
1275 reason: string;
1276 source: "keeper" | "reconciler" | string;
1277 /** Far off the current cost: look before approving. */
1278 suspect: boolean;
1279 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1280 createdAt: string;
1281 decidedAt: string | null;
1282 decidedBy: string | null;
1283 note: string | null;
1284 effectiveAt: string | null;
1285};
1286
1287/** One version of one meter's price; never changed once written. */
1288export type PriceVersion = {
1289 id: string;
1290 meter: string;
1291 version: number;
1292 costMicros: number;
1293 markupPercent: number;
1294 priceMicros: number;
1295 effectiveAt: string;
1296 reason: string;
1297 createdBy: string;
1298 appliedAt: string | null;
1299};
1300
1301/** What `resetBilling` removed. */
1302export type BillingReset = { workspace: string; rows: number; refreshed?: boolean };
1303
1304export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; givenMicros?: number; internal: boolean };
1305
1306export type CostLineSummary = {
1307 product: string;
1308 meter: string;
1309 rawName: string;
1310 unit: string;
1311 source: string;
1312 quantity: number;
1313 costMicros: number;
1314 /** Absent when no mapping claims it. */
1315 bucket: string | null;
1316};
1317
1318export type CostMapping = {
1319 product: string;
1320 meter: string;
1321 bucket: string;
1322 priceMeter: string | null;
1323 ownMeter: string | null;
1324 scaleToOwn: boolean;
1325 driftPercent: number;
1326 note: string;
1327 updatedAt: string;
1328 updatedBy: string;
1329};
1330
1331export type CostMappingInput = {
1332 product: string;
1333 meter: string;
1334 bucket?: string;
1335 priceMeter?: string | null;
1336 ownMeter?: string | null;
1337 scaleToOwn?: boolean;
1338 driftPercent?: number | null;
1339 note?: string;
1340 remove?: boolean;
1341};
1342
1343export type CostSettings = {
1344 autoApply: boolean;
1345 autoApplyPercent: number;
1346 noticeDays: number;
1347 marginFloorPercent: number;
1348 alertDays: number;
1349 minDailyCostMicros: number;
1350 anomalyFactor: number;
1351 anomalyFloorMicros: number;
1352 /** Pass Stripe's card fee on as its own line when AI credit is bought by card. */
1353 cardFee: boolean;
1354};
1355
1356export type CostsReport = {
1357 configured: boolean;
1358 fetchedAt: string | null;
1359 since: string;
1360 until: string;
1361 days: CostDay[];
1362 products: ProductMargin[];
1363 overall: OverallMargin;
1364 drift: CostDrift[];
1365 alerts: MarginAlert[];
1366 proposals: PriceProposal[];
1367 versions: PriceVersion[];
1368 topWorkspaces: WorkspaceCost[];
1369 lines: CostLineSummary[];
1370 mappings: CostMapping[];
1371 settings: CostSettings;
1372 /** g1t's own spend against its two caps. */
1373 caps: SpendCaps;
1374};
1375
1376/** What g1t pays for itself, at cost, against its caps (billing's `budget`). */
1377export type SpendCaps = {
1378 /** Today (UTC), YYYY-MM-DD, and this month, YYYY-MM. */
1379 day: string;
1380 month: string;
1381 /** What g1t paid for itself today across every workspace. */
1382 todayMicros: number;
1383 /** `PLATFORM_DAILY_SPEND_CAP_MICROS`; 0: no breaker. */
1384 dailyCapMicros: number;
1385 /** New hosted-model agent runs g1t would pay for are paused. */
1386 tripped: boolean;
1387 trippedAt: string | null;
1388 liftedBy: string | null;
1389 liftedAt: string | null;
1390 liftNote: string | null;
1391 /** This month so far, by what paid: comped, trial, oss, given, unpaid. */
1392 monthBuckets: { bucket: string; title: string; micros: number }[];
1393 comped: CompedBudget[];
1394 /** Free workspaces' share of reconciled costs this month (git, storage, platform). */
1395 freeTierMicros: number;
1396 /** Cloudflare's subscriptions a month: read from Cloudflare each day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate. */
1397 fixedMonthlyMicros: number;
1398 fixedSource?: "cloudflare" | "estimate" | string;
1399 fixedReadAt?: string | null;
1400 /** Each subscription, when read from Cloudflare. */
1401 fixedItems?: { name: string; monthlyMicros: number }[];
1402 /** Money in this month, through the last reconciled day. */
1403 revenueMicros: number;
1404};
1405
1406/** A comped account's monthly budget, at cost. */
1407export type CompedBudget = {
1408 account: string;
1409 name: string;
1410 usedMicros: number;
1411 /** 0: no budget. */
1412 ceilingMicros: number;
1413 /** `COMPED_MONTHLY_CEILING_MICROS`, not the account's own limit. */
1414 defaultCeiling: boolean;
1415 /** 50, 75, 90, 100, or 0. */
1416 level: number;
1417};
1418
1419export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };
1420
1421/** The product families the Usage page groups meters into, in order. */
1422export const PRODUCTS = [
1423 { key: "agent", label: "Agent" },
1424 { key: "sandboxes", label: "Sandboxes" },
1425 { key: "gateway", label: "AI Gateway" },
1426 { key: "deployments", label: "Deployments" },
1427 { key: "git_storage", label: "Git & storage" },
1428 { key: "packages", label: "Packages" },
1429 { key: "security", label: "Security & quality" },
1430 { key: "search", label: "Search" },
1431] as const;
1432
1433export type ProductKey = (typeof PRODUCTS)[number]["key"];
1434
1435/** What usage came to over a range, and what paid for it: price − discount − included − credits = charged. */
1436export type UsageTotals = {
1437 /** Usage at price, pending usage included. */
1438 priceMicros: number;
1439 discountMicros: number;
1440 /** Paid by the plan's included usage, the trial and g1t's pools. */
1441 includedMicros: number;
1442 /** Paid by AI credit and credit from g1t. */
1443 creditsMicros: number;
1444 /** Left for the workspace to pay. */
1445 chargedMicros: number;
1446 /** Metered this month, charged when it closes. */
1447 pendingMicros: number;
1448 costMicros: number;
1449};
1450
1451export type UsageDay = { day: string; product: string; micros: number };
1452
1453export type UsageAllowance = { used: number; of: number; unit: string };
1454
1455export type ProjectUsage = { project: string; micros: number; quantity: number };
1456
1457/** One meter over a range. */
1458export type MeterLine = {
1459 key: string;
1460 label: string;
1461 product: string;
1462 /** `tokens`, `seconds`, `bytes`, `operations`, `requests` or `entries`. */
1463 unit: string;
1464 quantity: number;
1465 micros: number;
1466 pendingMicros?: number;
1467 /** Every day of the range, oldest first, at price. */
1468 daily: number[];
1469 allowance?: UsageAllowance | null;
1470 byProject: ProjectUsage[];
1471 /** How the quantity is counted, when that needs saying (the agent rate's token weights). */
1472 note?: string | null;
1473};
1474
1475export type FeatureUsage = { key: string; label: string; micros: number; count: number };
1476
1477export type ProductUsage = { key: string; label: string; micros: number; meters: MeterLine[]; features?: FeatureUsage[] };
1478
1479/** The tokens one model used over a range, as the model proxy counted them. */
1480export type ModelTokens = { model: string; input: number; output: number; cacheRead: number; cacheWrite: number };
1481
1482export type UsageReport = {
1483 from: string;
1484 until: string;
1485 totals: UsageTotals;
1486 days: UsageDay[];
1487 products: ProductUsage[];
1488 projects: string[];
1489 /** Agent tokens by model over the range, most first. */
1490 models?: ModelTokens[];
1491 /** The plan's included usage this month, in micros. */
1492 included?: UsageAllowance | null;
1493 discountPercent?: number | null;
1494 aiCreditMicros: number;
1495 creditMicros: number;
1496 trialMicros?: number | null;
1497 plan: PlanKind;
1498 free: boolean;
1499};
1500
1501export type AiReload = {
1502 enabled: boolean;
1503 thresholdMicros: number;
1504 targetMicros: number;
1505 monthlyMaxMicros: number;
1506 reloadedMicros?: number;
1507 failedAt?: string | null;
1508 error?: string | null;
1509};
1510
1511export type CardFee = { on: boolean; percentMicros: number; fixedCents: number };
1512
1513/** Prepaid AI credit: what Agent and AI Gateway usage draws on. */
1514export type AiCredit = {
1515 balanceMicros: number;
1516 purchasedMicros: number;
1517 givenMicros: number;
1518 grants: CreditGrant[];
1519 /** A 100% discount pays for AI usage: nothing to buy. */
1520 freeViaDiscount: boolean;
1521 /** Invoiced after use (an enterprise). */
1522 postpaid: boolean;
1523 /** New runs on g1t's models are refused for want of credit. */
1524 blocked: boolean;
1525 canBuy: boolean;
1526 presetsCents: number[];
1527 minCents: number;
1528 maxCents: number;
1529 cardFee: CardFee;
1530 reload: AiReload;
1531 /** The agent rate per million tokens, at price. */
1532 agentRateMicros: number;
1533 modelMarkupPercent: number;
1534 gatewayMarkupPercent: number;
1535 upgradeCreditMicros: number;
1536 expiresDays: number;
1537};
1538
1539export type PostalAddress = { line1: string; line2: string; city: string; state: string; postalCode: string; country: string };
1540
1541export type PaymentMethod = {
1542 kind: string;
1543 brand?: string | null;
1544 last4?: string | null;
1545 expMonth?: number | null;
1546 expYear?: number | null;
1547};
1548
1549export type StripeInvoice = {
1550 id: string;
1551 number?: string | null;
1552 status: string;
1553 totalCents: number;
1554 currency: string;
1555 createdAt: string;
1556 description?: string | null;
1557 hostedUrl?: string | null;
1558 pdfUrl?: string | null;
1559};
1560
1561export type UpcomingInvoice = { closesAt: string; subscriptionsMicros: number; usageMicros: number; totalMicros: number };
1562
1563export type BillingDetails = {
1564 customer: boolean;
1565 email: string | null;
1566 name: string | null;
1567 address: PostalAddress | null;
1568 taxIdType: string | null;
1569 taxId: string | null;
1570 poNumber: string | null;
1571 language: string | null;
1572 paymentMethod: PaymentMethod | null;
1573 invoices: StripeInvoice[];
1574 upcoming: UpcomingInvoice;
1575 unavailable?: string | null;
1576};
1577
1578export type BillingDetailsInput = {
1579 email?: string;
1580 name?: string;
1581 address?: PostalAddress;
1582 taxIdType?: string;
1583 taxId?: string;
1584 poNumber?: string;
1585 language?: string;
1586};