UNPKG

eve

Version:

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

1 lines 2.8 kB
import{createHash}from"node:crypto";import{ContextContainer,contextStorage}from"#context/container.js";const ENVIRONMENT=Symbol.for(`eve.sandbox-environment`),PROVIDER_RUNTIME=Symbol.for(`eve.sandbox-provider-runtime`),CONFIGURATION_HASH=Symbol.for(`eve.sandbox-environment-configuration-hash`),SELECTOR_ENVIRONMENT=Symbol.for(`eve.sandbox-selector-environment`),RUNTIMES=Symbol.for(`eve.sandbox-constructor-runtimes`),globals=globalThis,runtimes=globals[RUNTIMES]??=new WeakMap;function createSandboxEnvironment(e){let t;return t={[CONFIGURATION_HASH]:hashConstructorOptions({environment:e.configuration,sandbox:{}}),[ENVIRONMENT]:!0,[PROVIDER_RUNTIME]:e.runtime,provider:e.runtime.providerName,async open(...n){let r=n[0],i=contextStorage.getStore(),a=i===void 0?void 0:runtimes.get(i);if(a===void 0)throw Error(`Sandbox environments can only open sandboxes inside defineSandbox().`);return await a.open({configurationHash:hashConstructorOptions({environment:e.configuration,sandbox:r}),environment:t,environmentConfigurationHash:t[CONFIGURATION_HASH],options:r,provider:e.runtime})}},t}function hashConstructorOptions(e){return createHash(`sha256`).update(stableSerialize(e)).digest(`hex`)}function stableSerialize(e,t=new WeakSet){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`function`)return`function:${e.toString()}`;if(Array.isArray(e))return`[${e.map(e=>stableSerialize(e,t)).join(`,`)}]`;if(typeof e==`object`){if(t.has(e))return`[circular]`;t.add(e);let n=e.constructor?.name??`Object`,r=`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>`${JSON.stringify(e)}:${stableSerialize(n,t)}`).join(`,`)}}`;return t.delete(e),`${n}:${r}`}return typeof e}function getSandboxEnvironmentConfigurationHash(e){return e[CONFIGURATION_HASH]}function getSandboxEnvironmentRuntime(e){return e[PROVIDER_RUNTIME]}function bindSandboxEnvironment(e,t){return Object.defineProperty(e,SELECTOR_ENVIRONMENT,{value:t}),e}function getBoundSandboxEnvironment(e){let t=typeof e==`function`?Reflect.get(e,SELECTOR_ENVIRONMENT):void 0;return isSandboxEnvironment(t)?t:void 0}function isSandboxEnvironment(e){return typeof e==`object`&&!!e&&Reflect.get(e,ENVIRONMENT)===!0&&typeof Reflect.get(e,`provider`)==`string`&&typeof Reflect.get(e,`open`)==`function`}async function runWithSandboxConstructorRuntime(e,t){let n=contextStorage.getStore(),r=n??new ContextContainer,i=runtimes.get(r);runtimes.set(r,e);try{return n===void 0?await contextStorage.run(r,t):await t()}finally{i===void 0?runtimes.delete(r):runtimes.set(r,i)}}export{bindSandboxEnvironment,createSandboxEnvironment,getBoundSandboxEnvironment,getSandboxEnvironmentConfigurationHash,getSandboxEnvironmentRuntime,isSandboxEnvironment,runWithSandboxConstructorRuntime};