Skip to content

Commit e7c94f6

Browse files
committed
feat: support configurable cost display currency
Add a display.currency config option that converts usage costs to the user's preferred currency at presentation boundaries (ACP usage_update, TUI, and app). The provider/model currency remains the source currency: when no display currency is configured, costs are shown unchanged in the source currency, and amounts are never relabeled when conversion is impossible (unknown rate). - Add Currency core module: approximate USD-based display rate table, convert() with user rate overrides, and locale-aware format() - Add display.currency and display.rates to the config schema - Convert in both ACP usage_update paths (Effect layer and ACP client) - Replace hardcoded USD formatters in TUI (sidebar, prompt, subagent footer) and app (context usage, context tab) with the shared utility - Regenerate SDK types and document the new options Relates to anomalyco#32485. Supersedes the approach explored in anomalyco#32487 and builds on provider-currency propagation from anomalyco#39425.
1 parent b41c0c9 commit e7c94f6

17 files changed

Lines changed: 488 additions & 59 deletions

File tree

‎packages/app/src/components/session-context-usage.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { getSessionContext } from "@/components/session/session-context-metrics"
1616
import { useSessionLayout } from "@/pages/session/session-layout"
1717
import { createSessionTabs } from "@/pages/session/helpers"
1818
import { useSettings } from "@/context/settings"
19+
import { createSessionContextFormatter } from "@/components/session/session-context-format"
1920

2021
interface SessionContextUsageProps {
2122
variant?: "button" | "indicator"
@@ -65,17 +66,11 @@ export function SessionContextUsage(props: SessionContextUsageProps) {
6566
const messages = createMemo(() => (params.id ? (sync().data.message[params.id] ?? []) : []))
6667
const info = createMemo(() => (params.id ? sync().session.get(params.id) : undefined))
6768

68-
const usd = createMemo(
69-
() =>
70-
new Intl.NumberFormat(language.intl(), {
71-
style: "currency",
72-
currency: "USD",
73-
}),
74-
)
69+
const formatter = createMemo(() => createSessionContextFormatter(language.intl()))
7570

7671
const context = createMemo(() => getSessionContext(messages(), [...providers.all().values()]))
7772
const cost = createMemo(() => {
78-
return usd().format(info()?.cost ?? 0)
73+
return formatter().cost(info()?.cost ?? 0, context()?.model?.cost?.currency ?? "USD", sync().data.config.display)
7974
})
8075
const contextVisible = createMemo(() => view().reviewPanel.opened() && tabState.activeTab() === "context")
8176
const hasOtherTabs = createMemo(() =>

‎packages/app/src/components/session/session-context-format.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { DateTime } from "luxon"
2+
import { Currency } from "@opencode-ai/core/currency"
23

34
export function createSessionContextFormatter(locale: string) {
45
return {
@@ -16,5 +17,16 @@ export function createSessionContextFormatter(locale: string) {
1617
if (!value) return "—"
1718
return DateTime.fromMillis(value).setLocale(locale).toLocaleString(DateTime.DATETIME_MED)
1819
},
20+
cost(
21+
amount: number,
22+
source: string,
23+
display: { currency?: string; exchangeRates?: Record<string, number> } | undefined,
24+
) {
25+
const target = display?.currency?.trim()
26+
if (!target) return Currency.format(amount, source, locale)
27+
const converted = Currency.convert(amount, source, target, display?.exchangeRates)
28+
if (converted === undefined) return Currency.format(amount, source, locale)
29+
return Currency.format(converted, target, locale)
30+
},
1931
}
2032
}

‎packages/app/src/components/session/session-context-metrics.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ type Model = {
1111
limit: {
1212
context: number
1313
}
14+
cost?: {
15+
currency?: string
16+
}
1417
}
1518

1619
type Context = {

‎packages/app/src/components/session/session-context-tab.tsx‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -130,19 +130,11 @@ export function SessionContextTab() {
130130
{ equals: same },
131131
)
132132

133-
const usd = createMemo(
134-
() =>
135-
new Intl.NumberFormat(language.intl(), {
136-
style: "currency",
137-
currency: "USD",
138-
}),
139-
)
140-
141133
const ctx = createMemo(() => getSessionContext(messages(), [...providers.all().values()]))
142134
const formatter = createMemo(() => createSessionContextFormatter(language.intl()))
143135

144136
const cost = createMemo(() => {
145-
return usd().format(info()?.cost ?? 0)
137+
return formatter().cost(info()?.cost ?? 0, ctx()?.model?.cost?.currency ?? "USD", sync().data.config.display)
146138
})
147139

148140
const counts = createMemo(() => {

‎packages/core/src/currency.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
export * as Currency from "./currency"
2+
3+
// Approximate display exchange rates, units per 1 USD. Snapshot: 2026-08.
4+
// These are display-only approximations and are never billing-authoritative.
5+
export const ExchangeRates: Readonly<Record<string, number>> = {
6+
USD: 1,
7+
EUR: 0.86,
8+
GBP: 0.74,
9+
JPY: 147.5,
10+
CNY: 7.15,
11+
HKD: 7.8,
12+
SGD: 1.34,
13+
KRW: 1380,
14+
INR: 84,
15+
CAD: 1.37,
16+
AUD: 1.52,
17+
NZD: 1.68,
18+
CHF: 0.8,
19+
SEK: 10.5,
20+
NOK: 10.8,
21+
DKK: 6.9,
22+
PLN: 3.9,
23+
BRL: 5.4,
24+
MXN: 18.5,
25+
ZAR: 18,
26+
}
27+
28+
export function normalize(currency: string): string {
29+
return currency.trim().toUpperCase()
30+
}
31+
32+
export function rate(currency: string, overrides?: Readonly<Record<string, number>>): number | undefined {
33+
const code = normalize(currency)
34+
if (overrides) {
35+
const matches = Object.entries(overrides).filter(([key]) => normalize(key) === code)
36+
if (matches.length > 0) {
37+
for (const [, value] of matches) {
38+
if (typeof value === "number" && Number.isFinite(value) && value > 0) return value
39+
}
40+
return undefined
41+
}
42+
}
43+
const builtin = ExchangeRates[code]
44+
if (typeof builtin === "number" && builtin > 0) return builtin
45+
return undefined
46+
}
47+
48+
export function convert(
49+
amount: number,
50+
from: string,
51+
to: string,
52+
rates?: Readonly<Record<string, number>>,
53+
): number | undefined {
54+
const source = normalize(from)
55+
const target = normalize(to)
56+
if (source === target) return amount
57+
const fromRate = rate(source, rates)
58+
const toRate = rate(target, rates)
59+
if (!fromRate || !toRate) return undefined
60+
return (amount / fromRate) * toRate
61+
}
62+
63+
const formatters = new Map<string, Intl.NumberFormat>()
64+
65+
export function format(amount: number, currency: string, locale = "en-US"): string {
66+
const code = normalize(currency)
67+
const key = `${locale}\u0000${code}`
68+
let formatter = formatters.get(key)
69+
if (!formatter) {
70+
try {
71+
formatter = new Intl.NumberFormat(locale, { style: "currency", currency: code })
72+
} catch {
73+
return `${amount.toFixed(2)} ${code}`
74+
}
75+
formatters.set(key, formatter)
76+
}
77+
return formatter.format(amount)
78+
}

‎packages/core/src/v1/config/config.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,21 @@ export const Info = Schema.Struct({
125125
description: "Additional instruction files or patterns to include",
126126
}),
127127
layout: Schema.optional(ConfigLayoutV1.Layout).annotate({ description: "@deprecated Always uses stretch layout." }),
128+
display: Schema.optional(
129+
Schema.Struct({
130+
currency: Schema.optional(Schema.String).annotate({
131+
description:
132+
'Preferred display currency (ISO 4217 code, e.g. "CNY") for usage costs. When unset, costs are shown in the provider\'s source currency.',
133+
}),
134+
exchangeRates: Schema.optional(Schema.Record(Schema.String, Schema.Finite)).annotate({
135+
description:
136+
"Custom exchange rates as units per 1 USD. Take precedence over the built-in approximate display rates. An invalid rate disables conversion for that currency.",
137+
}),
138+
}),
139+
).annotate({
140+
description:
141+
"Presentation options. The display currency only affects how usage costs are shown; amounts are never relabeled without conversion.",
142+
}),
128143
permission: Schema.optional(ConfigPermissionV1.Info),
129144
tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
130145
attachment: Schema.optional(ConfigAttachmentV1.Info).annotate({
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { Currency } from "@opencode-ai/core/currency"
3+
4+
describe("currency", () => {
5+
test("identity conversion returns the amount unchanged", () => {
6+
expect(Currency.convert(1.5, "USD", "USD")).toBe(1.5)
7+
})
8+
9+
test("identity conversion ignores case and whitespace", () => {
10+
expect(Currency.convert(2.25, " usd ", "USD")).toBe(2.25)
11+
})
12+
13+
test("converts between builtin rates", () => {
14+
expect(Currency.convert(1.5, "USD", "CNY")).toBeCloseTo(1.5 * 7.15, 10)
15+
})
16+
17+
test("converts via USD cross rate", () => {
18+
expect(Currency.convert(10, "EUR", "CNY")).toBeCloseTo((10 / 0.86) * 7.15, 10)
19+
})
20+
21+
test("normalizes currency codes", () => {
22+
expect(Currency.convert(1, " cny ", "usd")).toBeCloseTo(1 / 7.15, 10)
23+
})
24+
25+
test("overrides take precedence over builtin rates", () => {
26+
expect(Currency.convert(1.5, "USD", "CNY", { CNY: 7.2 })).toBeCloseTo(1.5 * 7.2, 10)
27+
})
28+
29+
test("overrides can introduce currencies missing from the builtin table", () => {
30+
expect(Currency.convert(2, "USD", "BTC", { BTC: 0.00001 })).toBeCloseTo(0.00002, 12)
31+
})
32+
33+
test("override lookup ignores key casing", () => {
34+
expect(Currency.convert(1.5, "USD", "CNY", { cny: 7.2 })).toBeCloseTo(1.5 * 7.2, 10)
35+
})
36+
37+
test("returns undefined when a rate is unknown", () => {
38+
expect(Currency.convert(1, "USD", "XYZ")).toBeUndefined()
39+
expect(Currency.convert(1, "XYZ", "USD")).toBeUndefined()
40+
})
41+
42+
test("returns undefined when the source currency is missing or empty", () => {
43+
expect(Currency.convert(1, "", "USD")).toBeUndefined()
44+
expect(Currency.convert(1, " ", "CNY")).toBeUndefined()
45+
})
46+
47+
test("an invalid override disables conversion instead of falling back", () => {
48+
expect(Currency.convert(1, "USD", "CNY", { CNY: 0 })).toBeUndefined()
49+
expect(Currency.convert(1, "USD", "CNY", { CNY: -7 })).toBeUndefined()
50+
expect(Currency.convert(1, "USD", "CNY", { CNY: Number.NaN })).toBeUndefined()
51+
})
52+
53+
test("invalid overrides do not introduce unknown currencies", () => {
54+
expect(Currency.convert(1, "USD", "XYZ", { XYZ: 0 })).toBeUndefined()
55+
})
56+
57+
test("rate resolves overrides before builtin table", () => {
58+
expect(Currency.rate("CNY")).toBe(7.15)
59+
expect(Currency.rate("CNY", { CNY: 7.2 })).toBe(7.2)
60+
expect(Currency.rate("CNY", { CNY: 0 })).toBeUndefined()
61+
expect(Currency.rate("XYZ")).toBeUndefined()
62+
})
63+
64+
test("formats amounts with the currency symbol", () => {
65+
expect(Currency.format(10.8, "CNY")).toContain("10.8")
66+
expect(Currency.format(10.8, "USD")).toContain("10.8")
67+
})
68+
69+
test("format falls back to a plain label for codes Intl rejects", () => {
70+
expect(Currency.format(1.234, "X")).toBe("1.23 X")
71+
})
72+
})

‎packages/opencode/src/acp/service.ts‎

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,7 @@ function makeDirectoryService(sdk: OpencodeClient) {
617617
function makeUsageService(sdk: OpencodeClient) {
618618
const limits = new Map<string, Promise<number | undefined>>()
619619
const currencies = new Map<string, Promise<string>>()
620+
const displays = new Map<string, Promise<Parameters<typeof UsageService.displayCost>[2]>>()
620621
const contextLimit: UsageService.Interface["contextLimit"] = Effect.fn("ACP.promptUsage.contextLimit")(
621622
function* (params) {
622623
const key = `${params.directory}\u0000${params.providerID}\u0000${params.modelID}`
@@ -637,25 +638,39 @@ function makeUsageService(sdk: OpencodeClient) {
637638
},
638639
)
639640

640-
const modelCurrency = Effect.fn("ACP.promptUsage.modelCurrency")(
641-
function* (params: { readonly directory: string; readonly providerID: ProviderV2.ID; readonly modelID: ModelV2.ID }) {
642-
const key = `${params.directory}\u0000${params.providerID}\u0000${params.modelID}`
643-
const current = currencies.get(key)
644-
if (current) return yield* Effect.promise(() => current)
641+
const modelCurrency = Effect.fn("ACP.promptUsage.modelCurrency")(function* (params: {
642+
readonly directory: string
643+
readonly providerID: ProviderV2.ID
644+
readonly modelID: ModelV2.ID
645+
}) {
646+
const key = `${params.directory}\u0000${params.providerID}\u0000${params.modelID}`
647+
const current = currencies.get(key)
648+
if (current) return yield* Effect.promise(() => current)
649+
650+
const next = sdk.config
651+
.providers({ directory: params.directory }, { throwOnError: true })
652+
.then((response) => {
653+
const providers = Object.fromEntries(
654+
(response.data?.providers ?? []).map((provider) => [provider.id, provider]),
655+
) as Record<ProviderV2.ID, Provider.Info>
656+
return UsageService.findCurrency(providers, params.providerID, params.modelID)
657+
})
658+
.catch(() => "USD")
659+
currencies.set(key, next)
660+
return yield* Effect.promise(() => next)
661+
})
645662

646-
const next = sdk.config
647-
.providers({ directory: params.directory }, { throwOnError: true })
648-
.then((response) => {
649-
const providers = Object.fromEntries(
650-
(response.data?.providers ?? []).map((provider) => [provider.id, provider]),
651-
) as Record<ProviderV2.ID, Provider.Info>
652-
return UsageService.findCurrency(providers, params.providerID, params.modelID)
653-
})
654-
.catch(() => "USD")
655-
currencies.set(key, next)
656-
return yield* Effect.promise(() => next)
657-
},
658-
)
663+
const displayConfig = Effect.fn("ACP.promptUsage.displayConfig")(function* (params: { readonly directory: string }) {
664+
const current = displays.get(params.directory)
665+
if (current) return yield* Effect.promise(() => current)
666+
667+
const next = sdk.config
668+
.get({ directory: params.directory }, { throwOnError: true })
669+
.then((response) => response.data?.display)
670+
.catch(() => undefined)
671+
displays.set(params.directory, next)
672+
return yield* Effect.promise(() => next)
673+
})
659674

660675
const sendUpdate: UsageService.Interface["sendUpdate"] = Effect.fn("ACP.promptUsage.sendUpdate")(function* (params) {
661676
const messages = yield* request(
@@ -692,6 +707,9 @@ function makeUsageService(sdk: OpencodeClient) {
692707
modelID: ModelV2.ID.make(message.modelID),
693708
})
694709

710+
const display = yield* displayConfig({ directory: params.directory })
711+
const cost = UsageService.displayCost(UsageService.totalSessionCost(messages), currency, display)
712+
695713
yield* Effect.promise(() =>
696714
params.connection
697715
.sessionUpdate({
@@ -700,7 +718,7 @@ function makeUsageService(sdk: OpencodeClient) {
700718
sessionUpdate: "usage_update",
701719
used: UsageService.contextTokens(message),
702720
size,
703-
cost: { amount: UsageService.totalSessionCost(messages), currency },
721+
cost,
704722
},
705723
})
706724
.catch(() => {}),

0 commit comments

Comments
 (0)