GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(usage): read Magpie gateway quotas and group limits by owner (#90) · nullStack65/t3code@60bba51

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • server
      • package.json
      • src
        • provider
          • CodexProvider.ts
          • ProviderRegistry.test.ts
        • usage
          • UsageLimitSources.test.ts
          • UsageLimitSources.ts
          • magpieQuotas.test.ts
          • magpieQuotas.ts
    • web/src/components/usage
      • UsageLimitsPooled.tsx
  • packages
    • contracts/src
      • providerUsageLimits.ts
      • settings.ts
    • provider-opencode/src/server
      • status.test.ts
      • usageLimits.ts
    • shared/src
      • serverSettings.ts
      • usageLimits.test.ts
      • usageLimits.ts
  • pnpm-lock.yaml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/package.json‎

Copy file name to clipboardExpand all lines: apps/server/package.json
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"diff": "8.0.3",
6767
"effect": "catalog:",
6868
"ffi-rs": "1.3.2",
69+
"jsonc-parser": "3.3.1",
6970
"node-pty": "^1.2.0-beta.15",
7071
"playwright-core": "1.64.1",
7172
"proper-lockfile": "4.1.2",
Collapse file

‎apps/server/src/provider/CodexProvider.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/provider/CodexProvider.ts
+10-1Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,10 @@ export const codexRoutesSpendNativeQuota = (
136136
): boolean =>
137137
account.requiresOpenaiAuth && account.account?.type !== "apiKey" && routesToNativeOpenai(config);
138138

139+
/** Shown when a custom model provider serves the instance; its gateway reports the accounts. */
140+
export const CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE =
141+
"Not applicable: this instance routes through a custom model provider, not OpenAI quota.";
142+
139143
const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
140144
const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000;
141145
const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000;
@@ -1133,7 +1137,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
11331137
// Sign-in guidance still applies when Codex itself says it needs an OpenAI login.
11341138
const usageLimits =
11351139
!snapshot.nativeUsage && !accountStatus.message
1136-
? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
1140+
? makeUnavailableUsageLimits({
1141+
checkedAt,
1142+
reason: "unsupported",
1143+
// A gateway route reports its pooled accounts itself; say so rather than vanish.
1144+
...(snapshot.endpoint ? { message: CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE } : {}),
1145+
})
11371146
: snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
11381147
? makeUnavailableUsageLimits({
11391148
checkedAt,
Collapse file

‎apps/server/src/provider/ProviderRegistry.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/provider/ProviderRegistry.test.ts
+20Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";
4949
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
5050

5151
import {
52+
CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE,
5253
checkCodexProviderStatus,
5354
mapCodexModelCapabilities,
5455
type CodexAppServerProviderSnapshot,
@@ -734,6 +735,25 @@ it.layer(
734735
}),
735736
);
736737

738+
it.effect("says why usage is not applicable for a gateway-routed instance", () =>
739+
Effect.gen(function* () {
740+
const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
741+
Effect.succeed(
742+
makeCodexProbeSnapshot({
743+
account: { account: null, requiresOpenaiAuth: false },
744+
endpoint: "http://127.0.0.1:3425",
745+
nativeUsage: false,
746+
}),
747+
),
748+
);
749+
assert.strictEqual(status.usageLimits?.unavailable?.reason, "unsupported");
750+
assert.strictEqual(
751+
status.usageLimits?.unavailable?.message,
752+
CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE,
753+
);
754+
}),
755+
);
756+
737757
it.effect("offers cyber access only on catalog models that advertise it", () =>
738758
Effect.gen(function* () {
739759
const catalogModel = (slug: string, cyber?: Array<"standard" | "daybreakBlue">) => ({
Collapse file

‎apps/server/src/usage/UsageLimitSources.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/UsageLimitSources.test.ts
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
23
import { expect, it } from "@effect/vitest";
34
import {
45
ProviderDriverKind,
@@ -105,6 +106,7 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () =>
105106
HttpClient.make(() => Effect.die("Unexpected network request")),
106107
),
107108
NodeCrypto.layer,
109+
NodeServices.layer,
108110
]),
109111
),
110112
);
@@ -171,6 +173,7 @@ it.effect("reads a management key from its secret provider", () => {
171173
),
172174
),
173175
NodeCrypto.layer,
176+
NodeServices.layer,
174177
]),
175178
);
176179
});
Collapse file

‎apps/server/src/usage/UsageLimitSources.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/UsageLimitSources.ts
+78-6Lines changed: 78 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ import * as DateTime from "effect/DateTime";
1616
import * as Duration from "effect/Duration";
1717
import * as Effect from "effect/Effect";
1818
import * as Equal from "effect/Equal";
19+
import * as FileSystem from "effect/FileSystem";
1920
import * as Layer from "effect/Layer";
21+
import * as Path from "effect/Path";
2022
import * as PubSub from "effect/PubSub";
2123
import * as Ref from "effect/Ref";
2224
import * as Semaphore from "effect/Semaphore";
@@ -29,6 +31,7 @@ import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts";
2931
import * as Settings from "../serverSettings.ts";
3032
import { windowLimitsModel } from "../provider/claudeUsageLimits.ts";
3133
import { makeCliproxyApi } from "./cliproxyApi.ts";
34+
import { discoverGatewayOrigins, gatewayOrigin, makeMagpieApi } from "./magpieQuotas.ts";
3235

3336
export class UsageLimitSources extends Context.Service<
3437
UsageLimitSources,
@@ -61,6 +64,9 @@ function missingManagementKey(config: UsageLimitSourceConfig): string {
6164
/** @public */
6265
export const make = Effect.gen(function* () {
6366
const api = yield* makeCliproxyApi;
67+
const magpie = yield* makeMagpieApi;
68+
const fileSystem = yield* FileSystem.FileSystem;
69+
const path = yield* Path.Path;
6470
const settingsService = yield* Settings.ServerSettingsService;
6571
const secrets = yield* SecretResolver.SecretResolver;
6672
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
@@ -95,19 +101,78 @@ export const make = Effect.gen(function* () {
95101
checkedAt,
96102
} as const;
97103
const managementKey = yield* readManagementKey(config);
98-
if (managementKey.length === 0) {
104+
// A Magpie gateway on loopback answers without a key.
105+
if (config.kind === "cliproxy" && managementKey.length === 0) {
99106
return { ...base, accounts: [], error: missingManagementKey(config) };
100107
}
101-
const accounts = yield* api
102-
.readAccounts({ url: config.url, managementKey })
103-
.pipe(Effect.result);
108+
const accounts = yield* (
109+
config.kind === "magpie"
110+
? magpie.readAccounts({ url: config.url, managementKey })
111+
: api.readAccounts({ url: config.url, managementKey })
112+
).pipe(Effect.result);
104113
if (accounts._tag === "Failure") {
105114
yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
106115
return { ...base, accounts: [], error: accounts.failure.detail };
107116
}
108117
return { ...base, accounts: accounts.success };
109118
});
110119

120+
// Gateways the enabled instances already route through, read without
121+
// configuration. An origin that does not answer the quotas route is not a
122+
// Magpie gateway and is dropped quietly; nobody configured it.
123+
const discoverMagpieSources = Effect.fn("UsageLimitSources.discoverMagpieSources")(
124+
function* (
125+
settings: ServerSettings | null,
126+
configured: ReadonlyArray<UsageLimitSourceSnapshot>,
127+
) {
128+
if (!settings) return [];
129+
const explicit = new Set(
130+
Object.values(settings.usageLimitSources)
131+
.filter((config) => config.enabled && config.kind === "magpie")
132+
.map((config) => gatewayOrigin(config.url)),
133+
);
134+
const origins = (yield* discoverGatewayOrigins(settings, process.env).pipe(
135+
Effect.provideService(FileSystem.FileSystem, fileSystem),
136+
Effect.provideService(Path.Path, path),
137+
)).filter((origin) => !explicit.has(origin));
138+
const reads = yield* Effect.forEach(
139+
origins,
140+
(origin) =>
141+
magpie.readAccounts({ url: origin, managementKey: "" }).pipe(
142+
Effect.map((accounts) => ({ origin, accounts })),
143+
Effect.option,
144+
),
145+
{ concurrency: 4 },
146+
);
147+
const checkedAt = DateTime.formatIso(yield* DateTime.now);
148+
// A forward and the gateway it reaches report the same accounts: show one.
149+
const seen = new Set(configured.map((source) => accountSet(source.accounts)));
150+
const discovered: UsageLimitSourceSnapshot[] = [];
151+
for (const read of reads) {
152+
if (read._tag === "None") continue;
153+
const key = accountSet(read.value.accounts);
154+
if (seen.has(key)) continue;
155+
seen.add(key);
156+
discovered.push({
157+
id: `magpie:${new URL(read.value.origin).host}` as UsageLimitSourceId,
158+
kind: "magpie",
159+
label: "Magpie",
160+
origin: read.value.origin,
161+
endpoint: read.value.origin,
162+
checkedAt,
163+
accounts: read.value.accounts,
164+
});
165+
}
166+
return discovered.length > 1
167+
? discovered.map((source) => ({
168+
...source,
169+
label: `Magpie · ${source.id.slice("magpie:".length)}`,
170+
}))
171+
: discovered;
172+
},
173+
Effect.orElseSucceed((): ReadonlyArray<UsageLimitSourceSnapshot> => []),
174+
);
175+
111176
const publish = Effect.fn("UsageLimitSources.publish")(function* (
112177
next: ReadonlyArray<UsageLimitSourceSnapshot>,
113178
) {
@@ -131,7 +196,7 @@ export const make = Effect.gen(function* () {
131196
([id, config]) => readSource(id as UsageLimitSourceId, config),
132197
{ concurrency: 4 },
133198
);
134-
yield* publish(snapshots);
199+
yield* publish([...snapshots, ...(yield* discoverMagpieSources(settings, snapshots))]);
135200
}).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
136201

137202
// Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
@@ -142,7 +207,7 @@ export const make = Effect.gen(function* () {
142207
Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
143208
);
144209
const config = settings.usageLimitSources[input.sourceId];
145-
if (!config?.enabled) {
210+
if (!config?.enabled || config.kind !== "cliproxy") {
146211
return yield* new UsageLimitSourceError({
147212
detail: "The usage limit source is missing or disabled.",
148213
});
@@ -209,6 +274,13 @@ export const make = Effect.gen(function* () {
209274
} satisfies UsageLimitSources["Service"];
210275
});
211276

277+
function accountSet(accounts: ReadonlyArray<{ readonly id: string }>): string {
278+
return accounts
279+
.map((account) => account.id)
280+
.sort()
281+
.join("\n");
282+
}
283+
212284
export const layer = Layer.effect(UsageLimitSources, make).pipe(
213285
Layer.provide(SecretResolverLayer.layer),
214286
);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.