import { createProducedWorkItem } from './db.js'; import { resolveRuntimeAttachmentBaseDirs } from './attachment-base-dirs.js'; import { logger } from './logger.js'; import { deliverOpenWorkItem } from './message-runtime-delivery.js'; import { getOutboundStageDir, stageOutboundAttachments, } from './outbound-attachments.js'; import type { AgentType, Channel, OutboundAttachment, PairedRoomRole, RegisteredGroup, } from './types.js'; export async function deliverMessageRuntimeFinalText(args: { text: string; attachments?: OutboundAttachment[]; chatJid: string; runId: string; channel: Channel; group: RegisteredGroup; startSeq: number | null; endSeq: number | null; forcedAgentType?: AgentType; deliveryRole: PairedRoomRole | null; deliveryServiceId: string | null; replaceMessageId?: string | null; hasDirectTerminalDeliveryForRun?: ( chatJid: string, runId: string, deliveryRole: PairedRoomRole | null, ) => boolean; isDuplicateOfLastBotFinal: (chatJid: string, text: string) => boolean; openContinuation: (chatJid: string) => void; }): Promise { if ( (args.deliveryRole === 'reviewer' || args.deliveryRole === 'arbiter') && args.hasDirectTerminalDeliveryForRun?.( args.chatJid, args.runId, args.deliveryRole, ) ) { logger.info( { chatJid: args.chatJid, runId: args.runId, deliveryRole: args.deliveryRole, }, 'Skipping final work item delivery because this run already sent a direct terminal IPC message', ); return true; } const attachmentBaseDirs = resolveRuntimeAttachmentBaseDirs(args.group); // Relocate attachments that live outside the room's allowed directories into // a safe staging dir before persisting the work item, so the path delivery // actually uses (and revalidates) is one the validator accepts. Without this, // agent-generated files written to an arbitrary working path are rejected as // "outside-allowed-dirs" and silently dropped. const attachments = args.attachments?.length ? stageOutboundAttachments(args.attachments, { baseDirs: attachmentBaseDirs, stageDir: getOutboundStageDir(args.group.folder), }) : args.attachments; const workItem = createProducedWorkItem({ group_folder: args.group.folder, chat_jid: args.chatJid, agent_type: args.forcedAgentType ?? args.group.agentType ?? 'claude-code', service_id: args.deliveryServiceId ?? undefined, delivery_role: args.deliveryRole, start_seq: args.startSeq, end_seq: args.endSeq, result_payload: args.text, attachments, }); return deliverOpenWorkItem({ channel: args.channel, item: workItem, log: logger, attachmentBaseDirs, replaceMessageId: args.replaceMessageId, isDuplicateOfLastBotFinal: args.isDuplicateOfLastBotFinal, openContinuation: args.openContinuation, }); }