Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions apps/server/src/orchestration-v2/SubagentProjection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/usage/magpieQuotas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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", () => {
Expand Down
12 changes: 9 additions & 3 deletions apps/server/src/usage/magpieQuotas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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"
Expand All @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions apps/server/src/usage/usagePricing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) });

Expand Down
11 changes: 10 additions & 1 deletion apps/server/src/usage/usagePricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<
Expand Down
12 changes: 10 additions & 2 deletions packages/provider-core/src/server/subagentProjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
24 changes: 24 additions & 0 deletions packages/provider-opencode/src/server/status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down
12 changes: 12 additions & 0 deletions packages/provider-opencode/src/server/usageLimits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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;
Expand Down
Loading