Record what every model call spends, and show it
Nothing anywhere recorded what a model call cost: the harness used a provider's usage numbers only to decide whether a turn had finished, then dropped them. So a reply could not say what it took to make, one model could not be compared with another on price, and there was no way to ask what a day, a week or a month of the crew's work came to. - `token_usages` records one row per call: user, bot, workspace, session, job and message, the harness, the provider and model that actually answered, the prompt and completion counts, and the cost when the provider reports one. - `harness-usage-scope.ts` carries those ids in an AsyncLocalStorage scope that `run-bot-job.ts` enters once, so a run's turns, its session summary, its transcriptions, images and embeddings are all attributed without threading ids through every harness function. Nested runs merge rather than replace, and a null genuinely clears a field (a bot's own chat has no workspace). - Work with no run behind it is charged to its owner instead: `run-with-fallback-scope.ts` reaches the workspace's creator else the bot's, and deliberately does not override a real run, so an ingest a bot asked for is not misattributed to the bot's owner. - All six harnesses record through `withCandidates`'s `on_success`. Recording never throws: a model that answered must not lose its answer to a failed insert. - A job's calls land before its message exists, so `complete-bot-job.ts` back-fills `message_id` once the message is inserted. - The message's actions row shows what it cost, beside the timestamp and the play button, with the breakdown in its title. - `/admin/usage` totals the install's spending for 7, 30 or 90 days: the total against the previous period, a day-by-day chart, a split per kind of call, and a table per model with the price per thousand tokens worked out from cost and tokens, which is what makes two models comparable. Crew managers only, since it is the whole install's work rather than one user's conversation. It sits with Routines and Activity in the user popover rather than under Settings, because it is a record of what happened, not something to configure. Days are grouped in local time (`date(created_at / 1000, 'unixepoch', 'localtime')`), matching the local midnights the window builds and the `YYYY-MM-DD` buckets it looks up. Grouping by the bare UTC day put a late evening's calls under a name no bucket carried, so they vanished and the chart's total silently disagreed with the totals card; a test pins it. `canSeeRailItem` now decides who sees a popover or rail entry. The two each filtered with their own inline rule and only one understood `can_view`, so a gated page could be offered in the popover to everyone.
This commit is contained in:
@@ -4,6 +4,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import { SessionNamePrompt } from "@/src/data/harness-prompts";
|
||||
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import generateText from "@/src/harness/text/generate-text";
|
||||
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
|
||||
import parseSessionName from "./parse-session-name";
|
||||
|
||||
type Params = {
|
||||
@@ -30,7 +31,7 @@ export default async function nameBotSession({
|
||||
}: Params): Promise<boolean> {
|
||||
const session = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT id, title, summary FROM bot_sessions WHERE id = ? LIMIT 1`,
|
||||
sql: `SELECT id, user_id, title, summary FROM bot_sessions WHERE id = ? LIMIT 1`,
|
||||
values: [session_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
@@ -57,14 +58,30 @@ export default async function nameBotSession({
|
||||
)
|
||||
.join("\n\n");
|
||||
|
||||
const result = await generateText({
|
||||
messages: [
|
||||
{ role: "system", content: SessionNamePrompt },
|
||||
{ role: "user", content: transcript },
|
||||
],
|
||||
bot_id,
|
||||
workspace_id,
|
||||
signal,
|
||||
/**
|
||||
* The naming turn is a model call too, so it is recorded for this
|
||||
* conversation. It runs after the job is complete, on purpose, so it
|
||||
* has no job and no message of its own to charge it to.
|
||||
*/
|
||||
const result = await runWithHarnessUsageScope({
|
||||
scope: {
|
||||
user_id: session.user_id || undefined,
|
||||
bot_id,
|
||||
workspace_id: workspace_id || null,
|
||||
session_id: session.id,
|
||||
job_id: null,
|
||||
message_id: null,
|
||||
},
|
||||
task: () =>
|
||||
generateText({
|
||||
messages: [
|
||||
{ role: "system", content: SessionNamePrompt },
|
||||
{ role: "user", content: transcript },
|
||||
],
|
||||
bot_id,
|
||||
workspace_id,
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
|
||||
const name = parseSessionName({ text: result.text });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
|
||||
import grabJobUserId from "@/src/functions/backend/db/bots-queue/grab-job-user-id";
|
||||
import HarnessError from "@/src/harness/harness-error";
|
||||
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
|
||||
import BotJobFatalError from "./bot-job-fatal-error";
|
||||
import runBotReply from "./run-bot-reply";
|
||||
import runBotTask from "./run-bot-task";
|
||||
@@ -33,9 +34,25 @@ const runBotJob: BotJobRunner = async (context) => {
|
||||
const owned = { ...bot, id: bot.id };
|
||||
|
||||
try {
|
||||
return job.kind == "reply"
|
||||
? await runBotReply({ ...context, bot: owned, user_id })
|
||||
: await runBotTask({ ...context, bot: owned, user_id });
|
||||
/**
|
||||
* Everything the job's models do is recorded for this user, this
|
||||
* bot, this conversation and this job. A reply's text loop adds
|
||||
* the message it is producing to the one-turn scope it opens.
|
||||
*/
|
||||
return await runWithHarnessUsageScope({
|
||||
scope: {
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
workspace_id: job.workspace_id || null,
|
||||
session_id: job.session_id || null,
|
||||
job_id: job.id || null,
|
||||
message_id: null,
|
||||
},
|
||||
task: () =>
|
||||
job.kind == "reply"
|
||||
? runBotReply({ ...context, bot: owned, user_id })
|
||||
: runBotTask({ ...context, bot: owned, user_id }),
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (
|
||||
error instanceof HarnessError &&
|
||||
|
||||
Reference in New Issue
Block a user