TypeScript
feat(usage): support custom model prices (#9774)
Julius Marminge394e8470c899
diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.tsindex 91895fd5dcf..141aa405af2 100644--- a/apps/server/src/environment/ServerEnvironment.test.ts+++ b/apps/server/src/environment/ServerEnvironment.test.ts@@ -166,6 +166,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {expect(second.capabilities.attachmentUploads).toBe(true);expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });expect(second.capabilities.pullRequests).toBe(true);+ expect(second.capabilities.usagePriceOverrides).toBe(true);expect(second.capabilities.threadTitleRegeneration).toBe(true);expect(second.capabilities.threadPullRequestLinking).toBe(true);expect(second.capabilities.agentActivityPublishing).toBe(false);diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex d050bde8856..cfecfc00c86 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -222,6 +222,7 @@ export const make = Effect.gen(function* () {threadSnooze: true,environmentThemes: true,usageLimitSources: true,+ usagePriceOverrides: true,threadPinning: true,threadPinReorder: true,threadTitleRegeneration: true,diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.tsindex 82ed8525b9b..4526e2c988a 100644--- a/apps/server/src/serverSettings.test.ts+++ b/apps/server/src/serverSettings.test.ts@@ -272,6 +272,32 @@ it.layer(NodeServices.layer)("server settings", (it) => {).pipe(Effect.provide(makeServerSettingsLayer())),);+ it.effect("persists custom usage prices and removes them from the settings file", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const serverConfig = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;+ const prices = {+ inputCostPerMillionTokens: 2,+ outputCostPerMillionTokens: 8,+ cacheReadCostPerMillionTokens: 0,+ };+ const readPersisted = fileSystem+ .readFileString(serverConfig.settingsPath)+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings))));++ yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": prices } });+ const persisted = yield* readPersisted;+ assert.deepStrictEqual(persisted.usagePriceOverrides, { "example-model": prices });++ yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": null } });+ const restored = yield* readPersisted;+ assert.deepStrictEqual(restored.usagePriceOverrides, {});+ }),+ ).pipe(Effect.provide(makeServerSettingsLayer())),+ );+it.effect("persists and broadcasts thread settlement settings", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.tsindex 63b74510e29..9d728c88cf4 100644--- a/apps/server/src/usage/UsageService.test.ts+++ b/apps/server/src/usage/UsageService.test.ts@@ -9,9 +9,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";import * as Duration from "effect/Duration";+import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Scheduler from "effect/Scheduler";import * as TestClock from "effect/testing/TestClock";@@ -21,7 +23,7 @@ import * as ServerConfig from "../config.ts";import * as ServerSettings from "../serverSettings.ts";import * as UsageService from "./UsageService.ts";-function claudeLine(id: number, outputTokens: number): string {+function claudeLine(id: number, outputTokens: number, model = "claude-fable-5"): string {return `${JSON.stringify({type: "assistant",timestamp: "2026-08-01T10:00:00Z",@@ -29,7 +31,7 @@ function claudeLine(id: number, outputTokens: number): string {sessionId: "session-1",message: {id: `msg_${id}`,- model: "claude-fable-5",+ model,usage: { input_tokens: 10, output_tokens: outputTokens },},})}\n`;@@ -96,6 +98,49 @@ function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens}describe("UsageService", () => {+ it.live("reprices unchanged transcripts when custom prices are added, edited, or removed", () =>+ Effect.gen(function* () {+ const { transcript, settings, home } = yield* setup;+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model")));++ yield* Effect.gen(function* () {+ const settingsService = yield* ServerSettings.ServerSettingsService;+ const service = yield* UsageService.make;++ const original = yield* service.readSummary(WINDOW);+ assert.strictEqual(original.buckets[0]?.costUsd, 0);+ assert.strictEqual(original.buckets[0]?.unpricedRecords, 1);++ yield* settingsService.updateSettings({+ usagePriceOverrides: {+ "example-model": { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 },+ },+ });+ const overridden = yield* service.readSummary(WINDOW);+ assert.closeTo(overridden.buckets[0]?.costUsd ?? -1, 0.00006, 1e-12);+ assert.strictEqual(overridden.buckets[0]?.costSource, "modelPriced");+ assert.strictEqual(overridden.buckets[0]?.unpricedRecords, 0);+ assert.deepStrictEqual(overridden.buckets[0]?.totals, original.buckets[0]?.totals);++ yield* settingsService.updateSettings({+ usagePriceOverrides: {+ "example-model": { inputCostPerMillionTokens: 4, outputCostPerMillionTokens: 16 },+ },+ });+ const edited = yield* service.readSummary(WINDOW);+ assert.closeTo(edited.buckets[0]?.costUsd ?? -1, 0.00012, 1e-12);++ yield* settingsService.updateSettings({ usagePriceOverrides: { "example-model": null } });+ const restored = yield* service.readSummary(WINDOW);+ assert.deepStrictEqual(restored.buckets, original.buckets);+ }).pipe(+ Effect.provide(+ serviceLayers({ prefix: "usage-service-price-overrides-test", home, settings }),+ ),+ );+ }).pipe(Effect.scoped),+ );+it.live("counts appended usage on a rescan of a grown transcript", () =>Effect.gen(function* () {const { transcript, settings, home } = yield* setup;@@ -114,6 +159,65 @@ describe("UsageService", () => {}).pipe(Effect.scoped),);+ it.live("does not share an in-flight scan after custom prices change", () =>+ Effect.gen(function* () {+ const { transcript, settings, home } = yield* setup;+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model")));++ yield* Effect.gen(function* () {+ const settingsService = yield* ServerSettings.ServerSettingsService;+ const fileSystem = yield* FileSystem.FileSystem;+ const firstScanStarted = yield* Deferred.make<void>();+ const secondScanStarted = yield* Deferred.make<void>();+ const releaseRates = yield* Deferred.make<void>();+ let homeProbes = 0;+ const service = yield* UsageService.make.pipe(+ Effect.provideService(FileSystem.FileSystem, {+ ...fileSystem,+ exists: (path) =>+ fileSystem.exists(path).pipe(+ Effect.tap(() => {+ if (path !== NodePath.join(home, "claude", ".claude", "projects"))+ return Effect.void;+ homeProbes += 1;+ return Deferred.succeed(+ homeProbes === 1 ? firstScanStarted : secondScanStarted,+ undefined,+ );+ }),+ ),+ }),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make((request) =>+ Deferred.await(releaseRates).pipe(+ Effect.as(HttpClientResponse.fromWeb(request, Response.json({}))),+ ),+ ),+ ),+ );++ const first = yield* service.readSummary(WINDOW).pipe(Effect.forkChild);+ yield* Deferred.await(firstScanStarted);+ yield* settingsService.updateSettings({+ usagePriceOverrides: {+ "example-model": { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 },+ },+ });+ const second = yield* service.readSummary(WINDOW).pipe(Effect.forkChild);+ yield* Deferred.await(secondScanStarted);+ yield* Deferred.succeed(releaseRates, undefined);++ const original = yield* Fiber.join(first);+ const updated = yield* Fiber.join(second);+ assert.strictEqual(original.buckets[0]?.costUsd, 0);+ assert.closeTo(updated.buckets[0]?.costUsd ?? -1, 0.00006, 1e-12);+ }).pipe(+ Effect.provide(serviceLayers({ prefix: "usage-service-price-race-test", home, settings })),+ );+ }).pipe(Effect.scoped),+ );+it.live("shares one scan between concurrent identical requests", () =>Effect.gen(function* () {const { transcript, settings, home } = yield* setup;diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.tsindex 7c446ae14f9..0e6b0c1eecd 100644--- a/apps/server/src/usage/UsageService.ts+++ b/apps/server/src/usage/UsageService.ts@@ -16,6 +16,7 @@ import * as NodeOS from "node:os";import {USAGE_CONTRACT_VERSION,+ type ServerSettings as ServerSettingsValue,type UsageProviderKind,type UsageSource,type UsagePricing,@@ -44,7 +45,7 @@ import * as ServerSettings from "../serverSettings.ts";import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";import { UsageAggregator } from "./usageAggregation.ts";-import { parseRateTable, type RateTable } from "./usagePricing.ts";+import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";import {listTranscriptFiles,readDirectoryVolumeId,@@ -232,24 +233,22 @@ export const make = Effect.gen(function* () {return nestedExists ? nested : path.join(homePath, "projects");});- /** Resolves the transcript directory for each provider. */- const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {- // A settings failure must surface as an error: swallowing it here would- // present "zero usage from every provider" as a valid answer.- const settings = yield* settingsService.getSettings.pipe(- Effect.catchCause(- (cause) =>- new UsageReadError({- reason: "scanFailed",- // Bounded description; the squashed failure travels as the cause.- // Squashed, not the Cause tree: a full tree in a Defect field is- // the unbounded wire payload the bounded detail exists to avoid.- detail: "Server settings could not be read.",- cause: Cause.squash(cause),- }),- ),- );+ // A settings failure must not silently discard custom rates or transcript homes.+ const readSettings = settingsService.getSettings.pipe(+ Effect.catchCause(+ (cause) =>+ new UsageReadError({+ reason: "scanFailed",+ detail: "Server settings could not be read.",+ cause: Cause.squash(cause),+ }),+ ),+ );+ /** Resolves the transcript directory for each provider. */+ const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (+ settings: ServerSettingsValue,+ ) {const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);@@ -379,10 +378,15 @@ export const make = Effect.gen(function* () {| null;}- const collectDirs = Effect.fn("UsageService.collectDirs")(function* (windowStartMs: number) {+ const collectDirs = Effect.fn("UsageService.collectDirs")(function* (+ windowStartMs: number,+ settings: ServerSettingsValue,+ ) {// The home resolvers ask for `Path` themselves; satisfy them from the// instance we already hold so the scan stays context-free.- const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));+ const dirs = yield* resolveTranscriptDirs(settings).pipe(+ Effect.provideService(Path.Path, path),+ );const scanned: ScannedDir[] = [];for (const { provider, dir, fileName } of dirs) {const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));@@ -406,7 +410,10 @@ export const make = Effect.gen(function* () {return scanned;});- const scanSummary = Effect.fn("UsageService.scanSummary")(function* (input: UsageSummaryInput) {+ const scanSummary = Effect.fn("UsageService.scanSummary")(function* (+ input: UsageSummaryInput,+ settings: ServerSettingsValue,+ ) {if (input.sinceDay > input.untilDay) {return yield* new UsageReadError({reason: "invalidWindow",@@ -455,9 +462,10 @@ export const make = Effect.gen(function* () {// Pricing only matters once records are aggregated, so the rate table// loads while transcripts stream instead of gating them: a cold rates// fetch on a slow network no longer delays the scan by its own timeout.- const [, scannedDirs] = yield* Effect.all([ensureRates(false), collectDirs(windowStartMs)], {- concurrency: 2,- });+ const [, scannedDirs] = yield* Effect.all(+ [ensureRates(false), collectDirs(windowStartMs, settings)],+ { concurrency: 2 },+ );const aggregator = new UsageAggregator({timeZone: input.timeZone,@@ -466,6 +474,7 @@ export const make = Effect.gen(function* () {resolution: input.resolution ?? "day",...hourlyWindow,rates,+ priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),});const sources: UsageSource[] = [];@@ -547,13 +556,16 @@ export const make = Effect.gen(function* () {});/**- * In-flight scans by window, so concurrent identical requests (the usage+ * In-flight scans by window and custom prices, so concurrent identical requests (the usage* page open on two clients at once) share one scan instead of racing over* the same corpus twice.*/const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();- const scanKey = (input: UsageSummaryInput): string =>+ const scanKey = (+ input: UsageSummaryInput,+ priceOverrides: ServerSettingsValue["usagePriceOverrides"],+ ): string =>JSON.stringify([input.timeZone,input.sinceDay,@@ -561,10 +573,12 @@ export const make = Effect.gen(function* () {input.resolution ?? "day",input.sinceTime ?? null,input.untilTime ?? null,+ priceOverrides,]);const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {- const key = scanKey(input);+ const settings = yield* readSettings;+ const key = scanKey(input, settings.usagePriceOverrides);const deferred = yield* Effect.uninterruptible(Effect.gen(function* () {const existing = inflightScans.get(key);@@ -576,7 +590,7 @@ export const make = Effect.gen(function* () {inflightScans.set(key, created);// Detached so one departing client cannot tear the scan out from under// the fibers awaiting it; a finished scan warms the cache either way.- yield* scanSummary(input).pipe(+ yield* scanSummary(input, settings).pipe(Effect.onExit((exit) =>Effect.sync(() => inflightScans.delete(key)).pipe(Effect.andThen(Deferred.done(created, exit)),diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.tsindex e100be76e97..01a1195efb6 100644--- a/apps/server/src/usage/usageAggregation.ts+++ b/apps/server/src/usage/usageAggregation.ts@@ -61,6 +61,7 @@ export interface AggregateOptions {readonly sinceDay: string;readonly untilDay: string;readonly rates: RateTable;+ readonly priceOverrides?: RateTable;readonly resolution?: UsageResolution;readonly sinceTimeMs?: number;readonly untilTimeMs?: number;@@ -165,11 +166,17 @@ export class UsageAggregator {record.model,record.totals,record.reportedCostUsd,+ this.#options.priceOverrides,);bucket.totals = addTotals(bucket.totals, record.totals);bucket.costUsd += priced.costUsd;- bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals);+ bucket.cacheSavingsUsd += cacheSavingsUsd(+ this.#options.rates,+ record.model,+ record.totals,+ this.#options.priceOverrides,+ );bucket.records += 1;if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.tsindex 45113414f69..d45dfe2dd09 100644--- a/apps/server/src/usage/usagePricing.test.ts+++ b/apps/server/src/usage/usagePricing.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from "@effect/vitest";-import { lookupRate, normalizeModelName, parseRateTable } from "./usagePricing.ts";+import {+ cacheSavingsUsd,+ createOverrideRateTable,+ lookupRate,+ normalizeModelName,+ parseRateTable,+ priceUsage,+} from "./usagePricing.ts";const rate = (input: number, cacheRead?: number) => ({input_cost_per_token: input,@@ -9,6 +16,73 @@ const rate = (input: number, cacheRead?: number) => ({});describe("usage pricing", () => {+ const totals = {+ uncachedInputTokens: 1_000_000,+ cachedInputTokens: 1_000_000,+ cacheCreationTokens: 1_000_000,+ outputTokens: 1_000_000,+ reasoningTokens: 500_000,+ };++ it("uses custom token rates ahead of public and provider-reported costs", () => {+ const table = parseRateTable({ "example-model": rate(1) });+ const overrides = createOverrideRateTable({+ "example-model": {+ inputCostPerMillionTokens: 2,+ outputCostPerMillionTokens: 8,+ cacheReadCostPerMillionTokens: 0.5,+ cacheWriteCostPerMillionTokens: 3,+ },+ });++ for (const reportedCostUsd of [null, 99]) {+ expect(priceUsage(table, "example-model", totals, reportedCostUsd, overrides)).toEqual({+ costUsd: 13.5,+ costSource: "modelPriced",+ });+ }+ expect(cacheSavingsUsd(table, "example-model", totals, overrides)).toBe(1.5);+ });++ it("prices unknown models offline and uses input prices for omitted cache rates", () => {+ const table = parseRateTable({});+ const overrides = createOverrideRateTable({+ "example-model": { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 },+ });++ expect(priceUsage(table, "example-model", totals, null, overrides)).toEqual({+ costUsd: 14,+ costSource: "modelPriced",+ });+ expect(cacheSavingsUsd(table, "example-model", totals, overrides)).toBe(0);+ });++ it("preserves explicit zero rates and matches only the exact trimmed model ID", () => {+ const table = parseRateTable({});+ const overrides = createOverrideRateTable({+ " vendor/example-model[1m] ": {+ inputCostPerMillionTokens: 0,+ outputCostPerMillionTokens: 0,+ },+ });+ expect(priceUsage(table, " vendor/example-model[1m] ", totals, 99, overrides)).toEqual({+ costUsd: 0,+ costSource: "modelPriced",+ });+ for (const model of [+ "example-model[1m]",+ "vendor/example-model",+ "vendor/Example-model[1m]",+ "other/example-model[1m]",+ ]) {+ expect(priceUsage(table, model, totals, null, overrides).costSource).toBe("unpriced");+ expect(priceUsage(table, model, totals, 99, overrides)).toEqual({+ costUsd: 99,+ costSource: "providerReported",+ });+ }+ });+it("keeps the existing model-name normalization contract", () => {expect(normalizeModelName(" Anthropic/Claude-Opus-5 ")).toBe("claude-opus-5");});diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.tsindex a7beecb1f55..5ca75a68cb3 100644--- a/apps/server/src/usage/usagePricing.ts+++ b/apps/server/src/usage/usagePricing.ts@@ -7,7 +7,11 @@** @module usagePricing*/-import type { UsageCostSource, UsageTokenTotals } from "@t3tools/contracts";+import type {+ UsageCostSource,+ UsageModelPriceOverride,+ UsageTokenTotals,+} from "@t3tools/contracts";/*** The subset of a LiteLLM entry we price against. All values are USD per token.@@ -26,6 +30,25 @@ export interface ModelRate {export type RateTable = ReadonlyMap<string, ModelRate>;+/** Custom IDs keep their case, provider prefix, and variant suffix. */+export function createOverrideRateTable(+ overrides: Readonly<Record<string, UsageModelPriceOverride>>,+): RateTable {+ return new Map(+ Object.entries(overrides).map(([model, prices]) => [+ model.trim(),+ {+ inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,+ outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,+ cacheReadCostPerToken:+ (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,+ cacheCreationCostPerToken:+ (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,+ },+ ]),+ );+}+/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */interface LiteLlmEntry {readonly input_cost_per_token?: unknown;@@ -168,12 +191,14 @@ export function priceUsage(model: string,totals: UsageTokenTotals,reportedCostUsd: number | null,+ overrides?: RateTable,): PricedUsage {- if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {+ const override = overrides?.get(model.trim());+ if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {return { costUsd: reportedCostUsd, costSource: "providerReported" };}- const rate = lookupRate(table, model);+ const rate = override ?? lookupRate(table, model);if (rate === null) return { costUsd: 0, costSource: "unpriced" };const costUsd =@@ -189,8 +214,13 @@ export function priceUsage(* What the cached input would have cost at full input rates, minus what it* actually cost. Drives the "cache savings" figure.*/-export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {- const rate = lookupRate(table, model);+export function cacheSavingsUsd(+ table: RateTable,+ model: string,+ totals: UsageTokenTotals,+ overrides?: RateTable,+): number {+ const rate = overrides?.get(model.trim()) ?? lookupRate(table, model);if (rate === null) return 0;return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);}diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.test.tsxindex 8e86b521e89..56bd1707342 100644--- a/apps/web/src/components/usage/UsagePage.test.tsx+++ b/apps/web/src/components/usage/UsagePage.test.tsx@@ -57,6 +57,7 @@ vi.mock("../WorkspaceBreadcrumb", () => ({vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));+vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));vi.mock("./usageProviders", async (importOriginal) => {const actual = await importOriginal<typeof import("./usageProviders")>();return {diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex 4b62df37412..a96e4ac3741 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -36,6 +36,7 @@ import {import { WorkspacePageContainer } from "../WorkspacePageContainer";import { WorkspacePageHeader } from "../WorkspacePageHeader";import { UsageLimitsSection } from "./UsageLimits";+import { UsagePriceOverrides } from "./UsagePriceOverrides";import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";@@ -264,6 +265,11 @@ export function UsagePage() {<ScrollArea className="min-h-0 flex-1"><WorkspacePageContainer width="wide">+ {!showingLimits ? (+ <div className="flex justify-end">+ <UsagePriceOverrides usage={environments} />+ </div>+ ) : null}{showingLimits ? (<UsageLimitsSection />) : settling ? (diff --git a/apps/web/src/components/usage/UsagePriceOverrides.tsx b/apps/web/src/components/usage/UsagePriceOverrides.tsxnew file mode 100644index 00000000000..faa161f9532--- /dev/null+++ b/apps/web/src/components/usage/UsagePriceOverrides.tsx@@ -0,0 +1,318 @@+import { useAtomValue } from "@effect/atom-react";+import type { EnvironmentId, UsageModelPriceOverride } from "@t3tools/contracts";+import { useState } from "react";++import { isElectron } from "../../env";+import {+ type EnvironmentPresentation,+ useEnvironments,+ usePrimaryEnvironmentId,+} from "../../state/environments";+import { serverEnvironment } from "../../state/server";+import { useEnvironmentSessionState } from "../../state/session";+import { useAtomCommand } from "../../state/use-atom-command";+import type { EnvironmentUsageStatus } from "../../state/usage";+import {+ resolvePrimaryOperateAccess,+ resolveRemoteOperateAccess,+} from "../settings/ProviderSettingsPanel.logic";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";+import { Input } from "../ui/input";+import { Label } from "../ui/label";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { parseUsagePriceForm, USAGE_PRICE_FIELDS, usagePriceForm } from "./usagePriceForm";++export function UsagePriceOverrides({+ usage,+}: {+ readonly usage: readonly EnvironmentUsageStatus[];+}) {+ const [open, setOpen] = useState(false);+ return (+ <>+ <Button variant="outline" size="sm" onClick={() => setOpen(true)}>+ Model prices+ </Button>+ {open ? <ModelPricesDialog usage={usage} onOpenChange={setOpen} /> : null}+ </>+ );+}++function ModelPricesDialog({+ usage,+ onOpenChange,+}: {+ readonly usage: readonly EnvironmentUsageStatus[];+ readonly onOpenChange: (open: boolean) => void;+}) {+ const { environments } = useEnvironments();+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const [selectedId, setSelectedId] = useState<EnvironmentId | null>(primaryEnvironmentId);+ const environment =+ environments.find((entry) => entry.environmentId === selectedId) ?? environments[0];+ const summary = usage.find(+ (entry) => entry.environmentId === environment?.environmentId,+ )?.summary;+ const models = [...new Set(summary?.buckets.map((bucket) => bucket.model) ?? [])].sort();++ return (+ <Dialog open onOpenChange={onOpenChange}>+ <DialogPopup className="max-w-xl">+ <DialogHeader>+ <DialogTitle>Model prices</DialogTitle>+ <DialogDescription>+ Override estimated costs using USD per million tokens. Prices apply to all saved history+ on the selected environment.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="grid gap-5 pb-6">+ {environment ? (+ <>+ <div className="grid gap-1.5">+ <Label htmlFor="usage-prices-environment">Environment</Label>+ <Select+ value={environment.environmentId}+ onValueChange={(value) => {+ const next = environments.find((entry) => entry.environmentId === value);+ if (next) setSelectedId(next.environmentId);+ }}+ >+ <SelectTrigger id="usage-prices-environment">+ <SelectValue>{environment.label}</SelectValue>+ </SelectTrigger>+ <SelectPopup>+ {environments.map((entry) => (+ <SelectItem key={entry.environmentId} value={entry.environmentId}>+ {entry.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ <EnvironmentModelPrices+ key={environment.environmentId}+ environment={environment}+ models={models}+ />+ </>+ ) : (+ <p className="text-sm text-muted-foreground">+ Connect an environment to set model prices.+ </p>+ )}+ </DialogPanel>+ </DialogPopup>+ </Dialog>+ );+}++function EnvironmentModelPrices({+ environment,+ models,+}: {+ readonly environment: EnvironmentPresentation;+ readonly models: readonly string[];+}) {+ const settings = useAtomValue(serverEnvironment.settingsValueAtom(environment.environmentId));+ const session = useEnvironmentSessionState(environment.environmentId);+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });+ const [form, setForm] = useState(usagePriceForm());+ const [editingModel, setEditingModel] = useState<string | null>(null);+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const prices = settings?.usagePriceOverrides ?? {};+ const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";+ const access = isPrimary+ ? resolvePrimaryOperateAccess({+ isPrimary,+ hasDesktopBridge: isElectron,+ session: session.data,+ isPending: session.isPending,+ hasError: session.hasError,+ })+ : resolveRemoteOperateAccess({+ session: session.data,+ isPending: session.isPending,+ hasError: session.hasError,+ });+ const supportsOverrides =+ environment.serverConfig?.environment.capabilities.usagePriceOverrides === true;+ const unavailable =+ environment.connection.phase !== "connected"+ ? "Connect this environment to change its model prices."+ : settings === null+ ? "Loading model prices..."+ : !supportsOverrides+ ? "Update this environment's server to set model prices."+ : access === "pending"+ ? "Checking permissions..."+ : access === "denied"+ ? "This session can view model prices but cannot change them."+ : null;+ const readOnly = unavailable !== null || pending;+ const parsed = parseUsagePriceForm(form);+ const duplicate = editingModel === null && parsed !== null && Object.hasOwn(prices, parsed.model);++ const reset = () => {+ setEditingModel(null);+ setForm(usagePriceForm());+ setError(null);+ };+ const save = async (model: string, price: UsageModelPriceOverride | null) => {+ if (readOnly) return;+ setPending(true);+ setError(null);+ try {+ const result = await updateSettings({+ environmentId: environment.environmentId,+ input: { patch: { usagePriceOverrides: { [model]: price } } },+ });+ if (result._tag === "Failure") {+ setError("Could not save model prices. Try again.");+ } else if (price !== null || editingModel === model) {+ reset();+ }+ } finally {+ setPending(false);+ }+ };++ return (+ <>+ {Object.keys(prices).length > 0 ? (+ <ul className="divide-y divide-border rounded-lg border border-border">+ {Object.entries(prices)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([model, price]) => (+ <li key={model} className="flex flex-wrap items-center gap-3 p-3">+ <div className="min-w-0 flex-1">+ <p className="break-all text-sm font-medium">{model}</p>+ <p className="text-xs text-muted-foreground">+ Input ${price.inputCostPerMillionTokens} · Output $+ {price.outputCostPerMillionTokens}+ <br />+ Cache read $+ {price.cacheReadCostPerMillionTokens ?? price.inputCostPerMillionTokens}+ {" · "}Cache write $+ {price.cacheWriteCostPerMillionTokens ?? price.inputCostPerMillionTokens}+ </p>+ </div>+ <Button+ variant="ghost"+ size="xs"+ disabled={readOnly}+ aria-label={`Edit price for ${model}`}+ onClick={() => {+ setEditingModel(model);+ setForm(usagePriceForm(model, price));+ setError(null);+ }}+ >+ Edit+ </Button>+ <Button+ variant="ghost"+ size="xs"+ disabled={readOnly}+ aria-label={`Remove price for ${model}`}+ onClick={() => void save(model, null)}+ >+ Remove+ </Button>+ </li>+ ))}+ </ul>+ ) : (+ <p className="text-sm text-muted-foreground">+ No custom prices. Public model pricing is used when available.+ </p>+ )}+ {unavailable ? <p className="text-sm text-muted-foreground">{unavailable}</p> : null}+ <form+ className="grid gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ if (parsed && !duplicate) void save(parsed.model, parsed.price);+ }}+ >+ <fieldset disabled={readOnly} className="grid min-w-0 gap-4">+ <legend className="mb-3 text-sm font-medium">+ {editingModel === null ? "Add model price" : "Edit model price"}+ </legend>+ <div className="grid gap-1.5">+ <Label htmlFor="usage-price-model">Model ID</Label>+ <Input+ id="usage-price-model"+ list="usage-price-models"+ value={form.model}+ disabled={editingModel !== null}+ placeholder="Exact model ID from usage"+ autoComplete="off"+ spellCheck={false}+ required+ onChange={(event) => setForm({ ...form, model: event.target.value })}+ />+ <datalist id="usage-price-models">+ {models.map((model) => (+ <option key={model} value={model} />+ ))}+ </datalist>+ {duplicate ? (+ <p role="alert" className="text-xs text-destructive">+ This model already has a price. Use Edit to change it.+ </p>+ ) : null}+ </div>+ <div className="grid grid-cols-2 gap-3">+ {USAGE_PRICE_FIELDS.map((field) => (+ <div key={field.key} className="grid gap-1.5">+ <Label htmlFor={`usage-price-${field.key}`}>+ {field.label}+ {field.optional ? " (optional)" : ""}+ </Label>+ <Input+ id={`usage-price-${field.key}`}+ type="number"+ min="0"+ step="any"+ inputMode="decimal"+ required={!field.optional}+ value={form[field.key]}+ placeholder={field.optional ? "Use input rate" : "0.00"}+ onChange={(event) => setForm({ ...form, [field.key]: event.target.value })}+ />+ </div>+ ))}+ </div>+ <p className="text-xs text-muted-foreground">+ Blank cache rates use the input price. Enter 0 for free tokens. Model IDs match exactly.+ Remove a price to restore automatic pricing.+ </p>+ {error ? (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ ) : null}+ <div className="flex justify-end gap-2">+ {editingModel !== null ? (+ <Button variant="outline" onClick={reset}>+ Cancel+ </Button>+ ) : null}+ <Button type="submit" disabled={parsed === null || duplicate || readOnly}>+ {pending ? "Saving..." : editingModel === null ? "Add price" : "Save price"}+ </Button>+ </div>+ </fieldset>+ </form>+ </>+ );+}diff --git a/apps/web/src/components/usage/usagePriceForm.test.ts b/apps/web/src/components/usage/usagePriceForm.test.tsnew file mode 100644index 00000000000..47c55565141--- /dev/null+++ b/apps/web/src/components/usage/usagePriceForm.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vite-plus/test";++import { parseUsagePriceForm, usagePriceForm } from "./usagePriceForm.ts";++describe("model price entry", () => {+ it("preserves exact model IDs and fractional rates", () => {+ expect(+ parseUsagePriceForm({+ ...usagePriceForm(),+ model: " vendor/Example-Model ",+ inputCostPerMillionTokens: "2.5",+ outputCostPerMillionTokens: "10",+ }),+ ).toEqual({+ model: "vendor/Example-Model",+ price: { inputCostPerMillionTokens: 2.5, outputCostPerMillionTokens: 10 },+ });+ });++ it("keeps free cache tokens distinct from blank cache prices", () => {+ const parsed = parseUsagePriceForm({+ ...usagePriceForm(),+ model: "example-model",+ inputCostPerMillionTokens: "2",+ outputCostPerMillionTokens: "8",+ cacheReadCostPerMillionTokens: "0",+ cacheWriteCostPerMillionTokens: " ",+ });+ expect(parsed?.price).toEqual({+ inputCostPerMillionTokens: 2,+ outputCostPerMillionTokens: 8,+ cacheReadCostPerMillionTokens: 0,+ });+ });++ it("preserves all prices when editing, including small fractional prices", () => {+ const price = {+ inputCostPerMillionTokens: 0,+ outputCostPerMillionTokens: 8,+ cacheReadCostPerMillionTokens: 0.0000001,+ cacheWriteCostPerMillionTokens: 3.5,+ };+ expect(parseUsagePriceForm(usagePriceForm("example-model", price))).toEqual({+ model: "example-model",+ price,+ });+ });++ it.each(["", " ", "-1", "Infinity", "NaN", "1e999", "$2", "0x10"])(+ "rejects invalid required prices: %j",+ (inputCostPerMillionTokens) => {+ expect(+ parseUsagePriceForm({+ ...usagePriceForm("example-model", {+ inputCostPerMillionTokens: 2,+ outputCostPerMillionTokens: 8,+ }),+ inputCostPerMillionTokens,+ }),+ ).toBeNull();+ },+ );++ it("rejects invalid optional rates and missing model IDs", () => {+ const form = usagePriceForm("example-model", {+ inputCostPerMillionTokens: 2,+ outputCostPerMillionTokens: 8,+ });+ expect(parseUsagePriceForm({ ...form, cacheReadCostPerMillionTokens: "-1" })).toBeNull();+ expect(parseUsagePriceForm({ ...form, cacheWriteCostPerMillionTokens: "invalid" })).toBeNull();+ expect(parseUsagePriceForm({ ...form, model: " " })).toBeNull();+ });+});diff --git a/apps/web/src/components/usage/usagePriceForm.ts b/apps/web/src/components/usage/usagePriceForm.tsnew file mode 100644index 00000000000..c52178300cd--- /dev/null+++ b/apps/web/src/components/usage/usagePriceForm.ts@@ -0,0 +1,62 @@+import type { UsageModelPriceOverride } from "@t3tools/contracts";++export const USAGE_PRICE_FIELDS = [+ { key: "inputCostPerMillionTokens", label: "Input", optional: false },+ { key: "outputCostPerMillionTokens", label: "Output", optional: false },+ { key: "cacheReadCostPerMillionTokens", label: "Cache read", optional: true },+ { key: "cacheWriteCostPerMillionTokens", label: "Cache write", optional: true },+] as const;++export type UsagePriceForm = { model: string } & Record<+ (typeof USAGE_PRICE_FIELDS)[number]["key"],+ string+>;++export function usagePriceForm(model = "", price?: UsageModelPriceOverride): UsagePriceForm {+ return {+ model,+ inputCostPerMillionTokens: price?.inputCostPerMillionTokens.toString() ?? "",+ outputCostPerMillionTokens: price?.outputCostPerMillionTokens.toString() ?? "",+ cacheReadCostPerMillionTokens: price?.cacheReadCostPerMillionTokens?.toString() ?? "",+ cacheWriteCostPerMillionTokens: price?.cacheWriteCostPerMillionTokens?.toString() ?? "",+ };+}++/** Blank cache prices use the input rate; explicit zero means free. */+export function parseUsagePriceForm(+ form: UsagePriceForm,+): { model: string; price: UsageModelPriceOverride } | null {+ const model = form.model.trim();+ if (model.length === 0) return null;+ const rates: Partial<Record<(typeof USAGE_PRICE_FIELDS)[number]["key"], number>> = {};+ for (const field of USAGE_PRICE_FIELDS) {+ const raw = form[field.key].trim();+ if (raw === "") {+ if (field.optional) continue;+ return null;+ }+ if (!/^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw)) return null;+ const value = Number(raw);+ if (!Number.isFinite(value) || value < 0) return null;+ rates[field.key] = value;+ }+ if (+ rates.inputCostPerMillionTokens === undefined ||+ rates.outputCostPerMillionTokens === undefined+ ) {+ return null;+ }+ return {+ model,+ price: {+ inputCostPerMillionTokens: rates.inputCostPerMillionTokens,+ outputCostPerMillionTokens: rates.outputCostPerMillionTokens,+ ...(rates.cacheReadCostPerMillionTokens === undefined+ ? {}+ : { cacheReadCostPerMillionTokens: rates.cacheReadCostPerMillionTokens }),+ ...(rates.cacheWriteCostPerMillionTokens === undefined+ ? {}+ : { cacheWriteCostPerMillionTokens: rates.cacheWriteCostPerMillionTokens }),+ },+ };+}diff --git a/docs/user/usage.md b/docs/user/usage.mdindex 3a61222be82..dc79a1e3074 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -12,6 +12,18 @@ record are missing from the totals.If recent work is missing or a new model shows no cost, refresh to rescan session history andupdate model pricing.+## Set custom model prices++On web or desktop, open **Usage → Model prices** to add, edit, or remove a model's estimated+price. Choose the environment whose history you want to price, then enter the exact model ID and+USD rates per million input and output tokens. You can enter any model ID, including models+without public pricing.++Cache read and cache write rates are optional and use the input rate when blank. Enter `0` for+tokens that are free. Saved prices replace automatic pricing for all of that environment's+history and are shared with clients connected to it. Set prices on each environment that needs+them. Removing a price restores automatic pricing.+## Track subscription limits**Usage → Limits** shows quota use and reset times for Codex and Claude subscriptions. It alsodiff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 4a2843abb80..7ba62a68148 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -807,6 +807,27 @@ export function createServerEnvironmentAtoms<R, E>(Atom.withLabel(`environment-data:server:settings:${environmentId}`),),);+ const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get) => {+ const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};+ // Only changed prices should trigger another transcript scan. Settings+ // snapshots can recreate the same mapping in a different property order.+ return JSON.stringify(+ Object.keys(overrides)+ .sort()+ .map((model) => {+ const price = overrides[model]!;+ return [+ model,+ price.inputCostPerMillionTokens,+ price.outputCostPerMillionTokens,+ price.cacheReadCostPerMillionTokens,+ price.cacheWriteCostPerMillionTokens,+ ];+ }),+ );+ }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),+ );const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(Atom.withLabel(`environment-data:server:providers:${environmentId}`),@@ -892,6 +913,7 @@ export function createServerEnvironmentAtoms<R, E>(label: "environment-data:server:usage-summary",tag: WS_METHODS.serverGetUsageSummary,staleTimeMs: 60_000,+ refreshTrigger: ({ environmentId }) => usagePricesAtom(environmentId),}),configProjection,welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {diff --git a/packages/client-runtime/src/state/serverUsage.test.ts b/packages/client-runtime/src/state/serverUsage.test.tsnew file mode 100644index 00000000000..9cf2667d8bc--- /dev/null+++ b/packages/client-runtime/src/state/serverUsage.test.ts@@ -0,0 +1,263 @@+import {+ DEFAULT_SERVER_SETTINGS,+ EnvironmentId,+ UsageDay,+ USAGE_CONTRACT_VERSION,+ WS_METHODS,+ type ServerConfig,+ type ServerConfigStreamEvent,+ type ServerSettings,+ type UsageSummary,+ type UsageSummaryInput,+} from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Queue from "effect/Queue";+import * as Stream from "effect/Stream";+import * as SubscriptionRef from "effect/SubscriptionRef";+import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";++import {+ AVAILABLE_CONNECTION_STATE,+ PrimaryConnectionTarget,+ type PreparedConnection,+ type SupervisorConnectionState,+} from "../connection/model.ts";+import { EnvironmentRegistry } from "../connection/registry.ts";+import { EnvironmentSupervisor } from "../connection/supervisor.ts";+import { EnvironmentCacheStore } from "../platform/persistence.ts";+import type { WsRpcProtocolClient } from "../rpc/protocol.ts";+import type { RpcSession } from "../rpc/session.ts";+import { createServerEnvironmentAtoms } from "./server.ts";++const TARGET = new PrimaryConnectionTarget({+ environmentId: EnvironmentId.make("usage-environment"),+ label: "Usage environment",+ httpBaseUrl: "https://environment.example.test",+ wsBaseUrl: "wss://environment.example.test",+});++const INPUT: UsageSummaryInput = {+ sinceDay: UsageDay.make("2026-09-01"),+ untilDay: UsageDay.make("2026-09-04"),+ timeZone: "UTC",+};++const CONFIG = {+ settings: DEFAULT_SERVER_SETTINGS,+ environment: { serverVersion: "0.0.1", capabilities: {} },+} as ServerConfig;++const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (+ beforeRead: (request: number) => Effect.Effect<void> = () => Effect.void,+) {+ const events = yield* Queue.unbounded<ServerConfigStreamEvent>();+ let settings = DEFAULT_SERVER_SETTINGS;+ let requests = 0;+ const client = {+ [WS_METHODS.subscribeServerConfig]: () =>+ Stream.concat(+ Stream.make({ version: 1 as const, type: "snapshot" as const, config: CONFIG }),+ Stream.fromQueue(events),+ ),+ [WS_METHODS.serverGetUsageSummary]: (input: UsageSummaryInput) =>+ Effect.gen(function* () {+ requests += 1;+ const price = settings.usagePriceOverrides["custom-model"]?.inputCostPerMillionTokens ?? 0;+ yield* beforeRead(requests);+ return {+ contractVersion: USAGE_CONTRACT_VERSION,+ readAt: "2026-09-04T12:00:00Z",+ ...input,+ buckets: [+ {+ day: input.sinceDay,+ provider: "codex",+ model: "custom-model",+ totals: {+ uncachedInputTokens: 1_000_000,+ cachedInputTokens: 0,+ cacheCreationTokens: 0,+ outputTokens: 0,+ reasoningTokens: 0,+ },+ costUsd: price,+ cacheSavingsUsd: 0,+ costSource: price === 0 ? "unpriced" : "modelPriced",+ records: 1,+ unpricedRecords: price === 0 ? 1 : 0,+ sessions: 1,+ },+ ],+ sources: [],+ pricing: { status: "unavailable", source: "test", fetchedAt: null, knownModels: 0 },+ scanDurationMs: 0,+ } satisfies UsageSummary;+ }),+ } as unknown as WsRpcProtocolClient;+ const session: RpcSession = {+ client,+ initialConfig: Effect.succeed(CONFIG),+ subscribeServerConfig: (input) => client.subscribeServerConfig(input),+ ready: Effect.void,+ probe: Effect.void,+ closed: Effect.never,+ };+ const supervisor = EnvironmentSupervisor.of({+ target: TARGET,+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({+ ...AVAILABLE_CONNECTION_STATE,+ phase: "connected",+ }),+ session: yield* SubscriptionRef.make(Option.some(session)),+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ });+ const environments = EnvironmentRegistry.of({+ run: (_environmentId, effect) =>+ Effect.provideService(effect, EnvironmentSupervisor, supervisor),+ followStream: (_environmentId, stream) =>+ Stream.provideService(stream, EnvironmentSupervisor, supervisor),+ } as EnvironmentRegistry["Service"]);+ const cache = EnvironmentCacheStore.of({+ loadShell: () => Effect.succeed(Option.none()),+ saveShell: () => Effect.void,+ loadThread: () => Effect.succeed(Option.none()),+ saveThread: () => Effect.void,+ removeThread: () => Effect.void,+ loadServerConfig: () => Effect.succeed(Option.none()),+ saveServerConfig: () => Effect.void,+ loadVcsRefs: () => Effect.succeed(Option.none()),+ saveVcsRefs: () => Effect.void,+ removeVcsRefs: () => Effect.void,+ clearVcsRefs: () => Effect.void,+ clear: () => Effect.void,+ });+ const runtime = Atom.runtime(+ Layer.merge(+ Layer.succeed(EnvironmentRegistry, environments),+ Layer.succeed(EnvironmentCacheStore, cache),+ ),+ );+ const initialConfigValueAtom = Atom.make(CONFIG);+ const atoms = createServerEnvironmentAtoms(runtime, {+ initialConfigValueAtom: () => initialConfigValueAtom,+ });+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>+ Effect.sync(() => registry.dispose()),+ );+ const updateSettings = Effect.fn("ServerUsageTest.updateSettings")(function* (+ next: ServerSettings,+ ) {+ settings = next;+ yield* Queue.offer(events, {+ version: 1,+ type: "settingsUpdated",+ payload: { settings },+ });+ yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(TARGET.environmentId)).pipe(+ Stream.filter((current) => current === next),+ Stream.runHead,+ );+ });+ return {+ registry,+ requests: () => requests,+ updateSettings,+ summary: (input = INPUT) => atoms.usageSummary({ environmentId: TARGET.environmentId, input }),+ };+});++function waitForCost<E>(+ registry: AtomRegistry.AtomRegistry,+ atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,+ cost: number,+) {+ return AtomRegistry.toStream(registry, atom).pipe(+ Stream.filter(+ (result) =>+ AsyncResult.isSuccess(result) &&+ !result.waiting &&+ result.value.buckets[0]?.costUsd === cost,+ ),+ Stream.runHead,+ );+}++it.effect("refreshes cached usage windows only when override prices change", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const harness = yield* makeHarness();+ const current = harness.summary();+ const previous = harness.summary({ ...INPUT, sinceDay: UsageDay.make("2026-08-01") });+ const unmountCurrent = harness.registry.mount(current);+ const unmountPrevious = harness.registry.mount(previous);+ yield* waitForCost(harness.registry, current, 0);+ yield* waitForCost(harness.registry, previous, 0);+ unmountPrevious();+ expect(harness.requests()).toBe(2);++ const prices = {+ "custom-model": { inputCostPerMillionTokens: 3, outputCostPerMillionTokens: 9 },+ "other-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 2 },+ };+ yield* harness.updateSettings({ ...DEFAULT_SERVER_SETTINGS, usagePriceOverrides: prices });+ yield* waitForCost(harness.registry, current, 3);+ yield* waitForCost(harness.registry, previous, 3);+ expect(harness.requests()).toBe(4);++ yield* harness.updateSettings({+ ...DEFAULT_SERVER_SETTINGS,+ usagePriceOverrides: {+ "other-model": { outputCostPerMillionTokens: 2, inputCostPerMillionTokens: 1 },+ "custom-model": { outputCostPerMillionTokens: 9, inputCostPerMillionTokens: 3 },+ },+ });+ yield* harness.updateSettings({+ ...DEFAULT_SERVER_SETTINGS,+ usagePriceOverrides: prices,+ defaultTheme: "custom-theme",+ });+ yield* harness.updateSettings(DEFAULT_SERVER_SETTINGS);+ yield* waitForCost(harness.registry, current, 0);+ yield* waitForCost(harness.registry, previous, 0);+ expect(harness.requests()).toBe(6);+ unmountCurrent();+ }),+ ),+);++it.effect("restarts a pending usage read after a price change", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const started = yield* Deferred.make<void>();+ const interrupted = yield* Deferred.make<void>();+ const harness = yield* makeHarness((request) =>+ request === 1+ ? Deferred.succeed(started, undefined).pipe(+ Effect.andThen(Effect.never),+ Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),+ )+ : Effect.void,+ );+ const summary = harness.summary();+ const unmount = harness.registry.mount(summary);+ yield* Deferred.await(started);+ yield* harness.updateSettings({+ ...DEFAULT_SERVER_SETTINGS,+ usagePriceOverrides: {+ "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },+ },+ });+ yield* waitForCost(harness.registry, summary, 5);+ yield* Deferred.await(interrupted);+ expect(harness.requests()).toBe(2);+ unmount();+ }),+ ),+);diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 8d03a73b024..38347ebc92b 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -105,6 +105,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({/** Server streams quota from configured usage-limit sources. Sameversion-skew contract as environmentThemes. */usageLimitSources: Schema.optionalKey(Schema.Boolean),+ /** Server persists custom model rates and applies them to usage summaries. */+ usagePriceOverrides: Schema.optionalKey(Schema.Boolean),/** Server understands thread.pin / thread.unpin commands. Sameversion-skew contract as threadSettlement. */threadPinning: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsindex 5d4c1573ef7..bee5c9a3f0d 100644--- a/packages/contracts/src/settings.test.ts+++ b/packages/contracts/src/settings.test.ts@@ -21,6 +21,58 @@ const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);const encodeServerSettings = Schema.encodeSync(ServerSettings);const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);+describe("ServerSettings usage price overrides", () => {+ const prices = { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 };++ it("defaults to automatic pricing and round-trips arbitrary model IDs", () => {+ expect(decodeServerSettings({}).usagePriceOverrides).toEqual({});+ const settings = decodeServerSettings({+ usagePriceOverrides: { " vendor/example-model ": prices },+ });+ expect(encodeServerSettings(settings).usagePriceOverrides).toEqual({+ "vendor/example-model": prices,+ });+ });++ it("accepts zero rates, optional cache rates, and per-model deletion", () => {+ const overrides = {+ "example-model": {+ inputCostPerMillionTokens: 0,+ outputCostPerMillionTokens: 0,+ cacheReadCostPerMillionTokens: 0.5,+ cacheWriteCostPerMillionTokens: 3,+ },+ "removed-model": null,+ };+ expect(+ decodeServerSettingsPatch({ usagePriceOverrides: overrides }).usagePriceOverrides,+ ).toEqual(overrides);+ });++ it.each([+ "inputCostPerMillionTokens",+ "outputCostPerMillionTokens",+ "cacheReadCostPerMillionTokens",+ "cacheWriteCostPerMillionTokens",+ ])("rejects invalid %s rates at the settings boundary", (field) => {+ for (const value of [-1, Number.NaN, Number.POSITIVE_INFINITY, "2"]) {+ const usagePriceOverrides = { "example-model": { ...prices, [field]: value } };+ expect(() => decodeServerSettings({ usagePriceOverrides })).toThrow();+ expect(() => decodeServerSettingsPatch({ usagePriceOverrides })).toThrow();+ }+ });++ it("rejects empty model IDs and incomplete input/output pricing", () => {+ for (const usagePriceOverrides of [+ { " ": prices },+ { "example-model": { inputCostPerMillionTokens: 2 } },+ { "example-model": { outputCostPerMillionTokens: 8 } },+ ]) {+ expect(() => decodeServerSettingsPatch({ usagePriceOverrides })).toThrow();+ }+ });+});+describe("ClaudeSettings auto-compaction", () => {it("uses Claude's default threshold when no override is configured", () => {expect(decodeClaudeSettings({}).autoCompactWindow).toBe("");diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex fef3b2992f0..cd4b12713ed 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -358,6 +358,20 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS// ── Server Settings (server-authoritative) ────────────────────+const UsageModelTokenPrice = Schema.Number.check(+ Schema.isFinite(),+ Schema.isGreaterThanOrEqualTo(0),+);++/** USD per million tokens. Omitted cache rates use the input rate. */+export const UsageModelPriceOverride = Schema.Struct({+ inputCostPerMillionTokens: UsageModelTokenPrice,+ outputCostPerMillionTokens: UsageModelTokenPrice,+ cacheReadCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),+ cacheWriteCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),+});+export type UsageModelPriceOverride = typeof UsageModelPriceOverride.Type;+const makeBinaryPathSetting = (fallback: string) =>TrimmedString.pipe(Schema.decodeTo(@@ -930,6 +944,10 @@ export const ServerSettings = Schema.Struct({usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(Schema.withDecodingDefault(Effect.succeed({})),),+ /** Exact model IDs, applied to past and future usage on this environment. */+ usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(+ Schema.withDecodingDefault(Effect.succeed({})),+ ),});export type ServerSettings = typeof ServerSettings.Type;@@ -1141,6 +1159,10 @@ export const ServerSettingsPatch = Schema.Struct({usageLimitSources: Schema.optionalKey(Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),),+ /** Each entry replaces one model's rates; `null` restores automatic pricing. */+ usagePriceOverrides: Schema.optionalKey(+ Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),+ ),});export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.tsindex 8c099ddb33a..c36a4557c29 100644--- a/packages/contracts/src/usage.ts+++ b/packages/contracts/src/usage.ts@@ -55,7 +55,7 @@ export type UsageResolution = typeof UsageResolution.Type;* Why a bucket's cost is what it is.** - `providerReported` - the transcript carried an explicit cost figure.- * - `modelPriced` - we matched the model against the LiteLLM rate table.+ * - `modelPriced` - we used a custom price override or the LiteLLM rate table.* - `unpriced` - tokens are known, rates are not. Counted in totals, excluded* from cost.*/diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.tsindex 64b0e1b8337..1f847412b6c 100644--- a/packages/shared/src/serverSettings.test.ts+++ b/packages/shared/src/serverSettings.test.ts@@ -322,6 +322,28 @@ describe("serverSettings helpers", () => {expect(Object.keys(removed.usageLimitSources)).toEqual([hubB]);});+ it("replaces and removes individual usage prices without clobbering other models", () => {+ const prices = { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 };+ const current = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {+ usagePriceOverrides: { "example-model": { ...prices, cacheReadCostPerMillionTokens: 0.5 } },+ });+ const added = applyServerSettingsPatch(current, {+ usagePriceOverrides: { "other-model": prices },+ });+ const replaced = applyServerSettingsPatch(added, {+ usagePriceOverrides: { "example-model": prices },+ });+ expect(replaced.usagePriceOverrides).toEqual({+ "example-model": prices,+ "other-model": prices,+ });+ const removed = applyServerSettingsPatch(replaced, {+ usagePriceOverrides: { "example-model": null },+ });+ expect(removed.usagePriceOverrides).toEqual({ "other-model": prices });+ expect(current.usagePriceOverrides["example-model"]?.cacheReadCostPerMillionTokens).toBe(0.5);+ });+it("stores background activity profiles as a versioned object and syncs legacy aliases", () => {const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {backgroundActivity: {diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.tsindex 67f73f84063..dfd5b742e4e 100644--- a/packages/shared/src/serverSettings.ts+++ b/packages/shared/src/serverSettings.ts@@ -123,10 +123,10 @@ function mergeModelSelectionOptionsById(input: {}/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */-function mergeUsageLimitSources(- current: ServerSettings["usageLimitSources"],- patch: NonNullable<ServerSettingsPatch["usageLimitSources"]>,-): ServerSettings["usageLimitSources"] {+function mergeSettingsEntries<Value>(+ current: Readonly<Record<string, Value>>,+ patch: Readonly<Record<string, Value | null>>,+): Record<string, Value> {const next = new Map(Object.entries(current));for (const [id, config] of Object.entries(patch)) {if (config === null) {@@ -135,7 +135,7 @@ function mergeUsageLimitSources(next.set(id, config);}}- return Object.fromEntries(next) as ServerSettings["usageLimitSources"];+ return Object.fromEntries(next);}export function applyServerSettingsPatch(@@ -150,6 +150,7 @@ export function applyServerSettingsPatch(backgroundActivity,// Merged per entry below; its `null` removals must not reach deepMerge.usageLimitSources: usageLimitSourcesPatch,+ usagePriceOverrides: usagePriceOverridesPatch,...patchForMerge} = patch;const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);@@ -208,12 +209,20 @@ export function applyServerSettingsPatch(: {}),...(usageLimitSourcesPatch !== undefined? {- usageLimitSources: mergeUsageLimitSources(+ usageLimitSources: mergeSettingsEntries(current.usageLimitSources,usageLimitSourcesPatch,),}: {}),+ ...(usagePriceOverridesPatch !== undefined+ ? {+ usagePriceOverrides: mergeSettingsEntries(+ current.usagePriceOverrides,+ usagePriceOverridesPatch,+ ),+ }+ : {}),...(patch.sourceControlWriterModelSelection !== undefined? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }: {}),