UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 13.8 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{t as killProcessTree}from"./kill-tree-CIjHhVfN.mjs";import{n as computeBackoff}from"./src-De06gkOi.mjs";import"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{a as resolveExecutable}from"./executable-path-BYWCW0PG.mjs";import{n as canAccessSync}from"./path-existence-BR9MXlgL.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as runCommandWithTimeout,s as releaseChildProcessOutputAfterExit}from"./exec-runner-BiCq-T1F.mjs";import"./exec-c5tqm8tb.mjs";import"./backoff-DRW5tqzp.mjs";import{i as formatCommandResult,r as formatCommandOutput}from"./command-error-B187dN8z.mjs";import{n as hasBinary}from"./config-eval-DjbEbFd6.mjs";import"./config-DyCaRdSv.mjs";import{S as resolveGogServeInvocation,c as GMAIL_INSECURE_TOKEN_ARGS_WARNING,f as buildGogWatchServeArgs,l as GMAIL_WATCH_HOOK_TOKEN_ENV,m as buildGogWatchStartArgs,p as buildGogWatchServeLogArgs,u as GMAIL_WATCH_PUSH_TOKEN_ENV,v as normalizeServePath,x as resolveGmailHookRuntimeConfig}from"./gmail-DTnq9xhd.mjs";import{t as inspectGog}from"./gmail-gog-BIDrAcJ7.mjs";import fs from"node:fs";import process$1 from"node:process";import path from"node:path";import{spawn}from"node:child_process"; //!src/hooks/gmail-setup-utils.ts let cachedPythonPath;let gcloudBin;function formatJsonParseFailure(e,t,n){return`${e} returned invalid JSON: ${formatCommandOutput(formatErrorMessage(n))}\n${formatCommandResult(e,t)}`}function findExecutablesOnPath(e){const t=(process.env.PATH??``).split(path.delimiter).filter(Boolean);const n=/* @__PURE__ */ new Set;const r=[];for(const i of t)for(const t of e){const e=path.join(i,t);if(n.has(e))continue;if(canAccessSync(e,fs.constants.X_OK)){r.push(e);n.add(e)}}return r}function ensureGcloudOnPath(){if(hasBinary(`gcloud`))return true;for(const e of[`/opt/homebrew/share/google-cloud-sdk/bin/gcloud`,`/usr/local/share/google-cloud-sdk/bin/gcloud`,`/opt/homebrew/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud`,`/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud`])if(canAccessSync(e,fs.constants.X_OK)){const t=path.dirname(e);const n=(process.env.PATH??``).split(path.delimiter).filter(Boolean);if(!n.includes(t))process.env.PATH=[...n,t].join(path.delimiter);return true}return false}const MIN_GCLOUD_PYTHON=[3,10];const MAX_GCLOUD_PYTHON=[3,14];function isSupportedGcloudPythonVersion(e,t){if(e!==MIN_GCLOUD_PYTHON[0])return false;return t>=MIN_GCLOUD_PYTHON[1]&&t<=MAX_GCLOUD_PYTHON[1]}async function resolvePythonExecutablePath(){if(cachedPythonPath!==void 0)return cachedPythonPath??void 0;const e=findExecutablesOnPath([`python3`,`python`]);for(const t of e){const e=await runCommandWithTimeout([t,`-c`,`import os, sys; print(os.path.realpath(sys.executable)); print('%d.%d' % sys.version_info[:2])`],{timeoutMs:2e3});if(e.code!==0)continue;const n=e.stdout.trim().split(/\r?\n/);const r=n[0]?.trim();if(!r)continue;const i=n[1]?.trim().match(/^(\d+)\.(\d+)/);if(!i)continue;if(!isSupportedGcloudPythonVersion(Number(i[1]),Number(i[2])))continue;if(canAccessSync(r,fs.constants.X_OK)){cachedPythonPath=r;return r}}cachedPythonPath=null}async function gcloudEnv(){return{CLOUDSDK_PYTHON:await resolvePythonExecutablePath(),CLOUDSDK_PYTHON_ARGS:void 0}}async function runGcloudCommand(e,t){return await runCommandWithTimeout([gcloudBin??=resolveExecutable(`gcloud`),...e],{timeoutMs:t,env:await gcloudEnv()})}async function ensureDependency(e,t){if(e===`gcloud`&&ensureGcloudOnPath())return;if(hasBinary(e))return;if(process.platform!==`darwin`)throw new Error(`${e} not installed; install it and retry`);if(!hasBinary(`brew`))throw new Error(`Homebrew not installed (install brew and retry)`);const n=e===`gcloud`?await gcloudEnv():void 0;const r=await runCommandWithTimeout([`brew`,`install`,...t],{timeoutMs:6e5,env:n});if(r.code!==0)throw new Error(formatCommandResult(`brew install for ${e}`,r));if(!hasBinary(e))throw new Error(`${e} still not available after brew install`)}async function ensureGcloudAuth(){const e=await runGcloudCommand([`auth`,`list`,`--filter`,`status:ACTIVE`,`--format`,`value(account)`],3e4);if(e.code===0&&e.stdout.trim())return;const t=await runGcloudCommand([`auth`,`login`],6e5);if(t.code!==0)throw new Error(formatCommandResult(`gcloud auth login`,t))}async function runGcloud(e){const t=await runGcloudCommand(e,12e4);if(t.code!==0)throw new Error(formatCommandResult(`gcloud command`,t));return t}async function ensureTopic(e,t){if((await runGcloudCommand([`pubsub`,`topics`,`describe`,t,`--project`,e],3e4)).code===0)return;await runGcloud([`pubsub`,`topics`,`create`,t,`--project`,e])}async function ensureSubscription(e,t,n,r){const i=await runGcloudCommand([`pubsub`,`subscriptions`,`describe`,t,`--project`,e],3e4);await runGcloud([`pubsub`,`subscriptions`,i.code===0?`update`:`create`,t,`--project`,e,...i.code===0?[]:[`--topic`,n],`--push-endpoint`,r])}async function ensureTailscaleEndpoint(e){if(e.mode===`off`)return``;const t=resolveExecutable(`tailscale`);const n=[`status`,`--json`];const r=`tailscale status --json`;const i=await runCommandWithTimeout([t,...n],{timeoutMs:3e4,signal:e.signal});if(i.code!==0)throw new Error(formatCommandResult(r,i));let a;try{a=JSON.parse(i.stdout)}catch(e){throw new Error(formatJsonParseFailure(r,i,e),{cause:e})}const o=a.Self?.DNSName?.replace(/\.$/,``);if(!o)throw new Error(`tailscale DNS name missing; run tailscale up`);const s=typeof e.target===`string`&&e.target.trim().length>0?e.target.trim():e.port?String(e.port):``;if(!s)throw new Error(`tailscale target missing; set a port or target URL`);const c=normalizeServePath(e.path);const l=[e.mode,`--bg`,`--set-path`,c,`--yes`,s];const u=await runCommandWithTimeout([t,...l],{timeoutMs:3e4,signal:e.signal});if(u.code!==0)throw new Error(formatCommandResult(`tailscale ${e.mode}`,u));const d=`https://${o}${c}`;return e.token?`${d}?token=${e.token}`:d}async function resolveProjectIdFromGogCredentials(){const e=gogCredentialsPaths();for(const t of e)try{const e=fs.readFileSync(t,`utf-8`);const n=extractGogClientId(JSON.parse(e))?.match(/^(\d+)-/)?.[1]??null;if(!n)continue;const r=await runGcloudCommand([`projects`,`list`,`--filter`,`projectNumber=${n}`,`--format`,`value(projectId)`],3e4);if(r.code!==0)continue;const i=r.stdout.trim().split(/\s+/)[0];if(i)return i}catch{}return null}function gogCredentialsPaths(){const e=[];const t=process.env.XDG_CONFIG_HOME;if(t)e.push(path.join(t,`gogcli`,`credentials.json`));e.push(resolveUserPath(`~/.config/gogcli/credentials.json`));if(process.platform===`darwin`)e.push(resolveUserPath(`~/Library/Application Support/gogcli/credentials.json`));return e}function extractGogClientId(e){const t=e.installed;const n=e.web;const r=t?.client_id||n?.client_id||e.client_id||``;return typeof r===`string`?r:null} //!src/hooks/gmail-watcher.ts const log=createSubsystemLogger(`gmail-watcher`);const GMAIL_BIND_RETRY_LIMIT=3;const GMAIL_BIND_BACKOFF={initialMs:5e3,maxMs:2e4,factor:2,jitter:0};let watcherProcess=null;let renewalScope;let shuttingDown=false;let currentConfig=null;let respawnTimeout=null;async function startGmailWatch(e,t,n={}){const r=resolveGogServeInvocation(buildGogWatchStartArgs(e),t);try{const t=await runCommandWithTimeout([r.command,...r.args],{timeoutMs:12e4,signal:n.signal,windowsVerbatimArguments:r.windowsVerbatimArguments});if(t.code!==0){log.error(formatCommandResult(`gog gmail watch start`,t));return false}log.info(`watch started for ${e.account}`);return true}catch(e){log.error(`watch start error: ${String(e)}`);return false}}function spawnGogServe(e,t,n,r=0){const i=buildGogWatchServeArgs(e,n);log.info(`starting gog ${buildGogWatchServeLogArgs(e,n).join(` `)}`);let a=false;let o=false;let s=``;const c=resolveGogServeInvocation(i,t);const l=spawn(c.command,c.args,{stdio:[`ignore`,`pipe`,`pipe`],detached:process$1.platform!==`win32`,windowsHide:c.windowsHide,windowsVerbatimArguments:c.windowsVerbatimArguments,...n===`env`?{env:{...process$1.env,[GMAIL_WATCH_PUSH_TOKEN_ENV]:e.pushToken,[GMAIL_WATCH_HOOK_TOKEN_ENV]:e.hookToken}}:{}});l.stdout?.on(`error`,e=>{log.error(`gog stdout error: ${String(e)}`)});l.stdout?.on(`data`,e=>{const t=e.toString().trim();if(t)log.info(`[gog] ${t}`)});l.stderr?.on(`error`,e=>{log.error(`gog stderr error: ${String(e)}`)});l.stderr?.on(`data`,e=>{const t=e.toString();const n=s+t;if(!a&&/address already in use|EADDRINUSE/i.test(n))a=true;s=n.slice(-512);const r=t.trim();if(!r)return;log.warn(`[gog] ${r}`)});l.on(`error`,e=>{if(l.pid===void 0)o=true;log.error(`gog process error: ${String(e)}`)});const u=releaseChildProcessOutputAfterExit(l);l.once(`exit`,()=>{if(!shuttingDown&&watcherProcess===l&&process$1.platform!==`win32`&&l.pid)killProcessTree(l.pid,{force:true,detached:true})});l.once(`close`,(i,s)=>{u();if(shuttingDown||watcherProcess!==l)return;if(o){watcherProcess=null;return}if(a&&r>=GMAIL_BIND_RETRY_LIMIT){log.error(`gog serve failed to bind after ${GMAIL_BIND_RETRY_LIMIT} retries (address already in use); stopping restarts. Stop the other process and restart the Gmail watcher, or set OPENCLAW_SKIP_GMAIL_WATCHER=1 if it is managed separately.`);watcherProcess=null;return}const c=a?r+1:0;const d=a?computeBackoff(GMAIL_BIND_BACKOFF,c):5e3;log.warn(a?`gog serve failed to bind (address already in use); retry ${c}/${GMAIL_BIND_RETRY_LIMIT} in ${d/1e3}s`:`gog exited (code=${i}, signal=${s}); restarting in 5s`);watcherProcess=null;respawnTimeout=setTimeout(()=>{respawnTimeout=null;if(shuttingDown||currentConfig!==e)return;watcherProcess=spawnGogServe(e,t,n,c)},d)});return l}function settleProcess(e){if(process$1.platform===`win32`&&(e.exitCode!=null||e.signalCode!=null))return Promise.resolve();return new Promise(t=>{let n=false;let r=false;let i=false;let a;const settle=()=>{if(n)return;n=true;if(a)clearTimeout(a);if(o)clearTimeout(o);e.removeListener(`exit`,settleAfterEscalation);e.removeListener(`close`,settleAfterEscalation);e.removeListener(`error`,settleAfterEscalation);t()};const settleAfterEscalation=()=>{r=true;if(i)settle()};const o=setTimeout(()=>{if(!n){log.warn(`gog process did not exit after SIGKILL; giving up`);settle()}},8e3);e.on(`exit`,settleAfterEscalation);e.on(`close`,settleAfterEscalation);e.on(`error`,settleAfterEscalation);if(typeof e.pid===`number`){killProcessTree(e.pid,{graceMs:3e3,detached:process$1.platform!==`win32`});a=setTimeout(()=>{i=true;if(r)settle()},3025)}else{try{e.kill(`SIGTERM`)}catch{}i=true}})}async function stopWatcherResources(e){shuttingDown=true;if(respawnTimeout){clearTimeout(respawnTimeout);respawnTimeout=null}const t=renewalScope;await t?.stop();if(renewalScope===t)renewalScope=void 0;if(watcherProcess){e?.();const t=watcherProcess;watcherProcess=null;await settleProcess(t)}}function cancelledGmailWatcherStart(e){if(currentConfig===e)currentConfig=null;return{started:false,reason:`startup cancelled`}}async function startGmailWatcher(e,t){if(!e.hooks?.enabled)return{started:false,reason:`hooks not enabled`};if(!e.hooks?.gmail?.account)return{started:false,reason:`no gmail account configured`};if(!hasBinary(`gog`))return{started:false,reason:`gog binary not found`};const n=resolveGmailHookRuntimeConfig(e,{});if(!n.ok)return{started:false,reason:n.error};return startGmailWatcherService(n.value,t)}async function startGmailWatcherService(e,t){if(t.signal?.aborted)return cancelledGmailWatcherStart(e);currentConfig=e;if(watcherProcess||renewalScope||respawnTimeout){await stopWatcherResources();shuttingDown=false}let n;try{n=await inspectGog({signal:t.signal});if(currentConfig!==e||t.signal?.aborted)return cancelledGmailWatcherStart(e);if(n.support!==`supported`&&t.prepareGog)n=await t.prepareGog(n,t.signal)}catch(n){if(t.signal?.aborted||currentConfig!==e)return cancelledGmailWatcherStart(e);throw n}if(currentConfig!==e||t.signal?.aborted)return cancelledGmailWatcherStart(e);const r=n.executable;if(!r){currentConfig=null;return{started:false,reason:`gog binary not found; install Gog and restart the watcher`}}const i=n.support===`supported`?`env`:`legacy-argv`;if(e.tailscale.mode!==`off`)try{await ensureTailscaleEndpoint({mode:e.tailscale.mode,path:e.tailscale.path,port:e.serve.port,signal:t.signal,target:e.tailscale.target});log.info(`tailscale ${e.tailscale.mode} configured for port ${e.serve.port}`);if(t.signal?.aborted||currentConfig!==e)return cancelledGmailWatcherStart(e)}catch(n){if(t.signal?.aborted)return cancelledGmailWatcherStart(e);log.error(`tailscale setup failed: ${String(n)}`);return{started:false,reason:`tailscale setup failed: ${String(n)}`}}const a=await startGmailWatch(e,r,{signal:t.signal});if(t.signal?.aborted||currentConfig!==e)return cancelledGmailWatcherStart(e);if(!a)log.warn(`gmail watch start failed, but continuing with serve`);shuttingDown=false;if(i===`legacy-argv`)log.warn(`${n.support===`indeterminate`?`Could not verify Gog token environment support. `:`Selected Gog lacks token environment support. `}${GMAIL_INSECURE_TOKEN_ARGS_WARNING}`);watcherProcess=spawnGogServe(e,r,i);const o=e.renewEveryMinutes*6e4;const s=t.scheduler.scope();renewalScope=s;s.schedule({id:`gmail-watch-renewal`,delayMs:o,everyMs:o,run:()=>startGmailWatch(e,r,{signal:s.signal})});log.info(`gmail watcher started for ${e.account} (renew every ${e.renewEveryMinutes}m)`);return{started:true}}async function stopGmailWatcher(){await stopWatcherResources(()=>log.info(`stopping gmail watcher`));currentConfig=null;log.info(`gmail watcher stopped`)}export{ensureGcloudAuth as a,ensureTopic as c,ensureDependency as i,resolveProjectIdFromGogCredentials as l,startGmailWatcherService as n,ensureSubscription as o,stopGmailWatcher as r,ensureTailscaleEndpoint as s,startGmailWatcher as t,runGcloud as u};