Skip to content
Merged
63 changes: 52 additions & 11 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3265,6 +3265,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
readonly text?: string;
readonly parentToolUseId?: string | null;
readonly apiErrorParams?: unknown;
readonly apiError?: string;
}) =>
claudeSdkFrame({
type: "assistant",
Expand All @@ -3286,6 +3287,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
parent_tool_use_id: input.parentToolUseId ?? null,
...(input.error === undefined ? {} : { error: input.error }),
...(input.apiErrorParams === undefined ? {} : { api_error_params: input.apiErrorParams }),
...(input.apiError === undefined ? {} : { api_error: input.apiError }),
uuid: input.uuid,
session_id: WAKE_NATIVE_SESSION,
});
Expand Down Expand Up @@ -7362,9 +7364,18 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);

it.effect("keeps a later future-window event-supplied Claude reset over the embedded reset", () =>
it.effect.each([
{ rateLimitType: "five_hour", scope: "account", proseOnly: false },
{ rateLimitType: "seven_day_overage_included", scope: "model", proseOnly: false },
{ rateLimitType: "model_requires_usage_credits", scope: "model", proseOnly: false },
{ rateLimitType: "unknown", scope: "model", proseOnly: true },
] as const)("preserves Claude limit scope and the later reset: $rateLimitType", (scenario) =>
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const usageCredits = scenario.scope === "model" && !scenario.proseOnly;
const limitText = usageCredits
? "You're out of usage credits. Switch to another model, or manage usage credits at https://claude.ai/admin-settings/usage, to continue."
: "Usage limit reached.";
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
Expand All @@ -7376,10 +7387,18 @@ describe("ClaudeAdapterV2 background wake turns", () => {
}),
);
yield* Queue.offerAll(harness.sdkMessages, [
...["five_hour", "seven_day"].map((rateLimitType) =>
claudeSdkFrame({
type: "rate_limit_event",
rate_limit_info: { status: "allowed", rateLimitType },
uuid: `allowed-${rateLimitType}`,
session_id: WAKE_NATIVE_SESSION,
}),
),
claudeSdkFrame({
type: "rate_limit_event",
rate_limit_info: {
status: "rejected",
status: usageCredits ? "allowed" : "rejected",
rateLimitType: "future_window",
resetsAt: 1791807600,
},
Expand All @@ -7389,17 +7408,31 @@ describe("ClaudeAdapterV2 background wake turns", () => {
makeAssistantErrorFrame({
uuid: "00000000-0000-4000-8000-000000000684",
error: "rate_limit",
apiErrorParams: {
rate_limit_info: {
status: "rejected",
rateLimitType: "five_hour",
resetsAt: 1791804000,
},
},
...(usageCredits ? { apiError: "model_requires_usage_credits" } : {}),
text: scenario.proseOnly
? "Usage limit reached until the 7-day Fable limit resets in 145h"
: limitText,
apiErrorParams:
scenario.proseOnly || scenario.rateLimitType === "model_requires_usage_credits"
? undefined
: {
rate_limit_info: {
status: "rejected",
rateLimitType: scenario.rateLimitType,
resetsAt: usageCredits ? 1794985200 : 1791804000,
...(usageCredits
? {
overageStatus: "rejected",
overageDisabledReason: "out_of_credits",
isUsingOverage: false,
}
: {}),
},
},
}),
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000685",
result: "Usage limit reached.",
result: limitText,
isError: true,
apiErrorStatus: 429,
terminalReason: "api_error",
Expand All @@ -7409,7 +7442,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
assert.equal(terminal.status, "failed");
if (terminal.status !== "failed") return;
assert.equal(terminal.failure.class, "usage_limit");
assert.equal(terminal.failure.resetAt, "2026-10-12T12:20:00.000Z");
assert.equal(
terminal.failure.resetAt,
usageCredits
? scenario.rateLimitType === "model_requires_usage_credits"
? null
: "2026-11-18T07:00:00.000Z"
: "2026-10-12T12:20:00.000Z",
);
assert.equal(terminal.failure.limitScope, scenario.scope);
assert.equal(terminal.accountFailure, "usage_limit");
assert.equal(terminal.noWorkObserved, true);
}).pipe(
Expand Down
33 changes: 31 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ import {
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
claudeRateLimitEventToUpdate,
claudeUsageLimitScope,
type ClaudeScopedLimitNames,
} from "../../provider/claudeUsageLimits.ts";
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
Expand Down Expand Up @@ -4382,6 +4383,9 @@ function isClaudeEmptyTaskNotificationSuccess(message: SDKMessage): boolean {

// The CLI throttles unchanged rate_limit_event frames, but repeats this
// undeclared payload on each blocked assistant response.
const isClaudeModelUsageCreditsError = Schema.is(
Schema.Struct({ api_error: Schema.Literal("model_requires_usage_credits") }),
);
const isClaudeBlockedAssistantRateLimit = Schema.is(
Schema.Struct({
api_error_params: Schema.Struct({
Expand Down Expand Up @@ -4826,6 +4830,7 @@ interface ActiveClaudeTurnContext {
latestAssistantRateLimit: {
readonly type: string | null;
readonly resetAt: string | null;
readonly scope?: "account" | "model" | undefined;
} | null;
// Set while this turn's latest compaction status reports a failure, with
// Claude's error text when it sent one.
Expand Down Expand Up @@ -10315,7 +10320,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
// Subagent uuids exist only in the sidechain transcript, so resume and fork cannot target them.
context.nativeMessageCursor = message.uuid;
context.latestAssistantRateLimit =
message.error === "rate_limit" ? { type: null, resetAt: null } : null;
message.error === "rate_limit"
? {
type: null,
resetAt: null,
scope: claudeUsageLimitScope(
isClaudeModelUsageCreditsError(message)
? ["model_requires_usage_credits"]
: [],
textFromClaudeContent(message.message.content),
),
}
: null;
if (message.error === "rate_limit" && isClaudeBlockedAssistantRateLimit(message)) {
const info = message.api_error_params.rate_limit_info;
const overageAllowed =
Expand All @@ -10325,6 +10341,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
info.overageInUse === true;
if (!overageAllowed) {
context.latestAssistantRateLimit = {
scope: context.latestAssistantRateLimit?.scope,
type: typeof info.rateLimitType === "string" ? info.rateLimitType : "unknown",
resetAt: claudeUsageLimitResetAt(info.resetsAt),
};
Expand Down Expand Up @@ -11322,9 +11339,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
failureHint,
usageLimited,
);
const limitScope =
claudeUsageLimitScope(
[
...context.rejectedRateLimitTypes,
...(assistantLimit?.type == null ? [] : [assistantLimit.type]),
],
message.subtype === "success" ? message.result : message.errors.join("\n"),
) ?? assistantLimit?.scope;
const terminalFailure =
resultFailure?.class === "usage_limit"
? { ...resultFailure, resetAt: resetAt ?? resultFailure.resetAt ?? null }
? {
...resultFailure,
resetAt: resetAt ?? resultFailure.resetAt ?? null,
...(limitScope === undefined ? {} : { limitScope }),
}
: resultFailure;
const accountFailure =
terminalFailure === null
Expand Down
156 changes: 119 additions & 37 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4016,56 +4016,88 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);

it.effect("reports a thread another Codex client is writing to as in use", () =>
it.effect.each(["exhaust", "recover"] as const)("bounds active-writer retries: %s", (outcome) =>
Effect.scoped(
Effect.gen(function* () {
const nativeThreadId = "thread-open-elsewhere";
const harness = yield* makeCodexReplayHarness(
makeCodexReplayTranscript({
scenario: "codex-resume-active-writer",
entries: [
...codexReplayPreamble({
nativeThreadId,
nativeTurnId: "unused-turn",
prompt: "unused-prompt",
}).slice(0, 5),
{
type: "expect_outbound",
label: "thread/resume",
frame: {
id: 3,
method: "thread/resume",
params: {
threadId: nativeThreadId,
excludeTurns: true,
cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
model: CODEX_TEST_MODEL_SELECTION.model,
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
},
const resumed = yield* Queue.unbounded<void>();
const preamble = codexReplayPreamble({
nativeThreadId,
nativeTurnId: "unused-turn",
prompt: "unused-prompt",
});
const started = preamble[4];
assert(started?.type === "emit_inbound");
const entries: Array<CodexReplay.CodexAppServerReplayEntry> = preamble.slice(0, 5);
for (let attempt = 0; attempt < (outcome === "recover" ? 2 : 4); attempt++) {
const requestId = 3 + attempt;
entries.push(
{
type: "expect_outbound",
label: "thread/resume",
frame: {
id: requestId,
method: "thread/resume",
params: {
threadId: nativeThreadId,
excludeTurns: true,
cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
model: CODEX_TEST_MODEL_SELECTION.model,
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
},
},
{
type: "emit_inbound",
label: "active writer",
frame: {
id: 3,
error: {
code: -32600,
message: `thread ${nativeThreadId} already has an active writer`,
},
outcome === "recover" && attempt === 1
? withReplayRequestId(started, requestId)
: {
type: "emit_inbound",
label: "resume result",
frame: {
id: requestId,
error: {
code: -32600,
message: `thread ${nativeThreadId} already has an active writer`,
},
},
},
},
],
);
}
const harness = yield* makeCodexReplayHarness(
makeCodexReplayTranscript({
scenario: "codex-resume-active-writer",
entries,
}),
() => Effect.void,
(method) =>
method === "thread/resume"
? Queue.offer(resumed, undefined).pipe(Effect.asVoid)
: Effect.void,
);

const error = yield* Effect.flip(
harness.runtime.resumeThread({
const resume = yield* harness.runtime
.resumeThread({
providerThread: harness.providerThread,
modelSelection: CODEX_TEST_MODEL_SELECTION,
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
}),
);
})
.pipe(Effect.result, Effect.forkChild);
yield* Queue.take(resumed);
yield* TestClock.adjust("250 millis");
yield* Queue.take(resumed);
if (outcome === "exhaust") {
yield* TestClock.adjust("500 millis");
yield* Queue.take(resumed);
yield* TestClock.adjust("1 second");
yield* Queue.take(resumed);
}
const result = yield* Fiber.join(resume);
if (outcome === "recover") {
assert.equal(result._tag, "Success");
return;
}
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") return;
const error = result.failure;

assert.equal(error._tag, "ProviderAdapterThreadInUseError");
assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id);
Expand Down Expand Up @@ -6696,6 +6728,49 @@ describe("CodexAdapterV2 post-settle continuation", () => {
expectedCode: "subscription_sharing_v2_invalid_user",
expectedMessage: "could not validate",
},
{
name: "sharing-unsupported-namespace-terminal",
code: "other",
message: JSON.stringify({
error: {
code: "subscription_sharing_unsupported_capability",
message: "tool 'namespace' is not supported; dummy-sensitive",
},
}),
notification: false,
expectedClass: "provider_error",
expectedCode: "subscription_sharing_unsupported_capability",
expectedMessage: "namespace",
},
{
name: "sharing-unsupported-additional-tools-notification",
code: "other",
details: JSON.stringify({
error: {
code: "subscription_sharing_unsupported_capability",
message: "input item 'additional_tools' is not supported; dummy-sensitive",
},
}),
notification: true,
expectedClass: "provider_error",
expectedCode: "subscription_sharing_unsupported_capability",
expectedMessage: "additional_tools",
},
{
name: "sharing-unsupported-namespace-retry",
code: "other",
details: JSON.stringify({
error: {
code: "subscription_sharing_unsupported_capability",
message: "tool 'namespace' is not supported; dummy-sensitive",
},
}),
notification: true,
willRetry: true,
expectedClass: "provider_error",
expectedCode: "subscription_sharing_unsupported_capability",
expectedMessage: "namespace",
},
] as const)("classifies Codex terminal failures from $name evidence", (scenario) =>
Effect.scoped(
Effect.gen(function* () {
Expand Down Expand Up @@ -7029,6 +7104,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(terminal.failure.code, scenario.expectedCode);
assert.include(terminal.failure.message, scenario.expectedMessage);
assert.equal(terminal.failure.resetAt, null);
if (scenario.expectedCode === "subscription_sharing_unsupported_capability") {
assert.include(
terminal.failure.message,
`Codex instance "${CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID}"`,
);
assert.notInclude(terminal.failure.message, "dummy-sensitive");
}
}
}).pipe(
Effect.provide(
Expand Down
Loading
Loading