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>
255 lines
7.8 KiB
TypeScript
255 lines
7.8 KiB
TypeScript
import { updatePairedTurnProgressText } from './db.js';
|
|
import { GroupQueue, GroupRunContext } from './group-queue.js';
|
|
import {
|
|
buildScopedMessageCheckEnqueuer,
|
|
processMessageLoopTick,
|
|
recoverPendingMessages as recoverRuntimePendingMessages,
|
|
} from './message-runtime-loop.js';
|
|
import { createImplicitContinuationTracker } from './message-runtime-rules.js';
|
|
import { schedulePairedFollowUpWithMessageCheck } from './message-runtime-follow-up.js';
|
|
import { Channel, NewMessage, RegisteredGroup } from './types.js';
|
|
import { logger } from './logger.js';
|
|
import {
|
|
createRunAgent,
|
|
createExecuteTurn,
|
|
isDuplicateOfLastBotFinal,
|
|
labelPairedSenders,
|
|
} from './message-runtime-turns.js';
|
|
import { handleMessageRuntimeAfterDeliverySuccess } from './message-runtime-after-delivery.js';
|
|
import { deliverMessageRuntimeFinalText } from './message-runtime-final-delivery.js';
|
|
import {
|
|
createProcessGroupMessages,
|
|
deliverRoomNotice,
|
|
} from './message-runtime-group-processing.js';
|
|
import { USER_STOP_CLOSE_REASON } from './message-close-reasons.js';
|
|
import type { RoomStopControls } from './room-stop.js';
|
|
|
|
export { isDuplicateOfLastBotFinal };
|
|
|
|
export interface MessageRuntimeDeps {
|
|
assistantName: string;
|
|
idleTimeout: number;
|
|
pollInterval: number;
|
|
timezone: string;
|
|
channels: Channel[];
|
|
queue: GroupQueue;
|
|
getRoomBindings: () => Record<string, RegisteredGroup>;
|
|
getSessions: () => Record<string, string>;
|
|
getLastTimestamp: () => string;
|
|
setLastTimestamp: (timestamp: string) => void;
|
|
getLastAgentTimestamps: () => Record<string, string>;
|
|
saveState: () => void;
|
|
persistSession: (groupFolder: string, sessionId: string) => void;
|
|
clearSession: (groupFolder: string, opts?: { allRoles?: boolean }) => void;
|
|
}
|
|
|
|
function createStartMessageLoop(args: {
|
|
pollInterval: number;
|
|
processTick: () => Promise<void>;
|
|
}): () => Promise<void> {
|
|
let messageLoopRunning = false;
|
|
|
|
return async (): Promise<void> => {
|
|
if (messageLoopRunning) {
|
|
logger.debug('Message loop already running, skipping duplicate start');
|
|
return;
|
|
}
|
|
messageLoopRunning = true;
|
|
|
|
logger.info('EJClaw running');
|
|
|
|
while (true) {
|
|
try {
|
|
await args.processTick();
|
|
} catch (err) {
|
|
logger.error({ err }, 'Error in message loop');
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, args.pollInterval));
|
|
}
|
|
};
|
|
}
|
|
|
|
function createRoomStopControls(
|
|
deps: Pick<MessageRuntimeDeps, 'queue' | 'channels' | 'getRoomBindings'>,
|
|
): RoomStopControls {
|
|
return {
|
|
hasQueuedWork: (chatJid) =>
|
|
(deps.queue.getStatuses([chatJid])[0]?.status ?? 'inactive') !==
|
|
'inactive',
|
|
stopRunningAgent: (chatJid) => {
|
|
deps.queue.closeStdin(chatJid, { reason: USER_STOP_CLOSE_REASON });
|
|
return deps.queue.killProcess(chatJid);
|
|
},
|
|
sendReply: (chatJid, text) =>
|
|
deliverRoomNotice(
|
|
{ channels: deps.channels, getRoomBindings: deps.getRoomBindings },
|
|
chatJid,
|
|
text,
|
|
),
|
|
};
|
|
}
|
|
|
|
export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
|
processGroupMessages: (
|
|
chatJid: string,
|
|
context: GroupRunContext,
|
|
) => Promise<boolean>;
|
|
recoverPendingMessages: () => void;
|
|
startMessageLoop: () => Promise<void>;
|
|
} {
|
|
const FAILURE_FINAL_TEXT = '요청을 완료하지 못했습니다. 다시 시도해 주세요.';
|
|
const continuationTracker = createImplicitContinuationTracker(
|
|
deps.idleTimeout,
|
|
);
|
|
const labelPairedRuntimeSenders = (
|
|
chatJid: string,
|
|
messages: NewMessage[],
|
|
): NewMessage[] => labelPairedSenders(deps.channels, chatJid, messages);
|
|
const enqueueScopedGroupMessageCheck = buildScopedMessageCheckEnqueuer(
|
|
deps.queue,
|
|
);
|
|
|
|
const checkDuplicateOfLastBotFinal = (
|
|
chatJid: string,
|
|
text: string,
|
|
): boolean => {
|
|
return isDuplicateOfLastBotFinal(chatJid, text);
|
|
};
|
|
const runAgent = createRunAgent({
|
|
assistantName: deps.assistantName,
|
|
queue: deps.queue,
|
|
getRoomBindings: deps.getRoomBindings,
|
|
getSessions: deps.getSessions,
|
|
persistSession: deps.persistSession,
|
|
clearSession: deps.clearSession,
|
|
});
|
|
const executeTurn = createExecuteTurn({
|
|
runAgent,
|
|
assistantName: deps.assistantName,
|
|
idleTimeout: deps.idleTimeout,
|
|
failureFinalText: FAILURE_FINAL_TEXT,
|
|
channels: deps.channels,
|
|
queue: deps.queue,
|
|
getRoomBindings: deps.getRoomBindings,
|
|
getSessions: deps.getSessions,
|
|
persistSession: deps.persistSession,
|
|
clearSession: deps.clearSession,
|
|
deliverFinalText: async ({
|
|
text,
|
|
attachments,
|
|
chatJid,
|
|
runId,
|
|
channel,
|
|
group,
|
|
startSeq,
|
|
endSeq,
|
|
forcedAgentType,
|
|
deliveryRole,
|
|
deliveryServiceId,
|
|
replaceMessageId,
|
|
}) => {
|
|
return deliverMessageRuntimeFinalText({
|
|
text,
|
|
attachments,
|
|
chatJid,
|
|
runId,
|
|
channel,
|
|
group,
|
|
startSeq,
|
|
endSeq,
|
|
forcedAgentType,
|
|
deliveryRole,
|
|
deliveryServiceId,
|
|
replaceMessageId,
|
|
hasDirectTerminalDeliveryForRun:
|
|
deps.queue.hasDirectTerminalDeliveryForRun?.bind(deps.queue),
|
|
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
|
openContinuation: (targetChatJid) =>
|
|
continuationTracker.open(targetChatJid),
|
|
});
|
|
},
|
|
recordTurnProgress: (turnId, progressText) => {
|
|
updatePairedTurnProgressText(turnId, progressText);
|
|
},
|
|
afterDeliverySuccess: async ({
|
|
chatJid,
|
|
runId,
|
|
deliveryRole,
|
|
pairedRoom,
|
|
}) => {
|
|
await handleMessageRuntimeAfterDeliverySuccess({
|
|
chatJid,
|
|
runId,
|
|
deliveryRole,
|
|
pairedRoom,
|
|
enqueueMessageCheck: (targetChatJid) =>
|
|
deps.queue.enqueueMessageCheck(targetChatJid),
|
|
});
|
|
},
|
|
});
|
|
|
|
const processGroupMessages = createProcessGroupMessages({
|
|
assistantName: deps.assistantName,
|
|
failureFinalText: FAILURE_FINAL_TEXT,
|
|
timezone: deps.timezone,
|
|
channels: deps.channels,
|
|
queue: deps.queue,
|
|
getRoomBindings: deps.getRoomBindings,
|
|
getLastAgentTimestamps: deps.getLastAgentTimestamps,
|
|
saveState: deps.saveState,
|
|
executeTurn,
|
|
openContinuation: continuationTracker.open,
|
|
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
|
labelPairedSenders: labelPairedRuntimeSenders,
|
|
});
|
|
|
|
const roomStopControls = createRoomStopControls(deps);
|
|
|
|
const startMessageLoop = createStartMessageLoop({
|
|
pollInterval: deps.pollInterval,
|
|
processTick: async () => {
|
|
await processMessageLoopTick({
|
|
assistantName: deps.assistantName,
|
|
failureFinalText: FAILURE_FINAL_TEXT,
|
|
timezone: deps.timezone,
|
|
channels: deps.channels,
|
|
getRoomBindings: deps.getRoomBindings,
|
|
getLastTimestamp: deps.getLastTimestamp,
|
|
setLastTimestamp: deps.setLastTimestamp,
|
|
lastAgentTimestamps: deps.getLastAgentTimestamps(),
|
|
saveState: deps.saveState,
|
|
hasImplicitContinuationWindow: continuationTracker.has,
|
|
executeTurn,
|
|
schedulePairedFollowUpWithMessageCheck,
|
|
enqueueScopedGroupMessageCheck,
|
|
sendQueuedMessage: deps.queue.sendMessage.bind(deps.queue),
|
|
closeStdin: (chatJid, reason) =>
|
|
deps.queue.closeStdin(chatJid, {
|
|
reason,
|
|
}),
|
|
isRunningMessageTurn: (chatJid) =>
|
|
deps.queue.getStatuses([chatJid])[0]?.runPhase === 'running_messages',
|
|
roomStopControls,
|
|
labelPairedSenders: labelPairedRuntimeSenders,
|
|
});
|
|
},
|
|
});
|
|
|
|
const recoverPendingMessages = (): void => {
|
|
recoverRuntimePendingMessages({
|
|
assistantName: deps.assistantName,
|
|
channels: deps.channels,
|
|
getRoomBindings: deps.getRoomBindings,
|
|
lastAgentTimestamps: deps.getLastAgentTimestamps(),
|
|
saveState: deps.saveState,
|
|
enqueueScopedGroupMessageCheck,
|
|
});
|
|
};
|
|
|
|
return {
|
|
processGroupMessages,
|
|
recoverPendingMessages,
|
|
startMessageLoop,
|
|
};
|
|
}
|