Skip to content

Commit a14388d

Browse files
feat(server): stop Codex and Cursor threads at subscription limits (#400)
Stop at subscription limit only protected Claude, so Codex could keep going on credits and Cursor on on-demand usage. Codex and Cursor now offer the same thread option and follow the application setting: a guarded turn is refused when the allowance is used up, and a running one stops when Codex reports it or a one-minute Cursor recheck finds it. Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 95794ca commit a14388d

23 files changed

Lines changed: 1037 additions & 132 deletions

‎apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ function AutoSettleSettingsRows() {
181181
<SettingsSwitchRow
182182
icon="clock"
183183
label="Stop at subscription limit"
184-
subtitle="Stop all Claude threads before paid extra usage, overriding thread options. Rechecks running sessions when enabled. Provider reports can lag; this is not a billing cap."
184+
subtitle="Stop all Claude, Codex, and Cursor threads before paid usage, overriding thread options. Rechecks running sessions when enabled. Provider reports can lag; this is not a billing cap."
185185
value={uniformMobileSetting(displayTargets, "stopAtSubscriptionLimit")}
186186
disabled={disabled}
187187
onValueChange={(value) => writeToAll({ stopAtSubscriptionLimit: value })}

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 10 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ import {
179179
makeProviderFailure,
180180
makeProviderRetryTurnItem,
181181
} from "@t3tools/provider-core/server/failure";
182+
import * as SubscriptionLimitPolicy from "@t3tools/provider-core/server/SubscriptionLimitPolicy";
182183
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
183184
import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
184185
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -1727,6 +1728,9 @@ const getNativeThreadId = Effect.fnUntraced(function* (
17271728
return nativeThreadId;
17281729
});
17291730

1731+
// Extra usage starts once the session or weekly allowance runs out.
1732+
const CLAUDE_SUBSCRIPTION_WINDOW_IDS = ["five_hour", "seven_day"];
1733+
17301734
const isSyntheticClaudeTurnId = (nativeTurnId: string): boolean => nativeTurnId.startsWith("turn:");
17311735

17321736
const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
@@ -4193,41 +4197,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
41934197
});
41944198
const subscriptionLimitFailure = Effect.fn("ClaudeAdapterV2.checkSubscriptionLimit")(
41954199
function* () {
4196-
const limits = yield* adapterOptions.checkUsageLimits ?? Effect.succeed(undefined);
4197-
const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
4198-
const subscriptionWindows =
4199-
limits?.windows.filter(
4200-
(window) => window.id === "five_hour" || window.id === "seven_day",
4201-
) ?? [];
4202-
const exhausted = subscriptionWindows.filter(
4203-
(window) =>
4204-
window.usedPercent >= 100 &&
4205-
(window.resetsAt === undefined || Date.parse(window.resetsAt) > nowMs),
4206-
);
4207-
if (
4208-
limits !== undefined &&
4209-
limits.unavailable === undefined &&
4210-
subscriptionWindows.length > 0 &&
4211-
exhausted.length === 0
4212-
)
4213-
return null;
4214-
const resetTimes = exhausted.map((window) => window.resetsAt);
4215-
const resetAt =
4216-
resetTimes.length > 0 && resetTimes.every((time) => time !== undefined)
4217-
? resetTimes.reduce((latest, time) => (time! > latest ? time! : latest), "")
4218-
: null;
4219-
return {
4220-
...makeProviderFailure({
4221-
class: exhausted.length > 0 ? "usage_limit" : "provider_error",
4222-
retryable: false,
4223-
code: "subscription_limit_guard",
4224-
message:
4225-
exhausted.length > 0
4226-
? "Claude subscription limit reached. This thread stopped because Stop at subscription limit is enabled."
4227-
: "Claude subscription usage could not be checked. Retry the turn, or disable Stop at subscription limit in application and thread settings to continue without this check.",
4228-
}),
4229-
resetAt,
4230-
};
4200+
return SubscriptionLimitPolicy.subscriptionLimitFailure({
4201+
limits: yield* adapterOptions.checkUsageLimits ?? Effect.succeed(undefined),
4202+
nowMs: DateTime.toEpochMillis(yield* DateTime.now),
4203+
provider: "Claude",
4204+
windowIds: CLAUDE_SUBSCRIPTION_WINDOW_IDS,
4205+
});
42314206
},
42324207
);
42334208

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import * as ServerConfig from "../../config.ts";
6161
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6262
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
6363
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
64+
import * as SubscriptionLimitPolicy from "@t3tools/provider-core/server/SubscriptionLimitPolicy";
6465
import * as EffectWorker from "../EffectWorker.ts";
6566
import * as Orchestrator from "../Orchestrator.ts";
6667
import * as ProviderReplayHarness from "../testkit/ProviderReplayHarness.ts";
@@ -2020,6 +2021,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
20202021
Effect.void,
20212022
onRequest: (method: string, params: unknown) => Effect.Effect<void> = () => Effect.void,
20222023
readChildMetadata?: Parameters<typeof withCodexReplayChildMetadata>[2],
2024+
subscriptionLimitPolicy?: SubscriptionLimitPolicy.SubscriptionLimitPolicy,
20232025
) =>
20242026
Effect.gen(function* () {
20252027
const fileSystem = yield* FileSystem.FileSystem;
@@ -2073,6 +2075,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
20732075
continuationRequests.push(request);
20742076
}),
20752077
},
2078+
...(subscriptionLimitPolicy === undefined ? {} : { subscriptionLimitPolicy }),
20762079
});
20772080
const threadId = ThreadId.make(`thread-${transcript.scenario}`);
20782081
const runtime = yield* adapter.openSession({
@@ -7336,6 +7339,152 @@ describe("CodexAdapterV2 post-settle continuation", () => {
73367339
),
73377340
);
73387341

7342+
const guardedPolicy: SubscriptionLimitPolicy.SubscriptionLimitPolicy = {
7343+
enabled: () => Effect.succeed(true),
7344+
enabledChanges: () => Stream.never,
7345+
};
7346+
const rateLimitsRead = (id: number, usedPercent: number) =>
7347+
[
7348+
{
7349+
type: "expect_outbound",
7350+
label: "account/rateLimits/read",
7351+
frame: { id, method: "account/rateLimits/read", params: null },
7352+
},
7353+
{
7354+
type: "emit_inbound",
7355+
label: "account/rateLimits/read",
7356+
frame: {
7357+
id,
7358+
result: {
7359+
rateLimits: {
7360+
limitId: "codex",
7361+
primary: { usedPercent, resetsAt: 2000100000, windowDurationMins: 300 },
7362+
},
7363+
},
7364+
},
7365+
},
7366+
] satisfies Array<CodexReplay.CodexAppServerReplayEntry>;
7367+
7368+
it.effect("refuses a guarded turn before Codex starts it once the allowance is used up", () =>
7369+
Effect.gen(function* () {
7370+
const preamble = codexReplayPreamble({
7371+
nativeThreadId: "native-guard-refused",
7372+
nativeTurnId: "turn-guard-refused",
7373+
prompt: "Continue.",
7374+
});
7375+
const transcript = makeCodexReplayTranscript({
7376+
scenario: "codex-subscription-guard-refused",
7377+
entries: [...preamble.slice(0, 5), ...rateLimitsRead(3, 100)],
7378+
});
7379+
const harness = yield* makeCodexReplayHarness(
7380+
transcript,
7381+
undefined,
7382+
undefined,
7383+
undefined,
7384+
guardedPolicy,
7385+
);
7386+
const error = yield* harness.runtime
7387+
.startTurn(
7388+
makeCodexTestTurnInput({
7389+
threadId: harness.threadId,
7390+
providerThread: harness.providerThread,
7391+
now: yield* DateTime.now,
7392+
text: "Continue.",
7393+
attemptId: RunAttemptId.make("attempt-guard-refused"),
7394+
}),
7395+
)
7396+
.pipe(Effect.flip);
7397+
const failure = SubscriptionLimitPolicy.findSubscriptionLimitStop(error);
7398+
assert.equal(failure?.class, "usage_limit");
7399+
assert.equal(failure?.code, "subscription_limit_guard");
7400+
assert.equal(failure?.resetAt, "2033-05-19T07:20:00.000Z");
7401+
assert.lengthOf(harness.terminalEvents(), 0);
7402+
}).pipe(
7403+
Effect.scoped,
7404+
Effect.provide(
7405+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
7406+
),
7407+
),
7408+
);
7409+
7410+
it.effect("stops a running guarded turn when Codex reports the allowance used up", () =>
7411+
Effect.gen(function* () {
7412+
const nativeThreadId = "native-guard-live";
7413+
const nativeTurnId = "turn-guard-live";
7414+
const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." });
7415+
const transcript = makeCodexReplayTranscript({
7416+
scenario: "codex-subscription-guard-live",
7417+
entries: [
7418+
...preamble.slice(0, 5),
7419+
...rateLimitsRead(3, 40),
7420+
...preamble.slice(5).map((entry) => withReplayRequestId(entry, 4)),
7421+
{
7422+
type: "emit_inbound",
7423+
label: "account/rateLimits/updated",
7424+
frame: {
7425+
method: "account/rateLimits/updated",
7426+
params: {
7427+
rateLimits: {
7428+
limitId: "codex",
7429+
primary: { usedPercent: 100, resetsAt: 2000100000, windowDurationMins: 300 },
7430+
},
7431+
},
7432+
},
7433+
},
7434+
{
7435+
type: "expect_outbound",
7436+
label: "turn/interrupt",
7437+
frame: {
7438+
id: 5,
7439+
method: "turn/interrupt",
7440+
params: { threadId: nativeThreadId, turnId: nativeTurnId },
7441+
},
7442+
},
7443+
{ type: "emit_inbound", label: "turn/interrupt", frame: { id: 5, result: {} } },
7444+
{
7445+
type: "emit_inbound",
7446+
label: "turn/completed",
7447+
frame: {
7448+
method: "turn/completed",
7449+
params: {
7450+
threadId: nativeThreadId,
7451+
turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }),
7452+
},
7453+
},
7454+
},
7455+
],
7456+
});
7457+
const harness = yield* makeCodexReplayHarness(
7458+
transcript,
7459+
undefined,
7460+
undefined,
7461+
undefined,
7462+
guardedPolicy,
7463+
);
7464+
yield* harness.runtime.startTurn(
7465+
makeCodexTestTurnInput({
7466+
threadId: harness.threadId,
7467+
providerThread: harness.providerThread,
7468+
now: yield* DateTime.now,
7469+
text: "Continue.",
7470+
attemptId: RunAttemptId.make("attempt-guard-live"),
7471+
}),
7472+
);
7473+
yield* harness.firstTerminal;
7474+
const terminal = harness.terminalEvents()[0];
7475+
assert.equal(terminal?.status, "failed");
7476+
if (terminal?.status !== "failed") return;
7477+
assert.equal(terminal.failure.class, "usage_limit");
7478+
assert.equal(terminal.failure.code, "subscription_limit_guard");
7479+
assert.equal(terminal.failure.resetAt, "2033-05-19T07:20:00.000Z");
7480+
}).pipe(
7481+
Effect.scoped,
7482+
Effect.provide(
7483+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
7484+
),
7485+
),
7486+
);
7487+
73397488
it.effect.each([
73407489
{
73417490
notificationStatus: 500,

0 commit comments

Comments
 (0)