Files
cobble/src/harness/media/read-image.ts
T
tben d9aea8e9c8 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.
2026-10-23 15:41:41 +01:00

103 lines
3.3 KiB
TypeScript

import { ReadImagePrompt } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import withCandidates from "../resolve/with-candidates";
import type { HarnessUsage } from "../types";
import grabChatParams from "../text/grab-chat-params";
import buildUsageCall from "../usage/build-usage-call";
import recordHarnessUsage from "../usage/record-harness-usage";
type Params = {
/**
* An https or `data:` URL.
*/
url: string;
/**
* What to look for, added to the standard reading prompt.
*/
focus?: string;
signal?: AbortSignal;
/**
* Uses this bot's media reading model when it has its own.
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
*/
workspace_id?: number | string | null;
};
/**
* Reads an image with the media reading (vision) harness and returns what
* it sees, as text for a model that can't see.
*/
export default async function readImage({ url, focus, signal, bot_id, workspace_id }: Params) {
const candidates = await resolveHarnessCandidates({
harness: "vision",
bot_id,
workspace_id,
});
const saved_params = await grabChatParams({
harness: "vision",
bot_id,
workspace_id,
});
const { result } = await withCandidates<{ text: string; usage?: HarnessUsage }>({
harness: "vision",
candidates,
on_success: async ({ candidate, result: answer }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "vision",
candidate,
usage: answer.usage,
}),
}),
run: async (candidate) => {
const answer = await grabHarnessAdapter({
kind: candidate.provider.kind,
}).chat({
candidate,
messages: [
{
role: "user",
content: [
{
type: "text",
text: focus
? `${ReadImagePrompt}\n\nPay special attention to: ${focus}`
: ReadImagePrompt,
},
{ type: "image", url },
],
},
],
/**
* Reading is a lookup, so it stays literal unless a
* temperature was set for the vision harness.
*/
params: {
temperature: 0,
...saved_params(candidate.model),
},
signal: signal || new AbortController().signal,
});
if (!answer.text?.trim()) {
throw new HarnessError({
message: `The model couldn't read the image.`,
retryable: true,
candidate_key: candidate.key,
});
}
return { text: answer.text.trim(), usage: answer.usage };
},
});
return result.text;
}