eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 14.4 kB
JavaScript
import{O as e,c as t,ct as n,i as r,lt as i,o as a,st as o,zl as s}from"./dist-DDeH-1ER.js";import{$ as c,C as l,D as u,F as d,G as f,Gn as ee,H as p,I as m,M as te,Mn as ne,Nn as re,Q as h,R as g,U as _,Wr as v,cr as y,dr as ie,fr as ae,gt as b,hr as oe,ir as se,jr as ce,l as le,lr as x,mr as S,mt as ue,n as de,pr as fe,qn as pe,r as C,rr as me,s as w,t as he,tr as T,tt as E,w as ge,xn as _e,yt as ve}from"./attribute-changes-C6H-fRVP.js";import{A as D,D as O,E as k,O as A,S as j,T as M,d as N,g as P,h as F,j as I,k as L,l as R,p as z,r as B,s as V,t as H,v as ye,w as be}from"./dist-xTushGCp.js";const xe=new Set([`PARSE_ERROR`,`SCHEMA_VALIDATION`,I.WORLD_CONTRACT_ERROR]),Se=new Set([`TRANSPORT`,`TIMEOUT`,I.STREAM_ERROR]),U=[L.is,F.is,be.is,z.is];function W(e){if(!D.is(e)||e.status!==void 0)return!1;let t=`cause`in e?e.cause:void 0;return e.code!==void 0&&xe.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 G(e){return ye.is(e)?!0:P.is(e)?e.status===void 0||e.status>=500:D.is(e)?e.status!==void 0&&e.status>=500||e.code!==void 0&&Se.has(e.code):!1}function Ce(e){if(R.is(e))return I.REPLAY_DIVERGENCE;if(H.is(e))return I.CORRUPTED_EVENT_LOG;if(V.is(e))return I.MAX_EVENTS_EXCEEDED;if(j.is(e))return I.DEPLOYMENT_MISMATCH;if(P.is(e))return I.STREAM_ERROR;if(W(e)||G(e))return I.WORLD_CONTRACT_ERROR;for(let t of U)if(t(e))return I.RUNTIME_ERROR;return I.USER_ERROR}const K=[`node`,`quickjs`];function q(e=process.env){let t=e.WORKFLOW_VM;if(t!==void 0&&t!==``){if(K.includes(t))return t;throw new L(`Invalid WORKFLOW_VM value: "${t}". Expected one of: ${K.join(`, `)}.`)}}function we(e){let t=e.executionContext?.workflowVm;if(t!==void 0){if(!K.includes(t))throw new L(`Invalid executionContext.workflowVm value: "${t}". Expected one of: ${K.join(`, `)}.`);return t===`quickjs`}return q()===`quickjs`}const Te=a();function Ee(){let e=c.getStore(),t=e?.workflowMetadata?.workflowRunId;if(t)return{[i]:e.rootRunId??t,[o]:t}}const J=s(`@workflow/core//latestNoOpWarning`,1,()=>({warned:!1}));async function Y(e,i,a){"use step";return await C(()=>{let o=e?.workflowId;if(!o)throw new L(`'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 ${v(o)}`;return b(s,async e=>{e?.setAttributes({...ne(o),...re(`start`)});let s=[],c=a??{};Array.isArray(i)?s=i:typeof i==`object`&&(c=i),e?.setAttributes({..._e(s.length)});let u=c.world??await S();oe(u);let d=await u.getDeploymentId(),f=c.deploymentId??d;f===`latest`&&(u.resolveLatestDeploymentId?f=await u.resolveLatestDeploymentId():(J.warned||(J.warned=!0,E.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:d})),f=d));let p=`wrun_${u.createRunId?u.createRunId(c):Te()}`,m,h,g,_;if(f===d)m=!0,h=!0,g=1;else if(typeof u.streams?.get!=`function`)m=!1,h=!1,g=void 0;else{let e=await le(u,{deploymentId:f,runId:p,timeout:2e3,namespace:c.namespace}).catch(()=>void 0);_=e?.encryptionPublicKey;let t=ge(e?.workflowCoreVersion);m=t.framedByteStreams,h=t.supportedFormats.has(se.GZIP),g=e?.hookResumeInputVersion}let v=[],y=await ue(),b=c.specVersion??u.specVersion,x=t(b),C=c.allowReservedAttributes===!0,T;if(c.attributes&&Object.keys(c.attributes).length>0){if(b<4)throw new L(`Initial workflow attributes require a World that supports spec version 4 or later.`);for(let[e,t]of Object.entries(c.attributes))if(typeof t!=`string`)throw new L(`Initial workflow attribute ${JSON.stringify(e)} must be a string value.`);let e=he(c.attributes,{allowReservedAttributes:C});T=Object.fromEntries(e.map(({key:e,value:t})=>[e,t]))}let D;if(c.experimental_retention!==void 0&&c.experimental_retention!=="default"){if(c.experimental_retention!==0)throw new L(`start({ experimental_retention }) must be 0 or 'default'; received ${JSON.stringify(c.experimental_retention)}.`);if(b<4)throw new L(`start({ experimental_retention }) requires a World that supports spec version 4 or later.`);D={[n]:`0`}}let O=b>=4?Ee():void 0,k=O||D?{...O,...T,...D}:T,A=k?{attributes:k,...C||O!=null||D!=null?{allowReservedAttributes:!0}:{}}:{};if(c.replayedFromRunId!==void 0&&!r.safeParse(c.replayedFromRunId).success)throw new L(`replayedFromRunId must be a run ID (wrun_<ulid>); received ${JSON.stringify(String(c.replayedFromRunId).slice(0,64))}.`);let j=ae(_),M,N;if(j)M=me(j),N=_;else{let e=await u.getEncryptionKeyForRun?.(p,{...c,deploymentId:f});M=e?await ce(e):void 0,N=e?ie((await fe(e)).publicKey):void 0}let P=await te(s,p,M,v,globalThis,x,m,h&&b>=5),F=u.getEnvironment?.(),I=q(),R={traceCarrier:y,workflowCoreVersion:l,features:{encryption:!!M},...g===void 0?{}:{hookResumeInputVersion:g},...I?{workflowVm:I}:{},...c.replayedFromRunId?{replayedFromRunId:c.replayedFromRunId}:{}},[z,V]=await Promise.allSettled([u.events.create(p,{eventType:`run_created`,specVersion:b,eventData:{deploymentId:f,workflowName:o,input:P,executionContext:R,...N?{encryptionPublicKey:N}:{},...A}},{v1Compat:x}),u.queue(w(o,c.namespace),{runId:p,traceCarrier:y,...b>=3?{runInput:{input:P,deploymentId:f,workflowName:o,specVersion:b,executionContext:R,...N?{encryptionPublicKey:N}:{},...F===void 0?{}:{environment:F},...A}}:{}},{deploymentId:f,specVersion:b,...c.region===void 0?{}:{region:c.region}})]);if(V.status===`rejected`)throw V.reason;let H=!1;if(z.status===`rejected`){let e=z.reason;if(!B.is(e)){if(G(e))H=!0,E.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:p,error:e.message});else throw e}}else{let e=z.value;if(!x&&e.run.runId!==p)throw new L(`Server returned different runId than requested: expected ${p}, got ${e.run.runId}`)}return de(Promise.all(v),e=>{E.warn(`Background flush of workflow argument streams failed`,{workflowRunId:p,error:e instanceof Error?e.message:String(e)})}),e?.setAttributes({...ee(p),...ve(f),...z.status===`fulfilled`?pe(z.value.run.status):{}}),new $(p,{resilientStart:H})})})}const De=e=>Array.isArray(e)?e:[e];async function Oe(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await T(i):void 0,o=De(await p(r.input,t,a,globalThis)),s=n.specVersion??r.specVersion??1,c=n.deploymentId??r.deploymentId;return(await Y({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 X(e,n,r){try{let i=(await e.runs.get(n,{resolveData:`none`})).specVersion??1,a=t(i),o={eventType:`run_cancelled`,specVersion:i,...r?.cancelReason===void 0?{}:{eventData:{cancelReason:r.cancelReason}}};await e.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 ke(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 X(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 Ae(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`});await e.queue(w(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 Z(e,n,r){try{let i=await e.runs.get(n,{resolveData:`none`}),a=t(i.specVersion),o=[],s=null;do{let t=await e.events.list({runId:n,pagination:{sortOrder:`asc`,...s?{cursor:s}:{}},resolveData:`none`});o.push(...t.data),s=t.hasMore?t.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 t of u){if(!t.correlationId)continue;let r=a?{eventType:`wait_completed`,correlationId:t.correlationId}:{eventType:`wait_completed`,correlationId:t.correlationId,specVersion:i.specVersion,eventData:{resumeAt:t.eventData.resumeAt}};try{await e.events.create(n,r,{v1Compat:a}),f++}catch(e){B.is(e)?f++:d.push(e instanceof Error?e:Error(String(e)))}}if(f>0&&await e.queue(w(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 P.is(e)?e:new P(`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 P.is(e)?e:new P(`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 e(`WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS`,1e3,{integer:!0,min:1})}function Fe(){return e(`WORKFLOW_RETURN_VALUE_WAIT_MS`,5e4,{integer:!0,min:1})}function Ie(){return e(`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[x](e){return{runId:e.runId,resilientStart:e.#r}}static[y](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=S(),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 T(r):void 0})(),this.#n}#a(){return()=>this.#i()}async wakeUp(e){"use step";return Z(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(A.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).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).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=h(this.runId,i),o=this.#a(),s=m(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=h(this.runId,r),a,o,s=()=>(a??=this.#o().then(async e=>{let t={key:await d(this.runId,e.deploymentId,e.encryptionPublicKey),deploymentId:e.deploymentId,encryptionPublicKey:e.encryptionPublicKey};return f(o,t),t}),a);return o=u({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(!A.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 N(`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 _(e.output,this.runId,t)}if(e.status===`cancelled`)throw new M(this.runId);if(e.status===`failed`){let t=await this.#i(e),n;try{n=await g(e.error,this.runId,t)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new k(this.runId,n,{errorCode:e.errorCode})}throw new O(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 M(this.runId);if(Ne.has(n.status)){let t=await e.runs.get(this.runId,{resolveData:`all`});return await this.#s(t)}throw new O(this.runId,n.status)}catch(e){if(O.is(e)){let e=Pe()-(Date.now()-o);e>0&&await new Promise(t=>setTimeout(t,e));continue}if(A.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,Ae as c,we as d,Ce as f,ke as i,Z as l,W as m,Re as n,je as o,G as p,X as r,Oe as s,$ as t,Y as u};