refactor: replace the Claude→Codex failover with a usage-limit notice

When Claude hit a limit the run was handed to a Codex service
(codex-main/codex-review) through service_handoffs and a global owner
failover. That service does not exist in this deployment, so handoffs
stayed pending forever (2 rows since May) and the user got no answer.

Removed:
- handoff creation (message-agent-executor-handoff, paired-turn-fallback)
  and the delegated paired-execution path
- the pending-handoff poll/claim worker (message-runtime-handoffs) and the
  service_handoffs CRUD module (db/service-handoffs, db exports)
- global owner failover in service-routing, its recovery timer in index,
  the dashboard failover line, the codex-review failover prompt pack and
  prompts/codex-review-failover-platform.md
- failoverOwner in RoomRoleContext and the `failover=` ROOM_ROLE field
- OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED and FAILOVER_MIN_DURATION_MS
- tests for the removed behaviour

Now, when a Claude run fails with a usage/rate limit (trigger reason
429 or usage-exhausted) the executor closes the open paired task as
completed/claude_usage_limit and sends the room one final notice:
"Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다." The reset time
comes from the error text (CLI banner "resets 9:40pm (Asia/Seoul)", dated
banners, "try again at ...", ISO timestamps), else from the cached usage
API window at 100%, else "잠시 후 다시 시도해 주세요". Nothing retries
silently; the next user message starts a new task. Other Claude failures
(session failure, org access denied) now end as ordinary run errors.

The service_handoffs table, its columns on paired_turn_attempts and the
migrations stay untouched for the later migration squash; the runtime no
longer reads or writes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:14:25 +09:00
parent a9eab5cb94
commit 8c68577a24
62 changed files with 719 additions and 3963 deletions

View File

@@ -1,11 +1,19 @@
import { AgentOutput } from './agent-runner.js';
import { GroupQueue } from './group-queue.js';
import type { AgentTriggerReason } from './agent-error-detection.js';
import { createPairedExecutionLifecycle } from './message-agent-executor-paired.js';
import {
createPairedExecutionLifecycle,
type PairedExecutionLifecycle,
} from './message-agent-executor-paired.js';
import type { PairedTurnIdentity } from './paired-turn-identity.js';
import { executeMessageAgentAttemptLifecycle } from './message-agent-executor-lifecycle.js';
import { runMessageAgentAttempt } from './message-agent-executor-attempt-runner.js';
import { handoffMessageAgentExecutionToCodex } from './message-agent-executor-handoff.js';
import {
buildClaudeUsageLimitMessage,
isClaudeUsageLimitReason,
} from './claude-usage-limit.js';
import { getPairedTaskById } from './db.js';
import { completePairedTaskWithReason } from './paired-task-status.js';
import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js';
import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js';
import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js';
@@ -17,6 +25,9 @@ import {
// ── Main executor ─────────────────────────────────────────────────
/** completion_reason of a paired task closed because Claude ran out of usage. */
export const CLAUDE_USAGE_LIMIT_COMPLETION_REASON = 'claude_usage_limit';
function buildPromptWithCompactRefresh(args: {
prompt: string;
sessionFolder: string;
@@ -47,6 +58,73 @@ function clearAppliedCompactRefreshAfterSuccess(args: {
});
}
interface ClaudeUsageLimitFailure {
reason: AgentTriggerReason;
errorText: string | null;
}
/**
* When a Claude run failed because the account is out of usage, close the
* paired task (nothing should retry against the exhausted account; the next
* user message starts a new task) and tell the room when Claude resets.
* Returns false for any other failure.
*/
async function reportClaudeUsageLimitToRoom(
args: ClaudeUsageLimitFailure & {
isClaudeCodeAgent: boolean;
activeRole: PairedRoomRole;
pairedTaskId?: string;
pairedExecutionLifecycle: Pick<
PairedExecutionLifecycle,
'updateSummary' | 'completeImmediately'
>;
onOutput?: (output: AgentOutput) => Promise<void>;
log: { warn: (obj: Record<string, unknown>, msg: string) => void };
},
): Promise<boolean> {
if (!args.isClaudeCodeAgent || !isClaudeUsageLimitReason(args.reason)) {
return false;
}
const notice = buildClaudeUsageLimitMessage(args.errorText);
const task = args.pairedTaskId
? getPairedTaskById(args.pairedTaskId)
: undefined;
if (task) {
completePairedTaskWithReason(task, CLAUDE_USAGE_LIMIT_COMPLETION_REASON);
}
args.log.warn(
{ reason: args.reason, role: args.activeRole, notice },
'Claude usage limit reached; told the room when it resets',
);
await deliverNoticeAndFailExecution({
notice,
summary: args.errorText ?? notice,
pairedExecutionLifecycle: args.pairedExecutionLifecycle,
onOutput: args.onOutput,
});
return true;
}
/** Send a final notice to the room and record the execution as failed. */
async function deliverNoticeAndFailExecution(args: {
notice: string;
summary: string;
pairedExecutionLifecycle: Pick<
PairedExecutionLifecycle,
'updateSummary' | 'completeImmediately'
>;
onOutput?: (output: AgentOutput) => Promise<void>;
}): Promise<void> {
args.pairedExecutionLifecycle.updateSummary({ outputText: args.summary });
await args.onOutput?.({
status: 'success',
result: null,
output: { visibility: 'public', text: args.notice },
phase: 'final',
});
args.pairedExecutionLifecycle.completeImmediately({ status: 'failed' });
}
export interface MessageAgentExecutorDeps {
assistantName: string;
queue: Pick<GroupQueue, 'registerProcess' | 'enqueueMessageCheck'> &
@@ -92,7 +170,6 @@ export async function runAgentForGroup(
pairedTurnIdentity: args.pairedTurnIdentity,
});
const {
currentLease,
activeRole,
effectiveServiceId,
effectiveAgentType,
@@ -147,24 +224,14 @@ export async function runAgentForGroup(
runtimePairedTurnIdentity?.role ?? activeRole,
);
const maybeHandoffToCodex = (
reason: AgentTriggerReason,
sawVisibleOutput: boolean,
): boolean =>
isClaudeCodeAgent &&
handoffMessageAgentExecutionToCodex({
const reportClaudeUsageLimit = (limit: ClaudeUsageLimitFailure) =>
reportClaudeUsageLimitToRoom({
...limit,
isClaudeCodeAgent,
activeRole,
effectiveAgentType,
hasReviewer: currentLease.reviewer_agent_type !== null,
reason,
sawVisibleOutput,
prompt,
startSeq,
endSeq,
chatJid,
group,
pairedTurnIdentity: runtimePairedTurnIdentity,
markDelegated: () => pairedExecutionLifecycle.markDelegated(),
pairedTaskId: pairedExecutionContext?.task.id,
pairedExecutionLifecycle,
onOutput,
log,
});
@@ -180,9 +247,6 @@ export async function runAgentForGroup(
};
if (pairedExecutionContext?.blockMessage) {
pairedExecutionLifecycle.updateSummary({
outputText: pairedExecutionContext.blockMessage,
});
log.warn(
{
roomRoleServiceId: roomRoleContext?.serviceId,
@@ -190,16 +254,12 @@ export async function runAgentForGroup(
},
'Blocked paired execution before runner start',
);
await onOutput?.({
status: 'success',
result: null,
output: {
visibility: 'public',
text: pairedExecutionContext.blockMessage,
},
phase: 'final',
await deliverNoticeAndFailExecution({
notice: pairedExecutionContext.blockMessage,
summary: pairedExecutionContext.blockMessage,
pairedExecutionLifecycle,
onOutput,
});
pairedExecutionLifecycle.completeImmediately({ status: 'failed' });
return 'success';
}
@@ -242,7 +302,7 @@ export async function runAgentForGroup(
},
clearRoleSdkSessions,
sessionFolder,
maybeHandoffToCodex,
reportClaudeUsageLimit,
hasDirectTerminalDelivery,
pairedExecutionLifecycle,
shouldRetryFreshSessionOnAgentFailure,