g1t/packages/contracts/src/billing.ts

1,263 lines50,427 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 /** A test workspace's billing wiped, to start again as a new customer. Only on Stripe's test key; never comped or enterprise. Logged. */
528 resetBilling(workspace: string, confirm: string, note: string, by: string): Promise<Result<BillingReset>>;
529 /** The workspace's Stripe billing page, to send to the customer. Logged. */
530 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
531 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
532 /** Stripe's state for billing; `fix` enables the destination and adds missing events first. */
533 stripe(fix?: boolean, by?: string): Promise<StripeStatus>;
534 /** Where an enterprise's invoices go; makes its Stripe customer. */
535 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
536 /** Sends an enterprise its invoice now, for what its workspaces owe. */
537 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
538 /** Exactly these workspaces' accounts, such as one page of the list. */
539 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
540 /** Every workspace worth reaching out to, most urgent first. */
541 signals(): Promise<Signal[]>;
542 /** The business at a glance. */
543 overview(): Promise<Overview>;
544 /** A workspace's sales record. */
545 sales(workspace: string): Promise<SalesRecord>;
546 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
547 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
548 /** A workspace's invoices from g1t, for staff. */
549 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
550 /** Every invoice g1t has sent, newest first. */
551 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
552 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
553 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
554 /** Limit and overage requests, with each workspace's history; `open` by default. */
555 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
556 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
557 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
558 /** The Overages queue. */
559 overages(): Promise<Overage[]>;
560 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. */
561 goodwill(workspace: string, amountMicros: number | null, reason: string, by: string, day?: string | null): Promise<Result<LedgerEntry>>;
562 /** Workspaces spending in the last day, fastest first. */
563 velocity(): Promise<Velocity[]>;
564 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
565 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
566 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
567 costs(days?: number): Promise<CostsReport>;
568 /** The open margin alerts, for the banner on every page. */
569 costAlerts(): Promise<MarginAlert[]>;
570 /** g1t's own spend against its caps: the daily breaker and comped budgets. */
571 spendCaps(): Promise<SpendCaps>;
572 /** Lets hosted-model runs start again for the rest of today (UTC); needs a note. */
573 liftBreaker(note: string, by: string): Promise<Result<SpendCaps>>;
574 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
575 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
576 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
577 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
578 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
579 runCosts(by: string): Promise<Result<CostsRun>>;
580}
581
582/** How much a workspace has earned g1t's trust with money. */
583export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
584
585/**
586 * How far a workspace's unpaid usage has gone this month, and where its
587 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
588 * requests. Usage counts at its cost to g1t or its charge, whichever is
589 * more, so it counts while g1t is free too.
590 */
591export type Limit = {
592 workspace: string;
593 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
594 account: string;
595 accountName: string;
596 trust: Trust;
597 exposureMicros: number;
598 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
599 ceilingMicros: number | null;
600 trustCeilingMicros: number | null;
601 spendLimitMicros: number | null;
602 state: "ok" | "warning" | "stopped";
603 message: string | null;
604 /** Charged this month: what the spend limit is measured against. */
605 spentMicros?: number;
606 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
607 defaultSpendLimit?: boolean;
608 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
609 availableMicros?: number | null;
610 /** How the ceiling grows from here, in a sentence. */
611 growth?: string | null;
612 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
613 prepaidMicros?: number;
614 /** The highest ceiling the workspace has had. */
615 maxCeilingMicros?: number | null;
616 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
617 raiseOnceMicros?: number | null;
618 /** When the one-time raise was used. */
619 raisedAt?: string | null;
620 /** A paid workspace's first billing cycle, on the starting ceiling. */
621 firstMonth?: boolean;
622};
623
624/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
625export type Price = {
626 meter:
627 | "sandbox_second"
628 | "build_second"
629 | "app_requests"
630 | "app_cpu"
631 | "app_month"
632 | "custom_domain_month"
633 | "private_storage"
634 | "embedding_tokens"
635 | "scan_cpu"
636 | "scan_rows"
637 | string;
638 title: string;
639 unit: string;
640 costMicros: number;
641 markupPercent: number;
642 priceMicros: number;
643 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
644 source: "list" | "cloudflare" | string;
645 checkedAt: string | null;
646 updatedAt: string;
647};
648
649export type PriceChange = {
650 meter: string;
651 oldCostMicros: number;
652 newCostMicros: number;
653 markupPercent: number;
654 /** The markup before, when the change was to the markup rather than the cost. */
655 oldMarkupPercent?: number;
656 reason: string;
657 createdAt: string;
658 /** When a change still to come takes effect: a rise is announced before it is charged. */
659 effectiveAt?: string;
660};
661
662export type PriceBook = {
663 prices: Price[];
664 changes: PriceChange[];
665 modelMarginPercent: number;
666 /** Every plan, as sold now. */
667 plans?: FeaturePlan[];
668 /** What is free, and the capped budgets that pay for it. */
669 free?: FreeTier | null;
670};
671
672/** One kind of meter's usage this month, from `usage_meters`. */
673export type MeterUsage = {
674 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
675 key: string;
676 label: string;
677 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
678 micros: number;
679 /** How much, when it is known: `12 runs`, `41 build minutes`. */
680 quantity?: string | null;
681};
682
683/** What g1t gives without a plan; each is paid for by a capped budget. */
684export type FreeTier = {
685 /** Each new workspace's trial credit, once. */
686 trialWorkspaceMicros: number;
687 /** Trial grants each month, in all; new trials wait when it is spent. */
688 trialMonthlyPoolMicros: number;
689 /** g1t's open-source pool each month, and any one repository's share. */
690 ossPoolMicros: number;
691 ossRepoMicros: number;
692 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
693 freePrivateStorageBytes: number;
694 /** Days of audit log a free workspace keeps. */
695 auditRetentionDays: number;
696 /** Days of audit log the g1t plan keeps, and g1t's own and enterprise workspaces; longer by arrangement. */
697 planAuditRetentionDays?: number;
698 /** The smallest amount a card is charged when a month closes; less carries over. */
699 minChargeMicros: number;
700 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
701 gitOperationsIncluded?: number;
702 /** A new paid workspace's ceiling in its first month. */
703 paidStartCeilingMicros?: number;
704 /** The most a one-click goodwill credit can cost g1t. */
705 overageForgiveCostMicros?: number;
706};
707
708/**
709 * A workspace's trial credit: one grant per workspace, made the first time
710 * it uses something, out of a pool that resets each calendar month. Mirrors
711 * `Trial` in `crates/contracts/src/billing.rs`.
712 */
713export type Trial = {
714 open: boolean;
715 usedMicros: number;
716 limitMicros: number;
717 /** No longer used: trials do not end on a date. */
718 endsAt: string | null;
719 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
720 reason: "off" | "ended" | "used" | "pool" | null;
721 /** Whether the workspace has its grant already. */
722 granted?: boolean;
723 /** With `pool`: when new trials start again, the first of next month. */
724 waitsUntil?: string | null;
725};
726
727/**
728 * What a workspace pays a monthly price for: the g1t plan (`plan`). Deployments
729 * are part of it; `has_feature` for `deployments` answers whether the workspace
730 * has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
731 */
732export type Feature = "plan" | "deployments";
733
734/**
735 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
736 * billing's price book cannot be read. Not an allowance: on the plan every
737 * unit is metered from the first, at cost plus 20%, and drawn from the
738 * plan's included usage first. Projects, previews and the apps behind them
739 * are not metered at all. Mirrors `deployment_costs`.
740 */
741export const DEPLOYMENT_COSTS = {
742 microsPerMillionRequests: 300_000,
743 microsPerMillionCpuMs: 20_000,
744 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
745 microsPerBuildSecond: 15,
746 /** One custom domain for a month. */
747 microsPerDomainMonth: 100_000,
748} as const;
749
750export type FeaturePlan = {
751 feature: Feature;
752 title: string;
753 /** Charged every month while the plan is on, in cents. */
754 monthlyCents: number;
755 /** What the price includes, one line each. */
756 includes: string[];
757 /** How usage past the allowance is charged. */
758 overage: string;
759};
760
761export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
762
763export type Subscription = {
764 feature: Feature;
765 status: SubscriptionStatus;
766 /** RFC 3339: when the period paid for ends. */
767 periodEnd: string | null;
768 startedBy: string;
769 startedAt: string;
770};
771
772/** A feature as a workspace sees it. */
773export type FeatureState = {
774 plan: FeaturePlan;
775 subscription: Subscription | null;
776 /** Whether the feature works for the workspace now. */
777 on: boolean;
778 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
779 included?: boolean;
780};
781
782export interface BillingApi {
783 status(): Promise<BillingStatus>;
784 /** Members of the workspace only. */
785 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
786 /** Newest first. Members of the workspace only. */
787 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
788 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
789 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
790 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
791 statementEntries(
792 workspace: string,
793 viewer: Viewer,
794 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
795 ): Promise<Result<LedgerEntry[]>>;
796 /** What the workspace's agents cost since `since`, broken down. Members only. */
797 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
798 /**
799 * The model tokens the workspace's runs used, day by day over the last
800 * `days` (42, at most 366), for everyone or for one `person`. Members
801 * only; a member may ask only for themselves, an owner for anyone.
802 */
803 tokenUsage(workspace: string, viewer: User, options?: { person?: string; days?: number }): Promise<Result<TokenUsage>>;
804 /**
805 * What one model answer used, added to its run's count for the day. The
806 * model proxy sends it; for usage views only, as runs are priced from AI
807 * Gateway. False when there was nothing to count.
808 */
809 recordTokens(usage: {
810 workspace: string;
811 /** The model session's id, one per run. */
812 session: string;
813 /** The person the run is for, by username. */
814 person?: string | null;
815 model: string;
816 tier?: "small" | "large" | null;
817 input: number;
818 output: number;
819 cacheRead: number;
820 cacheWrite: number;
821 }): Promise<Result<boolean>>;
822 /**
823 * Prepays usage ($25 at least) and returns the page to send the person to:
824 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
825 * The payment's id comes back to `returnUrl` as `session`.
826 */
827 checkout(
828 actor: User,
829 workspace: string,
830 amountCents: number,
831 returnUrl: string,
832 method?: "card" | "bank_transfer",
833 ): Promise<Result<{ url: string }>>;
834 /**
835 * Stripe's hosted billing page for the workspace: card, invoices, billing
836 * email and address. g1t never handles card numbers. Owners only.
837 */
838 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
839 /** Credits a payment once the processor says it was made. Safe to repeat. */
840 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
841 /**
842 * Whether a workspace may start an agent now, asked before anything is
843 * opened for it. A failure, with the reason to show, when it has no credit.
844 */
845 canStart(workspace: string): Promise<Result<boolean>>;
846 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
847 trial(workspace: string, exempt: string[]): Promise<Trial>;
848 /**
849 * Asks whether a workspace may start an agent and opens the run it will be
850 * charged for. Null when billing is off; a failure when there is no credit.
851 */
852 /** Every paid feature and the workspace's plan for each. Members only. */
853 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
854 /**
855 * Starts the card page for a feature's monthly plan. Owners only. The
856 * page's id comes back to `returnUrl` as `session`.
857 */
858 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
859 /** Turns the feature on once the plan is paid for. Safe to repeat. */
860 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
861 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
862 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
863 /** Whether a feature works for a workspace now; a failure with the reason when not. */
864 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
865 /**
866 * Usage past a plan's allowance, charged from credit at cost plus the
867 * margin, once per `reference`. False if it was charged before.
868 */
869 chargeFeature(charge: {
870 workspace: string;
871 feature: Feature;
872 costMicros: number;
873 description: string;
874 repo?: string | null;
875 reference: string;
876 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
877 buildSeconds?: number | null;
878 }): Promise<Result<boolean>>;
879 /**
880 * What a source cost g1t so far this month, so the workspace's limit
881 * counts it now. Replaces the last report. Billing charges `context`
882 * and `security` itself once the month is over; `deployments` charges
883 * its own.
884 */
885 notePending(
886 workspace: string,
887 source: "deployments" | "domains" | "context" | "security",
888 costMicros: number,
889 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
890 detail?: string | null,
891 ): Promise<boolean>;
892 /**
893 * This month's usage, one line per kind of meter, at what it is charged
894 * before the plan's included usage or a pool paid for it. Members only.
895 */
896 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
897 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
898 entitlements(workspace: string): Promise<Entitlements>;
899 /**
900 * Holds a start's estimated cost before the work starts. A failure's code says why not:
901 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
902 */
903 reserve(reservation: {
904 workspace: string;
905 repo: RepoPath;
906 public: boolean;
907 kind: ComputeKind;
908 /** The most the work is expected to cost g1t, before the margin. */
909 estimateMicros: number;
910 }): Promise<Result<ReservationHeld>>;
911 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
912 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
913 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
914 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
915 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
916 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
917 /** An owner asks for a higher limit, or for help with usage past what was meant. */
918 requestLimit(
919 actor: User,
920 workspace: string,
921 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
922 ): Promise<Result<LimitRequest>>;
923 /** The workspace's requests and their answers, newest first. Members only. */
924 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
925 /**
926 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
927 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
928 */
929 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
930 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
931 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
932 /** Every metered price and the recent changes. Public. */
933 prices(): Promise<PriceBook>;
934 /** A workspace's limit, for its members. */
935 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
936 /** The same, for the services that enforce it. */
937 checkLimit(workspace: string): Promise<Result<Limit>>;
938 /**
939 * The owners' own monthly limit, up to what is available; null goes back
940 * to the default, and `useFullLimit` uses everything available. Owners only.
941 */
942 setSpendLimit(
943 actor: User,
944 workspace: string,
945 spendLimitMicros: number | null,
946 useFullLimit?: boolean,
947 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
948 raiseOnce?: boolean,
949 ): Promise<Result<Limit>>;
950 /** The workspace's invoices from g1t, newest first. Members only. */
951 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
952 /**
953 * How long a sandbox ran for a workspace, reported when it stops. Its
954 * cost is recorded and every second is charged, from the first. False if
955 * `reference` was recorded before.
956 */
957 recordSandbox(usage: {
958 workspace: string;
959 seconds: number;
960 description: string;
961 repo?: string | null;
962 reference: string;
963 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
964 kind?: ComputeKind | null;
965 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
966 cpuSeconds?: number | null;
967 /** The reservation it started under, settled with this cost. */
968 reservationId?: string | null;
969 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
970 selfHosted?: boolean;
971 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
972 instance?: string | null;
973 }): Promise<Result<boolean>>;
974 startRun(run: {
975 workspace: string;
976 repo: RepoPath;
977 number: number;
978 task: string;
979 model: string;
980 /** `workspace` when the run uses the workspace's own model provider. */
981 billedTo?: "g1t" | "workspace";
982 /** The model session's id, so the run can be settled at AI Gateway's price. */
983 session?: string | null;
984 /** `small` or `large`: the tier g1t routed the run to, on its hosted models. */
985 tier?: "small" | "large" | null;
986 }): Promise<Result<RunTicket | null>>;
987}
988
989
990/** One slice of usage: what it was for, what it cost, how many runs. */
991export type UsageSlice = { key: string; micros: number; runs: number };
992
993/** The model tokens runs used over a window of days. */
994export type TokenUsage = {
995 /** `YYYY-MM-DD`, the first day counted. */
996 since: string;
997 /** The window's length: 42 unless asked, 366 at most. */
998 days: number;
999 /** Null for the whole workspace. */
1000 person: string | null;
1001 totalTokens: number;
1002 inputTokens: number;
1003 outputTokens: number;
1004 cacheReadTokens: number;
1005 cacheWriteTokens: number;
1006 /** What those runs were charged, as `usage` measures it. */
1007 costMicros: number;
1008 /** Days in the window with any tokens. */
1009 activeDays: number;
1010 /** Every day in the window, oldest first, zeros included. */
1011 byDay: { day: string; tokens: number }[];
1012};
1013
1014/** What a workspace's agents cost over a period. */
1015export type Usage = {
1016 since: string;
1017 /** Charged, including g1t's margin. */
1018 spentMicros: number;
1019 /** 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. */
1020 coveredMicros?: number;
1021 /** What g1t's model provider charged, before the margin. */
1022 costMicros: number;
1023 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
1024 providerMicros: number;
1025 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
1026 usedMicros: number;
1027 /** g1t charges nothing for now; the slices then measure usage at cost. */
1028 free: boolean;
1029 runs: number;
1030 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
1031 byDay: UsageSlice[];
1032 byTask: UsageSlice[];
1033 byRepo: UsageSlice[];
1034 /** Keyed `namespace/name#number`. */
1035 byPull: UsageSlice[];
1036 byModel: UsageSlice[];
1037 /** Credit bought in the period. */
1038 addedMicros: number;
1039};
1040
1041/** One of g1t's products (a "bucket") on one day. Money in micros. */
1042export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
1043
1044/** One product over the range: what customers were charged at price against what it cost. */
1045export type ProductMargin = {
1046 bucket: string;
1047 title: string;
1048 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
1049 costMicros: number;
1050 cfCostMicros: number;
1051 ownCostMicros: number;
1052 valueMicros: number;
1053 marginMicros: number;
1054 marginPercent: number | null;
1055 costSource: "cloudflare" | "ledger" | string;
1056 /** Running g1t, paid for by the plan. */
1057 overhead: boolean;
1058};
1059
1060/** All of g1t: money in (usage and the plan) against every cost. */
1061export type OverallMargin = {
1062 usageMicros: number;
1063 plansMicros: number;
1064 costMicros: number;
1065 marginMicros: number;
1066 marginPercent: number | null;
1067 /** Of costMicros, what went on usage g1t gave away on purpose: comped workspaces, free periods, the trial and the open-source pool. */
1068 givenMicros?: number;
1069 /** Money in against costMicros - givenMicros. */
1070 soldMarginMicros?: number;
1071 soldMarginPercent?: number | null;
1072 /** Usage sold: usageMicros against what that usage cost, less what was given. */
1073 usageCostMicros?: number;
1074 usageMarginMicros?: number;
1075 usageMarginPercent?: number | null;
1076 /** Running g1t: plansMicros against the platform's cost, less its given share. */
1077 runningCostMicros?: number;
1078 /** Cost no mapping names, less its given share. */
1079 unmappedCostMicros?: number;
1080 /** givenMicros by why. Free is free periods, free allowances and overruns g1t covered. */
1081 givenCompedMicros?: number;
1082 givenFreeMicros?: number;
1083 givenTrialMicros?: number;
1084 givenPoolMicros?: number;
1085 /** costMicros by who g1t pays: Cloudflare's bill (billed, after included allowances) and model providers (tokens, not on Cloudflare's bill). */
1086 /** What the plan's included usage paid for, at price: money in for usage, paid out of plansMicros. */
1087 includedMicros?: number;
1088 cloudflareCostMicros?: number;
1089 modelsCostMicros?: number;
1090};
1091
1092/** A count, cost or leak that does not add up. */
1093export type CostDrift = {
1094 bucket: string;
1095 title: string;
1096 kind: "count" | "cost" | "leak" | string;
1097 ours: number;
1098 cloudflare: number;
1099 deltaPercent: number | null;
1100 detail: string;
1101 foundAt: string;
1102};
1103
1104export type MarginAlert = {
1105 id: string;
1106 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1107 /** The product, or the workspace. */
1108 subject: string;
1109 detail: string;
1110 since: string;
1111 openedAt: string;
1112 emailedAt: string | null;
1113};
1114
1115/** A change to a price, measured from what Cloudflare charged. */
1116export type PriceProposal = {
1117 id: string;
1118 meter: string;
1119 title: string;
1120 unit: string;
1121 currentCostMicros: number;
1122 proposedCostMicros: number;
1123 changePercent: number;
1124 markupPercent: number;
1125 reason: string;
1126 source: "keeper" | "reconciler" | string;
1127 /** Far off the current cost: look before approving. */
1128 suspect: boolean;
1129 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1130 createdAt: string;
1131 decidedAt: string | null;
1132 decidedBy: string | null;
1133 note: string | null;
1134 effectiveAt: string | null;
1135};
1136
1137/** One version of one meter's price; never changed once written. */
1138export type PriceVersion = {
1139 id: string;
1140 meter: string;
1141 version: number;
1142 costMicros: number;
1143 markupPercent: number;
1144 priceMicros: number;
1145 effectiveAt: string;
1146 reason: string;
1147 createdBy: string;
1148 appliedAt: string | null;
1149};
1150
1151/** What `resetBilling` removed. */
1152export type BillingReset = { workspace: string; rows: number };
1153
1154export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; givenMicros?: number; internal: boolean };
1155
1156export type CostLineSummary = {
1157 product: string;
1158 meter: string;
1159 rawName: string;
1160 unit: string;
1161 source: string;
1162 quantity: number;
1163 costMicros: number;
1164 /** Absent when no mapping claims it. */
1165 bucket: string | null;
1166};
1167
1168export type CostMapping = {
1169 product: string;
1170 meter: string;
1171 bucket: string;
1172 priceMeter: string | null;
1173 ownMeter: string | null;
1174 scaleToOwn: boolean;
1175 driftPercent: number;
1176 note: string;
1177 updatedAt: string;
1178 updatedBy: string;
1179};
1180
1181export type CostMappingInput = {
1182 product: string;
1183 meter: string;
1184 bucket?: string;
1185 priceMeter?: string | null;
1186 ownMeter?: string | null;
1187 scaleToOwn?: boolean;
1188 driftPercent?: number | null;
1189 note?: string;
1190 remove?: boolean;
1191};
1192
1193export type CostSettings = {
1194 autoApply: boolean;
1195 autoApplyPercent: number;
1196 noticeDays: number;
1197 marginFloorPercent: number;
1198 alertDays: number;
1199 minDailyCostMicros: number;
1200 anomalyFactor: number;
1201 anomalyFloorMicros: number;
1202};
1203
1204export type CostsReport = {
1205 configured: boolean;
1206 fetchedAt: string | null;
1207 since: string;
1208 until: string;
1209 days: CostDay[];
1210 products: ProductMargin[];
1211 overall: OverallMargin;
1212 drift: CostDrift[];
1213 alerts: MarginAlert[];
1214 proposals: PriceProposal[];
1215 versions: PriceVersion[];
1216 topWorkspaces: WorkspaceCost[];
1217 lines: CostLineSummary[];
1218 mappings: CostMapping[];
1219 settings: CostSettings;
1220 /** g1t's own spend against its two caps. */
1221 caps: SpendCaps;
1222};
1223
1224/** What g1t pays for itself, at cost, against its caps (billing's `budget`). */
1225export type SpendCaps = {
1226 /** Today (UTC), YYYY-MM-DD, and this month, YYYY-MM. */
1227 day: string;
1228 month: string;
1229 /** What g1t paid for itself today across every workspace. */
1230 todayMicros: number;
1231 /** `PLATFORM_DAILY_SPEND_CAP_MICROS`; 0: no breaker. */
1232 dailyCapMicros: number;
1233 /** New hosted-model agent runs g1t would pay for are paused. */
1234 tripped: boolean;
1235 trippedAt: string | null;
1236 liftedBy: string | null;
1237 liftedAt: string | null;
1238 liftNote: string | null;
1239 /** This month so far, by what paid: comped, trial, oss, given, unpaid. */
1240 monthBuckets: { bucket: string; title: string; micros: number }[];
1241 comped: CompedBudget[];
1242 /** Free workspaces' share of reconciled costs this month (git, storage, platform). */
1243 freeTierMicros: number;
1244 /** `CLOUDFLARE_FIXED_MONTHLY_MICROS`: Cloudflare subscriptions, an estimate. */
1245 fixedMonthlyMicros: number;
1246 /** Money in this month, through the last reconciled day. */
1247 revenueMicros: number;
1248};
1249
1250/** A comped account's monthly budget, at cost. */
1251export type CompedBudget = {
1252 account: string;
1253 name: string;
1254 usedMicros: number;
1255 /** 0: no budget. */
1256 ceilingMicros: number;
1257 /** `COMPED_MONTHLY_CEILING_MICROS`, not the account's own limit. */
1258 defaultCeiling: boolean;
1259 /** 50, 75, 90, 100, or 0. */
1260 level: number;
1261};
1262
1263export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };