The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 16:00 UTC
fix(opencode): OpenCode 1.x threads report context-window usage (#36430)
Julius Marminge committed
Nov 13, 2026 at 15:36 UTC
eb14ddb79924a6cbcb6c26d1b97c9816c9732c55
3 files changed
+88
-18
packages/provider-opencode/src/server/OpenCodeRuntime.ts
+31
-18
@@ -267,24 +267,23 @@ export interface ParsedOpenCodeModelSlug {
267
readonly modelID: string;
268
}
269
270
-export type OpenCodeVariantCache = Map<string, ReadonlySet<string> | undefined>;
270
+export interface OpenCodeCatalogModel {
271
+ readonly variants: ReadonlySet<string>;
272
+ readonly contextWindow: number | undefined;
273
+}
274
272
-export const resolveOpenCodeVariant = Effect.fnUntraced(function* (
275
+export type OpenCodeVariantCache = Map<string, OpenCodeCatalogModel | undefined>;
276
+
277
+/** The model's catalog entry; a failed read returns undefined and is not cached. */
278
+export const readOpenCodeCatalogModel = Effect.fnUntraced(function* (
279
client: OpencodeClient,
274
- model: ParsedOpenCodeModelSlug | undefined,
275
- variant: string | undefined,
280
+ model: ParsedOpenCodeModelSlug,
281
abortSignal?: AbortSignal,
282
cache?: OpenCodeVariantCache,
283
) {
279
- if (!variant || !model) return variant;
280
-
284
const key = `${model.providerID}/${model.modelID}`;
282
- const cached = cache?.get(key);
283
- if (cache?.has(key)) {
284
- return cached !== undefined && !cached.has(variant) ? undefined : variant;
285
- }
285
+ if (cache?.has(key)) return cache.get(key);
286
287
- // Only a confirmed catalog mismatch can invalidate a persisted selection.
287
const response = yield* runOpenCodeSdk("provider.list", (signal) =>
288
client.provider.list(undefined, {
289
signal: abortSignal ? AbortSignal.any([signal, abortSignal]) : signal,
@@ -293,16 +292,30 @@ export const resolveOpenCodeVariant = Effect.fnUntraced(function* (
292
Effect.timeout("10 seconds"),
293
Effect.orElseSucceed(() => undefined),
294
);
296
- if (response?.data === undefined) return variant;
295
+ if (response?.data === undefined) return undefined;
296
297
const catalogModel = response.data.all.find((provider) => provider.id === model.providerID)
298
?.models[model.modelID];
300
- const variants = catalogModel ? new Set(Object.keys(catalogModel.variants ?? {})) : undefined;
301
- if (cache !== undefined) {
302
- // Keep only this model's names; provider.list can return several megabytes.
303
- cache.set(key, variants);
304
- }
305
- return variants !== undefined && !variants.has(variant) ? undefined : variant;
299
+ const entry: OpenCodeCatalogModel | undefined = catalogModel && {
300
+ variants: new Set(Object.keys(catalogModel.variants ?? {})),
301
+ contextWindow: catalogModel.limit?.input ?? catalogModel.limit?.context,
302
+ };
303
+ // Keep only what this model needs; provider.list can return several megabytes.
304
+ cache?.set(key, entry);
305
+ return entry;
306
+});
307
+
308
+export const resolveOpenCodeVariant = Effect.fnUntraced(function* (
309
+ client: OpencodeClient,
310
+ model: ParsedOpenCodeModelSlug | undefined,
311
+ variant: string | undefined,
312
+ abortSignal?: AbortSignal,
313
+ cache?: OpenCodeVariantCache,
314
+) {
315
+ if (!variant || !model) return variant;
316
+ // Only a confirmed catalog mismatch can invalidate a persisted selection.
317
+ const entry = yield* readOpenCodeCatalogModel(client, model, abortSignal, cache);
318
+ return entry !== undefined && !entry.variants.has(variant) ? undefined : variant;
319
});
320
321
export interface OpenCodeSkill {
packages/provider-opencode/src/server/adapter.test.ts
+17
@@ -775,6 +775,18 @@ describe("OpenCodeAdapterV2", () => {
775
let promptId = "";
776
const harness = yield* makeOpenCodeRuntimeHarness(`usage-${ending}`, "root", {
777
event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
778
+ provider: {
779
+ list: async () => ({
780
+ data: {
781
+ all: [
782
+ {
783
+ id: "anthropic",
784
+ models: { "claude-sonnet": { limit: { context: 200_000, output: 8_000 } } },
785
+ },
786
+ ],
787
+ },
788
+ }),
789
+ },
790
session: {
791
create: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }),
792
promptAsync: async (input: { messageID: string }) => {
@@ -895,6 +907,11 @@ describe("OpenCodeAdapterV2", () => {
907
hasSubagents: false,
908
},
909
);
910
+ // The thread's context window reads tokenUsage: the last step's context fill.
911
+ if (ending === "completed") {
912
+ assert.equal(completed?.providerTurn.tokenUsage?.usedTokens, 22);
913
+ assert.equal(completed?.providerTurn.tokenUsage?.maxTokens, 200_000);
914
+ }
915
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
916
);
917
packages/provider-opencode/src/server/adapter.ts
+40
@@ -226,6 +226,7 @@ interface OpenCodeTurnTokenUsageAccumulator {
226
reasoningTokens: number;
227
hasSubagents: boolean;
228
complete: boolean;
229
+ lastStep: OpenCodeStepUsage | null;
230
}
231
232
function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumulator {
@@ -241,6 +242,7 @@ function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumula
242
reasoningTokens: 0,
243
hasSubagents: false,
244
complete: true,
245
+ lastStep: null,
246
};
247
}
248
@@ -255,6 +257,29 @@ function accumulateOpenCodeStepUsage(
257
accumulator.cacheCreationTokens += part.tokens.cache.write;
258
accumulator.outputTokens += part.tokens.output + part.tokens.reasoning;
259
accumulator.reasoningTokens += part.tokens.reasoning;
260
+ accumulator.lastStep = part;
261
+}
262
+
263
+// The last step's prompt plus output is the context the next request starts from.
264
+function openCodeContextUsage(
265
+ lastStep: OpenCodeStepUsage | null,
266
+ contextWindow: number | undefined,
267
+ completedAt: DateTime.Utc,
268
+): Pick<OrchestrationV2ProviderTurn, "tokenUsage"> {
269
+ if (lastStep === null) return {};
270
+ const { tokens } = lastStep;
271
+ const inputTokens = tokens.input + tokens.cache.read + tokens.cache.write;
272
+ return {
273
+ tokenUsage: {
274
+ usedTokens: inputTokens + tokens.output,
275
+ maxTokens: contextWindow ?? null,
276
+ inputTokens,
277
+ cachedInputTokens: tokens.cache.read,
278
+ outputTokens: tokens.output,
279
+ reasoningOutputTokens: tokens.reasoning,
280
+ updatedAt: DateTime.formatIso(completedAt),
281
+ },
282
+ };
283
}
284
285
interface ActiveOpenCodeTurn {
@@ -1179,6 +1204,11 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1204
reasoningTokens: turn.usage.reasoningTokens,
1205
hasSubagents: turn.usage.hasSubagents,
1206
},
1207
+ ...openCodeContextUsage(
1208
+ turn.usage.lastStep,
1209
+ variantCache.get(turn.modelSelection.model.trim())?.contextWindow,
1210
+ completedAt,
1211
+ ),
1212
}),
1213
};
1214
Object.assign(turn.providerTurn, providerTurn);
@@ -2094,6 +2124,16 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2124
yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled");
2125
}
2126
}
2127
+ // Prompts read the catalog only for variants; a completed turn needs its context window.
2128
+ const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model);
2129
+ if (status === "completed" && turn.usage.lastStep !== null && parsedModel !== null) {
2130
+ yield* OpenCodeRuntime.readOpenCodeCatalogModel(
2131
+ client,
2132
+ parsedModel,
2133
+ undefined,
2134
+ variantCache,
2135
+ );
2136
+ }
2137
yield* emitProviderTurn(state, turn, status, completedAt);
2138
const threadDisposition = terminal?.threadDisposition ?? "reusable";
2139
yield* updateProviderThread(state, {