UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10 lines • 6.47 kB
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{d as redactToolPayloadText}from"./redact-BT59pdZ_.mjs";import{l as readExecRequestOwners}from"./exec-request-context-BB4c5QQi.mjs";import{m as joinExecFailureOutput}from"./bash-tools.exec-output-Ci2XRgYO.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{n as createSessionSlug}from"./session-slug-Bs6pqTOe.mjs";import{t as adoptReleasedProcess}from"./released-processes-1XlfHxCd.mjs";import{D as settleExecSessionFinalization,d as isProcessSessionIdTaken,m as listRunningSessions,n as addSession,o as createProcessSession,r as appendOutput,v as markExited}from"./bash-process-registry-BL4zA8Yf.mjs";import{n as recordAgentCleanupFailure}from"./run-cleanup-timeout-B__J_Jbc.mjs";import{randomBytes}from"node:crypto"; //!src/agents/bash-process-id.ts const bootId=randomBytes(6).toString(`hex`);function createProcessSessionId(){return`${createSessionSlug(e=>isProcessSessionIdTaken(`${e}:${bootId}`))}:${bootId}`}function missingProcessMessage(e){const t=/:([a-f0-9]{12})$/.exec(e)?.[1];if(t&&t!==bootId)return`Process ${e} was started before the Gateway restarted and is no longer tracked; rerun it if still needed. Check saved output and side effects before repeating work.`;return`Process ${e} is no longer tracked or is outside this session's scope. Handles are lost when the Gateway restarts; rerun it if still needed after checking saved output and side effects.`} //!src/agents/bash-process-adopted.ts const MAX_SERVICES_PER_SESSION=16;const MAX_SERVICES_PER_GATEWAY=64;const reservations=resolveGlobalSingleton(Symbol.for(`openclaw.execServiceReservations`),()=>/* @__PURE__ */ new Set);function serviceCapacityError(e){const t=listRunningSessions().filter(e=>!e.exited);const n=[...reservations];const r=t.filter(t=>t.scopeKey===e).length+n.filter(t=>t.scopeKey===e).length;const i=t.length+n.length;if(r<MAX_SERVICES_PER_SESSION&&i<MAX_SERVICES_PER_GATEWAY)return;return`This session runs ${r} of ${MAX_SERVICES_PER_SESSION} allowed services (Gateway: ${i} of ${MAX_SERVICES_PER_GATEWAY}). Use process list to see them and process kill <sessionId> to stop ones you no longer need.`}function reserveServiceSlot(e,t=true){if(!t)return;const n=serviceCapacityError(e);if(n)throw new Error(`Cannot start another background service. ${n}`);const r={scopeKey:e};reservations.add(r);return{[Symbol.dispose]:()=>{reservations.delete(r)}}}function formatProcess({pid:e,command:t}){return t?`pid ${e} (${t})`:`pid ${e}`}function adoptSurvivor(e,t){const n=createProcessSession({id:createProcessSessionId(),command:t.command??`pid ${t.pid}`,scopeKey:e.scopeKey,sessionKey:e.sessionKey,agentId:e.agentId,cleanupMs:e.cleanupMs,notifyOnExit:false,notifyOnExitEmptySuccess:false,exitNotified:false,startedAt:Date.now(),cwd:e.cwd,maxOutputChars:e.maxOutputChars,pendingMaxOutputChars:e.pendingMaxOutputChars,totalOutputChars:0,pendingStdoutChars:0,pendingStderrChars:0,pendingOutputDropped:false,exited:false,truncated:false,backgrounded:true,cursorKeyMode:`normal`,pid:t.pid,processActivity:{resultSettled:false,lastOutputAtMs:Date.now()}});const r=adoptReleasedProcess(e.scopeKey??``,t,()=>markExited(n,null,null,`completed`,n.cancellationRequested?`manual-cancel`:`exit`));if(!r)return;n.adopted={stop:async()=>{const e=await r.stop();n.cleanupUncertain=e.status===`uncertain`;if(e.status===`uncertain`){n.cleanupUncertain=true;appendOutput(n,`stderr`,`\nOpenClaw could not confirm that pid ${t.pid} stopped: ${e.reason}. It may still be running.\n`)}return e}};addSession(n);return n}function adoptExecSurvivors(e,t){return t.flatMap(t=>{const n=adoptSurvivor(e,t);return n?[`${formatProcess(t)} keeps running as background session ${n.id}: process list shows it and process kill ${n.id} stops it. Its later output to this command's stdout/stderr is discarded; redirect it to a file to keep it.`]:[]})} //!src/agents/bash-tools.exec-descendants.ts const UNCONFIRMED_DESCENDANT_CLEANUP_NOTE=`OpenClaw could not confirm that every process started by this command stopped; a detached process (such as a daemon or tmux server) may still be running. Use background: true for long-running services.`;function withNote(e,t,n,r){if(!e.backgrounded){n.push(r);return t}appendOutput(e,`stderr`,`\n${r}\n`);return{...t,aggregated:joinExecFailureOutput(t.aggregated,r)}}async function settleHostExecDescendants(e,t,n,r){if(!(t.releasesOnRootExit===true&&!e.requestCancelled&&(n.exitReason===`exit`||n.exitReason===`signal`)))t.cancel();let i=n;let a;try{a=await t.waitForExtinction?.()}catch(t){if(n.status!==`completed`||e.requestCancelled)throw t;e.cleanupUncertain=true;recordAgentCleanupFailure();logWarn(`exec: descendant cleanup after completion was not confirmed (${redactToolPayloadText(formatErrorMessage(t))}).`);i=withNote(e,n,r,UNCONFIRMED_DESCENDANT_CLEANUP_NOTE)}e.cleanupUncertain||=a?.status===`uncertain`;if(a?.status===`released`&&a.survivors.length>0){const t=adoptExecSurvivors(e,a.survivors);if(t.length>0)i=withNote(e,i,r,t.join(` `))}if(e.requestCancelled&&e.cleanupUncertain)throw new Error(`Command descendant cleanup could not be confirmed`);return i} //!src/agents/bash-tools.exec-settlement.ts async function settleExecProcessExit({session:e,outcome:t,onSettledBeforeNotify:n,notifyOnExit:r,failureOutcome:i}){let a=t;const{exitCode:o,exitSignal:s,status:c,exitReason:l,noOutputTimedOut:u}=a;const markProcessExited=()=>markExited(e,o,s,c,l,u);const d=e.outputFile;if(d){const t=e.backgrounded&&e.notifyOnExit?e.tail.length:e.output.length;if(!await d.close()||e.totalOutputChars<=t){e.outputFile=void 0;await d.remove()}}try{const t=!e.exited;const i=n?.(a);if(i instanceof Promise)await i;if(t){markProcessExited();await r(e,a.status)}}catch(t){e.finalizationFailed=true;a=i(t);const r=n?.(a);if(r instanceof Promise)await r}finally{try{await e.durable?.finalize()}catch{e.finalizationFailed=true}try{if(!e.exited)markProcessExited()}finally{delete e.sessionKey;delete e.eventRouting;delete e.notifyDeliveryContext;delete e.notifySessionTarget;delete e.notifyOnExit;delete e.notifyOnExitEmptySuccess;if(e.finalizationFailed||e.cleanupUncertain)for(const t of readExecRequestOwners(e)??[])t.cleanupUncertain=true;settleExecSessionFinalization(e)}}return a}export{missingProcessMessage as a,createProcessSessionId as i,settleHostExecDescendants as n,reserveServiceSlot as r,settleExecProcessExit as t};