@@ -10,9 +10,14 @@ import type { OpenClawConfig } from "../../config/types.openclaw.js";
1010import type { TtsAutoMode } from "../../config/types.tts.js" ;
1111import { isSuppressedControlReplyText } from "../../gateway/control-reply-text.js" ;
1212import { sleepWithAbort } from "../../infra/backoff.js" ;
13+ import {
14+ getDeliveryQueueEntryStatus ,
15+ loadDeliveryQueueEntry ,
16+ type DeliveryQueueCompletionRetention ,
17+ } from "../../infra/delivery-queue-sqlite.js" ;
1318import { isProvenDeliveryNotSentError } from "../../infra/delivery-recovery.shared.js" ;
1419import { isFastTestRuntimeEnv } from "../../infra/env.js" ;
15- import type { OutboundDeliveryResult } from "../../infra/outbound/deliver .js" ;
20+ import { OUTBOUND_DELIVERY_QUEUE_NAME } from "../../infra/outbound/delivery-queue-media-staging .js" ;
1621import { normalizeTargetForProvider } from "../../infra/outbound/target-normalization.js" ;
1722import { retryAsync } from "../../infra/retry.js" ;
1823import { stringifyRouteThreadId } from "../../plugin-sdk/channel-route.js" ;
@@ -26,6 +31,12 @@ import { cleanupCronRunSessionAfterRun } from "./session-cleanup.js";
2631
2732type SuccessfulDeliveryTarget = Extract < DeliveryTargetResolution , { ok : true } > ;
2833
34+ export const DIRECT_CRON_DELIVERY_COMPLETION_RETENTION = {
35+ idPrefix : "cron-direct-delivery:v1:" ,
36+ maxAgeMs : 24 * 60 * 60_000 ,
37+ maxEntries : 2_000 ,
38+ } as const satisfies DeliveryQueueCompletionRetention ;
39+
2940/** Deletes or retires ephemeral direct-delivery cron sessions for delete-after-run jobs. */
3041export async function cleanupDirectCronSession ( params : {
3142 job : CronJob ;
@@ -105,11 +116,6 @@ const PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS: readonly RegExp[] = [
105116
106117const STALE_CRON_DELIVERY_MAX_START_DELAY_MS = 3 * 60 * 60_000 ;
107118
108- type CompletedDirectCronDelivery = {
109- ts : number ;
110- results : OutboundDeliveryResult [ ] ;
111- } ;
112-
113119const deliveryLoggerRuntimeLoader = createLazyImportLoader (
114120 ( ) => import ( "./delivery-logger.runtime.js" ) ,
115121) ;
@@ -118,8 +124,6 @@ const deliverySubagentRegistryRuntimeLoader = createLazyImportLoader(
118124 ( ) => import ( "./delivery-subagent-registry.runtime.js" ) ,
119125) ;
120126
121- const COMPLETED_DIRECT_CRON_DELIVERIES = new Map < string , CompletedDirectCronDelivery > ( ) ;
122-
123127async function loadDeliveryLoggerRuntime ( ) : Promise < typeof import ( "./delivery-logger.runtime.js" ) > {
124128 return await deliveryLoggerRuntimeLoader . load ( ) ;
125129}
@@ -150,39 +154,6 @@ export function logCronDeliveryErrorDeferred(message: string): void {
150154 } ) ;
151155}
152156
153- function cloneDeliveryResults (
154- results : readonly OutboundDeliveryResult [ ] ,
155- ) : OutboundDeliveryResult [ ] {
156- return results . map ( ( result ) => ( {
157- ...result ,
158- ...( result . meta ? { meta : { ...result . meta } } : { } ) ,
159- } ) ) ;
160- }
161-
162- function pruneCompletedDirectCronDeliveries ( now : number ) {
163- const ttlMs = isFastTestRuntimeEnv ( ) ? 60_000 : 24 * 60 * 60 * 1000 ;
164- for ( const [ key , entry ] of COMPLETED_DIRECT_CRON_DELIVERIES ) {
165- if ( now - entry . ts >= ttlMs ) {
166- COMPLETED_DIRECT_CRON_DELIVERIES . delete ( key ) ;
167- }
168- }
169- const maxEntries = 2000 ;
170- if ( COMPLETED_DIRECT_CRON_DELIVERIES . size <= maxEntries ) {
171- return ;
172- }
173- const entries = [ ...COMPLETED_DIRECT_CRON_DELIVERIES . entries ( ) ] . toSorted (
174- ( a , b ) => a [ 1 ] . ts - b [ 1 ] . ts ,
175- ) ;
176- const toDelete = COMPLETED_DIRECT_CRON_DELIVERIES . size - maxEntries ;
177- for ( let i = 0 ; i < toDelete ; i += 1 ) {
178- const oldest = entries [ i ] ;
179- if ( ! oldest ) {
180- break ;
181- }
182- COMPLETED_DIRECT_CRON_DELIVERIES . delete ( oldest [ 0 ] ) ;
183- }
184- }
185-
186157export function resolveCronDeliveryScheduledAtMs ( params : {
187158 job : CronJob ;
188159 runStartedAt : number ;
@@ -202,32 +173,6 @@ export function isStaleCronDelivery(params: { job: CronJob; runStartedAt: number
202173 return resolveCronDeliveryStartDelayMs ( params ) > STALE_CRON_DELIVERY_MAX_START_DELAY_MS ;
203174}
204175
205- export function rememberCompletedDirectCronDelivery (
206- idempotencyKey : string ,
207- results : readonly OutboundDeliveryResult [ ] ,
208- ) {
209- // Cache completed sends by idempotency key so retry paths can report the
210- // original delivery result instead of double-announcing a cron run.
211- const now = Date . now ( ) ;
212- COMPLETED_DIRECT_CRON_DELIVERIES . set ( idempotencyKey , {
213- ts : now ,
214- results : cloneDeliveryResults ( results ) ,
215- } ) ;
216- pruneCompletedDirectCronDeliveries ( now ) ;
217- }
218-
219- export function getCompletedDirectCronDelivery (
220- idempotencyKey : string ,
221- ) : OutboundDeliveryResult [ ] | undefined {
222- const now = Date . now ( ) ;
223- pruneCompletedDirectCronDeliveries ( now ) ;
224- const cached = COMPLETED_DIRECT_CRON_DELIVERIES . get ( idempotencyKey ) ;
225- if ( ! cached ) {
226- return undefined ;
227- }
228- return cloneDeliveryResults ( cached . results ) ;
229- }
230-
231176export async function maybeApplyTtsToCronPayloads ( params : {
232177 cfg : OpenClawConfig ;
233178 payloads : ReplyPayload [ ] ;
@@ -276,25 +221,52 @@ export function buildDirectCronDeliveryIdempotencyKey(params: {
276221 : ( stringifyRouteThreadId ( params . delivery . threadId ) ?? "" ) ;
277222 const accountId = params . delivery . accountId ?. trim ( ) ?? "" ;
278223 const normalizedTo = normalizeDeliveryTarget ( params . delivery . channel , params . delivery . to ) ;
279- return `cron-direct-delivery:v1: ${ executionId } : ${ params . delivery . channel } : ${ accountId } : ${ normalizedTo } : ${ threadId } ` ;
280- }
281-
282- /** Clears the direct-delivery idempotency cache for deterministic tests. */
283- function resetCompletedDirectCronDeliveriesForTests ( ) {
284- COMPLETED_DIRECT_CRON_DELIVERIES . clear ( ) ;
224+ // Escape route fields independently so colon-bearing identities cannot
225+ // collide while ordinary shipped channel and target keys stay unchanged.
226+ const routeIdentity = [ params . delivery . channel , accountId , normalizedTo , threadId ]
227+ . map ( encodeURIComponent )
228+ . join ( ":" ) ;
229+ return ` ${ DIRECT_CRON_DELIVERY_COMPLETION_RETENTION . idPrefix } ${ executionId } : ${ routeIdentity } ` ;
285230}
286231
287- /** Returns the direct- delivery idempotency cache size for tests . */
288- function getCompletedDirectCronDeliveriesCountForTests ( ) : number {
289- return COMPLETED_DIRECT_CRON_DELIVERIES . size ;
232+ /** Receipts own recipient delivery; projections never stand in for custody . */
233+ export function isCompletedDirectCronDelivery ( id : string ) : boolean {
234+ return getDeliveryQueueEntryStatus ( OUTBOUND_DELIVERY_QUEUE_NAME , id ) === "completed" ;
290235}
291236
292- if ( process . env . VITEST || process . env . NODE_ENV === "test" ) {
293- ( globalThis as Record < PropertyKey , unknown > ) [ Symbol . for ( "openclaw.cronDeliveryDispatchTestApi" ) ] =
294- {
295- resetCompletedDirectCronDeliveriesForTests,
296- getCompletedDirectCronDeliveriesCountForTests,
297- } ;
237+ /** Wait only for an active recipient owner, never for crashed ambiguous sends. */
238+ export async function waitForCompletedDirectCronDelivery ( params : {
239+ id : string ;
240+ signal ?: AbortSignal ;
241+ } ) : Promise < boolean > {
242+ // SQLite producer leases fence cross-process sends for at most 30 seconds.
243+ for ( let attempt = 0 ; attempt < 120 ; attempt += 1 ) {
244+ const status = getDeliveryQueueEntryStatus ( OUTBOUND_DELIVERY_QUEUE_NAME , params . id ) ;
245+ if ( status === "completed" ) {
246+ return true ;
247+ }
248+ const owner =
249+ status === "pending" ? loadDeliveryQueueEntry ( OUTBOUND_DELIVERY_QUEUE_NAME , params . id ) : null ;
250+ if ( ! owner && status === "pending" ) {
251+ // Completion can replace a pending row between the two indexed reads.
252+ return isCompletedDirectCronDelivery ( params . id ) ;
253+ }
254+ if (
255+ ! owner ||
256+ ( owner . recoveryState === "send_attempt_started"
257+ ? typeof owner . platformSendStartedAt !== "number" ||
258+ owner . platformSendStartedAt <= Date . now ( ) - 30_000
259+ : owner . recoveryState !== "producer_claimed" ||
260+ typeof owner . availableAt !== "number" ||
261+ owner . availableAt <= Date . now ( ) )
262+ ) {
263+ return false ;
264+ }
265+ if ( attempt < 119 ) {
266+ await sleepWithAbort ( 250 , params . signal ) ;
267+ }
268+ }
269+ return false ;
298270}
299271
300272function summarizeDirectCronDeliveryError ( error : unknown ) : string {
0 commit comments