feat(opencode): surface context-window usage and session cost on the meter #8659
Closedardevdevts(GitHub profile, opens in a new tab)wants to merge 12 commits into
main fromrefs/pull/8659/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2014Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1478,0 +1617,21 @@1617+ return;1618+ }1619+ const modelKey = `${providerID}/${modelID}`;1620+ if (context.maxTokensModelKey === modelKey) {1621+ return;1622+ }1623+ const outcome = yield* runOpenCodeSdk("provider.list", () =>1624+ context.client.provider.list(),1625+ ).pipe(1626+ Effect.map((response) => {1627+ const providers = response.data?.all;1628+ if (!Array.isArray(providers)) {1629+ return undefined;1630+ }1631+ const provider = providers.find((entry) => entry.id === providerID);1632+ const limit = provider?.models?.[modelID]?.limit?.context;1633+ return typeof limit === "number" && Number.isFinite(limit) && limit > 01634+ ? Math.round(limit)1635+ : undefined;1636+ }),1637+ Effect.exit,
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1626OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1478,0 +1606,21 @@1606+ * unset and the meter renders the raw token count. A failed or timed-out1607+ * catalog call does not count as resolved, so a transient failure retries1608+ * on the next `session.updated`. Uses the same v1 `provider.list` endpoint1609+ * the runtime already relies on for inventory, so the response shape is1610+ * proven. Bounded by a short timeout because it runs on the event-pump1611+ * path: a wedged catalog request must leave `maxTokens` unresolved rather1612+ * than stall assistant deltas, requests, and turn completions.1613+ */1614+ const resolveOpenCodeMaxTokens = Effect.fn("resolveOpenCodeMaxTokens")(function* (1615+ context: OpenCodeSessionContext,1616+ providerID: string | undefined,1617+ modelID: string | undefined,1618+ ) {1619+ if (!providerID || !modelID) {1620+ return;1621+ }1622+ const modelKey = `${providerID}/${modelID}`;1623+ if (context.maxTokensModelKey === modelKey) {1624+ return;1625+ }1626+ const outcome = yield* runOpenCodeSdk("provider.list", () =>
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2021Resolvedby ardevdevts(GitHub profile, opens in a new tab)@@ -1562,0 +1723,21 @@1723+ Effect.map((response) => {1724+ const providers = response.data?.all;1725+ if (!Array.isArray(providers)) {1726+ return undefined;1727+ }1728+ const provider = providers.find((entry) => entry.id === providerID);1729+ const limit = provider?.models?.[modelID]?.limit?.context;1730+ return typeof limit === "number" && Number.isFinite(limit) && limit > 01731+ ? Math.round(limit)1732+ : undefined;1733+ }),1734+ // Event-pump path: never let an unresolved catalog request hold the1735+ // pump hostage. The timeout surfaces as a failure, which leaves the1736+ // model unresolved so the next `session.updated` retries.1737+ Effect.timeout("5 seconds"),1738+ Effect.exit,1739+ );1740+ if (Exit.isSuccess(outcome)) {1741+ context.maxTokensModelKey = modelKey;1742+ context.maxTokens = outcome.value;1743+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2119Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1634,0 +2070,21 @@2070+ readonly cost: number | null;2071+ readonly modelKey: string | null;2072+ readonly dedupeKey: string | undefined;2073+ readonly turnId: TurnId | undefined;2074+ },2075+ ): void => {2076+ const { tokens, cost, modelKey, dedupeKey, turnId } = input;2077+ if (2078+ tokens.input + tokens.output + tokens.cache.read + tokens.cache.write === 0 &&2079+ tokens.total === undefined2080+ ) {2081+ return;2082+ }2083+ if (dedupeKey !== undefined) {2084+ const owningTurn = context.contributionTurnMap.get(dedupeKey);2085+ if (owningTurn !== undefined) {2086+ if (turnId === undefined || owningTurn !== turnId) {2087+ return;2088+ }2089+ } else if (turnId !== undefined) {2090+ context.contributionTurnMap.set(dedupeKey, turnId);apps/server/src/provider/Layers/OpenCodeAdapter.ts lines 243 to 244OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -90,0 +224,21 @@224+ const cacheRaw = record.cache;225+ let cacheRead = 0;226+ let cacheWrite = 0;227+ if (typeof cacheRaw === "object" && cacheRaw !== null) {228+ const cache = cacheRaw as Record<string, unknown>;229+ cacheRead = typeof cache.read === "number" ? cache.read : 0;230+ cacheWrite = typeof cache.write === "number" ? cache.write : 0;231+ }232+ const total = typeof record.total === "number" ? record.total : undefined;233+ return {234+ input,235+ output,236+ reasoning,237+ cache: { read: cacheRead, write: cacheWrite },238+ ...(total !== undefined ? { total } : {}),239+ };240+}241+242+function mergeOpenCodeTurnTokens(a: OpenCodeTurnTokens, b: OpenCodeTurnTokens): OpenCodeTurnTokens {243+ const totalA = a.total ?? a.input + a.output + a.cache.read + a.cache.write;244+ const totalB = b.total ?? b.input + b.output + b.cache.read + b.cache.write;
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2106OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1634,0 +2086,21 @@2086+ * skipped, so e.g. compaction summaries never populate the ledger. A2087+ * report whose key was already seen under a *different* turn is a late2088+ * event from a prior turn and is fenced out instead of contaminating the2089+ * new turn's totals. Reports for any other turn (or no turn) are ignored:2090+ * only the active turn accumulates. Part-level reports feed turn2091+ * accounting only — the context-window meter keeps reflecting2092+ * latest-message occupancy plus session cumulative totals.2093+ */2094+ const recordOpenCodeTurnContribution = (2095+ context: OpenCodeSessionContext,2096+ input: {2097+ readonly tokens: OpenCodeTurnTokens;2098+ readonly cost: number | null;2099+ readonly modelKey: string | null;2100+ readonly dedupeKey: string | undefined;2101+ readonly turnId: TurnId | undefined;2102+ },2103+ ): void => {2104+ const { tokens, cost, modelKey, dedupeKey, turnId } = input;2105+ if (2106+ tokens.input + tokens.output + tokens.cache.read + tokens.cache.write === 0 &&
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2894OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2318,0 +2874,21 @@2874+ if (info.role === "assistant") {2875+ if (info.tokens) {2876+ const counts = normalizeOpenCodeTokenCounts(info.tokens);2877+ // Zero-token updates (e.g. compaction summary messages) must2878+ // not clobber the meter's per-message usage with nothing; keep2879+ // the last assistant message that actually reported usage.2880+ if (counts.input + counts.cacheRead + counts.cacheWrite > 0) {2881+ context.lastMessageTokenCounts = counts;2882+ yield* emitOpenCodeTokenUsage(context, { turnId, raw: event });2883+ }2884+ }2885+ // Per-turn contribution ledger (ported from #8918): same-id2886+ // re-emissions replace that message's report, distinct ids2887+ // (tool steps) each contribute; merged on turn completion into2888+ // `usage`/`modelUsage`/`totalCostUsd`. Deliberately message-level2889+ // only: part-level reports have unproven overlap semantics with2890+ // their parent message totals, and none of the preserved cases2891+ // exercise them.2892+ const contributionTokens = readOpenCodeTurnTokens(info.tokens);2893+ if (contributionTokens) {2894+ recordOpenCodeTurnContribution(context, {
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
0a20ac01-005b-431a-bc60-299cca213b4bYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.