Skip to content
Merged
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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Unreleased

- Bot avatars show what their bot is doing, using `open-bot-avatar` 0.3.0: three hopping dots while it thinks, bent over the work while it writes, searches, remembers, or uses tools, an exclamation mark while it retries, a short celebration when a reply finishes, and waiting in a group chat while it answers next. Live avatars ease from one state to the next instead of restarting. The `/avatars` page previews every state. Paused bots and disabled automations no longer show a dimmed, still avatar.
- A bot's details in the web chat show **Usage**: tokens and cost for each model and tool its bot chat has used, with a total. Job panes now include tool costs, such as intent checks, in their cost.
- **Settings** > **Providers** has a **Usage** tab: tokens and cost for each model across all of the account's bots, grouped by provider, and for tools that call a model of their own, with totals. `GET /v1/usage` returns the same figures. Job panes now include tool costs, such as intent checks, in their cost.
- When a bot's model can't read images and no vision model is set, the web chat warns as soon as an image is attached and links to the bot's profile and the vision model setting. The server refuses such a message before recording a turn, so the error shows once, names the bot, and the message goes back to the composer. `GET /v1/models` returns `images` for each model.
- Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:<id>` or `group:<id>` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. On the web, pin or unpin a bot chat or group chat from its **More** menu in the sidebar, and drag pins in the **Pinned** section to reorder them.
- Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with 👍 instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note.
Expand Down
9 changes: 0 additions & 9 deletions apps/docs/content/concepts/chats.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,6 @@ flowchart LR
**Compaction never deletes anything you can see.** It only changes what the
bot reads on its next turn.

## Usage

In the web client, a bot's details show **Usage** for its bot chat: the tokens
and cost of each model the chat has used, including the vision model, and of
tools that call a model of their own, such as questions to the vision model.
Providers that bill by subscription, such as Claude Code, report no cost, so
only their tokens show. Jobs keep their own usage, including their intent
checks, shown in each job's pane.

## Files

In the web client, attach any file up to 100 MB, with at most eight files per
Expand Down
14 changes: 12 additions & 2 deletions apps/docs/content/getting-started/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,17 @@ that read images.
| **Set** | Gets the vision model's description of each image, including any visible text, and can ask it follow-up questions about an image. The transcript keeps the image. |

The vision model describes each image once per conversation, and its tokens and
cost count toward the conversation's usage. Bots whose model reads images never
use it.
cost count toward [usage](#usage). Bots whose model reads images never use it.

## Usage

To see what your bots have spent, open **Settings** > **Providers** and select
**Usage**. It lists tokens and cost for each model, grouped by provider, with a
total for each provider and for your account. **Tools** lists tools that call a
model of their own, such as questions to the vision model and intent checks.

Usage covers every bot's chat and jobs since each started. Deleting a bot
removes its usage. Providers that bill by subscription, such as Claude Code,
report no cost, so only their tokens show. Over the API, use `GET /v1/usage`.

With a provider connected, [create your first bot](/getting-started/first-bot).
2 changes: 1 addition & 1 deletion apps/docs/content/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ The token reaches no other route.
| **Event relay** | `/v1/event-relay`, `/v1/event-sources`, `/v1/event-sources/{id}` |
| **Voice gateway** | `/v1/voice-gateway`, `/v1/voice-gateway/token` |
| **Voice gateway token** | `GET /v1/voice/events`, `POST /v1/voice/lines/{username}/messages`, `GET /v1/voice/lines/{username}/events`, `GET /v1/voice/lines/{username}/executions/{executionId}`, `PUT /v1/voice/lines`, `PUT /v1/voice/lines/{username}/calls/{callId}`, `POST /v1/voice/calls/{callId}` |
| **Providers & models** | `/v1/providers`, `/v1/providers/{provider}`, `POST /v1/providers/{provider}/login`, `/v1/provider-logins/{id}`, `POST /v1/provider-logins/{id}/responses`, `/v1/models`, `/v1/vision-model` |
| **Providers & models** | `/v1/providers`, `/v1/providers/{provider}`, `POST /v1/providers/{provider}/login`, `/v1/provider-logins/{id}`, `POST /v1/provider-logins/{id}/responses`, `/v1/models`, `/v1/vision-model`, `/v1/usage` |
| **Password managers** | `/v1/password-managers`, `/v1/password-managers/{id}` |
| **MCP servers** | `/v1/mcp-servers`, `/v1/mcp-servers/{id}`, `/v1/mcp-servers/{id}/oauth`, `POST /v1/mcp-servers/{id}/oauth/callback` |

Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/bots/bots-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type TranscriptMessage,
} from "../transcript/transcript";
import type { JobKindName } from "../shared/job-kinds";
import { usageSummary } from "./usage-summary";

export const botsReads = (context: BotsContext, lookup: BotsLookup) => {
const { agents, conversations, events, executions, runtime, schedules } =
Expand Down Expand Up @@ -145,10 +146,26 @@ export const botsReads = (context: BotsContext, lookup: BotsLookup) => {
);
});

// A bot with no conversation has never called a model; skipping it leaves its harness unopened.
const usage = Effect.gen(function* () {
const states = yield* Effect.forEach(
yield* agents.list,
Effect.fnUntraced(function* (each) {
const [first] = yield* conversations.list(each.id, true);

return first ? [yield* pi(() => runtime.usage(each))] : [];
}),
{ concurrency: "unbounded" },
);

return usageSummary(states.flat());
}).pipe(Effect.withSpan("Bots.usage"));

return {
origin,
snapshot,
agentPreviews,
usage,
history: Effect.fn("Bots.history")(function* (
agentId: string,
options: PageOptions,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/bots/bots-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const botsService = (context: BotsContext): Bots["Service"] => {
changed: notifications.changed,
onSettled: notifications.onSettled,
agentPreviews: reads.agentPreviews,
usage: reads.usage,
announceJobAnswer: notifications.announceJobAnswer,
announce: notifications.emit,
snapshot: reads.snapshot,
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/bots/bots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
} from "../transcript/transcript";
import type { ReplyReference } from "../contract/push";
import type { CallEventData } from "../transcript/entries";
import type { usageSummary } from "./usage-summary";

export type ChatPreviewActivity = {
type: "chat-preview";
Expand Down Expand Up @@ -100,6 +101,8 @@ export class Bots extends Context.Service<
readonly agentPreviews: Effect.Effect<
{ agent: Agent; lastMessage: string }[]
>;
/** Tokens and cost of every model and tool across all of the account's bots, since each bot's first conversation. */
readonly usage: Effect.Effect<ReturnType<typeof usageSummary>, AppError>;
/**
* Tells activity listeners about the bot's answer to a job's report, such as a desktop job asking for the owner.
* Job reports reach the chat without an execution, so a finished execution never announces them.
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/bots/chat-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
chatSnapshotResponse,
codingJobsResponse,
desktopJobsResponse,
usageResponse,
} from "../contract/api-responses";
import type { Register } from "../contract/route";
import { attachmentHeaders } from "../shared/attachments";
Expand All @@ -30,6 +31,11 @@ const registerChatReadRoutes = (options: ChatRoutesOptions) => {

return c.json(snapshot, 200);
});
register.plain(routes.usage, async (c) => {
const usage: z.output<typeof usageResponse> = await service.usage();

return c.json(usage, 200);
});
register.plain(routes.history, async (c) =>
c.json(await service.history(c.req.param("id"), c.req.valid("query")), 200),
);
Expand Down
5 changes: 5 additions & 0 deletions apps/server/src/bots/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,11 @@ export class AgentRuntime {
return (await this.open(agent)).harness;
}

/** Every conversation's `pi.usage` in the bot's harness, summed: its chat, jobs, and any other conversation. */
async usage(agent: Agent) {
return (await this.open(agent)).harness.usage(BACKGROUND_CONTEXT);
}

private skillTools(agent: Agent) {
const currentAgent = () => {
const current = this.callbacks.currentAgent(agent);
Expand Down
55 changes: 55 additions & 0 deletions apps/server/src/bots/usage-summary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { expect, test } from "bun:test";
import type { UsageState } from "@earendil-works/pi-durable";
import { usageSummary } from "./usage-summary";

const usage = (totalTokens: number, cost: number) => ({
input: totalTokens,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens,
cost: { input: cost, output: 0, cacheRead: 0, cacheWrite: 0, total: cost },
});

test("sums each model and tool across bots, most tokens first", () => {
const first: UsageState = {
models: {
"anthropic/claude-sonnet-5-5": usage(100, 0.5),
"openai/gpt-6": usage(10, 0.25),
},
tools: { vision: usage(5, 0.01) },
};

const second: UsageState = {
models: { "openai/gpt-6": usage(200, 1) },
tools: {},
};

expect(usageSummary([first, second])).toEqual({
models: [
{ provider: "openai", model: "gpt-6", tokens: 210, cost: 1.25 },
{
provider: "anthropic",
model: "claude-sonnet-5-5",
tokens: 100,
cost: 0.5,
},
],
tools: [{ name: "vision", tokens: 5, cost: 0.01 }],
});
});

test("splits a model key at its first slash", () => {
const state: UsageState = {
models: { "openrouter/meta/llama-5": usage(1, 0) },
tools: {},
};

expect(usageSummary([state]).models).toEqual([
{ provider: "openrouter", model: "meta/llama-5", tokens: 1, cost: 0 },
]);
});

test("returns empty lists without usage", () => {
expect(usageSummary([])).toEqual({ models: [], tools: [] });
});
40 changes: 40 additions & 0 deletions apps/server/src/bots/usage-summary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { UsageState } from "@earendil-works/pi-durable";

type Totals = { tokens: number; cost: number };

type Bucket = UsageState["models"];

const sum = (states: readonly UsageState[], bucket: keyof UsageState) => {
const totals = new Map<string, Totals>();

for (const state of states)
for (const [key, usage] of Object.entries<Bucket[string]>(state[bucket])) {
const total = totals.get(key) ?? { tokens: 0, cost: 0 };

total.tokens += usage.totalTokens;
total.cost += usage.cost.total;
totals.set(key, total);
}

return [...totals].sort(([, a], [, b]) => b.tokens - a.tokens);
};

/** Pi Durable keys a model `provider/modelId`; a model ID may hold a slash of its own, so split at the first. */
const modelOf = (key: string) => {
const slash = key.indexOf("/");

return slash < 0
? { provider: "", model: key }
: { provider: key.slice(0, slash), model: key.slice(slash + 1) };
};

/** Tokens and cost of every model and tool across `states`, most tokens first. */
export function usageSummary(states: readonly UsageState[]) {
return {
models: sum(states, "models").map(([key, totals]) => ({
...modelOf(key),
...totals,
})),
tools: sum(states, "tools").map(([name, totals]) => ({ name, ...totals })),
};
}
8 changes: 8 additions & 0 deletions apps/server/src/contract/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1580,6 +1580,14 @@ export const routes = {
operationId: "listProviders",
responses: { 200: json(z.array(response.providerResponse)) },
}),
usage: define({
method: "get",
path: "/v1/usage",
operationId: "getUsage",
description:
"Tokens and cost of each model and tool across all of the account's bots: their chats, jobs, and other conversations, since each started. Most tokens first. A deleted bot's usage is gone with it.",
responses: { 200: json(response.usageResponse) },
}),
previewReasoning: define({
method: "post",
path: "/v1/reasoning/preview",
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/contract/api-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,26 @@ export const providerResponse = z
})
.openapi("Provider");

const usageTotals = {
tokens: z.number(),
cost: z.number().openapi({
description:
"US dollars. Zero for providers that bill by subscription, such as Claude Code.",
}),
};

export const usageResponse = z
.object({
models: z.array(
z.object({ provider: z.string(), model: z.string(), ...usageTotals }),
),
tools: z.array(z.object({ name: z.string(), ...usageTotals })).openapi({
description:
"Tools that call a model of their own, such as vision questions and intent checks.",
}),
})
.openapi("Usage");

/** One object rather than a union, so generated clients keep the nullable prompt. */
export const loginPrompt = z.object({
id: z.string(),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/message-gateway/message-gateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ async function fixture(
changed: unexpected,
onSettled: unsubscribe,
agentPreviews: unexpected(),
usage: unexpected(),
announceJobAnswer: unexpected,
announce: unexpected,
snapshot: unexpected,
Expand Down
95 changes: 0 additions & 95 deletions apps/web/features/bot-chat/chat-usage.dom.test.tsx

This file was deleted.

Loading
Loading