@qoder-ai/qodercli 1.1.80 → 1.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,287 @@
1
+ import{parentPort as $,workerData as qe}from"node:worker_threads";function le(a){return{clock_time_get(i,o,c){let u=a(),l=new DataView(u.buffer);if(i===0||i===1){let d=BigInt(Date.now())*1000000n;return l.setBigUint64(c,d,!0),0}return 52},fd_write(i,o,c,u){let l=a(),d=new DataView(l.buffer),h=new Uint8Array(l.buffer),w=0;if(i!==1&&i!==2)return 8;for(let g=0;g<c;g++){let _=d.getUint32(o+g*8,!0),I=d.getUint32(o+g*8+4,!0),O=h.slice(_,_+I),x=new TextDecoder().decode(O);i===1?typeof process<"u"&&process.stdout?process.stdout.write(x):console.log(x):typeof process<"u"&&process.stderr?process.stderr.write(x):console.error(x),w+=I}return d.setUint32(u,w,!0),0},fd_close(i){return 52},fd_fdstat_get(i,o){let c=a(),u=new DataView(c.buffer);return i===1||i===2?(u.setUint8(o,2),u.setUint16(o+2,0,!0),u.setBigUint64(o+8,0n,!0),u.setBigUint64(o+16,0n,!0),0):8},fd_seek(i,o,c,u){return 52},random_get(i,o){let c=a(),u=new Uint8Array(c.buffer,i,o);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(u);else for(let l=0;l<o;l++)u[l]=Math.floor(Math.random()*256);return 0}}}var be=new TextDecoder;function xe(a,e){let t=new Uint8Array(a.buffer),r=e;for(;t[r]!==0;)r++;if(r===e)return{};let s=be.decode(t.slice(e,r)),n={};for(let i of s.split(`
2
+ `)){let o=i.indexOf("=");o>0&&(n[i.slice(0,o)]=i.slice(o+1))}return n}function Se(a,e){let t=`qjs_ext_${a.name.replace(/-/g,"_")}_versions`,r=a.instance.exports[t];if(typeof r!="function")return;let s=r();if(s!==0)return xe(e,s)}function M(a,e){let t=0,r=0;for(;e.value<a.length;){let s=a[e.value++];if(t|=(s&127)<<r,(s&128)===0)break;r+=7}return t}function Ee(a){let e=WebAssembly.Module.customSections(a,"dylink.0");if(e.length===0)return null;let t=new Uint8Array(e[0]),r={value:0},s={memorySize:0,memoryAlignment:0,tableSize:0,tableAlignment:0,needed:[]};for(;r.value<t.length;){let n=M(t,r),i=M(t,r),o=r.value+i;if(n===1)s.memorySize=M(t,r),s.memoryAlignment=M(t,r),s.tableSize=M(t,r),s.tableAlignment=M(t,r);else if(n===2){let c=M(t,r);for(let u=0;u<c;u++){let l=M(t,r),d=new TextDecoder().decode(t.slice(r.value,r.value+l));r.value+=l,s.needed.push(d)}}r.value=o}return s}async function Z(a,e,t,r,s,n){let i;a.wasm instanceof WebAssembly.Module?i=a.wasm:i=await WebAssembly.compile(a.wasm);let o=Ee(i);if(!o)throw new Error(`Extension "${a.name}" is not a WASM shared library (missing dylink.0 section)`);let c=e.memory,u=e.__indirect_function_table,l=e.__stack_pointer,d=e.malloc;if(!c)throw new Error("Main module does not export memory");if(!u)throw new Error("Main module does not export __indirect_function_table");if(!d)throw new Error("Main module does not export malloc");let h,w;if(n)h=n.memoryBase,w=n.tableBase;else if(o.memorySize>0){if(h=d(o.memorySize),h===0)throw new Error(`Failed to allocate ${o.memorySize} bytes for extension "${a.name}"`);new Uint8Array(c.buffer,h,o.memorySize).fill(0)}else h=0;n?(w=n.tableBase,w+o.tableSize>u.length&&u.grow(w+o.tableSize-u.length)):(w=u.length,o.tableSize>0&&u.grow(o.tableSize));let g=WebAssembly.Module.imports(i),_={env:{},"GOT.mem":{},"GOT.func":{}};if(g.some(f=>f.module==="wasi_snapshot_preview1")){let f=a.wasi&&s?a.wasi(s):void 0;_.wasi_snapshot_preview1={...t,...f,...r}}let O=new Set(WebAssembly.Module.exports(i).filter(f=>f.kind==="function").map(f=>f.name)),x=new Set;for(let f of g)if(f.module==="env"){if(f.name==="memory"&&f.kind==="memory")_.env.memory=c;else if(f.name==="__indirect_function_table"&&f.kind==="table")_.env.__indirect_function_table=u;else if(f.name==="__memory_base"&&f.kind==="global")_.env.__memory_base=new WebAssembly.Global({value:"i32",mutable:!1},h);else if(f.name==="__table_base"&&f.kind==="global")_.env.__table_base=new WebAssembly.Global({value:"i32",mutable:!1},w);else if(f.name==="__stack_pointer"&&f.kind==="global")_.env.__stack_pointer=l;else if(f.kind==="function"){let P=e[f.name];P&&typeof P=="function"?_.env[f.name]=P:(x.add(f.name),_.env[f.name]=()=>{throw new Error(`Extension "${a.name}" called unresolved symbol: env.${f.name}`)})}else if(f.kind==="global"){let P=e[f.name];P instanceof WebAssembly.Global?_.env[f.name]=P:_.env[f.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}}else if(f.module==="GOT.mem"&&f.kind==="global")_["GOT.mem"][f.name]=new WebAssembly.Global({value:"i32",mutable:!0},0);else if(f.module==="GOT.func"&&f.kind==="global"){let P=e[f.name];if(P&&typeof P=="function"){let L=u.length;u.grow(1),u.set(L,P),_["GOT.func"][f.name]=new WebAssembly.Global({value:"i32",mutable:!0},L)}else _["GOT.func"][f.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}let E=[...x].filter(f=>O.has(f)),v={};for(let f of E){let P={target:null};v[f]=P,_.env[f]=(...L)=>{if(!P.target)throw new Error(`Extension "${a.name}" called unresolved symbol during init: env.${f}`);return P.target(...L)}}let S=await WebAssembly.instantiate(i,_),k=S.exports;for(let f of E){let P=k[f];typeof P=="function"&&(v[f].target=P)}typeof k.__wasm_apply_data_relocs=="function"&&k.__wasm_apply_data_relocs(),typeof k.__wasm_call_ctors=="function"&&k.__wasm_call_ctors();let B=a.initFn??`qjs_ext_${a.name.replace(/-/g,"_")}_init`,y={name:a.name,module:i,instance:S,dylink:o,memoryBase:h,tableBase:w,initFn:B};return y.versions=Se(y,c),y}function ce(a,e){let t=a.instance.exports[a.initFn];if(typeof t!="function")throw new Error(`Extension "${a.name}" does not export init function "${a.initFn}"`);let r=e.qjs_get_context_ptr(),s=e.qjs_get_runtime_ptr(),n=t(r,s);if(n!==0)throw new Error(`Extension "${a.name}" init function returned error code ${n}`)}async function ue(a,e,t,r,s,n){let i=[];for(let o of e){let c=a.find(l=>l.name===o.name);if(!c)throw new Error(`Extension "${o.name}" required by snapshot but not provided`);let u=await Z(c,t,r,s,n,{memoryBase:o.memoryBase,tableBase:o.tableBase});u.initFn=o.initFn,i.push(u)}return i}var pe="3.6.2";var H=function(a,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),a.stack.push({value:e,dispose:r,async:t})}else t&&a.stack.push({async:!0});return e},F=function(a){return function(e){function t(i){e.error=e.hasError?new a(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}}(typeof SuppressedError=="function"?SuppressedError:function(a,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=a,r.suppressed=e,r}),G=512*1024;var ee=1363825491,te=2,V=24,Y=class a{exports;module;instance;encoder=new TextEncoder;decoder=new TextDecoder;disposed=!1;hostCallbacks=new Map;nextInternalId=1;interruptHandler=null;unhandledRejectionHandler=null;moduleNormalizeHandler=null;moduleLoadHandler=null;timezoneOffsetHandler=null;_global=null;_versions=null;_undefined=null;_null=null;_true=null;_false=null;_ownedHandles=new Set;_activeScope=null;loadedExtensions=[];constructor(e){this.module=e,this.instance=null,this.exports=null}setInstance(e){this.instance=e,this.exports=e.exports}get versions(){if(this.assertNotDisposed(),!this._versions){let e={"quickjs-wasi":pe,quickjs:this.readCString(this.exports.qjs_get_quickjs_version())};for(let t of this.loadedExtensions)t.versions&&Object.assign(e,t.versions);this._versions=e}return this._versions}get global(){return this._global||(this._global=new m(this,this.exports.qjs_get_global(),!0)),this._global}get undefined(){return this._undefined||(this._undefined=new m(this,this.exports.qjs_get_undefined(),!0)),this._undefined}get null(){return this._null||(this._null=new m(this,this.exports.qjs_get_null(),!0)),this._null}get true(){return this._true||(this._true=new m(this,this.exports.qjs_get_true(),!0)),this._true}get false(){return this._false||(this._false=new m(this,this.exports.qjs_get_false(),!0)),this._false}static async create(e){let t=a.normalizeOptions(e),r=await a.resolveModule(t.wasm),s=new a(r),{instance:n,wasiBuiltins:i,wasiUserOverrides:o,memoryProxy:c}=await a.instantiate(r,s,t.wasi);if(s.setInstance(n),s.exports._initialize(),(t.intrinsics!==void 0?s.exports.qjs_init2(t.intrinsics):s.exports.qjs_init())!==0)throw new Error("Failed to initialize QuickJS runtime");if(t.extensions){let l=n.exports;for(let d of t.extensions){let h=await Z(d,l,i,o,c);s.loadedExtensions.push(h),ce(h,l)}}return a.applyLimits(s,t),s}static async restore(e,t){let r=a.normalizeOptions(t),s=await a.resolveModule(r.wasm),n=new a(s),{instance:i,wasiBuiltins:o,wasiUserOverrides:c,memoryProxy:u}=await a.instantiate(s,n,r.wasi);n.setInstance(i);let l=i.exports,d=n.exports.memory,h=d.buffer.byteLength/65536,w=Math.ceil(e.memory.byteLength/65536);if(w>h&&d.grow(w-h),e.extensions.length>0){let _=r.extensions??[];n.loadedExtensions=await ue(_,e.extensions,l,o,c,u)}return new Uint8Array(d.buffer).set(e.memory),n.exports.qjs_set_runtime_and_context(e.runtimePtr,e.contextPtr),n.exports.__stack_pointer.value=e.stackPointer,a.applyLimits(n,r),n}static serializeSnapshot(e){let t=new TextEncoder,r=4,s=[],n=[];for(let d of e.extensions){let h=t.encode(d.name),w=t.encode(d.initFn);s.push(h),n.push(w),r+=4+h.length+4+4+4+w.length}let i=V+r+e.memory.byteLength,o=new ArrayBuffer(i),c=new DataView(o),u=new Uint8Array(o);c.setUint32(0,ee,!1),c.setUint8(4,te),c.setUint32(8,e.memory.byteLength,!0),c.setUint32(12,e.stackPointer,!0),c.setUint32(16,e.runtimePtr,!0),c.setUint32(20,e.contextPtr,!0);let l=V;c.setUint32(l,e.extensions.length,!0),l+=4;for(let d=0;d<e.extensions.length;d++){let h=e.extensions[d],w=s[d],g=n[d];c.setUint32(l,w.length,!0),l+=4,u.set(w,l),l+=w.length,c.setUint32(l,h.memoryBase,!0),l+=4,c.setUint32(l,h.tableBase,!0),l+=4,c.setUint32(l,g.length,!0),l+=4,u.set(g,l),l+=g.length}return u.set(e.memory,l),u}static deserializeSnapshot(e){if(e.length<V)throw new Error("Invalid snapshot: too small");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=t.getUint32(0,!1);if(r!==ee)throw new Error(`Invalid snapshot: bad magic (expected 0x${ee.toString(16)}, got 0x${r.toString(16)})`);let s=t.getUint8(4);if(s!==te&&s!==1)throw new Error(`Unsupported snapshot version: ${s} (expected ${te})`);let n=t.getUint32(8,!0),i=t.getUint32(12,!0),o=t.getUint32(16,!0),c=t.getUint32(20,!0),u=[],l=V;if(s>=2){let w=t.getUint32(24,!0),g=28,_=new TextDecoder;for(let I=0;I<w;I++){let O=t.getUint32(g,!0);g+=4;let x=_.decode(e.slice(g,g+O));g+=O;let E=t.getUint32(g,!0);g+=4;let v=t.getUint32(g,!0);g+=4;let S=t.getUint32(g,!0);g+=4;let k=_.decode(e.slice(g,g+S));g+=S,u.push({name:x,memoryBase:E,tableBase:v,initFn:k})}l=g}let d=l+n;if(e.length<d)throw new Error(`Invalid snapshot: expected ${d} bytes, got ${e.length}`);return{memory:e.slice(l,l+n),stackPointer:i,runtimePtr:o,contextPtr:c,extensions:u}}static normalizeOptions(e){if(!e)return{wasm:void 0};if(e instanceof WebAssembly.Module)return{wasm:e};if(typeof e=="object"&&("wasm"in e||"wasi"in e||"memoryLimit"in e||"maxStackSize"in e||"interruptHandler"in e||"onUnhandledRejection"in e||"moduleLoader"in e||"intrinsics"in e||"extensions"in e||"timezoneOffset"in e)){let t=e;if(t.maxStackSize!==void 0&&(!Number.isInteger(t.maxStackSize)||t.maxStackSize<0||t.maxStackSize>G))throw new RangeError(`maxStackSize must be an integer between 0 and ${G}`);return t}return{wasm:e}}static applyLimits(e,t){t.memoryLimit!==void 0&&e.exports.qjs_set_memory_limit(t.memoryLimit),t.maxStackSize!==void 0&&e.exports.qjs_set_max_stack_size(t.maxStackSize),t.interruptHandler&&(e.interruptHandler=t.interruptHandler,e.exports.qjs_set_interrupt_handler(1)),t.onUnhandledRejection&&(e.unhandledRejectionHandler=t.onUnhandledRejection,e.exports.qjs_set_promise_rejection_handler(1)),t.moduleLoader&&(e.moduleLoadHandler=t.moduleLoader.load,e.moduleNormalizeHandler=t.moduleLoader.normalize??null,e.exports.qjs_set_module_loader(1));let r=t.timezoneOffset;if(typeof r=="function")e.timezoneOffsetHandler=s=>-r(s)*60;else if(typeof r=="number"){let s=-r*60;e.timezoneOffsetHandler=()=>s}else e.timezoneOffsetHandler=s=>-new Date(s*1e3).getTimezoneOffset()*60}static async resolveModule(e){if(e instanceof WebAssembly.Module)return e;if(e)return WebAssembly.compile(e);throw new TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled `WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` and can be loaded via your environment's preferred mechanism (e.g. `fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).")}static async instantiate(e,t,r){let s=null,n=new Proxy({},{get(x,E){return s[E]}}),i=le(()=>s),o=r?r(n):void 0,c={...i,...o},u=(x,E,v,S,k)=>t.handleHostCall(x,E,v,S,k),l=()=>t.interruptHandler&&t.interruptHandler()?1:0,d=(x,E,v)=>{if(!t.unhandledRejectionHandler){t.exports.qjs_free_value(x),t.exports.qjs_free_value(E);return}let S=new m(t,x),k=new m(t,E);try{t.unhandledRejectionHandler(S,k,v!==0)}finally{S.dispose(),k.dispose()}},h=x=>{let E=t.newError(x instanceof Error?x:String(x));t.exports.qjs_throw(E.ptr),E.dispose()},w=(x,E)=>{if(typeof x=="string")return x;let v=x!==null&&typeof x=="object"&&typeof x.then=="function"?"a Promise":`type ${typeof x}`;throw new TypeError(`moduleLoader.${E} must synchronously return a string (got ${v}). Async module loading is not supported. Pre-fetch module sources instead (see the "ES Modules" section of the quickjs-wasi README).`)},g=(x,E)=>{if(!t.moduleNormalizeHandler){let k=t.readCString(E);return t.writeString(k).ptr}let v=t.readCString(x),S=t.readCString(E);try{let k=w(t.moduleNormalizeHandler(v,S),"normalize");return t.writeString(k).ptr}catch(k){return h(k),0}},_=(x,E)=>{if(!t.moduleLoadHandler)return 0;let v=t.readCString(x);try{let S=w(t.moduleLoadHandler(v),"load"),{ptr:k,len:B}=t.writeString(S);return new Uint32Array(t.exports.memory.buffer,E,1)[0]=B,k}catch(S){return h(S),0}},I=(x,E)=>{let v=Number(BigInt(x)<<32n|BigInt(E>>>0));return t.timezoneOffsetHandler?t.timezoneOffsetHandler(v):0},O=await WebAssembly.instantiate(e,{env:{host_call:u,host_interrupt:l,host_promise_rejection:d,host_module_normalize:g,host_module_load:_,host_get_timezone_offset:I},wasi_snapshot_preview1:c});return s=O.exports.memory,{instance:O,wasiBuiltins:i,wasiUserOverrides:o,memoryProxy:n}}handleHostCall(e,t,r,s,n){let i=this.decoder.decode(new Uint8Array(this.exports.memory.buffer,e,t)),o=this.hostCallbacks.get(i);if(!o){let l=this.newError(`Host callback "${i}" is not registered: it was unregistered, its ephemeral function handle was disposed, or it was never re-registered after a snapshot restore.`);return this.exports.qjs_throw(l.ptr),l.dispose(),0}let c=new m(this,r,!1,!0),u=[];if(s>0&&n!==0){let l=new DataView(this.exports.memory.buffer);for(let d=0;d<s;d++){let h=l.getUint32(n+d*4,!0);u.push(new m(this,h,!1,!0))}}try{let l=o.call(c,...u);return this.exports.qjs_dup_value(l.ptr)}catch(l){let d=this.newError(l instanceof Error?l:String(l));return this.exports.qjs_throw(d.ptr),d.dispose(),0}}writeString(e){let t=ke(e),r=this.exports.wasm_malloc(t.length+1);if(r===0)throw new Error("wasm_malloc failed");let s=new Uint8Array(this.exports.memory.buffer);return s.set(t,r),s[r+t.length]=0,{ptr:r,len:t.length}}readCString(e){let t=new Uint8Array(this.exports.memory.buffer),r=e;for(;t[r]!==0;)r++;return this.decoder.decode(t.slice(e,r))}throwIfException(e){if(this.exports.qjs_is_exception(e.ptr)!==0){let t=this.getException();throw e.dispose(),this._ownedHandles.add(t),new R(t)}return e}evalCode(e,t="<eval>",r=0){this.assertNotDisposed();let s=this.writeString(e),n=this.writeString(t),i=this.exports.qjs_eval(s.ptr,s.len,n.ptr,r);return this.exports.wasm_free(s.ptr),this.exports.wasm_free(n.ptr),this.throwIfException(new m(this,i))}compile(e,t="<compile>",r=0,s=0){this.assertNotDisposed();let n=this.writeString(e),i=this.writeString(t),o=this.exports.wasm_malloc(4),c=this.exports.qjs_compile(n.ptr,n.len,i.ptr,r,s,o);if(this.exports.wasm_free(n.ptr),this.exports.wasm_free(i.ptr),c===0){this.exports.wasm_free(o);let d=this.getException();throw new Error(`Compilation error: ${d.toString()}`)}let u=new Uint32Array(this.exports.memory.buffer,o,1)[0];this.exports.wasm_free(o);let l=new Uint8Array(this.exports.memory.buffer,c,u).slice();return this.exports.wasm_free(c),l}evalBytecode(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.byteLength);new Uint8Array(this.exports.memory.buffer,t,e.byteLength).set(e);let r=this.exports.qjs_eval_bytecode(t,e.byteLength);return this.exports.wasm_free(t),this.throwIfException(new m(this,r))}executePendingJobs(){this.assertNotDisposed();let e=0;for(;this.exports.qjs_is_job_pending();){if(this.exports.qjs_execute_pending_job()<0){let r=this.getException();throw new Error(`Job execution error: ${r.toString()}`)}e++}return e}runGC(){this.assertNotDisposed(),this.exports.qjs_run_gc()}get gcThreshold(){return this.assertNotDisposed(),this.exports.qjs_get_gc_threshold()}set gcThreshold(e){this.assertNotDisposed(),this.exports.qjs_set_gc_threshold(e)}getMemoryUsage(){this.assertNotDisposed();let e=this.exports.wasm_malloc(26*8);this.exports.qjs_compute_memory_usage(e);let t=new BigInt64Array(this.exports.memory.buffer,e,26),r={mallocSize:Number(t[0]),mallocLimit:Number(t[1]),memoryUsedSize:Number(t[2]),mallocCount:Number(t[3]),memoryUsedCount:Number(t[4]),atomCount:Number(t[5]),atomSize:Number(t[6]),strCount:Number(t[7]),strSize:Number(t[8]),objCount:Number(t[9]),objSize:Number(t[10]),propCount:Number(t[11]),propSize:Number(t[12]),shapeCount:Number(t[13]),shapeSize:Number(t[14]),jsFuncCount:Number(t[15]),jsFuncSize:Number(t[16]),jsFuncCodeSize:Number(t[17]),jsFuncPc2lineCount:Number(t[18]),jsFuncPc2lineSize:Number(t[19]),cFuncCount:Number(t[20]),arrayCount:Number(t[21]),fastArrayCount:Number(t[22]),fastArrayElements:Number(t[23]),binaryObjectCount:Number(t[24]),binaryObjectSize:Number(t[25])};return this.exports.wasm_free(e),r}getGlobal(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_global())}newString(e){this.assertNotDisposed();let{ptr:t,len:r}=this.writeString(e),s=this.exports.qjs_new_string(t,r);return this.exports.wasm_free(t),new m(this,s)}newNumber(e){return this.assertNotDisposed(),new m(this,this.exports.qjs_new_number(e))}newBigInt(e){this.assertNotDisposed();let t=Number(e&0xffffffffn),r=Number(e>>32n&0xffffffffn);return new m(this,this.exports.qjs_new_big_int64(t,r))}newObject(){return this.assertNotDisposed(),new m(this,this.exports.qjs_new_object())}newArray(){return this.assertNotDisposed(),new m(this,this.exports.qjs_new_array())}newSymbolFor(e){this.assertNotDisposed();let{ptr:t,len:r}=this.writeString(e),s=new m(this,this.exports.qjs_new_symbol(t,r,1));return this.exports.wasm_free(t),s}newArrayBuffer(e){this.assertNotDisposed();let t=e instanceof ArrayBuffer?new Uint8Array(e):e,r=this.exports.wasm_malloc(t.length);if(r===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(t,r);let s=new m(this,this.exports.qjs_new_array_buffer(r,t.length));return this.exports.wasm_free(r),s}newUint8Array(e){this.assertNotDisposed();let t=this.exports.wasm_malloc(e.length);if(t===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(e,t);let r=new m(this,this.exports.qjs_new_uint8_array(t,e.length));return this.exports.wasm_free(t),r}getUndefined(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_undefined())}getNull(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_null())}getTrue(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_true())}getFalse(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_false())}newFunction(e,t){if(this.assertNotDisposed(),this.hostCallbacks.has(e))throw new Error(`Host callback with name "${e}" is already registered`);this.hostCallbacks.set(e,t);let{ptr:r,len:s}=this.writeString(e),n=this.exports.qjs_new_host_function(r,s,0);return this.exports.wasm_free(r),new m(this,n)}withScope(e){this.assertNotDisposed();let t=this._activeScope,r=new Set;this._activeScope=r;let s={escape:n=>(r.delete(n),t?.add(n),n)};try{return e(s)}finally{this._activeScope=t;for(let n of r)n.dispose()}}exportHandle(e){if(this.assertNotDisposed(),e.vm!==this)throw new Error("exportHandle: handle belongs to a different VM");if(e.disposed)throw new Error("exportHandle: handle is disposed");if(e._isBorrowed)throw new Error("exportHandle: cannot export a borrowed handle (host-callback this/argument); its box is freed when the callback returns. dup() it and export the duplicate.");return e.ptr}importHandle(e){if(this.assertNotDisposed(),!Number.isInteger(e)||e<=0||e>=this.exports.memory.buffer.byteLength)throw new Error(`importHandle: invalid token ${e}`);return new m(this,this.exports.qjs_dup_value(e))}newEphemeralFunction(e){this.assertNotDisposed();let t=`__ephemeral:${this.nextInternalId++}`;this.hostCallbacks.set(t,e);let{ptr:r,len:s}=this.writeString(t),n=this.exports.qjs_new_host_function(r,s,0);this.exports.wasm_free(r);let i=new m(this,n);return i._onDispose=()=>{this.hostCallbacks.delete(t)},i}unregisterHostCallback(e){return this.hostCallbacks.delete(e)}newInternalFunction(e,t){this.hostCallbacks.set(e,t);let{ptr:r,len:s}=this.writeString(e),n=this.exports.qjs_new_host_function(r,s,0);return this.exports.wasm_free(r),new m(this,n)}newPromise(){this.assertNotDisposed();let e=this.exports.wasm_malloc(4),t=this.exports.wasm_malloc(4),r=this.exports.qjs_new_promise(e,t),s=new DataView(this.exports.memory.buffer),n=s.getUint32(e,!0),i=s.getUint32(t,!0);this.exports.wasm_free(e),this.exports.wasm_free(t);let o=new m(this,r),c=new m(this,n),u=new m(this,i),l=this;l._ownedHandles.add(c),l._ownedHandles.add(u);let d=null;return{handle:o,get settled(){if(!d){let h;d=new Promise(_=>{h=_});let w=`__settle:${l.nextInternalId++}`,g=l.newInternalFunction(w,()=>(h(),l.hostCallbacks.delete(w),l.undefined));l.promiseThenRaw(o,g,g).dispose(),g.dispose()}return d},resolve(h){l.callFunctionRaw(c,l.undefined,h).dispose(),l._ownedHandles.delete(c),c.dispose()},reject(h){l.callFunctionRaw(u,l.undefined,h).dispose(),l._ownedHandles.delete(u),u.dispose()}}}resolvePromise(e){if(this.assertNotDisposed(),!this.exports.qjs_is_promise(e.ptr))return Promise.resolve({value:e.dup()});let t=this.exports.qjs_promise_state(e.ptr);return t===1?Promise.resolve({value:new m(this,this.exports.qjs_promise_result(e.ptr))}):t===2?Promise.resolve({error:new m(this,this.exports.qjs_promise_result(e.ptr))}):new Promise(r=>{let s=this.nextInternalId++,n=`__onFulfilled:${s}`,i=`__onRejected:${s}`,o=this.newInternalFunction(n,(...u)=>{let l=u[0]?.dup()??this.undefined;return this.hostCallbacks.delete(n),this.hostCallbacks.delete(i),r({value:l}),this.undefined}),c=this.newInternalFunction(i,(...u)=>{let l=u[0]?.dup()??this.undefined;return this.hostCallbacks.delete(n),this.hostCallbacks.delete(i),r({error:l}),this.undefined});this.promiseThenRaw(e,o,c).dispose(),o.dispose(),c.dispose()})}promiseThenRaw(e,t,r){return new m(this,this.exports.qjs_promise_then(e.ptr,t.ptr,r.ptr))}markPromiseHandled(e){this.assertNotDisposed(),this.exports.qjs_promise_mark_as_handled(e.ptr)}callFunction(e,t,...r){return this.throwIfException(this.callFunctionRaw(e,t,...r))}construct(e,...t){this.assertNotDisposed();let r=t.length,s=0;if(r>0){s=this.exports.wasm_malloc(r*4);let i=new DataView(this.exports.memory.buffer);for(let o=0;o<r;o++)i.setUint32(s+o*4,t[o].ptr,!0)}let n=this.exports.qjs_call_constructor(e.ptr,r,s);return s&&this.exports.wasm_free(s),this.throwIfException(new m(this,n))}callFunctionRaw(e,t,...r){this.assertNotDisposed();let s=r.length,n=0;if(s>0){n=this.exports.wasm_malloc(s*4);let o=new DataView(this.exports.memory.buffer);for(let c=0;c<s;c++)o.setUint32(n+c*4,r[c].ptr,!0)}let i=this.exports.qjs_call(e.ptr,t.ptr,s,n);return n&&this.exports.wasm_free(n),new m(this,i)}setProp(e,t,r){if(this.assertNotDisposed(),typeof t=="string"){let{ptr:s}=this.writeString(t);this.exports.qjs_set_prop_string(e.ptr,s,r.ptr),this.exports.wasm_free(s)}else this.exports.qjs_set_prop_value(e.ptr,t.ptr,r.ptr)}defineProp(e,t,r,s){this.assertNotDisposed();let n=0;if(s?.configurable&&(n|=1),s?.writable&&(n|=2),s?.enumerable&&(n|=4),typeof t=="string"){let{ptr:i}=this.writeString(t);this.exports.qjs_define_prop_string(e.ptr,i,r.ptr,n),this.exports.wasm_free(i)}else this.exports.qjs_define_prop_value(e.ptr,t.ptr,r.ptr,n)}getProp(e,t){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_prop_value(e.ptr,t.ptr))}getException(){return this.assertNotDisposed(),new m(this,this.exports.qjs_get_exception())}newError(e){this.assertNotDisposed();let t=this.exports.qjs_new_error(),r=new m(this,t);if(typeof e=="string"){let s=this.newString(e);r.setProp("message",s),s.dispose()}else{let s=this.newString(e.message);if(r.setProp("message",s),s.dispose(),e.name){let n=this.newString(e.name);r.setProp("name",n),n.dispose()}if(e.stack){let n=this.newString(e.stack);r.setProp("stack",n),n.dispose()}}return r}typeof(e){this.assertNotDisposed();let t=this.exports;return t.qjs_is_undefined(e.ptr)?"undefined":t.qjs_is_null(e.ptr)?"object":t.qjs_is_bool(e.ptr)?"boolean":t.qjs_is_number(e.ptr)?"number":t.qjs_is_big_int(e.ptr)?"bigint":t.qjs_is_string(e.ptr)?"string":t.qjs_is_symbol(e.ptr)?"symbol":t.qjs_is_function(e.ptr)?"function":t.qjs_is_object(e.ptr)?"object":"unknown"}dump(e){return this.assertNotDisposed(),this._dump(e,new Map)}_dump(e,t){let r=this.exports;if(!r.qjs_is_undefined(e.ptr)){if(r.qjs_is_null(e.ptr))return null;if(r.qjs_is_bool(e.ptr))return r.qjs_get_bool(e.ptr)!==0;if(r.qjs_is_number(e.ptr))return r.qjs_get_float64(e.ptr);if(r.qjs_is_string(e.ptr))return e.toString();if(r.qjs_is_big_int(e.ptr))return e.toBigInt();if(r.qjs_is_symbol(e.ptr)){let s=r.wasm_malloc(4),n=r.qjs_get_symbol_description(e.ptr,s),o=new DataView(r.memory.buffer).getUint32(s,!0);if(r.wasm_free(s),n===1){let c=new m(this,o),u=c.toString();return c.dispose(),Symbol.for(u)}else if(n===2){new m(this,o).dispose();return}return}if(r.qjs_is_array_buffer(e.ptr))return e.toArrayBuffer();if(r.qjs_is_exception(e.ptr)){let s=this.getException(),n=s.toString();return s.dispose(),new Error(n)}if(!r.qjs_is_function(e.ptr)){if(r.qjs_is_object(e.ptr)){let s=r.qjs_get_value_ptr(e.ptr);if(s){let n=t.get(s);if(n!==void 0)return n}}if(r.qjs_is_object(e.ptr)){let s=r.wasm_malloc(4),n=r.wasm_malloc(4),i=r.wasm_malloc(4),o=r.qjs_get_typed_array_buffer(e.ptr,s,n,i),c=new m(this,o);if(r.qjs_is_exception(c.ptr)===0){let u=new DataView(r.memory.buffer),l=u.getUint32(s,!0),d=u.getUint32(n,!0),h=u.getUint32(i,!0);r.wasm_free(s),r.wasm_free(n),r.wasm_free(i);let w=r.wasm_malloc(4),g=r.qjs_get_array_buffer(c.ptr,w);if(r.wasm_free(w),c.dispose(),g!==0){let _=new Uint8Array(r.memory.buffer,g+l,d).slice();switch(h){case 1:return _;case 2:return new Uint16Array(_.buffer);case 4:return new Uint32Array(_.buffer);case 8:return new Float64Array(_.buffer);default:return _}}}else c.dispose(),r.wasm_free(s),r.wasm_free(n),r.wasm_free(i)}if(r.qjs_is_array(e.ptr)){let s=e.getProp("length"),n=r.qjs_get_float64(s.ptr);s.dispose();let i=[],o=r.qjs_get_value_ptr(e.ptr);o&&t.set(o,i);for(let c=0;c<n;c++){let u=r.qjs_get_prop_uint32(e.ptr,c),l=new m(this,u);i.push(this._dump(l,t)),l.dispose()}return i}if(r.qjs_is_error(e.ptr)){let s=e.getProp("name"),n=e.getProp("message"),i=e.getProp("stack"),o=s.isUndefined?"Error":s.toString(),c=n.isUndefined?"":n.toString(),u=i.isUndefined?void 0:i.toString();s.dispose(),n.dispose(),i.dispose();let l=new Error(c);return l.name=o,u!==void 0&&(l.stack=u),l}if(r.qjs_is_object(e.ptr)){let s=r.qjs_get_own_property_names(e.ptr),n=new m(this,s);if(r.qjs_is_exception(n.ptr)!==0)return n.dispose(),{};let i=n.getProp("length"),o=r.qjs_get_float64(i.ptr);i.dispose();let c={},u=r.qjs_get_value_ptr(e.ptr);u&&t.set(u,c);for(let l=0;l<o;l++){let d=r.qjs_get_prop_uint32(n.ptr,l),h=new m(this,d),w=h.toString();h.dispose();let g=e.getProp(w);c[w]=this._dump(g,t),g.dispose()}return n.dispose(),c}}}}hostToHandle(e){if(this.assertNotDisposed(),e===void 0)return this.undefined;if(e===null)return this.null;if(e===!0)return this.true;if(e===!1)return this.false;if(typeof e=="number")return this.newNumber(e);if(typeof e=="string")return this.newString(e);if(typeof e=="bigint")return this.newBigInt(e);if(typeof e=="symbol"){let t=Symbol.keyFor(e);if(t!==void 0)return this.newSymbolFor(t);throw new Error("Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.")}if(e instanceof Promise){let t=this.newPromise();return e.then(r=>{t.resolve(this.hostToHandle(r)),this.executePendingJobs()},r=>{t.reject(this.hostToHandle(r)),this.executePendingJobs()}),t.handle}if(e instanceof Error)return this.newError(e);if(e instanceof ArrayBuffer)return this.newArrayBuffer(e);if(e instanceof Uint8Array)return this.newUint8Array(e);if(ArrayBuffer.isView(e))return this.newArrayBuffer(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e)){let t=this.newArray();for(let r=0;r<e.length;r++){let s=this.hostToHandle(e[r]);this.exports.qjs_set_prop_uint32(t.ptr,r,s.ptr),s.dispose()}return t}if(typeof e=="object"&&e!==null){let t=this.newObject();for(let[r,s]of Object.entries(e)){let n=this.hostToHandle(s);t.setProp(r,n),n.dispose()}return t}return this.undefined}snapshot(){return this.assertNotDisposed(),{memory:new Uint8Array(this.exports.memory.buffer).slice(),stackPointer:this.exports.__stack_pointer.value,runtimePtr:this.exports.qjs_get_runtime_ptr(),contextPtr:this.exports.qjs_get_context_ptr(),extensions:this.loadedExtensions.map(e=>({name:e.name,memoryBase:e.memoryBase,tableBase:e.tableBase,initFn:e.initFn}))}}registerHostCallback(e,t){this.hostCallbacks.set(e,t)}dispose(){this.disposed||(this.disposed=!0,this._global=null,this._undefined=null,this._null=null,this._true=null,this._false=null,this._ownedHandles.clear(),this.hostCallbacks.clear(),this._activeScope=null,this.exports=null,this.instance=null,this.module=null)}[Symbol.dispose](){this.dispose()}assertNotDisposed(){if(this.disposed)throw new Error("QuickJS instance has been disposed")}_getExports(){return this.exports}_getMemory(){return this.exports.memory}_writeString(e){return this.writeString(e)}_readCString(e){return this.readCString(e)}};function J(a){return a.includes("\0")||de.test(a)}var ve=new TextDecoder,je=new TextEncoder,de=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;function ke(a){if(!de.test(a))return je.encode(a);let e=[];for(let t=0;t<a.length;t++){let r=a.charCodeAt(t);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r>=55296&&r<=56319&&t+1<a.length){let s=a.charCodeAt(t+1);if(s>=56320&&s<=57343){let n=65536+(r-55296<<10)+(s-56320);e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63),t++;continue}e.push(224|r>>12,128|r>>6&63,128|r&63)}else e.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(e)}function Pe(a){let e=!1;for(let s=0;s<a.length-1;s++)if(a[s]===237&&a[s+1]>=160&&a[s+1]<=191){e=!0;break}if(!e)return ve.decode(a);let t="",r=0;for(;r<a.length;){let s=a[r];if(s<128)t+=String.fromCharCode(s),r+=1;else if(s<224)t+=String.fromCharCode((s&31)<<6|a[r+1]&63),r+=2;else if(s<240)t+=String.fromCharCode((s&15)<<12|(a[r+1]&63)<<6|a[r+2]&63),r+=3;else{let n=(s&7)<<18|(a[r+1]&63)<<12|(a[r+2]&63)<<6|a[r+3]&63;t+=String.fromCodePoint(n),r+=4}}return t}var R=class extends Error{handle;#e;#t;#r;constructor(e){let t={stack:[],error:void 0,hasError:!1};try{super(),this.handle=e,delete this.stack;let r=H(t,e.getProp("message"),!1);this.#e=e.getProp("name").consume(s=>s.isUndefined?"Error":s.toString()),this.#t=r.isUndefined?e.toString():r.toString(),this.#r=e.getProp("stack").consume(s=>s.isUndefined?void 0:s.toString())}catch(r){t.error=r,t.hasError=!0}finally{F(t)}}get name(){return this.#e}set name(e){this.#e=e}get message(){return this.#t}set message(e){this.#t=e}get stack(){return this.#r}set stack(e){this.#r=e}dispose(){this.handle.dispose()}[Symbol.dispose](){this.handle.dispose()}},m=class a{vm;ptr;disposed_=!1;singleton;borrowed;_onDispose;constructor(e,t,r=!1,s=!1){this.vm=e,this.ptr=t,this.singleton=r,this.borrowed=s,!r&&!s&&e._activeScope?.add(this)}get _isBorrowed(){return this.borrowed}get disposed(){return this.disposed_}get isUndefined(){return this.vm._getExports().qjs_is_undefined(this.ptr)!==0}get isNull(){return this.vm._getExports().qjs_is_null(this.ptr)!==0}get isBool(){return this.vm._getExports().qjs_is_bool(this.ptr)!==0}get isNumber(){return this.vm._getExports().qjs_is_number(this.ptr)!==0}get isString(){return this.vm._getExports().qjs_is_string(this.ptr)!==0}get isSymbol(){return this.vm._getExports().qjs_is_symbol(this.ptr)!==0}get isBigInt(){return this.vm._getExports().qjs_is_big_int(this.ptr)!==0}get isObject(){return this.vm._getExports().qjs_is_object(this.ptr)!==0}get isArray(){return this.vm._getExports().qjs_is_array(this.ptr)!==0}get isFunction(){return this.vm._getExports().qjs_is_function(this.ptr)!==0}get isError(){return this.vm._getExports().qjs_is_error(this.ptr)!==0}get isPromise(){return this.vm._getExports().qjs_is_promise(this.ptr)!==0}get isArrayBuffer(){return this.vm._getExports().qjs_is_array_buffer(this.ptr)!==0}get isProxy(){return this.vm._getExports().qjs_is_proxy(this.ptr)!==0}get isMap(){return this.vm._getExports().qjs_is_map(this.ptr)!==0}get isSet(){return this.vm._getExports().qjs_is_set(this.ptr)!==0}get isDate(){return this.vm._getExports().qjs_is_date(this.ptr)!==0}get isRegExp(){return this.vm._getExports().qjs_is_regexp(this.ptr)!==0}get isWeakRef(){return this.vm._getExports().qjs_is_weak_ref(this.ptr)!==0}get isWeakMap(){return this.vm._getExports().qjs_is_weak_map(this.ptr)!==0}get isWeakSet(){return this.vm._getExports().qjs_is_weak_set(this.ptr)!==0}get isDataView(){return this.vm._getExports().qjs_is_data_view(this.ptr)!==0}get identity(){return this.vm._getExports().qjs_get_value_ptr(this.ptr)}toBoolean(){return this.vm._getExports().qjs_get_bool(this.ptr)!==0}get classId(){return this.vm._getExports().qjs_get_class_id(this.ptr)}get className(){let e=new a(this.vm,this.vm._getExports().qjs_get_class_name(this.ptr));if(this.vm._getExports().qjs_is_exception(e.ptr)!==0)throw e.dispose(),new R(this.vm.getException());try{return e.isUndefined?void 0:e.toString()}finally{e.dispose()}}get promiseState(){return this.vm._getExports().qjs_promise_state(this.ptr)}get typeof(){return this.vm.typeof(this)}get length(){let e=this.getProp("length"),t=e.toNumber();return e.dispose(),t}get constructorName(){let e=this.getProp("constructor");if(e.isUndefined||e.isNull){e.dispose();return}let t=e.getProp("name");if(e.dispose(),t.isUndefined||t.isNull){t.dispose();return}let r=t.toString();return t.dispose(),r}keys(){let e=this.vm._getExports(),t=e.qjs_get_own_property_names(this.ptr),r=new a(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),n=e.qjs_get_float64(s.ptr);s.dispose();let i=[];for(let o=0;o<n;o++){let c=e.qjs_get_prop_uint32(r.ptr,o),u=new a(this.vm,c);i.push(u.toString()),u.dispose()}return r.dispose(),i}getOwnPropertyNames(){let e=this.vm._getExports(),t=e.qjs_get_own_property_names_all(this.ptr),r=new a(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),n=e.qjs_get_float64(s.ptr);s.dispose();let i=[];for(let o=0;o<n;o++){let c=e.qjs_get_prop_uint32(r.ptr,o),u=new a(this.vm,c);i.push(u.toString()),u.dispose()}return r.dispose(),i}getOwnPropertyKeys(){let e=this.vm._getExports(),t=e.qjs_get_own_property_keys(this.ptr),r=new a(this.vm,t);if(e.qjs_is_exception(r.ptr)!==0)return r.dispose(),[];let s=r.getProp("length"),n=e.qjs_get_float64(s.ptr);s.dispose();let i=[];for(let o=0;o<n;o++){let c=e.qjs_get_prop_uint32(r.ptr,o),u=new a(this.vm,c);u.isSymbol?i.push(u):(i.push(u.toString()),u.dispose())}return r.dispose(),i}getOwnPropertyDescriptor(e){let t={stack:[],error:void 0,hasError:!1};try{let r=this.vm._getExports(),s,n;typeof e=="string"?(s=this.vm.newString(e),n=s.ptr):n=e.ptr;let i=r.qjs_get_own_property_descriptor(this.ptr,n);if(s?.dispose(),i===0)return;let o=H(t,new a(this.vm,i),!1);if(r.qjs_is_exception(o.ptr)!==0)throw new R(this.vm.getException());let c=o.getProp("enumerable").consume(l=>r.qjs_get_bool(l.ptr)!==0),u=o.getProp("configurable").consume(l=>r.qjs_get_bool(l.ptr)!==0);return o.hasOwnProperty("value")?{value:o.getProp("value"),writable:o.getProp("writable").consume(l=>r.qjs_get_bool(l.ptr)!==0),enumerable:c,configurable:u}:{get:o.getProp("get"),set:o.getProp("set"),enumerable:c,configurable:u}}catch(r){t.error=r,t.hasError=!0}finally{F(t)}}hasOwnProperty(e){if(J(e)){let s={stack:[],error:void 0,hasError:!1};try{let n=H(s,this.vm.newString(e),!1);return this.vm._getExports().qjs_has_own_property_value(this.ptr,n.ptr)===1}catch(n){s.error=n,s.hasError=!0}finally{F(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_has_own_property(this.ptr,t);return this.vm._getExports().wasm_free(t),r===1}propertyIsEnumerable(e){if(J(e)){let s={stack:[],error:void 0,hasError:!1};try{let n=H(s,this.vm.newString(e),!1);return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr,n.ptr)===1}catch(n){s.error=n,s.hasError=!0}finally{F(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_property_is_enumerable(this.ptr,t);return this.vm._getExports().wasm_free(t),r===1}getPrototypeOf(){let e=this.vm._getExports().qjs_get_prototype_of(this.ptr);return new a(this.vm,e)}getProxyTarget(){let e=this.vm._getExports().qjs_get_proxy_target(this.ptr),t=new a(this.vm,e);if(this.vm._getExports().qjs_is_exception(t.ptr)!==0)throw t.dispose(),new R(this.vm.getException());return t}getProxyHandler(){let e=this.vm._getExports().qjs_get_proxy_handler(this.ptr),t=new a(this.vm,e);if(this.vm._getExports().qjs_is_exception(t.ptr)!==0)throw t.dispose(),new R(this.vm.getException());return t}getProp(e){if(J(e)){let s={stack:[],error:void 0,hasError:!1};try{let n=H(s,this.vm.newString(e),!1);return this.vm.getProp(this,n)}catch(n){s.error=n,s.hasError=!0}finally{F(s)}}let{ptr:t}=this.vm._writeString(e),r=this.vm._getExports().qjs_get_prop_string(this.ptr,t);return this.vm._getExports().wasm_free(t),new a(this.vm,r)}setProp(e,t){if(J(e)){let s={stack:[],error:void 0,hasError:!1};try{let n=H(s,this.vm.newString(e),!1);this.vm.setProp(this,n,t);return}catch(n){s.error=n,s.hasError=!0}finally{F(s)}}let{ptr:r}=this.vm._writeString(e);this.vm._getExports().qjs_set_prop_string(this.ptr,r,t.ptr),this.vm._getExports().wasm_free(r)}defineProp(e,t,r){let s=0;if(r?.configurable&&(s|=1),r?.writable&&(s|=2),r?.enumerable&&(s|=4),typeof e=="string"){if(J(e)){let i={stack:[],error:void 0,hasError:!1};try{let o=H(i,this.vm.newString(e),!1);this.vm._getExports().qjs_define_prop_value(this.ptr,o.ptr,t.ptr,s);return}catch(o){i.error=o,i.hasError=!0}finally{F(i)}}let{ptr:n}=this.vm._writeString(e);this.vm._getExports().qjs_define_prop_string(this.ptr,n,t.ptr,s),this.vm._getExports().wasm_free(n)}else this.vm._getExports().qjs_define_prop_value(this.ptr,e.ptr,t.ptr,s)}toNumber(){return this.vm._getExports().qjs_get_float64(this.ptr)}toBigInt(){let e=this.vm._getExports(),t=e.wasm_malloc(4),r=e.wasm_malloc(4);if(e.qjs_get_big_int64(this.ptr,t,r)!==0)throw e.wasm_free(t),e.wasm_free(r),new Error("Failed to convert value to BigInt");let n=new DataView(e.memory.buffer),i=n.getUint32(t,!0),o=n.getInt32(r,!0);return e.wasm_free(t),e.wasm_free(r),BigInt(o)<<32n|BigInt(i)}toArrayBuffer(){let e=this.vm._getExports(),t=e.wasm_malloc(4);if(e.qjs_is_array_buffer(this.ptr)){let w=e.qjs_get_array_buffer(this.ptr,t);if(w===0)throw e.wasm_free(t),new Error("Failed to get ArrayBuffer data");let _=new DataView(e.memory.buffer).getUint32(t,!0);return e.wasm_free(t),new Uint8Array(e.memory.buffer,w,_).slice().buffer}e.wasm_free(t);let r=e.wasm_malloc(4),s=e.wasm_malloc(4),n=e.wasm_malloc(4),i=e.qjs_get_typed_array_buffer(this.ptr,r,s,n),o=new a(this.vm,i);if(this.vm._getExports().qjs_is_exception(o.ptr)!==0)throw o.dispose(),e.wasm_free(r),e.wasm_free(s),e.wasm_free(n),new Error("Value is not an ArrayBuffer or typed array");let c=new DataView(e.memory.buffer),u=c.getUint32(r,!0),l=c.getUint32(s,!0);e.wasm_free(r),e.wasm_free(s),e.wasm_free(n);let d=e.wasm_malloc(4),h=e.qjs_get_array_buffer(o.ptr,d);if(e.wasm_free(d),o.dispose(),h===0)throw new Error("Failed to get ArrayBuffer data from typed array");return new Uint8Array(e.memory.buffer,h+u,l).slice().buffer}toUint8Array(){return new Uint8Array(this.toArrayBuffer())}toString(){let e=this.vm._getExports(),t=e.wasm_malloc(4);if(t===0)throw new Error("wasm_malloc failed");try{let r=e.qjs_get_string_len(this.ptr,t);if(r===0)return"<null>";let s=new DataView(e.memory.buffer).getUint32(t,!0),n=new Uint8Array(e.memory.buffer,r,s),i=Pe(n);return e.qjs_free_cstring(r),i}finally{e.wasm_free(t)}}consume(e){try{return e(this)}finally{this.dispose()}}dup(){return new a(this.vm,this.vm._getExports().qjs_dup_value(this.ptr))}dispose(){if(!(this.singleton||this.borrowed)&&!this.disposed_){this.disposed_=!0,this._onDispose?.(),this._onDispose=void 0;let e=this.vm._getExports();e&&e.qjs_free_value(this.ptr)}}[Symbol.dispose](){this.dispose()}};var re=["image/png","image/jpeg","image/gif","image/webp"],Me=new Set(re);var Fe=Object.freeze({modelOnly:!0}),Be=Object.freeze({defaultDeferred:!0}),U=Object.freeze({codeBytes:128*1024,memoryBytes:128*1024*1024,workers:4,workerWaitMs:6e4,calls:128,concurrency:4,argumentBytes:256*1024,summaryArgumentBytes:4*1024,resultBytes:1024*1024,totalResultBytes:8*1024*1024,outputBytes:1024*1024,outputItems:1e3,images:8,imageBytes:8*1024*1024,minOutputTokens:200,defaultOutputTokens:1e4,maxOutputTokens:16e3,cellTimeoutMs:30*6e4,defaultYieldMs:1e4,maxYieldMs:6e4,maxSyncMs:6e4,searches:256,cleanupMs:5e3}),fe=Object.freeze({keys:256,keyChars:200,totalBytes:4*1024*1024});var Q=re,me={calls:"Tool call limit exceeded",result:"Cumulative tool result limit exceeded",output:"Script output limit exceeded",images:"Script image limit exceeded",searches:"Tool search limit exceeded"};var he=String.raw`
3
+ (bridge, namesJSON, directNamesJSON, catalogJSON, storeJSON, storeError, namespacesJSON) => {
4
+ 'use strict';
5
+ const parse = JSON.parse;
6
+ const stringify = JSON.stringify;
7
+ const create = Object.create;
8
+ const freeze = Object.freeze;
9
+ const define = Object.defineProperty;
10
+ const hasOwn = Object.hasOwn;
11
+ const PromiseClass = Promise;
12
+ const ErrorClass = Error;
13
+ const StringClass = String;
14
+ const ProxyClass = Proxy;
15
+ const pending = create(null);
16
+ const rejections = new Map();
17
+ const tools = create(null);
18
+ let sequence = 0;
19
+ const format = value => {
20
+ if (typeof value === 'string') return value;
21
+ return stringify(value, (_key, item) => item instanceof ErrorClass ? {
22
+ name: item.name, message: item.message,
23
+ ...(item.kind === undefined ? {} : {kind: item.kind}),
24
+ ...(item.toolName === undefined ? {} : {toolName: item.toolName}),
25
+ ...(item.callId === undefined ? {} : {callId: item.callId})
26
+ } : item);
27
+ };
28
+ const text = value => {
29
+ const rendered = format(value);
30
+ bridge('output', rendered ?? StringClass(value));
31
+ };
32
+ const names = parse(namesJSON);
33
+ const direct = create(null);
34
+ for (const name of parse(directNamesJSON)) direct[name] = true;
35
+ const request = (kind, prepare) => {
36
+ // Count attempts before serialization, even when the caller catches an error.
37
+ const id = ++sequence;
38
+ return new PromiseClass((resolve, reject) => {
39
+ bridge('attempt', id);
40
+ const payload = prepare();
41
+ pending[id] = { resolve, reject };
42
+ try {
43
+ bridge(kind, id, ...payload);
44
+ } catch (error) {
45
+ delete pending[id];
46
+ reject(error);
47
+ }
48
+ });
49
+ };
50
+ const invoke = (name, args) => request('call', () => {
51
+ const encoded = stringify(args);
52
+ if (encoded === undefined) throw new ErrorClass('Tool arguments must be a JSON object');
53
+ return [name, encoded];
54
+ });
55
+ for (const name of names) define(tools, name, { value: freeze(args => invoke(name, args)), enumerable: true });
56
+ const descriptions = create(null);
57
+ for (const entry of parse(catalogJSON)) {
58
+ if (hasOwn(tools, entry.name)) descriptions[entry.name] = entry.description;
59
+ }
60
+ const allTools = [];
61
+ const toolEntries = create(null);
62
+ for (const name of names) {
63
+ if (!hasOwn(tools, name)) continue;
64
+ toolEntries[name] = freeze({ name, description: descriptions[name] ?? '' });
65
+ allTools.push(toolEntries[name]);
66
+ }
67
+ define(globalThis, 'ALL_TOOLS', { value: freeze(allTools) });
68
+ define(globalThis, 'describeTool', { value: freeze(async name => {
69
+ if (typeof name !== 'string') throw new ErrorClass('describeTool(name) expects a tool name');
70
+ return hasOwn(tools, name) ? descriptions[name] ?? '' : undefined;
71
+ }) });
72
+ // Server names may be written as "docs", "mcp__docs" or with - and _ swapped.
73
+ const namespaceKey = name => StringClass(name).replace(/^mcp__/, '').toLowerCase().replace(/-/g, '_');
74
+ const namespaces = new Map();
75
+ for (const entry of parse(namespacesJSON)) namespaces.set(namespaceKey(entry.name), entry);
76
+ define(globalThis, 'describeNamespace', { value: freeze(async name => {
77
+ if (typeof name !== 'string') throw new ErrorClass('describeNamespace(name) expects a server name');
78
+ const entry = namespaces.get(namespaceKey(name));
79
+ if (!entry) return undefined;
80
+ return {
81
+ name: entry.name,
82
+ ...(entry.description ? { description: entry.description } : {}),
83
+ ...(entry.instructions ? { instructions: entry.instructions } : {}),
84
+ tools: entry.tools.filter(tool => hasOwn(tools, tool)),
85
+ };
86
+ }) });
87
+ const isSafeInteger = Number.isSafeInteger;
88
+ const searches = create(null);
89
+ let searchSequence = 0;
90
+ define(globalThis, 'searchTools', { value: freeze(async (query, options = {}) => {
91
+ if (typeof query !== 'string') throw new ErrorClass('searchTools(query) expects a string');
92
+ if (!options || typeof options !== 'object' || Array.isArray(options))
93
+ throw new ErrorClass('searchTools options must be an object with optional limit and namespace');
94
+ const limit = options.limit ?? 8;
95
+ if (!isSafeInteger(limit) || limit < 1) throw new ErrorClass('searchTools limit must be a positive integer');
96
+ if (options.namespace !== undefined && typeof options.namespace !== 'string')
97
+ throw new ErrorClass('searchTools namespace must be a server name');
98
+ // The host ranks with the index it shares with mcp_list and keeps between scripts.
99
+ const id = ++searchSequence;
100
+ const found = await new PromiseClass((resolve, reject) => {
101
+ searches[id] = resolve;
102
+ try {
103
+ bridge('search', id, stringify({ query, limit, namespace: options.namespace }));
104
+ } catch (error) {
105
+ delete searches[id];
106
+ reject(error);
107
+ }
108
+ });
109
+ return found.filter(name => hasOwn(toolEntries, name)).map(name => toolEntries[name]);
110
+ }) });
111
+ const imageTypes = ${JSON.stringify(Q)};
112
+ const imageUsage = 'image() expects an image block {type: "image", data, mimeType}, a base64 data: URL, or {path} to a local image file';
113
+ // A file read is a Read call: it takes a call id, so settle() resolves it like any tool call.
114
+ const showFile = path => request('imageFile', () => {
115
+ if (!path) throw new ErrorClass('image() path must be a non-empty file path');
116
+ return [path];
117
+ });
118
+ define(globalThis, 'image', { value: freeze(value => {
119
+ let mimeType;
120
+ let data;
121
+ if (value && typeof value === 'object' && typeof value.path === 'string' && value.data === undefined)
122
+ return showFile(value.path);
123
+ if (typeof value === 'string') {
124
+ const match = /^data:([^;,]+);base64,/.exec(value);
125
+ if (!match) throw new ErrorClass(imageUsage);
126
+ mimeType = match[1];
127
+ data = value.slice(match[0].length);
128
+ } else if (value && typeof value === 'object' && value.type === 'image' &&
129
+ typeof value.data === 'string' && typeof value.mimeType === 'string') {
130
+ mimeType = value.mimeType;
131
+ data = value.data;
132
+ } else throw new ErrorClass(imageUsage);
133
+ mimeType = mimeType.toLowerCase();
134
+ if (mimeType === 'image/jpg') mimeType = 'image/jpeg';
135
+ if (!imageTypes.includes(mimeType)) throw new ErrorClass('image() supports PNG, JPEG, GIF and WebP, not ' + mimeType);
136
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new ErrorClass('image() data must be base64 without whitespace; to show a file, await image({path})');
137
+ bridge('image', mimeType, data);
138
+ }) });
139
+ const assert = (condition, message) => {
140
+ if (!condition) throw new ErrorClass(message === undefined ? 'Assertion failed' : StringClass(message));
141
+ };
142
+ define(globalThis, 'assert', { value: freeze(assert) });
143
+ const storeLimits = ${JSON.stringify(fe)};
144
+ const state = new Map(Object.entries(parse(storeJSON)).map(([key, value]) => [key, stringify(value)]));
145
+ const initialState = new Map(state);
146
+ const bytes = value => {
147
+ let size = 0;
148
+ for (let i = 0; i < value.length; i++) {
149
+ const code = value.charCodeAt(i);
150
+ if (code < 128) size++;
151
+ else if (code < 2048) size += 2;
152
+ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length &&
153
+ value.charCodeAt(i + 1) >= 0xdc00 && value.charCodeAt(i + 1) <= 0xdfff) {
154
+ size += 4; i++;
155
+ } else size += 3;
156
+ }
157
+ return size;
158
+ };
159
+ let stateBytes = 0;
160
+ for (const [key, value] of state) stateBytes += bytes(key) + bytes(value);
161
+ const checkKey = key => {
162
+ if (storeError) {
163
+ const error = new ErrorClass(storeError);
164
+ error.name = 'StoreRestoreError';
165
+ throw error;
166
+ }
167
+ if (typeof key !== 'string' || !key || key.length > storeLimits.keyChars)
168
+ throw new ErrorClass('store key must be a non-empty string of at most ' + storeLimits.keyChars + ' characters');
169
+ };
170
+ const validateJSON = (value, seen = new Set()) => {
171
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
172
+ if (typeof value === 'number' && Number.isFinite(value)) return;
173
+ if (typeof value !== 'object' || seen.has(value) ||
174
+ (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null))
175
+ throw new ErrorClass('store requires a JSON value; await promises before storing them');
176
+ seen.add(value);
177
+ for (const item of Array.isArray(value) ? value : Object.values(value)) validateJSON(item, seen);
178
+ seen.delete(value);
179
+ };
180
+ define(globalThis, 'load', { value: freeze(key => {
181
+ checkKey(key);
182
+ return state.has(key) ? parse(state.get(key)) : undefined;
183
+ }) });
184
+ define(globalThis, 'store', { value: freeze((key, value) => {
185
+ checkKey(key);
186
+ if (value !== undefined) validateJSON(value);
187
+ const encoded = value === undefined ? undefined : stringify(value);
188
+ const previous = state.get(key);
189
+ const size = stateBytes - (previous === undefined ? 0 : bytes(key) + bytes(previous)) +
190
+ (encoded === undefined ? 0 : bytes(key) + bytes(encoded));
191
+ if (encoded !== undefined && previous === undefined && state.size >= storeLimits.keys)
192
+ throw new ErrorClass('store holds at most ' + storeLimits.keys + ' keys');
193
+ if (size > storeLimits.totalBytes) throw new ErrorClass('store size limit exceeded; delete unused keys first');
194
+ if (encoded === undefined) state.delete(key);
195
+ else state.set(key, encoded);
196
+ stateBytes = size;
197
+ }) });
198
+ const console = create(null);
199
+ for (const method of ['log', 'info', 'warn', 'error', 'debug']) {
200
+ define(console, method, { value: (...values) => {
201
+ let rendered = '';
202
+ for (let i = 0; i < values.length; i++) {
203
+ if (i) rendered += ' ';
204
+ rendered += format(values[i]) ?? StringClass(values[i]);
205
+ }
206
+ text(rendered);
207
+ }, enumerable: true });
208
+ }
209
+ const toolAccess = new ProxyClass(freeze(tools), {
210
+ get(target, name) {
211
+ if (hasOwn(target, name)) return target[name];
212
+ // Promise assimilation and JSON formatting may probe these properties.
213
+ if (typeof name !== 'string' || name === 'then' || name === 'toJSON') return undefined;
214
+ const distance = candidate => {
215
+ const a = name.toLowerCase(), b = candidate.toLowerCase();
216
+ let row = Array.from({length: b.length + 1}, (_, i) => i);
217
+ for (let i = 1; i <= a.length; i++) {
218
+ const next = [i];
219
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(next[j - 1] + 1, row[j] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
220
+ row = next;
221
+ }
222
+ return row[b.length];
223
+ };
224
+ const suggestions = name.length <= 100 ? allTools.map(entry => ({name: entry.name, distance: distance(entry.name)}))
225
+ .filter(entry => entry.distance <= Math.max(2, Math.min(3, Math.floor(name.length / 3))))
226
+ .sort((a, b) => a.distance - b.distance).slice(0, 3).map(entry => entry.name) : [];
227
+ const error = new ErrorClass('Tool ' + name + ' is not available inside CodeMode. ' +
228
+ (hasOwn(direct, name)
229
+ ? 'Call ' + name + ' directly outside CodeMode.'
230
+ : 'Use ALL_TOOLS or await searchTools(query) to find callable tools; check name in tools before calling.') +
231
+ (suggestions.length ? ' Similar callable tools: ' + suggestions.join(', ') + '.' : ''));
232
+ error.name = 'ToolCallError';
233
+ error.kind = 'unavailable';
234
+ error.toolName = name;
235
+ throw error;
236
+ }
237
+ });
238
+ define(globalThis, 'tools', { value: toolAccess });
239
+ define(globalThis, 'text', { value: freeze(text) });
240
+ define(globalThis, 'console', { value: freeze(console) });
241
+ return {
242
+ format,
243
+ trackRejection(promise, reason, handled) {
244
+ if (handled) rejections.delete(promise);
245
+ else rejections.set(promise, reason);
246
+ },
247
+ rejection() { return rejections.size ? {reason: rejections.values().next().value} : undefined; },
248
+ storeWrites() {
249
+ const writes = [];
250
+ for (const key of new Set([...initialState.keys(), ...state.keys()])) {
251
+ if (initialState.get(key) === state.get(key)) continue;
252
+ writes.push(state.has(key) ? {key, value: parse(state.get(key))} : {key});
253
+ }
254
+ return stringify(writes);
255
+ },
256
+ settleSearch(id, payload) {
257
+ if (!hasOwn(searches, id)) return;
258
+ const resolve = searches[id];
259
+ delete searches[id];
260
+ resolve(parse(payload));
261
+ },
262
+ settle(id, ok, payload) {
263
+ if (!hasOwn(pending, id)) return;
264
+ const waiter = pending[id];
265
+ delete pending[id];
266
+ const value = parse(payload);
267
+ if (ok) waiter.resolve(value);
268
+ else {
269
+ const error = new ErrorClass(value.message);
270
+ error.name = 'ToolCallError';
271
+ error.kind = value.kind;
272
+ error.toolName = value.toolName;
273
+ error.callId = value.callId;
274
+ waiter.reject(error);
275
+ }
276
+ }
277
+ };
278
+ }`;function ge(a,e,t){let r=e?.match(/[\s(]codemode\.js:(\d+):(\d+)/);if(!r)return a;let s=Number(r[1])-1,n=t.split(/\r\n|[\n\r\u2028\u2029]/)[s-1];return n===void 0?a:`${a}
279
+ at code:${s}:${r[2]}
280
+ ${n.slice(0,500)}`}function Ne(a,e){return a instanceof R?ge(`${a.name}: ${a.message}`,a.stack,e):a instanceof Error?a.message:"Script failed"}async function Te(a){let e,t=!1,r,s=0,n=0,i=0,o=0,c=0,u="",l=!1,d,h=a.maxSyncMs??U.maxSyncMs,w=performance.now(),g=new Set,_=new Set,I=new Set,O=new Set,x=0,E=p=>!Number.isSafeInteger(p)||p<1||p>c||g.has(p)?!1:(g.add(p),_.add(p),!0),v=p=>$?.postMessage(p),S=(p,b,j={})=>{t||(t=!0,v({type:"done",status:p,...j.errorKind?{errorKind:j.errorKind}:{},...j.limitKind?{limitKind:j.limitKind}:{},...j.storeWrites?.length?{storeWrites:j.storeWrites}:{},...b===void 0?{}:{error:b.slice(0,4e3)},..._.size?{pendingCallIds:[..._]}:{},...d!==void 0&&p==="completed"?{returnValue:d}:{}}))},k=[],B=!1;$?.on("message",p=>{B?ie(p):k.push(p)});let y=await Y.create({wasm:a.wasm,memoryLimit:U.memoryBytes,maxStackSize:G,interruptHandler:()=>t||e!==void 0&&Atomics.load(e,0)!==0?!0:performance.now()-w<=h?!1:(t=!0,v({type:"done",status:"timeout",error:`Script ran ${Math.round(h/1e3)}s without awaiting a tool call or returning; interrupted as a runaway loop. Await each call and split long computations.`,..._.size?{pendingCallIds:[..._]}:{}}),!0),onUnhandledRejection:(p,b,j)=>{r&&y.withScope(()=>y.callFunction(r,y.undefined,p,b,j?y.true:y.false))},wasi:p=>({fd_write:(b,j,D,q)=>{let N=new DataView(p.buffer),T=0;for(let A=0;A<D;A++)T+=N.getUint32(j+A*8+4,!0);return N.setUint32(q,T,!0),0}})}),f=p=>S("limit",me[p],{limitKind:p}),P=p=>(s+=Buffer.byteLength(p),s>U.outputBytes||++n>U.outputItems?(f("output"),!1):!0),L=p=>{P(p)&&v({type:"output",text:p})},_e=y.newFunction("codeModeBridge",(p,b,j,D)=>{if(t)return y.undefined;switch(p.toString()){case"attempt":c=b.toNumber(),c>U.calls&&f("calls");break;case"output":L(b.toString());break;case"search":{let q=b.toNumber(),N;try{N=JSON.parse(j.toString())}catch{N=void 0}let{query:T,limit:A,namespace:z}=N??{};if(q!==++x||typeof T!="string"||!Number.isSafeInteger(A)||z!==void 0&&typeof z!="string"){S("error","Invalid search bridge call");break}O.add(q),v({type:"search",id:q,query:T,limit:A,...z===void 0?{}:{namespace:z}});break}case"image":{let q=b.toString(),N=j.toString();if(o+=N.length,!Q.includes(q)||++i>U.images||o>U.imageBytes){f("images");break}v({type:"image",mimeType:q,data:N});break}case"imageFile":{let q=b.toNumber(),N=j.toString();if(!E(q)){S("error","Invalid image bridge call");break}v({type:"imageFile",id:q,path:N});break}case"call":{let q=b.toNumber(),N=j.toString(),T=D.toString();if(!I.has(N)||!E(q)){S("error","Invalid tool bridge call");break}v(Buffer.byteLength(T)>U.argumentBytes?{type:"call",id:q,name:N,args:"",argumentError:"Tool arguments exceed the byte limit"}:{type:"call",id:q,name:N,args:T});break}default:S("error","Invalid bridge message")}return y.undefined}),W=p=>{let b=p instanceof R&&p.name==="SyntaxError";S("error",Ne(p,u)+(b&&u.includes("`")?"\nIn template literals, escape embedded backticks as \\` and ${ as \\${.":""),{errorKind:b?"syntax":"script_exception"})},se,ne,oe,C,X=()=>{try{y.executePendingJobs(),setImmediate(()=>{!t&&_.size===0&&O.size===0&&S("incomplete","Script is waiting on a promise with no pending tool calls")})}catch(p){W(p)}},ye=p=>{l=!0,u=p.code,e=new Int32Array(p.interrupt);for(let j of p.tools)I.add(j);C=y.withScope(j=>j.escape(y.callFunction(y.evalCode(he,"codemode-prelude.js"),y.undefined,_e,y.newString(JSON.stringify(p.tools)),y.newString(JSON.stringify(p.directTools??[])),y.newString(JSON.stringify(p.toolCatalog??[])),y.newString(JSON.stringify(p.storeSnapshot??{})),y.newString(p.storeError??""),y.newString(JSON.stringify(p.namespaces??[]))))),se=C.getProp("settle"),ne=C.getProp("settleSearch"),oe=C.getProp("format"),r=C.getProp("trackRejection");let b=y.evalCode(`(async () => {
281
+ ${u}
282
+ })()`,"codemode.js");y.markPromiseHandled(b),y.resolvePromise(b).then(j=>{if(!t)try{let D=(T,A=!1)=>{let z,K;try{y.withScope(()=>{let ae=T.getProp("stack");z=ae.isUndefined?void 0:ae.toString(),K=T.getProp("name").toString()})}catch{}let we=K==="StoreRestoreError"?"store_restore":A?"unhandled_rejection":K==="SyntaxError"?"syntax":K==="ToolCallError"?"tool_call":"script_exception";S("error",ge((A?"Unhandled promise rejection: ":"")+T.toString(),z,u),{errorKind:we})};if("error"in j){D(j.error);return}let q=y.withScope(T=>T.escape(y.callFunction(C.getProp("rejection"),C)));if(!q.isUndefined){y.withScope(()=>D(q.getProp("reason"),!0)),q.dispose();return}if(q.dispose(),_.size>0){S("incomplete","Script returned with pending tool calls");return}j.value.isUndefined||y.withScope(()=>{let T=y.callFunction(oe,C,j.value);if(T.isUndefined)return;let A=T.toString();P(A)&&(d=A)});let N=y.withScope(()=>y.callFunction(C.getProp("storeWrites"),C).toString());S("completed",void 0,{storeWrites:JSON.parse(N)})}catch(D){W(D)}},W),b.dispose(),X()},ie=p=>{if(!t){if(w=performance.now(),p?.type==="start"){if(l||typeof p.code!="string"||!Array.isArray(p.tools)||p.directTools!==void 0&&!Array.isArray(p.directTools)||p.toolCatalog!==void 0&&(!Array.isArray(p.toolCatalog)||!p.toolCatalog.every(b=>b&&typeof b.name=="string"&&typeof b.description=="string"))||p.namespaces!==void 0&&(!Array.isArray(p.namespaces)||!p.namespaces.every(b=>b&&typeof b.name=="string"&&Array.isArray(b.tools)))||!(p.interrupt instanceof SharedArrayBuffer)){S("error","Invalid start message");return}try{ye(p)}catch(b){W(b)}return}if(l&&p?.type==="searched"){if(!O.delete(p.id)||!Array.isArray(p.names)||!p.names.every(b=>typeof b=="string")){S("error","Invalid host search result");return}try{y.withScope(()=>y.callFunction(ne,C,y.newNumber(p.id),y.newString(JSON.stringify(p.names)))),X()}catch(b){W(b)}return}if(!l||!p||p.type!=="settle"||typeof p.ok!="boolean"||typeof p.payload!="string"||!_.delete(p.id)||Buffer.byteLength(p.payload)>U.resultBytes){S("error","Invalid host result");return}try{y.withScope(()=>y.callFunction(se,C,y.newNumber(p.id),p.ok?y.true:y.false,y.newString(p.payload))),p.ok&&v({type:"received",id:p.id}),X()}catch(b){W(b)}}};B=!0;for(let p of k.splice(0))ie(p)}$&&Te(qe).catch(()=>{$?.postMessage({type:"done",status:"error",error:"Unable to initialize the script VM",errorKind:"runtime_start"}),$?.close()});
283
+ /**
284
+ * @license
285
+ * Copyright 2026 Google LLC
286
+ * SPDX-License-Identifier: Apache-2.0
287
+ */
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bundle/qoder-worker-runtime.mjs
3
- size: 35047907 bytes
4
- sha256: 3696ea0d2836596661f2878c3c9ceebe647b47d1294d337d3b226878887ce61d
3
+ size: 35859637 bytes
4
+ sha256: 4233d558c1c993c129fe96fe70ccb9300eb8b79db9007ec9b7084da366da1ce9
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bundle/qodercli.js
3
- size: 34834595 bytes
4
- sha256: b844d8195db333ea491ab7b58f13c66bd7b75412a982bceb409a0905265bea2c
3
+ size: 35653383 bytes
4
+ sha256: dcabbcaece1c0683ee4929ac7c0cf0ea00bbea4d319f5abeaae8216088b9888f
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qoder-ai/qodercli",
3
- "version": "1.1.80",
3
+ "version": "1.1.81",
4
4
  "description": "Qoder AI CLI - AI-powered coding assistant",
5
5
  "author": "Qoder AI",
6
6
  "type": "module",
@@ -20,12 +20,12 @@
20
20
  "sharp": "^0.34.5"
21
21
  },
22
22
  "optionalDependencies": {
23
- "@qoder-ai/qodercli-ripgrep-darwin-arm64": "1.1.80",
24
- "@qoder-ai/qodercli-ripgrep-darwin-x64": "1.1.80",
25
- "@qoder-ai/qodercli-ripgrep-linux-arm64": "1.1.80",
26
- "@qoder-ai/qodercli-ripgrep-linux-x64": "1.1.80",
27
- "@qoder-ai/qodercli-ripgrep-win32-arm64": "1.1.80",
28
- "@qoder-ai/qodercli-ripgrep-win32-x64": "1.1.80"
23
+ "@qoder-ai/qodercli-ripgrep-darwin-arm64": "1.1.81",
24
+ "@qoder-ai/qodercli-ripgrep-darwin-x64": "1.1.81",
25
+ "@qoder-ai/qodercli-ripgrep-linux-arm64": "1.1.81",
26
+ "@qoder-ai/qodercli-ripgrep-linux-x64": "1.1.81",
27
+ "@qoder-ai/qodercli-ripgrep-win32-arm64": "1.1.81",
28
+ "@qoder-ai/qodercli-ripgrep-win32-x64": "1.1.81"
29
29
  },
30
30
  "engines": {
31
31
  "node": ">=20.0.0"
@@ -1,275 +0,0 @@
1
- ---
2
- name: sdk
3
- description: >-
4
- Guide users building apps, scripts, CI pipelines, or automations on top of
5
- this CLI's companion TypeScript agent SDK. Use when the user mentions the
6
- companion SDK; asks to integrate, install, or write code against the SDK;
7
- says `query()`, `createSdkMcpServer`, `tool()`, `accessTokenFromEnv`, or
8
- `canUseTool`; asks to run agents programmatically from a script, CI/CD
9
- pipeline, backend service, or other code outside this CLI; wants to configure
10
- MCP servers for an SDK agent, handle streaming, permissions, hooks, session
11
- management, or sub-agents; or is wiring agents into an automation or bot. Use
12
- eagerly rather than answering from memory; the SDK surface evolves and this
13
- skill is the source of truth for the external package.
14
- ---
15
-
16
- # Qoder Agent SDK
17
-
18
- The Qoder TypeScript SDK (`@qoder-ai/qoder-agent-sdk`) runs Qoder AI agents programmatically. It spawns a `qodercli` subprocess and communicates over a bidirectional JSONL protocol. The single entry point is `query()`, which returns an `AsyncGenerator<SDKMessage, void>` — iterate it to receive assistant messages, tool calls, and the final result.
19
-
20
- Use this skill to help someone **bootstrap a working integration quickly** and **avoid the traps that bite new users**.
21
-
22
- ## Installation
23
-
24
- ```bash
25
- npm install @qoder-ai/qoder-agent-sdk zod
26
- ```
27
-
28
- **Requirements:**
29
- - Node.js 18+
30
- - A working `qodercli` executable (in PATH or via `options.pathToQoderCLIExecutable`)
31
- - `QODER_PERSONAL_ACCESS_TOKEN` environment variable set
32
-
33
- ## Voice and Posture
34
-
35
- - **When the user names the SDK explicitly** (`query()`, `@qoder-ai/qoder-agent-sdk`, `createSdkMcpServer`, etc.): assume they know what it is. Skip framing, go straight to producing the integration.
36
- - **When the user describes a problem the SDK fits but doesn't name it**: surface it as a question briefly, then wait: *"The Qoder SDK is what I'd reach for here — want me to design it that way?"*
37
- - Don't restate the user's intent. Open with the design decision or first actionable thing.
38
-
39
- ## The Two Invocation Patterns
40
-
41
- ### 1. Single-turn — `query({ prompt: "string" })`
42
-
43
- ```typescript
44
- import { query, accessTokenFromEnv } from '@qoder-ai/qoder-agent-sdk';
45
-
46
- for await (const msg of query({
47
- prompt: 'Refactor src/utils.ts for readability',
48
- options: {
49
- auth: accessTokenFromEnv(),
50
- permissionMode: 'acceptEdits',
51
- allowedTools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'],
52
- },
53
- })) {
54
- if (msg.type === 'assistant') {
55
- for (const block of msg.message.content) {
56
- if (block.type === 'text') process.stdout.write(block.text);
57
- }
58
- } else if (msg.type === 'result') {
59
- console.log(`Done: ${msg.subtype}, cost: $${msg.total_cost_usd}`);
60
- }
61
- }
62
- ```
63
-
64
- Use for fire-and-forget scripts, CI steps, GitHub Actions — "send prompt, get result, exit." No follow-ups, no streaming input. If you need multi-turn or `interrupt()`, use pattern 2.
65
-
66
- ### 2. Multi-turn — `query({ prompt: asyncIterable })`
67
-
68
- ```typescript
69
- import { query, accessTokenFromEnv } from '@qoder-ai/qoder-agent-sdk';
70
-
71
- function createChannel() {
72
- const queue = [];
73
- let resolve = null;
74
- let done = false;
75
- return {
76
- push(msg) { resolve ? resolve({ value: msg, done: false }) : queue.push(msg); resolve = null; },
77
- end() { done = true; if (resolve) resolve({ value: undefined, done: true }); },
78
- [Symbol.asyncIterator]() {
79
- return { next() {
80
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
81
- if (done) return Promise.resolve({ value: undefined, done: true });
82
- return new Promise(r => { resolve = r; });
83
- }};
84
- },
85
- };
86
- }
87
-
88
- const channel = createChannel();
89
- const q = query({ prompt: channel, options: { auth: accessTokenFromEnv() } });
90
-
91
- // Send first message
92
- channel.push({
93
- type: 'user',
94
- message: { role: 'user', content: 'Find the bug in src/auth.ts' },
95
- parent_tool_use_id: null,
96
- });
97
-
98
- for await (const msg of q) {
99
- if (msg.type === 'assistant') { /* render */ }
100
- if (msg.type === 'result' && msg.subtype === 'success') {
101
- // Follow-up keeps conversation context
102
- channel.push({
103
- type: 'user',
104
- message: { role: 'user', content: 'Now write a regression test' },
105
- parent_tool_use_id: null,
106
- });
107
- }
108
- }
109
- channel.end();
110
- ```
111
-
112
- Use when you need streaming input, multi-turn conversation, `q.interrupt()`, `q.setModel()`, or `q.setPermissionMode()`. This is the shape of most non-trivial integrations (chat UIs, bots, interactive CLIs).
113
-
114
- ## Top Five Traps
115
-
116
- ### 1. Missing `auth` throws synchronously
117
-
118
- `query()` throws `AuthNotConfiguredError` before any messages flow if `options.auth` is not set. Always pass it explicitly:
119
-
120
- ```typescript
121
- options: { auth: accessTokenFromEnv() }
122
- ```
123
-
124
- ### 2. Not consuming the generator leaks the subprocess
125
-
126
- Constructing `query()` spawns `qodercli` immediately. If you don't iterate `for await` or call `q.close()`, the child process stays alive. Always consume in a try/finally:
127
-
128
- ```typescript
129
- const q = query({ prompt, options });
130
- try {
131
- for await (const msg of q) { /* ... */ }
132
- } finally {
133
- q.close();
134
- }
135
- ```
136
-
137
- ### 3. `result.subtype` distinguishes success from failure
138
-
139
- ```typescript
140
- if (msg.type === 'result') {
141
- if (msg.subtype === 'success') {
142
- // Agent completed. Inspect msg.result for final text.
143
- } else {
144
- // msg.subtype is 'error_during_execution' | 'error_max_turns' | 'error_max_budget_usd'
145
- // msg.errors contains error descriptions.
146
- console.error('Agent failed:', msg.subtype, msg.errors);
147
- }
148
- }
149
- ```
150
-
151
- Don't catch exceptions for run failures — they come as `result` messages, not thrown errors. Thrown errors mean the process failed to start (auth, binary not found, protocol mismatch).
152
-
153
- ### 4. `canUseTool` must echo `toolUseID`
154
-
155
- When implementing the permission callback, always include the `toolUseID` from options in your response:
156
-
157
- ```typescript
158
- canUseTool: async (toolName, input, options) => {
159
- return { behavior: 'allow', toolUseID: options.toolUseID };
160
- // or: { behavior: 'deny', message: 'Not allowed', toolUseID: options.toolUseID }
161
- }
162
- ```
163
-
164
- Omitting `toolUseID` breaks permission correlation and the tool call hangs.
165
-
166
- ### 5. Control methods require multi-turn mode
167
-
168
- `q.interrupt()`, `q.setModel()`, `q.setPermissionMode()` throw if `prompt` was a plain string. If you need control but don't need multi-turn, pass `canUseTool` — it auto-converts to streaming mode internally.
169
-
170
- ## Auth
171
-
172
- ```bash
173
- export QODER_PERSONAL_ACCESS_TOKEN="qoder_..."
174
- ```
175
-
176
- | Helper | Use case |
177
- |--------|----------|
178
- | `accessTokenFromEnv()` | CI, scripts — reads `QODER_PERSONAL_ACCESS_TOKEN` |
179
- | `accessTokenFromEnv('MY_VAR')` | Custom env var name |
180
- | `accessToken(token)` | Token from secret manager / vault |
181
- | `qodercliAuth()` | Reuse local `qodercli login` state (interactive only) |
182
-
183
- If you're seeing auth failures: check env var is set without surrounding whitespace, and that the token belongs to the correct environment.
184
-
185
- ## MCP Servers (In-Process Tools)
186
-
187
- ```typescript
188
- import { query, createSdkMcpServer, tool, accessTokenFromEnv } from '@qoder-ai/qoder-agent-sdk';
189
- import { z } from 'zod';
190
-
191
- const server = createSdkMcpServer({
192
- name: 'my-tools',
193
- tools: [
194
- tool('lookup_user', 'Look up a user by email.', {
195
- email: z.string().describe('User email address'),
196
- }, async ({ email }) => ({
197
- content: [{ type: 'text', text: JSON.stringify(await db.findUser(email)) }],
198
- })),
199
- ],
200
- });
201
-
202
- for await (const msg of query({
203
- prompt: 'Find the user alice@example.com',
204
- options: {
205
- auth: accessTokenFromEnv(),
206
- mcpServers: { 'my-tools': server },
207
- allowedTools: ['mcp__my-tools__lookup_user'],
208
- },
209
- })) { /* ... */ }
210
- ```
211
-
212
- Key points:
213
- - Tool name in `allowedTools` follows the pattern `mcp__<server-name>__<tool-name>`
214
- - Use `.describe()` on Zod fields — the model reads those descriptions
215
- - Return business errors via `isError: true` in `CallToolResult`, don't throw
216
- - Set `annotations: { readOnlyHint: true }` on read-only tools for auto-approval hints
217
-
218
- ## Permissions
219
-
220
- | Mode | Behavior |
221
- |------|----------|
222
- | `'default'` | Prompt for every tool (requires `canUseTool`) |
223
- | `'acceptEdits'` | Auto-approve file reads/writes, prompt for others |
224
- | `'plan'` | Model plans but doesn't execute until approved |
225
- | `'bypassPermissions'` | Skip all prompts (requires `allowDangerouslySkipPermissions: true`) |
226
-
227
- For programmatic approval without UI:
228
-
229
- ```typescript
230
- options: {
231
- canUseTool: async (toolName, input, opts) => {
232
- if (['Read', 'Glob', 'Grep'].includes(toolName)) {
233
- return { behavior: 'allow', toolUseID: opts.toolUseID };
234
- }
235
- return { behavior: 'deny', message: 'Not allowed', toolUseID: opts.toolUseID };
236
- },
237
- }
238
- ```
239
-
240
- ## Session Management
241
-
242
- ```typescript
243
- import { listSessions, getSessionMessages, query } from '@qoder-ai/qoder-agent-sdk';
244
-
245
- // Continue most recent session
246
- const q = query({ prompt: 'Continue where we left off', options: { continue: true } });
247
-
248
- // Resume specific session
249
- const q2 = query({ prompt: 'Fix the remaining test', options: { resume: 'session-id' } });
250
-
251
- // Fork a session (branch from existing state)
252
- const q3 = query({ prompt: 'Try a different approach', options: { resume: 'session-id', forkSession: true } });
253
-
254
- // Inspect sessions offline
255
- const sessions = await listSessions({ dir: process.cwd() });
256
- const messages = await getSessionMessages({ sessionId: sessions[0].id, dir: process.cwd() });
257
- ```
258
-
259
- ## Production Best Practices
260
-
261
- 1. **Always consume or close the query** — `for await` in a try/finally with `q.close()`. Non-negotiable.
262
- 2. **Distinguish result subtypes for exit codes** — exit 0 for `success`, exit 2 for `error_*` subtypes.
263
- 3. **Log `session_id` from the init message immediately** — it's the key for debugging.
264
- 4. **Pass `auth` explicitly** — don't rely on ambient env vars in shared infrastructure.
265
- 5. **Use `settingSources: []`** to avoid loading ambient user/project config in services.
266
- 6. **Set `maxTurns` in CI** to prevent runaway agents (e.g., `maxTurns: 20`).
267
- 7. **For streaming UIs, enable `includePartialMessages: true`** — gives token-by-token output.
268
- 8. **Pass `pathToQoderCLIExecutable`** when the binary isn't in PATH (Docker, CI, etc.).
269
-
270
- ## What This Skill Doesn't Cover
271
-
272
- - The `qodercli` CLI itself (TUI, interactive mode, built-in tools).
273
- - Python SDK (`qoder-agent-sdk-python`) — different API surface.
274
- - Direct Connect transport — advanced internal integration pattern.
275
- - Plugin/extension authoring — separate docs.