eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
3 lines • 73 kB
JavaScript
import{Q as e,Y as t,ft as n,mt as r,ut as i}from"./dist-DjECvUyK.js";import{An as a,Dn as o,En as s,Fn as c,Hn as l,In as u,Jn as d,Kn as f,Mn as p,Pn as m,Rn as h,Un as g,Vn as _,Wn as ee,ct as te,d as v,dt as ne,ft as re,h as y,ht as ie,jn as ae,kn as oe,l as se,lt as ce,mt as le,n as b,pt as ue,t as x,ut as de,zn as S}from"./logger-DFNCa8Nl.js";import{P as fe,_ as pe,a as me,g as he,i as ge,k as C,l as _e,m as w,p as ve,u as ye}from"./dist-xTushGCp.js";import{i as be,r as xe}from"./global-DFW-hO6M.js";import{awaitEarlierDeliveries as Se,getStepFunction as Ce,registerDeliveryBarrier as we}from"../../@workflow/core/private.js";import{types as T}from"node:util";import{AsyncLocalStorage as Te}from"node:async_hooks";const Ee=2**32-1,De=Ee-1;var E=class extends Error{constructor(e,t,n,r){super(e),this.name=`DevalueError`,this.path=t.join(``),this.value=n,this.root=r}};const Oe=Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function ke(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||Object.getPrototypeOf(t)===null||Object.getOwnPropertyNames(t).sort().join(`\0`)===Oe}function Ae(e){return Object.prototype.toString.call(e).slice(8,-1)}function je(e){switch(e){case`"`:return`\\"`;case`<`:return`\\u003C`;case`\\`:return`\\\\`;case`
`:return`\\n`;case`\r`:return`\\r`;case` `:return`\\t`;case`\b`:return`\\b`;case`\f`:return`\\f`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return e<` `?`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`:``}}function D(e){let t=``,n=0,r=e.length;for(let i=0;i<r;i+=1){let r=e[i],a=je(r);a&&(t+=e.slice(n,i)+a,n=i+1)}return`"${n===0?e:t+e.slice(n)}"`}function Me(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.getOwnPropertyDescriptor(e,t).enumerable)}const Ne=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Pe(e){return Ne.test(e)?`.`+e:`[`+JSON.stringify(e)+`]`}function Fe(e){return!(!Number.isInteger(e)||e<0||e>De)}function Ie(e){return!(!Number.isInteger(e)||e<0||e>Ee)}function Le(e){if(e.length===0||e.length>1&&e.charCodeAt(0)===48)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return Fe(+e)}function Re(e){for(var t=e.length-1;t>=0&&!Le(e[t]);t--);return t+1}function ze(e){let t=Object.keys(e);return t.length=Re(t),t}function Be(e){return new Uint8Array(e).toBase64()}function Ve(e){return Uint8Array.fromBase64(e).buffer}function He(e){return Buffer.from(e).toString(`base64`)}function Ue(e){return Uint8Array.from(Buffer.from(e,`base64`)).buffer}function We(e){let t=new Uint8Array(e),n=``,r=32768;for(let e=0;e<t.length;e+=r){let i=t.subarray(e,e+r);n+=String.fromCharCode.apply(null,i)}return btoa(n)}function Ge(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}const Ke=typeof Uint8Array.fromBase64==`function`,qe=typeof process==`object`&&process.versions?.node!==void 0,Je=Ke?Be:qe?He:We,Ye=Ke?Ve:qe?Ue:Ge;function Xe(e,t){if(!t)return e;let n={};for(let r of Object.keys(e))n[r]=t[r]??e[r];return n}const Ze=Object.freeze({kind:`not-plain`}),Qe=Object.freeze({kind:`symbol-keys`}),$e=Object.freeze({identify:e=>e,typeOf:e=>e===null?`null`:typeof e,toPrimitive:e=>e,tagOf:e=>Ae(e),isThenable:e=>typeof e.then==`function`,toPromise:e=>Promise.resolve(e),unbox:e=>e.valueOf(),toISOString:e=>isNaN(e.getDate())?``:e.toISOString(),toStringValue:e=>e.toString(),regExpInfo:e=>({source:e.source,flags:e.flags}),valuesOf:e=>e,entriesOf:e=>e,viewInfo:e=>({buffer:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength,length:e.length,bufferByteLength:e.buffer.byteLength}),toArrayBuffer:e=>e,lengthOf:e=>e.length,hasOwn:(e,t)=>Object.hasOwn(e,t),indicesOf:e=>ze(e),shapeOf:e=>ke(e)?Me(e).length>0?Qe:{kind:Object.getPrototypeOf(e)===null?`null-proto`:`plain`,keys:Object.keys(e)}:Ze,get:(e,t)=>e[t]}),et=Object.freeze({fromPrimitive:e=>e,fromISOString:e=>new Date(e),fromStringValue:(e,t)=>e===`URL`?new URL(t):e===`URLSearchParams`?new URLSearchParams(t):Temporal[e.slice(9)].from(t),fromArrayBuffer:e=>e,fromRegExpInfo:(e,t)=>new RegExp(e,t),fromViewInfo:(e,t,n,r)=>{let i=globalThis[e];return n===void 0?new i(t):new i(t,n,r)},box:e=>Object(e),createArray:e=>Array(e),createSparseArray:e=>{let t=[];return t[De]=void 0,delete t[De],t.length=e,t},createObject:()=>({}),createNullPrototypeObject:()=>Object.create(null),createSet:()=>new Set,createMap:()=>new Map,set:(e,t,n)=>{e[t]=n},addValue:(e,t)=>{e.add(t)},addEntry:(e,t,n)=>{e.set(t,n)}});function tt(e,t,n){return nt(JSON.parse(e),t,n)}function nt(e,t,n){let r=Xe(et,n?.operations);if(typeof e==`number`)return s(e,!0);if(!Array.isArray(e)||e.length===0)throw Error(`Invalid input`);let i=e,a=Array(i.length),o=null;function s(e,n=!1){if(e===-1)return r.fromPrimitive(void 0);if(e===-3)return r.fromPrimitive(NaN);if(e===-4)return r.fromPrimitive(1/0);if(e===-5)return r.fromPrimitive(-1/0);if(e===-6)return r.fromPrimitive(-0);if(n||typeof e!=`number`)throw Error(`Invalid input`);if(e in a)return a[e];if(e>=i.length)throw Error(`Invalid input`);let c=i[e];if(!c||typeof c!=`object`)a[e]=r.fromPrimitive(c);else if(Array.isArray(c)){if(typeof c[0]==`string`){let n=c[0],l=t&&Object.hasOwn(t,n)?t[n]:void 0;if(l){let t=c[1];if(typeof t!=`number`&&(t=i.push(c[1])-1),Object.hasOwn(a,t))return a[e]=l(a[t]);if(o??=new Set,o.has(t))throw Error(`Invalid circular reference`);return o.add(t),a[e]=l(s(t)),o.delete(t),a[e]}switch(n){case`Date`:a[e]=r.fromISOString(c[1]);break;case`Set`:let t=r.createSet();a[e]=t;for(let e=1;e<c.length;e+=1)r.addValue(t,s(c[e]));break;case`Map`:let o=r.createMap();a[e]=o;for(let e=1;e<c.length;e+=2)r.addEntry(o,s(c[e]),s(c[e+1]));break;case`RegExp`:a[e]=r.fromRegExpInfo(c[1],c[2]);break;case`Object`:{let t=c[1];if(typeof i[t]==`object`&&i[t][0]!==`BigInt`)throw Error(`Invalid input`);a[e]=r.box(s(t));break}case`BigInt`:a[e]=r.fromPrimitive(BigInt(c[1]));break;case`null`:let l=r.createNullPrototypeObject();a[e]=l;for(let e=1;e<c.length;e+=2){if(c[e]===`__proto__`)throw Error("Cannot parse an object with a `__proto__` property");r.set(l,c[e],s(c[e+1]))}break;case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:case`Int16Array`:case`Uint16Array`:case`Float16Array`:case`Int32Array`:case`Uint32Array`:case`Float32Array`:case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:case`DataView`:{if(i[c[1]][0]!==`ArrayBuffer`)throw Error(`Invalid data`);let t=s(c[1]);a[e]=r.fromViewInfo(n,t,c[2],c[3]);break}case`ArrayBuffer`:{let t=c[1];if(typeof t!=`string`)throw Error(`Invalid ArrayBuffer encoding`);a[e]=r.fromArrayBuffer(Ye(t));break}case`URL`:case`URLSearchParams`:case`Temporal.Duration`:case`Temporal.Instant`:case`Temporal.PlainDate`:case`Temporal.PlainTime`:case`Temporal.PlainDateTime`:case`Temporal.PlainMonthDay`:case`Temporal.PlainYearMonth`:case`Temporal.ZonedDateTime`:a[e]=r.fromStringValue(n,c[1]);break;default:throw Error(`Unknown type ${n}`)}}else if(c[0]===-7){let t=c[1];if(!Ie(t))throw Error(`Invalid input`);let n=r.createSparseArray(t);a[e]=n;for(let e=2;e<c.length;e+=2){let i=c[e];if(!Fe(i)||i>=t)throw Error(`Invalid input`);r.set(n,i,s(c[e+1]))}}else{let t=r.createArray(c.length);a[e]=t;for(let e=0;e<c.length;e+=1){let n=c[e];n!==-2&&r.set(t,e,s(n))}}}else{let t=r.createObject();a[e]=t;for(let e of Object.keys(c)){if(e===`__proto__`)throw Error("Cannot parse an object with a `__proto__` property");r.set(t,e,s(c[e]))}}return a[e]}return s(0)}function O(e,t,n){let r=rt(!1,e,t,n);return typeof r==`string`?r:`[${r.join(`,`)}]`}function rt(e,t,n,r){let i=Xe($e,r?.operations),a=[],o=new Map,s=[];if(n)for(let e of Object.getOwnPropertyNames(n))s.push({key:e,fn:n[e]});let c=[],l=0;function u(n,r){let d=i.typeOf(n);if(d===`undefined`)return-1;let f;if(d===`number`){if(f=i.toPrimitive(n),Number.isNaN(f))return-3;if(f===1/0)return-4;if(f===-1/0)return-5;if(f===0&&1/f<0)return-6}let p=i.identify(n);if(o.has(p))return o.get(p);r??=l++,o.set(p,r);for(let{key:e,fn:t}of s){let i=t(n);if(i)return a[r]=`["${e}",${u(i)}]`,r}if(d===`function`)throw new E(`Cannot stringify a function`,c,n,t);if(d===`symbol`)throw new E(`Cannot stringify a Symbol primitive`,c,n,t);let m=``;if(d!==`object`)m=it(d===`number`?f:i.toPrimitive(n));else if(i.isThenable(n)){if(!e)throw new E(`Cannot stringify a Promise or thenable — use stringifyAsync instead`,c,n,t);m=i.toPromise(n).then(e=>{let t=u(e,r);t<0&&(a[r]=t)})}else{let e=i.tagOf(n);switch(e){case`Number`:case`String`:case`Boolean`:case`BigInt`:m=`["Object",${u(i.unbox(n))}]`;break;case`Date`:m=`["Date","${i.toISOString(n)}"]`;break;case`URL`:m=`["URL",${D(i.toStringValue(n))}]`;break;case`URLSearchParams`:m=`["URLSearchParams",${D(i.toStringValue(n))}]`;break;case`RegExp`:let{source:r,flags:a}=i.regExpInfo(n);m=a?`["RegExp",${D(r)},"${a}"]`:`["RegExp",${D(r)}]`;break;case`Array`:{let e=!1,t=i.lengthOf(n);m=`[`;for(let r=0;r<t;r+=1)if(r>0&&(m+=`,`),i.hasOwn(n,r))c.push(`[${r}]`),m+=u(i.get(n,r)),c.pop();else if(e)m+=-2;else{let r=i.indicesOf(n),a=r.length,o=String(t).length;if((t-a)*3>4+o+a*(o+1)){m=`[-7,`+t;for(let e=0;e<r.length;e++){let t=r[e];c.push(`[${t}]`),m+=`,`+t+`,`+u(i.get(n,t)),c.pop()}break}e=!0,m+=-2}m+=`]`;break}case`Set`:m=`["Set"`;for(let e of i.valuesOf(n))m+=`,${u(e)}`;m+=`]`;break;case`Map`:m=`["Map"`;for(let[e,t]of i.entriesOf(n)){let n=i.typeOf(e),r=n!==`object`&&n!==`function`&&n!==`symbol`;c.push(`.get(${r?it(i.toPrimitive(e)):`...`})`),m+=`,${u(e)},${u(t)}`,c.pop()}m+=`]`;break;case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:case`Int16Array`:case`Uint16Array`:case`Float16Array`:case`Int32Array`:case`Uint32Array`:case`Float32Array`:case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:{let t=i.viewInfo(n);m=`["`+e+`",`+u(t.buffer),t.byteLength!==t.bufferByteLength&&(m+=`,${t.byteOffset},${t.length}`),m+=`]`;break}case`DataView`:{let t=i.viewInfo(n);m=`["`+e+`",`+u(t.buffer),t.byteLength!==t.bufferByteLength&&(m+=`,${t.byteOffset},${t.byteLength}`),m+=`]`;break}case`ArrayBuffer`:m=`["ArrayBuffer","${Je(i.toArrayBuffer(n))}"]`;break;case`Temporal.Duration`:case`Temporal.Instant`:case`Temporal.PlainDate`:case`Temporal.PlainTime`:case`Temporal.PlainDateTime`:case`Temporal.PlainMonthDay`:case`Temporal.PlainYearMonth`:case`Temporal.ZonedDateTime`:m=`["${e}",${D(i.toStringValue(n))}]`;break;default:{let e=i.shapeOf(n);if(e.kind===`not-plain`)throw new E(`Cannot stringify arbitrary non-POJOs`,c,n,t);if(e.kind===`symbol-keys`)throw new E(`Cannot stringify POJOs with symbolic keys`,c,n,t);if(e.kind===`null-proto`){m=`["null"`;for(let r of e.keys){if(r===`__proto__`)throw new E(`Cannot stringify objects with __proto__ keys`,c,n,t);c.push(Pe(r)),m+=`,${D(r)},${u(i.get(n,r))}`,c.pop()}m+=`]`}else{m=`{`;let r=!1;for(let a of e.keys){if(a===`__proto__`)throw new E(`Cannot stringify objects with __proto__ keys`,c,n,t);r&&(m+=`,`),r=!0,c.push(Pe(a)),m+=`${D(a)}:${u(i.get(n,a))}`,c.pop()}m+=`}`}}}}return a[r]=m,r}let d=u(t);return d<0?`${d}`:a}function it(e){let t=typeof e;return t===`string`?D(e):e===void 0?`-1`:e===0&&1/e<0?`-6`:t===`bigint`?`["BigInt","${e}"]`:String(e)}const at=Symbol.for(`WORKFLOW_USE_STEP`),ot=Symbol.for(`WORKFLOW_SET_ATTRIBUTES`),st=Symbol.for(`WORKFLOW_CREATE_HOOK`),ct=Symbol.for(`WORKFLOW_SLEEP`),lt=Symbol.for(`WORKFLOW_GET_STREAM_ID`),ut=Symbol.for(`WORKFLOW_STABLE_ULID`),k=Symbol.for(`WORKFLOW_STREAM_NAME`),dt=Symbol.for(`WORKFLOW_STREAM_TYPE`),ft=Symbol.for(`WORKFLOW_STREAM_FRAMING`),A=Symbol.for(`WORKFLOW_STREAM_SERVER_RUN_ID`),j=Symbol.for(`WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID`),M=Symbol.for(`WORKFLOW_STREAM_SERVER_PUBLIC_KEY`),pt=Symbol.for(`WORKFLOW_STREAM_DRAIN`),mt=Symbol.for(`BODY_INIT`),ht=Symbol.for(`WEBHOOK_RESPONSE_WRITABLE`),gt=Symbol.for(`workflow-class-registry`),N=Symbol.for(`WORKFLOW_ABORT_STREAM_NAME`),P=Symbol.for(`WORKFLOW_ABORT_HOOK_TOKEN`),_t=Symbol.for(`WORKFLOW_ABORT_LISTENER_ATTACHED`),vt=Symbol.for(`WORKFLOW_ABORT_READER_CANCEL`),yt=()=>n(`WORKFLOW_STREAM_MAX_INFLIGHT_CHUNKS`,1e3,{integer:!0,min:1}),bt=()=>n(`WORKFLOW_STREAM_MAX_CHUNKS_PER_BATCH`,1e3,{integer:!0,min:1}),xt=()=>n(`WORKFLOW_STREAM_MAX_BYTES_PER_BATCH`,1048576,{integer:!0,min:1}),St=()=>n(`WORKFLOW_STREAM_MAX_BUFFERED_BYTES`,8388608,{integer:!0,min:1}),Ct=()=>n(`WORKFLOW_LOCK_POLL_INTERVAL_MS`,10,{integer:!0,min:1});function F(){let e={...be(),pendingOps:0,producedFrames:0,acceptedFrames:0,frameWaiters:[],doneResolved:!1,streamEnded:!1};return e.promise.catch(()=>{}),e}function wt(e){if(e.locked)return!1;let t;try{t=e.getWriter()}catch{return!1}try{t.releaseLock()}catch{return!1}return!0}function Tt(e){if(e.locked)return!1;let t;try{t=e.getReader()}catch{return!1}try{t.releaseLock()}catch{return!1}return!0}function Et(e){let t=e.drainBarrier;if(!t){e.resolve();return}t().then(()=>e.resolve(),t=>e.reject(t))}function Dt(e){e.producedFrames++}async function Ot(e){let t=async t=>{throw await e.drainBarrier?.().catch(()=>{}),t},n=e.producedFrames;if(e.acceptedFrames<n){if(e.pipeError!==void 0)return t(e.pipeError);try{await new Promise((t,r)=>{e.frameWaiters.push({target:n,resolve:t,reject:r})})}catch(e){return t(e)}}if(e.pipeError!==void 0)return t(e.pipeError);await e.drainBarrier?.()}function kt(e,t,n=WritableStream){let r=e.getWriter(),i=Symbol(`workflow-stream-release-checkpoint`),a,o=new n({start(e){a=e},async write(e){e!==i&&(Dt(t),await r.write(e))},async close(){t.userWritableClosing=!0;try{await r.close()}finally{r.releaseLock()}},async abort(e){try{await r.abort(e)}finally{r.releaseLock()}}});r.closed.catch(e=>{a.error(e)});let s;return t.settleReleasedWrites=()=>{if(t.releaseSettlementArmed=!0,s)return s;if(o.locked)return Promise.resolve(!1);if(t.userWritableClosing)return s=t.promise.then(()=>!0),s;let e;try{e=o.getWriter()}catch{return Promise.resolve(!1)}return s=(async()=>{try{try{await e.write(i)}catch(e){try{return await t.promise,!0}catch(t){throw t??e}}return await Ot(t),t.doneResolved||(t.doneResolved=!0,t.resolve()),!0}catch(e){throw t.doneResolved||(t.doneResolved=!0,t.reject(e)),e}finally{e.releaseLock()}})(),s},o}function At(e,t){if(t.writablePollingInterval!==void 0)return;let n=setInterval(()=>{if(t.doneResolved||t.streamEnded){clearInterval(n),t.writablePollingInterval=void 0;return}if(t.settleReleasedWrites){(!t.deferReleaseSettlement||t.releaseSettlementArmed)&&!e.locked&&(clearInterval(n),t.writablePollingInterval=void 0,t.settleReleasedWrites().catch(()=>{}));return}wt(e)&&t.pendingOps===0&&(t.doneResolved=!0,clearInterval(n),t.writablePollingInterval=void 0,Et(t))},Ct());t.writablePollingInterval=n}function jt(e,t){if(t.readablePollingInterval!==void 0)return;let n=setInterval(()=>{if(t.doneResolved||t.streamEnded){clearInterval(n),t.readablePollingInterval=void 0;return}Tt(e)&&t.pendingOps===0&&(t.doneResolved=!0,clearInterval(n),t.readablePollingInterval=void 0,Et(t))},Ct());t.readablePollingInterval=n}function I(e,t,n){let r=t[pt];return typeof r==`function`&&(n.drainBarrier=r),Mt(e,t,n)}async function Mt(e,t,n){let r=e.getReader(),i=t.getWriter(),a;try{for(;;){if(n.streamEnded)return;let e=await Promise.race([r.read(),i.closed.then(()=>{throw new C(`Writable stream closed prematurely`)})]);if(n.streamEnded)return;if(e.done){n.streamEnded=!0,await i.close(),n.doneResolved||(n.doneResolved=!0,n.resolve());return}n.pendingOps++;try{await i.write(e.value),n.acceptedFrames++;let t=n.frameWaiters.filter(e=>e.target<=n.acceptedFrames);n.frameWaiters=n.frameWaiters.filter(e=>e.target>n.acceptedFrames);for(let e of t)e.resolve()}finally{n.pendingOps--}}}catch(e){n.streamEnded=!0,n.pipeError=e,a=e;let t=n.frameWaiters;n.frameWaiters=[];for(let n of t)n.reject(e);throw n.drainBarrier&&await n.drainBarrier().catch(()=>{}),n.doneResolved||(n.doneResolved=!0,n.reject(e)),e}finally{r.cancel(a).catch(()=>{}),r.releaseLock(),i.releaseLock()}}let L=null,Nt=null;function Pt(e,t){let n=L,r=Nt;L=e??null,Nt=e?new WeakSet:null;try{return t()}finally{L=n,Nt=r}}const Ft=r(`@workflow/core//useStepClosures.fns`,1,()=>({fns:new WeakSet}));function It(e){return Ft.fns.add(e),e}function Lt(e){return typeof e==`function`&&Ft.fns.has(e)}function R(e,t){if(!L||(L.totalExecutions=(L.totalExecutions??L.executions.length)+1,L.executions.length>=5))return;let n={kind:e};t!==void 0&&(n.detail=t),L.executions.push(n)}function z(e){L&&Nt&&(Nt.has(e)||(Nt.add(e),R(`proxy`)))}const B=Function.prototype.bind.bind(Function.prototype.call);function V(e,t){let n=Object.getOwnPropertyDescriptor(e,t)?.get;if(!n)throw Error(`Missing intrinsic getter: ${String(t)}`);return B(n)}const Rt=B(Date.prototype.getDate),zt=B(Date.prototype.getTime),Bt=B(Date.prototype.toISOString),Vt=V(RegExp.prototype,`source`),Ht=V(RegExp.prototype,`flags`),Ut=V(ArrayBuffer.prototype,`byteLength`),Wt=B(Map.prototype.entries),Gt=B(Set.prototype.values),Kt=B(Number.prototype.valueOf),qt=B(String.prototype.valueOf),Jt=B(Boolean.prototype.valueOf),Yt=B(BigInt.prototype.valueOf),Xt=Object.getPrototypeOf(Uint8Array.prototype),Zt=V(Xt,Symbol.toStringTag),Qt=V(Xt,`buffer`),$t=V(Xt,`byteOffset`),en=V(Xt,`byteLength`),tn=V(Xt,`length`),nn=V(DataView.prototype,`buffer`),rn=V(DataView.prototype,`byteOffset`),an=V(DataView.prototype,`byteLength`),on=V(SharedArrayBuffer.prototype,`byteLength`),sn=B(Headers.prototype[Symbol.iterator]),cn=V(URL.prototype,`href`),ln=B(URLSearchParams.prototype.toString),{isProxy:H}=T,un=B(Function.prototype.toString);function dn(e){if(H(e))return!1;let t=Object.getOwnPropertyDescriptor(e,`name`)?.value;return typeof t==`string`&&t.startsWith(`bound `)?!1:un(e).endsWith(`{ [native code] }`)||Reflect.getPrototypeOf(e)===Function.prototype}function U(e,t){if(e===null||typeof e!=`object`&&typeof e!=`function`)return;if(H(e))return z(e),e[t];let n=e;for(;n!==null;){if(H(n))return z(n),e[t];let r=Object.getOwnPropertyDescriptor(n,t);if(r)return`value`in r?r.value:r.get?(dn(r.get)||R(`getter`,String(t)),r.get.call(e)):void 0;n=Reflect.getPrototypeOf(n)}}function fn(e,t){if(e===null||typeof e!=`object`&&typeof e!=`function`)return!1;if(H(e))return z(e),t in e;let n=e;for(;n!==null;){if(H(n))return z(n),t in e;if(Object.getOwnPropertyDescriptor(n,t))return!0;n=Reflect.getPrototypeOf(n)}return!1}function W(e,t){if(!t||typeof e!=`object`||!e)return!1;H(e)&&z(e);let n=Reflect.getPrototypeOf(e);for(;n!==null;){if(n===t)return!0;H(n)&&z(n),n=Reflect.getPrototypeOf(n)}return!1}function pn(e){return H(e)?(z(e),e.href):cn(e)}function mn(e){return H(e)?(z(e),String(e)):ln(e)}function hn(e){return H(e)?(z(e),Array.from(e)):[...sn(e)]}function gn(e){return[...Wt(e)]}function _n(e){return[...Gt(e)]}function vn(e){return T.isDataView(e)?{buffer:nn(e),byteOffset:rn(e),byteLength:an(e)}:{buffer:Qt(e),byteOffset:$t(e),byteLength:en(e)}}const yn=new Set([`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Float16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`]),bn=new Set([`Date`,`RegExp`,`Map`,`Set`,`Array`,`DataView`,`ArrayBuffer`,`SharedArrayBuffer`,`Number`,`String`,`Boolean`,`BigInt`,`URL`,`URLSearchParams`,...yn]);function xn(e){if(T.isDate(e))return`Date`;if(T.isRegExp(e))return`RegExp`;if(T.isMap(e))return`Map`;if(T.isSet(e))return`Set`;if(Array.isArray(e))return`Array`;if(T.isTypedArray(e)){let t=Zt(e);return t!==void 0&&yn.has(t)?t:void 0}if(T.isDataView(e))return`DataView`;if(T.isArrayBuffer(e))return`ArrayBuffer`;if(T.isSharedArrayBuffer(e))return`SharedArrayBuffer`;if(T.isNumberObject(e))return`Number`;if(T.isStringObject(e))return`String`;if(T.isBooleanObject(e))return`Boolean`;if(T.isBigIntObject(e))return`BigInt`;if(W(e,URL.prototype))return`URL`;if(W(e,URLSearchParams.prototype))return`URLSearchParams`}function Sn(e){let t=U(e,Symbol.toStringTag);return typeof t==`string`?t:void 0}const Cn={tagOf:e=>{if(H(e))return z(e),$e.tagOf(e);let t=xn(e);if(t!==void 0)return t;let n=Sn(e);return n===void 0||bn.has(n)?`Object`:n},isThenable:e=>T.isPromise(e)?!0:typeof U(e,`then`)==`function`,unbox:e=>T.isNumberObject(e)?Kt(e):T.isStringObject(e)?qt(e):T.isBooleanObject(e)?Jt(e):Yt(e),toISOString:e=>Number.isNaN(Rt(e))?``:Bt(e),toStringValue:e=>W(e,URL.prototype)?pn(e):W(e,URLSearchParams.prototype)?mn(e):(R(`method`,`toString (${Sn(e)??`unknown`})`),e.toString()),regExpInfo:e=>({source:Vt(e),flags:Ht(e)}),valuesOf:e=>_n(e),entriesOf:e=>gn(e),viewInfo:e=>{let t=vn(e);return{...t,length:T.isDataView(e)?0:tn(e),bufferByteLength:T.isSharedArrayBuffer(t.buffer)?on(t.buffer):Ut(t.buffer)}},shapeOf:e=>(H(e)&&z(e),$e.shapeOf(e)),get:(e,t)=>U(e,t)},wn=Symbol.for(`workflow-serialize`),Tn=Symbol.for(`workflow-deserialize`);function En(e=globalThis){let t=e,n=t[gt];return n||(n=new Map,t[gt]=n),n}const Dn=`class//workflow//Run`;function On(e,t,n=globalThis){En(n).set(e,t)}function kn(e,t){return En(t).get(e)}function An(){return{Class:e=>{if(typeof e!=`function`)return!1;let t=U(e,`classId`);return typeof t==`string`&&{classId:t}},Instance:e=>{if(typeof e!=`object`||!e)return!1;let t=U(e,`constructor`);if(!t||typeof t!=`function`)return!1;let n=U(t,wn);if(typeof n!=`function`)return!1;let r=U(t,`classId`);if(typeof r!=`string`)throw Error(`Class "${String(U(t,`name`))}" with ${String(wn)} must have a static "classId" property.`);return R(`method`,`[WORKFLOW_SERIALIZE] (${r})`),{classId:r,data:n.call(t,e)}}}}function jn(e=globalThis){return{Class:t=>{let n=t.classId,r=kn(n,e);if(!r)throw Error(`Class "${n}" not found. Make sure the class is registered with registerSerializationClass.`);return r},Instance:t=>{let n=t.classId,r=t.data,i=kn(n,e);if(!i)throw Error(`Class "${n}" not found. Make sure the class is registered with registerSerializationClass.`);let a=i[Tn];if(typeof a!=`function`)throw Error(`Class "${n}" does not have a static ${String(Tn)} method.`);return a.call(i,r)}}}function Mn(e,t,n){if(n===0)return`.`;let r=new Uint8Array(e,t,n);return Buffer.from(r).toString(`base64`)}function G(e){let t=vn(e);return Mn(t.buffer,t.byteOffset,t.byteLength)}function K(e,t){let n=e===`.`?``:e,r=Buffer.from(n,`base64`),i=new t.ArrayBuffer(r.length);return new t.Uint8Array(i).set(r),i}function Nn(e){return JSON.parse(e)}function Pn(e){let t=Object.getOwnPropertyDescriptor(e,`stack`);return t&&`value`in t?t.value:(R(`getter`,`stack`),t?.get?t.get.call(e):U(e,`stack`))}function Fn(e){if(!T.isNativeError(e))return!1;let t={message:U(e,`message`),stack:Pn(e)};return fn(e,`cause`)&&(t.cause=U(e,`cause`)),t}function In(e,t){return!T.isNativeError(t)||U(t,`name`)!==e?!1:Fn(t)}function q(e){return t=>In(e,t)||!1}function Ln(e,t){return n=>{let r=n,i=`cause`in r?{cause:r.cause}:void 0,a=e[t],o=new a(r.message,i);return r.stack!==void 0&&(o.stack=r.stack),o}}function Rn(e=globalThis){return{ArrayBuffer:e=>T.isArrayBuffer(e)&&Mn(e,0,Ut(e)),BigInt:e=>typeof e==`bigint`&&String(e),BigInt64Array:e=>T.isBigInt64Array(e)&&G(e),BigUint64Array:e=>T.isBigUint64Array(e)&&G(e),Date:e=>T.isDate(e)?Number.isNaN(Rt(e))?`.`:Bt(e):!1,DOMException:e=>{if(typeof e!=`object`||!e)return!1;let t=U(e,`constructor`);if(!t||U(t,`name`)!==`DOMException`)return!1;let n={message:U(e,`message`),name:U(e,`name`),stack:Pn(e)};return fn(e,`cause`)&&(n.cause=U(e,`cause`)),n},EvalError:q(`EvalError`),FatalError:q(`FatalError`),HookConflictError:e=>{let t=In(`HookConflictError`,e);if(!t)return!1;let n={...t,token:U(e,`token`)},r=U(e,`conflictingRunId`);return r!==void 0&&(n.conflictingRunId=r),n},RangeError:q(`RangeError`),ReferenceError:q(`ReferenceError`),RetryableError:e=>{let t=In(`RetryableError`,e);if(!t)return!1;let n=U(e,`retryAfter`),r;if(T.isDate(n)){let e=zt(n);r=Number.isNaN(e)?Date.now()+1e3:e}else if(n&&typeof n==`object`){let e=U(n,`getTime`);if(typeof e==`function`){R(`method`,`getTime`);let t=e.call(n);r=Number.isNaN(t)?Date.now()+1e3:t}else r=Date.now()+1e3}else if(typeof n==`string`||typeof n==`number`){let e=new Date(n).getTime();r=Number.isNaN(e)?Date.now()+1e3:e}else r=Date.now()+1e3;return{...t,retryAfter:r}},RuntimeDecryptionError:e=>{let t=In(`RuntimeDecryptionError`,e);if(!t)return!1;let n={...t},r=U(e,`context`);return r!==void 0&&(n.context=r),n},StreamError:e=>{let t=In(`StreamError`,e);if(!t)return!1;let n={...t},r=U(e,`status`),i=U(e,`url`);return typeof r==`number`&&(n.status=r),typeof i==`string`&&(n.url=i),n},SyntaxError:q(`SyntaxError`),TypeError:q(`TypeError`),URIError:q(`URIError`),AggregateError:e=>{let t=In(`AggregateError`,e);return t?{...t,errors:U(e,`errors`)}:!1},Error:e=>{if(!T.isNativeError(e))return!1;let t={name:U(e,`name`),message:U(e,`message`),stack:Pn(e)};return fn(e,`cause`)&&(t.cause=U(e,`cause`)),t},Float32Array:e=>T.isFloat32Array(e)&&G(e),Float64Array:e=>T.isFloat64Array(e)&&G(e),Headers:e=>W(e,Headers.prototype)&&hn(e),Int8Array:e=>T.isInt8Array(e)&&G(e),Int16Array:e=>T.isInt16Array(e)&&G(e),Int32Array:e=>T.isInt32Array(e)&&G(e),Map:e=>T.isMap(e)&&gn(e),RegExp:e=>T.isRegExp(e)&&{source:Vt(e),flags:Ht(e)},Set:e=>T.isSet(e)&&_n(e),URL:e=>W(e,URL.prototype)&&pn(e),WorkflowFunction:e=>{if(typeof e!=`function`)return!1;let t=U(e,`workflowId`);return typeof t==`string`&&{workflowId:t}},URLSearchParams:e=>{if(!W(e,URLSearchParams.prototype))return!1;let t=mn(e);return t===``?`.`:t},Uint8Array:e=>T.isUint8Array(e)&&G(e),Uint8ClampedArray:e=>T.isUint8ClampedArray(e)&&G(e),Uint16Array:e=>T.isUint16Array(e)&&G(e),Uint32Array:e=>T.isUint32Array(e)&&G(e)}}function zn(e=globalThis){return{ArrayBuffer:t=>K(t,e),BigInt:t=>e.BigInt(t),BigInt64Array:t=>new e.BigInt64Array(K(t,e)),BigUint64Array:t=>new e.BigUint64Array(K(t,e)),Date:t=>new e.Date(t),DOMException:t=>{let n=new e.DOMException(t.message,t.name);return t.stack!==void 0&&(n.stack=t.stack),`cause`in t&&(n.cause=t.cause),n},EvalError:Ln(e,`EvalError`),FatalError:t=>{let n=new(e[Symbol.for(`@workflow/errors//FatalError`)]??ge)(t.message);return t.stack!==void 0&&(n.stack=t.stack),`cause`in t&&(n.cause=t.cause),n},HookConflictError:t=>{let n=new(e[Symbol.for(`@workflow/errors//HookConflictError`)]??me)(t.token,t.conflictingRunId);return t.stack!==void 0&&(n.stack=t.stack),`cause`in t&&(n.cause=t.cause),n},RangeError:Ln(e,`RangeError`),ReferenceError:Ln(e,`ReferenceError`),RetryableError:t=>{let n=new(e[Symbol.for(`@workflow/errors//RetryableError`)]??ye)(t.message,{retryAfter:new e.Date(t.retryAfter)});return t.stack!==void 0&&(n.stack=t.stack),`cause`in t&&(n.cause=t.cause),n},RuntimeDecryptionError:t=>{let n=e[Symbol.for(`@workflow/errors//RuntimeDecryptionError`)]??ve,r={};`cause`in t&&(r.cause=t.cause),t.context!==void 0&&(r.context=t.context);let i=new n(t.message,r);return t.stack!==void 0&&(i.stack=t.stack),i},StreamError:t=>{let n=new(e[Symbol.for(`@workflow/errors//StreamError`)]??he)(t.message,{...`cause`in t?{cause:t.cause}:{},status:t.status,url:t.url});return t.stack!==void 0&&(n.stack=t.stack),n},SyntaxError:Ln(e,`SyntaxError`),TypeError:Ln(e,`TypeError`),URIError:Ln(e,`URIError`),AggregateError:t=>{let n=`cause`in t?{cause:t.cause}:void 0,r=new e.AggregateError(t.errors,t.message,n);return t.stack!==void 0&&(r.stack=t.stack),r},Error:t=>{let n=`cause`in t?{cause:t.cause}:void 0,r=new e.Error(t.message,n);return r.name=t.name,t.stack!==void 0&&(r.stack=t.stack),r},Float32Array:t=>new e.Float32Array(K(t,e)),Float64Array:t=>new e.Float64Array(K(t,e)),Headers:t=>new e.Headers(t),Int8Array:t=>new e.Int8Array(K(t,e)),Int16Array:t=>new e.Int16Array(K(t,e)),Int32Array:t=>new e.Int32Array(K(t,e)),Map:t=>new e.Map(t),RegExp:t=>new e.RegExp(t.source,t.flags),Set:t=>new e.Set(t),URL:t=>new e.URL(t),WorkflowFunction:e=>Object.assign(()=>{throw Error(`Workflow functions cannot be called directly. Use start() to invoke them.`)},{workflowId:e.workflowId}),URLSearchParams:t=>new e.URLSearchParams(t===`.`?``:t),Uint8Array:t=>new e.Uint8Array(K(t,e)),Uint8ClampedArray:t=>new e.Uint8ClampedArray(K(t,e)),Uint16Array:t=>new e.Uint16Array(K(t,e)),Uint32Array:t=>new e.Uint32Array(K(t,e))}}function Bn(){return{StepFunction:e=>{if(typeof e!=`function`)return!1;let t=U(e,`stepId`);if(typeof t!=`string`)return!1;let n=U(e,`__closureVarsFn`),r;typeof n==`function`&&(Lt(n)||R(`method`,`__closureVarsFn`),r=n());let i=fn(e,`__boundThis`),a=i?U(e,`__boundThis`):void 0,o=U(e,`__boundArgs`),s={stepId:t};return r!==void 0&&(s.closureVars=r),i&&(s.boundThis=a),Array.isArray(o)&&o.length>0&&(s.boundArgs=o),s}}}function Vn(e=globalThis){let t=e[Symbol.for(`WORKFLOW_USE_STEP`)];return{StepFunction:e=>{let n=e.stepId,r=e.closureVars;if(!t)throw Error(`WORKFLOW_USE_STEP not found on global object. Step functions cannot be deserialized outside workflow context.`);let i=r?t(n,()=>r):t(n);if(`boundThis`in e){let t=Array.isArray(e.boundArgs)?e.boundArgs:[];return i.bind(e.boundThis,...t)}return i}}}const Hn=new TextEncoder,Un=new TextDecoder,Wn=1e5,Gn={operations:{createSparseArray(e){if(e>Wn)throw RangeError(`Sparse array length ${e} exceeds the maximum of ${Wn}`);return et.createSparseArray(e)}}};function Kn(e,t=globalThis,n){let r;switch(e){case`workflow`:r={...An(),...Bn(),...Rn(t)};break;case`step`:r={...An(),...Rn(t)};break;case`client`:r={...An(),...Rn(t)}}return n?{...r,...n}:r}function qn(e,t=globalThis,n){let r;switch(e){case`workflow`:r={...jn(t),...Vn(t),...zn(t)};break;case`step`:r={...jn(t),...zn(t)};break;case`client`:r={...jn(t),...zn(t),StepFunction:()=>{throw Error(`Step functions cannot be deserialized in client context.`)}}}return n?{...r,...n}:r}const J={formatPrefix:S.DEVALUE_V1,serialize(e,t,n){let r=Kn(t,n?.global,n?.extraReducers),i=Pt(n?.guestCodeStats,()=>O(e,r,{operations:Cn}));return Hn.encode(i)},deserialize(e,t,n){let r=qn(t,n?.global,n?.extraRevivers);return tt(Un.decode(e),r,Gn)},deserializeLegacy(e,t,n){return nt(e,qn(t,n?.global,n?.extraRevivers),Gn)}};function Jn(){try{return typeof process<`u`&&process.env?.WORKFLOW_DISABLE_COMPRESSION===`1`}catch{return!1}}function Yn(){try{let e=process.env?.WORKFLOW_COMPRESSION_CODEC;return e===`gzip`||e===`zstd`?e:void 0}catch{return}}function Xn(){try{return globalThis.process?.getBuiltinModule?.(`node:zlib`)}catch{return}}function Zn(){let e=Xn();return typeof e?.zstdCompressSync==`function`&&typeof e?.zstdDecompressSync==`function`}function Qn(){return typeof CompressionStream==`function`&&typeof DecompressionStream==`function`}async function $n(e,t){let n=t.writable.getWriter(),r=n.write(e).then(()=>n.close());r.catch(()=>{});let i=[],a=0,o=t.readable.getReader();for(;;){let{done:e,value:t}=await o.read();if(e)break;i.push(t),a+=t.length}await r;let s=new Uint8Array(a),c=0;for(let e of i)s.set(e,c),c+=e.length;return s}async function er(e){return $n(e,new CompressionStream(`gzip`))}async function tr(e){return $n(e,new DecompressionStream(`gzip`))}function nr(e){let t=Xn(),n=t?.constants?.ZSTD_c_compressionLevel,r=n===void 0?void 0:{params:{[n]:3}};return new Uint8Array(t.zstdCompressSync(e,r))}function rr(e){let t=Xn();if(!t?.zstdDecompressSync)throw Error(`Compressed (zstd) workflow data encountered but node:zlib zstd support is not available in this runtime (requires Node.js 22.15+). In the browser, register a zstd decoder via registerZstdDecoder (serialization-format.ts).`);return new Uint8Array(t.zstdDecompressSync(e))}function Y(e,t,n,r){e&&(e.recorded=!0,e.compressed=t!==`none`,e.codec=t,e.uncompressedBytes=n,e.storedBytes=r)}function ir(){return Yn()===`gzip`?Qn()?`gzip`:`none`:Zn()?`zstd`:Qn()?`gzip`:`none`}async function ar(e,t,n){if(!(e instanceof Uint8Array))return e;if(!t||e.length<1024||Jn())return Y(n,`none`,e.length,e.length),e;let r=ir();if(r===`none`)return Y(n,`none`,e.length,e.length),e;let i=r===`zstd`?nr(e):await er(e),a=r===`zstd`?S.ZSTD:S.GZIP,o=4+i.length;return o>=e.length*.95?(Y(n,`none`,e.length,e.length),e):(Y(n,r,e.length,o),u(a,i))}async function or(e,t){if(!(e instanceof Uint8Array))return e;let n=h(e);if(n===S.ZSTD){let{payload:n}=c(e),r=rr(n);return Y(t,`zstd`,r.length,e.length),r}if(n===S.GZIP){if(!Qn())throw Error(`Compressed (gzip) workflow data encountered but DecompressionStream is not available in this runtime. Node.js 18+, browsers, and edge runtimes all support it.`);let{payload:n}=c(e),r=await tr(n);return Y(t,`gzip`,r.length,e.length),r}return Y(t,`none`,e.length,e.length),e}function sr(e){if(ve.is(e))throw e}function X(e,t){let n=e.includes(`return value`)?`returning`:`passing`,r=`Failed to serialize ${e}`;t instanceof E&&t.path&&(r+=` at path "${t.path}"`);let i=`Ensure you're ${n} workflow serializable types. Check the serialization docs to see what's serializable: https://workflow-sdk.dev/docs/foundations/serialization`;return t instanceof E&&t.value!==void 0&&b.error(`Serialization failed`,{context:e,problematicValue:t.value}),{message:r,hint:i}}async function cr(e,t,n){try{let r=J.serialize(e,`client`,n),i=await ar(u(S.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats);return oe(i,t)}catch(e){sr(e);let{message:t,hint:n}=X(`client value`,e);throw new w(t,{hint:n,cause:e})}}async function lr(e,t,n){let r=await or(await o(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(J.deserializeLegacy)return J.deserializeLegacy(r,`client`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=c(r);if(i===S.DEVALUE_V1)return J.deserialize(a,`client`,n);throw Error(`Unsupported serialization format: ${i}`)}async function ur(e,t,n){try{let r=J.serialize(e,`step`,n),i=await ar(u(S.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats);return oe(i,t)}catch(e){sr(e);let{message:t,hint:n}=X(`step value`,e);throw new w(t,{hint:n,cause:e})}}async function dr(e,t,n){let r=await or(await o(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(J.deserializeLegacy)return J.deserializeLegacy(r,`step`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=c(r);if(i===S.DEVALUE_V1)return J.deserialize(a,`step`,n);throw Error(`Unsupported serialization format: ${i}`)}function fr(e,t){if(!(e instanceof Uint8Array)){if(J.deserializeLegacy)return J.deserializeLegacy(e,`workflow`,t);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:n,payload:r}=c(e);if(n===S.DEVALUE_V1)return J.deserialize(r,`workflow`,t);throw Error(`Unsupported serialization format: ${n}`)}const pr=Symbol.for(`WORKFLOW_STEP_CONTEXT_STORAGE`),mr=(()=>{let e=globalThis;return e[pr]??=new Te,e[pr]})();function hr(e,t,n){if(e===0&&t===0&&n===0)return null;let r=[];e>0&&r.push(`${e} ${fe(`step`,`steps`,e)}`),t>0&&r.push(`${t} ${fe(`hook`,`hooks`,t)}`),n>0&&r.push(`${n} ${fe(`timer`,`timers`,n)}`);let i=[];e>0&&i.push(`steps are completed`),t>0&&i.push(`hooks are received`),n>0&&i.push(`timers have elapsed`);let a=i.join(` and `);return`${r.join(` and `)} to be enqueued\n Workflow will suspend and resume when ${a}`}function gr(e,t){let n=`${e.replace(`wrun_`,`strm_`)}_user`;return t?`${n}_${Buffer.from(t,`utf-8`).toString(`base64url`)}`:n}function _r(e){return`strm_${e}_system_abort`}function vr(e){if(!e.startsWith(`abrt_`))throw Error(`Invalid abort hook token format: expected "abrt_" prefix, got "${e}"`);return _r(e.slice(5))}const yr=()=>n(`WORKFLOW_DEFERRED_CHECK_DELAY_MS`,100,{integer:!0,min:10}),br=new Set([`hook_received`,`hook_conflict`,`wait_completed`,`attr_set`,`run_cancelled`]),xr=new Set([`wait_completed`]);function Sr(e,t){return`${e}:${t}`}const Cr=new Set([`run_completed`,`run_failed`,`run_cancelled`]);var Z;(function(e){e[e.Consumed=0]=`Consumed`,e[e.NotConsumed=1]=`NotConsumed`,e[e.Finished=2]=`Finished`})(Z||={});var wr=class{eventIndex;events;callbacks=[];parked=[];resolved=new Set;seenEventClasses=new Map;onConsumedEvent;onUnconsumedEvent;onDuplicateEvent;getPromiseQueue;isDeliveryIdle;pendingUnconsumedCheck=null;pendingUnconsumedTimeout=null;unconsumedCheckVersion=0;lastConsumed;constructor(e,t){this.events=[...e],this.eventIndex=0,this.onConsumedEvent=t.onConsumedEvent,this.onUnconsumedEvent=t.onUnconsumedEvent,this.onDuplicateEvent=t.onDuplicateEvent,this.getPromiseQueue=t.getPromiseQueue,this.isDeliveryIdle=t.isDeliveryIdle}get strandedEvent(){return this.parked[0]?.event}get parkedSummary(){let e=this.parked[0]?.event;if(e)return{count:this.parked.length,eventId:e.eventId,eventType:e.eventType}}describe(){return{index:this.eventIndex,length:this.events.length,parked:this.parked.length,lastConsumedEventId:this.lastConsumed?.eventId}}append(e){for(let t of e)this.events.push(t);process.nextTick(this.consume)}subscribe(e){this.callbacks.push(e),this.pendingUnconsumedCheck!==null&&(this.unconsumedCheckVersion++,this.pendingUnconsumedCheck=null,this.pendingUnconsumedTimeout!==null&&(clearTimeout(this.pendingUnconsumedTimeout),this.pendingUnconsumedTimeout=null)),process.nextTick(this.consume)}notifyConsumedEvent(e){if(this.onConsumedEvent)try{this.onConsumedEvent(e)}catch(e){x.error(`onConsumedEvent callback threw an error`,{error:e})}}consume=()=>{for(;;){this.drainParked();let t=this.events[this.eventIndex]??null;if(t!==null&&e(t)){this.skipSealedNoop(t);continue}let n=this.offer(t);if(n&&this.eventIndex++,t===null){n||this.handleEndOfLog();return}if(!n){let e=this.firstEventTypeOfClass(t);if(e!==void 0){this.skipDuplicateEvent(t,e);continue}this.scheduleUnconsumedCheck(t,!0);return}}};offer(e){for(let t=0;t<this.callbacks.length;t++){let n=this.callbacks[t],r=Z.NotConsumed;try{r=n(e)}catch(e){x.error(`EventConsumer callback threw an error`,{error:e})}if(r===Z.Consumed||r===Z.Finished)return e!==null&&(e.correlationId&&xr.has(e.eventType)&&this.resolved.add(Sr(e.eventType,e.correlationId)),this.recordEventClass(e),this.lastConsumed=e,this.notifyConsumedEvent(e)),r===Z.Finished&&this.callbacks.splice(t,1),!0}return!1}drainParked(){let e=this.parked.length>0;for(;e;){e=!1,this.dropParkedDuplicates();for(let t=0;t<this.parked.length;t++){let n=this.parked[t],r=this.eventIndex;this.eventIndex=n.index;let i;try{i=this.offer(n.event)}finally{this.eventIndex=r}if(i){this.parked.splice(t,1),e=this.parked.length>0;break}}}}dropParkedDuplicates(){for(let e=this.parked.length-1;e>=0;e--){let t=this.parked[e].event,n=this.firstEventTypeOfClass(t);if(n!==void 0){this.parked.splice(e,1),x.debug(`Releasing a parked event that repeats a class already in the log`,{eventId:t.eventId,eventType:t.eventType,firstEventType:n,correlationId:t.correlationId});try{this.onDuplicateEvent?.(t,n)}catch(e){x.error(`onDuplicateEvent callback threw an error`,{error:e})}}}}park(e){return!br.has(e.eventType)||e.correlationId&&this.resolved.has(Sr(e.eventType,e.correlationId))?!1:(this.parked.push({event:e,index:this.eventIndex}),this.eventIndex++,x.debug(`Parked an unclaimed event for later delivery`,{eventId:e.eventId,eventType:e.eventType,correlationId:e.correlationId,parked:this.parked.length}),!0)}eventClassKey(e){let n=t(e);return n===void 0?void 0:`${n.eventClass}:${n.entity}`}recordEventClass(e){let t=this.eventClassKey(e);t!==void 0&&!this.seenEventClasses.has(t)&&this.seenEventClasses.set(t,e.eventType)}firstEventTypeOfClass(e){let t=this.eventClassKey(e);return t===void 0?void 0:this.seenEventClasses.get(t)}skipSealedNoop(e){this.eventIndex++,x.debug(`Skipping sealed-log noop event`,{eventId:e.eventId})}skipDuplicateEvent(e,t){this.eventIndex++,x.debug(`Skipping event that repeats a class already in the log`,{eventId:e.eventId,eventType:e.eventType,firstEventType:t,correlationId:e.correlationId});try{this.onDuplicateEvent?.(e,t)}catch(e){x.error(`onDuplicateEvent callback threw an error`,{error:e})}}handleEndOfLog(){if(this.parked.length===0)return;let e=this.events.at(-1);if(!e||!Cr.has(e.eventType)){x.debug(`Reached the end of the log still holding events`,{eventId:this.parked[0].event.eventId,eventType:this.parked[0].event.eventType,correlationId:this.parked[0].event.correlationId,parked:this.parked.length});return}this.scheduleUnconsumedCheck(this.parked[0].event,!1)}scheduleUnconsumedCheck(e,t){let n=++this.unconsumedCheckVersion;this.pendingUnconsumedCheck=this.getPromiseQueue().then(()=>new Promise(e=>setTimeout(e,0))).then(()=>this.getPromiseQueue()).then(()=>{this.whenDeliveryIdle(n,()=>{this.pendingUnconsumedTimeout=setTimeout(()=>{this.pendingUnconsumedTimeout=null,this.unconsumedCheckVersion===n&&(this.pendingUnconsumedCheck=null,this.resolveUnconsumedEvent(e,t))},yr())})})}resolveUnconsumedEvent(e,t){if(t){if(this.events[this.eventIndex]!==e)return;if(this.park(e)){this.consume();return}}this.onUnconsumedEvent(e)}whenDeliveryIdle(e,t){let n=()=>{if(this.pendingUnconsumedTimeout=null,this.unconsumedCheckVersion===e){if(this.isDeliveryIdle()){t();return}this.getPromiseQueue().then(()=>{this.unconsumedCheckVersion===e&&(this.pendingUnconsumedTimeout=setTimeout(n,0))})}};n()}},Tr=class{aborted=!1;reason=void 0;[N];[P];#e=[];#t=null;get onabort(){return this.#t}set onabort(e){this.#t=e,e&&this.aborted&&e.call(this)}constructor(e,t){this[N]=e,this[P]=t}_setAborted(e){if(!this.aborted){this.aborted=!0,this.reason=e,this.#t&&this.#t.call(this);for(let e of this.#e)e();this.#e=[]}}addEventListener(e,t){if(e===`abort`){if(this.aborted){t();return}this.#e.push(t)}}removeEventListener(e,t){e===`abort`&&(this.#e=this.#e.filter(e=>e!==t))}throwIfAborted(){if(this.aborted)throw this.reason??new DOMException(`The operation was aborted.`,`AbortError`)}};function Er(e){return class{signal;[N];[P];constructor(){let t=e.generateUlid(),n=_r(t),r=`abrt_${t}`;this[N]=n,this[P]=r,this.signal=new Tr(n,r);let i=`hook_${e.generateUlid()}`;e.invocationsQueue.set(i,{type:`hook`,correlationId:i,token:r,isWebhook:!1,isSystem:!0}),e.eventsConsumer.subscribe(t=>{if(!t||t.correlationId!==i)return Z.NotConsumed;let n=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof n==`string`&&n!==this[P])return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new _e(`Replay divergence: abort hook event ${t.eventType} for ${i} belongs to token "${n}", but the current abort hook expects "${this[P]}"`,{eventId:t.eventId}))}),Z.Finished;if(t.eventType===`hook_created`){let t=e.invocationsQueue.get(i);return t&&t.type===`hook`&&(t.hasCreatedEvent=!0),Z.Consumed}if(t.eventType===`hook_received`){let n=t.eventData?.payload,r=e.eventsConsumer.eventIndex,a=we(e,r,`hook`,{deliveredAt:+t.createdAt}),o=Se(e,r,`hook`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{let r;try{if(n!==void 0)try{let i=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,n),a=await Fi(n,e.runId,e.encryptionKey,e.globalThis,{},i);a&&typeof a==`object`&&`reason`in a&&(r=a.reason)}catch{}}finally{e.pendingDeliveries--}o.then(()=>{a.markDelivered(),this.signal._setAborted(r)})}),e.invocationsQueue.delete(i),Z.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(i),Z.Finished):Z.NotConsumed})}abort(t){if(!this.signal.aborted){this.signal._setAborted(t);for(let[,n]of e.invocationsQueue)if(n.type===`hook`&&n.token===this[P]){n.abortRequested=!0,n.abortReason=t;break}}}}}function Dr(){return{abort(e){let t=new Tr(``,``);return t._setAborted(e??new DOMException(`The operation was aborted.`,`AbortError`)),t},any(e){let t=new Tr(``,``),n=Array.from(e);for(let e of n)if(e.aborted)return t._setAborted(e.reason),t;let r=[],i=()=>{for(let{signal:e,listener:t}of r)e.removeEventListener&&e.removeEventListener(`abort`,t);r.length=0};for(let e of n){if(!e.addEventListener)continue;let n=()=>{t.aborted||(t._setAborted(e.reason),i())};r.push({signal:e,listener:n}),e.addEventListener(`abort`,n)}return t},timeout(){throw Error(`AbortSignal.timeout() is not supported in workflow functions. Use sleep() with an AbortController instead. See: /docs/errors/abort-signal-timeout-in-workflow`)}}}const Or=i();function kr(e){try{return e.getReader({mode:`byob`}).releaseLock(),`bytes`}catch{}}function Ar(e){return sr(e),e instanceof w&&e.cause!==void 0||e instanceof C&&e.cause!==void 0?e.cause:e}async function Q(e,t){if(e.recorded)try{let n=await se();if(!n)return;let r=e.uncompressedBytes??0,i=e.storedBytes??0;n.setAttributes({...ue(t),...ce(e.compressed??!1),...te(e.codec??`none`),...ie(r),...le(i),...e.compressed&&r>0?de(1-i/r):{}})}catch{}}async function jr(e){let t=e.totalExecutions??e.executions.length;if(t!==0)try{let n=await se();if(!n)return;let r=[...new Set(e.executions.map(e=>e.detail?`${e.kind} (${e.detail})`:e.kind))];n.setAttributes({...re(t),...ne(r)})}catch{}}function Mr(e,t){let n=new TextEncoder,r={resolved:!1,key:void 0},i;return new TransformStream({async transform(a,o){try{r.resolved||(r.key=await p(t),r.resolved=!0,ae(r.key)&&(i=g(r.key.recipientPublicKey,r.key.aad)));let s=O(a,e),c=n.encode(s),l=u(S.DEVALUE_V1,c);i?l=u(S.SEALED,await i.seal(l)):r.key&&(l=await oe(l,r.key));let d=new Uint8Array(4+l.length);new DataView(d.buffer).setUint32(0,l.length,!1),d.set(l,4),o.enqueue(d)}catch(e){if(ve.is(e)){o.error(e);return}let{message:t,hint:n}=X(`stream chunk`,e);o.error(new w(t,{hint:n,cause:e}))}}})}function Nr(e,t){let n=new TextDecoder,r=new Uint8Array,i={resolved:!1,key:void 0},u;function d(e){let t=new Uint8Array(r.length+e.length);t.set(r,0),t.set(e,r.length),r=t}async function f(d){for(i.resolved||(i.key=await p(t),i.resolved=!0,a(i.key)&&(u=l(i.key.keyPair,i.key.aad)));r.length>=4;){let t=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,!1);if(r.length<4+t)break;let l=r.slice(4,4+t);r=r.slice(4+t);let{format:f,payload:p}=c(l);if(f===S.ENCRYPTED||f===S.SEALED){let e=f===S.SEALED;if(!(e?a(i.key):s(i.key)!==void 0)){d.error(new ve(e?`Sealed stream data encountered but no run keypair is available. Opening a sealed frame requires the run's own encryption key material.`:`Encrypted stream data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.`,{context:{operation:`decrypt`,byteLength:p.byteLength,formatPrefix:e?`encp`:`encr`}}));return}let t;try{t=e?await u.open(c(l).payload):await o(l,i.key)}catch(e){throw ve.is(e)&&e.context&&(e.context.formatPrefix=f),e}({format:f,payload:p}=c(t))}if(f===S.DEVALUE_V1){let t=n.decode(p);d.enqueue(tt(t,e))}}}return new TransformStream({async transform(t,i){if(r.length===0&&t.length>=4){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1);if(e>0&&e<1e8){d(t),await f(i);return}}else if(r.length>0){d(t),await f(i);return}let a=n.decode(t).split(`
`);for(let t of a)t.length>0&&i.enqueue(tt(t,e))},async flush(e){r.length>0&&await f(e)}})}const Pr=1e8;function Fr(){return new TransformStream({transform(e,t){if(e.length===0)return;if(e.length>Pr){t.error(new C(`Byte-stream chunk of ${e.length} bytes exceeds the maximum framed chunk size (${Pr}). Split the data into smaller chunks before writing.`,{slug:`serialization-failed`}));return}let n=new Uint8Array(4+e.length);new DataView(n.buffer).setUint32(0,e.length,!1),n.set(e,4),t.enqueue(n)}})}function Ir(){let e=new Uint8Array;function t(t){let n=new Uint8Array(e.length+t.length);n.set(e,0),n.set(t,e.length),e=n}return new TransformStream({transform(n,r){for(n.length>0&&t(n);e.length>=4;){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1);if(t>Pr){r.error(new C(`Byte-stream frame length ${t} exceeds maximum (${Pr}). This usually means a non-framed byte stream is being read as framed.`,{slug:`serialization-failed`}));return}let n=4+t;if(e.length<n)break;r.enqueue(e.slice(4,n)),e=e.slice(n)}},flush(t){e.length>0&&t.error(new C(`Byte-stream ended with ${e.length} bytes of incomplete frame data. The stream was truncated mid-frame.`,{slug:`serialization-failed`}))}})}function Lr(e,t,n,r,i){(async()=>{await y(`workflow.stream.read`,e,{kind:await v(`CLIENT`),attributes:{"workflow.run.id":t,"workflow.stream.name":n,"workflow.stream.operation":`read`,"workflow.stream.read.ttfc_ms":Date.now()-e,...typeof i==`number`?{"workflow.stream.read.connect_ms":i}:{},...typeof r==`number`?{"workflow.stream.start_index":r}:{}}})})()}function Rr(e,t,n,r){(async()=>{await y(`workflow.stream.read.resolve_key`,e,{kind:await v(`CLIENT`),attributes:{"workflow.run.id":t,"workflow.stream.name":n,"workflow.stream.read.key_succeeded":r}})})()}function zr(e,t,n,r,i,a){(async()=>{await y(`workflow.stream.read.complete`,e,{kind:await v(`CLIENT`),attributes:{"workflow.run.id":t,"workflow.stream.name":n,"workflow.stream.operation":`read_complete`,"workflow.stream.read.total_ms":Date.now()-e,"workflow.stream.read.chunks":r,"workflow.stream.read.bytes":i,...typeof a==`number`?{"workflow.stream.read.reconnects":a}:{}}})})()}var Br=class extends ReadableStream{#e;constructor(e,t,n){if(typeof t!=`string`||t.length===0)throw new C(`"name" is required, got "${t}"`);let r,i=!1,a,o=0,s=0;super({type:`bytes`,pull:async c=>{let l=this.#e;if(!l){r===void 0&&(r=Date.now());let i=await f(),o=Date.now(),s=await i.streams.get(e,t,n);a=Date.now()-o,l=this.#e=s.getReader()}if(!l){c.error(Error(`Failed to get reader`));return}let u=await l.read();u.done?(this.#e=void 0,r!==void 0&&zr(r,e,t,o,s),c.close()):(!i&&u.value.byteLength>0&&r!==void 0&&(i=!0,Lr(r,e,t,n,a)),o+=1,s+=u.value.byteLength,c.enqueue(u.value))},cancel:async e=>{this.#e&&=(await this.#e.cancel(e).catch(()=>{}),void 0)}})}};const Vr=50,Hr=()=>n(`WORKFLOW_FRAMED_STREAM_MAX_RECONNECTS`,50,{integer:!0,min:1}),Ur=1e3,Wr=()=>n(`WORKFLOW_FRAMED_STREAM_MAX_TOTAL_RECONNECTS`,Ur,{integer:!0,min:1});function Gr(e,t,n,r=async()=>void 0){let i=n===void 0||n>=0,a=n??0,o=0,s=0,c=0,l,u=!1,d,p=new Uint8Array,m,h,g=!1,_=0,ee=0,te=!1;function v(){if(te)return;te=!0;let n=Date.now();r().then(r=>{r&&Rr(n,e,t,!0)},()=>Rr(n,e,t,!1))}async function ne(){if(u)return!1;let r=await f();if(u)return!1;let s=i?a+o:n,c=Date.now(),p=await r.streams.get(e,t,s);return u?(await p.cancel(d).catch(()=>{}),!1):(h===void 0&&(h=Date.now()-c),l=p.getReader(),!0)}async function re(){try{let n=await(await f()).streams.getInfo(e,t);return n.done&&a+o>n.tailIndex}catch{return!0}}async function y(){if(u||(l&&=(await l.cancel().catch(()=>{}),void 0),u))return!1;a+=o,o=0,p=new Uint8Array;let e=Hr(),n=Wr();for(;;){if(s++,c++,s>e)throw new he(`Stream "${t}" exceeded maximum reconnection attempts (${e})`);if(c>n)throw new he(`Stream "${t}" exceeded maximum total reconnection attempts (${n})`);try{return!!await ne()}catch(e){if(u)return!1;if(pe.is(e))throw e}}}return new ReadableStream({pull:async r=>{if(!u)for(m===void 0&&(m=Date.now()),v();;){if(!l)try{if(!await ne())return}catch(e){if(u)return;r.error(e);return}let a;try{a=await l.read()}catch(e){if(u)return;if(!i){r.error(e);return}try{if(!await y())return}catch(e){r.error(e);return}continue}if(u)return;if(a.done||!a.value){l=void 0;let n=!i||await re();if(u)return;if(!n){try{if(!await y())return}catch(e){r.error(e);return}continue}m!==void 0&&zr(m,e,t,_,ee,c),r.close();return}let d=a.value;if(d.length>0){let e=new Uint8Array(p.length+d.length);e.set(p,0),e.set(d,p.length),p=e}let f=!1;for(;p.length>=4;){let i=4+new DataView(p.buffer,p.byteOffset,p.byteLength).getUint32(0,!1);if(p.length<i)break;r.enqueue(p.slice(0,i)),p=p.slice(i),o++,_++,ee+=i,!g&&m!==void 0&&(g=!0,Lr(m,e,t,n,h)),f=!0}if(f){s=0;return}}},cancel:async e=>{u=!0,d=e;let t=l;l=void 0,t&&await t.cancel(e).catch(e=>{console.warn(`Error closing ReadableStream reader:`,e)})}})}const Kr=()=>{let e=n(`WORKFLOW_STREAM_FLUSH_INTERVAL_MS`,NaN,{integer:!0});return Number.isNaN(e)?void 0:e};function qr(e,t,n,r,i,a,o){(async()=>{await y(`workflow.stream.flush`,e,{kind:await v(`CLIENT`),attributes:{"workflow.run.id":n,"workflow.stream.name":r,"workflow.stream.operation":`flush`,"workflow.stream.flush.buffer_dwell_ms":t-e,"workflow.stream.flush.chunks":i,"workflow.stream.flush.bytes":a,"workflow.stream.write.chunk_rtt":o}})})()}function Jr(e,t,n){(async()=>{await y(`workflow.stream.close`,e,{kind:await v(`CLIENT`),attributes:{"workflow.run.id":t,"workflow.stream.name":n,"workflow.stream.operation":`close`,"workflow.stream.close.rpc_ms":Date.now()-e}})})()}var $=class extends WritableStream{constructor(e,t,n){if(typeof e!=`string`)throw new C(`"runId" must be a string, got "${typeof e}"`);if(typeof t!=`string`||t.length===0)throw new C(`"name" is required, got "${t}"`);let r=f(),i=n,a=async()=>{if(i){try{await i}catch{}i=void 0}},o=`wrtr_${Or()}`,s=a().then(async()=>(await r).streams.createWriteSession?.(e,t,{writerId:o})),c=0,l=[],u=0,d=0,p=0,m=null,h=null,g,_=Kr(),ee=null,te=bt(),v=xt(),ne=yt(),re=St(),y,ie=[],ae=[],oe=e=>{let t=[...ie,...ae];ie=[],ae=[];for(let n of t)n.reject(e)},se=()=>{let e=0,t=0;for(let n of l){if(e>=te||e>0&&t+n.byteLength>v)break;e++,t+=n.byteLength}let n=l.slice(0,e);return l=l.slice(e),u-=t,{group:n,bytes:t}},ce=async(n,i,o)=>{await a();let l=await r,u=await s,d=Date.now();if(u)await u.write(c,n);else if(typeof l.streams.writeMulti==`function`&&n.length>1)await l.streams.writeMulti(e,t,n);else for(let r of n)await l.streams.write(e,t,r);c+=n.length,o!==void 0&&qr(o,d,e,t,n.length,i,Date.now()-d)},le=async()=>{for(;l.length>0;){m&&=(clearTimeout(m),null);let e=y,t=Date.now(),{group:n,bytes:r}=se();d=n.length,p=r,y=l.length>0?t:void 0;try{await ce(n,r,e),d=0,p=0}catch(t){throw l=n.concat(l),u+=r,d=0,p=0,y=e!==void 0&&y!==void 0?Math.min(e,y):e??y,t}let i=ie;ie=[];for(let e of i)e.resolve()}},b=()=>{h||g!==void 0||l.length===0||(h=le().then(()=>{if(h=null,l.length>0){b();return}let e=ae;ae=[];for(let t of e)t.resolve()},e=>{h=null,g??=e,oe(g)}))},ue=()=>{if(!(m||h)){if(_===void 0){ee??=Promise.resolve(r).then(e=>{_=e.streamFlushIntervalMs??0},()=>{_=0}).then(()=>{l.length>0&&ue()});return}if(_<=0){b();return}m=setTimeout(()=>{m=null,b()},_)}},x=async()=>{for(;;){if(g!==void 0)throw g;if(l.length===0&&!h)return;b(),await new Promise((e,t)=>{ae.push({resolve:e,reject:t})})}};super({async write(e){if(g!==void 0)throw g;for(y===void 0&&(y=Date.now()),l.push(e),u+=e.byteLength,l.length>=te||u>=v?b():ue();g===void 0&&(l.length+d>=ne||u+p>=re);)b(),await new Promise((e,t)=>{ie.push({resolve:e,reject:t})});if(g!==void 0)throw g},async close(){await x(),await a();let n=await r,i=await s,o=Date.now();i?await i.close():await n.streams.close(e,t),Jr(o,e,t)},async abort(e){try{await x()}catch{}m&&=(clearTimeout(m),null),l=[],u=0,g??=e??Error(`Stream aborted`),oe(g),await(await s.catch(()=>void 0))?.dispose?.()}}),Object.defineProperty(this,pt,{value:x,enumerable:!1,writable:!1})}};function Yr(e=globalThis){let t=xe(()=>ei(e,`Request`)),n=xe(()=>ei(e,`Response`));return{...An(),...Bn(),...Rn(e),Request:e=>{if(!W(e,t.value))return!1;let n={method:U(e,`method`),url:U(e,`url`),headers:U(e,`headers`),body:U(e,`body`),duplex:U(e,`duplex`)},r=U(e,ht);r&&(n.responseWritable=r);let i=U(e,`signal`);return i&&(U(i,`aborted`)||U(i,N))&&(n.signal=i),n},Response:e=>W(e,n.value)?{type:U(e,`type`),url:U(e,`url`),status:U(e,`status`),statusText:U(e,`statusText`),headers:U(e,`headers`),body:U(e,`body`),redirected:U(e,`redirected`)}:!1}}function Xr(e,t,n,r,i,a){let o=t[N],s=t[P];if(!o){let e=(n[ut]||Or)();o=_r(e),s=`abrt_${e}`,t[N]=o,t[P]=s,t.signal&&(t.signal[N]=o,t.signal[P]=s)}return Qr(e,o,i,a,r),{streamName:o,hookToken:s,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function Zr(e,t){let n=t[N]??t.signal?.[N],r=t[P]??t.signal?.[P];if(!n)throw Error(`AbortController/AbortSignal stream name is not set`);return{streamName:n,hookToken:r,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function Qr(e,t,n,r,i){e.aborted||e[_t]||(e[_t]=!0,e.addEventListener(`abort`,()=>{i.push((async()=>{try{let i=await p(r),a=await Oi({aborted:!0,reason:e.reason},n,i),o=new $(n,t).getWriter();await o.write(a),await o.close()}catch{}})())},{once:!0}))}function $r(e=globalThis,t,n,r,i=!1,a,o=t){return{...Yr(e),ReadableStream:s=>{if(!(s instanceof e.ReadableStream))return!1;if(s.locked)throw new w(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let c=`strm_${(e[ut]||Or)()}`,l=kr(s),u=new $(n,c,a);l===`bytes`?i?t.push(s.pipeThrough(Fr()).pipeTo(u)):t.push(s.pipeTo(u)):t.push(s.pipeThrough(Mr($r(e,t,n,r,i,a,o),r)).pipeTo(u));let d={name:c};return l&&(d.type=l),l===`bytes`&&i&&(d.framing=`framed-v1`),d},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let r=t[k],i=t[A];if(typeof r==`string`&&typeof i==`string`){let e={name:r,runId:i},n=t[M];typeof n==`string`&&(e.encryptionPublicKey=n);let a=t[j];return typeof a==`string`&&(e.deploymentId=a),e}let a=`strm_${(e[ut]||Or)()}`,s=new Br(n,a);return o.push(s.pipeTo(t)),{name:a}},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:Xr(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:Xr(i,i,e,t,n,r)}}function ei(e,t){let n=U(e,t)??U(globalThis,t);if(typeof n==`function`)return U(n,`prototype`)}function ti(e=globalThis){let t=xe(()=>ei(e,`ReadableStream`)),n=xe(()=>ei(e,`WritableStream`)),r=xe(()=>ei(e,`AbortController`)),i=xe(()=>ei(e,`AbortSignal`));return{...Yr(e),ReadableStream:e=>{if(!W(e,t.value))return!1;let n=U(e,mt);if(n!==void 0)return{bodyInit:n};let r=U(e,k);if(!r)throw new C("ReadableStream `name` is not set");let i={name:r},a=U(e,dt);a&&(i.type=a);let o=U(e,ft);return o&&(i.framing=o),i},WritableStream:e=>{if(!W(e,n.value))return!1;let t=U(e,k);if(!t)throw new C("WritableStream `name` is not set");let r={name:t},i=U(e,A);typeof i==`string`&&(r.runId=i);let a=U(e,j);typeof a==`string`&&(r.deploymentId=a);let o=U(e,M);return typeof o==`string`&&(r.encryptionPublicKey=o),r},AbortController:e=>{if(typeof e!=`object`||!e)return!1;let t=e,n=U(e,N),i=W(e,r.value);if(n===void 0&&!i){let t=U(e,`signal`);if(typeof t!=`object`||!t||U(t,N)===void 0)return!1}let a=U(e,`signal`);return a?Zr(a,t):!1},AbortSignal:e=>{if(typeof e!=`object`||!e)return!1;let t=U(e,N)!==void 0,n=W(e,i.value);return!t&&!n?!1:Zr(e,e)}}}function ni(e=globalThis,t,n,r,i=!1,a,o=t){return{...Yr(e),ReadableStream:s=>{if(!(s instanceof e.ReadableStream))return!1;if(s.locked)throw new w(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let c=s[k],l=s[dt],u=s[ft];if(!c){c=`strm_${(e[ut]||Or)()}`,l=kr(s),u=l===`bytes`&&i?`framed-v1`:u;let d=new $(n,c,a);l===`bytes`?u===`framed-v1`?t.push(s.pipeThrough(Fr()).pipeTo(d)):t.push(s.pipeTo(d)):t.push(s.pipeThrough(Mr(ni(e,t,n,r,i,a,o),r)).pipeTo(d))}let d={name:c};return l&&(d.type=l),u&&(d.framing=u),d},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let i=t[k],a=t[A];i||(i=`strm_${(e[ut]||Or)()}`,o.push(new Br(n,i).pipeThrough(Nr(vi(e,o,n,r),r)).pipeTo(t)));let s={name:i};typeof a==`string`&&(s.runId=a);let c=t[M];typeof c==`string`&&(s.encryptionPublicKey=c);let l=t[j];return typeof l==`string`&&(s.deploymentId=l),s},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:Xr(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:Xr(i,i,e,t,n,r)}}function ri(...e){let t=new WeakSet;function n(e){let t=e[vt];t&&!t.signal.aborted&&t.abort()}function r(e){if(typeof e==`object`&&e&&!t.has(e)){if(t.add(e),e instanceof AbortController){n(e),n(e.signal);return}if(e instanceof AbortSignal){n(e);return}if(Array.isArray(e)){for(let t of e)r(t);return}if(e instanceof Map){for(let t of e.values())r(t);return}if(e instanceof Set){for(let t of e)r(t);return}if(typeof Request<`u`&&e instanceof Request){r(e.signal);return}for(let t of Object.values(e))r(t)}}for(let t of e)r(t)}function ii(e,t,n,r){let i=new AbortController;return r.push((async()=>{try{let r=new Br(t,n).getReader(),a=await Promise.race([r.read(),new Promise(e=>{if(i.signal.aborted){e({value:void 0,done:!0});return}i.signal.addEventListener(`abort`,()=>e({value:void 0,done:!0}),{once:!0})})]);if(a.value&&!a.done){try{r.releaseLock()}catch{}try{let n=mr.getStore(),r=await ki(a.value,t,n?.encryptionKey);e.abort(r?.reason)}catch{e.abort()}}else r.cancel().catch(()=>{})}catch{}})()),i}function ai(e,t,n){let r=e,i=e.signal;r[N]=t.streamName,r[P]=t.hookToken,i[N]=t.streamName,i[P]=t.hookToken,n&&(r[vt]=n,i[vt]=n)}function oi(e,t){let n=e,r=t;n[N]!==void 0&&(r[N]=n[N]),n[P]!==void 0&&(r[P]=n[P]),n[vt]!==void 0&&(r[vt]=n[vt])}function si(e,t,n){let r=new AbortController;e.aborted?(ai(r,e),r.abort(e.reason)):e.streamName?ai(r,e,ii(r,n,e.streamName,t)):ai(r,e);let i=r.abort.bind(r);return r.abort=t=>{if(r.signal.aborted)return;i(t);let n=mr.getStore();if(n&&(n.ops.push((async()=>{try{let r=await Oi({aborted:!0,reason:t},n.workflowMetadata.workflowRunId,n.encryptionKey),i=new $(n.workflowMetadata.workflowRunId,e.streamName).getWriter();await i.write(r),await i.close()}catch{}})()),e.hookToken)){let r=(async()=>{try{let{resumeHook:n}=await import(`./resume-hook-BhA_nDEV.js`).then(e=>e.i);await n(e.hookToken,{aborted:!0,reason:t})}catch{}})();n.preCompletionOps.push(r)}},r}function ci(e,t,n){let r=new AbortController;return e.aborted?(ai(r,e),r.abort(e.reason)):e.streamName?ai(r,e,ii(r,n,e.streamName,t)):ai(r,e),r.signal}function li(e=globalThis){return{...jn(e),...zn(e)}}async function ui(e,t,n){let r=ee(n);if(r)return m(r);let i=await f();if(!i.getEncryptionKeyForRun)return;let a=t?await i.getEncryptionKeyForRun(e,{deploymentId:t}):await i.getEncryptionKeyForRun(await i.runs.get(e));return a?await d(a,[`encrypt`]):void 0}function di(e,t,n){let r;return()=>(r??=ui(e,t,n),r)}function fi(e,{deploymentId:t,encryptionPublicKey:n}){typeof t==`string`&&Object.defineProperty(e,j,{value:t,writable:!1}),typeof n==`string`&&Object.defineProperty(e,M,{value:n,writable:!1})}function pi({global:e,ops:t,runId:n,name:r,key:i,deploymentId:a,encryptionPublicKey:o,runReadyBarrier:s}){let c=Mr($r(e,t,n,i),i),l=new $(n,r,s),u=F();return t.push(u.promise),I(c.readable,l,u).catch(()=>{}),At(c.writable,u),Object.defineProperty(c.writable,k,{value:r,writable:!1}),Object.defineProperty(c.writable,A,{value:n,writable:!1}),fi(c.writable,{deploymentId:a,encryptionPublicKey:o}),c.writable}function mi(e,t,n,r,i,a){return hi(o=>gi(e,t,n,a,{onReadableState:o}).ReadableStream({name:r,startIndex:i}))}function hi(e,t){let n,r,i=!1,a;return a=new ReadableStream({async pull(o){try{n||(n=e(e=>{r=e}).getReader(),r&&!i&&(i=!0,t?t(r):jt(a,r)));let s=await n.read();s.done?o.close():o.enqueue(s.value)}catch(e){o.error(e)}},async cancel(e){await n?.cancel(e).catch(()=>{})}},{highWaterMark:0}),a}function gi(e=globalThis,t,n,r,i){function a(a,o=i?.onReadableState){if(a.type===`bytes`){let r=new Br(n,a.name,a.startIndex),i=F();t.push(i.promise);let{readable:s,writable:c}=a.framing===`framed-v1`?Ir():new e.TransformStream;return I(r,c,i).catch(()=>{}),o?o(i):jt(s,i),s}let s,c=()=>(s??=p(r),s),l=Gr(n,a.name,a.startIndex,c),u=Nr(gi(e,t,n,c,{lazyStreams:i?.lazyStreams,liveAbortSignals:i?.liveAbortSignals}),c),d=F();return t.push(d.promise),I(l,u.writable,d).catch(()=>{}),o?o(d):jt(u.readable,d),u.readable}function o(e){let t=new AbortController;return e.aborted&&t.abort(e.reason),t}return{...li(e),StepFunction:()=>{throw new w(`Step functions cannot be deserialized in client context. Step functions should not be returned from workflows.`,{hint:`A step function reference reached the client. Return a serializable value (e.g. the step result) instead of the step itself.`})},WorkflowFunction:e=>Object.assign(()=>{throw new w(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(n.signal=t.signal);let r=new e.Request(t.url,n);return t.signal&&oi(t.signal,r.signal),r},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:t=>{if(`bodyInit`in t){let n=t.bodyInit;return new e.Response(n).body}return i?.lazyStreams?hi(e=>a(t,e),i.onReadableState):a(t)},WritableStream:i=>{let a=typeof i.runId==`string`?i.runId:n,o=a===n?r:di(a,i.deploymentId,i.encryptionPublicKey);return pi({global:e,ops:t,runId:a,name:i.name,key:o,deploymentId:i.deploymentId,encryptionPublicKey:i.encryptionPublicKey})},AbortController:e=>i?.liveAbortSignals===!1?o(e):si(e,t,n),AbortSignal:e=>i?.liveAbortSignals===!1?o(e).signal:ci(e,t,n)}}function _i(e=globalThis){return{...li(e),...Vn(e),Request:t=>{Object.setPrototypeOf(t,e.Request.prototype);let n=t.responseWritable;return n&&(t[ht]=n,delete t.responseWritable,t.respondWith=()=>{throw new w("`respondWith()` must be called from within a step function.",{hint:'Move the `respondWith(...)` call inside a `"use step"` function — it cannot be invoked from a workflow context.'})}),t},WorkflowFunction:e=>Object.assign(()=>{throw new w(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Response:t=>(Object.setPrototypeOf(t,e.Response.prototype),t),ReadableStream:t=>`bodyInit`in t?Object.create(e.ReadableStream.prototype,{[mt]:{value:t.bodyInit,writable:!1}}):Object.create(e.ReadableStream.prototype,{[k]:{value:t.name,writable:!1},[dt]:{value:t.type,writable:!1},[ft]:{value:t.framing,writable:!1}}),WritableStream:t=>{let n={[k]:{value:t.name,writable:!1}};return typeof t.runId==`string`&&(n[A]={value:t.runId,writable:!1}),typeof t.deploymentId==`string`&&(n[j]={value:t.deploymentId,writable:!1}),typeof t.encryptionPublicKey==`string`&&(n[M]={value:t.encryptionPublicKey,writable:!1}),Object.create(e.WritableStream.prototype,n)},AbortController:e=>{let t=new Tr(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),{[N]:e.streamName,[P]:e.hookToken,signal:t,abort:()=>{}}},AbortSignal:e=>{let t=new Tr(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),t}}}function vi(e=globalThis,t,n,r,i,o){return{...li(e),StepFunction:e=>{let t=e.stepId,n=e.closureVars,r=`boundThis`in e,i=r?e.boundThis:void 0,a=Array.isArray(e.boundArgs)?e.boundArgs:[],o=Ce(t);if(!o)throw new w(`Step function "${t}" not found. Make sure the step function is registered.`,{hint:`Make sure the step file is included in your build (i.e. it is listed in the workflow manifest), and that the SWC plugin is configured for the file.`});if(!n&&!r&&a.length===0)return o;let s=function(...e){let t=r?i:this,s=a.length>0?[...a,...e]:e;if(n){let e=mr.getStore();if(!e)throw new C(`Cannot call step function with closure variables outside step context`);let r={...e,closureVars:n};return mr.run(r,()=>o.apply(t,s))}return o.apply(t,s)};return Object.defineProperty(s,"name",{value:o.name}),Object.defineProperty(s,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),o.maxRetries!==void 0&&(s.maxRetries=o.maxRetries),s},WorkflowFunction:e=>Object.assign(()=>{throw new w(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n=t.responseWritable,r={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(r.signal=t.signal);let i=new e.Request(t.url,r);return t.signal&&oi(t.signal,i.signal),n&&(i.respondWith=async e=>{let t=n.getWriter();await t.write(e),await t.close()}),i},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:a=>{if(`bodyInit`in a){let t=a.bodyInit;return new e.Response(t).body}let o=new Br(n,a.name);if(a.type===`bytes`){let n=F();t.push(n.promise);let{readable:r,writable:i}=a.framing===`framed-v1`?Ir():new e.TransformStream;return I(o,i,n).catch(()=>{}),jt(r,n),r}{let a=Nr(vi(e,t,n,r,i),r),s=F();return t.push(s.promise),I(o,a.writable,s).catch(()=>{}),jt(a.readable,s),a.readable}},WritableStream:s=>{let c=typeof s.runId==`string`?s.runId:n,l=typeof s.deploymentId==`string`?s.deploymentId:c===n?i:void 0,u=c===n?r:di(c,l,s.encryptionPublicKey),d=Mr(ni(e,t,c,u),u),f=new $(c,s.name),p=F();p.deferReleaseSettlement=o!==void 0,o?.push(p),t.push(p.promise),I(d.readable,f,p).catch(()=>{});let m=kt(d.writable,p,e.WritableStream);return At(m,p),Object.defineProperty(m,k,{value:s.name,writable:!1}),Object.defineProperty(m,A,{value:c,writable:!1}),l&&Object.defineProperty(m,j,{value:l,writable:!1}),typeof s.encryptionPublicKey!=`string`&&c===n&&a(r)&&Object.defineProperty(m,M,{value:_(r.keyPair.publicKey),writable:!1}),typeof s.encryptionPublicKey==`string`&&Object.defineProperty(m,M,{value:s.encryptionPublicKey,writable:!1}),m},AbortController:e=>si(e,t,n),AbortSignal:e=>ci(e,t,n)}}async function yi(e,t){return await oe(e,t)}async function bi(e,t){return o(e,t)}const xi=async(e,t)=>{let n={},r=await or(await o(e,t),n);return await Q(n,`deserialize`),{data:r}};function Si(e,t=globalThis,n={}){return fr(e.data,{global:t,extraRevivers:{...Ri(_i(t)),...n}})}function Ci(e,t=globalThis,n={}){let{data:r}=e;if(!(r instanceof Uint8Array))return nt(r,{..._i(t),...n});let{format:i,payload:a}=c(r);if(i===S.DEVALUE_V1)return tt(new TextDecoder().decode(a),{..._i(t),...n});throw Error(`Unsupported serialization format: ${i}`)}async function wi(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1,c=r){if(a)return Nn(O(e,$r(i,r,t,n,o,void 0,c)));try{let a={},l=await cr(e,n,{global:i,extraReducers:Li($r(i,r,t,n,o,void 0,c)),compression:s,compressionStats:a});return await Q(a,`serialize`),l}catch(e){let t=Ar(e),{message:n,hint:r}=X(`workflow arguments`,t);throw new w(n,{hint:r,cause:t})}}async function Ti(e,t,n,r=globalThis,i={},a){return Si(a??await xi(e,n),r,i)}async function Ei(e,t,n,r=globalThis,i=!1,a=!1,o){if(i)return Nn(O(e,ti(r)));try{let t={},i=o??{executions:[]},s=await ur(e,n,{global:r,extraReducers:Li(ti(r)),compression:a,compressionStats:t,guestCodeStats:i});return await Q(t,`serialize`),await jr(i),s}catch(e){let t=Ar(e),{message:n,hint:r}=X(`workflow return value`,t);throw new w(n,{hint:r,cause:t})}}async function Di(e,t,n,r=[],i=globalThis,a={}){let o={},s=await lr(e,n,{global:i,extraRevivers:{...Ri(gi(i,r,t,n)),...a},compressionStats:o});return await Q(o,`deserialize`),s}async function Oi(e,t,n,r=globalThis,i=!1,a=!1,o){if(i)return Nn(O(e,ti(r)));try{let t={},i=o??{executions:[]},s=await ur(e,n,{global:r,extraReducers:Li(ti(r)),compression:a,compressionStats:t,guestCodeStats:i});return await Q(t,`serialize`),await jr(i),s}catch(e){let t=Ar(e),{message:n,hint:r}=X(`step arguments`,t);throw new w(n,{hint:r,cause:t})}}async function ki(e,t,n,r=[],i=globalThis,a={},o,s){let c={},l=await dr(e,n,{global:i,extraRevivers:{...Ri(vi(i,r,t,n,o,s)),...a},compressionStats:c});return await Q(c,`deserialize`),l}async function Ai(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1,c,l=r){if(a)return Nn(O(e,ni(i,r,t,n,o,c,l)));try{let a={},u=await ur(e,n,{global:i,extraReducers:Li(ni(i,r,t,n,o,c,l)),compression:s,compressionStats:a});return await Q(a,`serialize`),u}catch(e){let t=Ar(e),{message:n,hint:r}=X(`step return value`,t);throw new w(n,{hint:r,cause:t})}}async function ji(e,t,n,r=[],i=globalThis,a=!1){try{let o=O(e,ni(i,r,t,n)),s=new TextEncoder().encode(o),c=u(S.DEVALUE_V1,s),l={},d=await yi(await ar(c,a,l),n);return await Q(l,`serialize`),d}catch(e){let t=Ar(e),{message:n,hint:r}=X(`step error`,t);throw new w(n,{hint:r,cause:t})}}async function Mi(e,t,n,r=globalThis,i={},a){return Ci(a??await xi(e,n),r,i)}async function Ni(e,t,n,r=globalThis,i=!1){try{let t=O(e,ti(r)),a=new TextEncoder().encode(t),o=u(S.DEVALUE_V1,a),s={},c=await yi(await ar(o,i,s),n);return await Q(s,`serialize`),c}catch(e){let t=Ar(e),{message:n,hint:r}=X(`run error`,t);throw new w(n,{hint:r,cause:t})}}async function Pi(e,t,n,r=[],i=globalThis,a={}){let s={},l=await or(await o(e,n),s);if(await Q(s,`deserialize`),!(l instanceof Uint8Array))return nt(l,{...gi(i,r,t,n),...a});let{format:u,payload:d}=c(l);if(u===S.DEVALUE_V1)return tt(new TextDecoder().decode(d),{...gi(i,r,t,n),...a});throw Error(`Unsupported serialization format: ${u}`)}async function Fi(e,t,n,r=globalThis,i={},a){return Si(a??await xi(e,n),r,i)}const Ii=[`ReadableStream`,`WritableStream`,`Request`,`Response`,`StepFunction`,`AbortController`,`AbortSignal`];function Li(e){let t={};for(let n of Ii)n in e&&(t[n]=e[n]);return t}function Ri(e){let t={};for(let n of Ii)n in e&&(t[n]=e[n]);return t}export{wn as $,Mi as A,Z as B,mi as C,_i as D,ti as E,yi as F,mr as G,hr as H,xi as I,or as J,X as K,fi as L,Ti as M,Di as N,Pi as O,bi as P,Tn as Q,Dr as R,ui as S,kr as T,vr as U,wr as V,gr as W,On as X,Dn as Y,kn as Z,Ir as _,ri as a,mt as at,$r as b,Ni as c,j as ct,Ai as d,ht as dt,It as et,wi as f,st as ft,Fr as g,at as gt,Ci as h,ct as ht,$ as i,kt as it,Fi as j,ki as k,Oi as l,M as lt,Si as m,ot as mt,Ur as n,I as nt,pi as o,ut as ot,Ei as p,lt as pt,ar as q,Br as r,At as rt,Gr as s,k as st,Vr as t,F as tt,ji as u,A as ut,li as v,Mr as w,gi as x,Nr as y,Er as z};