From 306ddbe89f378ac90647dae115ec9e158c262212 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:15:54 +0000 Subject: [PATCH] fix(usage): price Magpie model ids and read Magpie limits Magpie prefixes model ids with the harness (`codex/gpt-6.1-sol`, `claude/...`, `grok/...`), so rate lookup missed the table and reported them unpriced. A harness prefix now prices at the bare model's rate when that rate is unambiguous. OpenCode instances Magpie routes to another provider no longer probe OpenCode Go, which answered with a read error. Magpie's grok accounts map onto the Grok limits pool, and `grok/grok-4.7` running as `grok-4.7-build` is no longer flagged as a model substitution. Co-Authored-By: Claude Fable 5.2 --- .../SubagentProjection.test.ts | 27 +++++++++++++++++ apps/server/src/usage/magpieQuotas.test.ts | 30 +++++++++++++++++++ apps/server/src/usage/magpieQuotas.ts | 12 ++++++-- apps/server/src/usage/usagePricing.test.ts | 19 ++++++++++++ apps/server/src/usage/usagePricing.ts | 11 ++++++- .../src/server/subagentProjection.ts | 12 ++++++-- .../src/server/status.test.ts | 24 +++++++++++++++ .../src/server/usageLimits.ts | 12 ++++++++ 8 files changed, 141 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index c9f217fd1551a..a7238bfb8b563 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -612,6 +612,33 @@ it("ignores a context-window suffix when comparing models", () => { ); }); +it("treats a Magpie harness prefix and the vendor build id as the same model", () => { + assert.isUndefined( + workerAlert({ + requestedModel: "grok/grok-4.7", + executedModel: "grok-4.7-build", + finalText: "Done.", + }), + ); + assert.deepEqual( + workerAlert({ + requestedModel: "grok/grok-4.7", + executedModel: "grok-4.5-build", + finalText: "Done.", + })?.reasons, + ["model_substituted"], + ); + // A rate-table provider prefix is a different route, not a harness alias. + assert.deepEqual( + workerAlert({ + requestedModel: "openai/gpt-6.1-sol", + executedModel: "gpt-6.1-sol", + finalText: "Done.", + })?.reasons, + ["model_substituted"], + ); +}); + it.effect("ends an orphaned native subagent's node when only its record already ended", () => Effect.gen(function* () { const id = NodeId.make("node:orphaned-native-subagent"); diff --git a/apps/server/src/usage/magpieQuotas.test.ts b/apps/server/src/usage/magpieQuotas.test.ts index 1776dc2ce9b6f..015888e301e41 100644 --- a/apps/server/src/usage/magpieQuotas.test.ts +++ b/apps/server/src/usage/magpieQuotas.test.ts @@ -63,6 +63,20 @@ const entries = [ "this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace", }, { provider: "claude", user: "second@example.com", error: "upstream timed out" }, + { + provider: "grok", + name: "Grok", + kind: "subscription", + user: "jeffrey.smith@closura.ai", + windows: [{ name: "7 days", used: 40, resetsAt: "2026-11-22T02:00:00Z" }], + }, + { + provider: "grok", + name: "Grok", + kind: "subscription", + user: "kameron.smith@closura.ai", + windows: [{ name: "month", used: 15, resetsAt: "2026-12-01T00:00:00Z" }], + }, ]; describe("magpieQuotasToAccounts", () => { @@ -116,6 +130,22 @@ describe("magpieQuotasToAccounts", () => { }); expect(timedOut!.usageLimits.unavailable?.reason).toBe("probeFailed"); }); + + it("surfaces every Magpie Grok account under the Grok driver", () => { + const grok = accounts.filter((account) => account.driver === "grok"); + expect(grok.map((account) => account.email)).toEqual([ + "jeffrey.smith@closura.ai", + "kameron.smith@closura.ai", + ]); + expect(grok.map((account) => account.usageLimits.windows[0]?.id)).toEqual([ + "subscription", + "subscription", + ]); + expect(grok.map((account) => account.usageLimits.windows[0]?.kind)).toEqual([ + "weekly", + "monthly", + ]); + }); }); describe("gateway discovery", () => { diff --git a/apps/server/src/usage/magpieQuotas.ts b/apps/server/src/usage/magpieQuotas.ts index 0098b6ee46c14..754d8fc99eb4b 100644 --- a/apps/server/src/usage/magpieQuotas.ts +++ b/apps/server/src/usage/magpieQuotas.ts @@ -68,6 +68,8 @@ function driverFor(provider: string): ProviderDriverKind | null { case "opencode-go": case "opencode": return ProviderDriverKind.make("opencode"); + case "grok": + return ProviderDriverKind.make("grok"); default: return isProviderDriverKind(provider) ? provider : null; } @@ -92,8 +94,10 @@ function magpieWindow( ): ServerProviderUsageWindow { const [span = window.name, ...scopeParts] = window.name.split("·").map((part) => part.trim()); const scope = scopeParts.join(" · "); - const match = /^(\d+(?:\.\d+)?)\s*(minute|hour|day|week|month)s?$/i.exec(span); - const mins = match ? Number(match[1]) * MINUTES[match[2]!.toLowerCase()]! : undefined; + const match = /^(?:(\d+(?:\.\d+)?)\s+)?(minute|hour|day|week|month)s?$/i.exec(span); + const mins = match + ? Number(match[1] ?? 1) * MINUTES[match[2]!.toLowerCase()]! + : undefined; const kind: ServerProviderUsageWindow["kind"] = mins === undefined ? "other" @@ -119,7 +123,9 @@ function magpieWindow( ? "secondary" : driver === "codex" && kind !== "other" ? "primary" - : slug(span) || "window"; + : driver === "grok" + ? "subscription" + : slug(span) || "window"; const parsedReset = window.resetsAt ? DateTime.make(window.resetsAt) : Option.none(); const resetsAt = Option.isSome(parsedReset) ? DateTime.formatIso(parsedReset.value) : undefined; return { diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 9aff0eb194766..0c3c9c882d6f0 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -319,6 +319,25 @@ describe("usage pricing", () => { } }); + it("prices a Magpie harness prefix at the bare model's rate", () => { + const table = parseRateTable({ + "openai/gpt-6.1-sol": rate(1e-5, 1e-6), + "anthropic/claude-fable-5": rate(2e-5, 2e-6), + "xai/grok-4.7": rate(3e-6, 3e-7), + }); + + expect(lookupRate(table, "codex/gpt-6.1-sol")).toEqual(lookupRate(table, "gpt-6.1-sol")); + expect(lookupRate(table, "Claude/claude-fable-5[1m]")?.inputCostPerToken).toBe(2e-5); + expect(lookupRate(table, "grok/grok-4.7")?.cacheReadCostPerToken).toBe(3e-7); + // A real rate-table provider keeps its own entry, and an ambiguous bare name stays unpriced. + expect(lookupRate(table, "openai/gpt-6.1-sol")?.cacheReadCostPerToken).toBe(1e-6); + const ambiguous = parseRateTable({ + "openai/example-model": rate(1), + "xai/example-model": rate(3), + }); + expect(lookupRate(ambiguous, "codex/example-model")).toBeNull(); + }); + it("prices a bracketed context-tier variant at the base model's rate", () => { const table = parseRateTable({ "claude-fable-5-1": rate(1e-5, 2.5e-7) }); diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index a9ffc691643fd..c99314768a7b4 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -318,11 +318,20 @@ export function isUnlistedModel(table: RateTable, model: string): boolean { ); } +// Magpie names a model by the harness it served it through (`codex/gpt-6.1-sol`, +// `claude/claude-fable-5`, `grok/grok-4.7`). Those prefixes are not rate-table providers. +const HARNESS_RATE_PREFIXES = new Set(["claude", "codex", "grok"]); + function resolveRate(table: RateTable, model: string): ModelRate | null { const key = stripVariantSuffix(normalizeRateKey(model)); const bareName = bareModelName(key); if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null; - return table.get(key) ?? null; + const exact = table.get(key); + if (exact !== undefined) return exact; + const slash = key.indexOf("/"); + if (slash === -1 || !HARNESS_RATE_PREFIXES.has(key.slice(0, slash))) return null; + // The bare alias is added only when every qualified entry agrees, so an ambiguous name stays unpriced. + return table.get(bareName) ?? null; } export type PricedRecord = Pick< diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 64f05ee7de6a4..b14a23489b336 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -214,8 +214,16 @@ export function withholdsTask(text: string): boolean { ); } -// Context-window and similar suffixes, such as `[1m]`, name the same model. -const baseModel = (model: string) => model.replace(/\[[^\]]*\]$/, ""); +// Context-window suffixes (`[1m]`), a Magpie harness prefix (`grok/`) and a product suffix +// (`-build`) name the same model. Magpie selects `grok/grok-4.7` and xAI runs `grok-4.7-build`. +const HARNESS_PREFIXES = /^(?:claude|codex|grok)\//; +const baseModel = (model: string) => + model + .trim() + .toLowerCase() + .replace(/\[[^\]]*\]$/, "") + .replace(HARNESS_PREFIXES, "") + .replace(/-build$/, ""); /** What made a worker's run unfit for its task, or undefined when nothing did. */ export function workerAlert(input: { diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index b029ea00ca780..9913ac95d3f16 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -300,6 +300,30 @@ it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); +it.effect("does not probe OpenCode Go for an instance Magpie routes elsewhere", () => + Effect.gen(function* () { + const limits = yield* readOpenCodeGoUsageLimits({ + enabled: true, + serverUrl: "", + environment: { OPENCODE_FLAGS: "--model-provider grok" }, + }).pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: () => Effect.die("unexpected credential read"), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected usage request")), + ), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + NodeAssert.equal(limits.unavailable?.reason, "unsupported"); + NodeAssert.match(limits.unavailable?.message ?? "", /custom model provider/); + }), +); + it.effect("does not read local credentials for external or disabled OpenCode instances", () => Effect.gen(function* () { for (const settings of [ diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts index cbd8dc24b4a36..4f186ff2cc947 100644 --- a/packages/provider-opencode/src/server/usageLimits.ts +++ b/packages/provider-opencode/src/server/usageLimits.ts @@ -20,6 +20,11 @@ import { } from "@t3tools/provider-core/server/usageLimits"; import * as HostProcess from "@t3tools/shared/HostProcess"; +// Magpie's `model_provider` names the harness whose accounts the gateway pools. +function routedProvider(environment: NodeJS.ProcessEnv): string | undefined { + return /(?:^|\s)--model-provider(?:=|\s+)([\w-]+)/.exec(environment.OPENCODE_FLAGS ?? "")?.[1]; +} + const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknown) }); const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String }); const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile)); @@ -94,6 +99,13 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( const notApplicable = (message: string) => makeUnavailableUsageLimits({ checkedAt, reason: "unsupported", message }); if (!input.enabled || input.serverUrl.trim()) return unsupported; + // A Magpie route spends the gateway's pooled accounts, which the gateway reports itself. + const routed = routedProvider(input.environment); + if (routed !== undefined && routed !== "opencode") { + return notApplicable( + "Not applicable: this instance routes through a custom model provider, not OpenCode Go quota.", + ); + } return yield* Effect.gen(function* () { const fs = yield* FileSystem.FileSystem;