feat(usage): redeem Codex reset credits from the Limits tab (#9534)
Follow-up to #9507, carrying over the reset-credit redemption from #9421. Codex grants a reset credit when it has rate-limited an account unfairly (`"Thanks for using Codex! You've been granted one free rate limit reset."`). Redeeming one clears the current 5h/weekly windows. The Limits tab now shows how many are banked and when the next expires, with a confirmed **Use a reset credit** action. ## How it works - `ServerProviderUsageLimits.resetCredits` carries the count and soonest expiry; the Codex probe reads it from the same `account/rateLimits/read` it already makes. - `ProviderInstance.consumeResetCredit` is a new optional hook — account-level, so it sits beside `refreshModels` rather than on the thread-routed adapter. The Codex driver implements it over a short-lived app-server (via `withCodexAppServerClient`, factored out of the status and skills probes which duplicated the setup), then re-probes. - Single-flight per instance with one idempotency key kept until Codex reports an outcome, so a retry after a timeout does not open a second attempt. - New `provider.consumeResetCredit` RPC under the operate scope; the outcome (`reset` / `nothingToReset` / `noCredit` / `alreadyRedeemed`) is shown inline. Only Codex reports credits today. A provider without the hook gets a clear "does not bank reset credits" error; one without credits shows nothing. ## Screenshots The local Codex row with one banked credit (the same account via the CLIProxyAPI hub above it shows no credit, as expected — the hub does not relay them):  Close-up of the row:  Clicking it opens the confirmation; nothing is sent until **Use credit**:  ## Verification - Mapper tests for the credit summary; provider, contract, and Usage page suites pass; typecheck clean. - Verified against a real Codex Pro account holding one credit: summary and expiry render, the confirm dialog opens. **Not redeemed** — that would spend the credit. Written by Claude Fable 5 via Claude Code; design and single-flight approach from @StiensWout's #9421. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Redemption spends real account credits over a new RPC; correctness depends on per-account locking and idempotency, though disabled instances and non-Codex providers are rejected explicitly. > > **Overview** > Adds **end-to-end redemption of banked Codex rate-limit reset credits** from the Limits UI on web and mobile, backed by a new operate-scoped `provider.consumeResetCredit` RPC. > > **Contracts and server:** `ServerProviderUsageLimits` can include `resetCredits` (count + next expiry). Codex probes attach that from `account/rateLimits/read`. Optional `ProviderInstance.consumeResetCredit` is implemented for Codex via a scoped app-server call to `account/rateLimitResetCredit/consume`, then a limits refresh. `CodexResetCreditCoordinator` serializes redemptions per Codex account directory, reuses one idempotency key until Codex returns an outcome, and times out hung requests. `withCodexAppServerClient` is extracted so status, skills, and redemption share the same short-lived app-server setup. > > **Clients:** Limits rows show banked credits and a confirmed **Use a reset credit** action that calls `serverEnvironment.consumeResetCredit` and surfaces outcomes (`reset`, `nothingToReset`, etc.) or errors. > > **Web usage sources (same PR):** Adding/removing CLIProxyAPI hubs and the add dialog target a **selected connected environment** (with picker when several are connected), gated by operate access—not only the primary environment. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 98f32e60852dca1d38c94335b3ed7aac8c4b895e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-authored-by: Wout Stiens <[email protected]> Co-authored-by: Claude Code <[email protected]>
This commit is contained in:
18 files changed
+933
-172
No files matched your search
@@ -1,6 +1,10 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ProviderConsumeResetCreditOutcome,
|
||||
ProviderInstanceId,
|
||||
ServerProvider,
|
||||
ServerProviderResetCredits,
|
||||
ServerProviderUsageWindow,
|
||||
UsageLimitSourceAccount,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -8,16 +12,19 @@ import {
|
||||
collectLimitSources,
|
||||
collectLimitsGroups,
|
||||
elapsedShare,
|
||||
formatDuration,
|
||||
formatResetsIn,
|
||||
limitsNotice,
|
||||
paceOf,
|
||||
providerLimitsLabel,
|
||||
} from "@t3tools/shared/usageLimits";
|
||||
import { useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { Alert, Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { environmentPresentations } from "../../state/presentation";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { SettingsSection } from "../settings/components/SettingsSection";
|
||||
|
||||
const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
|
||||
@@ -71,6 +78,7 @@ function AccountLimits(props: {
|
||||
readonly limits: ServerProvider["usageLimits"];
|
||||
readonly now: number;
|
||||
readonly first: boolean;
|
||||
readonly footer?: ReactNode;
|
||||
}) {
|
||||
const { limits, now } = props;
|
||||
if (!limits) return null;
|
||||
@@ -88,23 +96,120 @@ function AccountLimits(props: {
|
||||
) : (
|
||||
limits.windows.map((window) => <WindowBar key={window.id} window={window} now={now} />)
|
||||
)}
|
||||
{props.footer}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
|
||||
reset: "Reset applied. Your windows have cleared.",
|
||||
nothingToReset: "Nothing to reset right now.",
|
||||
noCredit: "No reset credit left.",
|
||||
alreadyRedeemed: "That credit was already redeemed.",
|
||||
};
|
||||
|
||||
/**
|
||||
* Banked reset credits with a confirmed redeem action. Redeeming spends a
|
||||
* credit the provider granted the user, so it goes through the native
|
||||
* confirm alert rather than firing on a bare tap.
|
||||
*/
|
||||
function ResetCredits(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly credits: ServerProviderResetCredits;
|
||||
readonly now: number;
|
||||
}) {
|
||||
const { environmentId, instanceId, credits, now } = props;
|
||||
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
if (credits.availableCount === 0 && status === null) return null;
|
||||
|
||||
const expiresIn = credits.nextExpiresAt
|
||||
? formatDuration(Date.parse(credits.nextExpiresAt) - now)
|
||||
: null;
|
||||
const summary =
|
||||
credits.availableCount === 0
|
||||
? "No reset credits banked"
|
||||
: `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
|
||||
expiresIn ? ` · next expires in ${expiresIn}` : ""
|
||||
}`;
|
||||
|
||||
const redeem = async () => {
|
||||
setBusy(true);
|
||||
setStatus(null);
|
||||
const result = await consume({ environmentId, input: { instanceId } });
|
||||
setBusy(false);
|
||||
if (result._tag === "Success") {
|
||||
setStatus(OUTCOME_TEXT[result.value.outcome]);
|
||||
return;
|
||||
}
|
||||
setStatus(
|
||||
"error" in result.cause && result.cause.error instanceof Error
|
||||
? result.cause.error.message
|
||||
: "Could not use the reset credit.",
|
||||
);
|
||||
};
|
||||
|
||||
const confirm = () => {
|
||||
Alert.alert(
|
||||
"Use a reset credit?",
|
||||
"This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{ text: "Use credit", onPress: () => void redeem() },
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<View className="gap-2">
|
||||
<Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
|
||||
{credits.availableCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: busy }}
|
||||
disabled={busy}
|
||||
onPress={confirm}
|
||||
className="self-start rounded-full bg-subtle-strong px-3 py-1.5"
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">
|
||||
{busy ? "Using credit…" : "Use a reset credit"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{status ? <Text className="text-sm text-foreground">{status}</Text> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderLimits(props: {
|
||||
readonly provider: ServerProvider;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly now: number;
|
||||
readonly first: boolean;
|
||||
}) {
|
||||
const { provider } = props;
|
||||
const { provider, environmentId, now } = props;
|
||||
const credits = provider.usageLimits?.resetCredits;
|
||||
return (
|
||||
<AccountLimits
|
||||
label={providerLimitsLabel(provider, () => undefined)}
|
||||
detail={provider.auth.label}
|
||||
limits={provider.usageLimits}
|
||||
now={props.now}
|
||||
now={now}
|
||||
first={props.first}
|
||||
footer={
|
||||
credits ? (
|
||||
<ResetCredits
|
||||
environmentId={environmentId}
|
||||
instanceId={provider.instanceId}
|
||||
credits={credits}
|
||||
now={now}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -172,6 +277,7 @@ export function UsageLimitsSection() {
|
||||
<ProviderLimits
|
||||
key={provider.instanceId}
|
||||
provider={provider}
|
||||
environmentId={group.environmentId}
|
||||
now={now}
|
||||
first={index === 0}
|
||||
/>
|
||||
|
||||
@@ -34,6 +34,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.providerAuthStart]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.providerConsumeResetCredit]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.providerAuthComplete]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.providerAuthCancel]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.providerAuthLogout]: AuthOrchestrationOperateScope,
|
||||
|
||||
@@ -36,10 +36,15 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import {
|
||||
CODEX_RESET_CREDIT_TIMEOUT,
|
||||
CodexResetCreditCoordinator,
|
||||
} from "../Layers/codexResetCredit.ts";
|
||||
import {
|
||||
checkCodexProviderStatus,
|
||||
makePendingCodexProvider,
|
||||
probeCodexSkillsForCwd,
|
||||
withCodexAppServerClient,
|
||||
} from "../Layers/CodexProvider.ts";
|
||||
import { resolveCodexLaunchArgs } from "../Layers/codexLaunchArgs.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
@@ -81,6 +86,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| CodexResetCreditCoordinator
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
@@ -101,6 +107,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const resetCreditCoordinator = yield* CodexResetCreditCoordinator;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
@@ -229,6 +236,68 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
),
|
||||
);
|
||||
|
||||
// Redemption spends something on the user's account. It serialises on
|
||||
// the account (instances sharing a Codex home share the credit), keeps
|
||||
// one idempotency key until Codex reports an outcome, and is bounded so
|
||||
// a hung app-server cannot hold the account lock.
|
||||
// Keyed on the directory holding auth.json: an auth-overlay instance has
|
||||
// its own account under `effectiveHomePath`, while plain instances share
|
||||
// the common home. The continuation key would conflate the two.
|
||||
const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
|
||||
const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
|
||||
resetCreditCoordinator
|
||||
.redeem(accountKey, (idempotencyKey) =>
|
||||
Effect.gen(function* () {
|
||||
const { client } = yield* withCodexAppServerClient({
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
homePath: effectiveConfig.homePath,
|
||||
launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
|
||||
// Account-level request; any directory serves, same as the status probe.
|
||||
cwd: process.cwd(),
|
||||
environment: processEnv,
|
||||
});
|
||||
const response = yield* client.request("account/rateLimitResetCredit/consume", {
|
||||
idempotencyKey,
|
||||
});
|
||||
return response.outcome;
|
||||
}).pipe(Effect.scoped, Effect.timeout(CODEX_RESET_CREDIT_TIMEOUT)),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Codex could not redeem the reset credit.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
// The windows just changed; re-probe so the snapshot says so. A
|
||||
// failed probe republishes the pre-redemption limits rather than
|
||||
// marking them failed, so "confirmed" means `checkedAt` moved
|
||||
// past what was published before the redemption started.
|
||||
Effect.tap(() =>
|
||||
Effect.gen(function* () {
|
||||
const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
|
||||
const refreshed = yield* snapshot.refresh;
|
||||
const after = refreshed.usageLimits?.checkedAt;
|
||||
if (
|
||||
after === undefined ||
|
||||
after === before ||
|
||||
refreshed.usageLimits?.unavailable?.reason === "probeFailed"
|
||||
) {
|
||||
return yield* new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail:
|
||||
"The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
|
||||
});
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -238,6 +307,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
snapshot,
|
||||
snapshotForCwd,
|
||||
consumeResetCredit,
|
||||
adapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -39,13 +39,17 @@ import {
|
||||
codexRateLimitsFailureMessage,
|
||||
codexRateLimitsToLimits,
|
||||
type CodexRateLimitSnapshot,
|
||||
type CodexResetCreditsSummary,
|
||||
} from "./codexUsageLimits.ts";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
|
||||
const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;
|
||||
|
||||
type CodexRateLimitsProbe =
|
||||
| { readonly snapshot: CodexRateLimitSnapshot }
|
||||
| {
|
||||
readonly snapshot: CodexRateLimitSnapshot;
|
||||
readonly resetCredits: CodexResetCreditsSummary | null | undefined;
|
||||
}
|
||||
| { readonly failure: string };
|
||||
|
||||
const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
|
||||
@@ -334,126 +338,23 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
|
||||
};
|
||||
}
|
||||
|
||||
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
|
||||
/**
|
||||
* Spawns a short-lived `codex app-server`, runs the initialize handshake, and
|
||||
* hands the caller a connected client. Scoped: the process is killed when
|
||||
* the caller's scope closes. Shared by the status probe, the skills probe,
|
||||
* and account-level requests such as reset-credit redemption.
|
||||
*/
|
||||
export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly launchArgs?: string;
|
||||
readonly homePath?: string | undefined;
|
||||
readonly launchArgs?: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly customModels?: ReadonlyArray<string>;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly environment?: NodeJS.ProcessEnv | undefined;
|
||||
}) {
|
||||
// `~` is not shell-expanded when env vars are set via `child_process.spawn`,
|
||||
// so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
|
||||
// "CODEX_HOME points to '~/.codex_work', but that path does not exist".
|
||||
// Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
|
||||
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const environment = {
|
||||
...input.environment,
|
||||
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
|
||||
};
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
input.binaryPath,
|
||||
codexAppServerArgs(input.launchArgs),
|
||||
{
|
||||
env: environment,
|
||||
extendEnv: true,
|
||||
},
|
||||
);
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd: input.cwd,
|
||||
env: environment,
|
||||
extendEnv: true,
|
||||
forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CodexErrors.CodexAppServerSpawnError({
|
||||
command: `${input.binaryPath} app-server`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
|
||||
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
|
||||
Effect.provide(clientContext),
|
||||
);
|
||||
|
||||
const initialize = yield* client.request("initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
});
|
||||
yield* client.notify("initialized", undefined);
|
||||
|
||||
// Extract the version string after the first '/' in userAgent, up to the next space or the end
|
||||
const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
|
||||
const version = versionMatch ? versionMatch[1] : undefined;
|
||||
|
||||
const accountResponse = yield* client.request("account/read", {});
|
||||
if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
|
||||
return {
|
||||
account: accountResponse,
|
||||
version,
|
||||
models: appendCustomCodexModels([], input.customModels ?? []),
|
||||
skills: [],
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
}
|
||||
|
||||
const [skillsResponse, models, rateLimits] = yield* Effect.all(
|
||||
[
|
||||
client.request("skills/list", {
|
||||
cwds: [input.cwd],
|
||||
}),
|
||||
requestAllCodexModels(client),
|
||||
// Usage is an enrichment: a failure or a slow answer degrades to "no
|
||||
// usage this probe" rather than costing the account and models.
|
||||
client.request("account/rateLimits/read", undefined).pipe(
|
||||
Effect.map((response): CodexRateLimitsProbe => ({ snapshot: response.rateLimits })),
|
||||
Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
|
||||
Effect.map(
|
||||
Option.getOrElse((): CodexRateLimitsProbe => ({
|
||||
failure: "Codex did not answer the usage request.",
|
||||
})),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
|
||||
Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
account: accountResponse,
|
||||
rateLimits,
|
||||
version,
|
||||
models: applyPreferredCodexDefaultModel(
|
||||
appendCustomCodexModels(models, input.customModels ?? []),
|
||||
),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly launchArgs?: string;
|
||||
readonly cwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) {
|
||||
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const environment = {
|
||||
@@ -488,8 +389,83 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi
|
||||
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
|
||||
Effect.provide(clientContext),
|
||||
);
|
||||
yield* client.request("initialize", buildCodexInitializeParams());
|
||||
const initialize = yield* client.request("initialize", buildCodexInitializeParams());
|
||||
yield* client.notify("initialized", undefined);
|
||||
return { client, initialize };
|
||||
});
|
||||
|
||||
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly launchArgs?: string;
|
||||
readonly cwd: string;
|
||||
readonly customModels?: ReadonlyArray<string>;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) {
|
||||
const { client, initialize } = yield* withCodexAppServerClient(input);
|
||||
|
||||
// Extract the version string after the first '/' in userAgent, up to the next space or the end
|
||||
const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
|
||||
const version = versionMatch ? versionMatch[1] : undefined;
|
||||
|
||||
const accountResponse = yield* client.request("account/read", {});
|
||||
if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
|
||||
return {
|
||||
account: accountResponse,
|
||||
version,
|
||||
models: appendCustomCodexModels([], input.customModels ?? []),
|
||||
skills: [],
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
}
|
||||
|
||||
const [skillsResponse, models, rateLimits] = yield* Effect.all(
|
||||
[
|
||||
client.request("skills/list", {
|
||||
cwds: [input.cwd],
|
||||
}),
|
||||
requestAllCodexModels(client),
|
||||
// Usage is an enrichment: a failure or a slow answer degrades to "no
|
||||
// usage this probe" rather than costing the account and models.
|
||||
client.request("account/rateLimits/read", undefined).pipe(
|
||||
Effect.map((response): CodexRateLimitsProbe => ({
|
||||
snapshot: response.rateLimits,
|
||||
resetCredits: response.rateLimitResetCredits,
|
||||
})),
|
||||
Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
|
||||
Effect.map(
|
||||
Option.getOrElse((): CodexRateLimitsProbe => ({
|
||||
failure: "Codex did not answer the usage request.",
|
||||
})),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
|
||||
Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
account: accountResponse,
|
||||
rateLimits,
|
||||
version,
|
||||
models: applyPreferredCodexDefaultModel(
|
||||
appendCustomCodexModels(models, input.customModels ?? []),
|
||||
),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly launchArgs?: string;
|
||||
readonly cwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) {
|
||||
const { client } = yield* withCodexAppServerClient(input);
|
||||
const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
|
||||
return parseCodexSkillsListResponse(skillsResponse, input.cwd);
|
||||
});
|
||||
@@ -682,7 +658,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
reason: "probeFailed",
|
||||
...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
|
||||
})
|
||||
: codexRateLimitsToLimits({ snapshot: snapshot.rateLimits.snapshot, checkedAt });
|
||||
: codexRateLimitsToLimits({
|
||||
snapshot: snapshot.rateLimits.snapshot,
|
||||
resetCredits: snapshot.rateLimits.resetCredits,
|
||||
checkedAt,
|
||||
});
|
||||
|
||||
return buildServerProvider({
|
||||
presentation: CODEX_PRESENTATION,
|
||||
|
||||
@@ -52,6 +52,7 @@ import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import * as ModelManifest from "../ModelManifest.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import * as CodexResetCredit from "./codexResetCredit.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
@@ -152,6 +153,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
);
|
||||
|
||||
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
|
||||
@@ -321,6 +323,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
);
|
||||
|
||||
it.live("boots one instance of every shipped driver from a single config map", () =>
|
||||
|
||||
@@ -37,6 +37,7 @@ import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { AntigravityInstallation } from "../AntigravityInstallation.ts";
|
||||
import * as ModelManifest from "../ModelManifest.ts";
|
||||
import * as CodexResetCredit from "./codexResetCredit.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
@@ -2007,6 +2008,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
@@ -2107,6 +2109,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
|
||||
ChildProcessSpawner.make((command) => {
|
||||
@@ -2222,6 +2225,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
@@ -2283,6 +2287,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
Layer.provideMerge(CodexResetCredit.layerTest),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import { CodexResetCreditCoordinator, layerTest } from "./codexResetCredit.ts";
|
||||
|
||||
describe("CodexResetCreditCoordinator", () => {
|
||||
it.effect("re-sends the same idempotency key after a failed attempt, then clears it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { redeem } = yield* CodexResetCreditCoordinator;
|
||||
const keys = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const attempts = yield* Ref.make(0);
|
||||
const consume = (key: string) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.update(keys, (seen) => [...seen, key]);
|
||||
const attempt = yield* Ref.updateAndGet(attempts, (n) => n + 1);
|
||||
if (attempt === 1) return yield* Effect.fail("timed out" as const);
|
||||
return "reset" as const;
|
||||
});
|
||||
|
||||
const first = yield* redeem("acct", consume).pipe(Effect.result);
|
||||
assert.isTrue(first._tag === "Failure");
|
||||
const second = yield* redeem("acct", consume);
|
||||
assert.strictEqual(second, "reset");
|
||||
// A fresh redemption after success must be a fresh attempt.
|
||||
yield* redeem("acct", consume);
|
||||
|
||||
const seen = yield* Ref.get(keys);
|
||||
assert.strictEqual(seen.length, 3);
|
||||
assert.strictEqual(seen[0], seen[1]);
|
||||
assert.notStrictEqual(seen[1], seen[2]);
|
||||
}).pipe(Effect.provide(layerTest)),
|
||||
);
|
||||
|
||||
it.effect("serialises concurrent redemptions on the same account, not per caller", () =>
|
||||
Effect.gen(function* () {
|
||||
const { redeem } = yield* CodexResetCreditCoordinator;
|
||||
const release = yield* Deferred.make<void>();
|
||||
const inFlight = yield* Ref.make(0);
|
||||
const peak = yield* Ref.make(0);
|
||||
const consume = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Ref.updateAndGet(inFlight, (n) => n + 1);
|
||||
yield* Ref.update(peak, (p) => Math.max(p, now));
|
||||
yield* Deferred.await(release);
|
||||
yield* Ref.update(inFlight, (n) => n - 1);
|
||||
return "reset" as const;
|
||||
});
|
||||
|
||||
// Two instances of the same account redeem at once.
|
||||
const a = yield* redeem("acct", consume).pipe(Effect.forkChild);
|
||||
const b = yield* redeem("acct", consume).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(a);
|
||||
yield* Fiber.join(b);
|
||||
|
||||
assert.strictEqual(yield* Ref.get(peak), 1);
|
||||
}).pipe(Effect.provide(layerTest)),
|
||||
);
|
||||
|
||||
it.effect("keeps different accounts independent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { redeem } = yield* CodexResetCreditCoordinator;
|
||||
const release = yield* Deferred.make<void>();
|
||||
const peak = yield* Ref.make(0);
|
||||
const inFlight = yield* Ref.make(0);
|
||||
const consume = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Ref.updateAndGet(inFlight, (n) => n + 1);
|
||||
yield* Ref.update(peak, (p) => Math.max(p, now));
|
||||
yield* Deferred.await(release);
|
||||
return "reset" as const;
|
||||
});
|
||||
const a = yield* redeem("acct-a", consume).pipe(Effect.forkChild);
|
||||
const b = yield* redeem("acct-b", consume).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(a);
|
||||
yield* Fiber.join(b);
|
||||
assert.strictEqual(yield* Ref.get(peak), 2);
|
||||
}).pipe(Effect.provide(layerTest)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Redeeming a Codex reset credit is an account-level action: instances that
|
||||
* share the directory holding `auth.json` share the credit, so their
|
||||
* redemptions must serialise on that directory, not the instance. This
|
||||
* service keeps one lock and one pending idempotency key per account key so
|
||||
* overlapping confirmations from any instance queue rather than spending two
|
||||
* credits, and a retry after a timeout re-sends the same attempt.
|
||||
*
|
||||
* @module provider/Layers/codexResetCredit
|
||||
*/
|
||||
import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
/**
|
||||
* Bounded so a hung app-server cannot hold the account lock forever; the
|
||||
* timeout interrupts the scoped request, which kills the process, and the
|
||||
* kept idempotency key makes the user's retry safe.
|
||||
*/
|
||||
export const CODEX_RESET_CREDIT_TIMEOUT = Duration.seconds(20);
|
||||
|
||||
interface AccountRedemptionState {
|
||||
readonly lock: Semaphore.Semaphore;
|
||||
readonly pendingKey: Ref.Ref<string | null>;
|
||||
}
|
||||
|
||||
export class CodexResetCreditCoordinator extends Context.Service<
|
||||
CodexResetCreditCoordinator,
|
||||
{
|
||||
/**
|
||||
* Run `consume` under the account's lock with a stable idempotency key.
|
||||
* The key is cleared only when Codex reports an outcome; a failure
|
||||
* (timeout included) keeps it so the next attempt is the same attempt.
|
||||
*/
|
||||
readonly redeem: <E, R>(
|
||||
accountKey: string,
|
||||
consume: (idempotencyKey: string) => Effect.Effect<ProviderConsumeResetCreditOutcome, E, R>,
|
||||
) => Effect.Effect<ProviderConsumeResetCreditOutcome, E | PlatformError.PlatformError, R>;
|
||||
}
|
||||
>()("t3/provider/Layers/codexResetCredit/CodexResetCreditCoordinator") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map());
|
||||
|
||||
// Get-or-create through one Ref.modify so two first redemptions for the
|
||||
// same account cannot each install their own lock.
|
||||
const stateFor = Effect.fn("CodexResetCreditCoordinator.stateFor")(function* (
|
||||
accountKey: string,
|
||||
) {
|
||||
const existing = (yield* Ref.get(statesRef)).get(accountKey);
|
||||
if (existing) return existing;
|
||||
const candidate = {
|
||||
lock: yield* Semaphore.make(1),
|
||||
pendingKey: yield* Ref.make<string | null>(null),
|
||||
};
|
||||
return yield* Ref.modify(statesRef, (states) => {
|
||||
const current = states.get(accountKey);
|
||||
if (current) return [current, states] as const;
|
||||
const next = new Map(states);
|
||||
next.set(accountKey, candidate);
|
||||
return [candidate, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const redeem: CodexResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume) =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* stateFor(accountKey);
|
||||
return yield* state.lock.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(state.pendingKey);
|
||||
const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4);
|
||||
yield* Ref.set(state.pendingKey, idempotencyKey);
|
||||
const outcome = yield* consume(idempotencyKey);
|
||||
yield* Ref.set(state.pendingKey, null);
|
||||
return outcome;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return { redeem } satisfies CodexResetCreditCoordinator["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(CodexResetCreditCoordinator, make);
|
||||
|
||||
/**
|
||||
* Self-contained for tests: a counter-backed Crypto so keys are deterministic
|
||||
* and distinct without the platform layer.
|
||||
*/
|
||||
export const layerTest = Layer.effect(
|
||||
CodexResetCreditCoordinator,
|
||||
Effect.gen(function* () {
|
||||
let counter = 0;
|
||||
return yield* make.pipe(
|
||||
Effect.provideService(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => {
|
||||
counter += 1;
|
||||
return new Uint8Array(size).fill(counter);
|
||||
},
|
||||
digest: (_algorithm, data) => Effect.succeed(data),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
codexRateLimitsFailureMessage,
|
||||
codexRateLimitsToLimits,
|
||||
codexRateLimitsToUpdate,
|
||||
codexResetCreditsToContract,
|
||||
} from "./codexUsageLimits.ts";
|
||||
|
||||
const checkedAt = "2026-07-18T10:00:00.000Z";
|
||||
@@ -101,3 +102,30 @@ describe("codexRateLimitsFailureMessage", () => {
|
||||
).toBe("Codex exited before it could report usage.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("codexResetCreditsToContract", () => {
|
||||
it("counts available credits and reports the soonest expiry", () => {
|
||||
expect(
|
||||
codexResetCreditsToContract({
|
||||
availableCount: 2,
|
||||
credits: [
|
||||
{ status: "available", expiresAt: 1_784_500_000 },
|
||||
{ status: "redeemed", expiresAt: 1_700_000_000 },
|
||||
{ status: "available", expiresAt: 1_784_000_000 },
|
||||
],
|
||||
}),
|
||||
).toEqual({ availableCount: 2, nextExpiresAt: "2026-07-14T03:33:20.000Z" });
|
||||
expect(codexResetCreditsToContract({ availableCount: 0 })).toEqual({ availableCount: 0 });
|
||||
expect(codexResetCreditsToContract(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rides along on the probe's limits", () => {
|
||||
expect(
|
||||
codexRateLimitsToLimits({
|
||||
checkedAt,
|
||||
snapshot: { primary: { usedPercent: 5, windowDurationMins: 300 } },
|
||||
resetCredits: { availableCount: 1 },
|
||||
}).resetCredits,
|
||||
).toEqual({ availableCount: 1 });
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import type {
|
||||
ProviderUsageLimitsUpdate,
|
||||
ServerProviderResetCredits,
|
||||
ServerProviderUsageLimits,
|
||||
ServerProviderUsageWindow,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -30,6 +31,15 @@ export interface CodexRateLimitSnapshot {
|
||||
readonly secondary?: CodexRateLimitWindow | null;
|
||||
}
|
||||
|
||||
/** Structural view of the read response's `rateLimitResetCredits`. */
|
||||
export interface CodexResetCreditsSummary {
|
||||
readonly availableCount: number;
|
||||
readonly credits?: ReadonlyArray<{
|
||||
readonly status: string;
|
||||
readonly expiresAt?: number | null;
|
||||
}> | null;
|
||||
}
|
||||
|
||||
const SESSION_MINS = 5 * 60;
|
||||
const WEEK_MINS = 7 * 24 * 60;
|
||||
const MONTH_MINS = 30 * 24 * 60;
|
||||
@@ -82,14 +92,35 @@ export function codexRateLimitsToWindows(
|
||||
return windows;
|
||||
}
|
||||
|
||||
export function codexResetCreditsToContract(
|
||||
summary: CodexResetCreditsSummary | null | undefined,
|
||||
): ServerProviderResetCredits | undefined {
|
||||
if (!summary) return undefined;
|
||||
const expiries = (summary.credits ?? [])
|
||||
.filter((credit) => credit.status === "available")
|
||||
.map((credit) => credit.expiresAt)
|
||||
.filter((value): value is number => typeof value === "number");
|
||||
const nextExpiresAt =
|
||||
expiries.length > 0 ? isoFromEpochSeconds(Math.min(...expiries)) : undefined;
|
||||
return {
|
||||
availableCount: Math.max(0, summary.availableCount),
|
||||
...(nextExpiresAt ? { nextExpiresAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function codexRateLimitsToLimits(input: {
|
||||
readonly snapshot: CodexRateLimitSnapshot;
|
||||
readonly resetCredits?: CodexResetCreditsSummary | null | undefined;
|
||||
readonly checkedAt: string;
|
||||
}): ServerProviderUsageLimits {
|
||||
return makeUsageLimits({
|
||||
checkedAt: input.checkedAt,
|
||||
windows: codexRateLimitsToWindows(input.snapshot),
|
||||
});
|
||||
const resetCredits = codexResetCreditsToContract(input.resetCredits);
|
||||
return {
|
||||
...makeUsageLimits({
|
||||
checkedAt: input.checkedAt,
|
||||
windows: codexRateLimitsToWindows(input.snapshot),
|
||||
}),
|
||||
...(resetCredits ? { resetCredits } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function codexRateLimitsToUpdate(
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
* @module provider/ProviderDriver
|
||||
*/
|
||||
import type {
|
||||
ProviderConsumeResetCreditOutcome,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceEnvironment,
|
||||
ProviderInstanceId,
|
||||
@@ -73,6 +74,15 @@ export interface ProviderInstance {
|
||||
readonly snapshot: ServerProviderShape;
|
||||
readonly snapshotForCwd?: (cwd: string) => Effect.Effect<ServerProvider, ProviderDriverError>;
|
||||
readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
|
||||
/**
|
||||
* Redeem one banked rate-limit reset credit on the signed-in account, then
|
||||
* re-probe so the snapshot reflects the cleared windows. Account-level,
|
||||
* not thread-level, which is why it lives here rather than on the adapter.
|
||||
*/
|
||||
readonly consumeResetCredit?: () => Effect.Effect<
|
||||
ProviderConsumeResetCreditOutcome,
|
||||
ProviderDriverError
|
||||
>;
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly textGeneration: TextGeneration.TextGeneration["Service"];
|
||||
readonly auth?: ProviderAuthController;
|
||||
|
||||
@@ -34,6 +34,7 @@ import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionD
|
||||
import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
|
||||
import * as ModelManifest from "./provider/ModelManifest.ts";
|
||||
import * as CodexResetCredit from "./provider/Layers/codexResetCredit.ts";
|
||||
import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
|
||||
import { ProviderAuthServiceLive } from "./provider/Layers/ProviderAuthService.ts";
|
||||
@@ -479,7 +480,9 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// `ModelManifest.layer` is the legacy-model classification data, refreshed
|
||||
// from the repo's `model-manifest.json` on `main` and applied by the
|
||||
// Codex/Claude drivers.
|
||||
Layer.provideMerge(Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer)),
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, CodexResetCredit.layer),
|
||||
),
|
||||
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
|
||||
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
|
||||
// the rewritten registry reads snapshots off the instance registry and
|
||||
|
||||
@@ -1746,6 +1746,41 @@ const makeWsRpcLayer = (
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.providerConsumeResetCredit]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.providerConsumeResetCredit,
|
||||
Effect.gen(function* () {
|
||||
const instance = yield* providerInstances.getInstance(input.instanceId);
|
||||
// A disabled instance must not spend anything on its account.
|
||||
if (instance === undefined || !instance.enabled) {
|
||||
return yield* new ProviderSetupError({
|
||||
instanceId: input.instanceId,
|
||||
operation: "consume-reset-credit",
|
||||
detail: instance ? "This provider is disabled." : "Provider instance not found.",
|
||||
});
|
||||
}
|
||||
if (instance.consumeResetCredit === undefined) {
|
||||
return yield* new ProviderSetupError({
|
||||
instanceId: input.instanceId,
|
||||
operation: "consume-reset-credit",
|
||||
detail: "This provider does not bank reset credits.",
|
||||
});
|
||||
}
|
||||
const outcome = yield* instance.consumeResetCredit().pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ProviderSetupError({
|
||||
instanceId: input.instanceId,
|
||||
operation: "consume-reset-credit",
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { outcome };
|
||||
}),
|
||||
{ "rpc.aggregate": "provider" },
|
||||
),
|
||||
[WS_METHODS.providerAuthStart]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.providerAuthStart,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { UsageLimitSourceId } from "@t3tools/contracts";
|
||||
import { type EnvironmentId, UsageLimitSourceId } from "@t3tools/contracts";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -35,18 +35,22 @@ function sourceIdFromUrl(url: string): UsageLimitSourceId {
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a CLIProxyAPI hub as a usage-limit source on the primary environment.
|
||||
* The management key is sent once and kept in the server's secret store;
|
||||
* Adds a CLIProxyAPI hub as a usage-limit source on one environment. The
|
||||
* management key is sent once and kept in that server's secret store;
|
||||
* settings only ever carry a redaction marker for it afterwards.
|
||||
*/
|
||||
export function AddUsageLimitSourceDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
environmentId,
|
||||
environmentLabel,
|
||||
}: {
|
||||
readonly open: boolean;
|
||||
readonly onOpenChange: (open: boolean) => void;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly environmentLabel: string;
|
||||
}) {
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const updateSettings = useUpdateEnvironmentSettings(environmentId);
|
||||
const [label, setLabel] = useState("");
|
||||
const [url, setUrl] = useState("");
|
||||
const [managementKey, setManagementKey] = useState("");
|
||||
@@ -90,8 +94,8 @@ export function AddUsageLimitSourceDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add a CLIProxyAPI hub</DialogTitle>
|
||||
<DialogDescription>
|
||||
Show the quota of every account the hub pools, next to the providers on this machine.
|
||||
The key stays on the server.
|
||||
Show the quota of every account the hub pools, next to the providers on{" "}
|
||||
{environmentLabel}. The key stays on that server.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type {
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ProviderConsumeResetCreditOutcome,
|
||||
ProviderInstanceId,
|
||||
ServerProvider,
|
||||
ServerProviderResetCredits,
|
||||
ServerProviderUsageWindow,
|
||||
UsageLimitSourceAccount,
|
||||
UsageLimitSourceId,
|
||||
UsageLimitSourceSnapshot,
|
||||
UsageProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -11,6 +14,7 @@ import {
|
||||
collectLimitSources,
|
||||
collectLimitsGroups,
|
||||
elapsedShare,
|
||||
formatDuration,
|
||||
formatResetsIn,
|
||||
limitsNotice,
|
||||
type LimitPace,
|
||||
@@ -20,16 +24,25 @@ import {
|
||||
import { GaugeIcon, PlusIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
|
||||
import { Fragment, useState } from "react";
|
||||
|
||||
import { isElectron } from "../../env";
|
||||
import { usePrimarySessionState } from "../../environments/primary";
|
||||
import { usePrimarySettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
usePrimarySettings,
|
||||
usePrimarySettingsAvailable,
|
||||
useUpdatePrimarySettings,
|
||||
} from "../../hooks/useSettings";
|
||||
import { usePrimaryEnvironmentId } from "../../state/environments";
|
||||
type EnvironmentPresentation,
|
||||
useEnvironments,
|
||||
usePrimaryEnvironmentId,
|
||||
} from "../../state/environments";
|
||||
import { useEnvironmentSessionState } from "../../state/session";
|
||||
import { environmentPresentations } from "../../state/presentation";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { formatUpcomingTimestamp } from "../../timestampFormat";
|
||||
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
|
||||
import { getDriverOption } from "../settings/providerDriverMeta";
|
||||
import {
|
||||
resolvePrimaryOperateAccess,
|
||||
resolveRemoteOperateAccess,
|
||||
} from "../settings/ProviderSettingsPanel.logic";
|
||||
import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -42,6 +55,7 @@ import {
|
||||
} from "../ui/alert-dialog";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
|
||||
import { PROVIDER_PRESENTATION } from "./usageProviders";
|
||||
@@ -245,9 +259,11 @@ function AccountHeading({
|
||||
|
||||
function ProviderLimits({
|
||||
provider,
|
||||
environmentId,
|
||||
now,
|
||||
}: {
|
||||
readonly provider: ServerProvider;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly now: number;
|
||||
}) {
|
||||
const limits = provider.usageLimits;
|
||||
@@ -267,10 +283,101 @@ function ProviderLimits({
|
||||
) : (
|
||||
<LimitWindows driver={provider.driver} windows={limits.windows} now={now} />
|
||||
)}
|
||||
{limits.resetCredits ? (
|
||||
<ResetCredits
|
||||
environmentId={environmentId}
|
||||
instanceId={provider.instanceId}
|
||||
credits={limits.resetCredits}
|
||||
now={now}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
|
||||
reset: "Reset applied. Your windows have cleared.",
|
||||
nothingToReset: "Nothing to reset right now.",
|
||||
noCredit: "No reset credit left.",
|
||||
alreadyRedeemed: "That credit was already redeemed.",
|
||||
};
|
||||
|
||||
/**
|
||||
* Banked reset credits with a confirmed redeem action. Redeeming spends a
|
||||
* credit the provider granted the user, so it never fires on a bare click.
|
||||
*/
|
||||
function ResetCredits({
|
||||
environmentId,
|
||||
instanceId,
|
||||
credits,
|
||||
now,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly credits: ServerProviderResetCredits;
|
||||
readonly now: number;
|
||||
}) {
|
||||
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
if (credits.availableCount === 0 && status === null) return null;
|
||||
|
||||
const expiresIn = credits.nextExpiresAt
|
||||
? formatDuration(Date.parse(credits.nextExpiresAt) - now)
|
||||
: null;
|
||||
const summary =
|
||||
credits.availableCount === 0
|
||||
? "No reset credits banked"
|
||||
: `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
|
||||
expiresIn ? ` · next expires in ${expiresIn}` : ""
|
||||
}`;
|
||||
|
||||
const redeem = async () => {
|
||||
setConfirming(false);
|
||||
setBusy(true);
|
||||
setStatus(null);
|
||||
const result = await consume({ environmentId, input: { instanceId } });
|
||||
setBusy(false);
|
||||
if (result._tag === "Success") {
|
||||
setStatus(OUTCOME_TEXT[result.value.outcome]);
|
||||
return;
|
||||
}
|
||||
setStatus(
|
||||
"error" in result.cause && result.cause.error instanceof Error
|
||||
? result.cause.error.message
|
||||
: "Could not use the reset credit.",
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">{summary}</span>
|
||||
{credits.availableCount > 0 ? (
|
||||
<Button size="xs" variant="outline" disabled={busy} onClick={() => setConfirming(true)}>
|
||||
{busy ? "Using credit…" : "Use a reset credit"}
|
||||
</Button>
|
||||
) : null}
|
||||
{status ? <span className="text-foreground">{status}</span> : null}
|
||||
<AlertDialog open={confirming} onOpenChange={setConfirming}>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This redeems one credit on your account and clears the current rate-limit windows. It
|
||||
cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button onClick={() => void redeem()}>Use credit</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One account pooled by a usage-limit source, drawn like a provider row. */
|
||||
function SourceAccountLimits({
|
||||
account,
|
||||
@@ -386,6 +493,58 @@ function SourceLimits({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this client's credential may write settings on an environment,
|
||||
* resolved the way Settings → Providers does: the desktop app owns its
|
||||
* primary outright; a browser session checks the scopes it was granted;
|
||||
* a remote environment reports scopes over its own session endpoint.
|
||||
*/
|
||||
function useCanOperateEnvironment(environment: EnvironmentPresentation | null): boolean {
|
||||
const isPrimary = environment?.entry.target._tag === "PrimaryConnectionTarget";
|
||||
const primarySession = usePrimarySessionState();
|
||||
const remoteSession = useEnvironmentSessionState(
|
||||
environment?.environmentId ?? EnvironmentId.make("none"),
|
||||
);
|
||||
if (environment === null || environment.connection.phase !== "connected") return false;
|
||||
if (isPrimary && isElectron) return true;
|
||||
const access = isPrimary
|
||||
? resolvePrimaryOperateAccess({
|
||||
isPrimary: true,
|
||||
hasDesktopBridge: false,
|
||||
session: primarySession.data,
|
||||
isPending: primarySession.isPending,
|
||||
hasError: primarySession.error !== null,
|
||||
})
|
||||
: resolveRemoteOperateAccess({
|
||||
session: remoteSession.data,
|
||||
isPending: remoteSession.isPending,
|
||||
hasError: remoteSession.hasError,
|
||||
});
|
||||
return access === "granted";
|
||||
}
|
||||
|
||||
/** One source with a remove control bound to the environment it lives in. */
|
||||
function SourceLimitsRow({
|
||||
source,
|
||||
now,
|
||||
}: {
|
||||
readonly source: UsageLimitSourceSnapshot & {
|
||||
readonly key: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
};
|
||||
readonly now: number;
|
||||
}) {
|
||||
const updateSettings = useUpdateEnvironmentSettings(source.environmentId);
|
||||
const { environments } = useEnvironments();
|
||||
const environment =
|
||||
environments.find((entry) => entry.environmentId === source.environmentId) ?? null;
|
||||
const canOperate = useCanOperateEnvironment(environment);
|
||||
// The patch names only this entry, so two edits in flight cannot clobber
|
||||
// each other's map.
|
||||
const remove = () => updateSettings({ usageLimitSources: { [source.id]: null } });
|
||||
return <SourceLimits source={source} now={now} onRemove={canOperate ? remove : null} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscription quota windows from every connected environment's providers.
|
||||
* Countdowns anchor to render time rather than ticking: a live clock would
|
||||
@@ -395,49 +554,108 @@ export function UsageLimitsSection() {
|
||||
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
|
||||
const groups = collectLimitsGroups(presentations);
|
||||
const sources = collectLimitSources(presentations);
|
||||
const configuredSources = usePrimarySettings((settings) => settings.usageLimitSources);
|
||||
const canEditSources = usePrimarySettingsAvailable();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const { environments } = useEnvironments();
|
||||
const [adding, setAdding] = useState(false);
|
||||
// Anchored once per mount on purpose: countdowns must not tick (see below).
|
||||
const [now] = useState(() => Date.now());
|
||||
|
||||
// The patch names only this entry, so two edits in flight cannot clobber
|
||||
// each other's map.
|
||||
const removeSource = (id: UsageLimitSourceId) => {
|
||||
updateSettings({ usageLimitSources: { [id]: null } });
|
||||
};
|
||||
|
||||
const addHubButton = canEditSources ? (
|
||||
<Button size="xs" variant="outline" onClick={() => setAdding(true)}>
|
||||
<PlusIcon className="size-3" aria-hidden />
|
||||
Add CLIProxyAPI hub
|
||||
</Button>
|
||||
) : null;
|
||||
// Sources live in one environment's settings. Writing them needs only the
|
||||
// operate scope, like any provider control, so a T3 Connect client can add
|
||||
// a hub to whichever environment it is connected to: the primary when there
|
||||
// is one, else the first connected environment, with a picker for more.
|
||||
const connected = environments.filter(
|
||||
(environment) => environment.connection.phase === "connected",
|
||||
);
|
||||
const [pickedEnvironmentId, setPickedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const targetEnvironment =
|
||||
(pickedEnvironmentId !== null
|
||||
? connected.find((environment) => environment.environmentId === pickedEnvironmentId)
|
||||
: undefined) ??
|
||||
(primaryEnvironmentId !== null
|
||||
? connected.find((environment) => environment.environmentId === primaryEnvironmentId)
|
||||
: undefined) ??
|
||||
connected[0] ??
|
||||
null;
|
||||
const canOperateTarget = useCanOperateEnvironment(targetEnvironment);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
{/* Sources first: they are the thing a user configures here, so the
|
||||
control to add one sits at the top rather than after every row. */}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 className="text-sm font-medium text-foreground">Usage sources</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Quota from a CLIProxyAPI hub shows beside the providers signed in on this machine.
|
||||
</p>
|
||||
</div>
|
||||
{/* The picker stays whenever several environments are connected, so
|
||||
a read-only default target does not hide the way to an operable
|
||||
one; only the button follows the picked target's access. */}
|
||||
{targetEnvironment ? (
|
||||
<div className="flex items-center gap-2">
|
||||
{connected.length > 1 ? (
|
||||
<Select
|
||||
value={targetEnvironment.environmentId}
|
||||
onValueChange={(value) => {
|
||||
if (value !== null) setPickedEnvironmentId(EnvironmentId.make(value));
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
aria-label="Environment to add the hub to"
|
||||
size="compact"
|
||||
variant="ghost"
|
||||
className="w-auto min-w-0"
|
||||
>
|
||||
<SelectValue>{targetEnvironment.label}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{connected.map((environment) => (
|
||||
<SelectItem key={environment.environmentId} value={environment.environmentId}>
|
||||
{environment.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
) : null}
|
||||
{canOperateTarget ? (
|
||||
<Button size="xs" variant="outline" onClick={() => setAdding(true)}>
|
||||
<PlusIcon className="size-3" aria-hidden />
|
||||
Add hub
|
||||
</Button>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
className="rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="inline-flex" inert>
|
||||
<Button size="xs" variant="outline" disabled>
|
||||
<PlusIcon className="size-3" aria-hidden />
|
||||
Add hub
|
||||
</Button>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="max-w-72">
|
||||
Your session cannot change settings on {targetEnvironment.label}.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{groups.length === 0 && sources.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No provider on a connected environment reports subscription limits.
|
||||
</p>
|
||||
) : null}
|
||||
{sources.map((source) => (
|
||||
<SourceLimits
|
||||
key={source.key}
|
||||
source={source}
|
||||
now={now}
|
||||
// Only the primary environment's own sources can be edited from
|
||||
// here; a remote environment's row with the same id is read-only.
|
||||
onRemove={
|
||||
canEditSources &&
|
||||
source.environmentId === primaryEnvironmentId &&
|
||||
source.id in configuredSources
|
||||
? () => removeSource(source.id)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
<SourceLimitsRow key={source.key} source={source} now={now} />
|
||||
))}
|
||||
{groups.map((group) => (
|
||||
<div key={group.environmentId} className="flex flex-col gap-6">
|
||||
@@ -447,12 +665,27 @@ export function UsageLimitsSection() {
|
||||
</h2>
|
||||
) : null}
|
||||
{group.providers.map((provider) => (
|
||||
<ProviderLimits key={provider.instanceId} provider={provider} now={now} />
|
||||
<ProviderLimits
|
||||
key={provider.instanceId}
|
||||
provider={provider}
|
||||
environmentId={group.environmentId}
|
||||
now={now}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{addHubButton ? <div>{addHubButton}</div> : null}
|
||||
<AddUsageLimitSourceDialog open={adding} onOpenChange={setAdding} />
|
||||
{targetEnvironment && canOperateTarget ? (
|
||||
// Keyed on the target: if it disconnects or the primary changes while
|
||||
// the dialog is open, a fresh dialog mounts empty rather than carrying
|
||||
// a typed key over to a different environment.
|
||||
<AddUsageLimitSourceDialog
|
||||
key={targetEnvironment.environmentId}
|
||||
open={adding}
|
||||
onOpenChange={setAdding}
|
||||
environmentId={targetEnvironment.environmentId}
|
||||
environmentLabel={targetEnvironment.label}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -902,6 +902,15 @@ export function createServerEnvironmentAtoms<R, E>(
|
||||
Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
|
||||
),
|
||||
}),
|
||||
consumeResetCredit: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:consume-reset-credit",
|
||||
tag: WS_METHODS.providerConsumeResetCredit,
|
||||
concurrency: {
|
||||
mode: "singleFlight",
|
||||
// Both ids are free-form strings; a delimiter could collide.
|
||||
key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
|
||||
},
|
||||
}),
|
||||
refreshProviders: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:refresh-providers",
|
||||
tag: WS_METHODS.serverRefreshProviders,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ProviderDriverKind } from "./providerInstance.ts";
|
||||
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
|
||||
|
||||
/**
|
||||
@@ -27,6 +27,17 @@ export const ServerProviderUsageWindow = Schema.Struct({
|
||||
});
|
||||
export type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type;
|
||||
|
||||
/**
|
||||
* Reset credits a provider banks on the account. Codex grants these when it
|
||||
* has rate-limited the user unfairly; redeeming one clears the current
|
||||
* windows. Only present when the provider reports them at all.
|
||||
*/
|
||||
export const ServerProviderResetCredits = Schema.Struct({
|
||||
availableCount: NonNegativeInt,
|
||||
nextExpiresAt: Schema.optional(IsoDateTime),
|
||||
});
|
||||
export type ServerProviderResetCredits = typeof ServerProviderResetCredits.Type;
|
||||
|
||||
/**
|
||||
* Subscription usage the provider knows about the signed-in account.
|
||||
*
|
||||
@@ -37,6 +48,7 @@ export type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type;
|
||||
export const ServerProviderUsageLimits = Schema.Struct({
|
||||
checkedAt: IsoDateTime,
|
||||
windows: ForwardCompatibleArray(ServerProviderUsageWindow),
|
||||
resetCredits: Schema.optional(ServerProviderResetCredits),
|
||||
unavailable: Schema.optional(
|
||||
Schema.Struct({
|
||||
reason: Schema.Literals(["unsupported", "probeFailed"]),
|
||||
@@ -90,3 +102,22 @@ export type UsageLimitSourceSnapshot = typeof UsageLimitSourceSnapshot.Type;
|
||||
|
||||
export const UsageLimitSourceSnapshots = ForwardCompatibleArray(UsageLimitSourceSnapshot);
|
||||
export type UsageLimitSourceSnapshots = typeof UsageLimitSourceSnapshots.Type;
|
||||
|
||||
export const ProviderConsumeResetCreditInput = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
});
|
||||
export type ProviderConsumeResetCreditInput = typeof ProviderConsumeResetCreditInput.Type;
|
||||
|
||||
/** Mirrors Codex's own outcome set; other providers map onto it. */
|
||||
export const ProviderConsumeResetCreditOutcome = Schema.Literals([
|
||||
"reset",
|
||||
"nothingToReset",
|
||||
"noCredit",
|
||||
"alreadyRedeemed",
|
||||
]);
|
||||
export type ProviderConsumeResetCreditOutcome = typeof ProviderConsumeResetCreditOutcome.Type;
|
||||
|
||||
export const ProviderConsumeResetCreditResult = Schema.Struct({
|
||||
outcome: ProviderConsumeResetCreditOutcome,
|
||||
});
|
||||
export type ProviderConsumeResetCreditResult = typeof ProviderConsumeResetCreditResult.Type;
|
||||
@@ -206,6 +206,10 @@ import {
|
||||
ResourceTelemetryRetryResult,
|
||||
ResourceTelemetrySnapshot,
|
||||
} from "./resourceTelemetry.ts";
|
||||
import {
|
||||
ProviderConsumeResetCreditInput,
|
||||
ProviderConsumeResetCreditResult,
|
||||
} from "./providerUsageLimits.ts";
|
||||
import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
|
||||
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
|
||||
import {
|
||||
@@ -243,6 +247,7 @@ export const WS_METHODS = {
|
||||
// Provider methods
|
||||
providerUploadFeedback: "provider.uploadFeedback",
|
||||
providerAuthStart: "provider.auth.start",
|
||||
providerConsumeResetCredit: "provider.consumeResetCredit",
|
||||
providerAuthComplete: "provider.auth.complete",
|
||||
providerAuthCancel: "provider.auth.cancel",
|
||||
providerAuthLogout: "provider.auth.logout",
|
||||
@@ -410,6 +415,12 @@ export const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvide
|
||||
|
||||
const ProviderSetupRpcError = Schema.Union([ProviderSetupError, EnvironmentAuthorizationError]);
|
||||
|
||||
export const WsProviderConsumeResetCreditRpc = Rpc.make(WS_METHODS.providerConsumeResetCredit, {
|
||||
payload: ProviderConsumeResetCreditInput,
|
||||
success: ProviderConsumeResetCreditResult,
|
||||
error: ProviderSetupRpcError,
|
||||
});
|
||||
|
||||
export const WsProviderAuthStartRpc = Rpc.make(WS_METHODS.providerAuthStart, {
|
||||
payload: ProviderSetupInput,
|
||||
success: ProviderAuthState,
|
||||
@@ -1157,6 +1168,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetConfigRpc,
|
||||
WsServerRefreshProvidersRpc,
|
||||
WsServerUpdateProviderRpc,
|
||||
WsProviderConsumeResetCreditRpc,
|
||||
WsProviderAuthStartRpc,
|
||||
WsProviderAuthCompleteRpc,
|
||||
WsProviderAuthCancelRpc,
|
||||
|
||||
Reference in new issue
Block a user