UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 10.6 kB
import{l as normalizeOptionalString,u as normalizeOptionalStringifiedId}from"./string-coerce-CpTFcSwY.mjs";import{o as isFastTestRuntimeEnv}from"./env-fLMEolk5.mjs";import{d as sleepWithAbort}from"./src-De06gkOi.mjs";import{t as createLazyImportLoader}from"./lazy-promise-CismJCQR.mjs";import{g as toAgentStoreSessionKey}from"./session-key-BPgKfU2m.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import"./backoff-DRW5tqzp.mjs";import{t as retryAsync}from"./retry-DH5OEIsj.mjs";import{t as chatRef}from"./chat-ref-DFIHpEiJ.mjs";import{o as hasReplyPayloadContent}from"./payload-B5c5LLYp.mjs";import{o as copyReplyPayloadMetadata}from"./reply-payload-C7eQHHoS.mjs";import{t as createCronExecutionId}from"./run-id-CYBVQnKU.mjs";import{r as normalizeTargetForProvider}from"./target-normalization-BgbbEqEG.mjs";import{c as shouldAttemptTtsPayload}from"./tts-config-ByMAYymf.mjs";import{n as hasExplicitCronDeliveryTarget}from"./delivery-target-validation-C-8re9js.mjs";import{d as resolveDeliveryNotSentRetryability,l as isProvenDeliveryNotSentError}from"./delivery-recovery.shared-CMcli399.mjs";import{t as captureDeliveryQueueStateContext}from"./delivery-queue-state-context-hv3uu8YS.mjs";import{a as inspectDeliveryQueueReceipt}from"./delivery-queue-sqlite-BtAn8uTD.mjs";import{n as prepareTtsPreferences}from"./tts-preferences-CgPNb82p.mjs";import{s as hasScheduledNextRunAtMs}from"./jobs-scheduling-CgLyZKXg.mjs"; //!src/cron/isolated-agent/delivery-dispatch-policy.ts const DIRECT_CRON_DELIVERY_COMPLETION_RETENTION={idPrefix:`cron-direct-delivery:v1:`,maxAgeMs:864e5,maxEntries:2e3};function deliveredToPersistentExecution(e,t){const n=e.resolvedDelivery.ok?e.resolvedDelivery.sessionRoute?.sessionKey:void 0;const r=toAgentStoreSessionKey({agentId:e.agentId,requestKey:e.agentSessionKey,mainKey:e.cfgWithAgentDefaults.session?.mainKey});return t===`delivered`&&e.undeliveredRunStatus===`ok`&&e.job.sessionTarget.startsWith(`session:`)&&n===r?n:void 0}function resolveDirectCronDeliveryGeneration(e){return(e.job.sessionTarget===`isolated`||e.job.sessionTarget===`current`)&&e.sourceSessionKey&&e.sourceSessionGeneration&&!hasExplicitCronDeliveryTarget(e.deliveryPlan)?chatRef({agentId:e.agentId,storePath:resolveSessionStorePathCore(e.cfgWithAgentDefaults.session?.store,{agentId:e.agentId}),sessionKey:e.sourceSessionKey}):void 0}function normalizeDeliveryTarget(e,t){const n=t.trim();return normalizeTargetForProvider(e,n)??n}const PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS=[/unsupported channel/i,/unknown channel/i,/chat not found/i,/user not found/i,/bot.*not.*member/i,/bot was blocked by the user/i,/forbidden: bot was kicked/i,/recipient is not a valid/i,/outbound not configured for channel/i];const STALE_CRON_DELIVERY_MAX_START_DELAY_MS=108e5;const deliveryLoggerRuntimeLoader=createLazyImportLoader(()=>import(`./logger-Cv2qhOZd.mjs`));const ttsRuntimeLoader=createLazyImportLoader(()=>import(`./tts.runtime-BJIttbPS.mjs`));const deliverySubagentRegistryRuntimeLoader=createLazyImportLoader(()=>import(`./delivery-subagent-registry.runtime-LcoBc8Qr.mjs`));const subagentFollowupRuntimeLoader=createLazyImportLoader(()=>import(`./subagent-followup.runtime-B65pTaHy.mjs`));async function resolveDescendantSubagentFollowup(e){const t=await deliverySubagentRegistryRuntimeLoader.load();let n=await t.hasUnsettledCronDescendants(e.sessionKey);const r=!e.abortSignal?.aborted&&!n&&(e.spawnOnlyHandoff||!e.initialSynthesizedText.trim());const i=r||n?await subagentFollowupRuntimeLoader.load():void 0;if(e.spawnOnlyHandoff&&i){const n=await i.waitForDescendantSubagentResult({sessionKey:e.sessionKey,runStartedAt:e.runStartedAt,timeoutMs:e.timeoutMs,abortSignal:e.abortSignal});return{finalReply:n?.reply,finalDisposition:n?.disposition,hasUnsettledDescendants:await t.hasUnsettledCronDescendants(e.sessionKey)}}const a=r?await i?.readDescendantSubagentFallbackReply({sessionKey:e.sessionKey,runStartedAt:e.runStartedAt}):void 0;if(!e.deliveryBestEffort&&n){let r=await i?.waitForDescendantSubagentSummary({sessionKey:e.sessionKey,initialReply:e.initialSynthesizedText,timeoutMs:e.timeoutMs,observedActiveDescendants:n,abortSignal:e.abortSignal});n=await t.hasUnsettledCronDescendants(e.sessionKey);if(!e.abortSignal?.aborted&&!r&&!n)r=await i?.readDescendantSubagentFallbackReply({sessionKey:e.sessionKey,runStartedAt:e.runStartedAt});return{finalReply:r&&!n?r:void 0,hasUnsettledDescendants:n}}return{finalReply:a,hasUnsettledDescendants:n}}async function logCronDeliveryWarn(e){const{logWarn:t}=await deliveryLoggerRuntimeLoader.load();t(e)}function resolveStaleCronDeliveryError(e){const t=e.job.state?.nextRunAtMs;const n=hasScheduledNextRunAtMs(t)?t:e.runStartedAt;const r=e.runStartedAt-n;if(r>STALE_CRON_DELIVERY_MAX_START_DELAY_MS){const e=Date.now();return`skipping stale delivery scheduled at ${new Date(n).toISOString()}, started ${Math.round(r/6e4)}m late, current age ${Math.round((e-n)/6e4)}m`}}async function maybeApplyTtsToCronPayloads(e){const t=await prepareTtsPreferences();if(!await shouldAttemptTtsPayload({cfg:e.cfg,preparedTtsPreferences:t,ttsAuto:e.ttsAuto,agentId:e.agentId,channelId:e.delivery.channel,accountId:e.delivery.accountId}))return e.payloads;const{maybeApplyTtsToPayload:n}=await ttsRuntimeLoader.load();return await Promise.all(e.payloads.map(r=>n({payload:r,preparedTtsPreferences:t,cfg:e.cfg,channel:e.delivery.channel,kind:`final`,ttsAuto:e.ttsAuto,agentId:e.agentId,accountId:e.delivery.accountId})))}function buildDirectCronDeliveryIdempotencyKey(e){const t=createCronExecutionId(e.jobId,e.runStartedAt);const n=e.delivery.threadId==null||e.delivery.threadId===``?``:normalizeOptionalStringifiedId(e.delivery.threadId)??``;const r=e.delivery.accountId?.trim()??``;const i=normalizeDeliveryTarget(e.delivery.channel,e.delivery.to);const a=[e.delivery.channel,r,i,n].map(encodeURIComponent).join(`:`);return`${DIRECT_CRON_DELIVERY_COMPLETION_RETENTION.idPrefix}${t}:${a}`}async function isCompletedDirectCronDelivery(e,t){const n=captureDeliveryQueueStateContext();return(await inspectDeliveryQueueReceipt(t,e,false,n)).status===`completed`}async function waitForCompletedDirectCronDelivery(e){const t=captureDeliveryQueueStateContext();for(let n=0;n<120;n+=1){e.signal?.throwIfAborted();const{status:r,pendingEntry:i}=await inspectDeliveryQueueReceipt(e.queueName,e.id,true,t);e.signal?.throwIfAborted();if(r===`completed`)return true;if(!i||(i.recoveryState===`send_attempt_started`?typeof i.platformSendStartedAt!==`number`||i.platformSendStartedAt<=Date.now()-3e4:i.recoveryState!==`producer_claimed`||typeof i.availableAt!==`number`||i.availableAt<=Date.now()))return false;if(n<119)await sleepWithAbort(250,e.signal)}return false}function summarizeDirectCronDeliveryError(e){if(e instanceof Error)return e.message||`error`;if(typeof e===`string`)return e;try{return JSON.stringify(e)||String(e)}catch{return String(e)}}function isTransientDirectCronDeliveryError(e){const t=resolveDeliveryNotSentRetryability(e);if(t!==void 0)return t;const n=summarizeDirectCronDeliveryError(e);if(!n)return false;if(PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS.some(e=>e.test(n)))return false;return isProvenDeliveryNotSentError(e)}async function retryTransientDirectCronDelivery(e){const t=isFastTestRuntimeEnv()?[0,0,0]:[5e3,1e4,2e4];const assertActive=()=>{if(e.signal?.aborted)throw new Error(`cron delivery aborted`);if(e.deadlineAtMs!==void 0&&Date.now()>=e.deadlineAtMs){const e=/* @__PURE__ */ new Error(`cron delivery deadline exceeded`);e.name=`TimeoutError`;throw e}};assertActive();const runWithAbortCheck=async()=>{assertActive();return await e.run()};return await retryAsync(runWithAbortCheck,{attempts:t.length+1,minDelayMs:0,maxDelayMs:Math.max(...t),delayMs:({attempt:e})=>t[e-1]??0,shouldRetry:t=>e.signal?.aborted!==true&&(e.deadlineAtMs===void 0||Date.now()<e.deadlineAtMs)&&isTransientDirectCronDeliveryError(t)&&(e.shouldRetryError?.(t)??true),onRetry:async({attempt:t,maxAttempts:n,delayMs:r,err:i})=>{await logCronDeliveryWarn(`[cron:${e.jobId}] transient ${e.label??`direct announce`} delivery failure, retrying ${t+1}/${n} in ${Math.round(r/1e3)}s: ${summarizeDirectCronDeliveryError(i)}`);if(r===0)await sleepWithAbort(0,e.signal)},sleep:async t=>{const n=e.deadlineAtMs===void 0?t:Math.max(0,e.deadlineAtMs-Date.now());await sleepWithAbort(Math.min(t,n),e.signal);assertActive()}})} //!src/cron/isolated-agent/delivery-payload-normalization.ts function shouldAttachDirectCronFallbackText(e){return Boolean(e.channelData)&&!hasReplyPayloadContent(e,{trimText:true,hasChannelData:false})}function normalizeDirectCronDeliveryPayloads(e){const t=normalizeOptionalString(e.outputText)??normalizeOptionalString(e.summary)??normalizeOptionalString(e.synthesizedText);const n=e.deliveryPayloads.filter(e=>hasReplyPayloadContent(e,{trimText:true}));if(n.length===0&&t)n.push({text:t});const r=t?n.findLastIndex(e=>normalizeOptionalString(e.text)===t):-1;let i=r>=0?r:void 0;if(t&&i===void 0&&n.some(shouldAttachDirectCronFallbackText)){n.unshift({text:t});i=0}const a=n.map(e=>shouldAttachDirectCronFallbackText(e)&&t&&i!==void 0?copyReplyPayloadMetadata(e,Object.assign({},e,{fallbackText:{text:t,replacesPayloadIndex:i}})):e);const o=[];let s=false;for(const[t,n]of a.entries()){const r=e.channelTransform?e.channelTransform.apply(n):n;if(r===null)s=true;else o.push({payload:r,sourceIndex:t})}if(o.length===0)return{kind:`suppress`,reason:s?`channel_transform`:`empty`};const c=o.findIndex(({sourceIndex:e})=>e===i);return{kind:`deliver`,payload:o.map(({payload:e})=>{const t=e.fallbackText;if(!t||t.replacesPayloadIndex!==i)return e;return copyReplyPayloadMetadata(e,Object.assign({},e,{fallbackText:c<0?void 0:{...t,replacesPayloadIndex:c}}))})}}function appendCronRunInspectionLink(e,t,n){const r=e.findLastIndex(e=>e.text?.trim());if(!t||r<0)return e;const i=e[r];const a=n===`telegram`||n===`discord`?`[Inspect run](${t.replace(/[()]/g,e=>e===`(`?`%28`:`%29`)})`:`Inspect: ${t}`;const o=copyReplyPayloadMetadata(i,{...i,text:`${i.text}\n${a}`});return e.map((e,t)=>t===r?o:e)}export{deliveredToPersistentExecution as a,maybeApplyTtsToCronPayloads as c,resolveStaleCronDeliveryError as d,retryTransientDirectCronDelivery as f,buildDirectCronDeliveryIdempotencyKey as i,resolveDescendantSubagentFollowup as l,normalizeDirectCronDeliveryPayloads as n,isCompletedDirectCronDelivery as o,waitForCompletedDirectCronDelivery as p,DIRECT_CRON_DELIVERY_COMPLETION_RETENTION as r,logCronDeliveryWarn as s,appendCronRunInspectionLink as t,resolveDirectCronDeliveryGeneration as u};