Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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