Skip to content

Commit ac00531

Browse files
feat(server): option to start a turn on another account when the limit is used up
With switchAccountAtUsageLimit on, a fresh turn whose account has used up a quota window starts on another signed-in account of the same provider that offers the model. It applies to every way of starting a turn, because it sits in ThreadManagementService.dispatch. Off by default. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent cab18c5 commit ac00531

4 files changed

Lines changed: 211 additions & 1 deletion

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import {
3+
ProviderDriverKind,
4+
ProviderInstanceId,
5+
RunId,
6+
type ModelSelection,
7+
type ServerProvider,
8+
} from "@t3tools/contracts";
9+
10+
import {
11+
limitAccountSwitchSelection,
12+
type LimitAccountSwitchCommand,
13+
} from "./LimitAccountSwitch.ts";
14+
15+
const NOW = Date.parse("2026-10-10T12:00:00.000Z");
16+
17+
function provider(instanceId: string, weeklyUsed: number): ServerProvider {
18+
return {
19+
instanceId: ProviderInstanceId.make(instanceId),
20+
driver: ProviderDriverKind.make("codex"),
21+
enabled: true,
22+
installed: true,
23+
version: "1.0.0",
24+
status: "ready",
25+
auth: { status: "authenticated" },
26+
checkedAt: "2026-10-10T11:59:00.000Z",
27+
models: [{ slug: "gpt-6", name: "GPT-6", isCustom: false, capabilities: null }],
28+
slashCommands: [],
29+
skills: [],
30+
usageLimits: {
31+
checkedAt: "2026-10-10T11:59:00.000Z",
32+
windows: [
33+
{
34+
id: "secondary",
35+
kind: "weekly",
36+
label: "Weekly",
37+
usedPercent: weeklyUsed,
38+
resetsAt: "2026-10-14T02:00:00.000Z",
39+
},
40+
],
41+
},
42+
};
43+
}
44+
45+
const usedUp: ModelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6" };
46+
const providers = [provider("codex", 100), provider("codex_personal", 20)];
47+
48+
function command(overrides: Partial<LimitAccountSwitchCommand> = {}): LimitAccountSwitchCommand {
49+
return { dispatchMode: { type: "start_immediately" }, ...overrides };
50+
}
51+
52+
const idle = { modelSelection: usedUp, activeRunId: null };
53+
54+
describe("limitAccountSwitchSelection", () => {
55+
it("moves a fresh turn off the used-up account, whether the selection came with the message or from the thread", () => {
56+
expect(
57+
limitAccountSwitchSelection({ command: command(), thread: idle, providers, nowMs: NOW }),
58+
).toEqual({ instanceId: "codex_personal", model: "gpt-6" });
59+
expect(
60+
limitAccountSwitchSelection({
61+
command: command({ modelSelection: usedUp }),
62+
thread: { ...idle, modelSelection: { ...usedUp, instanceId: providers[1]!.instanceId } },
63+
providers,
64+
nowMs: NOW,
65+
}),
66+
).toEqual({ instanceId: "codex_personal", model: "gpt-6" });
67+
});
68+
69+
it("leaves a turn alone when the message already targets an account with allowance", () => {
70+
expect(
71+
limitAccountSwitchSelection({
72+
command: command({
73+
modelSelection: { ...usedUp, instanceId: providers[1]!.instanceId },
74+
}),
75+
thread: idle,
76+
providers,
77+
nowMs: NOW,
78+
}),
79+
).toBeNull();
80+
});
81+
82+
it("leaves work alone that belongs to a run already under way", () => {
83+
const runId = RunId.make("run:test");
84+
const cases: ReadonlyArray<[Partial<LimitAccountSwitchCommand>, RunId | null]> = [
85+
[{}, runId],
86+
[{ dispatchMode: { type: "steer_active", targetRunId: runId } }, null],
87+
[{ dispatchMode: { type: "restart_active", targetRunId: runId } }, null],
88+
[{ deliveryIntent: "steer" }, null],
89+
[{ restartContinuationOfRunId: runId }, null],
90+
[{ delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [] } }, null],
91+
];
92+
for (const [overrides, activeRunId] of cases) {
93+
expect(
94+
limitAccountSwitchSelection({
95+
command: command(overrides),
96+
thread: { ...idle, activeRunId },
97+
providers,
98+
nowMs: NOW,
99+
}),
100+
).toBeNull();
101+
}
102+
});
103+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Moves a new turn to another account of the same provider when the thread's
3+
* account has used up a quota window, so the turn does not fail on the limit
4+
* or run on paid credits while another subscription sits unused.
5+
*
6+
* Only fresh turns are rerouted. Work that belongs to a run already under way
7+
* (a steer, a restart, a delegated completion) stays on that run's account.
8+
*
9+
* @module LimitAccountSwitch
10+
*/
11+
import type {
12+
ModelSelection,
13+
OrchestrationV2Command,
14+
OrchestrationV2ThreadShell,
15+
ServerProvider,
16+
} from "@t3tools/contracts";
17+
import { selectionAfterExhaustedLimit } from "@t3tools/shared/usageLimitSwitch";
18+
19+
/** The parts of a message dispatch that decide whether its turn may be rerouted. */
20+
export type LimitAccountSwitchCommand = Pick<
21+
Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
22+
| "modelSelection"
23+
| "delegatedCompletion"
24+
| "restartContinuationOfRunId"
25+
| "deliveryIntent"
26+
| "dispatchMode"
27+
>;
28+
29+
/** Null when the command should be dispatched as it came. */
30+
export function limitAccountSwitchSelection(input: {
31+
readonly command: LimitAccountSwitchCommand;
32+
readonly thread: Pick<OrchestrationV2ThreadShell, "modelSelection" | "activeRunId">;
33+
readonly providers: ReadonlyArray<ServerProvider>;
34+
readonly nowMs: number;
35+
}): ModelSelection | null {
36+
const { command, thread } = input;
37+
if (
38+
thread.activeRunId !== null ||
39+
command.delegatedCompletion !== undefined ||
40+
command.restartContinuationOfRunId !== undefined ||
41+
command.deliveryIntent === "steer" ||
42+
command.deliveryIntent === "restart" ||
43+
command.dispatchMode.type === "steer_active" ||
44+
command.dispatchMode.type === "restart_active"
45+
) {
46+
return null;
47+
}
48+
return selectionAfterExhaustedLimit({
49+
providers: input.providers,
50+
current: command.modelSelection ?? thread.modelSelection,
51+
nowMs: input.nowMs,
52+
});
53+
}

‎apps/server/src/orchestration-v2/ThreadManagementService.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
type TurnItemId,
3131
} from "@t3tools/contracts";
3232
import { modelSelectionCommandType, modelSelectionsEqual } from "@t3tools/shared/model";
33+
import * as Clock from "effect/Clock";
3334
import * as Context from "effect/Context";
3435
import * as DateTime from "effect/DateTime";
3536
import * as Duration from "effect/Duration";
@@ -39,6 +40,9 @@ import * as Option from "effect/Option";
3940
import * as Schema from "effect/Schema";
4041
import * as Stream from "effect/Stream";
4142

43+
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
44+
import * as ServerSettings from "../serverSettings.ts";
45+
import { limitAccountSwitchSelection } from "./LimitAccountSwitch.ts";
4246
import * as Orchestrator from "./Orchestrator.ts";
4347
import { projectTurnItemForDetail } from "./WireProjection.ts";
4448
import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
@@ -452,6 +456,9 @@ const make = Effect.gen(function* () {
452456
const orchestrator = yield* Orchestrator.OrchestratorV2;
453457
const layerScope = yield* Effect.scope;
454458
const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
459+
// Optional, so harnesses that build this service without providers still work.
460+
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
461+
const providerRegistry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
455462

456463
const ensureLegacyTranscript = Effect.fn(
457464
"orchestrationV2.threadManagement.ensureLegacyTranscript",
@@ -518,8 +525,48 @@ const make = Effect.gen(function* () {
518525
Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
519526
);
520527

528+
// Every way to start a turn (clients, agent tools, scheduled tasks) comes
529+
// through here, so this is where a used-up account hands over. Reading the
530+
// limits is I/O, which the orchestrator's decisions must not do.
531+
const withLimitAccountSwitch = Effect.fn("orchestrationV2.threadManagement.limitAccountSwitch")(
532+
function* (command: Parameters<ThreadManagementServiceShape["dispatch"]>[0]) {
533+
if (
534+
command.type !== "message.dispatch" ||
535+
Option.isNone(serverSettings) ||
536+
Option.isNone(providerRegistry)
537+
) {
538+
return command;
539+
}
540+
const enabled = yield* serverSettings.value.getSettings.pipe(
541+
Effect.map((settings) => settings.switchAccountAtUsageLimit),
542+
Effect.orElseSucceed(() => false),
543+
);
544+
if (!enabled) return command;
545+
const thread = yield* orchestrator
546+
.getThreadShell(command.threadId)
547+
.pipe(Effect.orElseSucceed(() => null));
548+
if (thread === null) return command;
549+
const selection = limitAccountSwitchSelection({
550+
command,
551+
thread,
552+
providers: yield* providerRegistry.value.getProviders,
553+
nowMs: yield* Clock.currentTimeMillis,
554+
});
555+
if (selection === null) return command;
556+
yield* Effect.logInfo("Starting the turn on another account: usage limit reached", {
557+
threadId: command.threadId,
558+
from: (command.modelSelection ?? thread.modelSelection).instanceId,
559+
to: selection.instanceId,
560+
});
561+
return { ...command, modelSelection: selection };
562+
},
563+
);
564+
521565
const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
522-
ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
566+
ensureCommandTranscripts(command).pipe(
567+
Effect.andThen(withLimitAccountSwitch(command)),
568+
Effect.flatMap((routed) => orchestrator.dispatch(routed)),
569+
);
523570

524571
const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
525572
getThreadProjection(input.threadId).pipe(

‎packages/contracts/src/settings.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,6 +1116,12 @@ export const ServerSettings = Schema.Struct({
11161116
Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
11171117
),
11181118
enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1119+
/**
1120+
* Start a new turn on another signed-in account of the same provider when
1121+
* the thread's account has used up a quota window, instead of failing on the
1122+
* limit or spending paid credits.
1123+
*/
1124+
switchAccountAtUsageLimit: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
11191125
// Retain the update-era key; recovery now needs an environment-owned opt-in.
11201126
continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
11211127
Schema.withDecodingDefault(Effect.succeed(false)),
@@ -1467,6 +1473,7 @@ export const ServerSettingsPatch = Schema.Struct({
14671473
// Server settings
14681474
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
14691475
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1476+
switchAccountAtUsageLimit: Schema.optionalKey(Schema.Boolean),
14701477
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
14711478
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
14721479
projectAgentBrowserAccessOverrides: Schema.optionalKey(

0 commit comments

Comments
 (0)