openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
124 lines • 27.8 kB
JavaScript
import{t as DURABLE_PROCESS_LAUNCHD_LABEL_PREFIX}from"./constants-tH5Q8GoI.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import"./errors-D37BJTfI.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{w as isSubagentSessionKey,x as isCronSessionKey}from"./session-key-BPgKfU2m.mjs";import{n as waitForAgentDatabasePreparation}from"./agent-database-preparation-context-CPut921o.mjs";import{c as resolveExecutablePath}from"./executable-path-BYWCW0PG.mjs";import{r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import{n as getSpawnBroker,r as runWithSpawnBroker}from"./context-state-CSLm35p3.mjs";import"./context-B64RxSW7.mjs";import{n as describeLiveProcesses}from"./service-child-group-ownership-CzRiJZ_p.mjs";import{c as watchHostExecMemory,o as getHostExecMemoryBudget,s as readCgroupMemoryUsage}from"./linux-exec-cgroup-kO5YhBoe.mjs";import{a as getRuntimeConfigSnapshot}from"./runtime-snapshot-Bg5K4JNu.mjs";import"./session-event-handoff-DPJ2DWnj.mjs";import{i as readSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{m as withoutGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{i as captureSessionEventTargetForHost}from"./session-event-target-xxrhl4__.mjs";import{l as buildExecExitOutcome,p as hasExitWake,u as buildExecRuntimeErrorOutcome}from"./bash-tools.exec-output-Ci2XRgYO.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{n as isVisibleSpawnedSession,t as isSubagentEnvelopeSession}from"./subagent-capabilities-Cq_ZFJj-.mjs";import{t as getProcessSupervisor}from"./supervisor-4YHLp8V6.mjs";import{A as waitForExecSession,E as setExitWakeRecorder,T as setDurableProcessObserver,f as listExecSessionsForCancellation,n as addSession,o as createProcessSession,r as appendOutput}from"./bash-process-registry-BL4zA8Yf.mjs";import{n as escapeXml}from"./xml-CHe3sJCs.mjs";import{t as parseKeyValueOutput}from"./runtime-parse-Ctdyqc8N.mjs";import{n as createStreamingBinaryOutputSanitizer}from"./shell-utils-B6f0UW0e.mjs";import{a as maybeNotifyOnExit}from"./bash-tools.exec-notify-CT6pCobB.mjs";import{n as settleHostExecDescendants,t as settleExecProcessExit}from"./bash-tools.exec-settlement-Bl5VupHb.mjs";import{t as createDurableProcessStore}from"./bash-durable-process-store-DyIJzLnz.mjs";import path from"node:path";import{createHash}from"node:crypto";import{chmod,mkdir,open,readFile,rm,unlink,writeFile}from"node:fs/promises";import os from"node:os";import{isSupported,readProcessIdentity}from"@openclaw/proc-safe/identity";import{setTimeout}from"node:timers/promises";import{StringDecoder}from"node:string_decoder";
//!src/agents/bash-process-durable-notify.ts
async function prepareAdoptedDurableProcessNotification(e){e.notifySessionTarget=void 0;const{agentId:t,sessionKey:n}=e;if(!e.notifyOnExit||e.cancellationRequested||!t||!n||isCronSessionKey(n)||isSubagentSessionKey(n)){e.notifyOnExit=false;return}const assertNotificationsEnabled=()=>{const e=getRuntimeConfigSnapshot();if(!e||(resolveAgentConfig(e,t)?.tools?.exec?.notifyOnExit??e.tools?.exec?.notifyOnExit)===false)throw new Error(`Automatic exec completion notifications are disabled`)};try{assertNotificationsEnabled();const r=await withoutGatewayToolCallerIdentity(()=>captureSessionEventTargetForHost(t,n,{assertCurrent:assertNotificationsEnabled}));const i=await readSessionEntryReadOnlyInWorker({agentId:t,sessionKey:n,storePath:r.storePath},assertNotificationsEnabled);if(!i||i.archivedAt!==void 0||i.incognito||isSubagentEnvelopeSession(n,{entry:i})&&!isVisibleSpawnedSession(n,{entry:i})){e.notifyOnExit=false;return}e.notifySessionTarget=r}catch{e.notifyOnExit=false}}
//!src/agents/bash-process-durable-supervisor.ts
const MAX_OUTPUT=256e3;async function runDurableControlCommand(e,t,n){try{const r=resolveExecutablePath(e[0],{env:process.env,cwd:process.cwd()});if(!r)throw n();const i=await(await getProcessSupervisor().spawn({mode:`child`,argv:[r,...e.slice(1)],env:process.env,exactEnv:true,cleanupOwnership:`external`,stdinMode:`pipe-closed`,timeoutMs:15e3,maxCapturedOutputChars:MAX_OUTPUT,...t})).wait();if(i.reason!==`exit`||i.stdout.length>=MAX_OUTPUT)throw n();return i}catch{throw n()}}
//!src/agents/bash-process-launchd-wrapper.ts
const DURABLE_LAUNCHD_WRAPPER_SOURCE=String.raw`"use strict";
const fs = require("node:fs");
const { spawn } = require("node:child_process");
const specPath = process.argv[2];
const spec = JSON.parse(fs.readFileSync(specPath, "utf8"));
fs.unlinkSync(specPath);
const startedAt = Date.now();
const save = (value) => {
const temp = spec.statusPath + ".tmp";
fs.writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });
fs.renameSync(temp, spec.statusPath);
};
let pgid, timedOut = false, finished = false, killTimer;
const finish = (result) => {
if (finished) return;
finished = true;
save({ phase: "exited", ...result, pgid, startedAt, durationMs: Date.now() - startedAt });
process.exit(0);
};
// EPERM proves a process still holds the group; only ESRCH proves it empty.
const groupAlive = () => {
try {
process.kill(-pgid, 0);
return true;
} catch (error) {
return error.code !== "ESRCH";
}
};
const signalGroup = (signal) => {
try {
process.kill(-pgid, signal);
} catch {}
};
// Stop and timeout end the whole group, as process kill does for any exec.
const stop = () => {
if (pgid === undefined) return;
signalGroup("SIGTERM");
killTimer ??= setTimeout(() => signalGroup("SIGKILL"), spec.killGraceMs);
};
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(signal, stop);
const failStart = (error) => {
try {
fs.appendFileSync(spec.logPath, "Durable process failed to start: " + error.message + "\n");
} catch {}
finish({ exitCode: null, exitSignal: null, reason: "spawn-error" });
};
let child;
try {
const log = fs.openSync(spec.logPath, "a");
try {
child = spawn(spec.argv[0], spec.argv.slice(1), {
cwd: spec.cwd,
env: spec.env,
stdio: ["ignore", log, log],
detached: true,
});
} finally {
fs.closeSync(log);
}
} catch (error) {
failStart(error);
}
child.once("error", (error) => {
if (pgid === undefined) failStart(error);
});
if (child.pid !== undefined) {
pgid = child.pid;
// Accepted edge case: if this write fails (disk full), the wrapper dies and the command
// runs on unsupervised; the Gateway reports its outcome as unknown.
save({ phase: "running", pgid, startedAt });
child.once("exit", (code, signal) => {
const result = {
exitCode: code,
exitSignal: signal,
reason: timedOut ? "overall-timeout" : signal ? "signal" : "exit",
};
// The command's own exit is its outcome; what it left running keeps running. A stop
// confirms the whole group ended (SIGKILL after the grace) before it records.
const settle = () => (killTimer && groupAlive() ? setTimeout(settle, 200) : finish(result));
settle();
});
if (spec.timeoutMs > 0) {
setTimeout(() => {
timedOut = true;
stop();
}, spec.timeoutMs);
}
}
`;
//!src/agents/bash-process-launchd.ts
const REQUIREMENT$1=`Durable exec requires Gateway-host execution on Linux with systemd 250 or newer, or on macOS from a logged-in user's GUI (Aqua) session. Use ordinary background exec on unsupported hosts.`;const KILL_GRACE_MS=1e4;const failure$1=()=>/* @__PURE__ */ new Error("Durable process control was not confirmed; inspect process status and `launchctl list` before retrying.");const LOST_NOTE=`
Durable process supervisor ended before recording the outcome; outcome unknown. Check saved output and side effects before repeating work.
`;const command$1=(e,t={})=>runDurableControlCommand(e,t,failure$1);const domain=()=>`gui/${process.getuid()}`;const directory=()=>path.join(resolveStateDir(),`processes`);const file=(e,t)=>path.join(directory(),`${e}${t}`);function durableProcessUnitName$1(e){return`${DURABLE_PROCESS_LAUNCHD_LABEL_PREFIX}${createHash(`sha256`).update(e).digest(`hex`)}`}function assertLabel(e){if(!new RegExp(`^${`ai.openclaw.durable-proc.`.replaceAll(`.`,`\\.`)}[a-f0-9]{64}$`).test(e))throw new Error(`Invalid durable process job identity.`)}async function requireDurableProcessHost$1(){try{if(process.platform!==`darwin`||typeof process.getuid!==`function`)throw failure$1();const e=await command$1([`launchctl`,`managername`]);if(e.exitCode!==0||e.stdout.trim()!==`Aqua`)throw failure$1()}catch{throw new Error(REQUIREMENT$1)}}async function readStatus(e){let t;try{t=await readFile(file(e,`.status.json`),`utf8`)}catch(e){if(hasErrnoCode(e,`ENOENT`))return;throw e}return JSON.parse(t)}async function listJob(e){const t=await command$1([`launchctl`,`list`]);const[n,...r]=t.stdout.split(`
`);if(t.exitCode!==0||n?.trim().split(/\s+/).join(` `)!==`PID Status Label`)throw failure$1();for(const t of r){const n=t.split(` `);if(n[2]!==e)continue;const r=n[0]===`-`?void 0:Number(n[0]);const i=Number(n[1]);if(r!==void 0&&!(Number.isInteger(r)&&r>0)||!Number.isInteger(i))throw failure$1();return{pid:r,status:i}}}function alive(e,t){if(Date.now()-os.uptime()*1e3>t)return false;try{process.kill(e,0);return true}catch(e){return!hasErrnoCode(e,`ESRCH`)}}function leftovers(e,t,n){if(!alive(-e,t))return[];return describeLiveProcesses(t=>{if(t.pgid!==e)return false;const r=isSupported()?readProcessIdentity(t.pid):null;return!r||r.startTimeMicros/1e3<=n})}function exited(e){const{pgid:t,startedAt:n}=e;return{state:`exited`,exitCode:e.exitCode,exitSignal:e.exitSignal,reason:e.reason,result:e.reason,durationMs:e.durationMs,survivors:t===void 0||n===void 0?[]:leftovers(t,n,n+e.durationMs)}}async function readDurableProcess$1(e){assertLabel(e);const t=await readStatus(e);if(t?.phase===`exited`)return exited(t);const n=await listJob(e);const r=await readStatus(e);if(r?.phase===`exited`)return exited(r);if(n?.pid)return{state:`running`,pid:n.pid};if(r?.phase===`running`)return t?.phase!==`running`||alive(r.pgid,r.startedAt)?{state:`running`}:{state:`exited`,exitCode:null,exitSignal:null,reason:`spawn-error`,result:`supervisor-lost`,note:LOST_NOTE,survivors:leftovers(r.pgid,r.startedAt,Date.now())};if(!n)return{state:`missing`};return n.status===0?{state:`running`}:{state:`exited`,exitCode:null,exitSignal:null,reason:`spawn-error`,result:`launchd-status-${n.status}`,note:LOST_NOTE}}async function launchDurableProcess$1(e){const t=durableProcessUnitName$1(e.id);const n=createHash(`sha256`).update(DURABLE_LAUNCHD_WRAPPER_SOURCE).digest(`hex`);const r=path.join(directory(),`durable-wrapper-${n.slice(0,16)}.cjs`);await writeFile(r,DURABLE_LAUNCHD_WRAPPER_SOURCE,{flag:`wx`,mode:384}).catch(e=>{if(!hasErrnoCode(e,`EEXIST`))throw e});const i=file(t,`.spec.json`);const a={argv:e.argv,cwd:e.cwd,env:e.env,logPath:e.logPath,statusPath:file(t,`.status.json`),timeoutMs:e.timeoutMs??0,killGraceMs:KILL_GRACE_MS};await writeFile(i,JSON.stringify(a),{flag:`wx`,mode:384});const strings=e=>e.map(e=>`<string>${escapeXml(e)}</string>`).join(``);const o=file(t,`.plist`);await writeFile(o,`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>${t}</string>
<key>ProgramArguments</key><array>${strings([process.execPath,r,i])}</array>
<key>WorkingDirectory</key>${strings([directory()])}
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><false/>
<key>ProcessType</key><string>Interactive</string>
<key>ExitTimeOut</key><integer>15</integer>
<key>SoftResourceLimits</key><dict><key>Core</key><integer>0</integer></dict>
<key>HardResourceLimits</key><dict><key>Core</key><integer>0</integer></dict>
<key>StandardOutPath</key>${strings([e.logPath])}
<key>StandardErrorPath</key>${strings([e.logPath])}
</dict></plist>
`,{flag:`wx`});await chmod(o,420);if((await command$1([`launchctl`,`bootstrap`,domain(),o],{assertCurrent:e.assertCurrent,initiateSpawn:e.initiateSpawn})).exitCode!==0)throw failure$1();return{unitName:t}}async function stopDurableProcess$1(e,t={}){assertLabel(e);const n=Date.now()+KILL_GRACE_MS+5e3;let r=false;let i=await readDurableProcess$1(e);while(i.state===`running`){if(i.pid&&!r)r=(await command$1([`launchctl`,`kill`,`SIGTERM`,`${domain()}/${e}`],t)).exitCode===0;if(Date.now()>n)throw failure$1();await setTimeout(250);i=await readDurableProcess$1(e)}}async function cleanupDurableProcess$1(e,t){assertLabel(e);if((await command$1([`launchctl`,`bootout`,`${domain()}/${e}`],t)).exitCode!==0&&await listJob(e))throw failure$1();for(const t of[`.plist`,`.spec.json`,`.status.json`,`.status.json.tmp`])await rm(file(e,t),{force:true})}const launchdDurableSupervisor={unitName:durableProcessUnitName$1,requireHost:requireDurableProcessHost$1,launch:launchDurableProcess$1,read:readDurableProcess$1,stop:stopDurableProcess$1,cleanup:cleanupDurableProcess$1};
//!src/agents/bash-process-systemd.ts
const REQUIREMENT=`Durable exec requires Gateway-host execution on Linux, systemd 250 or newer, and a reachable Gateway user's systemd manager (XDG_RUNTIME_DIR or DBUS_SESSION_BUS_ADDRESS). Use ordinary background exec on unsupported hosts.`;const MANAGER_KEYS=[`XDG_RUNTIME_DIR`,`DBUS_SESSION_BUS_ADDRESS`];const EXIT_REASONS={timeout:`overall-timeout`,"oom-kill":`memory-limit`};let version$1;const SUCCESS_EXIT_STATUS=[...Array.from({length:255},(e,t)=>t+1),...[`HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT`,`CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH IO PWR SYS`].join(` `).split(` `).map(e=>`SIG${e}`)].join(` `);const failure=()=>/* @__PURE__ */ new Error(`Durable process control was not confirmed; inspect process status and the systemd user manager before retrying.`);const command=(e,t={})=>runDurableControlCommand(e,t,failure);function durableProcessUnitName(e){return`openclaw-proc-${createHash(`sha256`).update(e).digest(`hex`)}.service`}function control(e,t,n){if(!/^openclaw-proc-[a-f0-9]{64}\.service$/.test(t))throw new Error(`Invalid durable process unit identity.`);return command([`systemctl`,`--user`,`--no-ask-password`,...e,`--`,t],n)}async function requireDurableProcessHost(e=process.env){if(process.platform!==`linux`||!MANAGER_KEYS.some(e=>process.env[e]))throw new Error(REQUIREMENT);if(MANAGER_KEYS.some(t=>e[t]!==void 0&&e[t]!==process.env[t]))throw new Error(`${REQUIREMENT} Remove user-manager environment overrides.`);try{const e=await(version$1??=command([`systemctl`,`--user`,`--version`]).then(e=>Number(/^systemd (\d+)/m.exec(e.stdout)?.[1])));const t=await command([`systemctl`,`--user`,`show`,`--property=Version`]);if(!(e>=250)||t.exitCode!==0||!(Number(/^Version=(\d+)/m.exec(t.stdout)?.[1])>=250))throw failure()}catch{throw new Error(REQUIREMENT)}}async function launchDurableProcess(e){const t=durableProcessUnitName(e.id);const n=await command([`systemctl`,`--user`,`show-environment`]);if(n.exitCode!==0)throw failure();const r=n.stdout.split(`
`).map(e=>/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(e)?.[1]).filter(t=>t&&!(t in e.env));const i=getHostExecMemoryBudget();const a={Type:`exec`,RemainAfterExit:`yes`,SuccessExitStatus:SUCCESS_EXIT_STATUS,KillMode:`control-group`,TimeoutStopSec:`10s`,LimitCORE:0,StandardInput:`null`,StandardOutput:`append:${e.logPath}`,StandardError:`inherit`,RuntimeMaxSec:e.timeoutMs?`${e.timeoutMs/1e3}s`:`infinity`,MemoryMax:i?.memoryBytes??`infinity`,...i?{MemorySwapMax:i.swapBytes,OOMPolicy:`kill`}:{},UnsetEnvironment:r.join(` `)};const o={...e.env};for(const e of MANAGER_KEYS)o[e]=process.env[e];if((await command([`systemd-run`,`--user`,`--quiet`,`--no-ask-password`,`--unit=${t}`,`--description=OpenClaw durable process`,`--working-directory=${e.cwd}`,...Object.entries(a).map(([e,t])=>`--property=${e}=${t}`),...Object.keys(e.env).map(e=>`--setenv=${e}`),`--`,...e.argv.map(e=>e.replaceAll(`$`,()=>`$$`))],{env:o,initiateSpawn:e.initiateSpawn,assertCurrent:e.assertCurrent})).exitCode!==0)throw failure();return{unitName:t}}async function readDurableProcess(e){const t=await control([`show`,`--property=LoadState,ActiveState,SubState,MainPID,ControlGroup,ExecMainCode,ExecMainStatus,Result`],e);const n=parseKeyValueOutput(t.stdout,`=`);if(n.loadstate===`not-found`)return{state:`missing`};if(t.exitCode!==0||n.loadstate!==`loaded`)throw failure();const r=n.controlgroup;const i=r?.startsWith(`/`)&&!r.split(`/`).includes(`..`)?path.join(`/sys/fs/cgroup`,r):void 0;if([`activating`,`deactivating`,`reloading`].includes(n.activestate??``)||n.activestate===`active`&&n.substate!==`exited`)return{state:`running`,pid:Number(n.mainpid)||void 0,...i?{cgroupDirectory:i}:{}};const a=Number(n.execmaincode),o=Number(n.execmainstatus),s=a===2||a===3;const c=EXIT_REASONS[n.result??``]??(s?`signal`:a===1?`exit`:`spawn-error`);const l=i?await readFile(path.join(i,`cgroup.procs`),`utf8`).catch(e=>{if(!hasErrnoCode(e,`ENOENT`))throw e;return``}):``;const u=new Set(l.split(`
`).filter(Boolean).map(Number));return{state:`exited`,exitCode:a===1?o:null,exitSignal:s?o:null,reason:c,result:n.result??`unknown`,survivors:u.size===0?[]:describeLiveProcesses(e=>u.has(e.pid))}}async function stopDurableProcess(e,t){if((await control([`stop`],e,t)).exitCode!==0)throw failure()}async function cleanupDurableProcess(e,t){const n=await readDurableProcess(e);if(n.state===`exited`&&n.survivors?.length!==0)return;for(const n of[`stop`,`reset-failed`])if((await control([n],e,t)).exitCode!==0&&(await readDurableProcess(e)).state!==`missing`)throw failure()}const systemdDurableSupervisor={unitName:durableProcessUnitName,requireHost:requireDurableProcessHost,launch:launchDurableProcess,read:readDurableProcess,stop:stopDurableProcess,cleanup:cleanupDurableProcess};
//!src/agents/bash-process-durable.ts
let store;const supervisor=()=>process.platform===`darwin`?launchdDurableSupervisor:systemdDurableSupervisor;const warn=()=>logWarn(`exec: durable process observation or persistence failed; inspect process status and the systemd user manager or launchd.`);const sessions=()=>listExecSessionsForCancellation().filter(e=>e.durable);async function forgetLog(e){await unlink(e).catch(e=>{if(!hasErrnoCode(e,`ENOENT`))throw e})}async function observe(){for(const e of sessions())await e.durable.observe().catch(warn)}const ordinaryRecords=/* @__PURE__ */ new WeakMap;const ordinaryWrites=/* @__PURE__ */ new Map;function writeOrdinary(e,t){const n=(ordinaryWrites.get(e)??Promise.resolve()).then(t).catch(()=>logWarn(`exec: could not record a background command for restart reporting.`));ordinaryWrites.set(e,n);n.finally(()=>{if(ordinaryWrites.get(e)===n)ordinaryWrites.delete(e)})}const ordinaryExitWakeRecorder={backgrounded(e){const t=store;if(!t||e.durable||!hasExitWake(e)||!e.agentId||!e.sessionKey||isIncognitoSessionKey(e.sessionKey))return;const n=supervisor().unitName(e.id);const r={kind:`ordinary`,...e.sandboxContainerName?{sandboxed:true}:{},id:e.id,agentId:e.agentId,sessionKey:e.sessionKey,scopeKey:e.scopeKey,unitName:n,logPath:path.join(resolveStateDir(),`processes`,`${n}.log`),command:`Background exec`,cwd:e.cwd,startedAt:e.startedAt,cleanupMs:e.cleanupMs,maxOutputChars:e.maxOutputChars,notifyOnExit:true,notifyOnExitEmptySuccess:e.notifyOnExitEmptySuccess};ordinaryRecords.set(e,r);writeOrdinary(e.id,()=>t.upsert(r))},exited(e){const t=store;const n=ordinaryRecords.get(e);if(!t||!n)return;ordinaryRecords.delete(e);writeOrdinary(e.id,()=>t.remove(n.id))}};async function settleLostOrdinaryProcess(e,t){const n=createProcessSession({...e,totalOutputChars:0,pendingStdoutChars:0,pendingStderrChars:0,pendingOutputDropped:false,exited:false,truncated:false,backgrounded:true,cursorKeyMode:`normal`});const r=new Date(e.startedAt).toISOString();const i=t?.[e.agentId]?.some(t=>e.startedAt>=t.startedAt&&e.startedAt<t.endedAt);const a=!e.sandboxed&&(!i||process.platform===`linux`);appendOutput(n,`stderr`,a?`This background command (started ${r}) was stopped when the Gateway ${i?`restarted unexpectedly`:`shut down`}, so its result will not arrive. If you still need it, check its output and side effects, then run it again.\n`:`The Gateway ${i?`restarted unexpectedly`:`restarted`} while this background command (started ${r}) was running. It may still be running, but its result will not wake this conversation. Check its output and side effects before running it again.\n`);n.finalizing=true;await waitForAgentDatabasePreparation(e.agentId);await prepareAdoptedDurableProcessNotification(n);ordinaryRecords.set(n,e);addSession(n);await settleExecProcessExit({session:n,outcome:buildExecExitOutcome({exit:{reason:`spawn-error`,exitCode:null,exitSignal:null,durationMs:Date.now()-e.startedAt,stdout:``,stderr:``,timedOut:false,noOutputTimedOut:false},aggregated:n.aggregated,durationMs:Date.now()-e.startedAt,timeoutSec:null,processContinuationAvailable:false}),notifyOnExit:(e,t)=>maybeNotifyOnExit(e,t,false),failureOutcome:t=>buildExecRuntimeErrorOutcome({error:t,aggregated:n.aggregated,durationMs:Date.now()-e.startedAt})})}async function initializeDurableProcesses(e={}){if(store)throw new Error(`Durable processes already have a Gateway owner`);const t=createDurableProcessStore({assertCurrent:()=>{e.assertCurrent?.();if(store!==t)throw new Error(`Durable process Gateway owner is closed`)}});store=t;setExitWakeRecorder(ordinaryExitWakeRecorder);for(const n of await t.list()){if(n.kind===`ordinary`){settleLostOrdinaryProcess(n,e.crashWindows).catch(()=>logWarn(`exec: could not report a background command the last Gateway lost.`));continue}if(n.notificationSettled&&n.endedAt!==void 0&&n.endedAt+n.cleanupMs<=Date.now()){supervisor().cleanup(n.unitName,{assertCurrent:t.assertCurrent}).then(async()=>{await t.remove(n.id);await forgetLog(n.logPath)}).catch(warn);continue}const r=createProcessSession({...n,totalOutputChars:0,pendingStdoutChars:0,pendingStderrChars:0,pendingOutputDropped:false,exited:false,truncated:false,backgrounded:true,cursorKeyMode:`normal`});const prepareNotification=()=>{r.notifyOnExit=n.notifyOnExit&&!n.notificationSettled;return prepareAdoptedDurableProcessNotification(r)};await prepareNotification();const i=bind(r,n,t);addSession(r);i.wait().then(async e=>{r.finalizing=true;await prepareNotification();const t=buildExecExitOutcome({exit:e,aggregated:r.aggregated,durationMs:e.durationMs,timeoutSec:null,processContinuationAvailable:true});await settleExecProcessExit({session:r,outcome:await settleHostExecDescendants(r,i,t,[]),notifyOnExit:(e,t)=>maybeNotifyOnExit(e,t,false),failureOutcome:t=>buildExecRuntimeErrorOutcome({error:t,aggregated:r.aggregated,durationMs:e.durationMs})})}).catch(warn)}setDurableProcessObserver(observe)}async function disposeDurableProcesses(){setDurableProcessObserver(void 0);setExitWakeRecorder(void 0);await Promise.all(ordinaryWrites.values());await Promise.allSettled(sessions().map(e=>e.durable.drain()));await Promise.all(sessions().filter(e=>e.exited||e.processActivity?.resultSettled).map(waitForExecSession));store=void 0}async function startDurableExecProcess(e,t,n={}){if(!store||!e.agentId||!e.sessionKey||t.mode!==`child`)throw new Error(`Durable exec requires a Gateway-host session on Linux with systemd 250 or newer and a reachable user manager, or on macOS in a logged-in GUI session; sandbox, node, worker, and one-shot execution are unsupported.`);const r=store;await supervisor().requireHost(t.env);const i=supervisor().unitName(e.id);const a=path.join(resolveStateDir(),`processes`,`${i}.log`);await mkdir(path.dirname(a),{recursive:true,mode:448});await(await open(a,`wx`,384)).close();const o={id:e.id,agentId:e.agentId,sessionKey:e.sessionKey,scopeKey:e.scopeKey,unitName:i,logPath:a,command:`Durable background exec`,cwd:e.cwd,startedAt:e.startedAt,cleanupMs:e.cleanupMs,maxOutputChars:e.maxOutputChars,notifyOnExit:n.notifyOnExit??e.notifyOnExit,notifyOnExitEmptySuccess:n.notifyOnExitEmptySuccess??e.notifyOnExitEmptySuccess};const assertCurrent=()=>{r.assertCurrent();t.assertCurrent?.();t.beforeSpawn?.()};await r.upsert(o,assertCurrent);const s=Object.fromEntries(Object.entries(t.env??{}).filter(e=>e[1]!==void 0));try{await supervisor().launch({id:e.id,argv:t.argv,cwd:t.cwd,env:s,logPath:a,timeoutMs:t.timeoutMs,assertCurrent,initiateSpawn:t.initiateSpawn})}catch{appendOutput(e,`stderr`,`Durable launch was not confirmed. Check this process and the systemd user manager or launchd before repeating work.
`)}const c=bind(e,o,r);setDurableProcessObserver(observe);return c}function bind(e,t,n){const r=getSpawnBroker();const i=createDeferredCore();let a=Promise.resolve(),o=0,s=false,c;let l;let u=[];const d=new StringDecoder(`utf8`),f=createStreamingBinaryOutputSanitizer();const enqueue=e=>a=a.catch(warn).then(()=>runWithSpawnBroker(r,e));const observeUnit=async()=>{if(s)return;const r=t.result?{state:`missing`}:await supervisor().read(t.unitName);const a=await open(t.logPath,`r`).catch(e=>{if(!hasErrnoCode(e,`ENOENT`))throw e});if(a)try{const t=(await a.stat()).size,n=Math.max(o,t-e.maxOutputChars*4);e.truncated||=n>o;e.totalOutputChars+=n-o;const r=Buffer.alloc(Math.max(0,t-n));const{bytesRead:i}=await a.read(r,0,r.length,n);o=n+i;appendOutput(e,`stdout`,f(d.write(r.subarray(0,i))))}finally{await a.close()}if(!t.result){if(r.state===`running`){e.pid=r.pid;l=r.cgroupDirectory;return}if(r.state===`missing`&&!c)appendOutput(e,`stderr`,`
Durable process unit is missing; outcome unknown. Check saved output and side effects before repeating work.
`);if(r.state===`exited`&&r.note)appendOutput(e,`stderr`,r.note);u=r.state===`exited`&&r.survivors||[];const i={reason:c??(r.state===`exited`?r.reason:`spawn-error`),exitCode:r.state===`exited`?r.exitCode:null,exitSignal:r.state===`exited`?r.exitSignal:null,durationMs:(r.state===`exited`?r.durationMs:void 0)??Date.now()-t.startedAt};const a=Date.now();await n.upsert({...t,result:i,endedAt:a});t.result=i;t.endedAt=a}e.endedAt=t.endedAt;appendOutput(e,`stdout`,f(d.end()));s=true;p();i.resolve({...t.result,stdout:``,stderr:``,timedOut:t.result.reason===`overall-timeout`,noOutputTimedOut:false});await release()};const release=()=>supervisor().cleanup(t.unitName,{assertCurrent:n.assertCurrent});const cancel=(e,r)=>{const assertCurrent=()=>{n.assertCurrent();r?.()};return enqueue(async()=>{if(s)return;if(e===`manual-cancel`)t.cancellationRequested=true;await n.upsert(t,assertCurrent);await supervisor().stop(t.unitName,{assertCurrent});c??=e;await observeUnit()})};const p=runInDetachedAsyncContext(()=>watchHostExecMemory({readUsage:async()=>{if(!l&&!s)await enqueue(observeUnit);if(s)return{memoryBytes:0,swapBytes:0};if(!l)throw new Error(`Durable process cgroup usage is unavailable`);try{return await readCgroupMemoryUsage(l)}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e;await enqueue(observeUnit);if(s)return{memoryBytes:0,swapBytes:0};throw e}},onLimit:()=>cancel(`memory-limit`),onDiagnostic:t=>appendOutput(e,`stderr`,t)}));e.durable={observe:()=>enqueue(observeUnit),cancel:e=>{cancel(`manual-cancel`,e).catch(warn)},remove:()=>{enqueue(async()=>{await release();await n.remove(t.id);await forgetLog(t.logPath)}).catch(warn)},finalize:()=>enqueue(async()=>{t.notificationSettled=true;await n.upsert(t)}),drain:()=>{p();return a}};const m={get resultSettled(){return s},lastOutputAtMs:t.startedAt};e.processActivity=m;return{runId:e.id,startedAtMs:t.startedAt,activity:m,wait:()=>i.promise,releasesOnRootExit:true,waitForExtinction:async()=>{await i.promise;return{status:`released`,survivors:u}},cancel:(e=`manual-cancel`)=>{cancel(e).catch(warn)}}}export{disposeDurableProcesses,initializeDurableProcesses,startDurableExecProcess};