UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 14.5 kB
import{T as parseStrictInteger}from"./number-coercion-B3CfI447.mjs";import{n as sliceUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import"./utils-Dlk0IYAa.mjs";import{n as notifyListeners}from"./listeners-awzYn4LE.mjs";import{r as parseEnvValue}from"./shared-D0HXA3v0.mjs";import{n as encodeOwnedBuffer}from"./owned-buffer-DQuyHNHR.mjs";import{randomUUID}from"node:crypto"; //!src/agents/bash-tools.shared.ts const CHUNK_LIMIT=8192;function buildSandboxEnv(e){return Object.assign({PATH:e.defaultPath,HOME:e.containerWorkdir},e.sandboxEnv,e.paramsEnv)}function coerceEnv(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(e))if(typeof r===`string`)t[n]=r;return t}function clampWithDefault(e,t,n,r){if(e===void 0||Number.isNaN(e))return t;return Math.min(Math.max(e,n),r)}function readEnvInt(e,t){const n=process.env[e]||(t?process.env[t]:void 0);return parseStrictInteger(n)}function chunkString(e){const t=[];let n=0;while(n<e.length){const r=sliceUtf16Safe(e,n,n+CHUNK_LIMIT);t.push(r);n+=r.length}return t}function truncateMiddle(e,t){if(e.length<=t)return e;const n=Math.floor((t-3)/2);return`${sliceUtf16Safe(e,0,n)}...${sliceUtf16Safe(e,-n)}`}function sliceLogLines(e,t,n){if(!e)return{slice:``,totalLines:0,totalChars:0};const r=e.replace(/\r\n/g,` `).split(` `);if(r.length>0&&r[r.length-1]===``)r.pop();const i=r.length;const a=e.length;let o=typeof t===`number`&&Number.isFinite(t)?Math.max(0,Math.floor(t)):0;if(n!==void 0&&t===void 0)o=Math.max(i-Math.max(0,Math.floor(n)),0);const s=typeof n===`number`&&Number.isFinite(n)?o+Math.max(0,Math.floor(n)):void 0;return{slice:r.slice(o,s).join(` `),totalLines:i,totalChars:a}}function deriveSessionName(e){const t=tokenizeCommand(e);const n=t[0];if(!n)return;let r=t.slice(1).find(e=>!e.startsWith(`-`));if(!r)r=t[1];if(!r)return n;const i=truncateMiddle(parseEnvValue(r),48);return`${parseEnvValue(n)} ${i}`}function tokenizeCommand(e){return(e.match(/(?:[^\s"']+|"(?:\\.|[^"\\])*"|'[^']*')+/g)??[]).map(e=>parseEnvValue(e)).filter(Boolean)} //!src/agents/bash-process-registry.ts const DEFAULT_JOB_TTL_MS=18e5;const MIN_JOB_TTL_MS=6e4;const MAX_JOB_TTL_MS=108e5;const DEFAULT_PENDING_OUTPUT_CHARS=3e4;const MAX_FINISHED_SESSION_COUNT=50;const MAX_FINISHED_SESSION_OUTPUT_CHARS=2e6;const EMPTY_OUTPUT={order:0,text:Buffer.alloc(0)};function clampTtl(e){return clampWithDefault(e,DEFAULT_JOB_TTL_MS,MIN_JOB_TTL_MS,MAX_JOB_TTL_MS)}const defaultJobTtlMs=clampTtl(readEnvInt(`OPENCLAW_BASH_JOB_TTL_MS`,`PI_BASH_JOB_TTL_MS`));function resolveProcessCleanupMs(e){return e===void 0?defaultJobTtlMs:clampTtl(e)}var ProcessOutput=class{constructor(){this.chunks=[];this.head=0;this.offset=0;this.length=0}append(e,t,n){if(n>t){this.chunks=[];this.head=0;this.offset=0;this.length=0}if(e.text.length===0)return;this.chunks.push(e);this.length+=e.text.length/2;let r=Math.max(0,this.length-t);while(r>0){const e=this.chunks[this.head].text;const t=Math.min(r,e.length/2-this.offset);const n=e.readUInt16LE((this.offset+t-1)*2);this.offset+=t;this.length-=t;r-=t;if(this.offset*2===e.length){this.chunks[this.head++]=EMPTY_OUTPUT;this.offset=0}if(r===0&&this.length>0&&n>=55296&&n<=56319){const e=this.chunks[this.head].text.readUInt16LE(this.offset*2);if(e>=56320&&e<=57343)r=1}}if(this.head>0&&this.head*2>=this.chunks.length){this.chunks=this.chunks.slice(this.head);this.head=0}}text(e=this.length){if(this.finished!==void 0)return tail(this.finished,e);let t=Math.min(e+1,this.length);const n=[];for(let e=this.chunks.length-1;e>=this.head&&t>0;e--){const r=this.chunks[e].text;const i=Math.max(e===this.head?this.offset*2:0,r.length-t*2);n.push(r.subarray(i));t-=(r.length-i)/2}const r=Buffer.concat(n.toReversed()).toString(`utf16le`);return sliceUtf16Safe(r,Math.max(0,r.length-e))}freeze(){this.finished=this.text();this.chunks=[];this.head=0;this.offset=0}entries(){const e=this.chunks.slice(this.head);const t=e[0];if(t&&this.offset>0)e[0]={...t,text:t.text.subarray(this.offset*2)};return e}};function createProcessSession(e){const t=new ProcessOutput;return{...e,output:t,pendingOutput:{stdout:new ProcessOutput,stderr:new ProcessOutput},get aggregated(){return t.text()},get tail(){return t.text(2e3)}}}const pollWaiters=/* @__PURE__ */ new WeakMap;const runningSessions=/* @__PURE__ */ new Map;const finishedSessions=/* @__PURE__ */ new Map;let processSessionStartOrders=/* @__PURE__ */ new WeakMap;let nextProcessSessionStartOrder=0;const processInstanceIds=/* @__PURE__ */ new WeakMap;const activeExecSessions=/* @__PURE__ */ new Map;let finishedSessionOutputChars=0;let sweeper=null;let sweeperDueAt=0;let observeDurableProcesses;function setDurableProcessObserver(e){observeDurableProcesses=e;scheduleSweeper()}let exitWakeRecorder;function setExitWakeRecorder(e){exitWakeRecorder=e}const changeListeners=/* @__PURE__ */ new Set;const pendingChanges=/* @__PURE__ */ new Map;let changeTimer;function onBackgroundProcessesChanged(e){changeListeners.add(e);return()=>{changeListeners.delete(e);if(changeListeners.size===0){clearTimeout(changeTimer);changeTimer=void 0;pendingChanges.clear()}}}function queueProcessChange(e){const t=e.scopeKey??e.sessionKey;if(!t||changeListeners.size===0)return;const n=pendingChanges.get(t);if(n)n.add(e.agentId);else pendingChanges.set(t,/* @__PURE__ */ new Set([e.agentId]));changeTimer??=runInDetachedAsyncContext(()=>setTimeout(()=>{changeTimer=void 0;const e=[...pendingChanges];pendingChanges.clear();for(const[t,n]of e)for(const e of n)notifyListeners(changeListeners,{sessionKey:t,agentId:e})},5e3).unref())}function isProcessSessionIdTaken(e){return runningSessions.has(e)||finishedSessions.has(e)||activeExecSessions.has(e)}function addSession(e){processSessionStartOrders.set(e,nextProcessSessionStartOrder++);processInstanceIds.set(e,randomUUID());runningSessions.set(e.id,e);activeExecSessions.set(e.id,{session:e,promoted:e.backgrounded});if(e.backgrounded)queueProcessChange(e);if(e.durable)scheduleSweeper()}function compareProcessSessionStartOrder(e,t){return t.startedAt-e.startedAt||processSessionStartOrders.get(t)-processSessionStartOrders.get(e)}function processSessionInstanceId(e){const t=processInstanceIds.get(e);if(!t)throw new Error(`Process is not registered`);return t}function getSession(e){return runningSessions.get(e)}function getFinishedSession(e){return finishedSessions.get(e)}function deleteFinishedSession(e){const t=finishedSessions.get(e);if(!t)return false;finishedSessions.delete(e);finishedSessionOutputChars-=t.output.length;t.durable?.remove();queueProcessChange(t);return true}function deleteSession(e){const t=runningSessions.get(e);runningSessions.delete(e);if(t&&(t.backgrounded||activeExecSessions.get(e)?.promoted))queueProcessChange(t);deleteFinishedSession(e);scheduleSweeper()}function clearFinishedSessionsForScopes(e){const t=/* @__PURE__ */ new Set;for(const n of e){const e=n.trim();if(e)t.add(e)}if(t.size===0)return;for(const[e,n]of finishedSessions)if(n.scopeKey&&t.has(n.scopeKey))deleteFinishedSession(e);scheduleSweeper()}function appendOutput(e,t,n){if(!n||typeof e.pendingOutput===`string`)return;const r=t===`stdout`?e.pendingStdoutChars:e.pendingStderrChars;const i=Math.min(e.pendingMaxOutputChars??DEFAULT_PENDING_OUTPUT_CHARS,e.maxOutputChars);const a={order:e.totalOutputChars,text:encodeOwnedBuffer(sliceUtf16Safe(n,Math.max(0,n.length-e.maxOutputChars)),`utf16le`)};const o=e.pendingOutput[t];o.append(a,i,n.length);const s=o.length;if(s<r+n.length){e.truncated=true;e.pendingOutputDropped=true}if(t===`stdout`)e.pendingStdoutChars=s;else e.pendingStderrChars=s;e.totalOutputChars+=n.length;e.outputFile?.write(n);const c=e.output.length;e.output.append(a,e.maxOutputChars,n.length);e.truncated||=e.output.length<c+n.length;wakeSessionPolls(e);if(e.backgrounded)queueProcessChange(e)}function drainSession(e){const t=e.pendingOutput;const n=typeof t===`string`?t:Buffer.concat([...t.stdout.entries(),...t.stderr.entries()].toSorted((e,t)=>e.order-t.order).map(e=>e.text)).toString(`utf16le`);const r=e.pendingOutputDropped;e.pendingOutput=typeof t===`string`?``:{stdout:new ProcessOutput,stderr:new ProcessOutput};e.pendingStdoutChars=0;e.pendingStderrChars=0;e.pendingOutputDropped=false;return{output:n,outputDropped:r}}function prepareSessionPoll(e,t){if(!t)return{...drainSession(e),acknowledge(){}};let n=e.pendingPollDelivery;if(n){if(n.scope===t)return{output:``,outputDropped:false,acknowledge(){}};n.scope=t}else{const r=drainSession(e);if(r.output.length===0&&!r.outputDropped)return{...r,acknowledge(){}};n={...r,scope:t};e.pendingPollDelivery=n}return{output:n.output,outputDropped:n.outputDropped,acknowledge(){if(e.pendingPollDelivery===n)e.pendingPollDelivery=void 0}}}function wakeSessionPolls(e){const t=pollWaiters.get(e);if(t)for(const e of t)e()}function waitForSessionPoll(e,t,n){if(e.exited||e.pendingPollDelivery||e.pendingStdoutChars+e.pendingStderrChars>0||e.pendingOutputDropped||n?.aborted)return Promise.resolve();return new Promise(r=>{const i=pollWaiters.get(e)??/* @__PURE__ */ new Set;const wake=()=>{clearTimeout(a);n?.removeEventListener(`abort`,wake);i.delete(wake);if(i.size===0)pollWaiters.delete(e);r()};const a=setTimeout(wake,t);i.add(wake);pollWaiters.set(e,i);n?.addEventListener(`abort`,wake,{once:true})})}function markExited(e,t,n,r,i,a){e.terminalStatus=r;e.exited=true;delete e.processActivity;e.exitCode=t;e.exitSignal=n;e.exitReason=i;e.noOutputTimedOut=a;const o=drainSession(e);e.pendingOutput=o.output;e.pendingOutputDropped=o.outputDropped;e.output.freeze();moveToFinished(e);wakeSessionPolls(e);if(e.backgrounded){queueProcessChange(e);exitWakeRecorder?.exited(e)}if(!e.finalizing)settleExecSessionFinalization(e)}function settleExecSessionFinalization(e){e.finalizing=false;const t=activeExecSessions.get(e.id);if(t?.session===e){activeExecSessions.delete(e.id);t.settled?.resolve()}}function markCancellationRequested(e){if(e.cancellationRequested)return;e.cancellationRequested=true;if(e.backgrounded)queueProcessChange(e)}function markBackgrounded(e){if(!e.backgrounded){queueProcessChange(e);exitWakeRecorder?.backgrounded(e)}e.backgrounded=true;const t=activeExecSessions.get(e.id);if(t?.session===e)t.promoted=true}function recordNotifyOnExitRemoval(e,t){if(e.terminalPollObserved||e.requestCancelled){t();return}e.notifyOnExitRemoval=t}function acknowledgeNotifyOnExit(e){e.terminalPollObserved=true;removeNotifyOnExit(e)}function removeNotifyOnExit(e){const t=e.notifyOnExitRemoval;if(!t)return;t();e.notifyOnExitRemoval=void 0}function getActiveBackgroundExecSessionCount(){let e=0;for(const{promoted:t,session:n}of activeExecSessions.values())if(t&&!n.durable)e+=1;return e}const releasedSessions=/* @__PURE__ */ new WeakSet;function markExecSessionReleased(e){releasedSessions.add(e)}async function waitForExecScope(e){while(true){const t=Array.from(activeExecSessions.values()).filter(({session:t})=>t.scopeKey===e&&!t.adopted&&!releasedSessions.has(t)).map(e=>(e.settled??=createDeferredCore()).promise);if(t.length===0)return;await Promise.all(t)}}function listExecSessionsForCancellation(){return[...new Set([...activeExecSessions.values()].map(({session:e})=>e).concat([...finishedSessions.values()]))]}async function waitForExecSession(e){const t=activeExecSessions.get(e.id);if(t?.session===e)await(t.settled??=createDeferredCore()).promise}function moveToFinished(e){runningSessions.delete(e.id);const t=e.stdin;if(t){if(typeof t.destroy===`function`)t.destroy();else t.end();delete e.stdin}if(!e.backgrounded)return;deleteFinishedSession(e.id);const n=e.endedAt??Date.now();finishedSessions.set(e.id,Object.assign(e,{endedAt:n,expiresAt:n+e.cleanupMs}));finishedSessionOutputChars+=e.output.length;while(finishedSessions.size>MAX_FINISHED_SESSION_COUNT||finishedSessions.size>1&&finishedSessionOutputChars>MAX_FINISHED_SESSION_OUTPUT_CHARS){const e=finishedSessions.keys().next().value;if(e===void 0)break;deleteFinishedSession(e)}scheduleSweeper()}function tail(e,t=2e3){if(e.length<=t)return e;return Buffer.from(sliceUtf16Safe(e,e.length-t),`utf16le`).toString(`utf16le`)}function listRunningSessions(){return Array.from(runningSessions.values()).filter(e=>e.backgrounded)}function listFinishedSessions(){return Array.from(finishedSessions.values())}function resetProcessRegistryForTests(){clearTimeout(changeTimer);changeTimer=void 0;pendingChanges.clear();runningSessions.clear();finishedSessions.clear();processSessionStartOrders=/* @__PURE__ */ new WeakMap;nextProcessSessionStartOrder=0;finishedSessionOutputChars=0;for(const e of activeExecSessions.values())e.settled?.resolve();activeExecSessions.clear();observeDurableProcesses=void 0;stopSweeper()}if(process.env.VITEST||false)globalThis[Symbol.for(`openclaw.bashProcessRegistryTestApi`)]={resetProcessRegistryForTests};function scheduleSweeper(){const e=Date.now();let t=Number.POSITIVE_INFINITY;for(const[n,r]of finishedSessions)if(r.expiresAt<=e)deleteFinishedSession(n);else t=Math.min(t,r.expiresAt);if(observeDurableProcesses&&[...activeExecSessions.values()].some(({session:e})=>e.durable))t=Math.min(t,e+5e3);if(!Number.isFinite(t)){stopSweeper();return}if(sweeper&&sweeperDueAt<=t)return;stopSweeper();sweeperDueAt=t;sweeper=runInDetachedAsyncContext(()=>setTimeout(()=>{sweeper=null;const e=observeDurableProcesses?.();if(e)e.then(scheduleSweeper,scheduleSweeper);else scheduleSweeper()},t-e));sweeper.unref()}function stopSweeper(){if(!sweeper)return;clearTimeout(sweeper);sweeper=null}export{waitForExecSession as A,removeNotifyOnExit as C,settleExecSessionFinalization as D,setExitWakeRecorder as E,coerceEnv as F,deriveSessionName as I,readEnvInt as L,buildSandboxEnv as M,chunkString as N,tail as O,clampWithDefault as P,sliceLogLines as R,recordNotifyOnExitRemoval as S,setDurableProcessObserver as T,markExecSessionReleased as _,compareProcessSessionStartOrder as a,prepareSessionPoll as b,getActiveBackgroundExecSessionCount as c,isProcessSessionIdTaken as d,listExecSessionsForCancellation as f,markCancellationRequested as g,markBackgrounded as h,clearFinishedSessionsForScopes as i,waitForSessionPoll as j,waitForExecScope as k,getFinishedSession as l,listRunningSessions as m,addSession as n,createProcessSession as o,listFinishedSessions as p,appendOutput as r,deleteSession as s,acknowledgeNotifyOnExit as t,getSession as u,markExited as v,resolveProcessCleanupMs as w,processSessionInstanceId as x,onBackgroundProcessesChanged as y,truncateMiddle as z};