UNPKG

eve

Version:

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

1 lines • 14.6 kB
import{a as e,ft as t,i as n,it as r,mt as i,nt as a,rt as o,ut as s}from"./dist-DjECvUyK.js";import{$t as c,Bt as l,Gn as u,Jn as d,Kn as f,On as p,Pn as ee,S as te,Vn as ne,Wn as re,Zn as m,_ as ie,en as ae,fn as oe,mn as se,n as h,qn as ce,y as g,zn as le}from"./logger-DFNCa8Nl.js";import{A as _,D as v,E as y,O as b,S as x,T as S,d as C,g as w,h as T,j as E,k as D,l as O,p as k,r as A,s as j,t as M,v as N,w as P}from"./dist-xTushGCp.js";import{$ as F,C as I,G as L,L as R,M as z,N as B,O as V,Q as H,S as U,W,f as ue,o as de}from"./serialization-Cl0SYU0I.js";import{D as fe,l as pe,s as G}from"./helpers-Bw52uyzw.js";import{t as me}from"./attribute-changes-DFx4eluc.js";import{n as he,r as ge,t as _e}from"./wait-until-Dzhr6tzf.js";const ve=new Set([`PARSE_ERROR`,`SCHEMA_VALIDATION`,E.WORLD_CONTRACT_ERROR]),ye=new Set([`TRANSPORT`,`TIMEOUT`,E.STREAM_ERROR]),be=[D.is,T.is,P.is,k.is];function K(e){if(!_.is(e)||e.status!==void 0)return!1;let t=`cause`in e?e.cause:void 0;return e.code!==void 0&&ve.has(e.code)||e.message.startsWith(`Failed to parse response body for `)||e.message.startsWith(`Schema validation failed for `)||typeof t==`object`&&!!t&&`name`in t&&t.name===`ZodError`}function q(e){return N.is(e)?!0:w.is(e)?e.status===void 0||e.status>=500:_.is(e)?e.status!==void 0&&e.status>=500||e.code!==void 0&&ye.has(e.code):!1}function xe(e){if(O.is(e))return E.REPLAY_DIVERGENCE;if(M.is(e))return E.CORRUPTED_EVENT_LOG;if(j.is(e))return E.MAX_EVENTS_EXCEEDED;if(x.is(e))return E.DEPLOYMENT_MISMATCH;if(w.is(e))return E.STREAM_ERROR;if(K(e)||q(e))return E.WORLD_CONTRACT_ERROR;for(let t of be)if(t(e))return E.RUNTIME_ERROR;return E.USER_ERROR}const J=[`node`,`quickjs`];function Y(e=process.env){let t=e.WORKFLOW_VM;if(t!==void 0&&t!==``){if(J.includes(t))return t;throw new D(`Invalid WORKFLOW_VM value: "${t}". Expected one of: ${J.join(`, `)}.`)}}function Se(e){let t=e.executionContext?.workflowVm;if(t!==void 0){if(!J.includes(t))throw new D(`Invalid executionContext.workflowVm value: "${t}". Expected one of: ${J.join(`, `)}.`);return t===`quickjs`}return Y()===`quickjs`}const Ce=s();function we(){let e=L.getStore(),t=e?.workflowMetadata?.workflowRunId;if(t)return{[r]:e.rootRunId??t,[a]:t}}const X=i(`@workflow/core//latestNoOpWarning`,1,()=>({warned:!1}));async function Z(t,r,i){"use step";return await he(()=>{let a=t?.workflowId;if(!a)throw new D(`'start' received an invalid workflow function. Ensure the Workflow SDK is configured correctly and the function includes a 'use workflow' directive.`,{slug:`start-invalid-workflow-function`});let s=`workflow.start ${m(a)}`;return g(s,async t=>{t?.setAttributes({...c(a),...ae(`start`)});let s=[],p=i??{};Array.isArray(r)?s=r:typeof r==`object`&&(p=r),t?.setAttributes({...l(s.length)});let m=p.world??await f();ce(m);let g=await m.getDeploymentId(),_=p.deploymentId??g;_===`latest`&&(m.resolveLatestDeploymentId?_=await m.resolveLatestDeploymentId():(X.warned||(X.warned=!0,h.warn(`deploymentId: 'latest' has no effect in this world and was ignored. It is only supported by worlds with atomic deployments, such as Vercel. The run will target the current deployment.`,{currentDeploymentId:g})),_=g));let v=`wrun_${m.createRunId?m.createRunId(p):Ce()}`,y,b,x,S;if(_===g)y=!0,b=!0,x=1;else if(typeof m.streams?.get!=`function`)y=!1,b=!1,x=void 0;else{let e=await pe(m,{deploymentId:_,runId:v,timeout:2e3,namespace:p.namespace}).catch(()=>void 0);S=e?.encryptionPublicKey;let t=ge(e?.workflowCoreVersion);y=t.framedByteStreams,b=t.supportedFormats.has(le.GZIP),x=e?.hookResumeInputVersion}let C=[],w=await ie(),T=p.specVersion??m.specVersion,E=e(T),O=p.allowReservedAttributes===!0,k;if(p.attributes&&Object.keys(p.attributes).length>0){if(T<4)throw new D(`Initial workflow attributes require a World that supports spec version 4 or later.`);for(let[e,t]of Object.entries(p.attributes))if(typeof t!=`string`)throw new D(`Initial workflow attribute ${JSON.stringify(e)} must be a string value.`);let e=me(p.attributes,{allowReservedAttributes:O});k=Object.fromEntries(e.map(({key:e,value:t})=>[e,t]))}let j;if(p.experimental_retention!==void 0&&p.experimental_retention!=="default"){if(p.experimental_retention!==0)throw new D(`start({ experimental_retention }) must be 0 or 'default'; received ${JSON.stringify(p.experimental_retention)}.`);if(T<4)throw new D(`start({ experimental_retention }) requires a World that supports spec version 4 or later.`);j={[o]:`0`}}let M=T>=4?we():void 0,N=M||j?{...M,...k,...j}:k,P=N?{attributes:N,...O||M!=null||j!=null?{allowReservedAttributes:!0}:{}}:{};if(p.replayedFromRunId!==void 0&&!n.safeParse(p.replayedFromRunId).success)throw new D(`replayedFromRunId must be a run ID (wrun_<ulid>); received ${JSON.stringify(String(p.replayedFromRunId).slice(0,64))}.`);let F=re(S),I,L;if(F)I=ee(F),L=S;else{let e=await m.getEncryptionKeyForRun?.(v,{...p,deploymentId:_});I=e?await d(e):void 0,L=e?ne((await u(e)).publicKey):void 0}let R=await ue(s,v,I,C,globalThis,E,y,b&&T>=5),z=m.getEnvironment?.(),B=Y(),V={traceCarrier:w,workflowCoreVersion:fe,features:{encryption:!!I},...x===void 0?{}:{hookResumeInputVersion:x},...B?{workflowVm:B}:{},...p.replayedFromRunId?{replayedFromRunId:p.replayedFromRunId}:{}},[H,U]=await Promise.allSettled([m.events.create(v,{eventType:`run_created`,specVersion:T,eventData:{deploymentId:_,workflowName:a,input:R,executionContext:V,...L?{encryptionPublicKey:L}:{},...P}},{v1Compat:E}),m.queue(G(a,p.namespace),{runId:v,traceCarrier:w,...T>=3?{runInput:{input:R,deploymentId:_,workflowName:a,specVersion:T,executionContext:V,...L?{encryptionPublicKey:L}:{},...z===void 0?{}:{environment:z},...P}}:{}},{deploymentId:_,specVersion:T,...p.region===void 0?{}:{region:p.region}})]);if(U.status===`rejected`)throw U.reason;let W=!1;if(H.status===`rejected`){let e=H.reason;if(!A.is(e)){if(q(e))W=!0,h.warn(`Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.`,{workflowRunId:v,error:e.message});else throw e}}else{let e=H.value;if(!E&&e.run.runId!==v)throw new D(`Server returned different runId than requested: expected ${v}, got ${e.run.runId}`)}return _e(Promise.all(C),e=>{h.warn(`Background flush of workflow argument streams failed`,{workflowRunId:v,error:e instanceof Error?e.message:String(e)})}),t?.setAttributes({...oe(v),...te(_),...H.status===`fulfilled`?se(H.value.run.status):{}}),new $(v,{resilientStart:W})})})}const Te=e=>Array.isArray(e)?e:[e];async function Ee(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await p(i):void 0,o=Te(await z(r.input,t,a,globalThis)),s=n.specVersion??r.specVersion??1,c=n.deploymentId??r.deploymentId;return(await Z({workflowId:r.workflowName},o,{deploymentId:c,world:e,specVersion:s,replayedFromRunId:t,namespace:n.namespace})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function De(t,n,r){try{let i=(await t.runs.get(n,{resolveData:`none`})).specVersion??1,a=e(i),o={eventType:`run_cancelled`,specVersion:i,...r?.cancelReason===void 0?{}:{eventData:{cancelReason:r.cancelReason}}};await t.events.create(n,o,{v1Compat:a})}catch(e){throw Error(`Failed to cancel run ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Oe(e,t,n){if(t.length===0)throw Error(`cancelRuns requires at least one run ID.`);if(t.length>500)throw Error(`cancelRuns accepts at most 500 run IDs (received ${t.length}).`);if(new Set(t).size!==t.length)throw Error(`cancelRuns requires unique run IDs (duplicates found).`);if(e.runs.cancelMany)return e.runs.cancelMany({runIds:t,...n?.cancelReason===void 0?{}:{cancelReason:n.cancelReason}});let r=Array(t.length),i=0,a=async()=>{for(;;){let a=i++;if(a>=t.length)return;let o=t[a];try{await De(e,o,n),r[a]={runId:o,outcome:`cancelled`}}catch{r[a]={runId:o,outcome:`failed`,code:`internal_error`,retryable:!0}}}},o=Math.min(20,t.length);await Promise.all(Array.from({length:o},()=>a()));let s={requested:t.length,cancelled:0,alreadyCancelled:0,notCancellable:0,notFound:0,failed:0};for(let e of r)switch(e.outcome){case`cancelled`:s.cancelled++;break;case`already_cancelled`:s.alreadyCancelled++;break;case`not_cancellable`:s.notCancellable++;break;case`not_found`:s.notFound++;break;case`failed`:s.failed++}return{summary:s,results:r}}async function ke(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`});await e.queue(G(r.workflowName,n?.namespace),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Ae(t,n,r){try{let i=await t.runs.get(n,{resolveData:`none`}),a=e(i.specVersion),o=[],s=null;do{let e=await t.events.list({runId:n,pagination:{sortOrder:`asc`,...s?{cursor:s}:{}},resolveData:`none`});o.push(...e.data),s=e.hasMore?e.cursor:null}while(s);let c=o.filter(e=>e.eventType===`wait_created`),l=new Set(o.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),u=c.filter(e=>!l.has(e.correlationId));if(r?.correlationIds&&r.correlationIds.length>0){let e=new Set(r.correlationIds);u=u.filter(t=>t.correlationId&&e.has(t.correlationId))}let d=[],f=0;for(let e of u){if(!e.correlationId)continue;let r=a?{eventType:`wait_completed`,correlationId:e.correlationId}:{eventType:`wait_completed`,correlationId:e.correlationId,specVersion:i.specVersion,eventData:{resumeAt:e.eventData.resumeAt}};try{await t.events.create(n,r,{v1Compat:a}),f++}catch(e){A.is(e)?f++:d.push(e instanceof Error?e:Error(String(e)))}}if(f>0&&await t.queue(G(i.workflowName,r?.namespace),{runId:n},{deploymentId:i.deploymentId,specVersion:i.specVersion??1}),d.length>0)throw AggregateError(d,`Failed to complete ${d.length}/${u.length} pending wait(s) for run ${n}`);return{stoppedCount:f}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function je(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw w.is(e)?e:new w(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Me(e,t){try{return await e.streams.list(t)}catch(e){throw w.is(e)?e:new w(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}const Ne=new Set([`completed`,`failed`]),Q=[1e3,3e3,6e3];function Pe(){return t(`WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS`,1e3,{integer:!0,min:1})}function Fe(){return t(`WORKFLOW_RETURN_VALUE_WAIT_MS`,5e4,{integer:!0,min:1})}function Ie(){return t(`WORKFLOW_RETURN_VALUE_MAX_LONG_POLLS`,10,{integer:!0,min:1})}function Le(){let e=process.env.WORKFLOW_RETURN_VALUE_LONG_POLL;return e===void 0||e===``||e!==`0`&&e.toLowerCase()!==`false`}var $=class e{static[F](e){return{runId:e.runId,resilientStart:e.#r}}static[H](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=f(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(e){return this.#n||=(async()=>{let t=await this.#t,n=e??await t.runs.get(this.runId),r=await t.getEncryptionKeyForRun?.(n);return r?await p(r):void 0})(),this.#n}#a(){return()=>this.#i()}async wakeUp(e){"use step";return Ae(await this.#t,this.runId,e)}async cancel(e){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:7,...e?.cancelReason===void 0?{}:{eventData:{cancelReason:e.cancelReason}}})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(b.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(e=>e.status))}get returnValue(){"use step";return this.#c()}get workflowName(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(e=>e.completedAt))}get readable(){return this.getReadable()}getReadable(e={}){"use step";let{ops:t=[],global:n=globalThis,startIndex:r,namespace:i}=e,a=W(this.runId,i),o=this.#a(),s=I(n,t,this.runId,a,r,o),c=this.#t,l=this.runId;return Object.assign(s,{getTailIndex:async()=>(await(await c).streams.getInfo(l,a)).tailIndex})}get writable(){return this.getWritable()}getWritable(e={}){"use step";let{ops:t=[],global:n=globalThis,namespace:r}=e,i=W(this.runId,r),a,o,s=()=>(a??=this.#o().then(async e=>{let t={key:await U(this.runId,e.deploymentId,e.encryptionPublicKey),deploymentId:e.deploymentId,encryptionPublicKey:e.encryptionPublicKey};return R(o,t),t}),a);return o=de({global:n,ops:t,runId:this.runId,name:i,key:()=>s().then(({key:e})=>e)}),o}async#o(){let e=await this.#t,t=this.#r?Q.length:0,n=0;for(;;)try{return await e.runs.get(this.runId,{resolveData:`none`})}catch(e){if(!b.is(e)||n>=t)throw e;let r=Q[n];n++,await new Promise(e=>setTimeout(e,r))}}async#s(e){let t=e.expiredAt;if(t!=null&&t<=new Date)throw new C(`Run "${this.runId}" ${e.status===`completed`?`completed`:`is ${e.status}`}, but its data expired at ${t.toISOString()} and is no longer readable.`,this.runId,e.status,t);if(e.status===`completed`){let t=await this.#i(e);return await B(e.output,this.runId,t)}if(e.status===`cancelled`)throw new S(this.runId);if(e.status===`failed`){let t=await this.#i(e),n;try{n=await V(e.error,this.runId,t)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new y(this.runId,n,{errorCode:e.errorCode})}throw new v(this.runId,e.status)}async#c(){let e=await this.#t,t=0,n=this.#r?Q.length:0,r=Le()?e.runs.waitForTerminalStatus?.bind(e.runs):void 0,i=0,a=Ie();for(;;){let o=Date.now();try{let t=r&&i<a;t&&i++;let n=t?await r(this.runId,{timeoutMs:Fe(),resolveData:`none`}):await e.runs.get(this.runId,{resolveData:`none`});if(n.status===`cancelled`)throw new S(this.runId);if(Ne.has(n.status)){let t=await e.runs.get(this.runId,{resolveData:`all`});return await this.#s(t)}throw new v(this.runId,n.status)}catch(e){if(v.is(e)){let e=Pe()-(Date.now()-o);e>0&&await new Promise(t=>setTimeout(t,e));continue}if(b.is(e)&&t<n){let e=Q[t];t++,await new Promise(t=>setTimeout(t,e));continue}throw e}}}};function Re(e){return new $(e)}export{Me as a,ke as c,Se as d,xe as f,Oe as i,Ae as l,K as m,Re as n,je as o,q as p,De as r,Ee as s,$ as t,Z as u};