GeezerVison is showing github.com — fix(usage): read Magpie gateway quotas and group limits by owner by nullStack65 · Pull Request #90 · nullStack65/t3code
fix(usage): read Magpie gateway quotas and group limits by owner
#90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.ts
(5)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(usage): keep action-needed states out of "Not applicable" and bou…
…nd gateway reads
Review round on #90 :
- Only explicit "Not applicable:" reasons (and Magpie standing refusals) are
listed as not applicable; sign-in prompts and shared-usage notices are not.
- One 5-second deadline now covers the gateway's headers and body, so a
stalled body cannot hold the usage-source refresh lock.
- Codex discovery accepts single-quoted TOML values.
- The Codex custom-provider reason no longer claims the provider reports usage.
Model: claude-opus-5-5
Task: fix
Agent: claude-code-usage-limits
Lane: magpie
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 353ed13c9ebae39145f5bed6cd72bc8c05f58bd4
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -138,7 +138,7 @@ export const codexRoutesSpendNativeQuota = (
/** Shown when a custom model provider serves the instance; its gateway reports the accounts. */
export const CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE =
"Not applicable: this instance routes through its model provider, which reports usage itself .";
"Not applicable: this instance routes through a custom model provider, not OpenAI quota .";
const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,6 +2,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import { ProviderDriverKind, ProviderInstanceId, type ServerSettings } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import * as FileSystem from "effect/FileSystem";
import { HttpClient, HttpClientResponse } from "effect/http";
Expand Down
Expand Up
@@ -131,6 +133,12 @@ describe("gateway discovery", () => {
expect(codexBaseUrl(toml, "")).toBe("http://127.0.0.1:13425/v1");
expect(codexBaseUrl(toml, "-c model_provider=openai")).toBe("https://api.openai.com/v1");
expect(codexBaseUrl("model = 'x'", undefined)).toBeUndefined();
expect(
codexBaseUrl(
"model_provider = 'm'\n[model_providers.m]\nbase_url = 'http://127.0.0.1:1/v1'",
"",
),
).toBe("http://127.0.0.1:1/v1");
});
it("reads OpenCode provider base URLs from JSONC", () => {
Expand Down
Expand Up
@@ -235,6 +243,32 @@ describe("makeMagpieApi", () => {
}),
);
it.effect("gives up on a gateway whose body never finishes", () =>
Effect.gen(function* () {
const http = HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
new Response(new ReadableStream({ start() {} }), {
headers: { "content-type": "application/json" },
}),
),
),
);
const fiber = yield* makeMagpieApi.pipe(
Effect.flatMap((api) =>
api.readAccounts({ url: "http://127.0.0.1:3425", managementKey: "" }),
),
Effect.result,
Effect.provideService(HttpClient.HttpClient, http),
Effect.forkChild,
);
yield* TestClock.adjust("5 seconds");
const result = yield* Fiber.join(fiber);
expect(result._tag === "Failure" && result.failure.detail).toMatch(/did not answer/);
}),
);
it.effect("sends a configured gateway key and explains a refusal", () =>
Effect.gen(function* () {
const { result, seen } = yield* run("gateway-key", 401);
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -46,6 +46,7 @@ const QuotaEntry = Schema.Struct({
});
const QuotasResponse = Schema.Struct({ data: Schema.Array(QuotaEntry) });
const isProviderDriverKind = Schema.is(ProviderDriverKind);
const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
export type MagpieQuotaEntry = typeof QuotaEntry.Type;
const MINUTES: Record<string, number> = {
Expand Down
Expand Up
@@ -204,21 +205,30 @@ export const makeMagpieApi = Effect.gen(function* () {
const request = HttpClientRequest.get(`${origin}/v1/magpie/quotas`).pipe(
config.managementKey ? HttpClientRequest.bearerToken(config.managementKey) : (r) => r,
);
const response = yield* client.execute(request).pipe(
Effect.timeout("5 seconds"),
Effect.mapError(
() => new UsageLimitSourceError({ detail: "The Magpie gateway did not answer." }),
// One deadline covers headers and body: a stalled body must not hold the refresh lock.
const body = yield* client.execute(request).pipe(
Effect.flatMap((response) =>
response.status === 401 || response.status === 403
? Effect.fail(
new UsageLimitSourceError({
detail: "The Magpie gateway refused the key. Add the gateway key to this source.",
}),
)
: HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(QuotasResponse)),
Effect.mapError(
() =>
new UsageLimitSourceError({
detail: "The Magpie gateway did not report quotas.",
}),
),
),
),
);
if (response.status === 401 || response.status === 403) {
return yield* new UsageLimitSourceError({
detail: "The Magpie gateway refused the key. Add the gateway key to this source.",
});
}
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(QuotasResponse)),
Effect.mapError(
() => new UsageLimitSourceError({ detail: "The Magpie gateway did not report quotas." }),
Effect.timeout("5 seconds"),
Effect.mapError((error) =>
isUsageLimitSourceError(error)
? error
: new UsageLimitSourceError({ detail: "The Magpie gateway did not answer." }),
),
);
return magpieQuotasToAccounts(body.data, DateTime.formatIso(yield* DateTime.now));
Expand Down
Expand Up
@@ -260,7 +270,7 @@ export function isPrivateOrigin(origin: string): boolean {
/** The selected provider's `base_url` in a Codex `config.toml`, or a `-c model_provider=` override. */
export function codexBaseUrl(toml: string, launchArgs: string | undefined): string | undefined {
const override = /model_provider\s*=\s*"?([\w.-]+)"?/.exec(launchArgs ?? "")?.[1];
const provider = override ?? /^\s*model_provider\s*=\s*" ([^"]+)" /m.exec(toml)?.[1];
const provider = override ?? /^\s*model_provider\s*=\s*["'] ([^"' ]+)["'] /m.exec(toml)?.[1];
if (!provider) return undefined;
let inSection = false;
for (const line of toml.split(/\r?\n/)) {
Expand All
@@ -270,7 +280,7 @@ export function codexBaseUrl(toml: string, launchArgs: string | undefined): stri
continue;
}
if (!inSection) continue;
const value = /^\s*base_url\s*=\s*" ([^"]+)" /.exec(line)?.[1];
const value = /^\s*base_url\s*=\s*["'] ([^"' ]+)["'] /.exec(line)?.[1];
if (value) return value;
}
return undefined;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -1887,14 +1887,25 @@ describe("owners and not-applicable usage", () => {
unavailable: { reason: "unsupported", message: "Not applicable: gateway reports it." },
},
});
// Unsupported, but asking the user to act: never "not applicable".
const signIn = provider({
instanceId: ProviderInstanceId.make("antigravity"),
driver: ProviderDriverKind.make("antigravity"),
displayName: "Antigravity",
usageLimits: {
checkedAt,
windows: [],
unavailable: { reason: "unsupported", message: "Sign in with Google to see limits." },
},
});
const presentations = (owners?: Record<string, string>) =>
new Map([
[
EnvironmentId.make("env-a"),
{
entry: { target: { label: "Crown" } },
serverConfig: {
providers: [routed],
providers: [routed, signIn ],
usageLimitSources: [magpie],
...(owners ? { settings: { usageAccountOwners: owners } } : {}),
},
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -478,12 +478,22 @@ export function collectNotApplicable(
for (const presentation of presentations.values()) {
const environmentLabel = presentation.entry.target.label;
for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
// Only an explicit "Not applicable:" reason: other unsupported messages
// (a sign-in prompt, a sharing notice shown as a link) ask for action.
const unavailable = provider.usageLimits?.unavailable;
if (unavailable?.reason !== "unsupported" || !unavailable.message) continue;
if (
unavailable?.reason !== "unsupported" ||
!unavailable.message?.startsWith(NOT_APPLICABLE_PREFIX) ||
provider.usageLimits?.externalUsage
) {
continue;
}
const name = provider.displayName?.trim() || String(provider.driver);
entries.set(label(environmentLabel, name), unavailable.message);
}
for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
// Magpie maps only standing vendor refusals to unsupported.
if (source.kind !== "magpie") continue;
for (const account of source.accounts) {
const unavailable = account.usageLimits.unavailable;
if (unavailable?.reason !== "unsupported") continue;
Expand All
@@ -499,6 +509,8 @@ export function collectNotApplicable(
export const UNASSIGNED_OWNER = "Unassigned";
const NOT_APPLICABLE_PREFIX = "Not applicable:";
/** `[email protected] · Team` and `[email protected] ` look up the same owner. */
function ownerLookupKey(email: string): string {
return email.split(" · ")[0]!.trim().toLowerCase();
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.