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,708 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 /** Stripe Tax for the key's mode: `active`, or `pending` with the settings it still needs. Null when it could not be read. */
418 tax?: { status: "active" | "pending" | string; missingFields: string[] } | null;
419 /** The customer portal configuration billing makes (`metadata[g1t]=billing`). Null until the first portal session makes it. */
420 portal?: { configurationId: string; active: boolean } | null;
421};
422
423/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
424export type EnterpriseInvoice = {
425 invoiceId: string;
426 hostedUrl: string | null;
427 amountMicros: number;
428 status: "open" | "paid" | "overdue" | "void" | string;
429 period: string;
430 lines: { workspace: string; amountMicros: number }[];
431 createdAt: string;
432};
433
434/** A workspace's invoice: monthly, or when charged near its limit. Itemised, in Stripe's billing page. */
435export type WorkspaceInvoice = {
436 invoiceId: string;
437 workspace: string;
438 reason: "month" | "threshold" | string;
439 period: string;
440 amountMicros: number;
441 status: "paid" | "open" | "failed" | "void" | string;
442 hostedUrl: string | null;
443 pdfUrl: string | null;
444 lines: { description: string; amountMicros: number }[];
445 createdAt: string;
446 /** The card processing fee on top of `amountMicros` (only on invoices from before g1t's prices included it), and the tax Stripe added once known. */
447 feeMicros?: number;
448 taxMicros?: number;
449};
450
451/** A month of the ledger, grouped by day or project, a line per kind of charge. */
452export type Statement = {
453 month: string;
454 months: string[];
455 groups: {
456 key: string;
457 label: string;
458 /** `coveredMicros`: what the plan's included usage, the trial, the open-source pool or g1t paid, not in `chargedMicros`. */
459 /** `priceMicros`: usage at its price; `discountMicros`: what the account's discount took off it. */
460 lines: {
461 kind: string;
462 count: number;
463 chargedMicros: number;
464 costMicros: number;
465 coveredMicros?: number;
466 priceMicros?: number;
467 discountMicros?: number;
468 /** On `Tax` and `Card processing fees` lines: what was paid with payments on top of what reached the balance. Never charged. */
469 passedMicros?: number;
470 /** On a `Runner minutes, <machine>` line: the minutes charged, each job's time rounded up to the minute. */
471 minutes?: number;
472 }[];
473 chargedMicros: number;
474 priceMicros?: number;
475 discountMicros?: number;
476 }[];
477 totals: {
478 chargedMicros: number;
479 paidMicros: number;
480 costMicros: number;
481 entries: number;
482 /** Usage at price, and what the discount took off: charged is the price less the discount and what paid for it. */
483 priceMicros?: number;
484 discountMicros?: number;
485 /** The account's discount now, in percent; absent without one. */
486 discountPercent?: number | null;
487 /** What paid for usage before it was charged, such as "Paid by g1t's open-source pool". */
488 covered?: { source: "included" | "trial" | "oss_pool" | "given" | string; label: string; micros: number }[];
489 /** Owed when the month closed but under the minimum charge: on the next invoice. */
490 carriedMicros?: number;
491 /** Tax and card processing fees paid with the month's payments, on top of `paidMicros`. */
492 taxMicros?: number;
493 cardFeeMicros?: number;
494 };
495};
496
497export type MonthFigures = {
498 month: string;
499 /** Usage charged, after what paid for it first. */
500 chargedMicros: number;
501 /** What usage cost g1t: never a workspace's own model provider. */
502 costMicros: number;
503 paidMicros: number;
504 /** The plan's monthly price, paid. */
505 plansMicros?: number;
506 /** What g1t gave at price (internal use, trials, the open-source pool, goodwill, covered). Not margin. */
507 givenMicros?: number;
508};
509
510/** What g1t gave this month from one source. */
511export type GivenFigures = { source: "internal" | "trial" | "oss_pool" | "goodwill" | "covered" | string; label: string; micros: number; costMicros: number };
512
513/** One internal workspace's use this month, and why it is not charged. */
514export type InternalUse = { workspace: string; reason: string; costMicros: number; entries: number };
515
516export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend" | "cost_over_revenue";
517
518/** Why a workspace is worth reaching out to. */
519export type Signal = {
520 workspace: string;
521 kind: SignalKind;
522 detail: string;
523 valueMicros: number;
524 stage: string | null;
525 owner: string | null;
526 nextStep?: string | null;
527 /** When the next step is due, YYYY-MM-DD. */
528 nextAt?: string | null;
529};
530
531/** One invoice g1t has sent, a workspace's or an enterprise's. */
532export type InvoiceSummary = {
533 invoiceId: string;
534 kind: "workspace" | "enterprise";
535 account: string;
536 name: string;
537 reason: string;
538 period: string;
539 amountMicros: number;
540 status: string;
541 hostedUrl: string | null;
542 createdAt: string;
543 paidAt: string | null;
544};
545
546export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
547
548export type SalesRecord = {
549 workspace: string;
550 stage: SalesStage | string;
551 owner: string | null;
552 nextStep: string | null;
553 nextAt: string | null;
554 notes: { id: string; text: string; by: string; createdAt: string }[];
555 updatedAt: string | null;
556};
557
558export type Overview = {
559 month: string;
560 months: MonthFigures[];
561 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
562 payingWorkspaces: number;
563 stopped: number;
564 nearCeiling: number;
565 declined: number;
566 openInvoicesMicros: number;
567 followUpsDue: number;
568 /** g1t's capped budgets for free usage, this month. */
569 pools?: Pools | null;
570 /** Usage charged plus the plan's price paid, this month. */
571 revenueMicros?: number;
572 activePlans?: number;
573 planMrrMicros?: number;
574 /** What g1t gave this month, by source, apart from its margin. */
575 given?: GivenFigures[];
576 /** g1t's own and Flagon's workspaces: what their use cost, and why they are not charged. */
577 internal?: InternalUse[];
578 openRequests?: number;
579 overages?: number;
580 openSpikes?: number;
581};
582
583/** A customer's Stripe billing page, for staff to send them. */
584export type BillingLink = {
585 /** One-time and short-lived, signed in already. */
586 portalUrl: string;
587 /** The page's sign-in, which does not expire: the customer signs in by email. */
588 loginUrl: string | null;
589 customerEmail: string | null;
590 expiresNote: string;
591};
592
593export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
594
595export type AccountDetail = {
596 summary: AccountSummary;
597 workspaces: Limit[];
598 ledger: LedgerEntry[];
599 audit: AdminAction[];
600};
601
602/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
603export interface BillingAdminApi {
604 accounts(query?: string): Promise<AccountSummary[]>;
605 account(id: string): Promise<Result<AccountDetail>>;
606 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
607 /** Team on or off without charge, and the account's share of the pools. Needs a note. */
608 setAllowances(id: string, allowances: Allowances, note: string, by: string): Promise<Result<PayingAccount>>;
609 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
610 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
611 /** Credit for a workspace: promotional, goodwill or a refund; the owners are emailed. */
612 credit(workspace: string, amountMicros: number, note: string, by: string, options?: CreditOptions): Promise<Result<LedgerEntry>>;
613 /** Every credit g1t gave, filtered, with each month's totals by kind. */
614 credits(filter?: { workspace?: string | null; kind?: CreditKind | null; month?: string | null; by?: string | null }): Promise<AdminCredits>;
615 /** What is left of a credit, taken back, with why. */
616 revokeCredit(id: string, note: string, by: string): Promise<Result<CreditGrant>>;
617 /** A test workspace's billing wiped, to start again as a new customer. Only on Stripe's test key; never comped or enterprise. Logged. */
618 resetBilling(workspace: string, confirm: string, note: string, by: string): Promise<Result<BillingReset>>;
619 /**
620 * Test-mode Stripe data made inert before the live key, history kept: one
621 * workspace (any but an enterprise's), or every workspace not comped, not an
622 * enterprise's and not excluded (default syntaqx, flagon-io). Refused on a live key. Logged.
623 */
624 detachTestStripe(args: DetachTestStripeArgs): Promise<Result<TestStripeDetach>>;
625 /** The workspace's Stripe billing page, to send to the customer. Logged. */
626 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
627 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
628 /** Stripe's state for billing; `fix` enables the destination and adds missing events first. */
629 stripe(fix?: boolean, by?: string): Promise<StripeStatus>;
630 /** Where an enterprise's invoices go; makes its Stripe customer. */
631 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
632 /** The enterprise's billing address and tax ID, on its Stripe customer: Stripe Tax works its invoices out from them. */
633 enterpriseAddress(id: string, address: PostalAddress, taxIdType: string | null, taxId: string | null, by: string): Promise<Result<boolean>>;
634 /** Sends an enterprise its invoice now, for what its workspaces owe. */
635 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
636 /** Exactly these workspaces' accounts, such as one page of the list. */
637 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
638 /** Every workspace worth reaching out to, most urgent first. */
639 signals(): Promise<Signal[]>;
640 /** The business at a glance. */
641 overview(): Promise<Overview>;
642 /** A workspace's sales record. */
643 sales(workspace: string): Promise<SalesRecord>;
644 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
645 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
646 /** A workspace's invoices from g1t, for staff. */
647 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
648 /** Every invoice g1t has sent, newest first. */
649 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
650 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
651 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
652 /** Limit and overage requests, with each workspace's history; `open` by default. */
653 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
654 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
655 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
656 /** The Overages queue. */
657 overages(): Promise<Overage[]>;
658 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. `requestKey`, made once per form, makes a double click or a retry one credit. */
659 goodwill(
660 workspace: string,
661 amountMicros: number | null,
662 reason: string,
663 by: string,
664 day?: string | null,
665 requestKey?: string | null,
666 ): Promise<Result<LedgerEntry>>;
667 /** Workspaces spending in the last day, fastest first. */
668 velocity(): Promise<Velocity[]>;
669 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
670 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
671 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
672 costs(days?: number): Promise<CostsReport>;
673 /** The open margin alerts, for the banner on every page. */
674 costAlerts(): Promise<MarginAlert[]>;
675 /** g1t's own spend against its caps: the daily breaker and comped budgets. */
676 spendCaps(): Promise<SpendCaps>;
677 /** Lets compute start again for the rest of today (UTC) after the daily breaker; needs a note. */
678 liftBreaker(note: string, by: string): Promise<Result<SpendCaps>>;
679 /** Platform pauses, the last hour of platform usage, the month so far and the last day's breaches (billing's platform.rs). */
680 platformGuard(): Promise<PlatformGuard>;
681 /** Pauses or resumes one level across g1t; needs a note, recorded in the audit log. */
682 setPause(level: PauseLevel, paused: boolean, note: string, by: string): Promise<Result<PlatformGuard>>;
683 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
684 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
685 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
686 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
687 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
688 runCosts(by: string): Promise<Result<CostsRun>>;
689}
690
691/** How much a workspace has earned g1t's trust with money. */
692export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
693
694/**
695 * How far a workspace's unpaid usage has gone this month, and where its
696 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
697 * requests. Usage counts at its cost to g1t or its charge, whichever is
698 * more, so it counts while g1t is free too.
699 */
700export type Limit = {
701 workspace: string;
702 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
703 account: string;
704 accountName: string;
705 trust: Trust;
706 exposureMicros: number;
707 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
708 ceilingMicros: number | null;
709 trustCeilingMicros: number | null;
710 spendLimitMicros: number | null;
711 state: "ok" | "warning" | "stopped";
712 message: string | null;
713 /**
714 * Charged this month, which the spend limit is measured against: usage at
715 * price less the discount, included usage, the trial, pools and credit,
716 * with usage metered through the month counted on the same terms. The
717 * same number as the month's `UsageTotals.chargedMicros`.
718 */
719 spentMicros?: number;
720 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
721 defaultSpendLimit?: boolean;
722 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
723 availableMicros?: number | null;
724 /** How the ceiling grows from here, in a sentence. */
725 growth?: string | null;
726 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
727 prepaidMicros?: number;
728 /** The highest ceiling the workspace has had. */
729 maxCeilingMicros?: number | null;
730 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
731 raiseOnceMicros?: number | null;
732 /** When the one-time raise was used. */
733 raisedAt?: string | null;
734 /** A paid workspace's first billing cycle, on the starting ceiling. */
735 firstMonth?: boolean;
736 /** The budget's alerts, in percent of the spend limit: some of 50, 75, 90 and 100. */
737 alertLevels?: number[];
738 /** Whether usage pauses at the spend limit (the default); off, it only alerts. */
739 pauseAtLimit?: boolean;
740 /** An HTTPS address told of each budget alert. */
741 budgetWebhook?: string | null;
742};
743
744/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
745export type Price = {
746 meter:
747 | "sandbox_second"
748 | "build_second"
749 | "app_requests"
750 | "app_cpu"
751 | "app_month"
752 | "custom_domain_month"
753 | "private_storage"
754 | "embedding_tokens"
755 | "scan_cpu"
756 | "scan_rows"
757 | string;
758 title: string;
759 unit: string;
760 costMicros: number;
761 markupPercent: number;
762 priceMicros: number;
763 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
764 source: "list" | "cloudflare" | string;
765 checkedAt: string | null;
766 updatedAt: string;
767};
768
769export type PriceChange = {
770 meter: string;
771 oldCostMicros: number;
772 newCostMicros: number;
773 markupPercent: number;
774 /** The markup before, when the change was to the markup rather than the cost. */
775 oldMarkupPercent?: number;
776 reason: string;
777 createdAt: string;
778 /** When a change still to come takes effect: a rise is announced before it is charged. */
779 effectiveAt?: string;
780};
781
782export type PriceBook = {
783 prices: Price[];
784 changes: PriceChange[];
785 /** Retired with the models g1t no longer runs; still sent. */
786 modelMarginPercent: number;
787 /** Every plan, as sold now. */
788 plans?: FeaturePlan[];
789 /** What is free, and the capped budgets that pay for it. */
790 free?: FreeTier | null;
791};
792
793/** One kind of meter's usage this month, from `usage_meters`. */
794export type MeterUsage = {
795 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
796 key: string;
797 label: string;
798 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
799 micros: number;
800 /** How much, when it is known: `12 runs`, `41 build minutes`. */
801 quantity?: string | null;
802};
803
804/** What g1t gives without a plan; each is paid for by a capped budget. */
805export type FreeTier = {
806 /** Each new workspace's trial credit, once. */
807 trialWorkspaceMicros: number;
808 /** Trial grants each month, in all; new trials wait when it is spent. */
809 trialMonthlyPoolMicros: number;
810 /** g1t's open-source pool each month, and any one repository's share. */
811 ossPoolMicros: number;
812 ossRepoMicros: number;
813 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
814 freePrivateStorageBytes: number;
815 /** Days of audit log a free workspace keeps. */
816 auditRetentionDays: number;
817 /** Days of audit log the g1t plan keeps, and g1t's own and enterprise workspaces; longer by arrangement. */
818 planAuditRetentionDays?: number;
819 /** The smallest amount a card is charged when a month closes; less carries over. */
820 minChargeMicros: number;
821 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
822 gitOperationsIncluded?: number;
823 /** A new paid workspace's ceiling in its first month. */
824 paidStartCeilingMicros?: number;
825 /** The most a one-click goodwill credit can cost g1t. */
826 overageForgiveCostMicros?: number;
827};
828
829/**
830 * A workspace's trial credit: one grant per workspace, made the first time
831 * it uses something, out of a pool that resets each calendar month. Mirrors
832 * `Trial` in `crates/contracts/src/billing.rs`.
833 */
834export type Trial = {
835 open: boolean;
836 usedMicros: number;
837 limitMicros: number;
838 /** No longer used: trials do not end on a date. */
839 endsAt: string | null;
840 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
841 reason: "off" | "ended" | "used" | "pool" | null;
842 /** Whether the workspace has its grant already. */
843 granted?: boolean;
844 /** With `pool`: when new trials start again, the first of next month. */
845 waitsUntil?: string | null;
846};
847
848/**
849 * What a workspace has: the g1t plan (`plan`), and Security and quality
850 * (`security`), which comes with the plan at no price of its own. Deployments
851 * are part of the plan too; `has_feature` for either answers whether the
852 * workspace has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
853 */
854export type Feature = "plan" | "deployments" | "security";
855
856/**
857 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
858 * billing's price book cannot be read. Not an allowance: on the plan every
859 * unit is metered from the first, at cost plus 20%, and drawn from the
860 * plan's included usage first. Projects, previews and the apps behind them
861 * are not metered at all. Mirrors `deployment_costs`.
862 */
863export const DEPLOYMENT_COSTS = {
864 microsPerMillionRequests: 300_000,
865 microsPerMillionCpuMs: 20_000,
866 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
867 microsPerBuildSecond: 15,
868 /** One custom domain for a month. */
869 microsPerDomainMonth: 100_000,
870 /**
871 * Container apps, at Cloudflare Containers' list prices: a vCPU-second
872 * $0.00002, a GiB-second of memory $0.0000025, a GB-second of disk
873 * $0.00000007, the Durable Object in front of each instance while it
874 * runs (128 MB at $12.50 per million GB-seconds), and a GB of egress
875 * at $0.05, the most Cloudflare charges for one anywhere (Oceania, Korea
876 * and Taiwan; $0.025 in North America and Europe), since g1t cannot
877 * tell where a container's traffic went.
878 */
879 container: {
880 vcpuSecond: 20,
881 memoryGibSecond: 2.5,
882 diskGbSecond: 0.07,
883 instanceSecond: 1.5625,
884 egressGb: 50_000,
885 },
886} as const;
887
888export type FeaturePlan = {
889 feature: Feature;
890 title: string;
891 /** Charged every month while the plan is on, in cents, excluding tax: all of it, with no card fee on top. */
892 monthlyCents: number;
893 /** What the price includes, one line each. */
894 includes: string[];
895 /** How usage past the allowance is charged. */
896 overage: string;
897};
898
899export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
900
901export type Subscription = {
902 feature: Feature;
903 status: SubscriptionStatus;
904 /** RFC 3339: when the period paid for ends. */
905 periodEnd: string | null;
906 startedBy: string;
907 startedAt: string;
908};
909
910/** A feature as a workspace sees it. */
911export type FeatureState = {
912 plan: FeaturePlan;
913 subscription: Subscription | null;
914 /** Whether the feature works for the workspace now. */
915 on: boolean;
916 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
917 included?: boolean;
918};
919
920export interface BillingApi {
921 status(): Promise<BillingStatus>;
922 /** Members of the workspace only. */
923 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
924 /** Newest first. Members of the workspace only. */
925 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
926 /** Credits from g1t, newest first, with what is left of each. Members only. */
927 credits(workspace: string, viewer: Viewer): Promise<Result<Credits>>;
928 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
929 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
930 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
931 statementEntries(
932 workspace: string,
933 viewer: Viewer,
934 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
935 ): Promise<Result<LedgerEntry[]>>;
936 /** What the workspace's agents cost since `since`, broken down. Members only. */
937 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
938 /**
939 * Prepays usage ($25 at least) and returns the page to send the person to:
940 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
941 * The payment's id comes back to `returnUrl` as `session`.
942 */
943 checkout(
944 actor: User,
945 workspace: string,
946 amountCents: number,
947 returnUrl: string,
948 method?: "card" | "bank_transfer",
949 ): Promise<Result<{ url: string }>>;
950 /**
951 * Stripe's hosted billing page for the workspace: card, invoices, billing
952 * email and address. g1t never handles card numbers. Owners only.
953 */
954 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
955 /** Credits a payment once the processor says it was made. Safe to repeat. */
956 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
957 /** A workspace's free trial allowance; `exempt` workspaces are open anyway. */
958 trial(workspace: string, exempt: string[]): Promise<Trial>;
959 /** Every paid feature and the workspace's plan for each. Members only. */
960 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
961 /**
962 * Starts the card page for a feature's monthly plan. Owners only. The
963 * page's id comes back to `returnUrl` as `session`.
964 */
965 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
966 /** Turns the feature on once the plan is paid for. Safe to repeat. */
967 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
968 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
969 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
970 /** Which of the workspaces are free (on no paid plan); none where payments are not set up. */
971 freeWorkspaces(workspaces: string[]): Promise<string[]>;
972 /** Whether a feature works for a workspace now; a failure with the reason when not. */
973 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
974 /**
975 * Usage past a plan's allowance, charged from credit at cost plus the
976 * margin, once per `reference`. False if it was charged before.
977 */
978 chargeFeature(charge: {
979 workspace: string;
980 feature: Feature;
981 costMicros: number;
982 description: string;
983 repo?: string | null;
984 reference: string;
985 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
986 buildSeconds?: number | null;
987 }): Promise<Result<boolean>>;
988 /**
989 * What a source cost g1t so far this month, so the workspace's limit
990 * counts it now. Replaces the last report. Billing charges `context`
991 * and `security` itself once the month is over; `deployments` charges
992 * its own. `context` is search embeddings (services/artifacts) and
993 * `telemetry` is observability ingest past the free amount
994 * (services/telemetry), both at cost.
995 */
996 notePending(
997 workspace: string,
998 source: "deployments" | "domains" | "context" | "security" | "telemetry",
999 costMicros: number,
1000 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
1001 detail?: string | null,
1002 /**
1003 * The month (`YYYY-MM`, UTC) the total belongs to, read when it was
1004 * worked out. Billing takes this month, or the month before while its
1005 * figure for the source is not charged and the month is not closed.
1006 * Left out: the month the report arrives in.
1007 */
1008 month?: string | null,
1009 ): Promise<boolean>;
1010 /**
1011 * This month's usage, one line per kind of meter, at what it is charged
1012 * before the plan's included usage or a pool paid for it. Members only.
1013 */
1014 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
1015 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
1016 entitlements(workspace: string): Promise<Entitlements>;
1017 /**
1018 * Holds a start's estimated cost before the work starts. A failure's code says why not:
1019 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
1020 */
1021 reserve(reservation: {
1022 workspace: string;
1023 repo: RepoPath;
1024 public: boolean;
1025 kind: ComputeKind;
1026 /** The most the work is expected to cost g1t, before the margin. */
1027 estimateMicros: number;
1028 }): Promise<Result<ReservationHeld>>;
1029 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
1030 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
1031 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
1032 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
1033 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
1034 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
1035 /** An owner asks for a higher limit, or for help with usage past what was meant. */
1036 requestLimit(
1037 actor: User,
1038 workspace: string,
1039 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
1040 ): Promise<Result<LimitRequest>>;
1041 /** The workspace's requests and their answers, newest first. Members only. */
1042 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
1043 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
1044 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
1045 /** Every metered price and the recent changes. Public. */
1046 prices(): Promise<PriceBook>;
1047 /** A workspace's limit, for its members. */
1048 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
1049 /** The same, for the services that enforce it. */
1050 checkLimit(workspace: string): Promise<Result<Limit>>;
1051 /**
1052 * The owners' own monthly limit, up to what is available; null goes back
1053 * to the default, and `useFullLimit` uses everything available. Owners only.
1054 */
1055 setSpendLimit(
1056 actor: User,
1057 workspace: string,
1058 spendLimitMicros: number | null,
1059 useFullLimit?: boolean,
1060 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
1061 raiseOnce?: boolean,
1062 ): Promise<Result<Limit>>;
1063 /** The workspace's invoices from g1t, newest first. Owners and billing managers only. */
1064 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
1065 /**
1066 * How long a sandbox ran for a workspace, reported when it stops. Its
1067 * cost is recorded and every second is charged, from the first. False if
1068 * `reference` was recorded before.
1069 */
1070 recordSandbox(usage: {
1071 workspace: string;
1072 seconds: number;
1073 description: string;
1074 repo?: string | null;
1075 reference: string;
1076 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
1077 kind?: ComputeKind | null;
1078 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
1079 cpuSeconds?: number | null;
1080 /** The reservation it started under, settled with this cost. */
1081 reservationId?: string | null;
1082 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
1083 selfHosted?: boolean;
1084 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
1085 instance?: string | null;
1086 }): Promise<Result<boolean>>;
1087 /** Usage over a range of days (`YYYY-MM-DD`, both included), at price, by product, meter, project and day. Members only. */
1088 usageReport(
1089 workspace: string,
1090 viewer: Viewer,
1091 range: { from: string; until: string; products?: string[]; projects?: string[] },
1092 ): Promise<Result<UsageReport>>;
1093 /** The monthly budget: the spend limit, its alerts, whether usage pauses at 100%, and a webhook. Owners only. */
1094 setBudget(
1095 actor: User,
1096 workspace: string,
1097 budget: { amountMicros: number | null; alerts: number[]; pauseAtLimit: boolean; webhook: string | null; keepLimit?: boolean },
1098 ): Promise<Result<Limit>>;
1099 /** Invoice details from the Stripe customer, the default payment method, invoices and the next invoice: owners and billing managers. Any other member gets the next invoice only. */
1100 billingDetails(workspace: string, viewer: Viewer): Promise<Result<BillingDetails>>;
1101 /** Saves invoice details on the Stripe customer; absent fields stay, empty clears. Owners only. */
1102 setBillingDetails(actor: User, workspace: string, details: BillingDetailsInput): Promise<Result<BillingDetails>>;
1103}
1104
1105
1106/** One slice of usage: what it was for, what it cost, how many runs. */
1107export type UsageSlice = { key: string; micros: number; runs: number };
1108
1109/** What a workspace's agents cost over a period. */
1110export type Usage = {
1111 since: string;
1112 /** Charged, including g1t's margin. */
1113 spentMicros: number;
1114 /** 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. */
1115 coveredMicros?: number;
1116 /** What the account's discount took off the price; usage at price is spent + covered + this. */
1117 discountMicros?: number;
1118 /** The account's discount now, in percent; with one, the slices are at price. */
1119 discountPercent?: number | null;
1120 /** Usage at price: spent + covered + discount, from the same ledger lines. The one usage figure every page shows. */
1121 priceMicros?: number;
1122 /** What g1t's model provider charged, before the margin. */
1123 costMicros: number;
1124 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
1125 providerMicros: number;
1126 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
1127 usedMicros: number;
1128 /** g1t charges nothing for now; the slices then measure usage at cost. */
1129 free: boolean;
1130 runs: number;
1131 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
1132 byDay: UsageSlice[];
1133 byTask: UsageSlice[];
1134 byRepo: UsageSlice[];
1135 /** Keyed `namespace/name#number`. */
1136 byPull: UsageSlice[];
1137 byModel: UsageSlice[];
1138 /** Credit bought in the period. */
1139 addedMicros: number;
1140};
1141
1142/** One of g1t's products (a "bucket") on one day. Money in micros. */
1143export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
1144
1145/** One product over the range: what customers were charged at price against what it cost. */
1146export type ProductMargin = {
1147 bucket: string;
1148 title: string;
1149 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
1150 costMicros: number;
1151 cfCostMicros: number;
1152 ownCostMicros: number;
1153 valueMicros: number;
1154 marginMicros: number;
1155 marginPercent: number | null;
1156 costSource: "cloudflare" | "ledger" | string;
1157 /** Running g1t, paid for by the plan. */
1158 overhead: boolean;
1159};
1160
1161/** All of g1t: money in (usage and the plan) against every cost. */
1162export type OverallMargin = {
1163 usageMicros: number;
1164 plansMicros: number;
1165 costMicros: number;
1166 marginMicros: number;
1167 marginPercent: number | null;
1168 /** Of costMicros, what went on usage g1t gave away on purpose: comped workspaces, free periods, the trial and the open-source pool. */
1169 givenMicros?: number;
1170 /** Money in against costMicros - givenMicros. */
1171 soldMarginMicros?: number;
1172 soldMarginPercent?: number | null;
1173 /** Usage sold: usageMicros against what that usage cost, less what was given. */
1174 usageCostMicros?: number;
1175 usageMarginMicros?: number;
1176 usageMarginPercent?: number | null;
1177 /** Running g1t: plansMicros against the platform's cost, less its given share. */
1178 runningCostMicros?: number;
1179 /** Cost no mapping names, less its given share. */
1180 unmappedCostMicros?: number;
1181 /** givenMicros by why. Free is free periods, free allowances and overruns g1t covered. */
1182 givenCompedMicros?: number;
1183 givenFreeMicros?: number;
1184 givenTrialMicros?: number;
1185 givenPoolMicros?: number;
1186 /** What discounts on an account's terms took below cost plus the margin: given, not margin lost. */
1187 givenDiscountMicros?: number;
1188 /** Credits from g1t spent on usage, by kind: given, never money in. Refunds come off money in instead. */
1189 givenCreditPromotionalMicros?: number;
1190 givenCreditGoodwillMicros?: number;
1191 /** What testing resets wiped that g1t paid for: the usage still happened, so its cost is given, never a leak. */
1192 givenResetMicros?: number;
1193 /** Credits over the range: given (every kind), spent on usage, and refunds' money given back. */
1194 creditsGivenMicros?: number;
1195 creditsUsedMicros?: number;
1196 creditsRefundedMicros?: number;
1197 /** costMicros by who g1t pays: Cloudflare's bill (billed, after included allowances) and model providers (tokens, not on Cloudflare's bill). */
1198 /** What the plan's included usage paid for, at price: money in for usage, paid out of plansMicros. */
1199 includedMicros?: number;
1200 cloudflareCostMicros?: number;
1201 modelsCostMicros?: number;
1202 /** Tax collected with payments over the range, net of refunds: owed to tax authorities, never cash or revenue. */
1203 taxCollectedMicros?: number;
1204 /** Card processing fees passed on with card payments, net of refunds: they pay Stripe's fee, not revenue. */
1205 cardFeesMicros?: number;
1206 /** What workspaces were charged while payments were not live (Stripe's test mode): given, never money in. */
1207 givenUnpaidMicros?: number;
1208 /** Cloudflare's subscriptions over the range: each day's share of the billing cycle it is in. */
1209 subscriptionsMicros?: number;
1210 /** What AI Gateway priced g1t's own provider traffic at over the range, beside the ledger's model cost. */
1211 gatewayCostMicros?: number;
1212};
1213
1214/** A count, cost or leak that does not add up. */
1215export type CostDrift = {
1216 bucket: string;
1217 title: string;
1218 kind: "count" | "cost" | "leak" | string;
1219 ours: number;
1220 cloudflare: number;
1221 deltaPercent: number | null;
1222 detail: string;
1223 foundAt: string;
1224};
1225
1226export type MarginAlert = {
1227 id: string;
1228 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1229 /** The product, or the workspace. */
1230 subject: string;
1231 detail: string;
1232 since: string;
1233 openedAt: string;
1234 emailedAt: string | null;
1235};
1236
1237/** A change to a price, measured from what Cloudflare charged. */
1238export type PriceProposal = {
1239 id: string;
1240 meter: string;
1241 title: string;
1242 unit: string;
1243 currentCostMicros: number;
1244 proposedCostMicros: number;
1245 changePercent: number;
1246 markupPercent: number;
1247 reason: string;
1248 source: "keeper" | "reconciler" | string;
1249 /** Far off the current cost: look before approving. */
1250 suspect: boolean;
1251 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1252 createdAt: string;
1253 decidedAt: string | null;
1254 decidedBy: string | null;
1255 note: string | null;
1256 effectiveAt: string | null;
1257};
1258
1259/** One version of one meter's price; never changed once written. */
1260export type PriceVersion = {
1261 id: string;
1262 meter: string;
1263 version: number;
1264 costMicros: number;
1265 markupPercent: number;
1266 priceMicros: number;
1267 effectiveAt: string;
1268 reason: string;
1269 createdBy: string;
1270 appliedAt: string | null;
1271 /**
1272 * What `costMicros` is: `cost`, what g1t pays for a unit; `rate`, a price
1273 * g1t sets with no cost behind it (the agent rate), so it is no cost;
1274 * `weight`, a multiplier in millionths, not money. Absent from older
1275 * billing: read as `cost`.
1276 */
1277 basis?: "cost" | "rate" | "weight" | "";
1278};
1279
1280/** `detachTestStripe`'s arguments. `confirm`: the slug, or "detach" for every workspace; not needed for a dry run. */
1281export type DetachTestStripeArgs = {
1282 workspace?: string | null;
1283 exclude?: string[] | null;
1284 dryRun: boolean;
1285 cancelAtStripe?: boolean;
1286 confirm?: string;
1287 by: string;
1288};
1289
1290/** One workspace's detach (snake_case, as billing sends it). */
1291export type WorkspaceDetach = {
1292 workspace: string;
1293 done: boolean;
1294 customer: boolean;
1295 card: string | null;
1296 card_cached: boolean;
1297 subscriptions: number;
1298 card_checks: number;
1299 checkouts: number;
1300 ai_reload: boolean;
1301 autopay_cleared: boolean;
1302 invoices_voided: number;
1303 months_skipped: string[];
1304 credit_grants_closed: number;
1305 credit_closed_micros: number;
1306 payments_reversed_micros: number;
1307 plan_payments_reversed_micros: number;
1308 written_off_micros: number;
1309 balance_before_micros: number;
1310 balance_after_micros: number;
1311 stripe_canceled: number;
1312 stripe_errors: string[];
1313 /** Metered figures of months before this one marked charged without a charge, and what they came to. */
1314 pending_months_marked: number;
1315 pending_marked_micros: number;
1316 /** This month's metered figures kept as the baseline later reports are charged past. */
1317 pending_baselined: number;
1318 pending_baselined_micros: number;
1319 /** This month's draws on the plan's included usage removed. */
1320 plan_credit_cleared_micros: number;
1321 /** What lost test-mode disputes left owed, cleared. */
1322 dispute_owed_cleared_micros: number;
1323 /** Open test-mode disputes closed. */
1324 disputes_closed: number;
1325};
1326
1327/** What `detachTestStripe` changed, or would change. */
1328export type TestStripeDetach = {
1329 dry_run: boolean;
1330 workspaces: WorkspaceDetach[];
1331 skipped: { workspace: string; reason: string }[];
1332 /** Workspaces left for another call (25 a call). */
1333 remaining: number;
1334};
1335
1336/** What `resetBilling` removed. */
1337export type BillingReset = { workspace: string; rows: number; refreshed?: boolean };
1338
1339export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; givenMicros?: number; internal: boolean };
1340
1341export type CostLineSummary = {
1342 product: string;
1343 meter: string;
1344 rawName: string;
1345 unit: string;
1346 source: string;
1347 quantity: number;
1348 costMicros: number;
1349 /** Absent when no mapping claims it. */
1350 bucket: string | null;
1351};
1352
1353export type CostMapping = {
1354 product: string;
1355 meter: string;
1356 bucket: string;
1357 priceMeter: string | null;
1358 ownMeter: string | null;
1359 scaleToOwn: boolean;
1360 driftPercent: number;
1361 note: string;
1362 updatedAt: string;
1363 updatedBy: string;
1364};
1365
1366export type CostMappingInput = {
1367 product: string;
1368 meter: string;
1369 bucket?: string;
1370 priceMeter?: string | null;
1371 ownMeter?: string | null;
1372 scaleToOwn?: boolean;
1373 driftPercent?: number | null;
1374 note?: string;
1375 remove?: boolean;
1376};
1377
1378export type CostSettings = {
1379 autoApply: boolean;
1380 autoApplyPercent: number;
1381 noticeDays: number;
1382 marginFloorPercent: number;
1383 alertDays: number;
1384 minDailyCostMicros: number;
1385 anomalyFactor: number;
1386 anomalyFloorMicros: number;
1387};
1388
1389export type CostsReport = {
1390 configured: boolean;
1391 fetchedAt: string | null;
1392 since: string;
1393 until: string;
1394 days: CostDay[];
1395 products: ProductMargin[];
1396 overall: OverallMargin;
1397 drift: CostDrift[];
1398 alerts: MarginAlert[];
1399 proposals: PriceProposal[];
1400 versions: PriceVersion[];
1401 topWorkspaces: WorkspaceCost[];
1402 lines: CostLineSummary[];
1403 mappings: CostMapping[];
1404 settings: CostSettings;
1405 /** g1t's own spend against its two caps. */
1406 caps: SpendCaps;
1407 /** Cloudflare's current billing cycle: usage cost so far by meter, and the projection. Absent until the bill is read. */
1408 cycle?: CloudflareCycle | null;
1409 /** The last read of Cloudflare's billable usage: what came back. */
1410 billRead?: BillRead | null;
1411 /** Of the range's cost, what no workspace's usage could carry: running g1t, attributed to no one. */
1412 unattributedMicros?: number;
1413};
1414
1415/** Cloudflare's billing cycle, as its Billable usage page shows it. */
1416export type CloudflareCycle = {
1417 /** First and last days, YYYY-MM-DD, UTC. */
1418 start: string;
1419 end: string;
1420 days: number;
1421 /** Days from its start to today, today included. */
1422 daysElapsed: number;
1423 /** Usage cost so far, after the included allowances. */
1424 usageMicros: number;
1425 /** usageMicros over the days elapsed, times the cycle's days. */
1426 projectedMicros: number;
1427 averageDailyMicros: number;
1428 /** Cloudflare's subscriptions for the cycle (not on the usage bill). */
1429 subscriptionsMicros: number;
1430 meters: CycleMeter[];
1431};
1432
1433/** One of Cloudflare's meters over the cycle so far. */
1434export type CycleMeter = {
1435 product: string;
1436 meter: string;
1437 rawName: string;
1438 unit: string;
1439 quantity: number;
1440 /** What the cycle includes; null without a list price. */
1441 included: number | null;
1442 billableQuantity: number;
1443 costMicros: number;
1444 /** cloudflare: Cloudflare's own cost; list: the list price past the included amount; none: no list price known. */
1445 basis: "cloudflare" | "list" | "none" | string;
1446};
1447
1448/** What the last read of Cloudflare's billable usage got back. */
1449export type BillRead = {
1450 readAt: string;
1451 since: string;
1452 until: string;
1453 rows: number;
1454 pages: number;
1455 consumedRows: number;
1456 pricingOnlyRows: number;
1457 costedRows: number;
1458};
1459
1460/** One level of the platform pause, as sudo shows it. Snake case, as billing sends it. */
1461export type PauseState = {
1462 level: PauseLevel;
1463 paused: boolean;
1464 note: string | null;
1465 set_by: string | null;
1466 set_at: string | null;
1467 /** Set by billing's usage watcher, not a person. */
1468 auto: boolean;
1469};
1470
1471/** One platform metric over an hour or the month so far. */
1472export type PlatformMetric = {
1473 metric: string;
1474 title: string;
1475 value: number;
1476 /** Its hourly threshold (`PLATFORM_HOURLY_*`); 0: none. */
1477 threshold: number;
1478 /** The script, queue, database or namespace that counted most. */
1479 top_name: string | null;
1480 top_value: number | null;
1481};
1482
1483/** A breach billing's usage watcher found. */
1484export type PlatformBreach = {
1485 id: string;
1486 metric: string;
1487 hour: string;
1488 rule: "threshold" | "spike";
1489 value: number;
1490 threshold: number;
1491 severe: boolean;
1492 top_name: string | null;
1493 detail: string;
1494 /** Levels it paused. */
1495 paused: PauseLevel[];
1496 opened_at: string;
1497 emailed_at: string | null;
1498};
1499
1500/** Billing's `admin_platform_guard`: the platform pause and usage watcher
1501 * (docs.g1t.sh/guides/deploy-to-cloudflare/#spend-guardrails). */
1502export type PlatformGuard = {
1503 levels: PauseState[];
1504 /** The last hour read, `YYYY-MM-DDTHH:00:00Z`. */
1505 hour: string | null;
1506 last_hour: PlatformMetric[];
1507 month: string;
1508 month_to_date: PlatformMetric[];
1509 breaches: PlatformBreach[];
1510 /** Whether billing can read Cloudflare's analytics. */
1511 can_read: boolean;
1512 /** `AUTO_PAUSE`: the levels a severe breach may pause. */
1513 auto_pause: PauseLevel[];
1514 /** What the latest run could not see: each query that failed, with its error. */
1515 blind?: { key: string; dataset: string; error: string }[];
1516 /** The latest run found every dataset empty: the wrong account, or a token that cannot see it. */
1517 empty?: boolean;
1518 /** The hour the latest run read. */
1519 last_run?: string | null;
1520};
1521
1522/** What g1t pays for itself, at cost, against its caps (billing's `budget`). */
1523export type SpendCaps = {
1524 /** Today (UTC), YYYY-MM-DD, and this month, YYYY-MM. */
1525 day: string;
1526 month: string;
1527 /** What g1t paid for itself today across every workspace. */
1528 todayMicros: number;
1529 /** `PLATFORM_DAILY_SPEND_CAP_MICROS`; 0: no breaker. */
1530 dailyCapMicros: number;
1531 /** New workflows, checks and merge queue runs g1t would pay for are paused. */
1532 tripped: boolean;
1533 trippedAt: string | null;
1534 liftedBy: string | null;
1535 liftedAt: string | null;
1536 liftNote: string | null;
1537 /** This month so far, by what paid: comped, trial, oss, given, unpaid. */
1538 monthBuckets: { bucket: string; title: string; micros: number }[];
1539 comped: CompedBudget[];
1540 /** Free workspaces' share of reconciled costs this month (git, storage, platform). */
1541 freeTierMicros: number;
1542 /** Cloudflare's subscriptions a month: read from Cloudflare each day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate. */
1543 fixedMonthlyMicros: number;
1544 fixedSource?: "cloudflare" | "estimate" | string;
1545 fixedReadAt?: string | null;
1546 /** Each subscription, when read from Cloudflare. */
1547 fixedItems?: { name: string; monthlyMicros: number }[];
1548 /** Of fixedMonthlyMicros, this calendar month's days so far, each at its billing cycle's daily share. */
1549 fixedMonthMicros?: number;
1550 /** Money in this month, through the last reconciled day. */
1551 revenueMicros: number;
1552 /**
1553 * Of this month's buckets, what was spent on workspaces whose billing a
1554 * testing reset later wiped (still g1t's spend; the reconciled figures
1555 * have it only where the reset kept it), and those workspaces.
1556 */
1557 resetMicros?: number;
1558 resetWorkspaces?: string[];
1559};
1560
1561/** A comped account's monthly budget, at cost. */
1562export type CompedBudget = {
1563 account: string;
1564 name: string;
1565 usedMicros: number;
1566 /** 0: no budget. */
1567 ceilingMicros: number;
1568 /** `COMPED_MONTHLY_CEILING_MICROS`, not the account's own limit. */
1569 defaultCeiling: boolean;
1570 /** 50, 75, 90, 100, or 0. */
1571 level: number;
1572};
1573
1574export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };
1575
1576/** The product families the Usage page groups meters into, in order. */
1577export const PRODUCTS = [
1578 { key: "sandboxes", label: "Sandboxes" },
1579 { key: "deployments", label: "Deployments" },
1580 { key: "git_storage", label: "Git & storage" },
1581 { key: "packages", label: "Packages" },
1582 { key: "security", label: "Security & quality" },
1583 { key: "search", label: "Search" },
1584 { key: "observability", label: "Observability" },
1585] as const;
1586
1587export type ProductKey = (typeof PRODUCTS)[number]["key"];
1588
1589/** What usage came to over a range, and what paid for it: price − discount − included − credits = charged. */
1590export type UsageTotals = {
1591 /** Usage at price, pending usage included. */
1592 priceMicros: number;
1593 discountMicros: number;
1594 /** Paid by the plan's included usage, the trial and g1t's pools. */
1595 includedMicros: number;
1596 /** Paid by credit from g1t, and AI credit bought before g1t stopped selling it. */
1597 creditsMicros: number;
1598 /** Left for the workspace to pay. */
1599 chargedMicros: number;
1600 /** Metered this month, charged when it closes. */
1601 pendingMicros: number;
1602 /** What of `pendingMicros` will be charged at the close, after the discount and what g1t covers; absent from an older billing. */
1603 pendingChargedMicros?: number;
1604 costMicros: number;
1605};
1606
1607export type UsageDay = { day: string; product: string; micros: number };
1608
1609/** 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. */
1610
1611export type UsageAllowance = { used: number; of: number; unit: string };
1612
1613export type ProjectUsage = { project: string; micros: number; quantity: number };
1614
1615/** One meter over a range. */
1616export type MeterLine = {
1617 key: string;
1618 label: string;
1619 product: string;
1620 /** `tokens`, `seconds`, `bytes`, `operations`, `requests` or `entries`. */
1621 unit: string;
1622 quantity: number;
1623 micros: number;
1624 pendingMicros?: number;
1625 /** Every day of the range, oldest first, at price. */
1626 daily: number[];
1627 allowance?: UsageAllowance | null;
1628 byProject: ProjectUsage[];
1629 /** How the quantity is counted, when that needs saying (the agent rate's token weights). */
1630 note?: string | null;
1631};
1632
1633export type ProductUsage = { key: string; label: string; micros: number; meters: MeterLine[] };
1634
1635export type UsageReport = {
1636 from: string;
1637 until: string;
1638 totals: UsageTotals;
1639 days: UsageDay[];
1640 products: ProductUsage[];
1641 projects: string[];
1642 /** The plan's included usage this month, in micros. */
1643 included?: UsageAllowance | null;
1644 discountPercent?: number | null;
1645 /** AI credit bought before g1t stopped selling it, left now; kept apart from credit for everything. */
1646 aiCreditMicros: number;
1647 creditMicros: number;
1648 trialMicros?: number | null;
1649 plan: PlanKind;
1650 free: boolean;
1651};
1652
1653export type PostalAddress = { line1: string; line2: string; city: string; state: string; postalCode: string; country: string };
1654
1655export type PaymentMethod = {
1656 kind: string;
1657 brand?: string | null;
1658 last4?: string | null;
1659 expMonth?: number | null;
1660 expYear?: number | null;
1661};
1662
1663export type StripeInvoice = {
1664 id: string;
1665 number?: string | null;
1666 status: string;
1667 totalCents: number;
1668 currency: string;
1669 createdAt: string;
1670 description?: string | null;
1671 hostedUrl?: string | null;
1672 pdfUrl?: string | null;
1673};
1674
1675export type UpcomingInvoice = { closesAt: string; subscriptionsMicros: number; usageMicros: number; totalMicros: number };
1676
1677export type BillingDetails = {
1678 customer: boolean;
1679 email: string | null;
1680 name: string | null;
1681 address: PostalAddress | null;
1682 taxIdType: string | null;
1683 taxId: string | null;
1684 poNumber: string | null;
1685 language: string | null;
1686 paymentMethod: PaymentMethod | null;
1687 invoices: StripeInvoice[];
1688 upcoming: UpcomingInvoice;
1689 unavailable?: string | null;
1690 /** Whether Stripe Tax can place the customer from the address; without it nothing is charged. */
1691 taxLocation?: boolean;
1692 /** Set when g1t did not charge for want of a billing address. */
1693 taxAddressNeededAt?: string | null;
1694 /** Stripe's check of the tax ID: pending, verified, unverified or unavailable. */
1695 taxIdStatus?: string | null;
1696 /** none, exempt or reverse, as set at Stripe. */
1697 taxExempt?: string | null;
1698};
1699
1700export type BillingDetailsInput = {
1701 email?: string;
1702 name?: string;
1703 address?: PostalAddress;
1704 taxIdType?: string;
1705 taxId?: string;
1706 poNumber?: string;
1707 language?: string;
1708};