@@ -6,14 +6,21 @@ import {
66 resolveDefaultAgentId ,
77} from "../../agents/agent-scope-config.js" ;
88import { resolveSessionAgentId } from "../../agents/agent-scope.js" ;
9- import type { ReplyPayload } from "../../auto-reply/reply-payload.js" ;
9+ import { copyReplyPayloadMetadata , type ReplyPayload } from "../../auto-reply/reply-payload.js" ;
1010import { normalizeReplyPayload } from "../../auto-reply/reply/normalize-reply.js" ;
1111import { createReplyMediaPathNormalizer } from "../../auto-reply/reply/reply-media-paths.runtime.js" ;
12+ import { formatBtwTextForExternalDelivery } from "../../auto-reply/reply/reply-payloads-base.js" ;
13+ import {
14+ filterMessagingToolMediaDuplicates ,
15+ resolveMessagingToolPayloadDedupe ,
16+ } from "../../auto-reply/reply/reply-payloads-dedupe.runtime.js" ;
17+ import { resolveResponsePrefixTemplate } from "../../auto-reply/reply/response-prefix-template.js" ;
1218import {
1319 sendDurableMessageBatch ,
1420 serializeDurableMessagePayloadOutcomes ,
1521 type SerializedDurableMessagePayloadOutcome ,
1622} from "../../channels/message/runtime.js" ;
23+ import { resolveChannelDefaultAccountId } from "../../channels/plugins/helpers.js" ;
1724import { getChannelPlugin , normalizeChannelId } from "../../channels/plugins/index.js" ;
1825import { createReplyPrefixContext } from "../../channels/reply-prefix.js" ;
1926import { createOutboundSendDeps , type CliDeps } from "../../cli/outbound-send-deps.js" ;
@@ -30,10 +37,12 @@ import {
3037 createOutboundPayloadPlan ,
3138 formatOutboundPayloadLog ,
3239 type NormalizedOutboundPayload ,
40+ projectOutboundPayloadPlanForDelivery ,
3341 projectOutboundPayloadPlanForJson ,
3442 projectOutboundPayloadPlanForOutbound ,
3543} from "../../infra/outbound/payloads.js" ;
3644import type { OutboundSessionContext } from "../../infra/outbound/session-context.js" ;
45+ import { hasReplyPayloadContent } from "../../interactive/payload.js" ;
3746import { type RuntimeEnv , writeRuntimeJson } from "../../runtime.js" ;
3847import { isInternalMessageChannel } from "../../utils/message-channel.js" ;
3948import type { MessagingToolSend } from "../embedded-agent-messaging.types.js" ;
@@ -306,16 +315,19 @@ async function normalizeReplyMediaPathsForDelivery(params: {
306315 outboundSession : OutboundSessionContext | undefined ;
307316 deliveryChannel : string ;
308317 accountId ?: string ;
309- } ) : Promise < ReplyPayload [ ] > {
318+ } ) : Promise < {
319+ payloads : ReplyPayload [ ] ;
320+ normalizeMediaPaths ?: ( payload : ReplyPayload ) => Promise < ReplyPayload > ;
321+ } > {
310322 if ( params . payloads . length === 0 ) {
311- return params . payloads ;
323+ return { payloads : params . payloads } ;
312324 }
313325 const agentId =
314326 params . outboundSession ?. agentId ??
315327 resolveSessionAgentId ( { sessionKey : params . sessionKey , config : params . cfg } ) ;
316328 const workspaceDir = agentId ? resolveAgentWorkspaceDir ( params . cfg , agentId ) : undefined ;
317329 if ( ! workspaceDir ) {
318- return params . payloads ;
330+ return { payloads : params . payloads } ;
319331 }
320332 const normalizeMediaPaths = createReplyMediaPathNormalizer ( {
321333 cfg : params . cfg ,
@@ -329,7 +341,131 @@ async function normalizeReplyMediaPathsForDelivery(params: {
329341 for ( const payload of params . payloads ) {
330342 result . push ( await normalizeMediaPaths ( payload ) ) ;
331343 }
332- return result ;
344+ return { payloads : result , normalizeMediaPaths } ;
345+ }
346+
347+ async function normalizeSentMediaUrlsForDelivery ( params : {
348+ sentMediaUrls : readonly string [ ] ;
349+ normalizeMediaPaths ?: ( payload : ReplyPayload ) => Promise < ReplyPayload > ;
350+ } ) : Promise < string [ ] > {
351+ const normalizedUrls : string [ ] = [ ] ;
352+ const seen = new Set < string > ( ) ;
353+ for ( const raw of params . sentMediaUrls ) {
354+ const trimmed = raw . trim ( ) ;
355+ if ( ! trimmed ) {
356+ continue ;
357+ }
358+ if ( ! seen . has ( trimmed ) ) {
359+ seen . add ( trimmed ) ;
360+ normalizedUrls . push ( trimmed ) ;
361+ }
362+ if ( ! params . normalizeMediaPaths ) {
363+ continue ;
364+ }
365+ try {
366+ const normalized = await params . normalizeMediaPaths ( {
367+ mediaUrl : trimmed ,
368+ mediaUrls : [ trimmed ] ,
369+ } ) ;
370+ for ( const mediaUrl of [ normalized . mediaUrl , ...( normalized . mediaUrls ?? [ ] ) ] ) {
371+ const candidate = mediaUrl ?. trim ( ) ;
372+ if ( ! candidate || seen . has ( candidate ) ) {
373+ continue ;
374+ }
375+ seen . add ( candidate ) ;
376+ normalizedUrls . push ( candidate ) ;
377+ }
378+ } catch {
379+ // Keep the original evidence. Delivery normalization will report invalid media separately.
380+ }
381+ }
382+ return normalizedUrls ;
383+ }
384+
385+ const UNRESOLVED_RESPONSE_PREFIX_VAR_PATTERN = / \{ [ a - z A - Z ] [ a - z A - Z 0 - 9 . ] * \} / ;
386+
387+ async function filterAlreadyDeliveredReplyPayloads ( params : {
388+ cfg : OpenClawConfig ;
389+ payloads : ReplyPayload [ ] ;
390+ result : RunResult ;
391+ deliveryChannel : string ;
392+ deliveryTarget : string ;
393+ accountId ?: string ;
394+ sourceAccountId ?: string ;
395+ defaultAccountId ?: string ;
396+ threadId ?: string | number ;
397+ normalizeMediaPaths ?: ( payload : ReplyPayload ) => Promise < ReplyPayload > ;
398+ normalizeSentTexts ?: ( sentTexts : readonly string [ ] ) => string [ ] ;
399+ } ) : Promise < ReplyPayload [ ] > {
400+ const sentTexts = params . result . messagingToolSentTexts ?? [ ] ;
401+ const sentMediaUrls = params . result . messagingToolSentMediaUrls ?? [ ] ;
402+ // The message tool injects the run account after telemetry captures its
403+ // original args. Preserve that source route before falling back to default.
404+ const implicitToolAccountId = params . sourceAccountId ?? params . defaultAccountId ;
405+ const sentTargets = ( params . result . messagingToolSentTargets ?? [ ] ) . flatMap ( ( target ) => {
406+ if ( target . accountId || ! params . accountId ) {
407+ return [ target ] ;
408+ }
409+ return implicitToolAccountId ? [ { ...target , accountId : implicitToolAccountId } ] : [ ] ;
410+ } ) ;
411+ if ( sentTexts . length === 0 && sentMediaUrls . length === 0 && sentTargets . length === 0 ) {
412+ return params . payloads ;
413+ }
414+
415+ const decision = resolveMessagingToolPayloadDedupe ( {
416+ config : params . cfg ,
417+ messageProvider : params . deliveryChannel ,
418+ messagingToolSentTargets : sentTargets ,
419+ originatingTo : params . deliveryTarget ,
420+ originatingThreadId : params . threadId ,
421+ accountId : params . accountId ,
422+ } ) ;
423+ if ( ! decision . matchingRoute ) {
424+ return params . payloads ;
425+ }
426+ const routeSentMediaUrls = decision . useGlobalSentMediaUrlEvidenceFallback
427+ ? sentMediaUrls
428+ : decision . routeSentMediaUrls ;
429+ const rawRouteSentTexts = decision . useGlobalSentTextEvidenceFallback
430+ ? sentTexts
431+ : decision . routeSentTexts ;
432+ const routeSentTexts = params . normalizeSentTexts ?.( rawRouteSentTexts ) ?? rawRouteSentTexts ;
433+ const exactRouteSentTexts = new Set ( routeSentTexts . filter ( ( text ) => Boolean ( text . trim ( ) ) ) ) ;
434+ const normalizedSentMediaUrls = await normalizeSentMediaUrlsForDelivery ( {
435+ sentMediaUrls : routeSentMediaUrls ,
436+ normalizeMediaPaths : params . normalizeMediaPaths ,
437+ } ) ;
438+ const mediaFiltered = filterMessagingToolMediaDuplicates ( {
439+ payloads : params . payloads ,
440+ sentMediaUrls : normalizedSentMediaUrls ,
441+ } ) ;
442+
443+ const filteredPayloads : ReplyPayload [ ] = [ ] ;
444+ for ( const candidate of mediaFiltered ) {
445+ if ( candidate . delivery ) {
446+ filteredPayloads . push ( candidate ) ;
447+ continue ;
448+ }
449+ const effectiveCandidateText =
450+ formatBtwTextForExternalDelivery ( candidate ) ?? candidate . text ?? "" ;
451+ if ( ! effectiveCandidateText . trim ( ) || ! exactRouteSentTexts . has ( effectiveCandidateText ) ) {
452+ filteredPayloads . push ( candidate ) ;
453+ continue ;
454+ }
455+ const withoutDuplicateText = copyReplyPayloadMetadata ( candidate , {
456+ ...candidate ,
457+ text : undefined ,
458+ } ) ;
459+ if (
460+ hasReplyPayloadContent ( withoutDuplicateText , {
461+ trimText : true ,
462+ extraContent : withoutDuplicateText . location != null ,
463+ } )
464+ ) {
465+ filteredPayloads . push ( withoutDuplicateText ) ;
466+ }
467+ }
468+ return filteredPayloads ;
333469}
334470
335471/** Normalizes reply payloads and media paths before delivery. */
@@ -342,6 +478,7 @@ export function normalizeAgentCommandReplyPayloads(params: {
342478 deliveryChannel ?: string ;
343479 accountId ?: string ;
344480 applyChannelTransforms ?: boolean ;
481+ includeRunModelContext ?: boolean ;
345482} ) : ReplyPayload [ ] {
346483 const payloads = params . payloads ?? [ ] ;
347484 if ( payloads . length === 0 ) {
@@ -372,14 +509,24 @@ export function normalizeAgentCommandReplyPayloads(params: {
372509 } ) ;
373510 const modelUsed = params . result . meta . agentMeta ?. model ;
374511 const providerUsed = params . result . meta . agentMeta ?. provider ;
375- if ( providerUsed && modelUsed ) {
512+ if ( params . includeRunModelContext !== false && providerUsed && modelUsed ) {
376513 replyPrefix . onModelSelected ( {
377514 provider : providerUsed ,
378515 model : modelUsed ,
379516 thinkLevel : undefined ,
380517 } ) ;
381518 }
382519 const responsePrefixContext = replyPrefix . responsePrefixContextProvider ( ) ;
520+ const resolvedResponsePrefix = resolveResponsePrefixTemplate (
521+ replyPrefix . responsePrefix ,
522+ responsePrefixContext ,
523+ ) ;
524+ const responsePrefix =
525+ params . includeRunModelContext === false &&
526+ resolvedResponsePrefix &&
527+ UNRESOLVED_RESPONSE_PREFIX_VAR_PATTERN . test ( resolvedResponsePrefix )
528+ ? undefined
529+ : replyPrefix . responsePrefix ;
383530 const transformReplyPayload = deliveryPlugin ?. messaging ?. transformReplyPayload
384531 ? ( payload : ReplyPayload ) =>
385532 deliveryPlugin . messaging ?. transformReplyPayload ?.( {
@@ -392,7 +539,7 @@ export function normalizeAgentCommandReplyPayloads(params: {
392539 const normalizedPayloads : ReplyPayload [ ] = [ ] ;
393540 for ( const payload of payloads ) {
394541 const normalized = normalizeReplyPayload ( payload as ReplyPayload , {
395- responsePrefix : replyPrefix . responsePrefix ,
542+ responsePrefix,
396543 applyChannelTransforms,
397544 responsePrefixContext,
398545 transformReplyPayload,
@@ -470,12 +617,19 @@ export async function deliverAgentCommandResult(
470617 opts . deliveryTargetMode ??
471618 effectiveDeliveryPlan . deliveryTargetMode ??
472619 ( opts . to ? "explicit" : "implicit" ) ;
473- const resolvedAccountId = effectiveDeliveryPlan . resolvedAccountId ;
620+ const defaultAccountId = deliveryPlugin
621+ ? resolveChannelDefaultAccountId ( { plugin : deliveryPlugin , cfg } )
622+ : undefined ;
623+ const resolvedAccountId = effectiveDeliveryPlan . resolvedAccountId ?? defaultAccountId ;
624+ const resolvedDeliveryPlan =
625+ resolvedAccountId === effectiveDeliveryPlan . resolvedAccountId
626+ ? effectiveDeliveryPlan
627+ : { ...effectiveDeliveryPlan , resolvedAccountId } ;
474628 const resolved =
475629 deliver && isDeliveryChannelKnown && deliveryChannel
476630 ? resolveAgentOutboundTarget ( {
477631 cfg,
478- plan : effectiveDeliveryPlan ,
632+ plan : resolvedDeliveryPlan ,
479633 targetMode,
480634 validateExplicitTarget : true ,
481635 } )
@@ -494,10 +648,11 @@ export async function deliverAgentCommandResult(
494648 return {
495649 deliveryPlan,
496650 deliveryChannel,
497- effectiveDeliveryPlan,
651+ effectiveDeliveryPlan : resolvedDeliveryPlan ,
498652 deliveryPlugin,
499653 isDeliveryChannelKnown,
500654 targetMode,
655+ defaultAccountId,
501656 resolvedAccountId,
502657 resolved,
503658 resolvedTarget : resolved . resolvedTarget ,
@@ -570,6 +725,7 @@ export async function deliverAgentCommandResult(
570725 const {
571726 deliveryChannel,
572727 isDeliveryChannelKnown,
728+ defaultAccountId,
573729 resolvedAccountId,
574730 resolvedTarget,
575731 deliveryTarget,
@@ -624,22 +780,72 @@ export async function deliverAgentCommandResult(
624780 accountId : resolvedAccountId ,
625781 applyChannelTransforms : deliver ,
626782 } ) ;
783+ const canonicalReplyPayloads = projectOutboundPayloadPlanForDelivery (
784+ createOutboundPayloadPlan ( normalizedReplyPayloads ) ,
785+ ) ;
786+ const shouldFilterDeliveredPayloads =
787+ deliver &&
788+ ! deliveryStatus &&
789+ Boolean ( deliveryTarget ) &&
790+ ! isInternalMessageChannel ( deliveryChannel ) ;
791+ const normalizeSentTexts = ( sentTexts : readonly string [ ] ) =>
792+ normalizeAgentCommandReplyPayloads ( {
793+ cfg,
794+ opts,
795+ outboundSession,
796+ payloads : sentTexts . map ( ( text ) => ( { text } ) ) ,
797+ result,
798+ deliveryChannel,
799+ accountId : resolvedAccountId ,
800+ applyChannelTransforms : deliver ,
801+ includeRunModelContext : false ,
802+ } ) . flatMap ( ( payload ) => ( payload . text ?. trim ( ) ? [ payload . text ] : [ ] ) ) ;
803+ const filterDeliveredPayloads = (
804+ replyPayloads : ReplyPayload [ ] ,
805+ normalizeMediaPaths ?: ( payload : ReplyPayload ) => Promise < ReplyPayload > ,
806+ ) => {
807+ if ( ! shouldFilterDeliveredPayloads || ! deliveryTarget ) {
808+ return Promise . resolve ( replyPayloads ) ;
809+ }
810+ return filterAlreadyDeliveredReplyPayloads ( {
811+ cfg,
812+ payloads : replyPayloads ,
813+ result,
814+ deliveryChannel,
815+ deliveryTarget,
816+ accountId : resolvedAccountId ,
817+ sourceAccountId : turnSourceAccountId ,
818+ defaultAccountId,
819+ // Command delivery projects payloads onto one batch route below, so
820+ // per-payload reply metadata does not change the destination here.
821+ threadId : resolvedThreadTarget ?? resolvedReplyToId ?? undefined ,
822+ normalizeMediaPaths,
823+ normalizeSentTexts,
824+ } ) ;
825+ } ;
826+ // Remove exact raw media matches before blocked-path normalization can turn
827+ // a successful message-tool send into a false media failure warning.
828+ const rawFilteredReplyPayloads = await filterDeliveredPayloads ( canonicalReplyPayloads ) ;
627829 // Auto-reply-style media-path normalization must also run for the CLI
628830 // `--deliver` path. Without it, relative reply media paths reach the
629831 // outbound loader unresolved and `assertLocalMediaAllowed` fails with
630832 // "Local media path is not under an allowed directory". Mirrors the
631833 // normalizer wiring in `src/auto-reply/reply/agent-runner.ts`.
632- const mediaNormalizedReplyPayloads =
834+ const mediaNormalization =
633835 deliver && ! deliveryStatus && ! isInternalMessageChannel ( deliveryChannel )
634836 ? await normalizeReplyMediaPathsForDelivery ( {
635837 cfg,
636- payloads : normalizedReplyPayloads ,
838+ payloads : rawFilteredReplyPayloads ,
637839 sessionKey : effectiveSessionKey ,
638840 outboundSession,
639841 deliveryChannel,
640842 accountId : resolvedAccountId ,
641843 } )
642- : normalizedReplyPayloads ;
844+ : { payloads : rawFilteredReplyPayloads } ;
845+ const mediaNormalizedReplyPayloads = await filterDeliveredPayloads (
846+ mediaNormalization . payloads ,
847+ mediaNormalization . normalizeMediaPaths ,
848+ ) ;
643849 params . assertDeliveryCurrent ?.( ) ;
644850 const outboundPayloadPlan = createOutboundPayloadPlan ( mediaNormalizedReplyPayloads ) ;
645851 const normalizedPayloads = projectOutboundPayloadPlanForJson ( outboundPayloadPlan ) ;
0 commit comments