# fleetlayer-spend

This month's spend for each cloud and AI account, and where the month is heading, tagged by what the account is for
(`agents`, `ci`, `production`, `dev`...). The dashboard's Usage page shows it below the subscriptions' usage,
grouped and filtered by tag, against a budget per tag, and only to people allowed to see money.

It's a node plugin that ships with Fleetlayer as `fleetlayer-spend`. It reads:

| Provider | How | Key |
|---|---|---|
| `aws` | Cost Explorer: the month so far and AWS's own forecast, every 6 hours ($0.01 a request) | An IAM user whose only policy allows `ce:GetCostAndUsage` and `ce:GetCostForecast` |
| `digitalocean` | `/v2/customers/my/balance` (`month_to_date_usage`) | A token with only the `billing:read` scope |
| `openai` | `/v1/organization/costs`, the API platform's costs | An organisation admin key |
| `anthropic` | `/v1/organizations/cost_report`, the Console organisation's costs | An Admin API key (`sk-ant-admin01-…`); it can't be limited to reading costs |
| `hetzner-cloud` | Worked out: each server's hourly price times the hours it ran, capped at its monthly price (Hetzner has no cost API). Not counted: backups, volumes, IPs, load balancers, snapshots, traffic, servers deleted during the month | A Read token, one per project |
| `fixed` | A monthly amount you name, for what has no API | none |

Some bills have no API at all: Claude Pro/Max extra usage, ChatGPT subscriptions, Render, Hetzner dedicated servers
(Robot). Give them as `fixed` accounts. Where a provider gives no forecast, the month so far is scaled up to the
whole month once three days have passed.

## Setup

Run it under a Unix user of its own (`billing`), with its own node: its keys read bills, and its readings are money.
Let only the admins read that node in the access policy:

```yaml
allow:
  - who: role:admin
    can: [read]
    to: ["-@billing"]
```

Deliver each key with the [1Password plugin](https://fleetlayer.ai/docs/plugins/1password.md) as an env file only this user can read (mode 0600; a file
others can read is refused), and add the plugin in `node.yaml`:

```yaml
plugins:
  - name: spend
    command: fleetlayer-spend
    grants: [reading.publish]
    config:                     # optional
      settings: ~/.config/fleetlayer/spend.yaml
      state_dir: ~/.local/state/fleetlayer/spend   # when each account was last read
```

The accounts and budgets, in `~/.config/fleetlayer/spend.yaml` (read again every minute). One cloud account per
purpose keeps billing clean, so each account is a few lines:

```yaml
accounts:
  - name: aws-prod
    provider: aws
    label: Production
    tags: [production]
    credentials: ~/.config/fleetlayer/secrets/aws-prod.env   # AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  - name: do-ci
    provider: digitalocean
    tags: [ci]
    credentials: ~/.config/fleetlayer/secrets/do.env          # DIGITALOCEAN_TOKEN
  - name: openai
    provider: openai
    tags: [agents]
    credentials: ~/.config/fleetlayer/secrets/openai.env      # OPENAI_ADMIN_KEY
  - name: hetzner-builds
    provider: hetzner-cloud
    tags: [ci, agents]          # a blend at the top level: it counts in each
    credentials: ~/.config/fleetlayer/secrets/hcloud.env      # HCLOUD_TOKEN
  - name: chatgpt-pro
    provider: fixed
    label: ChatGPT Pro
    tags: [agents]
    monthly: 200
    currency: USD
budgets:
  - { tag: ci, monthly: 300, currency: EUR }
  - { tag: agents, monthly: 1500, currency: USD }
```

Each account takes `name` (letters, digits, `-`, `_`), `provider`, `tags`, `credentials` (or, for `fixed`, `monthly`
and `currency`), and optionally `label`, `category` (`ai`, `machines` or `other`; the provider's by default), `budget`
(the account's own), `every` (how often to ask: `30m`, `6h`, `1d`) and, for AWS, `aws_account` (one linked account of
an organisation). The variables each provider's credentials file needs: `AWS_ACCESS_KEY_ID` and
`AWS_SECRET_ACCESS_KEY`, `DIGITALOCEAN_TOKEN`, `OPENAI_ADMIN_KEY`, `ANTHROPIC_ADMIN_KEY`, `HCLOUD_TOKEN`.

Check the file with `fleetlayer-spend check` (it also says whether each key file is there and complete), and try one
account with `fleetlayer-spend probe <name>`.

## What it publishes

`spend.month`, one per account, keyed `<provider>/<name>`: `{provider, account, label, category, tags, currency,
spent, forecast, budget?, source, periodStart, periodEnd, every}`, where `source` is `api`, `estimate` or `fixed`.
It's published when the account is read and again every hour, with the time it was read. `spend.index`, keyed
`index`: `{accounts: [keys], budgets: [{tag, monthly, currency}]}`, the accounts and budgets in the settings now, on
change and hourly: readings are never deleted, so the dashboard counts only the accounts the newest index lists, and
only figures for the current month. Sums only: never invoices, card details or keys.

Keys go only to their own provider, over HTTPS, and never follow a redirect. When a provider refuses, the status says
its HTTP status and short error code only: a provider's whole answer (which can quote part of a key or name an
account) goes to the plugin's local log at debug level, never into readings or the status. When each account was
last read is kept in its state directory, so a restart doesn't ask every account again at once (each AWS Cost
Explorer request costs money), and a failing account is asked again only on its interval, also across a new month.

## Monitoring

It reports its status every minute: a problem when its settings can't be read or aren't there, or an account has
failed three times in a row or had no good read for twice its interval and an hour (a refused key, a missing
credentials file, a provider that's down), naming the account and the short reason. The detail
holds each account's last good read. That shows on its node's status, the dashboard, and wherever node problems alert.

## Moving it

Its state is its settings file and state directory; `fleetlayer move` carries both. The credentials files are delivered again by the
1Password plugin on the new machine.
