UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines (7 loc) • 9.91 kB
import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{C as isOneShotRunSessionKey,N as parseAgentSessionKey,b as isCronRunSessionKey,w as isSubagentSessionKey}from"./session-key-BPgKfU2m.mjs";import{c as resolveSystemEventQueueKey,l as withSystemEventOwner}from"./system-event-ownership-CSF0k-1v.mjs";import{n as claimSessionEventOccurrenceInput,r as prepareSessionEventInput,t as enqueueSessionEventForHost}from"./session-event-handoff-DPJ2DWnj.mjs";import{d as withExecRequestOwners,l as readExecRequestOwners}from"./exec-request-context-BB4c5QQi.mjs";import{n as channelRouteDedupeKey}from"./channel-route-Buw3JZjL.mjs";import{d as enqueueSystemEventWithReceipt,i as consumeSelectedSystemEventEntries,t as SystemEventQueueFullError}from"./system-events-BXet8b2T.mjs";import{o as getGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{a as combineSessionEventTargetsForHost,i as captureSessionEventTargetForHost}from"./session-event-target-xxrhl4__.mjs";import{_ as renderExecExitLabel,p as hasExitWake,s as appendExecTimeoutRetryGuidance,v as renderExecOutputFile}from"./bash-tools.exec-output-Ci2XRgYO.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{S as recordNotifyOnExitRemoval,m as listRunningSessions,p as listFinishedSessions,x as processSessionInstanceId}from"./bash-process-registry-BL4zA8Yf.mjs";import{t as formatDurationCompact}from"./format-duration-CDAHVcL7.mjs";import{t as resolveEventSessionKeyForPolicy}from"./event-session-routing-BUjmzHiY.mjs"; //!src/auto-reply/reply/session-event-batch.ts const lanes=/* @__PURE__ */ new Map;const BATCH_SETTLE_MS=1e3;const BATCH_MAX_CHARS=8e3;function enqueueBatchedSessionEventForHost(e,t){const n=t.expectedTarget;if(!n||t.occurrences||isCronRunSessionKey(t.sessionKey))return enqueueSessionEventForHost(e,t);const r=JSON.stringify([t.agentId,t.sessionKey]);const i=lanes.get(r);if(!i){const n=enqueueSessionEventForHost(e,t);track(r,[],n);return n}t.assertCurrent?.();n.assertCurrent?.();const{agentId:a,sessionKey:o,operatorAuthority:s}=prepareSessionEventInput(e,t);const c={};const l=claimSessionEventOccurrenceInput({text:e,options:t,sessionKey:o,agentId:a,route:structuredClone(t.deliveryContext??n.deliveryContext),execRequestOwners:readExecRequestOwners(t),cancel:()=>c.member&&retire(r,c.member)});const u={...l,options:{...t,expectedTarget:n},queueKey:resolveSystemEventQueueKey(o,a),retired:false,settled:createDeferredCore(),accepted:createDeferredCore()};try{u.releaseAuthority=s?.retain?.()}catch(e){l.ownership.cancel();throw e}c.member=u;i.push(u);return{id:l.occurrenceId,cancel:()=>{const e=u.batch;if(!e)return!u.retired&&l.ownership.cancel();e.cancelled.add(u);return e.cancelled.size===e.size&&e.receipt.cancel()},settled:u.settled.promise,accepted:u.accepted.promise}}function retire(e,t){if(t.retired||t.batch)return;t.retired=true;const n=lanes.get(e)??[];if(n.includes(t))n.splice(n.indexOf(t),1);t.releaseAuthority?.();t.accepted.resolve({ok:false,error:`Session event was cancelled before acceptance`});t.settled.resolve({status:`cancelled`,executionStarted:false,delivered:false})}function track(e,t,n){lanes.set(e,t);const next=()=>{if(t.length===0){lanes.delete(e);return}setTimeout(()=>flush(e,t),BATCH_SETTLE_MS).unref?.()};n.settled.then(next,next)}function sameBatch(e,t){const n=new Set(readExecRequestOwners(e.options));const r=readExecRequestOwners(t.options)??[];return e.options.sourceRunId===t.options.sourceRunId&&n.size===new Set(r).size&&r.every(e=>n.has(e))&&channelRouteDedupeKey(e.options.deliveryContext)===channelRouteDedupeKey(t.options.deliveryContext)}function flush(e,t){const n=t[0];if(!n){lanes.delete(e);return}const r=[n];let i=n.options.expectedTarget;let a=n.occurrence.text.length;for(const e of t.slice(1)){a+=1+e.occurrence.text.length;if(a>BATCH_MAX_CHARS||!sameBatch(n,e))break;try{i=combineSessionEventTargetsForHost([...r,e].map(e=>e.options.expectedTarget))}catch{break}r.push(e)}t.splice(0,r.length);const o=r.map(e=>e.occurrence);for(const e of r)e.ownership.release();let s;try{s=enqueueSessionEventForHost(o.map(e=>e.text).join(` `),{...n.options,expectedTarget:i,occurrences:o})}catch(i){consumeSelectedSystemEventEntries(n.queueKey,o);for(const e of r){e.retired=true;e.releaseAuthority?.();e.accepted.resolve({ok:false,error:String(i)});e.settled.resolve({status:`failed`,executionStarted:false,delivered:false,error:String(i)})}flush(e,t);return}const c={receipt:s,size:r.length,cancelled:/* @__PURE__ */ new Set};for(const e of r){e.batch=c;e.releaseAuthority?.();e.accepted.resolve(s.accepted);e.settled.resolve(s.settled)}track(e,t,s)} //!src/agents/bash-tools.exec-notify.ts function enqueueExecExitNotification(e,t,n,r={}){return enqueueBatchedSessionEventForHost(e,{...r,agentId:t.agentId,sessionKey:t.sessionKey,source:`exec`,contextKey:r.contextKey??`exec:${n}`,sourceTurnId:`exec:${n}`,expectedTarget:t})}function prepareExecExitNotification(e,t,n){if(!e.notifyOnExit||!e.sessionKey)return;const r=t||isSubagentSessionKey(e.sessionKey);if(r&&!n)return;const i=t||isOneShotRunSessionKey(e.sessionKey);const a=i?e.sessionKey:resolveEventSessionKeyForPolicy(e.sessionKey,e.eventRouting??{});const o=e.agentId??parseAgentSessionKey(a)?.agentId;if(!o)return;return captureSessionEventTargetForHost(o,a,{operatorAuthority:getGatewayToolCallerIdentity()?.operatorAuthority,retainRequesterOwner:true}).then(t=>{if(i&&n)e.exitWakeAfterYield=true;e.notifySessionTarget=t},t=>{if(!r)e.notifyOnExit=false;logWarn(`exec: automatic completion has no destination (${formatErrorMessage(t)}); use process poll.`)})}const execYieldResumes=/* @__PURE__ */ new Map;const pendingExitWakes=/* @__PURE__ */ new Set;const execChatKey=e=>`${e.agentId}\0${e.sessionKey}`;const processChat=e=>e.sessionKey&&e.agentId?execChatKey({agentId:e.agentId,sessionKey:e.sessionKey}):void 0;function listChatRunningSessions(e){const t=execChatKey(e);return listRunningSessions().filter(e=>processChat(e)===t)}function listYieldAwaitableExecs(e){if(!e?.sessionKey)return[];return listChatRunningSessions(e).filter(e=>!e.cancellationRequested&&hasExitWake(e))}function hasExecYieldWake(e){if(listYieldAwaitableExecs(e).length>0)return true;for(const t of pendingExitWakes)if(t.agentId===e.agentId&&t.sessionKey===e.sessionKey)return true;const t=execChatKey(e);return listFinishedSessions().some(e=>e.finalizing&&e.resumesYieldedRun&&processChat(e)===t)}function awaitExecsForYield(e){for(const t of e){t.resumesYieldedRun=true;const e=processChat(t);if(e)execYieldResumes.get(e)?.awaited.add(t)}}function openExecYieldResume(e){const t=execChatKey(e);const n={awaited:/* @__PURE__ */ new Set,exits:[]};execYieldResumes.set(t,n);return{async next(e){for(;;){if(n.exits.length>0)return n.exits.splice(0).join(` `);if(n.awaited.size===0||e?.aborted)return;await new Promise(t=>{n.changed=t;e?.addEventListener(`abort`,()=>t(),{once:true})})}},[Symbol.dispose](){if(execYieldResumes.get(t)===n)execYieldResumes.delete(t)}}}async function maybeNotifyOnExit(e,t,n){const r=processChat(e);const i=r?execYieldResumes.get(r):void 0;if(!i?.awaited.has(e))return notifyOnExit(e,t,n);try{const n=prepareExecExitWake(e,t);if(n)i.exits.push(n)}finally{i.awaited.delete(e);i.changed?.()}}function prepareExecExitWake(e,t){if(e.exitNotified)return;if(!e.backgrounded||!e.notifyOnExit||e.requestCancelled||readExecRequestOwners(e)?.some(e=>e.signal.aborted)||e.terminalPollObserved||!e.sessionKey?.trim())return;e.exitNotified=true;if(e.exitReason===`manual-cancel`&&e.finalizationFailed!==true)return;const n=e.tail;const r=n.trim();if(t===`completed`&&e.exitCode===0&&!r&&e.notifyOnExitEmptySuccess!==true)return;const i=`Exec ${t} (${e.id.slice(0,8)}, ${renderExecExitLabel(e)}, ${formatDurationCompact((e.endedAt??Date.now())-e.startedAt)??`0s`})`;const a=e.outputFile;const o=!r?`${i} with no output.`:e.totalOutputChars<=n.length?`${i}:\n${r}`:a?`${i}, last ${n.length} of ${e.totalOutputChars} output chars:\n${r}\n${renderExecOutputFile(a)}`:`${i}, last ${n.length} of ${e.totalOutputChars} output chars (${e.totalOutputChars>e.aggregated.length?`process log keeps the last ${e.aggregated.length}; earlier output was discarded`:`process log has the rest`}):\n${r}`;return appendExecTimeoutRetryGuidance(o,e.exitReason)}async function notifyOnExit(e,t,n){const r=prepareExecExitWake(e,t);const i=e.sessionKey?.trim();if(!r||!i)return;const a=e.notifySessionTarget?.sessionKey??resolveEventSessionKeyForPolicy(i,e.eventRouting);const o=withExecRequestOwners({sessionKey:a,contextKey:`exec:${e.id}`,deliveryContext:e.notifyDeliveryContext},readExecRequestOwners(e));if(e.resumesYieldedRun||!n&&!isSubagentSessionKey(i)){const t=e.agentId??parseAgentSessionKey(a)?.agentId;if(!t||!e.notifySessionTarget){logWarn(`exec: completion ${e.id} has no admitted session destination; inspect its process result.`);return}try{const n=enqueueExecExitNotification(r,e.notifySessionTarget,processSessionInstanceId(e),{...o,sourceRunId:e.startedByRunId});recordNotifyOnExitRemoval(e,n.cancel);const i={agentId:t,sessionKey:a};pendingExitWakes.add(i);n.settled.then(e=>{pendingExitWakes.delete(i);if(e.status===`failed`)logWarn(`exec: completion delivery failed (${e.error}); inspect the process result.`)})}catch(e){logWarn(`exec: completion was not admitted (${formatErrorMessage(e)}); inspect the result with process log.`)}return}try{const t=enqueueSystemEventWithReceipt(r,e.agentId?withSystemEventOwner(o,e.agentId):o,{allowDuplicate:true});if(t)recordNotifyOnExitRemoval(e,t)}catch(t){if(!(t instanceof SystemEventQueueFullError))throw t;logWarn(`exec: completion ${e.id} was not queued (${t.message}); use process poll.`)}}export{maybeNotifyOnExit as a,listYieldAwaitableExecs as i,hasExecYieldWake as n,openExecYieldResume as o,listChatRunningSessions as r,prepareExecExitNotification as s,awaitExecsForYield as t};