Skip to content

Commit 98f8271

Browse files
fix(usage): group limits by subscription identity
1 parent a5dd76a commit 98f8271

18 files changed

Lines changed: 541 additions & 87 deletions

‎apps/server/src/provider/Drivers/ClaudeDriver.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
186186
lookup: () =>
187187
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
188188
Effect.provideService(Path.Path, path),
189+
Effect.provideService(FileSystem.FileSystem, fileSystem),
189190
),
190191
});
191192
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(

‎apps/server/src/provider/Drivers/CodexDriver.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
206206
),
207207
),
208208
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
209+
Effect.provideService(FileSystem.FileSystem, fileSystem),
210+
Effect.provideService(Path.Path, pathService),
209211
);
210212
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
211213
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({

‎apps/server/src/provider/Drivers/CodexManagedProvider.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { ProviderDriverKind, TextGenerationError, type CodexSettings } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
3+
import * as FileSystem from "effect/FileSystem";
4+
import * as Path from "effect/Path";
35
import * as Stream from "effect/Stream";
46
import * as Option from "effect/Option";
57
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -28,6 +30,8 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
2830
const { instanceId, enabled, displayName, accentColor, config } = input;
2931
const http = yield* HttpClient.HttpClient;
3032
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
33+
const fs = yield* FileSystem.FileSystem;
34+
const path = yield* Path.Path;
3135
const settings = yield* ServerSettingsService;
3236
const runtime = yield* makeCodexManagedRuntime({
3337
instanceId,
@@ -187,7 +191,11 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
187191
),
188192
Effect.scoped,
189193
);
190-
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
194+
}).pipe(
195+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
196+
Effect.provideService(FileSystem.FileSystem, fs),
197+
Effect.provideService(Path.Path, path),
198+
);
191199
const snapshot = yield* makeManagedServerProvider({
192200
resolveMaintenance: () => Effect.succeed({ provider: DRIVER, packageName: null, update: null }),
193201
getSettings: settings.getSettings,

‎apps/server/src/provider/Layers/ClaudeCapabilitiesProbe.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
6060
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
6161
const executablePath = path.join(tempDir, "fake-claude.mjs");
6262
const invocationPath = path.join(tempDir, "invocation.json");
63+
yield* fs.writeFileString(
64+
path.join(tempDir, ".claude.json"),
65+
'{"oauthAccount":{"organizationUuid":"org-a"}}',
66+
);
6367
// The probe aborts the SDK without awaiting the child's exit, and on
6468
// Windows a directory that is still some process's cwd cannot be
6569
// removed. Keep the workspace outside the scoped directory and let it
@@ -136,7 +140,7 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
136140
yield* fs.chmod(executablePath, 0o755);
137141

138142
const capabilities = yield* probeClaudeCapabilities(
139-
decodeClaudeSettings({ binaryPath: executablePath }),
143+
decodeClaudeSettings({ binaryPath: executablePath, homePath: tempDir }),
140144
{
141145
...process.env,
142146
T3_PROBE_INVOCATION_PATH: invocationPath,
@@ -146,6 +150,7 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
146150
);
147151

148152
assert.deepEqual(capabilities, {
153+
accountId: "org-a",
149154
150155
subscriptionType: "pro",
151156
tokenSource: "oauth",

‎apps/server/src/provider/Layers/ClaudeProvider.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
claudeUsageResponseToLimits,
4343
recordClaudeUsageResponse,
4444
} from "./claudeUsageLimits.ts";
45+
import { claudeAccountConfigPath, readClaudeAccountId } from "./claudeResetCredits.ts";
4546
import {
4647
BUNDLED_CLAUDE_MODEL_CATALOG,
4748
type ClaudeModelCatalog,
@@ -226,6 +227,7 @@ function nonEmptyProbeString(value: string): string | undefined {
226227
}
227228

228229
type ClaudeCapabilitiesProbe = {
230+
readonly accountId?: string;
229231
readonly email: string | undefined;
230232
readonly subscriptionType: string | undefined;
231233
readonly tokenSource: string | undefined;
@@ -337,6 +339,7 @@ const probeClaudeCapabilities = (
337339
const abort = new AbortController();
338340
return Effect.gen(function* () {
339341
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
342+
const accountConfigPath = yield* claudeAccountConfigPath(claudeEnvironment.CLAUDE_CONFIG_DIR);
340343
const executablePath = yield* resolveClaudeSdkExecutablePath(
341344
claudeSettings.binaryPath,
342345
claudeEnvironment,
@@ -357,11 +360,11 @@ const probeClaudeCapabilities = (
357360
}),
358361
});
359362
const init = await q.initializationResult();
360-
return { q, init };
363+
return { q, init, accountConfigPath };
361364
});
362365
}).pipe(
363366
Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
364-
Effect.flatMap(({ q, init }) =>
367+
Effect.flatMap(({ q, init, accountConfigPath }) =>
365368
Effect.gen(function* () {
366369
// Usage has its own deadline so a slow optional request cannot discard initialization.
367370
const usageResult = yield* Effect.tryPromise(() =>
@@ -381,7 +384,11 @@ const probeClaudeCapabilities = (
381384
readonly apiProvider?: string;
382385
}
383386
| undefined;
387+
const accountId = account?.subscriptionType
388+
? yield* readClaudeAccountId(accountConfigPath)
389+
: undefined;
384390
return {
391+
...(accountId ? { accountId } : {}),
385392
email: account?.email,
386393
subscriptionType: account?.subscriptionType,
387394
tokenSource: account?.tokenSource,
@@ -592,6 +599,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
592599
auth: {
593600
status: "authenticated",
594601
...(capabilities.email ? { email: capabilities.email } : {}),
602+
...(capabilities.accountId ? { accountId: capabilities.accountId } : {}),
595603
...(authMetadata ? authMetadata : {}),
596604
},
597605
...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),

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

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import { assert, it } from "@effect/vitest";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Path from "effect/Path";
26

3-
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
7+
import {
8+
applyPreferredCodexDefaultModel,
9+
mapCodexModelCapabilities,
10+
readCodexAccountId,
11+
} from "./CodexProvider.ts";
412

513
it("maps current Codex model capability fields", () => {
614
const capabilities = mapCodexModelCapabilities({
@@ -171,3 +179,29 @@ it("ignores custom models that shadow a preferred slug", () => {
171179

172180
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
173181
});
182+
183+
it.effect(
184+
"reads Codex subscription identity from the instance home without publishing tokens",
185+
() =>
186+
Effect.gen(function* () {
187+
const fs = yield* FileSystem.FileSystem;
188+
const path = yield* Path.Path;
189+
const home = yield* fs.makeTempDirectoryScoped();
190+
const authPath = path.join(home, "auth.json");
191+
yield* fs.writeFileString(
192+
authPath,
193+
'{"tokens":{"account_id":" account-a ","access_token":"private"}}',
194+
);
195+
assert.equal(yield* readCodexAccountId(home, { CODEX_HOME: "/other" }), "account-a");
196+
assert.equal(yield* readCodexAccountId("", { CODEX_HOME: home }), "account-a");
197+
const token = `${Buffer.from("{}").toString("base64url")}.${Buffer.from('{"https://api.openai.com/auth":{"chatgpt_account_id":"account-b"}}').toString("base64url")}.signature`;
198+
yield* fs.writeFileString(authPath, JSON.stringify({ tokens: { id_token: token } }));
199+
assert.equal(yield* readCodexAccountId(home, {}), "account-b");
200+
for (const encoded of ["not-json", "{}", '{"tokens":{"id_token":"not-a-jwt"}}']) {
201+
yield* fs.writeFileString(authPath, encoded);
202+
assert.equal(yield* readCodexAccountId(home, {}), undefined);
203+
}
204+
yield* fs.remove(authPath);
205+
assert.equal(yield* readCodexAccountId(home, {}), undefined);
206+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
207+
);

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

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import * as NodeOS from "node:os";
2+
import { decodeJwt } from "jose";
3+
import * as FileSystem from "effect/FileSystem";
4+
import * as Path from "effect/Path";
15
import * as DateTime from "effect/DateTime";
26
import * as Duration from "effect/Duration";
37
import * as Effect from "effect/Effect";
@@ -70,6 +74,7 @@ const CODEX_PRESENTATION = {
7074
} as const;
7175

7276
export interface CodexAppServerProviderSnapshot {
77+
readonly accountId?: string;
7378
readonly account: CodexSchema.V2GetAccountResponse;
7479
readonly rateLimits?: CodexRateLimitsProbe;
7580
readonly version: string | undefined;
@@ -149,6 +154,48 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
149154
return account.email;
150155
}
151156

157+
const CodexAuthIdentity = Schema.Struct({
158+
tokens: Schema.optional(
159+
Schema.Struct({
160+
account_id: Schema.optional(Schema.String),
161+
id_token: Schema.optional(Schema.String),
162+
}),
163+
),
164+
});
165+
const CodexIdentityClaims = Schema.Struct({
166+
"https://api.openai.com/auth": Schema.optional(
167+
Schema.Struct({
168+
chatgpt_account_id: Schema.optional(Schema.String),
169+
}),
170+
),
171+
});
172+
173+
/** Reads only grouping identity from the same native home used by the app server. */
174+
export const readCodexAccountId = Effect.fn("readCodexAccountId")(function* (
175+
homePath: string,
176+
environment: NodeJS.ProcessEnv,
177+
) {
178+
const fs = yield* FileSystem.FileSystem;
179+
const path = yield* Path.Path;
180+
const home = homePath.trim()
181+
? expandHomePath(homePath)
182+
: environment.CODEX_HOME || path.join(environment.HOME || NodeOS.homedir(), ".codex");
183+
const auth = yield* fs.readFileString(path.join(home, "auth.json")).pipe(
184+
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(CodexAuthIdentity))),
185+
Effect.orElseSucceed(() => undefined),
186+
);
187+
const accountId = auth?.tokens?.account_id?.trim();
188+
if (accountId) return accountId;
189+
const idToken = auth?.tokens?.id_token;
190+
if (!idToken) return undefined;
191+
// This is grouping metadata, not authentication; the CLI verifies its tokens.
192+
const claims = yield* Effect.try(() => decodeJwt(idToken)).pipe(
193+
Effect.flatMap(Schema.decodeUnknownEffect(CodexIdentityClaims)),
194+
Effect.orElseSucceed(() => undefined),
195+
);
196+
return claims?.["https://api.openai.com/auth"]?.chatgpt_account_id?.trim() || undefined;
197+
});
198+
152199
export function mapCodexModelCapabilities(
153200
model: CodexSchema.V2ModelListResponse__Model,
154201
): ModelCapabilities {
@@ -444,6 +491,10 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
444491
} satisfies CodexAppServerProviderSnapshot;
445492
}
446493

494+
const accountId =
495+
!input.skipNativeUsage && accountResponse.account?.type === "chatgpt"
496+
? yield* readCodexAccountId(input.homePath ?? "", input.environment ?? process.env)
497+
: undefined;
447498
const [skillsResponse, models, rateLimits] = yield* Effect.all(
448499
[
449500
client.request("skills/list", {
@@ -478,6 +529,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
478529

479530
return {
480531
account: accountResponse,
532+
...(accountId ? { accountId } : {}),
481533
...(rateLimits ? { rateLimits } : {}),
482534
version,
483535
models: applyPreferredCodexDefaultModel(
@@ -584,14 +636,14 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
584636
}) => Effect.Effect<
585637
CodexAppServerProviderSnapshot,
586638
CodexErrors.CodexAppServerError,
587-
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
639+
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
588640
> = probeCodexAppServerProvider,
589641
environment?: NodeJS.ProcessEnv,
590642
managedAuth?: ServerProvider["auth"],
591643
): Effect.fn.Return<
592644
ServerProviderDraft,
593645
ServerSettingsError,
594-
ChildProcessSpawner.ChildProcessSpawner
646+
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
595647
> {
596648
const resolvedEnvironment = environment ?? process.env;
597649
const checkedAt = DateTime.formatIso(yield* DateTime.now);
@@ -707,7 +759,10 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
707759
installed: true,
708760
version: snapshot.version ?? null,
709761
status: accountStatus.status,
710-
auth: accountStatus.auth,
762+
auth: {
763+
...accountStatus.auth,
764+
...(snapshot.accountId ? { accountId: snapshot.accountId } : {}),
765+
},
711766
...(accountStatus.message ? { message: accountStatus.message } : {}),
712767
...(managedAuth ? {} : { usageLimits }),
713768
},

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ function booleanDescriptor(id: string, label: string) {
150150
}
151151

152152
type TestClaudeCapabilities = {
153+
readonly accountId?: string;
153154
readonly email: string | undefined;
154155
readonly subscriptionType: string | undefined;
155156
readonly tokenSource: string | undefined;
@@ -391,6 +392,7 @@ it.layer(Layer.mergeAll(TestNodeServices, ServerSettingsModule.layerTest(), Test
391392
const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
392393
Effect.succeed(
393394
makeCodexProbeSnapshot({
395+
accountId: "subscription-a",
394396
skills: [
395397
{
396398
name: "github:gh-fix-ci",
@@ -410,6 +412,7 @@ it.layer(Layer.mergeAll(TestNodeServices, ServerSettingsModule.layerTest(), Test
410412
assert.strictEqual(status.auth.type, "chatgpt");
411413
assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription");
412414
assert.strictEqual(status.auth.email, "[email protected]");
415+
assert.strictEqual(status.auth.accountId, "subscription-a");
413416
assert.deepStrictEqual(status.models, [
414417
{
415418
slug: "gpt-live-codex",
@@ -2747,11 +2750,12 @@ it.layer(Layer.mergeAll(TestNodeServices, ServerSettingsModule.layerTest(), Test
27472750
Effect.gen(function* () {
27482751
const status = yield* checkClaudeProviderStatus(
27492752
defaultClaudeSettings,
2750-
claudeCapabilities(),
2753+
claudeCapabilities({ subscriptionType: "pro", accountId: "org-a" }),
27512754
);
27522755
assert.strictEqual(status.status, "ready");
27532756
assert.strictEqual(status.installed, true);
27542757
assert.strictEqual(status.auth.status, "authenticated");
2758+
assert.strictEqual(status.auth.accountId, "org-a");
27552759
}).pipe(
27562760
Effect.provide(
27572761
mockSpawnerLayer((args) => {

‎apps/server/src/provider/Layers/claudeResetCredits.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,3 +257,21 @@ effectIt.layer(NodeServices.layer)("consumeClaudeResetCredit", (it) => {
257257
}),
258258
);
259259
});
260+
261+
effectIt.effect(
262+
"reads Claude organization identity and tolerates missing or malformed account config",
263+
() =>
264+
Effect.gen(function* () {
265+
const fs = yield* FileSystem.FileSystem;
266+
const login = yield* writeLogin;
267+
expect(yield* ClaudeResetCredits.readClaudeAccountId(login.accountConfigPath)).toBe("org-1");
268+
yield* fs.writeFileString(login.accountConfigPath, "not-json");
269+
expect(
270+
yield* ClaudeResetCredits.readClaudeAccountId(login.accountConfigPath),
271+
).toBeUndefined();
272+
yield* fs.remove(login.accountConfigPath);
273+
expect(
274+
yield* ClaudeResetCredits.readClaudeAccountId(login.accountConfigPath),
275+
).toBeUndefined();
276+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
277+
);

‎apps/server/src/provider/Layers/claudeResetCredits.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,16 @@ export const claudeAccountConfigPath = (configDir: string | undefined) =>
195195
configDir ? path.join(configDir, ".claude.json") : path.join(NodeOS.homedir(), ".claude.json"),
196196
);
197197

198+
/** The quota and reset-credit organization is the subscription identity. */
199+
export const readClaudeAccountId = Effect.fn("readClaudeAccountId")(function* (
200+
accountConfigPath: string,
201+
) {
202+
const config = yield* readJson(Config, accountConfigPath).pipe(
203+
Effect.orElseSucceed(() => undefined),
204+
);
205+
return config?.oauthAccount?.organizationUuid?.trim() || undefined;
206+
});
207+
198208
const CLAIM_OUTCOMES = {
199209
reset: "reset",
200210
not_limited: "nothingToReset",

0 commit comments

Comments
 (0)