openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
21 lines • 13.7 kB
JavaScript
import{c as toErrorObject}from"./error-coercion-B-1Loz4b.mjs";import{a as isRecord}from"./record-coerce-DwDZngEy.mjs";import{a as normalizeOptionalString,n as normalizeLowercaseStringOrEmpty}from"./string-coerce-BBqv4GXj.mjs";import{d as floorPositiveFiniteNumber}from"./number-coercion-DIhBGkET.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import"./prototype-keys-DI_O-fr9.mjs";import{t as formatErrorMessage}from"./errors-BKYtsKt6.mjs";import{t as logDebug}from"./logger-DmLqrh-9.mjs";import{createRequire}from"node:module";import{readFileSync}from"node:fs";import fsPromises,{readFile as readFile$1}from"node:fs/promises";import{release,version}from"node:os";import{EventEmitter}from"node:events";import*as net$1 from"node:net";import net from"node:net";
//!src/infra/net/proxy-env.ts
function readProxyEnvValue(e,t){const n=t[e];return normalizeOptionalString(typeof n===`string`?n:t[e.toUpperCase()])}function resolveEnvHttpProxyUrl(e,t=process.env){const n=readProxyEnvValue(`http_proxy`,t);const r=readProxyEnvValue(`https_proxy`,t);return e===`https`?r??n:n}function hasEnvHttpProxyConfigured(e=`https`,t=process.env){return resolveEnvHttpProxyUrl(e,t)!==void 0}function resolveEnvHttpProxyAgentOptions(e=process.env){const t=readProxyEnvValue(`all_proxy`,e);const n=resolveEnvHttpProxyUrl(`http`,e)??t;const r=resolveEnvHttpProxyUrl(`https`,e)??n;const i={...n?{httpProxy:n}:{},...r?{httpsProxy:r}:{}};return i.httpProxy||i.httpsProxy?i:void 0}function shouldUseEnvHttpProxyForUrl(e,t=process.env){const n=URL.parse(e);if(!n||n.protocol!==`http:`&&n.protocol!==`https:`)return false;return hasEnvHttpProxyConfigured(n.protocol===`https:`?`https`:`http`,t)&&!matchesNoProxy(n,t)}function matchesNoProxy(e,t=process.env){const n=t.no_proxy??t.NO_PROXY??``;if(!n)return false;const r=e instanceof URL?e:URL.parse(e);if(!r)return false;const i=r.hostname.toLowerCase().replace(/^\[|\]$/g,``).replace(/^(.+)\.$/,`$1`);if(!i)return false;if(n===`*`)return true;const a=parseIpv4Address(i);const o=r.port!==``?r.port:r.protocol===`https:`?`443`:r.protocol===`http:`?`80`:``;for(const e of n.split(/[,\s]/)){const t=e.trim().toLowerCase();if(!t)continue;let n;let r;if(t.startsWith(`[`)){const e=t.match(/^\[([^\]]+)\](?::(\d+))?$/);if(!e)continue;n=expectDefined(e[1],`m capture group 1`);r=e[2]}else{const e=t.indexOf(`:`);const i=t.lastIndexOf(`:`);if(e>-1&&e===i&&/^\d+$/.test(t.slice(i+1))){n=t.slice(0,i);r=t.slice(i+1)}else n=t}if(r&&r!==o)continue;const s=n.replace(/^\*?\./,``).replace(/^(.+)\.$/,`$1`);if(!s||s===`*`)continue;if(matchesIpv4NoProxyPattern(a,s))return true;if(i===s)return true;if(i.endsWith(`.`+s))return true}return false}function parseIpv4Address(e){const t=e.split(`.`);if(t.length!==4)return;let n=0;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(t>255)return;n=n<<8|t}return n>>>0}function matchesIpv4NoProxyPattern(e,t){if(e===void 0)return false;const n=t.match(/^(\d{1,3}(?:\.\d{1,3}){3})\/(\d{1,2})$/);if(n){const t=parseIpv4Address(expectDefined(n[1],`cidr match capture group 1`));const r=Number(n[2]);if(t===void 0||r>32)return false;const i=r===0?0:4294967295<<32-r>>>0;return(e&i)===(t&i)}if(!t.includes(`*`))return false;const r=t.split(`.`);if(r.length>4)return false;for(const[t,n]of r.entries()){if(n===`*`){if(t===r.length-1)return true;continue}if(!/^\d{1,3}$/.test(n)||Number(n)!==(e>>>(3-t)*8&255))return false}return r.length===4}
//!src/infra/net/proxy/active-proxy-state.ts
let activeProxyUrl;let activeProxyLoopbackMode;let activeProxyTlsOptions;function parseActiveManagedProxyLoopbackMode(e){if(e===`gateway-only`||e===`proxy`||e===`block`)return e}function readInheritedActiveManagedProxyLoopbackMode(){if(process.env[`OPENCLAW_PROXY_ACTIVE`]!==`1`)return;return parseActiveManagedProxyLoopbackMode(process.env[`OPENCLAW_PROXY_LOOPBACK_MODE`])??`gateway-only`}function getActiveManagedProxyLoopbackMode(){return activeProxyLoopbackMode??readInheritedActiveManagedProxyLoopbackMode()}function getActiveManagedProxyUrl(){return activeProxyUrl}function getActiveManagedProxyTlsOptions(){return activeProxyTlsOptions}
//!src/infra/net/proxy/proxy-tls.ts
function resolveManagedProxyCaFileForUrl(e){if(!e.proxyUrl||URL.parse(e.proxyUrl)?.protocol!==`https:`)return;return normalizeOptionalString(e.caFileOverride)??normalizeOptionalString(e.config?.tls?.caFile)}function loadManagedProxyTlsOptionsSync(e){if(!e)return;try{return{ca:readFileSync(e,`utf8`)}}catch(t){throw new Error(`proxy CA file could not be read (${e}): ${formatErrorMessage(t)}`,{cause:t})}}
//!src/infra/net/proxy/active-managed-proxy-tls.ts
function normalizeProxyUrl(e){return e?URL.parse(e)?.href:void 0}function resolveManagedProxyUrl(e=process.env){const t=getActiveManagedProxyUrl();if(t)return t.href;if(e.OPENCLAW_PROXY_ACTIVE!==`1`)return;return normalizeProxyUrl(resolveEnvHttpProxyUrl(`https`,e))}function resolveActiveManagedProxyTlsOptions(e){const t=e?.env??process.env;const n=resolveManagedProxyUrl(t);const r=normalizeProxyUrl(e?.proxyUrl??resolveEnvHttpProxyUrl(`https`,t));if(!n||r!==n)return;const i=getActiveManagedProxyTlsOptions();if(i)return i;const a=resolveManagedProxyCaFileForUrl({proxyUrl:n,caFileOverride:t.OPENCLAW_PROXY_CA_FILE});try{return loadManagedProxyTlsOptionsSync(a)}catch{return}}
//!src/infra/net/proxy/managed-proxy-undici.ts
function readProxyTlsRecord(e){if(!e||!(`proxyTls`in e))return;return isRecord(e.proxyTls)?e.proxyTls:void 0}function readProxyUrlFromOptions(e){if(!e)return;if(`uri`in e){const t=e.uri;return t instanceof URL?t.href:typeof t===`string`?t:void 0}if(`httpsProxy`in e||`httpProxy`in e){const t=Reflect.get(e,`httpsProxy`);const n=Reflect.get(e,`httpProxy`);return typeof t===`string`?t:typeof n===`string`?n:void 0}}function addActiveManagedProxyTlsOptions(e,t){const n=resolveActiveManagedProxyTlsOptions({proxyUrl:readProxyUrlFromOptions(e),env:t?.env});if(!n)return e;const r=readProxyTlsRecord(e);return{...e,proxyTls:{...n,...r}}}
//!src/infra/net/undici-error-diagnostics.ts
const observedDispatcherValues=/* @__PURE__ */ new WeakSet;function logUndiciDispatcherError(e){logDebug(`undici: internal dispatcher error: ${formatErrorMessage(e)}`)}function observeDispatcherValue(e){if(typeof e!==`object`&&typeof e!==`function`||e===null)return;if(observedDispatcherValues.has(e))return;observedDispatcherValues.add(e);if(e instanceof EventEmitter){EventEmitter.prototype.on.call(e,`error`,logUndiciDispatcherError);EventEmitter.prototype.on.call(e,`connect`,(e,t)=>{observeDispatcherValue(t)});for(const t of Reflect.ownKeys(e)){const n=Object.getOwnPropertyDescriptor(e,t);if(n&&`value`in n)observeDispatcherValue(n.value)}return}if(Array.isArray(e)||e instanceof Set||e instanceof Map)for(const t of e instanceof Map?e.values():e)observeDispatcherValue(t)}function withUndiciErrorDiagnostics(e){observeDispatcherValue(e);return e}
//!src/infra/wsl.ts
function isWSL2Sync(){if(process.platform!==`linux`)return false;try{const e=normalizeLowercaseStringOrEmpty(`${release()} ${version()}`);return e.includes(`wsl2`)||e.includes(`microsoft-standard`)}catch{return false}}
//!src/infra/net/undici-family-policy.ts
const AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS=300;function resolveUndiciAutoSelectFamily(){const e=net$1.getDefaultAutoSelectFamily();if(e&&isWSL2Sync())return false;return e}function createUndiciAutoSelectFamilyConnectOptions(e){if(e===void 0)return;return{autoSelectFamily:e,autoSelectFamilyAttemptTimeout:AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS}}function resolveUndiciAutoSelectFamilyConnectOptions(){return createUndiciAutoSelectFamilyConnectOptions(resolveUndiciAutoSelectFamily())}
//!src/infra/net/undici-dispatcher-options.ts
const TEST_UNDICI_RUNTIME_DEPS_KEY=`__OPENCLAW_TEST_UNDICI_RUNTIME_DEPS__`;const requireUndici=createRequire(import.meta.url);let undiciModule;let globalUndiciStreamTimeoutMs;function loadUndiciModule(e){const t=globalThis[TEST_UNDICI_RUNTIME_DEPS_KEY];if(isRecord(t)&&e.every(e=>typeof t[e]===`function`))return t;return undiciModule??=requireUndici(`undici/index.js`)}function createHttp1ProxyClient(e,t){const n=isRecord(t)?t.connect:void 0;return createUndiciPool(e,{...t,...typeof n===`function`?{connect:(e,t)=>{const{servername:r,...i}=e;return n(r&&net.isIP(r.replace(/^\[|\]$/g,``))?i:e,t)}}:{}})}function buildProxyConnectOptions(e,t){const n={...resolveUndiciAutoSelectFamilyConnectOptions(),...typeof e.connect===`object`?e.connect:{}};const r=floorPositiveFiniteNumber(t);return{autoSelectFamily:n.autoSelectFamily,autoSelectFamilyAttemptTimeout:n.autoSelectFamilyAttemptTimeout,family:`family`in n?n.family:void 0,keepAlive:n.keepAlive,keepAliveInitialDelay:n.keepAliveInitialDelay,timeout:e.connectTimeout,...e.proxyTls,...r!==void 0?{timeout:r}:{},allowH2:false}}function createUndiciClient(e,t){const{Client:n}=loadUndiciModule([`Client`]);return withUndiciErrorDiagnostics(new n(e,t))}function createUndiciPool(e,t){const{Pool:n}=loadUndiciModule([`Pool`]);return withUndiciErrorDiagnostics(new n(e,{...t,factory:createUndiciClient}))}function createUndiciOriginDispatcher(e,t){return t.connections===1?createUndiciClient(e,t):createUndiciPool(e,t)}function buildHttp1AgentOptions(e={},t){const n=floorPositiveFiniteNumber(t);return{factory:createUndiciOriginDispatcher,...e,allowH2:false,connect:typeof e.connect===`function`?e.connect:{...resolveUndiciAutoSelectFamilyConnectOptions(),...e.connect,...n!==void 0?{timeout:n}:{}},bodyTimeout:n??e.bodyTimeout??globalUndiciStreamTimeoutMs,headersTimeout:n??e.headersTimeout??globalUndiciStreamTimeoutMs}}function buildHttp1ProxyAgentOptions(e,t,n){const r=typeof e===`string`||e instanceof URL?{uri:e.toString()}:e;const{clientFactory:i=createHttp1ProxyClient}=r;const a=addActiveManagedProxyTlsOptions(r,{env:n});return{proxyTunnel:true,...a,...buildHttp1AgentOptions(a,t),clientFactory:i}}
//!src/infra/net/undici-runtime.ts
function loadUndiciRuntimeDeps(){return loadUndiciModule([`Agent`,`EnvHttpProxyAgent`,`ProxyAgent`,`fetch`])}function loadUndiciGlobalDispatcherDeps(){return loadUndiciModule([`getGlobalDispatcher`,`setGlobalDispatcher`])}function createHttp1Agent(e,t){const{Agent:n}=loadUndiciRuntimeDeps();return withUndiciErrorDiagnostics(new n(buildHttp1AgentOptions(e,t)))}function isSocksProxy(e){return e!==void 0&&[`socks:`,`socks5:`].includes(URL.parse(e)?.protocol??``)}function createSocksProxyAgent(e,t){const{Agent:n,Socks5ProxyAgent:r,buildConnector:i,errors:a}=loadUndiciModule([`Agent`,`Socks5ProxyAgent`,`buildConnector`]);if(typeof e.clientFactory!==`function`)throw new a.InvalidArgumentError(`Proxy opts.clientFactory must be a function.`);if(e.auth&&e.token)throw new a.InvalidArgumentError(`opts.auth cannot be used in combination with opts.token`);const o=i(buildProxyConnectOptions(e,t));class SocksProxyAgent extends n{}const s=withUndiciErrorDiagnostics(new SocksProxyAgent({...e,factory:()=>withUndiciErrorDiagnostics(new r(e.uri,{...e,connect:o}))}));const c={connections:e.connections,pipelining:e.pipelining,bodyTimeout:e.bodyTimeout,headersTimeout:e.headersTimeout};return s.compose(e=>(t,n)=>{const r=t.headers;const i=Array.isArray(r)?r.filter((e,t)=>t%2===0):[];if(!Array.isArray(r))for(const e in r)i.push(e);if(i.some(e=>typeof e===`string`&&e.toLowerCase()===`proxy-authorization`))throw new a.InvalidArgumentError(`Proxy-Authorization should be sent in ProxyAgent constructor`);return e({...c,...t},n)})}function completeProxyLifecycle(e,t){if(t!==void 0&&typeof t!==`function`){const{errors:e}=loadUndiciModule([]);throw new e.InvalidArgumentError(`invalid callback`)}const n=e().then(()=>void 0);if(t)n.then(()=>t(null,null),e=>t(toErrorObject(e,`Proxy shutdown failed`),null));else return n}function createHttp1EnvHttpProxyAgent(e,t,n){const{EnvHttpProxyAgent:r}=loadUndiciRuntimeDeps();const i=e?.httpProxy??process.env.http_proxy??process.env.HTTP_PROXY;const a=(e?.httpsProxy??process.env.https_proxy??process.env.HTTPS_PROXY)||i;const o=/* @__PURE__ */ new Map;for(const r of[i,a])if(r&&!o.has(r))o.set(r,createHttp1ProxyAgent({...e,uri:r},t,n));const s=withUndiciErrorDiagnostics(new r({...buildHttp1AgentOptions(e,t),httpProxy:``,httpsProxy:``,noProxy:`*`}));if(o.size===0)return s;const c=[s,...o.values()];const isDestroyed=()=>c.every(e=>Reflect.get(e,`destroyed`)===true);let l;return new Proxy(s,{get(t,n,r){if(n===`destroyed`)return isDestroyed();if(n===`dispatch`)return(n,r)=>{const s=n?.origin?URL.parse(String(n.origin)):null;const c=s?.protocol===`https:`?a:i;const l=c&&o.get(c);const u=e?.noProxy===void 0?process.env:{no_proxy:e.noProxy};return l&&s&&!matchesNoProxy(s,u)?l.dispatch(n,r):t.dispatch(n,r)};if(n===`close`)return e=>completeProxyLifecycle(()=>isDestroyed()?t.close():l??=Promise.all(c.map(e=>e.close())).finally(()=>{l=void 0}),e);if(n===`destroy`)return(e,t)=>completeProxyLifecycle(()=>Promise.all(c.map(t=>t.destroy(typeof e===`function`?null:e??null))),typeof e===`function`?e:t);return Reflect.get(t,n,r)}})}function createHttp1ProxyAgent(e,t,n){const r=buildHttp1ProxyAgentOptions(e,t,n);if(isSocksProxy(r.uri))return createSocksProxyAgent(r,t);const{ProxyAgent:i}=loadUndiciRuntimeDeps();return withUndiciErrorDiagnostics(new i({...r,proxyTls:buildProxyConnectOptions(r,t)}))}export{loadUndiciRuntimeDeps as a,resolveActiveManagedProxyTlsOptions as c,getActiveManagedProxyLoopbackMode as d,resolveEnvHttpProxyAgentOptions as f,loadUndiciGlobalDispatcherDeps as i,loadManagedProxyTlsOptionsSync as l,createHttp1EnvHttpProxyAgent as n,globalUndiciStreamTimeoutMs as o,shouldUseEnvHttpProxyForUrl as p,createHttp1ProxyAgent as r,resolveUndiciAutoSelectFamilyConnectOptions as s,createHttp1Agent as t,resolveManagedProxyCaFileForUrl as u};