UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

520 lines (519 loc) • 17.9 kB
import { T as parseStrictInteger } from "./number-coercion-D6u-4YD8.mjs"; import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs"; import { n as sliceUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { n as notifyListeners } from "./listeners-Cb2-CnP8.mjs"; import { r as parseEnvValue } from "./shared-DyBTHA2R.mjs"; import { n as encodeOwnedBuffer } from "./owned-buffer-C1_N0F1K.mjs"; import { randomUUID } from "node:crypto"; //#region 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); } /** Coerces process/env-like records to string-only environment variables. */ 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; } /** * Clamp a number within min/max bounds, using defaultValue if undefined or NaN. */ function clampWithDefault(e, t, n, r) { if (e === void 0 || Number.isNaN(e)) return t; return Math.min(Math.max(e, n), r); } /** Reads a strict integer from the preferred env var or one legacy alias. */ function readEnvInt(e, t) { const n = process.env[e] || (t ? process.env[t] : void 0); return parseStrictInteger(n); } /** Splits output into bounded chunks without splitting UTF-16 surrogate pairs. */ 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; } /** Truncates long labels in the middle while preserving UTF-16 boundaries. */ 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, "\n").split("\n"); 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("\n"), totalLines: i, totalChars: a }; } /** Derives a compact human label from a shell command. */ 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); } //#endregion //#region 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")); /** Resolves the retention duration captured by one admitted exec process. */ 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; } }; /** Creates one output owner; string views are materialized only by readers. */ 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 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; const changeListeners = /* @__PURE__ */ new Set(); const pendingChanges = /* @__PURE__ */ new Map(); let changeTimer; /** Process observation is independent of the creating turn's lifetime. */ 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 = { sessionKey: t, agentId: e.agentId }; pendingChanges.set(JSON.stringify([t, e.agentId]), n); changeTimer ??= runInDetachedAsyncContext(() => setTimeout(() => { changeTimer = void 0; const e = [...pendingChanges.values()]; pendingChanges.clear(); for (const t of e) notifyListeners(changeListeners, t); }, 5e3)); changeTimer.unref(); } /** Return whether a process session id is live, retained, or reserved for notification. */ function isProcessSessionIdTaken(e) { return runningSessions.has(e) || finishedSessions.has(e) || activeExecSessions.has(e); } /** Adds a running session; retention starts only after background completion. */ 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); } /** Sorts registered process records newest-first, including same-millisecond starts. */ function compareProcessSessionStartOrder(e, t) { return t.startedAt - e.startedAt || processSessionStartOrders.get(t) - processSessionStartOrders.get(e); } /** Stable while this exact process is retained, including after its friendly ID is reused. */ function processSessionInstanceId(e) { const t = processInstanceIds.get(e); if (!t) throw new Error("Process is not registered"); return t; } /** Returns a running session by id. */ function getSession(e) { return runningSessions.get(e); } /** Returns a retained finished background session by id. */ 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; queueProcessChange(t); return true; } /** Removes visible session records without changing live-process activity. */ function deleteSession(e) { const t = runningSessions.get(e); runningSessions.delete(e); if (t && (t.backgrounded || activeExecSessions.get(e)?.promoted)) queueProcessChange(t); deleteFinishedSession(e); scheduleSweeper(); } /** Removes completed process records belonging to retired session identities. */ 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(); } /** Appends process output while enforcing aggregate and pending-output caps. */ 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; const c = e.output.length; e.output.append(a, e.maxOutputChars, n.length); e.truncated ||= e.output.length < c + n.length; if (e.backgrounded) queueProcessChange(e); } /** Drains pending chunks in producer callback order for a process poll. */ 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 }; } /** Stages one poll result until the agent transcript acknowledges its attachment. */ 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; } }; } /** Returns whether a prior poll has output ready for immediate replay. */ function hasPendingPollDelivery(e) { return e.pendingPollDelivery !== void 0; } /** Moves a session to finished state and records exit metadata. */ 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); if (e.backgrounded) queueProcessChange(e); if (!e.finalizing) settleExecSessionFinalization(e); } /** Releases scope joins after the process owner's task and notification work settles. */ function settleExecSessionFinalization(e) { e.finalizing = false; const t = activeExecSessions.get(e.id); if (t?.session === e) { activeExecSessions.delete(e.id); t.settled?.resolve(); } } /** Publish accepted Stop while cleanup still owns the terminal transition. */ function markCancellationRequested(e) { if (e.cancellationRequested) return; e.cancellationRequested = true; if (e.backgrounded) queueProcessChange(e); } /** Marks a running session as reconnectable after the exec call returns. */ function markBackgrounded(e) { if (!e.backgrounded) queueProcessChange(e); e.backgrounded = true; const t = activeExecSessions.get(e.id); if (t?.session === e) t.promoted = true; } /** Retains the precise completion-event removal handle on its process owner. */ function recordNotifyOnExitRemoval(e, t) { if (e.terminalPollObserved || e.requestCancelled) { t(); return; } e.notifyOnExitRemoval = t; } /** Acknowledges one completion event without touching unrelated queue entries. */ function acknowledgeNotifyOnExit(e) { e.terminalPollObserved = true; removeNotifyOnExit(e); } /** Retire notification custody without claiming that retained output was observed. */ function removeNotifyOnExit(e) { const t = e.notifyOnExitRemoval; if (!t) return; t(); e.notifyOnExitRemoval = void 0; } /** Returns the number of live background exec sessions without exposing process details. */ function getActiveBackgroundExecSessionCount() { let e = 0; for (const { promoted: t } of activeExecSessions.values()) if (t) e += 1; return e; } /** Joins registered exec cleanup, including foreground and hidden processes. */ async function waitForExecScope(e) { while (true) { const t = Array.from(activeExecSessions.values()).filter(({ session: t }) => t.scopeKey === e).map((e) => (e.settled ??= createDeferredCore()).promise); if (t.length === 0) return; await Promise.all(t); } } /** Cancellation captures exact records, including startup, hidden work and queued completions. */ 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 = 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(); } /** Returns the last `max` characters of text without adding ellipses. */ function tail(e, t = 2e3) { if (e.length <= t) return e; return Buffer.from(sliceUtf16Safe(e, e.length - t), "utf16le").toString("utf16le"); } /** Lists backgrounded running sessions visible to reconnect/poll callers. */ function listRunningSessions() { return Array.from(runningSessions.values()).filter((e) => e.backgrounded); } /** Lists retained finished background sessions. */ function listFinishedSessions() { return Array.from(finishedSessions.values()); } /** Test-only reset for in-memory registry state and retention timers. */ 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(); stopSweeper(); } if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.bashProcessRegistryTestApi")] = { resetProcessRegistryForTests }; function scheduleSweeper() { stopSweeper(); 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 (!Number.isFinite(t)) return; sweeper = setTimeout(scheduleSweeper, t - e); sweeper.unref(); } function stopSweeper() { if (!sweeper) return; clearTimeout(sweeper); sweeper = null; } //#endregion export { chunkString as A, removeNotifyOnExit as C, waitForExecScope as D, tail as E, sliceLogLines as F, truncateMiddle as I, coerceEnv as M, deriveSessionName as N, waitForExecSession as O, readEnvInt as P, recordNotifyOnExitRemoval as S, settleExecSessionFinalization as T, markCancellationRequested as _, compareProcessSessionStartOrder as a, prepareSessionPoll as b, getActiveBackgroundExecSessionCount as c, hasPendingPollDelivery as d, isProcessSessionIdTaken as f, markBackgrounded as g, listRunningSessions as h, clearFinishedSessionsForScopes as i, clampWithDefault as j, buildSandboxEnv as k, getFinishedSession as l, listFinishedSessions as m, addSession as n, createProcessSession as o, listExecSessionsForCancellation 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 };