UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines 12.7 kB
import{r as e}from"../_chunks/node/virtual-loader-Cwgujv7l.js";import{Readable as t}from"node:stream";import{rm as n}from"node:fs/promises";import r,{request as i}from"node:http";import a,{request as o}from"node:https";import"node:http2";const s=/(^|,)\s*upgrade\s*($|,)/i,c=/(^|,)\s*transfer-encoding\s*($|,)/i,l={http:new r.Agent({keepAlive:!0,maxSockets:256,maxFreeSockets:64}),https:new a.Agent({keepAlive:!0,maxSockets:256,maxFreeSockets:64})},u=/^https|wss/;function d(e){let t=!1;for(let n in e)if(e[n]!==void 0&&n.toLowerCase()===`transfer-encoding`){t=!0;break}let n=e.connection,r=typeof n==`string`&&c.test(n);(t||r)&&(e.connection=`close`)}const f=[`:method`,`:path`,`:scheme`,`:authority`];function p(e,t,n,r){e.port=t[r||`target`].port||(u.test(t[r||`target`].protocol??`http`)?443:80);for(let n of[`host`,`hostname`,`socketPath`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`secureProtocol`]){let i=t[r||`target`][n];i!==void 0&&(e[n]=i)}if(e.host===void 0&&typeof e.hostname==`string`){let t=e.hostname.includes(`:`)&&!e.hostname.startsWith(`[`)?`[${e.hostname}]`:e.hostname;e.host=e.port?`${t}:${e.port}`:t}if(e.method=t.method||n.method,e.headers={...n.headers},n.headers?.[`:authority`]&&(e.headers.host=n.headers[`:authority`]),t.headers)for(let n of Object.keys(t.headers))e.headers[n]=t.headers[n];if(n.httpVersionMajor>1)for(let t of f)delete e.headers[t];if(t.auth&&(e.auth=t.auth),t.ca&&(e.ca=t.ca),u.test(t[r||`target`].protocol??`http`)&&(e.rejectUnauthorized=t.secure===void 0?!0:t.secure),t.agent!==void 0)e.agent=t.agent||!1;else if(n.httpVersionMajor>1||s.test(n.headers.connection||``))e.agent=!1;else{let n=t[r||`target`].protocol??`http`;e.agent=u.test(n)?l.https:l.http}e.localAddress=t.localAddress,e.agent||(e.headers=e.headers||{},(typeof e.headers.connection!=`string`||!s.test(e.headers.connection))&&(e.headers.connection=`close`)),e.headers=e.headers||{},d(e.headers);let i=t[r||`target`],a=i&&t.prependPath!==!1&&i.pathname||``,o=i instanceof URL&&t.prependPath!==!1&&i.search||``,c=n.url||``,p=c.indexOf(`?`),h=p===-1?c:c.slice(0,p),g=p===-1?``:c.slice(p),_=h?h[0]===`/`?h:`/`+h:`/`,v=t.toProxy?`/`+c:_+g;v=t.ignorePath?``:v;let y=m(a,v);return o&&(y=y.includes(`?`)?y.replace(`?`,o+`&`):y+o),e.path=y,t.changeOrigin&&(e.headers.host=x(e.port,t[r||`target`].protocol)&&!b(e.host)?e.host+`:`+e.port:e.host??void 0),e}function m(e,t){if(!e||e===`/`)return t||`/`;if(!t||t===`/`)return e||`/`;let n=e[e.length-1]===`/`,r=t[0]===`/`;return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t}function h(e){return e.setTimeout(0),e.setNoDelay(!0),e.setKeepAlive(!0,0),e}function g(e){let t=e.headers[`:authority`]||e.headers.host,n=t?t.match(/:(\d+)/):``;return n?n[1]:_(e)?`443`:`80`}function _(e){let t=e.socket;return!!t&&`encrypted`in t&&t.encrypted}function v(e,t,n){return Array.isArray(e)?e.map(function(e){return v(e,t,n)}):e.replace(RegExp(String.raw`(;\s*`+n+`=)([^;]+)`,`i`),function(e,n,r){let i;if(r in t)i=t[r];else if(`*`in t)i=t[`*`];else return e;return i?n+i:``})}function y(e){if(typeof e==`string`){if(e.startsWith(`unix:`))return{socketPath:e.slice(5)};let t=new URL(e);return{host:t.hostname,port:Number(t.port)||(u.test(t.protocol)?443:80)}}if(!e.socketPath&&!e.port)throw Error("ProxyAddr must have either `port` or `socketPath`");return e}function b(e){return e?!!~e.indexOf(`:`):!1}function x(e,t){let n=t?.split(`:`)[0],r=+e;if(!r)return!1;switch(n){case`http`:case`ws`:return r!==80;case`https`:case`wss`:return r!==443;case`ftp`:return r!==21;case`gopher`:return r!==70;case`file`:return!1}return r!==0}async function S(e,n,r,a){let s=y(e),c=!1,d=``;if(typeof e==`string`&&!e.startsWith(`unix:`)){let t=new URL(e);c=u.test(t.protocol),t.pathname&&t.pathname!==`/`&&(d=t.pathname)}let f,p;n instanceof Request?(f=new URL(n.url),p={...C(n),...C(r)}):(f=new URL(n),p=C(r)),p={redirect:`manual`,...p},p.body&&(p.duplex=`half`);let h=f.pathname+f.search,g=d?m(d,h):h,_={};if(p.headers)if(!(p.headers instanceof Headers)&&!Array.isArray(p.headers))Object.assign(_,p.headers);else for(let[e,t]of p.headers){let n=_[e];n===void 0?_[e]=t:_[e]=Array.isArray(n)?[...n,t]:[n,t]}if(a?.xfwd&&(_[`x-forwarded-for`]||=f.hostname,_[`x-forwarded-port`]||=f.port||(f.protocol===`https:`?`443`:`80`),_[`x-forwarded-proto`]||=f.protocol.replace(`:`,``),_[`x-forwarded-host`]||=f.host),a?.changeOrigin)if(s.socketPath)_.host=`localhost`;else{let e=s.host||`localhost`,t=s.port;_.host=t&&t!==(c?443:80)?`${e}:${t}`:e}let v=typeof a?.followRedirects==`number`?a.followRedirects:a?.followRedirects?5:0,b=v>0?await T(p.body):w(p.body),x=a?.agent===void 0?c?l.https:l.http:a.agent||!1,S=await D(c?o:i,p.method||`GET`,g,_,s,b,{signal:p.signal||void 0,agent:x,timeout:a?.timeout,ssl:a?.ssl,maxRedirects:v,redirectCount:0,originalHeaders:_}),E=[],O=S.rawHeaders;for(let e=0;e<O.length;e+=2){let t=O[e],n=t.toLowerCase();n===`transfer-encoding`||n===`keep-alive`||n===`connection`||E.push([t,O[e+1]])}let k=S.statusCode!==204&&S.statusCode!==304;return new Response(k?t.toWeb(S):null,{status:S.statusCode,statusText:S.statusMessage,headers:E})}function C(e){if(e)return e instanceof Request?{method:e.method,headers:e.headers,body:e.body,duplex:e.body?`half`:void 0}:e}function w(e){if(e)return typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e):e instanceof ReadableStream?t.fromWeb(e):e instanceof Blob?t.fromWeb(e.stream()):Buffer.from(String(e))}async function T(e){if(e){if(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Buffer.from(e);if(e instanceof ReadableStream){let n=t.fromWeb(e),r=[];for await(let e of n)r.push(typeof e==`string`?Buffer.from(e):e);return Buffer.concat(r)}return e instanceof Blob?Buffer.from(await e.arrayBuffer()):Buffer.from(String(e))}}const E=new Set([301,302,303,307,308]);function D(e,n,r,a,s,c,l){return d(a),new Promise((d,f)=>{let p={method:n,path:r,headers:a,agent:l.agent};s.socketPath?p.socketPath=s.socketPath:(p.hostname=s.host||`localhost`,p.port=s.port),l.signal&&(p.signal=l.signal),l.ssl&&Object.assign(p,l.ssl);let m=e(p,e=>{let t=e.statusCode;if(l.maxRedirects>0&&E.has(t)&&l.redirectCount<l.maxRedirects&&e.headers.location){e.resume();let a=new URL(r,`http://${s.host||`localhost`}:${s.port||80}`),p=new URL(e.headers.location,a),m=u.test(p.protocol),h=t===307||t===308,g=h?n:`GET`,_={...l.originalHeaders};_.host=p.host,p.host!==a.host&&(delete _.authorization,delete _.cookie),h||(delete _[`content-length`],delete _[`content-type`],delete _[`transfer-encoding`]),D(m?o:i,g,p.pathname+p.search,_,{host:p.hostname,port:Number(p.port)||(m?443:80)},h?c:void 0,{...l,redirectCount:l.redirectCount+1}).then(d,f);return}d(e)});m.on(`error`,f),l.timeout&&m.setTimeout(l.timeout,()=>{m.destroy(Error(`Proxy request timed out`))}),c instanceof t?(c.on(`error`,e=>{m.destroy(e),f(e)}),c.pipe(m)):c?m.end(c):m.end()})}function O(e,t,n,r,a){let s=y(e),c=!1;if(typeof e==`string`&&!e.startsWith(`unix:`)&&(c=u.test(new URL(e).protocol)),t.method!==`GET`||t.headers.upgrade?.toLowerCase()!==`websocket`)return n.destroy(),Promise.reject(Error(`Not a valid WebSocket upgrade request`));if(a?.xfwd!==!1){let e=t.headers[`x-forwarded-for`],n=t.headers[`x-forwarded-port`],r=t.headers[`x-forwarded-proto`];t.headers[`x-forwarded-for`]=`${e?`${e},`:``}${t.socket?.remoteAddress}`,t.headers[`x-forwarded-port`]=`${n?`${n},`:``}${g(t)}`,t.headers[`x-forwarded-proto`]=`${r?`${r},`:``}${_(t)?`wss`:`ws`}`}let l=k(s,c),d={...a,target:l,prependPath:a?.prependPath!==!1},f=p(d.ssl||{},d,t),m=n;return new Promise((e,t)=>{let n=!1;h(m),r&&r.length>0&&m.unshift(r),m.once(`error`,s);let a=(u.test(l.protocol)?o:i)(f);a.once(`error`,c),a.once(`response`,e=>{e.upgrade||(!m.destroyed&&m.writable?(m.write(A(`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}`,e.headers)),e.on(`error`,c),e.pipe(m)):e.resume(),n||(n=!0,t(Error(`Upstream server did not upgrade the connection`))))}),a.once(`upgrade`,(t,r,i)=>{r.once(`error`,c),m.removeListener(`error`,s),m.once(`error`,()=>{r.end()}),h(r),i&&i.length>0&&r.unshift(i),m.write(A(`HTTP/1.1 101 Switching Protocols`,t.headers)),r.pipe(m).pipe(r),n=!0,e(r)}),a.end();function s(e){a.destroy(),n||(n=!0,t(e))}function c(e){m.end(),n||(n=!0,t(e))}})}function k(e,t=!1){let n=t?`https`:`http`;if(e.socketPath){let t=new URL(`${n}://unix`);return t.socketPath=e.socketPath,t}return new URL(`${n}://${e.host||`localhost`}${e.port?`:${e.port}`:``}`)}function A(e,t){let n=e;for(let e of Object.keys(t)){let r=t[e];if(r!==void 0)if(Array.isArray(r))for(let t of r)n+=`\r\n${e}: ${t}`;else n+=`\r\n${e}: ${r}`}return`${n}\r\n\r\n`}var j=class{closed=!1;_name;_workerEntry;_data;_virtualSources;_hooks;_address;_messageListeners;_pendingRequests;_virtualResolved;constructor(e){this._name=e.name,this._workerEntry=e.workerEntry,this._data=e.data,this._hooks=e.hooks||{},this._messageListeners=new Set,this._pendingRequests=new Set}get ready(){return!!(!this.closed&&this._address&&this._hasRuntime())}get address(){return this._address}async fetch(e,t){for(let e=0;e<5&&!this._address&&!this.closed;e++)await new Promise(t=>setTimeout(t,100*2**e));return this._address?S(this._address,this._resolveFetchInput(e),t):new Response(`${this._runtimeType()} env runner is unavailable`,{status:503})}async upgrade(e){if(this.ready||await this.waitForReady().catch(()=>{}),!this.ready||!this._address){e.node.socket.destroy();return}try{await O(this._address,e.node.req,e.node.socket,e.node.head)}catch{}}onMessage(e){this._messageListeners.add(e)}offMessage(e){this._messageListeners.delete(e)}waitForReady(e=15e3){return this.ready?Promise.resolve():this.closed?Promise.reject(Error(`Runner closed before becoming ready`)):new Promise((t,n)=>{let r=setTimeout(()=>{this._messageListeners.delete(i),n(Error(`Runner did not become ready in time`))},e),i=()=>{this.ready?(clearTimeout(r),this._messageListeners.delete(i),t()):this.closed&&(clearTimeout(r),this._messageListeners.delete(i),n(Error(`Runner closed before becoming ready`)))};this._messageListeners.add(i)})}rpc(e,t,n){let r=Math.random().toString(36).slice(2);return this._request({__rpc:e,__rpc_id:r,data:t},{match:e=>e?.__rpc_id===r,timeout:n?.timeout??3e3,timeoutError:`RPC "${e}" timed out`}).then(e=>e.data)}async reloadModule(e=5e3){await this._request({event:`reload-module`},{match:e=>e?.event===`module-reloaded`,timeout:e,timeoutError:`Module reload timed out`})}async invalidateModule(e,t=5e3){let n=await this._refreshVirtualSource(e);await this._request({event:`invalidate-module`,specifier:e,source:n},{match:t=>t?.event===`module-invalidated`&&t.specifier===e,timeout:t,timeoutError:`Module invalidation timed out for "${e}"`})}async close(e){if(this.closed)return;this.closed=!0;for(let t of this._pendingRequests)t(e);this._pendingRequests.clear(),this._hooks.onClose?.(this,e),this._hooks={};let t=e=>console.error(e);await this._closeRuntime().catch(t),await this._closeSocket().catch(t)}async[Symbol.asyncDispose](){await this.close()}[Symbol.for(`nodejs.util.inspect.custom`)](){let e=this.closed?`closed`:this.ready?`ready`:`pending`;return`${this.constructor.name}#${this._name}(${e})`}_resolveFetchInput(e){return typeof e==`string`&&!URL.canParse(e)?new URL(e,`http://localhost`):e}_handleMessage(e){e?.address&&(this._address=e.address,this._hooks.onReady?.(this,this._address)),e?.event===`init-error`&&!this.ready&&!this.closed&&this.close(Error(String(e.error||`Worker initialization failed`)));for(let t of this._messageListeners)t(e)}_request(e,t){return this.closed?Promise.reject(Error(`Runner is closed`)):new Promise((n,r)=>{let i=setTimeout(()=>{s(),r(Error(t.timeoutError))},t.timeout),a=e=>{t.match(e)&&(s(),e.error?r(typeof e.error==`string`?Error(e.error):e.error):n(e))},o=e=>{s(),r(Error(`Runner closed before responding`,e?{cause:e}:void 0))},s=()=>{clearTimeout(i),this.offMessage(a),this._pendingRequests.delete(o)};this.onMessage(a),this._pendingRequests.add(o);try{(t.send??(e=>this.sendMessage(e)))(e)}catch(e){s(),r(e)}})}_resolveVirtualData(){let t=this._data?.virtual;if(this._virtualSources=t,!(!t||!Object.values(t).some(e=>typeof e==`function`)))return this._virtualResolved=e(t).then(e=>{this._data={...this._data,virtual:e}}),this._virtualResolved}async _refreshVirtualSource(e){await this._virtualResolved?.catch(()=>{});let t=this._virtualSources?.[e];if(typeof t!=`function`)return;let n=await t(),r=this._data?.virtual;return r&&(r[e]=n),n}_initWithVirtualData(e){let t=this._resolveVirtualData();t?t.then(()=>{this.closed||e()},e=>this.close(e)):e()}async _closeSocket(){let e=this._address?.socketPath;e&&e[0]!==`\0`&&!e.startsWith(String.raw`\\.\\pipe`)&&await n(e).catch(()=>{}),this._address=void 0}};export{j as BaseEnvRunner};