openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 19.3 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{r as resolveRuntimeScriptPosition}from"./runtime-binary-DNstBs1K.mjs";import{o as getCommandPositionalsWithRootOptions,s as getRootOptionAwareCommandPath}from"./cli-root-options-eez2TgAl.mjs";import{d as normalizeWindowsTaskIdentity,f as resolveGatewayLaunchAgentLabel,g as resolveGatewaySystemdServiceName,i as GATEWAY_SERVICE_MARKER,r as GATEWAY_SERVICE_KIND,s as LEGACY_GATEWAY_SYSTEMD_SERVICE_NAMES,u as isNodeLaunchAgentLabel,v as resolveGatewayWindowsTaskName}from"./constants-tH5Q8GoI.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{a as findExistingAncestor}from"./fs-safe-Bxzu1j4h.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as classifyOpenClawArgv}from"./gateway-process-argv-CNoJIDKD.mjs";import{n as POSIX_INLINE_COMMAND_FLAGS,p as resolveInlineCommandMatch}from"./shell-inline-command-Ba_Xy6r0.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{n as awaitWithinDeadline,t as ABSOLUTE_DEADLINE_EXPIRED}from"./absolute-deadline-CE14TWdo.mjs";import{r as splitShellArgs}from"./shell-argv-DTuTJ2xJ.mjs";import{S as isEnvAssignmentToken,r as POSIX_SHELL_WRAPPERS,w as resolveCarrierCommandArgv}from"./shell-wrapper-resolution-NzL5LGuL.mjs";import{t as resolveDaemonHomeDir}from"./paths-DJalwizy.mjs";import{t as quoteCliArg}from"./quote-cli-arg-BUHoGELl.mjs";import{a as parseCmdSetAssignment}from"./cmd-argv-B4rWHSat.mjs";import{T as splitSystemdLogicalLines,b as parseSystemdInlineEnvironment,c as resolveSystemdServiceName,y as parseSystemdExecStart}from"./systemd-service-files-C0LoSdR4.mjs";import{t as splitArgsPreservingQuotes}from"./arg-split-4lIyoVOa.mjs";import{a as readScheduledTaskCommand,c as resolveStartupEntryPaths,h as listScheduledTasks,o as readStartupEntryCommand,s as resolveStartupEntryPath,u as resolveTaskName}from"./schtasks-layout-77R2ivPQ.mjs";import{t as WINDOWS_POWERSHELL_COLD_SPAWN_TIMEOUT_MS}from"./windows-powershell-spawn-DerlBd0z.mjs";import{n as resolveWindowsServiceCommandProfile}from"./service-env-merge-Db3tXSCb.mjs";import{n as resolveLaunchAgentLabel}from"./launchd-label-Daj1UmUS.mjs";import{c as resolveGeneratedEnvWrapperLayout,i as decodeLaunchdPlistMetadata}from"./launchd-plist-Bg6wneGv.mjs";import{n as resolveSystemdUnitLoadDirectories,t as DEFAULT_SYSTEMD_SYSTEM_UNIT_DIRS}from"./systemd-unit-load-paths-COA9POVF.mjs";import{n as listLoadedSystemdUnits}from"./systemd-loaded-unit-inventory-B5lwrkK0.mjs";import path from"node:path";import fs from"node:fs/promises";
//!src/daemon/inspect-markers.ts
const EXTRA_MARKERS=[`openclaw`,`clawdbot`];function classifyGatewayCommand(e){let t=resolveCarrierCommandArgv(e)??e;if(POSIX_SHELL_WRAPPERS.has(path.posix.basename(t[0]??``).toLowerCase())){const{command:e}=resolveInlineCommandMatch(t,POSIX_INLINE_COMMAND_FLAGS,{allowCombinedC:true});const n=e?splitShellArgs(e):null;if(!n)return`unknown`;while(n.length>0&&isEnvAssignmentToken(n[0]))n.shift();t=resolveCarrierCommandArgv(n)??n}t=resolveCarrierCommandArgv(t)??t;const{position:n}=resolveRuntimeScriptPosition(t);if(typeof n!==`number`&&n.kind!==`not-runtime`)return`unknown`;const r=typeof n===`number`?n:0;const i=[`node`,...t.slice(r)];if(getRootOptionAwareCommandPath(i,1)[0]!==`gateway`)return`unknown`;const a=getCommandPositionalsWithRootOptions(i,{commandPath:[`gateway`],maxPositionals:1,mode:`command-path`})?.[0];if(a===void 0||a===`run`)return`run`;const o=classifyOpenClawArgv(t,{command:`gateway`});return o.kind===`openclaw`&&o.entryIndex===r?`maintenance`:`run`}function hasGatewaySubcommandArg(e){return classifyGatewayCommand(e)===`run`}function detectMarkerLineWithGateway(e){for(const t of splitSystemdLogicalLines(e)){const e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`;`))continue;const n=e.indexOf(`=`);if(n>0){if(normalizeLowercaseStringOrEmpty(e.slice(0,n))!==`execstart`||!hasGatewaySubcommandArg(parseSystemdExecStart(e.slice(n+1).trim())))continue}const r=normalizeLowercaseStringOrEmpty(e);if(!r.includes(`gateway`))continue;for(const e of EXTRA_MARKERS)if(r.includes(e))return e}return null}function hasGatewayServiceMarker(e){const t=asOptionalRecord(e);return t?.OPENCLAW_SERVICE_MARKER===`openclaw`&&t.OPENCLAW_SERVICE_KIND===`gateway`}function detectSystemdGatewayExecutionMarker(e){const t=e.map(e=>`${e.path} ${e.programArguments.join(` `)}`).join(` `).toLowerCase();return/(?:^|[\s;])gateway(?:[\s;]|$)/.test(t)?EXTRA_MARKERS.find(e=>t.includes(e))??null:null}function areSystemdCommandsMaintenance(e){return e.every(e=>classifyGatewayCommand([e.path,...e.programArguments.slice(1)])===`maintenance`)}function detectLaunchdGatewayExecutionMarker(e){const t=e.ProgramArguments;if(!Array.isArray(t)||!t.every(e=>typeof e===`string`))return null;if(e.Program!==void 0&&typeof e.Program!==`string`)return null;const n=typeof e.Program===`string`?[e.Program,...t.slice(1)]:t;const r=resolveGeneratedEnvWrapperLayout(n);const i=r?n.slice(r.commandStartIndex):n;if(!hasGatewaySubcommandArg(i))return null;const a=normalizeLowercaseStringOrEmpty(i.join(`
`));return EXTRA_MARKERS.find(e=>a.includes(e))??null}function isOpenClawGatewayTaskName(e){const t=normalizeLowercaseStringOrEmpty(e).replace(/^\\+/,``);return t===normalizeLowercaseStringOrEmpty(resolveGatewayWindowsTaskName())||/^openclaw gateway \(.+\)$/.test(t)}function detectWindowsServiceExecutionMarker(e,t){if(classifyOpenClawArgv(e,{command:`gateway`,cwd:t}).kind===`openclaw`||classifyOpenClawArgv(e,{command:`node`,cwd:t}).kind===`openclaw`)return`openclaw`;const n=normalizeLowercaseStringOrEmpty(e.join(`
`));if(n.includes(`clawdbot`))return`clawdbot`;return n.includes(`openclaw`)&&e.some(e=>/^(?:gateway|node)$/.test(normalizeLowercaseStringOrEmpty(e)))?`openclaw`:null}function detectLauncherGatewayMarker(e){const t={};for(const n of e.split(/\r?\n/)){const e=normalizeLowercaseStringOrEmpty(n);if(e.startsWith(`set `)){const e=parseCmdSetAssignment(n.trimStart().slice(4),true);if(e)t[e.key]=e.value;continue}if(/^(?:#|;|'|rem\s)/.test(e)||!e.includes(`gateway`))continue;const r=EXTRA_MARKERS.find(t=>e.includes(t));if(r)return r}return hasGatewayServiceMarker(t)?`openclaw`:null}
//!src/daemon/inspect-files.ts
function isPotentialGatewayServiceName(e,t,n){return e===n||(t===`darwin`?e.startsWith(`ai.openclaw.`)&&!isNodeLaunchAgentLabel(e)||/clawdbot.*gateway/.test(e):/^(?:openclaw|clawdbot)(?:$|@|-gateway(?:$|[-.@]))/.test(e))}async function collectServiceFiles(e){const t=[];let n;try{n=await fs.readdir(e.dir)}catch(n){if(!hasErrnoCode(n,`ENOENT`))e.errors?.push({source:e.dir,message:`Service path could not be inspected.`});return t}for(const r of n.toSorted()){if(!r.endsWith(e.extension))continue;const n=r.slice(0,-e.extension.length);const i=path.join(e.dir,r);let a;try{a=await fs.readFile(i)}catch{if(e.isPotentialName(n))e.errors?.push({source:i,message:`Service path could not be inspected.`});continue}t.push({entry:r,name:n,fullPath:i,contents:a})}return t}function isLegacyLabel(e){return normalizeLowercaseStringOrEmpty(e).includes(`clawdbot`)}async function scanSystemdDir(e){const t=[];const n=await collectServiceFiles({dir:e.dir,extension:`.service`,isPotentialName:t=>isPotentialGatewayServiceName(t,`linux`,e.selectedName),errors:e.errors});for(const{entry:r,name:i,fullPath:a,contents:o}of n){const n=o.toString(`utf8`);const s=hasGatewayServiceMarker(parseSystemdInlineEnvironment(n));const c=s?`openclaw`:detectMarkerLineWithGateway(n);if(!c)continue;t.push({platform:`linux`,label:r,detail:`unit: ${a}`,sourcePath:a,scope:e.scope,marker:c,legacy:c!==`openclaw`,managedGateway:c===`openclaw`,extra:i!==resolveGatewaySystemdServiceName()&&!(c===`openclaw`&&!isLegacyLabel(i)&&e.scope===`user`&&i===e.selectedName)&&!s&&!(c===`openclaw`&&i.startsWith(`openclaw-gateway`))})}return t}
//!src/daemon/inspect.ts
function projectService({extra:e,managedGateway:t,windowsProfile:n,...r}){return r}function renderGatewayServiceCleanupHints(e=[]){const t=[];for(const n of e)switch(n.platform){case`darwin`:{const e=n.sourcePath;const r=n.scope===`system`&&e?.startsWith(`/Library/LaunchDaemons/`)?`system`:`gui/$UID`;const i=r===`system`?`sudo launchctl`:`launchctl`;t.push(terminalText`${i} bootout ${r}/${quoteCliArg(n.label)}`);if(e){const r=n.scope===`system`?`sudo rm`:`rm`;t.push(terminalText`${r} ${quoteCliArg(e)}`)}break}case`linux`:{const e=`systemctl --${n.scope}`;const r=quoteCliArg(n.label);t.push(terminalText`${e} status -- ${r}`,terminalText`${e} cat -- ${r}`);break}case`win32`:if(n.windowsStartupEntry){t.push(terminalText`Get-Item -LiteralPath '${n.windowsStartupEntry.replaceAll(`'`,`''`)}'`);break}if(/^[A-Za-z0-9_. ()\\/-]+$/.test(n.label))t.push(terminalText`schtasks /Query /TN "${n.label}" /V /FO LIST`)}return t}async function scanLaunchdDir(e){const t=[];const isPotentialName=t=>isPotentialGatewayServiceName(t,`darwin`,e.selectedName);const n=await collectServiceFiles({dir:e.dir,extension:`.plist`,isPotentialName,errors:e.errors});for(const{name:r,fullPath:i,contents:a}of n){const n=await decodeLaunchdPlistMetadata(a).catch(t=>{if(hasCommandProcessCleanupError(t))throw t;const n=normalizeLowercaseStringOrEmpty(a.toString(`utf8`).replaceAll(`\0`,``));if(isPotentialName(r)||EXTRA_MARKERS.some(e=>n.includes(e)))e.errors?.push({source:i,message:`Service plist could not be inspected.`})});if(!n)continue;const o=typeof n.Label===`string`&&n.Label?n.Label:r;const s=detectLaunchdGatewayExecutionMarker(n);const c=hasGatewayServiceMarker(n.EnvironmentVariables);const l=isLegacyLabel(r)||isLegacyLabel(o);const u=o===e.managedLabel||c?`openclaw`:s??(l?`clawdbot`:null);if(!u)continue;t.push({platform:`darwin`,label:o,detail:`plist: ${i}`,sourcePath:i,scope:e.scope,marker:u,legacy:u!==`openclaw`||isLegacyLabel(o),managedGateway:u===`openclaw`&&(c||s===`openclaw`),extra:e.scope===`system`||o!==resolveGatewayLaunchAgentLabel()&&!(u===`openclaw`&&!l&&e.scope===`user`&&o===e.selectedName)&&!(u===`openclaw`&&(c||s===`openclaw`&&o.startsWith(`ai.openclaw.`)))})}return t}async function findSystemGatewayServices(){if(process.platform!==`linux`)return[];const e=[];try{for(const t of DEFAULT_SYSTEMD_SYSTEM_UNIT_DIRS)e.push(...(await scanSystemdDir({dir:t,scope:`system`})).map(projectService))}catch{return[]}return e}async function scanWindowsStartupEntries(e,t,n){let r;let i;try{r=path.dirname(resolveStartupEntryPath(e));i=new Set(resolveStartupEntryPaths(e).map(e=>path.win32.normalize(e).toLowerCase()))}catch{t.push({source:`startup`,message:`Windows Startup folder could not be located.`});return[]}let a;try{const e=await awaitWithinDeadline(async()=>{try{return await fs.readdir(r)}catch(e){if(!hasErrnoCode(e,`ENOENT`)||performance.now()>=n)throw e;const t=await findExistingAncestor(r);if(!t||t===path.resolve(r)||performance.now()>=n||!(await fs.stat(t)).isDirectory())throw e;return[]}},n,()=>performance.now());if(e===ABSOLUTE_DEADLINE_EXPIRED)throw new Error(`Startup inventory deadline expired.`);a=e}catch{t.push({source:r,message:`Windows Startup folder could not be inspected.`});return[]}const o=/* @__PURE__ */ new Set;if(a.some(e=>i.has(path.win32.normalize(path.join(r,e)).toLowerCase())))try{const t=await readScheduledTaskCommand(e,{requireLoaded:true,deadline:n});for(const e of t?.startupEntryPaths??[])o.add(path.win32.normalize(e).toLowerCase())}catch{t.push({source:resolveTaskName(e),message:`Selected Gateway service could not be inspected.`})}const s=[];for(const e of a.toSorted()){if(performance.now()>=n){t.push({source:r,message:`Startup inventory deadline expired.`});break}if(!/\.(?:cmd|vbs)$/i.test(e))continue;const a=e.slice(0,-4);const c=path.join(r,e);const l=path.win32.normalize(c).toLowerCase();let u=/(?:openclaw|clawdbot).*gateway/i.test(a);let d;try{const e=await readStartupEntryCommand(c,{deadline:n,onLauncherContent:e=>{const t=detectLauncherGatewayMarker(e);u||=Boolean(t);d=t??d}});const t=detectWindowsServiceExecutionMarker(e.programArguments,e.workingDirectory);const r=hasGatewayServiceMarker(e.environment);u=hasGatewaySubcommandArg(e.programArguments)||r;d=r?`openclaw`:t??void 0;const i=resolveWindowsServiceCommandProfile(e);const f=e.environment?.OPENCLAW_WINDOWS_TASK_NAME?.trim()||a;if(!d||!u&&d!==`clawdbot`)continue;s.push({platform:`win32`,label:f,detail:`startup: ${c}`,scope:`user`,marker:d,legacy:d!==`openclaw`,windowsStartupEntry:c,extra:d!==`openclaw`||!o.has(l),managedGateway:d===`openclaw`&&u,...i.kind===`resolved`?{windowsProfile:i.profile}:{}})}catch{const e=performance.now()>=n;if(e||u||i.has(l))t.push({source:c,message:`Startup launcher could not be inspected.`});if(e)break}}return s}async function scanGatewayServices(e,t,n=false){const r=[];const i=[];const a={services:r,errors:i};const o=/* @__PURE__ */ new Set;const push=e=>{const t=`${e.platform}:${e.label}:${e.detail}:${e.scope}`;if(o.has(t))return;o.add(t);r.push(e)};if(process.platform===`darwin`){try{const n=resolveDaemonHomeDir(e);const scan=async(t,n,r)=>{for(const a of await scanLaunchdDir({dir:t,scope:n,managedLabel:r,selectedName:resolveLaunchAgentLabel(e),errors:i}))push(a)};await scan(path.join(n,`Library`,`LaunchAgents`),`user`);if(t.deep){await scan(path.join(path.sep,`Library`,`LaunchAgents`),`system`);await scan(path.join(path.sep,`Library`,`LaunchDaemons`),`system`,resolveLaunchAgentLabel(e))}}catch(e){if(hasCommandProcessCleanupError(e))throw e;i.push({source:`launchd`,message:`Gateway service discovery could not finish.`})}return a}if(process.platform===`linux`){try{const r=resolveDaemonHomeDir(e);const a=path.join(r,`.config`,`systemd`,`user`);const o=n?resolveSystemdUnitLoadDirectories(e,r,process.geteuid?.()):void 0;if(o&&!o.complete)i.push({source:`systemd`,message:`Systemd unit load paths could not be verified.`});const s=[];for(const t of o?.userDirs??[a])s.push(...await scanSystemdDir({dir:t,scope:`user`,selectedName:resolveSystemdServiceName(e),errors:i}));for(const e of s)push(e);for(const e of LEGACY_GATEWAY_SYSTEMD_SERVICE_NAMES){const t=`${e}.service`;if(s.some(e=>e.label===t))continue;const n=path.join(a,`${e}.service.bak`);if(await fs.readFile(n).catch(e=>{if(!hasErrnoCode(e,`ENOENT`))i.push({source:n,message:`Service path could not be inspected.`});return null})!==null)push({platform:`linux`,label:t,detail:`unit backup: ${n}`,scope:`user`,marker:`clawdbot`,legacy:true,extra:true,managedGateway:false})}if(t.deep)for(const t of o?.systemDirs??DEFAULT_SYSTEMD_SYSTEM_UNIT_DIRS)for(const n of await scanSystemdDir({dir:t,scope:`system`,selectedName:resolveSystemdServiceName(e),errors:i}))push(n);if(n)for(const t of[`user`,`system`])try{for(const n of await listLoadedSystemdUnits(t,e)){const r=n.name.slice(0,-8);const a=detectSystemdGatewayExecutionMarker(n.commands);const o=isPotentialGatewayServiceName(r,`linux`,resolveSystemdServiceName(e));if(!a&&!o)continue;if(!path.posix.isAbsolute(n.fragmentPath)){i.push({source:n.name,message:`Loaded systemd Gateway definition could not be inspected.`});continue}if(!o&&areSystemdCommandsMaintenance(n.commands))continue;push({platform:`linux`,label:n.name,detail:`unit: ${n.fragmentPath}`,sourcePath:n.fragmentPath,scope:t,marker:a??`openclaw`,legacy:a===`clawdbot`,extra:true,managedGateway:a!==`clawdbot`})}}catch(e){if(hasCommandProcessCleanupError(e))throw e;i.push({source:t===`user`?`systemctl --user`:`systemctl --system`,message:`Loaded systemd services could not be inspected.`})}}catch(e){if(hasCommandProcessCleanupError(e))throw e;i.push({source:`systemd`,message:`Gateway service discovery could not finish.`})}return a}if(process.platform===`win32`){if(!t.deep)return a;const r=performance.now()+WINDOWS_POWERSHELL_COLD_SPAWN_TIMEOUT_MS;const expired=()=>r-performance.now()<1;const o={source:`schtasks`,message:`Scheduled Task inventory deadline expired; some services could not be inspected.`};const recordDeadline=()=>{if(!i.includes(o))i.push(o)};let s;try{s=listScheduledTasks(r-performance.now())}catch{i.push({source:`schtasks`,message:`Scheduled tasks could not be queried.`});s=[]}if(expired()){recordDeadline();return a}for(const t of s){if(expired()){recordDeadline();break}const a=t.taskPath?.trim();if(!a){if(n)i.push({source:`schtasks`,message:`Scheduled Task identity could not be inspected.`});continue}const o=t.actions?.map(e=>`${e.path} ${e.arguments}`.trim()).join(`; `)??``;const s=t.actions?.map(e=>[e.path,...splitArgsPreservingQuotes(e.arguments,{escapeMode:`backslash-quote-only`})])??[];const c=normalizeWindowsTaskIdentity(a)===normalizeWindowsTaskIdentity(resolveTaskName(e));const l=c||isOpenClawGatewayTaskName(a)||isLegacyLabel(a);const u=s.some(e=>e.some(e=>/\.(?:bat|cmd|vbs)$/i.test(e)&&detectLauncherGatewayMarker(e)));if(!t.actions?.length){if(l)i.push({source:a,message:`Scheduled Task action could not be inspected.`});continue}const d=s.map((e,n)=>detectWindowsServiceExecutionMarker(e,t.actions?.[n]?.workingDirectory));const f=s.some((e,t)=>d[t]===`openclaw`&&hasGatewaySubcommandArg(e));const p=s.some(e=>e.some(e=>/\.(?:bat|cmd|vbs)$/i.test(e)));if(n&&t.actions.length>1&&(f||p&&(l||u))){i.push({source:a,message:`Multiple Scheduled Task actions could not be inspected as one Gateway.`});continue}let m=f?`openclaw`:d.find(Boolean)??null;let h=f;let g=s.length===1?resolveWindowsServiceCommandProfile({programArguments:s[0]}):void 0;let _=u;if(u||p)try{const t=await readScheduledTaskCommand({...e,OPENCLAW_WINDOWS_TASK_NAME:a,OPENCLAW_PROFILE:void 0},{requireEffective:true,requireLoaded:true,profileScope:`registered`,deadline:r,onLauncherContent:e=>{_||=Boolean(detectLauncherGatewayMarker(e))}});if(!t&&(l||_))throw new Error(`Registered launcher disappeared during inspection.`);g=t?resolveWindowsServiceCommandProfile(t):void 0;const n=t?.environment?.OPENCLAW_SERVICE_MARKER;const i=t?.environment?.OPENCLAW_SERVICE_KIND;m=t?detectWindowsServiceExecutionMarker(t.programArguments,t.workingDirectory):null;h=Boolean(t&&hasGatewaySubcommandArg(t.programArguments));if(n===`openclaw`&&(i===`gateway`||i===`node`)){m=`openclaw`;h=i===`gateway`}}catch{if(expired()){recordDeadline();break}if(l||_)i.push({source:a,message:`Scheduled Task launcher could not be inspected.`});continue}if(!m)continue;if(n&&m===`openclaw`&&h&&g?.kind!==`resolved`){i.push({source:a,message:`Scheduled Task profile could not be inspected.`});continue}push({platform:`win32`,label:a,detail:o?`task: ${a}, run: ${o}`:a,scope:`system`,marker:m,legacy:m!==`openclaw`,extra:!(m===`openclaw`&&h&&!isLegacyLabel(a)&&(c||isOpenClawGatewayTaskName(a))),managedGateway:m===`openclaw`&&h,...g?.kind===`resolved`?{windowsProfile:g.profile}:{}})}if(expired()){recordDeadline();return a}for(const t of await scanWindowsStartupEntries(e,i,r))push(t);return a}return a}async function findExtraGatewayServices(e,t={}){const n=await scanGatewayServices(e,t);return{services:n.services.filter(e=>e.extra).map(projectService),errors:n.errors}}async function listManagedOpenClawGatewayServices(e){const t=await scanGatewayServices(e,{deep:true},true);return{services:t.services.filter(e=>e.managedGateway).map(({extra:e,managedGateway:t,...n})=>n),errors:t.errors}}export{renderGatewayServiceCleanupHints as i,findSystemGatewayServices as n,listManagedOpenClawGatewayServices as r,findExtraGatewayServices as t};