g1t/packages/contracts/src/billing.ts

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