import J from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as A,shouldInterruptAfterDeadline as I}from"quickjs-emscripten-core";const $=1e4,C=64*1024*1024,L=256*1024,w=100,N=1024*1024,R=1024*1024;let O;function x(){return O??=A(J)}function Y(t){return`(() => {
    const invoke = globalThis.__invoke;
    delete globalThis.__invoke;
    globalThis.tools = Object.freeze({ ${t.map(r=>`${JSON.stringify(r)}: (input) => invoke(${JSON.stringify(r)}, JSON.stringify(input ?? {})).then(JSON.parse)`).join(", ")} });
  })();`}async function F(t,n,r={}){const{timeoutMs:s=$}=r,m=new Set;let M=0,f=0;const e=(await x()).newContext();let l,g=()=>{};const y=new Promise((o,c)=>{g=()=>c(new Error(`Execution timed out after ${s}ms`))}),S=()=>e.runtime.setInterruptHandler(I(Date.now()+s)),p=()=>{clearTimeout(l),l=setTimeout(g,s)};let u;try{e.runtime.setMemoryLimit(C),e.runtime.setMaxStackSize(L),S(),p(),B(e,"__invoke",(E,b)=>{const P=e.getString(E),j=JSON.parse(e.getString(b)),i=e.newPromise();return m.add(i),f++,clearTimeout(l),(++M>w?Promise.reject(new Error(`Exceeded the limit of ${w} tool calls`)):Promise.resolve().then(()=>n[P](j))).then(a=>{if(!e.alive)return;const d=JSON.stringify(a??null);if(d.length>N){const k=`Tool output is too large (${d.length} bytes); request narrower data instead`;e.newError(k).consume(i.reject)}else e.newString(d).consume(i.resolve)},a=>{e.alive&&e.newError(h(a)).consume(i.reject)}),i.settled.then(()=>{e.alive&&(S(),--f===0&&p(),e.runtime.executePendingJobs())}),i.handle}),U(e,Y(Object.keys(n))),u=e.unwrapResult(e.evalCode(`(async () => {
${t}
})()`));const o=e.resolvePromise(u);e.runtime.executePendingJobs();const c=await Promise.race([o,y]),T=e.unwrapResult(c),_=e.dump(T);T.dispose();const v=JSON.stringify(_??null).length;return v>R?{error:`Result is too large (${v} bytes); return less data`}:{result:_}}catch(o){return{error:h(o)}}finally{clearTimeout(l),u?.dispose();for(const o of m)o.alive&&o.dispose();try{e.dispose()}catch{O=void 0}}}function B(t,n,r){t.newFunction(n,r).consume(s=>t.setProp(t.global,n,s))}function U(t,n){t.unwrapResult(t.evalCode(n)).dispose()}function h(t){return t instanceof Error?t.message:String(t)}export{F as runInSandbox};
