UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines (4 loc) • 14.2 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{vs as validateChatAbortParams}from"./src-BDZMFmKa.mjs";import{yt as getSessionControllerSourceIdentity}from"./session-controller.state-BIDbpLPn.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{s as resolveStateContentionPresentation}from"./chat-display-projection.sanitize-DPZ4F1ws.mjs";import{E as captureRpcSourceScopeMatcher,T as captureGatewayScopeMatcher,v as holdSessionControllerSourceWithdrawal}from"./session-controller.lifecycle-M3NLAkoz.mjs";import{r as resolveRequestedSessionAgentId,s as tryResolveSessionCompatibilityOwnerAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{o as resolveSessionStoreKey}from"./session-store-key-DZXBwthg.mjs";import{a as getRpcSourceIdentity,g as isRpcSourceRegistered,h as isRpcSourceQueued,r as getRpcSourceForGateway,t as getReservedRpcSourceInput,v as listRpcSourceEntries}from"./session-controller.rpc-sources-IDCkO6sT.mjs";import"./session-controller.mailbox-9GxioY-x.mjs";import{i as captureSessionControllerStop,r as stopSession,t as cancelCapturedSessionControllerSource}from"./session-controller.stop-DE-wTVTx.mjs";import{n as captureExecRequestCancellation}from"./bash-process-control-ByEEGn0n.mjs";import{r as emitSessionsChanged}from"./session-change-event-M_-ScXDH.mjs";import{t as respondError}from"./response-BYbuAh7a.mjs";import{t as assertValidParams}from"./validation-CM41YclJ.mjs";import"./session-utils-Cd7daNqX.mjs";import{l as waitForChatAbortTerminalPersistence,s as waitForChatAbortAcknowledgment}from"./chat-abort-lifecycle-internal-zVsPSOIf.mjs";import{r as createChatAbortSignalReason}from"./chat-abort-DTWUmwzL.mjs";import{a as canRequesterAbortChatRun,d as resolveChatAbortSessionRestriction,f as resolveChatAbortTargetRejection,o as captureChatAbortAuthority,s as getChatRunAbortAuthority,t as abortChatRunsForSessionKeyWithPartials}from"./chat-abort-runtime-BiN_zmEs.mjs";import{a as persistAbortedPartials}from"./chat-transcript-persistence-Dkuuyx0-.mjs";import{a as prepareChatAbortSessionSnapshot,c as withAbortedPartialPersistenceWarning,i as deferAbortedPartialPersistence,n as abortedPartialPersistenceError,r as captureAbortedPartial}from"./chat-aborted-partial-DRzVH5wh.mjs";import{i as getWorkerInferenceSessionControl}from"./inference-control-internal-mrfHAhL2.mjs";import{n as createChatAbortOps,t as captureWorkerInferenceForSession}from"./chat-abort-ops-BUCPKCsd.mjs";import{n as descendantAbortError,t as abortControlledSubagents}from"./chat-abort-descendants-CfGWZ0QV.mjs";import{n as formatStopRequest}from"./control-plane-audit-Ds7o9s4B.mjs";import{n as stopExactClientRun,t as captureSourceAssertion}from"./chat-abort-exact-run-Dca68Kac.mjs";import{t as discardSessionPendingInput}from"./session-pending-input-withdrawal-CvsbPlDM.mjs"; //!src/gateway/server-methods/chat-abort-handler.ts async function handleChatAbortRequestWithLifecycle(e,t={}){const{params:n,respond:r,context:i,sessionMutationAuthorization:a}=e;const{requester:o,assertRequesterCurrent:s,narrow:c}=captureChatAbortAuthority(e);const assertCurrent=()=>{s();a?.assertCurrent();o.sessionAuthority?.assertCurrent();o.personalAuthority?.assertCurrent()};if(!assertValidParams(n,validateChatAbortParams,`chat.abort`,r))return;const{sessionKey:l,sessionId:u,runId:d,preserveSideRuns:f,discardPendingInput:p}=n;const m=normalizeOptionalString(n.agentId);const h=i.getRuntimeConfig();const g=parseAgentSessionKey(l);const _=tryResolveSessionCompatibilityOwnerAgentId(h,l);const v=!g?resolveRequestedSessionAgentId(h,l,m):void 0;if(v&&!v.ok){r(false,void 0,v.error);return}const y=g?m??normalizeAgentId(g.agentId):v?.agentId;if(!y){respondError(r,ErrorCodes.INVALID_REQUEST,l.trim().toLowerCase()===`global`?`agentId is required for global chat.abort when no compatibility owner exists`:`agentId is required for unscoped chat.abort when no compatibility owner exists`);return}if(m&&g&&normalizeAgentId(g.agentId)!==normalizeAgentId(m)){respondError(r,ErrorCodes.INVALID_REQUEST,`agentId "${m}" does not match session key "${l}"`);return}const b=resolveSessionStoreKey({cfg:h,sessionKey:l,storeAgentId:y});const x=resolveChatAbortSessionRestriction({requestedSessionId:u,runId:d,discardPendingInput:p,narrow:c,admittedTarget:a?.admittedTarget,sessionKey:b,agentId:normalizeAgentId(y)});if(!x.ok){respondError(r,ErrorCodes.INVALID_REQUEST,x.message);return}const{requiredSessionId:S}=x;const C=createChatAbortOps(i);const prepareAbortSession=(e=b,t=y)=>prepareChatAbortSessionSnapshot({excludeInternalEffects:true,cfg:h,key:e,agentId:t});const w=t.hookContext??{sessionKey:b,sessionId:S,commandSource:`gateway:chat.abort`,senderId:o.deviceId??o.connId};if(!d){const e=await abortChatRunsForSessionKeyWithPartials({context:i,ops:C,sessionKey:b,sessionKeyAliases:b===l?void 0:[l],agentId:y,sessionId:S,requiredSessionId:S,defaultAgentId:_,abortOrigin:`rpc`,stopReason:`rpc`,userInitiated:n.userInitiated,stopSource:`client-session`,hookContext:w,requester:o,assertCurrent,preserveSideRuns:f,cascadeDescendants:t.cascadeDescendants,announceRunStopped:true,yieldedRequesterRunId:t.yieldedRequesterRunId},prepareAbortSession);if(e.unauthorized){respondError(r,ErrorCodes.INVALID_REQUEST,`unauthorized`);return}if(e.descendants?.killed||e.descendants?.continuationRetired)t.onDescendantsCancelled?.(e.descendants);const a=e.error??descendantAbortError(e.descendants,`Session`);if(a){r(false,void 0,withAbortedPartialPersistenceWarning(a,e.warning));return}r(true,{ok:true,aborted:e.aborted,runIds:e.runIds,...e.warning?{warning:e.warning}:{}});return}const T=i.resolveGatewayContext;const ee=captureGatewayScopeMatcher(T);const E=listRpcSourceEntries().filter(([e,t])=>e===d&&ee(t.input));const D=getReservedRpcSourceInput(d,{resolveGatewayContext:T});if(!p&&D&&!D.target&&D.sourceAdapter?.preparation){const e=D.sourceAdapter;const t=e.preparation?.agentId;const i=S!==void 0?`runId does not match session incarnation`:t&&normalizeAgentId(t)!==normalizeAgentId(y)?`runId does not match agentId`:!canRequesterAbortChatRun({requester:e.requester},o,{requireOwnerMatch:true})?`unauthorized`:void 0;if(i){respondError(r,ErrorCodes.INVALID_REQUEST,i);return}const a=cancelCapturedSessionControllerSource(captureSessionControllerStop({inputs:[D]}),{assertCurrent,reason:createChatAbortSignalReason(`rpc`,n.userInitiated)});const s=a.failures[0];if(s)throw s.error;const c=a.abortedInputs.includes(D);r(true,{ok:true,aborted:c,runIds:c?[d]:[]});return}const O=captureExecRequestCancellation({runId:d,sessionKey:b,sessionId:S,agentId:y});const k=await prepareAbortSession();const A=k.ok?k.value.entry:void 0;if(u){if(!k.ok)throw k.error;if(A?.sessionId!==u){respondError(r,ErrorCodes.INVALID_REQUEST,`session incarnation changed`);return}}const j=new Set([...E.map(([,e])=>e.input),D].flatMap(e=>e?.target?[e.target.storeScope]:[]));const M=k.ok?k.value.storePath:j.size===1?j.values().next().value:void 0;const N=M?captureRpcSourceScopeMatcher({storePath:M,resolveGatewayContext:T}):()=>false;const stopWithoutCapturedRun=(e,t)=>stopSession({source:`client-run`,capture:captureSessionControllerStop({}),assertCurrent,reason:e,hookContext:w,afterParent:t}).completed;const authorizeRunTarget=e=>{const t=resolveChatAbortTargetRejection({target:e,requester:o,requestedSessionKey:l,canonicalSessionKey:b,requestedAgentId:normalizeAgentId(y),defaultAgentId:_,requiredSessionId:S,discardPendingInput:p,narrow:c});if(t)respondError(r,ErrorCodes.INVALID_REQUEST,t);return t===void 0};const P=E.flatMap(([,e])=>N(e)?[e]:[]);const F=P.length===1?P[0]:void 0;const I=!F&&D&&M&&D.target?.storeScope===M?D:void 0;const L=F?getRpcSourceIdentity(F):I?getSessionControllerSourceIdentity(I):void 0;const R=getWorkerInferenceSessionControl(i.workerEnvironmentService)?.resolveSessionTargetForRunId(d);if(R&&S!==void 0&&!authorizeRunTarget(R))return;const z=captureWorkerInferenceForSession({context:i,sessionId:L?.sessionId??R?.sessionId??A?.sessionId,runId:d});let B=false;if(p){if(F&&!authorizeRunTarget(getChatRunAbortAuthority(F)))return;if(!F||!isRpcSourceQueued(F)||F.input.phase===`injecting`||F.input.claim||F.input.retirementRequested){r(true,{ok:true,aborted:false,runIds:[]});return}const e=getRpcSourceIdentity(F);const t=F.input.target;const n={...e,agentId:e.agentId??y};const a=holdSessionControllerSourceWithdrawal(F.input);try{if(!k.ok)throw k.error;B=await discardSessionPendingInput({...n,storePath:k.value.storePath},d,()=>{assertCurrent();const n=getRpcSourceIdentity(F);if(!isRpcSourceRegistered(F)||!isRpcSourceQueued(F)||!t||F.input.target!==t||n.sessionKey!==e.sessionKey||n.sessionId!==e.sessionId||n.agentId!==e.agentId)throw new Error(`Run changed before input removal; refresh and retry.`)});if(B){F.adapter.abortStopReason=`rpc`;B=a.commit(`rpc`);if(B)emitSessionsChanged(i,{...n,reason:`agent.input.settled`},{accessChanged:false})}}finally{a()}r(true,{ok:true,aborted:B,runIds:B?[d]:[]});return}const V=/* @__PURE__ */ new Set;let H;const cancelWorker=()=>{if(!o.isAdmin||!z?.runIds.length)return;assertCurrent();const e=z.cancel({assertCurrent,onCancelled:e=>{V.add(e);t.onExactRunAborted?.(e)}});H=e;e.catch(()=>void 0)};const respondWithWorkerRuns=async(e,t,n=false)=>{await H;const i=/* @__PURE__ */ new Set([...e,...V]);if(!k.ok)throw k.error;r(true,{ok:true,aborted:i.size>0||n,runIds:[...i],...t?{warning:t}:{}})};if(!F){if(I&&L){if(!authorizeRunTarget({...L,requester:I.sourceAdapter?.requester}))return;const e=captureSourceAssertion(I,assertCurrent);const t=L.sessionKey===l||L.sessionKey===b?k:await prepareAbortSession(L.sessionKey,L.agentId??y);const i=t.ok?t.value.entry:void 0;let a=false;let o;await stopSession({source:`client-run`,capture:captureSessionControllerStop({inputs:[I]}),assertCurrent:e,reason:createChatAbortSignalReason(`rpc`,n.userInitiated),hookContext:{...w,sessionKey:L.sessionKey,sessionId:L.sessionId},afterParent:cancelWorker,onCancelled:e=>{if(e===I)a=true},stopChildren:async t=>{await t();o=await abortControlledSubagents({cfg:h,sessionKey:L.sessionKey,agentId:L.agentId,requesterTurnRunId:d,sessionId:L.sessionId,lifecycleRevision:i?.sessionId===L.sessionId?i.lifecycleRevision:void 0,assertCurrent:e});return{stopped:o?.killed??0,failed:o?.status===`error`?o.failed:0}}}).completed;const s=descendantAbortError(o,`Parent run`);if(s){r(false,void 0,s);return}await respondWithWorkerRuns(a?[d]:[]);return}if(O.owners.length>0){for(const e of O.owners){const{identity:t}=e;const n={...t,requester:{connectionId:t.ownerConnId,deviceId:t.ownerDeviceId}};if(!t.sessionKey||!t.sessionId||!canRequesterAbortChatRun(n,o,{requireOwnerMatch:true})){respondError(r,ErrorCodes.INVALID_REQUEST,`unauthorized`);return}if(!authorizeRunTarget(n))return}const e=await abortControlledSubagents({cfg:h,sessionKey:b,agentId:y,sessionId:A?.sessionId,requesterTurnRunId:d,lifecycleRevision:A?.lifecycleRevision,execCancellation:O,assertCurrent,beforeKill:async()=>{assertCurrent();if(getRpcSourceForGateway(d,T))throw new Error(`Run changed before cancellation; retry Stop.`);await stopWithoutCapturedRun(`rpc`,cancelWorker);return true}});const t=descendantAbortError(e,`Parent run`);if(t){r(false,void 0,t);return}await respondWithWorkerRuns([],void 0,e?.execAborted);return}if(!z?.runIds.length){if(!k.ok)throw k.error;await stopWithoutCapturedRun();r(true,{ok:true,aborted:false,runIds:[]});return}if(!o.isAdmin){respondError(r,ErrorCodes.INVALID_REQUEST,`unauthorized`);return}cancelWorker();await stopWithoutCapturedRun(`rpc`);await respondWithWorkerRuns([]);return}if(!authorizeRunTarget(getChatRunAbortAuthority(F)))return;const{sessionKey:U,sessionId:W,agentId:G}=getRpcSourceIdentity(F);assertCurrent();const K=captureSourceAssertion(F.input,assertCurrent);const q=U===l||U===b?k:await prepareAbortSession(U,G??y);let J;const{aborted:Y,descendants:te,failure:X}=await stopExactClientRun({ops:C,cfg:h,runId:d,active:F,userInitiated:n.userInitiated,lifecycleRevision:q.ok&&q.value.entry?.sessionId===W?q.value.entry.lifecycleRevision:void 0,assertCurrent:K,hookContext:w,afterParent:cancelWorker,stoppedSession:{agentId:G??y,sessionKey:U},onAborted:()=>t.onExactRunAborted?.(d),onAbortPrepared:()=>{const e=i.chatRunState.resolveBuffer(d,{final:true}).text;if(F.adapter.controlUiVisible===false||!e?.trim())return;J=captureAbortedPartial({runId:d,sessionKey:U,sessionId:W,agentId:G??y,text:e,abortOrigin:`rpc`,resolveTerminalProducer:F.adapter.resolveTerminalProducer,session:q});return deferAbortedPartialPersistence(J,i)}});const Z=descendantAbortError(te,`Parent run`);let Q;const $=X?[X.error]:[];if(Y)try{const e=J?persistAbortedPartials({context:i,snapshots:[J]}).then(e=>{Q=e;return e}):void 0;await waitForChatAbortAcknowledgment(Promise.all([e,waitForChatAbortTerminalPersistence(F)].map(e=>Promise.resolve(e).catch(e=>$.push(e)))))}catch(e){$.push(e)}if($.length){if(Z){r(false,void 0,withAbortedPartialPersistenceWarning({...Z,message:[Z.message,...$.map(formatErrorMessage)].join(` `)},Q));return}throw abortedPartialPersistenceError($.length===1?$[0]:new AggregateError($,`Chat cancellation and persistence failed`),Q)}if(!k.ok)throw abortedPartialPersistenceError(k.error,Q);if(Z){r(false,void 0,withAbortedPartialPersistenceWarning(Z,Q));return}try{await respondWithWorkerRuns(Y?[d]:[],Q)}catch(e){throw abortedPartialPersistenceError(e,Q)}}async function handleChatAbortRequest(e){if(validateChatAbortParams(e.params))e.context.logGateway.info(formatStopRequest(`chat.abort`,e.client,e.params));try{await handleChatAbortRequestWithLifecycle(e)}catch(t){const n=resolveStateContentionPresentation(t);if(!n)throw t;e.respond(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`The server is busy. Check this turn's status before trying Stop again. SQLite transaction admission remained busy. Stopping may already have taken effect.`,{details:{errorKind:n.errorKind}}))}}export{handleChatAbortRequestWithLifecycle as n,handleChatAbortRequest as t};