fix(core): measure context windows for model IDs a chat reports

This commit is contained in:
Aiden Cline 2026-11-24 22:20:54 -06:00
parent 58621ad6cc
commit d849af005f
6 changed files with 158 additions and 36 deletions

View file

@ -12,6 +12,8 @@ export interface Result {
readonly version: string | undefined
readonly account: AccountInfo
readonly models: readonly Model[]
// Windows of IDs a chat reported that this check does not list
readonly contextWindows?: Readonly<Record<string, number>>
}
export class ProbeError extends Schema.TaggedError<ProbeError>()("ClaudeProbe.ProbeError", {
@ -41,7 +43,7 @@ function atLeast(version: string, minimum: string) {
}
// The input never sends a message, so no model call is made and no tokens are used.
export const run = Effect.fn("ClaudeProbe.run")(function* (options: Options) {
export const run = Effect.fn("ClaudeProbe.run")(function* (options: Options, measure: readonly string[] = []) {
const stop = Promise.withResolvers<void>()
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
@ -66,8 +68,15 @@ export const run = Effect.fn("ClaudeProbe.run")(function* (options: Options) {
// The version is checked when a chat starts, and that chat's error tells the user to update.
const version = init.claude_code_version
const models: Model[] = init.models.map((model) => ({ ...model }))
if (version && atLeast(version, CONTEXT_DISCOVERY_VERSION)) yield* discoverContext(session, models)
return { version, account: init.account, models } satisfies Result
const unlisted: Array<{ value: string; contextWindow?: number }> = measure
.filter((id) => !models.some((model) => model.value === id))
.map((value) => ({ value }))
if (version && atLeast(version, CONTEXT_DISCOVERY_VERSION))
yield* discoverContext(session, [...models, ...unlisted])
const contextWindows = Object.fromEntries(
unlisted.flatMap((model) => (model.contextWindow === undefined ? [] : [[model.value, model.contextWindow]])),
)
return { version, account: init.account, models, contextWindows } satisfies Result
}),
(session) =>
Effect.sync(() => {
@ -79,7 +88,7 @@ export const run = Effect.fn("ClaudeProbe.run")(function* (options: Options) {
// Sets each model's context window in place, so models discovered before a timeout keep theirs.
const discoverContext = Effect.fn("ClaudeProbe.discoverContext")(
function* (session: Query, models: readonly Model[]) {
function* (session: Query, models: ReadonlyArray<{ readonly value: string; contextWindow?: number }>) {
for (const model of models) {
if (model.value === "default") continue
yield* Effect.tryPromise(async () => {

View file

@ -18,7 +18,8 @@ export type State =
export interface Interface {
readonly state: SubscriptionRef.SubscriptionRef<State>
readonly refresh: () => Effect.Effect<void>
// Also measures the context windows of `models`, IDs a chat reported that the check may not list
readonly refresh: (models?: readonly string[]) => Effect.Effect<void>
// What a chat's own process found when it started
readonly report: (next: State) => Effect.Effect<void>
}
@ -32,11 +33,11 @@ export const make = Effect.fn("ClaudeStatus.make")(function* (
const lock = yield* Semaphore.make(1)
// Serialized so a reconnect checks again after startup, rather than racing it with an older account snapshot.
const refresh = Effect.fn("ClaudeStatus.refresh")(function* () {
const refresh = Effect.fn("ClaudeStatus.refresh")(function* (models?: readonly string[]) {
const executable = io.which()
if (!executable) return yield* SubscriptionRef.set(state, { type: "missing" })
const env = ClaudeQueryOptions.withoutDefaultFolder(yield* connection(), io)
const next = yield* ClaudeProbe.run(ClaudeQueryOptions.base({ executable, io, connection: env })).pipe(
const next = yield* ClaudeProbe.run(ClaudeQueryOptions.base({ executable, io, connection: env }), models).pipe(
Effect.map((probe): State => ({ type: "ready", probe, configDir: env.CLAUDE_CONFIG_DIR })),
Effect.catch((error) =>
Effect.logWarning("Claude Code login check failed", { cause: error.cause }).pipe(

View file

@ -74,14 +74,18 @@ export const register = Effect.fn("ClaudeProvider.register")(function* (
const stored = Schema.decodeUnknownOption(Catalog)(yield* ctx.storage.get(CATALOG_KEY))
const next = {
priceSource: priceSource(state.probe.account, baseURL),
models: fromClaude(state.probe.models, Option.getOrElse(stored, () => current.catalog).models),
models: fromClaude(
state.probe.models,
Option.getOrElse(stored, () => current.catalog).models,
state.probe.contextWindows,
),
}
const unknown = next.models.filter(
(model) => !model.hidden && model.contextWindow === undefined && !checked.has(model.id),
)
if (state.fromChat && unknown.length > 0) {
for (const model of unknown) checked.add(model.id)
yield* status.refresh().pipe(Effect.forkScoped)
yield* status.refresh(unknown.map((model) => model.id)).pipe(Effect.forkScoped)
}
if (JSON.stringify(next) === JSON.stringify(current.catalog)) return
current.catalog = next
@ -115,7 +119,11 @@ export const configDirs = Effect.fn("ClaudeProvider.configDirs")(function* (ctx:
// chat or the config may hold any ID that was ever listed. So no ID is dropped, and a model already offered under one
// ID keeps it when Claude Code lists it under another.
// Context windows only come from the full check, so a chat's startup report keeps the saved ones.
function fromClaude(models: readonly ClaudeProbe.Model[], saved: readonly CatalogModel[]): CatalogModel[] {
function fromClaude(
models: readonly ClaudeProbe.Model[],
saved: readonly CatalogModel[],
windows: ClaudeProbe.Result["contextWindows"],
): CatalogModel[] {
// "default" follows Claude Code's own default, which can change under a running opencode session
const listed = models.filter((model) => model.value !== "default")
const result = new Map<string, CatalogModel>()
@ -136,14 +144,15 @@ function fromClaude(models: readonly ClaudeProbe.Model[], saved: readonly Catalo
id: model.value,
name: model.displayName,
efforts: model.supportedEffortLevels ?? [],
contextWindow: model.contextWindow ?? (offered ?? own)?.contextWindow,
contextWindow: model.contextWindow ?? offered?.contextWindow ?? own?.contextWindow,
resolvedModel: model.resolvedModel,
}
if (offered) result.set(offered.id, { ...entry, id: offered.id })
result.set(entry.id, offered ? { ...entry, hidden: true } : entry)
}
for (const model of saved) {
if (!result.has(model.id)) result.set(model.id, { ...model, hidden: true })
if (!result.has(model.id))
result.set(model.id, { ...model, contextWindow: windows?.[model.id] ?? model.contextWindow, hidden: true })
}
return [...result.values()]
}

View file

@ -47,6 +47,24 @@ describe("login check", () => {
}),
)
it.effect("measures IDs a chat reported that the check does not list", () =>
Effect.gen(function* () {
const claude = FakeClaude.make([FakeClaude.expectStartup()], { windows: { "claude-fable-5-2": 1_000_000 } })
const result = yield* ClaudeProbe.run(
ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io: FakeIO.make({ claude }) }),
["claude-fable-5-2", "opus"],
)
expect(result.contextWindows).toEqual({ "claude-fable-5-2": 1_000_000 })
expect(result.models.some((model) => model.value === "claude-fable-5-2")).toBe(false)
const models = claude.runs[0]!.received.flatMap((message) =>
message.request?.subtype === "set_model" ? [message.request.model] : [],
)
expect(models.filter((model) => model === "opus")).toHaveLength(1)
expect(models.at(-1)).toBe("claude-fable-5-2")
claude.check()
}),
)
it.effect("closes stuck context discovery without turning it into a login failure", () =>
Effect.gen(function* () {
const steps = FakeClaude.replay("startup").slice(0, 3)

View file

@ -183,11 +183,17 @@ function loadProbeControls() {
return controls
}
function probeResponse(message: any, model: string | undefined) {
// A model in `windows` was not recorded, so it answers like a recorded one with its own context window.
function probeResponse(message: any, model: string | undefined, windows?: Readonly<Record<string, number>>) {
probeControls ??= loadProbeControls()
const reply = probeControls.get(`${model}/${message.request?.subtype}`)
const window = model === undefined ? undefined : windows?.[model]
const reply = probeControls.get(`${window === undefined ? model : "opus"}/${message.request?.subtype}`)
if (!reply) return
return { ...reply, response: { ...reply.response, request_id: message.request_id } }
const response =
window !== undefined && reply.response.response
? { ...reply.response.response, maxTokens: window, rawMaxTokens: window }
: reply.response.response
return { ...reply, response: { ...reply.response, request_id: message.request_id, response } }
}
// One `claude` the SDK started: its flags, its environment and every message the SDK wrote to it
@ -201,7 +207,10 @@ export interface Run {
export type Fake = ReturnType<typeof make>
export function make(script: readonly Step[], options?: { readonly probes?: boolean }) {
export function make(
script: readonly Step[],
options?: { readonly probes?: boolean; readonly windows?: Readonly<Record<string, number>> },
) {
const runs: Run[] = []
const errors: string[] = []
const transcripts = new Map<string, SessionMessage[]>()
@ -265,7 +274,7 @@ export function make(script: readonly Step[], options?: { readonly probes?: bool
: type === step?.type
if (!matches && isProbe(run.args)) {
const model = run.received.findLast((message) => message.request?.subtype === "set_model")?.request.model
const reply = probeResponse(message, model)
const reply = probeResponse(message, model, options?.windows)
if (reply) {
process.stdout.write(JSON.stringify(reply) + "\n")
return

View file

@ -80,6 +80,27 @@ const connectionStatus = Effect.gen(function* () {
return integration?.connections[0]?.status
})
const chatOnHaiku = Effect.gen(function* () {
const aisdk = yield* AISDK.Service
const sdk = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(ClaudeProvider.ID, haiku.id),
modelID: haiku.id,
package: Provider.aisdk(ClaudeProvider.PACKAGE),
}),
package: ClaudeProvider.PACKAGE,
options: {},
})
const model: LanguageModelV3 = sdk.sdk.languageModel("haiku")
const result = yield* Effect.promise(() =>
model.doStream({
prompt: TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker."),
headers: { [RequestKind.SESSION_HEADER]: "session-a", [RequestKind.HEADER]: "primary" },
}),
)
expect(TestSessions.text(yield* Effect.promise(() => TestSessions.collect(result.stream)))).toBe("COPPER-OTTER")
})
function find(models: readonly Model.Info[], id: string) {
const model = models.find((model) => model.id === id)
if (!model) throw new Error(`Expected model ${id}`)
@ -279,25 +300,7 @@ describe("ClaudeAgentPlugin models", () => {
{ probes: true },
)
const registry = yield* addPlugin(FakeIO.make({ claude }))
const aisdk = yield* AISDK.Service
const sdk = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(ClaudeProvider.ID, haiku.id),
modelID: haiku.id,
package: Provider.aisdk(ClaudeProvider.PACKAGE),
}),
package: ClaudeProvider.PACKAGE,
options: {},
})
const model: LanguageModelV3 = sdk.sdk.languageModel("haiku")
const result = yield* Effect.promise(() =>
model.doStream({
prompt: TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker."),
headers: { [RequestKind.SESSION_HEADER]: "session-a", [RequestKind.HEADER]: "primary" },
}),
)
expect(TestSessions.text(yield* Effect.promise(() => TestSessions.collect(result.stream)))).toBe("COPPER-OTTER")
yield* chatOnHaiku
expect(yield* store.get("sessions/session-a")).toMatchObject({ claudeSessionID: expect.any(String) })
yield* eventually(claudeModels, (models) =>
@ -307,6 +310,79 @@ describe("ClaudeAgentPlugin models", () => {
claude.check()
}),
)
it.live("keeps a saved context window when a chat lists the model under another ID", () =>
Effect.gen(function* () {
const store = yield* storage
const listed = FakeClaude.expectStartup().reply.models.filter(
(model) => model.value !== "default" && model.value !== "fable",
)
yield* store.set("models", {
models: [
...listed.map((model) => ({
id: model.value,
name: model.displayName,
efforts: [],
contextWindow: 200_000,
resolvedModel: model.resolvedModel ?? model.value,
})),
{
id: "fable",
name: "Fable 5.1",
efforts: [],
contextWindow: 777_000,
resolvedModel: "claude-fable-5-1",
hidden: true,
},
// The chat lists this model as `fable`, and no full check has measured this ID
{ id: "claude-fable-5-1", name: "Fable 5.1", efforts: [], resolvedModel: "claude-fable-5-1" },
],
})
yield* connect
const claude = FakeClaude.make([
FakeClaude.expectStartup(),
FakeClaude.expectTurn(),
FakeClaude.expectInterrupt(),
])
const registry = yield* addPlugin(FakeIO.make({ claude }))
yield* chatOnHaiku
// The saved row has no efforts, so the chat's report has been applied once it has some
const models = yield* eventually(claudeModels, (models) => find(models, "claude-fable-5-1").variants.length > 0)
expect(find(models, "claude-fable-5-1").limit.context).toBe(777_000)
yield* registry.close()
claude.check()
}),
)
it.live("measures the context window of a model a chat lists and the full check does not", () =>
Effect.gen(function* () {
const store = yield* storage
yield* store.set("models", { models: [{ id: "haiku", name: "Haiku", efforts: [], contextWindow: 123_456 }] })
yield* connect
const startup = FakeClaude.expectStartup()
const fable = {
value: "claude-fable-5-2",
resolvedModel: "claude-fable-5-2",
displayName: "Fable 5.2",
description: "Fable 5.2",
}
const claude = FakeClaude.make(
[
{ ...startup, reply: { ...startup.reply, models: [...startup.reply.models, fable] } },
FakeClaude.expectTurn(),
FakeClaude.expectInterrupt(),
],
{ probes: true, windows: { "claude-fable-5-2": 1_000_000 } },
)
const registry = yield* addPlugin(FakeIO.make({ claude }))
yield* chatOnHaiku
yield* eventually(claudeModels, (models) =>
models.some((model) => model.id === "claude-fable-5-2" && model.limit.context === 1_000_000),
)
yield* registry.close()
claude.check()
}),
)
})
describe("ClaudeAgentPlugin deleted sessions", () => {