# usage

> Spend: `noclick.usage(group_by="user")`, `noclick.Usage.series(group_by="agent")`, `noclick.Usage.limits()`, `noclick.Usage.set_account_cap(50)`, the account's ledger: `noclick.Usage.ledger()`, `noclick.Usage.charges()`, `noclick.Usage.billing()`, and the workstreams it's counted under (`noclick.Workstream`).

## usage

```typescript
function usage(options?: UsageOptions): Promise<Usage>
```

Spend for `period` (default `month`), optionally split `groupBy` user, key, agent, `project` (each
app), `person` (who each charge was for: the person whose message, click or key started the work; the
account's owner for work nobody else started) or `workstream` (the line of work it belongs to, as the agent that
started it named it; the `null` one is work nobody named one for), and narrowed to one `agent`. Needs the `usage`
scope. Without `groupBy`, `groups` is empty.

    const month = await usage({ groupBy: "user" });
    console.log(month.totalUsd, month.groups);

    for (const person of (await usage({ groupBy: "person" })).groups) console.log(person.name, person.usd);

    for (const line of (await usage({ groupBy: "workstream" })).groups) console.log(line.name ?? "(unnamed)", line.usd);

Parameters:

- `options.groupBy` (`"user" | "key" | "agent" | "project" | "person" | "workstream"`)
- `options.agent` (`string | ApiObject`)
- `options.user` (`UserOption`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.period` (`string`)

Returns: The period's `total_usd` and, with `group_by`, one group per user, key, agent, app, person or
workstream that spent, largest first; a person's or workstream's group has its `name` (the `None`
workstream is work nobody named one for). Without `group_by`, `groups` is empty.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

## Usage

```typescript
class Usage
```

What the account (or the current user) spent in `period`.

| Attribute | Type | Description |
| --- | --- | --- |
| `period` | `string` |  |
| `totalUsd` | `number` |  |
| `groups` | `UsageGroup[]` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Usage.get

```typescript
get(id: string | null): UsageGroup | null
```

The group of an id that spent something in a grouped usage, else null.

Parameters:

- `id` (`string | null`, required)

Returns: The `UsageGroup`, or `default` when the id spent nothing in the period.

### Usage.series

```typescript
static series(options?: UsageSeriesOptions): Promise<UsageSeries>
```

Daily spend between `from` and `to`, one line per key, user, agent, app, person, workstream or usage type.

Parameters:

- `options.from` (`Date | string`): Default: the current month (at most 92 days).
- `options.to` (`Date | string`)
- `options.interval` (`"day"`)
- `options.groupBy` (`"key" | "user" | "agent" | "type" | "project" | "person" | "workstream"`): `project`: one line per app; `person`: one per person each charge was for; `workstream`: one per workstream.
- `options.key` (`string`): A key id or prefix.
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The lines, largest first, each with its `label`, `total_usd` and daily `points`.
A day with no spend has no point.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Usage.ledger

```typescript
static ledger(options?: { tz?: string; client?: NoClick }): Promise<UsageLedger>
```

The account's ledger, as Settings → Usage reads it: every charge it was billed in its billing period and the
one before (its automations' runs, its chat with NoClick, a teammate's work it pays for, its keys' and agents'
calls), grouped by day in `tz` and by every field a breakdown splits by, with names for what they were for.
For the signed-in owner and the account's own secret keys. `usage()` reads only what its keys and agents spent.

    const ledger = await Usage.ledger({ tz: "Europe/London" });
    const thisPeriod = ledger.groups.filter((g) => g.current && !g.ownResource);
    console.log(thisPeriod.reduce((sum, g) => sum + g.usd, 0));

Parameters:

- `options.tz` (`string`)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The period, the fields groups are split by, the groups (each with its `key`, `day`, `usd` and
`fields`) and the `directory` naming what they name.

### Usage.charges

```typescript
static charges(options?: UsageChargesOptions): Promise<UsageCharges>
```

A page of the ledger's charges, newest first, narrowed to groups (`keys`) or a day; the billing period's by
default. Pass `next` back as `cursor` for the page after it.

    const ledger = await Usage.ledger();
    const calls = ledger.groups.filter((g) => g.current && g.subtype === "voice/call").map((g) => g.key);
    let page = await Usage.charges({ keys: calls });
    while (page.next) page = await Usage.charges({ keys: calls, cursor: page.next });

Parameters:

- `options.from` (`Date | string`): Default: the billing period's start.
- `options.to` (`Date | string`): Default: the billing period's end.
- `options.keys` (`string[]`): Only charges in these groups (`LedgerGroup.key`).
- `options.day` (`string`): Only charges on this day (`YYYY-MM-DD`) in `tz`.
- `options.tz` (`string`): The IANA time zone the ledger was read in.
- `options.cursor` (`string`): The previous page's `next`.
- `options.limit` (`number`): Charges per page, up to 500 (default 50).
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The charges, the runs they were recorded in, and `next`: pass it as `cursor` for the next page.

### Usage.billing

```typescript
static billing(options?: { client?: NoClick }): Promise<UsageBilling | null>
```

The money behind the ledger, as the credit gate reads it: the plan and its pools, the balance, funds added and
what's scheduled to be charged; null where nobody is billed.

Parameters:

- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The money, or None where nobody is billed.

### Usage.limits

```typescript
static limits(options?: { client?: NoClick }): Promise<UsageLimits>
```

This month's spend of every capped key, user and agent (account principals), of every budgeted app, and your
account's own monthly cap (`account`).

Parameters:

- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Each capped key and user with its `cap` and `spent`, each budgeted agent with its
`budget`, `spent` and `subtree_spent`, each budgeted app (`projects`) with its
`budget` and `spent`, when the caps reset (`resets_at`), and the account's cap
(`account`), over its billing period.

### Usage.setAccountCap

```typescript
static setAccountCap(
  capUsd: number | null,
  options?: { client?: NoClick },
): Promise<AccountCap>
```

Set your account's monthly spending cap, in whole dollars; `null` removes it. Past it, every call that costs
money rejects with `SpendCapExceeded` until the billing period resets. Your account's own keys lower the cap, or
set one where there's none; raising or removing it is your account's owner's (in Settings → Plan and billing in
the NoClick app), so from a key it rejects with `PermissionDenied` and changes nothing. Through MCP, and from an
agent on the word of the person whose message started its turn, a raise or a removal waits for the owner's
approval. Needs the `usage` scope. Resolves to the cap as it stands, with who set it (`setBy`).

    const cap = await Usage.setAccountCap(50);
    console.log(cap.capUsd, cap.spentUsd, cap.resetsAt);

Parameters:

- `capUsd` (`number | null`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The cap as it now stands, with what its billing period has spent and who set it (`set_by`).

### Usage.group

```typescript
group(id: string | null): UsageGroup
```

The spend of one user, key, agent, app or person id in a grouped usage (null is the account's own); an id
that spent nothing reads as $0 with no events.

Parameters:

- `id` (`string | null`, required)

## UsageGroup

```typescript
interface UsageGroup
```

Spend of one user, key, agent, app, person or workstream (`id`) in the period. `name` is a person's
name, with `group_by="person"`, or a workstream's, with `group_by="workstream"`.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string | null` |  |
| `usd` | `number` |  |
| `events` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `name` | `string | null` | A person's name, with `groupBy: "person"`, or a workstream's, with `groupBy: "workstream"`; otherwise null. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsageSeries

```typescript
interface UsageSeries
```

| Attribute | Type | Description |
| --- | --- | --- |
| `interval` | `string` |  |
| `from` | `Date | null` |  |
| `to` | `Date | null` |  |
| `totalUsd` | `number` |  |
| `series` | `UsageSeriesLine[]` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsageSeriesLine

```typescript
interface UsageSeriesLine
```

One key, user, agent, app, person, workstream or usage type's spend over the period.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string | null` |  |
| `label` | `string | null` | A key name (`Console` for the console key), a user's id, an agent name, a person's name, a workstream's name or a type label. |
| `totalUsd` | `number` |  |
| `events` | `number` |  |
| `points` | `UsagePoint[]` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsagePoint

```typescript
interface UsagePoint
```

Spend in one interval starting at `t`.

| Attribute | Type | Description |
| --- | --- | --- |
| `t` | `Date | null` | The start of the interval. |
| `usd` | `number` |  |
| `events` | `number` |  |

## UsageLimits

```typescript
interface UsageLimits
```

Every capped key, user and agent with this month's spend, every app with a budget, and your account's own cap.

| Attribute | Type | Description |
| --- | --- | --- |
| `periodStart` | `Date | null` |  |
| `resetsAt` | `Date | null` |  |
| `keys` | `KeyCap[]` |  |
| `users` | `UserCap[]` |  |
| `agents` | `AgentBudget[]` |  |
| `projects` | `ProjectBudget[]` | Each app with a `budgetUsdPerMonth`. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `account` | `AccountCap | null` | Your account's monthly spending cap, over its billing period. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## KeyCap

```typescript
interface KeyCap
```

A capped key's spend this month.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string | null` |  |
| `cap` | `number | null` |  |
| `spent` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UserCap

```typescript
interface UserCap
```

A capped user's spend this month.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` | Your id for the user. |
| `cap` | `number | null` |  |
| `spent` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## AgentBudget

```typescript
interface AgentBudget
```

A budgeted agent's spend this month; `subtreeSpent` adds the agents it spawned.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string | null` |  |
| `budget` | `number | null` |  |
| `spent` | `number` |  |
| `subtreeSpent` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## ProjectBudget

```typescript
interface ProjectBudget
```

A budgeted app's spend this month; `userId` is the user it belongs to (null: your account's own).

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string | null` |  |
| `userId` | `string | null` |  |
| `budget` | `number | null` |  |
| `spent` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsageLedger

```typescript
interface UsageLedger
```

The account's ledger: every charge it was billed in its billing period and the one before, grouped.

| Attribute | Type | Description |
| --- | --- | --- |
| `periodStart` | `Date | null` |  |
| `periodEnd` | `Date | null` |  |
| `previousStart` | `Date | null` | Where the period before starts. |
| `fields` | `string[]` | The fields each group is split by. |
| `groups` | `LedgerGroup[]` |  |
| `directory` | `Record<string, Record<string, JsonObject>>` | Names for what the groups name, by kind (`workflows`, `agents`, `people`, `projects`, `keys`…) and id. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## LedgerGroup

```typescript
interface LedgerGroup
```

One group of the account's ledger: its charges in one period (this billing period or the one before), one day
and one set of breakdown fields, added up.

| Attribute | Type | Description |
| --- | --- | --- |
| `key` | `string` | The group's key: list its charges with `Usage.charges({ keys: [key] })`. |
| `current` | `boolean` | In this billing period (true) or the one before. |
| `day` | `string` | Its day (`YYYY-MM-DD`) in the zone the ledger was read in. |
| `usageType` | `string` |  |
| `subtype` | `string` | What was charged for: a model's id, or a service like `voice/call` or `apps/hosting`. |
| `unit` | `string` |  |
| `ownResource` | `boolean` | On the account's own key or resource: nobody was charged. |
| `charges` | `number` | How many charges it holds. |
| `quantity` | `number` |  |
| `usd` | `number` |  |
| `fields` | `Record<string, unknown>` | Every breakdown field (`UsageLedger.fields`) by name: the automation, agent step, person, app, key… it names. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsageCharges

```typescript
interface UsageCharges
```

A page of the ledger's charges, newest first.

| Attribute | Type | Description |
| --- | --- | --- |
| `charges` | `LedgerCharge[]` |  |
| `runs` | `Record<string, JsonObject>` | The runs the charges were recorded in, by run id. |
| `next` | `string | null` | Pass as `cursor` for the next page; null at the end. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## LedgerCharge

```typescript
interface LedgerCharge
```

One charge in the account's ledger.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `at` | `Date | null` |  |
| `usageType` | `string` |  |
| `subtype` | `string` |  |
| `unit` | `string` |  |
| `quantity` | `number` |  |
| `usd` | `number` |  |
| `ownResource` | `boolean` |  |
| `key` | `string` | Its group's key. |
| `metadata` | `JsonObject` | What it was for: the automation, agent step and run, the number, sender, key or app it names. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## UsageBilling

```typescript
interface UsageBilling
```

The money behind the ledger, as the credit gate reads it. One of the account's own keys reads the plan, the
balance, funds added and what's scheduled; `autoTopUp` and friends' credit (in `raw`) are the signed-in owner's.

| Attribute | Type | Description |
| --- | --- | --- |
| `plan` | `JsonObject` | The plan, its window and its pools: included usage, Free's daily share, an older plan's top-up. |
| `balanceUsd` | `number` | What was added less what it paid for; below zero is owed. |
| `fundsUsd` | `number` | Funds added this period, and the plan's fee on them. |
| `feesUsd` | `number` |  |
| `recurring` | `JsonObject[]` | Charges that come on a date: a number's month, a connection's hours. |
| `domains` | `JsonObject[]` | Domains that renew soon. |
| `autoTopUp` | `JsonObject | null` | Auto top-up, for the signed-in owner; null otherwise. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## Workstream

```typescript
class Workstream
```

A line of work your spend is counted under. An agent names one when it starts work (a child's task, a message it
hands another agent, an app's coding job; `agent.spawn(task, { workstream })`), from your workstreams or a new
name, and every charge of that work, and of what it starts, belongs to it. A person renames one, or archives it
once its work is done: its charges still read under it, and it leaves the workstreams agents choose from until
it's brought back or an agent names it again.

    for (const workstream of await Workstream.list()) console.log(workstream.name, workstream.spentUsd);
    await Workstream.rename("Menu", "Bakery site");   // merges Menu into Bakery site
    await Workstream.archive("Q3 launch");

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string` | As it was first written; matched whatever its case. |
| `spentUsd` | `number` | What it spent this month (a call acting for one of your users: that user's share). |
| `events` | `number` |  |
| `createdAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `archived` | `boolean` | Put away: out of the workstreams agents choose from, its charges still under it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Workstream.list

```typescript
static list(
  options?: { archived?: boolean; user?: UserOption; client?: NoClick },
): Promise<Workstream[]>
```

Your open workstreams (`archived: true`: the ones put away), most spent this month first, each with what it spent
(as `usage({ groupBy: "workstream" })` counts it). Needs the `usage` scope.

Parameters:

- `options.archived` (`boolean`)
- `options.user` (`UserOption`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Each workstream's `id`, `name`, `spent_usd` and `events`. What work nobody named one for spent is
the `None` group of `noclick.usage(group_by="workstream")`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Workstream.rename

```typescript
static rename(
  workstream: string | Workstream,
  name: string,
  options?: { client?: NoClick },
): Promise<Workstream>
```

Rename `workstream` (a `Workstream`, its name in any case, or its id) to `name`. Renamed onto another
workstream's name, it merges into that one: its charges so far read as that one's (none is rewritten), and
`raw.merged_from` names it. Your account's alone: a call acting for one of your users can't. Answers the
workstream it reads as now, without this month's spend (`Workstream.list()` reads it). Needs the `usage` scope.

Parameters:

- `workstream` (`string | Workstream`, required)
- `name` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The workstream it reads as now, without this month's spend (`spent_usd` 0; `Workstream.list()` reads
it).

### Workstream.archive

```typescript
static archive(
  workstream: string | Workstream,
  options?: { client?: NoClick },
): Promise<Workstream>
```

Archive `workstream` (a `Workstream`, its name in any case, or its id) once its work is done: its charges still
read under it, and it leaves `Workstream.list()` (`{ archived: true }` lists it) and the workstreams agents choose
from, until `unarchive` brings it back or an agent names it again. Your account's alone. Needs the `usage` scope.

Parameters:

- `workstream` (`string | Workstream`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The workstream, `archived`, without this month's spend.

### Workstream.unarchive

```typescript
static unarchive(
  workstream: string | Workstream,
  options?: { client?: NoClick },
): Promise<Workstream>
```

Bring an archived `workstream` back among your open ones. Your account's alone. Needs the `usage` scope.

Parameters:

- `workstream` (`string | Workstream`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The workstream, open again, without this month's spend.

## AccountCap

```typescript
interface AccountCap
```

Your account's monthly spending cap: `capUsd` (null while none is set) and, where one is set, what its billing
period has spent (`spentUsd`), when that period started and resets, and whether it's `reached`: then every call
that costs money rejects with `SpendCapExceeded`. `setBy` says who set it last (null: nobody has, or only NoClick's
own hold on an account no person has claimed).

| Attribute | Type | Description |
| --- | --- | --- |
| `capUsd` | `number | null` |  |
| `spentUsd` | `number | null` |  |
| `periodStart` | `Date | null` |  |
| `resetsAt` | `Date | null` |  |
| `reached` | `boolean` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `setBy` | `CapChange | null` |  |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## CapChange

```typescript
interface CapChange
```

Who set your account's monthly cap last: `by` (`owner`, signed in; `key`, one of your account's keys; `connection`,
an MCP connection; `agent`, an agent's turn; `assistant`, your NoClick assistant), the person it was for
(`responsibleUserId`: the person whose message started the agent's turn, the person a connection acts for, else
your account's owner), the key it was made with, the connection (`grantId`) and agent (`agentId`, its `turnId`) it
came through and their name (`client`), the approval a raise ran on, the cap before and after, and when.

| Attribute | Type | Description |
| --- | --- | --- |
| `by` | `string` |  |
| `responsibleUserId` | `string | null` |  |
| `keyId` | `string | null` |  |
| `grantId` | `string | null` |  |
| `agentId` | `string | null` |  |
| `turnId` | `string | null` |  |
| `client` | `string | null` |  |
| `approvalId` | `string | null` |  |
| `capBeforeUsd` | `number | null` |  |
| `capAfterUsd` | `number | null` |  |
| `at` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
