Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@
"account:usage": {
"description": "Report organization contract usage, credits, and projections."
},
"account:spending-cap": {
"description": "Show and manage the overage spending cap."
},
"alert-channels": {
"description": "List and inspect alert channels in your Checkly account."
},
Expand Down
6 changes: 5 additions & 1 deletion packages/cli/src/ai-context/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ export const MANAGE_REFERENCES = [
id: 'manage-account-members',
description: 'List account members and pending invites (`members`), update member roles, and delete members',
},
{
id: 'manage-spending-cap',
description: 'Show, set, and remove the overage spending cap (`account spending-cap`)',
},
] as const

export const SKILL = {
Expand Down Expand Up @@ -125,7 +129,7 @@ export const ACTIONS = [
},
{
id: 'manage',
description: 'Understand your account plan, entitlements, feature limits, members, and pending invites.',
description: 'Understand your account plan, entitlements, feature limits, members, pending invites, and spending cap.',
references: MANAGE_REFERENCES,
},
] as const
Expand Down
39 changes: 39 additions & 0 deletions packages/cli/src/ai-context/references/manage-spending-cap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Spending Cap

Show and manage the account's overage spending cap: the most the account may spend on runs beyond what the plan includes. When overage reaches the cap, checks stop running.

## Usage

```bash
npx checkly account spending-cap # Cap, overage so far, whether checks are stopped
npx checkly account spending-cap --output json # Raw API response (recommended for agents)
npx checkly account spending-cap set 50 # Set or change the cap, in US dollars
npx checkly account spending-cap set 12.50 --dry-run # Preview the change without applying it
npx checkly account spending-cap remove --force # Remove the cap (overage is no longer capped)
```

- `set <dollars>` takes 0 to 10000 with at most 2 decimals. `0` allows no overage at all.
- `set` and `remove` require confirmation. In non-interactive mode, review the confirmation preview and rerun with `--force`. Do not change the cap unless the user asked for it: lowering it to or below the overage so far stops checks at once.
- Plans that cannot hold a cap (e.g. prepaid or contract plans) are rejected.
- Needs a user or service API key; legacy account API keys are rejected (401).

## JSON response shape

```json
{
"spendingCapCents": 3000,
"standing": {
"measuredAt": "2026-11-15T00:00:00.000Z",
"pools": {
"API": { "used": 17230, "included": 100000, "overageRuns": 0, "overageCents": 0 },
"BROWSER": { "used": 14890, "included": 12000, "overageRuns": 2890, "overageCents": 1806.25 }
},
"overageCents": 1806.25,
"limit": { "capCents": 3000, "state": "CLOSE", "closeAtCents": 2400 }
}
}
```

- Amounts are in US cents. `spendingCapCents: null` means no cap.
- `standing: null` means overage is not measured (runs not measured yet, or the plan has no overage). It does not mean $0 overage.
- Checks are stopped when `standing.limit.state` is `REACHED`.
2 changes: 1 addition & 1 deletion packages/cli/src/ai-context/references/manage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Account Management

Understand your account's plan, entitlements, limits, members, and pending invites.
Understand your account's plan, entitlements, limits, members, pending invites, and overage spending cap.

## Plan-aware workflow

Expand Down
119 changes: 119 additions & 0 deletions packages/cli/src/commands/__tests__/account-spending-cap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../../helpers/cli-mode', () => ({
detectCliMode: vi.fn(() => 'agent'),
}))

vi.mock('../../rest/api', () => ({
spendingCap: { get: vi.fn(), update: vi.fn() },
}))

import * as api from '../../rest/api.js'
import { ConflictError } from '../../rest/errors.js'
import { InvalidInputError } from '../../helpers/invalid-input-error.js'
import { stripAnsi } from '../../formatters/render.js'
import type { SpendingCap } from '../../rest/spending-cap.js'
import AccountSpendingCap from '../account/spending-cap.js'
import AccountSpendingCapSet from '../account/spending-cap/set.js'
import AccountSpendingCapRemove from '../account/spending-cap/remove.js'
import { createCommandContext } from './helpers/command-context.js'

const current: SpendingCap = {
spendingCapCents: 5000,
standing: {
measuredAt: '2099-11-15T00:00:00.000Z',
pools: { BROWSER: { used: 14890, included: 12000, overageRuns: 2890, overageCents: 1806.25 } },
overageCents: 1806.25,
limit: { capCents: 5000, state: 'UNDER', closeAtCents: 4000 },
},
}

const mutationFlags = { 'output': 'detail', 'force': false, 'dry-run': false }

function context (Command: any, parsed: Record<string, unknown>) {
return createCommandContext({ command: Command, parsed })
}

beforeEach(() => {
vi.clearAllMocks()
process.exitCode = undefined
vi.mocked(api.spendingCap.get).mockResolvedValue({ data: current } as any)
vi.mocked(api.spendingCap.update).mockImplementation(cap =>
Promise.resolve({ data: { spendingCapCents: cap } } as any))
})

describe('account spending-cap', () => {
it('prints the API response as is for --output json', async () => {
const ctx = context(AccountSpendingCap, { flags: { output: 'json' } })
await AccountSpendingCap.prototype.run.call(ctx as any)
expect(JSON.parse(ctx.logged[0])).toEqual(current)
})

it('renders the terminal view', async () => {
const ctx = context(AccountSpendingCap, { flags: { output: 'detail' } })
await AccountSpendingCap.prototype.run.call(ctx as any)
expect(stripAnsi(ctx.logged[0])).toMatch(/Spending cap:\s+\$50\.00/)
})

it('maps a 409 to a clear error and exits 1', async () => {
vi.mocked(api.spendingCap.get).mockRejectedValue(
new ConflictError({ statusCode: 409, error: 'Conflict', message: 'PREPAID' }))
const ctx = context(AccountSpendingCap, { flags: { output: 'detail' } })
await AccountSpendingCap.prototype.run.call(ctx as any)
expect(ctx.style.longError).toHaveBeenCalledWith('Failed to load the spending cap.',
expect.stringMatching(/plan cannot have a spending cap/))
expect(process.exitCode).toBe(1)
})
})

describe('account spending-cap set', () => {
it('rejects invalid amounts before calling the API', async () => {
const ctx = context(AccountSpendingCapSet, { args: { dollars: '10000.01' }, flags: mutationFlags })
await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow(InvalidInputError)
expect(api.spendingCap.get).not.toHaveBeenCalled()
})

it('asks for confirmation in agent mode, previewing the change and the warning', async () => {
const ctx = context(AccountSpendingCapSet, { args: { dollars: '12.50' }, flags: mutationFlags })
await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3')
const preview = JSON.parse(ctx.logged[0])
expect(preview).toMatchObject({ status: 'confirmation_required', command: 'account spending-cap set' })
expect(preview.changes[0]).toBe('Change the spending cap from $50.00 to $12.50')
expect(preview.changes[1]).toMatch(/stop running at once/)
expect(preview.confirmCommand).toBe('npx checkly account spending-cap set 12.50 --force')
expect(api.spendingCap.update).not.toHaveBeenCalled()
})

it('--dry-run previews and exits 0', async () => {
const ctx = context(AccountSpendingCapSet, {
args: { dollars: '20' }, flags: { ...mutationFlags, 'dry-run': true },
})
await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_0')
expect(JSON.parse(ctx.logged[0]).status).toBe('dry_run')
expect(api.spendingCap.update).not.toHaveBeenCalled()
})

it('sends integer cents with --force and prints the response for --output json', async () => {
const ctx = context(AccountSpendingCapSet, {
args: { dollars: '0.29' }, flags: { ...mutationFlags, output: 'json', force: true },
})
await AccountSpendingCapSet.prototype.run.call(ctx as any)
expect(api.spendingCap.update).toHaveBeenCalledExactlyOnceWith(29)
expect(JSON.parse(ctx.logged[0])).toEqual({ spendingCapCents: 29 })
})
})

describe('account spending-cap remove', () => {
it('sends null with --force', async () => {
const ctx = context(AccountSpendingCapRemove, { flags: { ...mutationFlags, force: true } })
await AccountSpendingCapRemove.prototype.run.call(ctx as any)
expect(api.spendingCap.update).toHaveBeenCalledExactlyOnceWith(null)
expect(ctx.style.shortSuccess).toHaveBeenCalledWith('Spending cap removed. Overage is no longer capped.')
})

it('previews removing the current cap', async () => {
const ctx = context(AccountSpendingCapRemove, { flags: mutationFlags })
await expect(AccountSpendingCapRemove.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3')
expect(JSON.parse(ctx.logged[0]).changes).toEqual(['Remove the spending cap of $50.00'])
})
})
6 changes: 6 additions & 0 deletions packages/cli/src/commands/__tests__/command-metadata.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ import UsageTermCommand from '../account/usage/term.js'
import UsageProjectionsCommand from '../account/usage/projections.js'
import UsageSummaryCommand from '../account/usage/summary.js'
import UsageSeriesCommand from '../account/usage/series.js'
import AccountSpendingCap from '../account/spending-cap.js'
import AccountSpendingCapSet from '../account/spending-cap/set.js'
import AccountSpendingCapRemove from '../account/spending-cap/remove.js'

const commands: Array<[string, typeof BaseCommand]> = [
['api', Api],
Expand All @@ -77,6 +80,9 @@ const commands: Array<[string, typeof BaseCommand]> = [
['account usage projections', UsageProjectionsCommand],
['account usage summary', UsageSummaryCommand],
['account usage series', UsageSeriesCommand],
['account spending-cap', AccountSpendingCap],
['account spending-cap set', AccountSpendingCapSet],
['account spending-cap remove', AccountSpendingCapRemove],
['incidents list', IncidentsList],
['incidents create', IncidentsCreate],
['incidents update', IncidentsUpdate],
Expand Down
36 changes: 36 additions & 0 deletions packages/cli/src/commands/account/spending-cap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { AuthCommand } from '../authCommand.js'
import { outputFlag } from '../../helpers/flags.js'
import { exitCodeFor } from '../../helpers/invalid-input-error.js'
import { describeSpendingCapError } from '../../helpers/spending-cap.js'
import * as api from '../../rest/api.js'
import type { OutputFormat } from '../../formatters/render.js'
import { formatSpendingCap } from '../../formatters/spending-cap.js'

export default class AccountSpendingCap extends AuthCommand {
static hidden = false
static readOnly = true
static destructive = false
static idempotent = true
static description = 'Show the overage spending cap, the overage spent so far, and whether checks are stopped.'

static flags = {
output: outputFlag({ default: 'detail' }),
}

async run (): Promise<void> {
const { flags } = await this.parse(AccountSpendingCap)
this.style.outputFormat = flags.output
try {
const { data } = await api.spendingCap.get()
if (flags.output === 'json') {
this.log(JSON.stringify(data, null, 2))
return
}
const fmt: OutputFormat = flags.output === 'md' ? 'md' : 'terminal'
this.log(formatSpendingCap(data, fmt))
} catch (err: unknown) {
this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read'))
process.exitCode = exitCodeFor(err)
}
}
}
57 changes: 57 additions & 0 deletions packages/cli/src/commands/account/spending-cap/remove.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { AuthCommand } from '../../authCommand.js'
import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js'
import { exitCodeFor } from '../../../helpers/invalid-input-error.js'
import { describeSpendingCapError, spendingCapChanges } from '../../../helpers/spending-cap.js'
import * as api from '../../../rest/api.js'

export default class AccountSpendingCapRemove extends AuthCommand {
static hidden = false
static readOnly = false
static destructive = true
static idempotent = true
static description = 'Remove the overage spending cap, so overage is no longer capped.'

static flags = {
'output': outputFlag({ default: 'detail' }),
'force': forceFlag(),
'dry-run': dryRunFlag(),
}

async run (): Promise<void> {
const { flags } = await this.parse(AccountSpendingCapRemove)
this.style.outputFormat = flags.output

let current
try {
({ data: current } = await api.spendingCap.get())
} catch (err: unknown) {
this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read'))
process.exitCode = exitCodeFor(err)
return
}

await this.confirmOrAbort({
command: 'account spending-cap remove',
description: 'Remove the spending cap',
changes: spendingCapChanges(current, null),
flags,
classification: {
readOnly: AccountSpendingCapRemove.readOnly,
destructive: AccountSpendingCapRemove.destructive,
idempotent: AccountSpendingCapRemove.idempotent,
},
}, { force: flags.force, dryRun: flags['dry-run'] })

try {
const { data } = await api.spendingCap.update(null)
if (flags.output === 'json') {
this.log(JSON.stringify(data, null, 2))
return
}
this.style.shortSuccess('Spending cap removed. Overage is no longer capped.')
} catch (err: unknown) {
this.style.longError('Failed to remove the spending cap.', describeSpendingCapError(err, 'billing:update'))
process.exitCode = exitCodeFor(err)
}
}
}
73 changes: 73 additions & 0 deletions packages/cli/src/commands/account/spending-cap/set.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Args } from '@oclif/core'
import { AuthCommand } from '../../authCommand.js'
import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js'
import { exitCodeFor } from '../../../helpers/invalid-input-error.js'
import {
describeSpendingCapError,
MAX_SPENDING_CAP_DOLLARS,
parseDollarsToCents,
spendingCapChanges,
} from '../../../helpers/spending-cap.js'
import * as api from '../../../rest/api.js'
import { formatDollars } from '../../../formatters/spending-cap.js'

export default class AccountSpendingCapSet extends AuthCommand {
static hidden = false
static readOnly = false
static destructive = false
static idempotent = true
static description = 'Set or change the overage spending cap. Checks stop running once overage reaches it.'

static args = {
dollars: Args.string({
required: true,
description: `The cap in US dollars, e.g. 50 or 12.50 (0 to ${MAX_SPENDING_CAP_DOLLARS}).`,
}),
}

static flags = {
'output': outputFlag({ default: 'detail' }),
'force': forceFlag(),
'dry-run': dryRunFlag(),
}

async run (): Promise<void> {
const { args, flags } = await this.parse(AccountSpendingCapSet)
this.style.outputFormat = flags.output
const capCents = parseDollarsToCents(args.dollars)

let current
try {
({ data: current } = await api.spendingCap.get())
} catch (err: unknown) {
this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read'))
process.exitCode = exitCodeFor(err)
return
}

await this.confirmOrAbort({
command: 'account spending-cap set',
description: 'Set the spending cap',
changes: spendingCapChanges(current, capCents),
flags,
args: { dollars: args.dollars },
classification: {
readOnly: AccountSpendingCapSet.readOnly,
destructive: AccountSpendingCapSet.destructive,
idempotent: AccountSpendingCapSet.idempotent,
},
}, { force: flags.force, dryRun: flags['dry-run'] })

try {
const { data } = await api.spendingCap.update(capCents)
if (flags.output === 'json') {
this.log(JSON.stringify(data, null, 2))
return
}
this.style.shortSuccess(`Spending cap set to ${formatDollars(data.spendingCapCents ?? capCents)}.`)
} catch (err: unknown) {
this.style.longError('Failed to set the spending cap.', describeSpendingCapError(err, 'billing:update'))
process.exitCode = exitCodeFor(err)
}
}
}
Loading