openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
14 lines • 27.7 kB
JavaScript
import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{d as sleepWithAbort,s as raceWithTimeout}from"./src-De06gkOi.mjs";import{o as registerSecretValueForRedaction}from"./secret-redaction-registry-DospXE4m.mjs";import{t as runCommandBuffered}from"./exec-c5tqm8tb.mjs";import{t as detectBinary}from"./detect-binary-CIeTTVvG.mjs";import{t as getProcessSupervisor}from"./supervisor-4YHLp8V6.mjs";import{i as tryListenOnPort}from"./ports-probe-B-fmalcq.mjs";import{r as probeRfbServer,t as classifyRfbSecurity}from"./rfb-probe-BmgZholI.mjs";import{n as HostDesktopCredentialsRequiredError}from"./host-source-errors-OIAs3Kv5.mjs";import{r as mintDesktopObserverToken}from"./observe-bridge-oJ9dsvHx.mjs";import path from"node:path";import crypto from"node:crypto";import fs from"node:fs/promises";import os from"node:os";import{Readable}from"node:stream";
//!src/gateway/desktop/host-guidance.ts
const HOST_DESKTOP_GUIDANCE={darwin:"Enable System Settings -> General -> Sharing -> Screen Sharing, or run `sudo launchctl enable system/com.apple.screensharing && sudo launchctl kickstart -k system/com.apple.screensharing`.",linux:"Install the managed desktop binaries with `apt install tigervnc-standalone-server tigervnc-tools xfce4-session dbus-daemon`, enable desktop.host.managed, or run a loopback-only VNC server yourself. For optional managed desktop audio, also install pulseaudio pulseaudio-utils; audio uses a private null sink, never the host microphone or physical system mix. gnome-remote-desktop uses unsupported VeNCrypt.",win32:"Install TightVNC with `SET_USEVNCAUTHENTICATION=1 SET_ALLOWLOOPBACK=1 ACCEPTHTTPCONNECTIONS=0` and listen on 127.0.0.1:5900. Locked or UAC sessions may render black."};function getHostDesktopGuidance(e){return HOST_DESKTOP_GUIDANCE[e]??HOST_DESKTOP_GUIDANCE.linux}
//!src/gateway/desktop/managed-linux-audio.ts
const SINK_NAME=`openclaw_desktop`;const STARTUP_TIMEOUT_MS=5e3;const MAX_BUFFER_BYTES=192e3;const AUDIO_GUIDANCE=`Install pulseaudio and pulseaudio-utils for managed desktop audio.`;function managedLinuxAudioEnv(e){const t=path.join(e,`pulse`);return{PULSE_SERVER:`unix:${path.join(t,`native`)}`,PULSE_SINK:SINK_NAME,PULSE_SOURCE:`${SINK_NAME}.monitor`,PULSE_RUNTIME_PATH:t,PULSE_STATE_PATH:path.join(t,`state`),PULSE_CLIENTCONFIG:path.join(t,`client.conf`)}}function createManagedLinuxAudio(e){const{supervisor:t}=e;const n={...e.env,...managedLinuxAudioEnv(e.tempDir)};const r={...n,LC_ALL:`C`,PULSE_CONFIG:path.join(e.tempDir,`pulse`,`daemon.conf`)};delete r.PULSE_SCRIPT;delete r.PULSE_DLPATH;delete r.NOTIFY_SOCKET;delete r.PULSE_COOKIE;delete r.PULSE_LOG;delete r.PULSE_LOG_TARGET;const i=`managed-desktop-audio:${crypto.randomUUID()}`;const a=t.acquireScopeCleanup(i,{processTree:`required-all`});const o=createDeferredCore();const s=createDeferredCore();const c=createDeferredCore();const l=/* @__PURE__ */ new Set;let u=true;let d;let f=``;const p={stop:()=>stop()};const assertActive=()=>{e.assertCurrent();if(!u)throw new Error(p.unavailableReason??`Managed desktop audio is stopped`)};const stop=()=>{if(d)return d;u=false;delete p.source;s.reject(/* @__PURE__ */ new Error(`Managed desktop audio stopped during startup`));const e=Promise.allSettled([...l].map(e=>e()));t.cancelScope(i,`manual-cancel`);d=Promise.resolve().then(async()=>{await g;const t=await e;await a();const n=t.find(e=>e.status===`rejected`);if(n)throw n.reason});return d};const unavailable=e=>{const t=e instanceof Error?e.message:String(e);p.unavailableReason??=`Managed desktop audio unavailable: ${t}. ${AUDIO_GUIDANCE}`;stop().catch(()=>{});c.resolve()};s.promise.catch(()=>{});const m=setTimeout(()=>{unavailable(/* @__PURE__ */ new Error(`private PulseAudio startup timed out`))},STARTUP_TIMEOUT_MS).unref();const h={async start(e,r){const assertCaptureCurrent=()=>{assertActive();e.throwIfAborted();r?.()};assertCaptureCurrent();const a=`${i}:capture:${crypto.randomUUID()}`;const o=t.acquireScopeCleanup(a,{processTree:`required-all`});const s=createDeferredCore();let c=true;let u;let d=``;let f;const p=new Readable({read(){},highWaterMark:MAX_BUFFER_BYTES});p.on(`error`,()=>{});const stopCapture=()=>{if(u)return u;c=false;clearTimeout(m);e.removeEventListener(`abort`,abort);s.reject(/* @__PURE__ */ new Error(`Desktop audio capture stopped`));p.destroy();f?.detachOutput?.();t.cancelScope(a,`manual-cancel`);u=Promise.resolve().then(async()=>{await h;await o();l.delete(stopCapture)});return u};const failCapture=e=>{if(!c)return;s.reject(e);p.destroy(e);stopCapture().catch(()=>{})};const abort=()=>failCapture(/* @__PURE__ */ new Error(`Desktop audio capture aborted`));const m=setTimeout(()=>failCapture(/* @__PURE__ */ new Error(`Desktop audio capture startup timed out`)),STARTUP_TIMEOUT_MS).unref();l.add(stopCapture);e.addEventListener(`abort`,abort,{once:true});p.once(`close`,()=>void stopCapture().catch(()=>{}));const h=Promise.resolve().then(async()=>{try{f=await t.spawn({scopeKey:a,mode:`child`,argv:[`parec`,`--server=${n.PULSE_SERVER}`,`--device=${SINK_NAME}.monitor`,`--raw`,`--format=s16le`,`--rate=48000`,`--channels=2`,`--channel-map=front-left,front-right`,`--latency-msec=40`],env:n,exactEnv:true,stdinMode:`pipe-closed`,captureOutput:false,assertCurrent:()=>{assertCaptureCurrent();if(!c)throw new Error(`Desktop audio capture stopped`)},onStderr:e=>{d=(d+e).slice(-4096)},onStdoutRaw:e=>{if(!c||e.length===0)return;if(p.readableLength+e.length>MAX_BUFFER_BYTES){failCapture(/* @__PURE__ */ new Error(`Desktop audio viewer is not consuming audio`));return}p.push(e);s.resolve()}});f.wait().then(()=>failCapture(new Error(d.trim()||`Desktop audio capture exited`)),e=>failCapture(e instanceof Error?e:new Error(String(e))))}catch(e){failCapture(e instanceof Error?e:new Error(String(e)))}});try{await s.promise;await h;assertCaptureCurrent();if(!c)throw new Error(`Desktop audio capture stopped during startup`);return{stream:p,stop:stopCapture}}catch(e){await stopCapture();throw e}finally{clearTimeout(m)}}};const g=Promise.resolve().then(async()=>{try{for(const e of[`pulseaudio`,`parec`]){if(!await detectBinary(e))throw new Error(`${e} is not installed`);assertActive()}const n=path.join(e.tempDir,`pulse`);await fs.mkdir(n,{recursive:true,mode:448});await fs.writeFile(path.join(n,`client.conf`),`autospawn = no
`,{mode:384});await fs.writeFile(path.join(n,`daemon.conf`),`local-server-type = user
`,{mode:384});const a=path.join(n,`default.pa`);await fs.writeFile(a,[`.fail`,`load-module module-null-sink sink_name=${SINK_NAME} format=s16le rate=48000 channels=2 channel_map=front-left,front-right`,`set-default-sink ${SINK_NAME}`,`set-default-source ${SINK_NAME}.monitor`,`load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0`,``].join(`
`),{mode:384});assertActive();(await t.spawn({scopeKey:i,mode:`child`,argv:[`pulseaudio`,`--daemonize=no`,`--fail=yes`,`--use-pid-file=no`,`--exit-idle-time=-1`,`--disable-shm=yes`,`--system=no`,`--realtime=no`,`--high-priority=no`,`--disallow-exit=yes`,`--disallow-module-loading=yes`,`--log-target=stderr`,`--log-level=info`,`-n`,`--file`,a],env:r,exactEnv:true,assertCurrent:assertActive,stdinMode:`pipe-closed`,captureOutput:false,onStderr:e=>{f=(f+e).slice(-4096);if(f.includes(`Daemon startup complete.`))s.resolve()}})).wait().then(()=>unavailable(new Error(f.trim()||`private PulseAudio exited`)),unavailable);await s.promise;assertActive();p.source=h;p.failed=c.promise}catch(e){unavailable(e)}finally{clearTimeout(m);o.resolve(p)}});return{ready:o.promise.then(async e=>{if(d)await d;return e}),stop}}
//!src/gateway/desktop/managed-linux.ts
const MANAGED_DISPLAY_FIRST=99;const MANAGED_DISPLAY_LAST=199;const RESTART_LIMIT=3;const RESTART_WINDOW_MS=3e5;const MANAGED_READINESS_TIMEOUT_MS=15e3;const MANAGED_READINESS_POLL_MS=100;const STDERR_TAIL_CHARS=4096;function buildTigerVncArgv(e){return[`Xtigervnc`,`:${e.display}`,`-geometry`,`1920x1080`,`-depth`,`24`,`-localhost`,`yes`,`-rfbport`,String(e.port),`-SecurityTypes`,`VncAuth`,`-PasswordFile`,e.passwordFile,`-AlwaysShared`,`-AcceptSetDesktopSize`,`-nolisten`,`tcp`,`-ac`]}function chooseDisplayNumber(e){const t=new Set(e.flatMap(e=>{const t=/^X(\d+)$/u.exec(e);return t?[Number.parseInt(t[1]??``,10)]:[]}));for(let e=MANAGED_DISPLAY_FIRST;e<=MANAGED_DISPLAY_LAST;e+=1)if(!t.has(e))return e;throw new Error(`managed Linux desktop could not find an unused X display between :${MANAGED_DISPLAY_FIRST} and :${MANAGED_DISPLAY_LAST}`)}function appendTail(e,t){return(e+t).slice(-4096)}function lastStderrLine(e){return e.split(/\r?\n/u).findLast(e=>e.trim())?.trim()}async function readDisplaySocketNames(e,t){let n;try{n=await fs.readdir(e)}catch(e){if(e.code!==`ENOENT`)throw e;n=[]}let r;try{r=await fs.readFile(t,`utf8`)}catch{return n}const i=`${e}/`;for(const e of r.split(`
`)){const t=e.trim().split(/\s+/u)[7]?.replace(/^@/u,``);if(t?.startsWith(i))n.push(t.slice(i.length))}return n}function binaryError(e,t){const n=t instanceof Error?t.message:String(t);return new Error(`managed Linux desktop could not start ${e}: ${n}. ${getHostDesktopGuidance(`linux`)}`,{cause:t})}function createManagedLinuxDesktop(e={}){const t=getProcessSupervisor();const n=e.runtime?.tempRoot??os.tmpdir();const r=e.runtime?.x11SocketDir??`/tmp/.X11-unix`;const i=e.runtime?.unixSocketTable??`/proc/self/net/unix`;const a=`host-desktop-managed-linux:${crypto.randomUUID()}`;let o={state:`not-started`};let s;let c;let l;let u;let d;let f;let p=false;let m=``;const h=/* @__PURE__ */ new Map;const claimRestart=e=>{const t=Date.now();const n=(h.get(e)??[]).filter(e=>t-e<RESTART_WINDOW_MS);h.set(e,n);if(n.length>=RESTART_LIMIT)return false;n.push(t);return true};const g=/* @__PURE__ */ new Set;const _=/* @__PURE__ */ new Set;const isPairCurrent=e=>!p&&c===e&&!e.stopPromise&&e.processes.every(({run:e})=>!e.activity.resultSettled);const assertStartupCurrent=()=>{if(p)throw new Error(`managed Linux desktop stopped during startup`)};const publicResult=e=>({attachment:{kind:`tcp`,host:`127.0.0.1`,port:e.port},auth:`vnc-password`,vncPassword:e.password,resolveAudio:()=>{if(s!==e)return;if(!c||!isPairCurrent(c))throw new Error(`managed Linux desktop is restarting; retry when it is ready`);return c.audio.source},get audioUnavailableReason(){return s===e&&c&&isPairCurrent(c)?c.audio.unavailableReason:void 0}});const removeResources=async()=>{const e=s;s=void 0;if(e)await fs.rm(e.tempDir,{recursive:true,force:true})};const markFailed=t=>{const n=s?{display:s.display,port:s.port}:o.state===`starting`||o.state===`failed`?{display:o.display,port:o.port}:{};o={state:`failed`,error:t.message,...n};e.onFailed?.(t.message)};const prepareResources=async()=>{const e=await fs.mkdtemp(path.join(n,`openclaw-managed-desktop-`));await fs.chmod(e,448);const t=path.join(e,`passwd`);try{const n=crypto.randomBytes(12).toString(`base64url`).slice(0,8);registerSecretValueForRedaction(n);const a=await runCommandBuffered([`tigervncpasswd`,`-f`],{input:Buffer.from(n),maxOutputBytes:{stdout:64,stderr:4096},timeoutMs:1e4});if(a.termination!==`exit`||a.code!==0||a.stdout.length===0)throw binaryError(`tigervncpasswd`,(a.error?.message??a.stderr.toString(`utf8`).trim())||`exit code ${a.code??`none`}`);await fs.writeFile(t,a.stdout,{mode:384,flag:`wx`});const o=await tryListenOnPort({port:0,host:`127.0.0.1`,exclusive:true});const s=chooseDisplayNumber(await readDisplaySocketNames(r,i));const c={...process.env,DISPLAY:`:${s}`,DBUS_SESSION_BUS_ADDRESS:`unix:path=${path.join(e,`bus`)}`,XDG_SESSION_TYPE:`x11`};delete c.WAYLAND_DISPLAY;delete c.SESSION_MANAGER;delete c.AT_SPI_BUS_ADDRESS;delete c.DBUS_SESSION_BUS_PID;return{tempDir:e,passwordFile:t,password:n,display:s,port:o,env:Object.freeze(c)}}catch(t){await fs.rm(e,{recursive:true,force:true});throw t}};const waitUntilReady=async e=>{const t=Date.now()+MANAGED_READINESS_TIMEOUT_MS;let n=`unreachable`;for(;;){if(p)break;const r=await probeRfbServer({host:`127.0.0.1`,port:e.port,timeoutMs:1e3,vncPassword:e.password});if(r.kind===`auth-rejected`)throw new Error(`managed Linux desktop rejected its VNC password on 127.0.0.1:${e.port}`);n=r.kind;if(r.kind===`rfb`&&r.securityTypes.includes(2))return;if(Date.now()>=t)break;await sleepWithAbort(MANAGED_READINESS_POLL_MS,void 0,{ref:false})}assertStartupCurrent();throw new Error(`managed Linux desktop did not become ready on 127.0.0.1:${e.port} within ${MANAGED_READINESS_TIMEOUT_MS}ms (last check: ${n})`)};const stopPair=e=>{if(e?.stopPromise)return e.stopPromise;const n=Promise.resolve().then(async()=>{const n=f;const r=n?.stop();r?.catch(()=>void 0);const i=(await Promise.allSettled([...e?.computerLeases??[]].map(async t=>{await t.onStop();e?.computerLeases.delete(t)}))).find(e=>e.status===`rejected`);await r;if(f===n)f=void 0;if(i)throw i.reason;t.cancelScope(a,`manual-cancel`);const o=d;await o?.();await Promise.allSettled(g);if(d===o)d=void 0;if(c===e)c=void 0});if(e){e.stopPromise=n;n.catch(()=>{e.stopPromise=void 0})}return n};const waitForRun=e=>{const t=e.wait().catch(e=>({exitCode:null,stderr:e instanceof Error?e.message:String(e)}));g.add(t);t.finally(()=>g.delete(t));return t};const spawnRun=async(e,n,r,i)=>{let o;try{o=await t.spawn({scopeKey:a,mode:`child`,argv:n,...r?{env:r}:{},assertCurrent:assertStartupCurrent,...i?{onStdout:i}:{},stdinMode:`pipe-closed`,maxCapturedOutputChars:STDERR_TAIL_CHARS,onStderr:e=>{m=appendTail(m,e)}})}catch(t){throw binaryError(e,t)}return{binary:e,run:o,exited:waitForRun(o)}};const describeExit=(e,t)=>{return lastStderrLine(t.stderr)??lastStderrLine(m)??`${e} exited with code ${t.exitCode??`none`}`};const createPairAudio=(e,n)=>createManagedLinuxAudio({supervisor:t,tempDir:e.tempDir,env:e.env,assertCurrent:n});const startPair=async e=>{o={state:`starting`,display:e.display,port:e.port};d=t.acquireScopeCleanup(a,{processTree:`required-all`});const n=await spawnRun(`Xtigervnc`,buildTigerVncArgv(e));try{await Promise.race([waitUntilReady(e),n.exited.then(e=>{throw new Error(describeExit(`Xtigervnc`,e))})]);assertStartupCurrent();let t=null;f=createPairAudio(e,()=>{if(p||t&&!isPairCurrent(t))throw new Error(`managed Linux desktop stopped`)});const r=await f.ready;const i=r.source?Object.freeze({...e.env,...managedLinuxAudioEnv(e.tempDir)}):e.env;const a=createDeferredCore();let s=``;await fs.rm(path.join(e.tempDir,`bus`),{force:true});const l=await spawnRun(`dbus-daemon`,[`dbus-daemon`,`--session`,`--nofork`,`--nopidfile`,`--print-address=1`,`--address=${e.env.DBUS_SESSION_BUS_ADDRESS}`],i,e=>{s=appendTail(s,e);if(s.includes(`
`))a.resolve()});await raceWithTimeout(Promise.race([a.promise,l.exited.then(e=>{throw new Error(describeExit(`dbus-daemon`,e))}),n.exited.then(e=>{throw new Error(describeExit(`Xtigervnc`,e))})]),MANAGED_READINESS_TIMEOUT_MS,()=>{throw new Error(`managed Linux desktop D-Bus session did not become ready`)});const u={processes:[n,l,await spawnRun(`startxfce4`,[`startxfce4`],i)],computerLeases:/* @__PURE__ */ new Set,audio:r,env:i};t=u;c=u;o={state:`running`,display:e.display,port:e.port};return u}catch(e){await stopPair(void 0);throw e}};const monitorPair=(e,t)=>{const n=Promise.race(e.processes.map(({binary:e,exited:t})=>t.then(t=>describeExit(e,t))));const stillOwned=()=>c===e&&!p;const r=(async()=>{for(;;){const r=e.audio;const i=await Promise.race([n,...r.failed?[r.failed.then(()=>r.unavailableReason??`private PulseAudio exited`)]:[]]);if(!stillOwned())return;if(isPairCurrent(e)&&r.failed){const disableAudio=t=>{const n=f??r;e.audio={stop:()=>n.stop(),unavailableReason:`Managed desktop audio unavailable: ${t}. Healthy desktop applications remain running. Check pulseaudio and pulseaudio-utils, then restart the managed desktop if audio is needed.`}};try{await r.stop();if(!stillOwned())return;if(isPairCurrent(e)){if(!claimRestart(`audio`)){disableAudio(`${RESTART_LIMIT} restarts within 5 minutes: ${i}`);continue}f=createPairAudio(t,()=>{if(!stillOwned()||!isPairCurrent(e))throw new Error(`managed Linux desktop stopped`)});const n=await f.ready;if(!stillOwned())return;e.audio=n;if(isPairCurrent(e)){if(!n.source){await n.stop();disableAudio(n.unavailableReason??`private PulseAudio recovery failed`)}continue}}}catch(t){if(!stillOwned())return;if(isPairCurrent(e)){disableAudio(t instanceof Error?t.message:String(t));continue}}}if(!claimRestart(`desktop`)){await stopPair(e);if(!p)markFailed(/* @__PURE__ */ new Error(`managed Linux desktop failed after ${RESTART_LIMIT} restarts within 5 minutes: ${i}`));return}o={state:`starting`,display:t.display,port:t.port};await stopPair(e);if(p)return;const a=await startPair(t);monitorPair(a,t);return}})().catch(async t=>{try{await stopPair(e)}finally{if(!p)markFailed(t instanceof Error?t:new Error(String(t)))}});_.add(r);r.finally(()=>_.delete(r)).catch(()=>void 0)};const start=async()=>{try{s=await prepareResources();assertStartupCurrent();const e=await startPair(s);monitorPair(e,s);return s}catch(e){if(!p)markFailed(e instanceof Error?e:new Error(String(e)));throw e}};return{async acquire(){if(p||u)throw new Error(`managed Linux desktop is stopping`);if(o.state===`failed`)throw new Error(o.error);if(o.state===`running`&&s&&c&&isPairCurrent(c))return publicResult(s);if(_.size>0)throw new Error(`managed Linux desktop is restarting; retry when it is ready`);if(!l){p=false;h.clear();m=``;l=start().finally(()=>{l=void 0})}return publicResult(await l)},async acquireComputer(e){const t=c;if(o.state!==`running`||!s||!t||!isPairCurrent(t))throw new Error(`managed Linux desktop is unavailable for computer control`);const n={onStop:()=>e.onStop()};t.computerLeases.add(n);return{env:t.env,isCurrent:()=>isPairCurrent(t)&&t.computerLeases.has(n),release:()=>{t.computerLeases.delete(n)}}},stop(){if(u)return u;p=true;const e=o.state===`failed`?o:void 0;const t=Promise.resolve().then(async()=>{await stopPair(c);await l?.catch(()=>void 0);await Promise.all(_);await stopPair(c);await removeResources();l=void 0;h.clear();o=e??{state:`not-started`};p=false});u=t;t.finally(()=>{u=void 0}).catch(()=>void 0);return t},status(){return{...o}}}}
//!src/gateway/desktop/host-source.ts
const DEFAULT_HOST_DESKTOP_PORT=5900;const HOST_DESKTOP_PROBE_TIMEOUT_MS=1500;function nonRfbError(e){return`desktop.host.port ${e} is occupied by a non-VNC service; configure desktop.host.port for the loopback VNC server, then retry`}function unavailableError(e,t){return`gateway host desktop is unavailable at 127.0.0.1:${e}. ${getHostDesktopGuidance(t)}`}function managedPlatformError(e){return`desktop.host.managed is available only on Linux; disable it on ${e} or configure desktop.host.port for an existing loopback VNC server`}function managedInspection(e){const t={enabled:true,state:`managed`,managedState:e.state,port:DEFAULT_HOST_DESKTOP_PORT};if(e.state!==`not-started`&&e.state!==`unknown`){t.port=e.port??DEFAULT_HOST_DESKTOP_PORT;if(e.display!==void 0)t.display=e.display}if(e.state===`running`)return{status:{...t,security:`VncAuth`},detail:`managed (running, display :${e.display}, port ${e.port}, security: VncAuth)`};if(e.state===`failed`)return{status:{...t,error:e.error},detail:`managed (failed: ${e.error})`,unavailableReason:`unsupported`};return{status:t,detail:e.state===`unknown`?`managed (configured; runtime state is available from the running Gateway status)`:e.state===`starting`?`managed (starting)`:`managed (not started)`}}async function inspectHostDesktop(e,t){if(e.config?.enabled!==true)return{status:{enabled:false,state:`disabled`,port:e.config?.port??DEFAULT_HOST_DESKTOP_PORT},detail:`disabled; enable the Desktop lab with desktop.host.enabled=true`};return inspectConfiguredHostDesktop(e,true,t)}async function inspectHostDesktopSetup(e){const t=await inspectConfiguredHostDesktop(e,false);if(t.status.state===`attached`)return{state:`ready`};if(t.status.state===`managed`)return{state:`managed`};return{state:t.unavailableReason===`not-listening`?`needs-server`:`unsupported`,detail:t.detail}}async function readConfiguredVncPassword(e){if(!e)return{};let t;try{t=await fs.readFile(e,`utf8`)}catch(t){return{error:`could not read desktop.host.passwordFile ${e}: ${t instanceof Error?t.message:String(t)}; fix the absolute path or remove desktop.host.passwordFile so the UI can prompt`}}const n=t.replace(/[\r\n]+$/u,``);if(!n)return{error:`desktop.host.passwordFile is empty; write the VNC password or remove desktop.host.passwordFile so the UI can prompt`};registerSecretValueForRedaction(n);return{password:n}}async function inspectConfiguredHostDesktop(e,t,n){const r=e.config?.port??DEFAULT_HOST_DESKTOP_PORT;const i=e.platform??process.platform;n?.assertCurrent?.();const a=t?await readConfiguredVncPassword(e.config?.passwordFile):{};n?.assertCurrent?.();const o=await probeRfbServer({host:`127.0.0.1`,port:r,timeoutMs:HOST_DESKTOP_PROBE_TIMEOUT_MS,signal:n?.signal,assertCurrent:n?.assertCurrent,...a.password?{vncPassword:a.password}:{}});const unavailable=(e,t,n)=>({status:{enabled:true,state:`unavailable`,port:r,...n!==void 0?{security:n}:{}},detail:e,unavailableReason:t});if(o.kind===`unreachable`||o.kind===`timeout`){if(e.config?.port===void 0&&e.config?.managed===true){if(i!==`linux`)return unavailable(managedPlatformError(i),`unsupported`);return managedInspection(e.managedDesktop?.status()??{state:`unknown`})}return unavailable(unavailableError(r,i),`not-listening`)}if(o.kind===`not-rfb`)return unavailable(nonRfbError(r),`not-rfb`);if(o.kind===`auth-rejected`)return unavailable(`VNC authentication failed; check desktop.host.passwordFile and retry`,`unsupported`,`VncAuth`);const s=classifyRfbSecurity(o.securityTypes);const c=s===`unsupported`?o.securityTypes.includes(19)?`VeNCrypt`:`unsupported`:{"vnc-password":`VncAuth`,"ard-account":`ARD`,none:`None`}[s];if(s===`vnc-password`||s===`ard-account`)return{status:{enabled:true,state:`attached`,port:r,security:c},detail:`attached (127.0.0.1:${r}, security: ${c})`};return unavailable(s===`none`?`unavailable: unauthenticated VNC server at 127.0.0.1:${r}; require a password-protected VncAuth server, then retry`:`unavailable: ${c} security is not supported; configure a VncAuth server and desktop.host.passwordFile, then retry`,`unsupported`,c)}function createHostDesktopSource(e){const t=e.config.port??DEFAULT_HOST_DESKTOP_PORT;const n=e.platform??process.platform;const r=e.managedDesktop??(e.config.managed===true&&n===`linux`?createManagedLinuxDesktop():void 0);let i=false;const acquireAttached=async(e,n)=>{const r=classifyRfbSecurity(e.securityTypes);if(r===`none`)throw new Error(`refusing unauthenticated VNC server on 127.0.0.1:${t}; require a password-protected VncAuth server, then retry`);if(r===`unsupported`){const t=e.securityTypes.includes(19)?`VeNCrypt`:`the offered VNC security`;throw new Error(`${t} is not supported; configure a VncAuth server and desktop.host.passwordFile, then retry`)}return{attachment:{kind:`tcp`,host:`127.0.0.1`,port:t},auth:r,...n?{vncPassword:n}:{}}};const acquire=async a=>{a?.();i=false;const o=await readConfiguredVncPassword(e.config.passwordFile);a?.();const s=await probeRfbServer({host:`127.0.0.1`,port:t,timeoutMs:HOST_DESKTOP_PROBE_TIMEOUT_MS,assertCurrent:a,...o.password?{vncPassword:o.password}:{}});a?.();if(s.kind===`unreachable`||s.kind===`timeout`){if(e.config.port===void 0&&e.config.managed===true){if(n!==`linux`)throw new Error(managedPlatformError(n));if(!r)throw new Error(`managed Linux desktop lifecycle is unavailable; retry`);const e=await r.acquire();a?.();i=true;return e}throw new Error(unavailableError(t,n))}if(s.kind===`not-rfb`)throw new Error(nonRfbError(t));if(o.error)throw new Error(o.error);if(s.kind===`auth-rejected`)throw new Error(`VNC authentication failed; check desktop.host.passwordFile and retry`);return await acquireAttached(s,o.password)};return{acquire,acquireComputer:async e=>{if(!i||!r)throw new Error(`COMPUTER_HOST_UNAVAILABLE: the selected host desktop is an external VNC server; its local computer session is unknown`);return await r.acquireComputer(e)},teardown:r?()=>{i=false;return r.stop()}:void 0,inspect:t=>inspectHostDesktop({config:e.config,platform:n,managedDesktop:r},t)}}function createHostDesktopService(e){let t;let n=0;const isCurrent=n=>{const r=e.getConfig();return t===n&&!n.controller.signal.aborted&&r?.enabled===true&&r.managed===n.config.managed&&r.port===n.config.port&&r.passwordFile===n.config.passwordFile};const assertCurrent=e=>{if(!isCurrent(e))throw new Error(`gateway host desktop configuration changed; retry`)};const reconcileRuntimePolicy=async()=>{const n=t;if(!n||isCurrent(n))return;n.controller.abort();if(!n.stopping)n.stopping=e.registry.stop(`host`,n.ownerEpoch).then(()=>{if(t===n)t=void 0},e=>{n.stopping=void 0;throw e});await n.stopping};const resolveRuntime=async()=>{await reconcileRuntimePolicy();const r=e.getConfig();if(r?.enabled!==true)return;if(!t){const i=n++;const a=r.managed===true&&process.platform===`linux`?createManagedLinuxDesktop({onFailed:()=>{e.registry.stop(`host`,i)}}):void 0;const o={...r};t={config:o,ownerEpoch:i,controller:new AbortController,source:createHostDesktopSource({config:o,...a?{managedDesktop:a}:{}})}}return t};const acquire=async()=>{const t=await resolveRuntime();if(!t)throw new Error(`gateway host desktop is disabled; enable the Desktop lab (config: desktop.host.enabled=true)`);assertCurrent(t);const n=await e.registry.acquire({sourceKey:`host`,ownerEpoch:t.ownerEpoch,start:()=>t.source.acquire(()=>assertCurrent(t)),...t.source.teardown?{teardown:t.source.teardown}:{}});assertCurrent(t);return{acquired:n,runtime:t}};return{async observe(e){const{acquired:t,runtime:n}=await acquire();assertCurrent(n);const r=t.auth;const i=t.resolveAudio?.();if(!r)throw new Error(`gateway host desktop authentication state is unavailable; retry observe`);let a;if(r===`ard-account`){const t=e.credentials?.username?.trim()??``;const n=e.credentials?.password??``;if(!t||!n)throw new HostDesktopCredentialsRequiredError;registerSecretValueForRedaction(n);a={auth:`ard-account`,credentials:{username:t,password:n}}}if(i&&r===`vnc-password`&&t.vncPassword)a={auth:r,credentials:{password:t.vncPassword}};const o=mintDesktopObserverToken({sourceKey:`host`,ownerEpoch:n.ownerEpoch,control:e.control,requester:{...e.requester,signal:e.requester?.signal?AbortSignal.any([n.controller.signal,e.requester.signal]):n.controller.signal,isCurrent:()=>isCurrent(n)&&e.requester?.isCurrent()!==false},attachment:t.attachment,...i?{audio:i}:{},...a?{preauth:a}:{}});return{transport:`rfb`,wsPath:`/desktop/observe?token=${o.token}`,expiresAtMs:o.expiresAtMs,control:e.control,auth:r,...o.audio?{audio:o.audio,preauthenticated:true}:{},...!i&&t.audioUnavailableReason?{audioUnavailableReason:`setup-unavailable`}:{},...r===`vnc-password`&&t.vncPassword&&!a?{vncPassword:t.vncPassword}:{}}},async acquireComputer(t){const{runtime:n}=await acquire();assertCurrent(n);const r=e.registry.retainActivity(`host`,n.ownerEpoch);if(!r)throw new Error(`COMPUTER_HOST_UNAVAILABLE: the host desktop stopped during acquisition`);try{const e=await n.source.acquireComputer(t);if(!isCurrent(n)||!r.isCurrent()||!e.isCurrent()){e.release();throw new Error(`COMPUTER_HOST_UNAVAILABLE: the host desktop stopped during acquisition`)}return{env:e.env,isCurrent:()=>isCurrent(n)&&r.isCurrent()&&e.isCurrent(),release(){e.release();r.release()}}}catch(e){r.release();throw e}},async status(){const t=await resolveRuntime();if(!t)return(await inspectHostDesktop({config:e.getConfig()})).status;assertCurrent(t);return(await t.source.inspect({assertCurrent:()=>assertCurrent(t),signal:t.controller.signal})).status},reconcileRuntimePolicy}}export{inspectHostDesktopSetup as i,createHostDesktopSource as n,inspectHostDesktop as r,createHostDesktopService as t};