UNPKG

eve

Version:

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

1 lines • 8.86 kB
import{r as e}from"./rolldown-runtime-DPpTSio4.js";import{T as t,b as n,f as r,g as i,i as a,r as o}from"./schemas-4CmFgxN_.js";import{_ as s,a as c,ot as l,ut as u,x as d,z as f}from"./dist-DjECvUyK.js";import{$t as p,A as m,D as h,Jn as g,Kn as _,M as v,N as ee,O as te,On as y,Pn as b,Wn as x,fn as S,m as C,n as ne,y as w,zn as T}from"./logger-DFNCa8Nl.js";import{A as E,O as D,d as O,k,n as A,o as j}from"./dist-xTushGCp.js";import{d as re,dt as M,k as N}from"./serialization-Cl0SYU0I.js";import{s as P}from"./helpers-Bw52uyzw.js";import{n as F,r as ie,t as ae}from"./wait-until-Dzhr6tzf.js";const I=n({type:i(`hook_resume`),version:i(1),hookId:t(),token:t(),payload:a(Uint8Array)}),oe=r(`status`,[n({status:i(`accepted`)}),n({status:i(`rejected`),code:o([`HOOK_NOT_FOUND`,`INVALID_INPUT`])})]);async function L(e,t,n,r){let i=I.safeParse(r);if(!i.success||!n)throw new E(`Invalid invocation input`,{status:400,code:`INVALID_INPUT`});let a=i.data,o=Buffer.from(await crypto.subtle.digest(`SHA-256`,a.payload)).toString(`hex`);try{let n=await e.hooks.get(a.hookId);if(n.runId!==t||n.token!==a.token)throw new j(a.token);let r=await e.runs.get(t,{resolveData:`none`});if(f(r.status))throw new j(a.token)}catch(r){if(!R(r))throw r;let i=await e.runs.get(t,{resolveData:`none`});if(i.expiredAt||f(i.status)&&l(i.attributes).mode===`none`)throw new E(`Invocation data has expired under the run retention policy`,{status:410,code:`INVOCATION_DATA_EXPIRED`});if(!e.capabilities?.hookResumeDedup||!await z(e,t,a.hookId,n))throw r}return await e.events.create(t,{eventType:`hook_received`,correlationId:a.hookId,specVersion:7,eventData:{token:a.token,payload:a.payload}},{...e.capabilities?.hookResumeDedup?{resumeId:n,resumePayloadDigest:o}:{}}),{status:`accepted`}}function R(e){return j.is(e)||O.is(e)||D.is(e)}async function z(e,t,n,r){let i=null;do{let a=await e.events.listByCorrelationId({runId:t,correlationId:n,resolveData:`none`,pagination:{limit:100,...i?{cursor:i}:{}}});if(a.data.some(e=>e.eventType===`hook_received`&&e.resumeId===r))return!0;i=a.hasMore?a.cursor:null}while(i);return!1}var B=class{revision=0;listeners=new Set;notify(){this.revision++;for(let e of this.listeners)e()}async waitForActivity(e,t=100){return this.revision!==e||(await new Promise(e=>{let n=()=>{clearTimeout(r),this.listeners.delete(n),e()},r=setTimeout(n,t);this.listeners.add(n)}),this.revision!==e)}};function V(e){return t=>{let n=new Map;return async(r,i)=>{if(s.safeParse(r).success)return t(r,i);let a=d.safeParse(r);if(!e.capabilities?.invoke||!a.success||a.data.stepId)return t(r,i);let o=a.data,c=n.get(o.runId);c||(c={activity:new B,admission:Promise.resolve(),references:0},n.set(o.runId,c));let l=c;l.references++;try{if(o.invoke){if(!o.requestId)throw new k(`Invocation requestId is required`);let t=o.requestId,n=l.admission.then(()=>w(`workflow.invoke.receive`,async n=>{n?.setAttributes({...S(o.runId),"workflow.invocation.id":t});let r=await L(e,o.runId,t,o.input);return r.status===`accepted`&&l.activity.notify(),r}));return l.admission=n.catch(()=>{}),await n}if(l.execution)return await l.execution;let n=t(r,i,l.activity);l.execution=n;try{return await n}finally{l.execution===n&&(l.execution=void 0)}}finally{l.references--,l.references===0&&n.get(o.runId)===l&&n.delete(o.runId)}}}}var H=e({getHookByToken:()=>X,resumeHook:()=>Z,resumeWebhook:()=>$});const U=u();async function W(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}const G=[25,100];function K(e,t){if(t?.(e))return!1;let n=e??{},r=n.status??n.statusCode;if(typeof r==`number`)return r>=500||r===408||r===429;let i=e?.name;return i!==`BadRequestError`&&i!==`UnauthorizedError`&&i!==`ForbiddenError`}async function se(e,t){let n;for(let r=0;r<=G.length;r++)try{await e();return}catch(e){if(n=e,!K(e,t))break;let i=G[r];i!==void 0&&await new Promise(e=>setTimeout(e,i))}throw j.is(n)?new k(`The hook resume was committed, but its workflow wake could not be published`,{cause:n}):n}function ce(e){let t=e.executionContext?.workflowCoreVersion,n=e.executionContext?.traceCarrier,r=e.executionContext?.hookResumeInputVersion;return{deploymentId:e.deploymentId,workflowName:e.workflowName,runSpecVersion:e.specVersion,workflowCoreVersion:typeof t==`string`?t:void 0,traceCarrier:n&&typeof n==`object`?n:void 0,encryptionPublicKey:e.encryptionPublicKey,hookResumeInputVersion:typeof r==`number`?r:void 0}}async function q(e){if(e.resumeContext)return{resumeContext:e.resumeContext,source:`hook`};let t=await(await _()).runs.get(e.runId);return{resumeContext:ce(t),source:`run_fallback`,run:t}}async function le(e,t){let n=await _(),r=t.run?await n.getEncryptionKeyForRun?.(t.run):await n.getEncryptionKeyForRun?.(e.runId,{deploymentId:t.resumeContext.deploymentId});return r?await g(r):void 0}function ue(e){let t=Object.getOwnPropertyDescriptor(e,`metadata`);return t!==void 0&&typeof t.get==`function`}function J(e){let t=e.metadata,n,r,i=async()=>{let n=await _(),i=await q(e),a=i.run?await n.getEncryptionKeyForRun?.(i.run):await n.getEncryptionKeyForRun?.(e.runId,{deploymentId:i.resumeContext.deploymentId});return r=a?await y(a):void 0,await N(t,e.runId,r)},a=e;return Object.defineProperty(a,"metadata",{get:()=>n??=t===void 0?Promise.resolve(void 0):i(),enumerable:!1,configurable:!0}),{hook:a,metadataEncryptionKey:()=>r}}function Y(e){return ue(e)?e:J(e).hook}async function X(e){return J(await(await _()).hooks.getByToken(e)).hook}async function Z(e,t,n){return Q(e,t,n,!1,Date.now())}async function Q(e,t,n,r,i){return await F(()=>w(`hook.resume`,async a=>{let o=await _();try{let s=typeof e==`string`,l=s?await o.hooks.getByToken(e):e,u=s||r,d=await q(l),{resumeContext:h}=d;if(a?.setAttributes({...v(l.token),...te(l.hookId),...S(l.runId),"workflow.hook.resume_context_source":d.source}),d.run&&f(d.run.status))throw new j(l.token);let g=ie(h.workflowCoreVersion),_,y=n?void 0:x(h.encryptionPublicKey);if(y)_=b(y);else{let e=n??await le(l,d);g.supportedFormats.has(T.ENCRYPTED)||(e=void 0),_=e}let w=(h.runSpecVersion??0)>=5&&g.supportedFormats.has(T.GZIP),E=[],D=[],A=c(l.specVersion),M=await re(t,l.runId,_,E,globalThis,A,g.framedByteStreams,w,void 0,D);await Promise.all(E.map(e=>e.catch(e=>{if(e!==void 0)throw e}))),ae(Promise.all(D),e=>{e!==void 0&&ne.warn(`Background readback of hook payload failed`,{workflowRunId:l.runId,hookId:l.hookId,error:e instanceof Error?e.message:String(e)})}),a?.setAttributes({...p(h.workflowName)});let N=await C(h.traceCarrier);if(N&&a?.addLink?.(N),o.capabilities?.invoke===!0&&!A&&M instanceof Uint8Array){if(!o.invoke)throw new k(`World advertises invoke without implementing it`);a?.setAttributes({"workflow.hook.resume_strategy":`invoke`});let e=oe.parse(await o.invoke(l.runId,{type:`hook_resume`,version:1,hookId:l.hookId,token:l.token,payload:M},{idempotencyKey:U()}));if(e.status===`rejected`)throw e.code===`HOOK_NOT_FOUND`?new j(l.token):new k(`Executor rejected the hook invocation input`);return a?.setAttributes(m(!0)),Y(l)}let F=P(h.workflowName),I={deploymentId:h.deploymentId,specVersion:h.runSpecVersion??1},L=((u?l.resumeCapabilities?.hookResumeDedupVersion??0:0)>=1||o.capabilities?.hookResumeDedup===!0)&&!A&&M instanceof Uint8Array;a?.setAttributes({"workflow.hook.resume_strategy":`sequential`});let R=L?U():void 0,z=L?await W(M):void 0;R&&a?.setAttributes({"workflow.hook.resume_id":R});let B=e=>j.is(e)||O.is(e);try{await o.events.create(l.runId,{eventType:`hook_received`,specVersion:7,correlationId:l.hookId,eventData:{...A?{}:{token:l.token},payload:M}},{v1Compat:A,...R&&z?{resumeId:R,resumePayloadDigest:z}:{}})}catch(e){throw B(e)?new j(l.token):e}a?.setAttributes(m(!0));let V=Date.now();return await se(()=>o.queue(F,{runId:l.runId,traceCarrier:h.traceCarrier??void 0,hookResumeTiming:{resumeRequestedAtMs:i,queuePublishRequestedAtMs:V,strategy:`sequential`}},{...I,...R?{idempotencyKey:`hook-${R}`}:{}}),o.isDeploymentUnavailableError?.bind(o)),a?.setAttributes(ee(!0)),Y(l)}catch(t){throw a?.setAttributes({...v(typeof e==`string`?e:e.token),...h(!1)}),t}}))}async function $(e,t){let n=Date.now(),{hook:r,metadataEncryptionKey:i}=J(await(await _()).hooks.getByToken(e));if(r.isWebhook===!1)throw new j(e);let a=await r.metadata,o,s;if(a&&typeof a==`object`&&`respondWith`in a){if(a.respondWith===`manual`){let{readable:e,writable:n}=new TransformStream;s=e,t[M]=n}else if(a.respondWith instanceof Response)o=a.respondWith;else throw new k(`Invalid \`respondWith\` value: ${a.respondWith}`,{slug:A.WEBHOOK_INVALID_RESPOND_WITH_VALUE})}else o=new Response(null,{status:202});if(await Q(r,t,i(),!0,n),s){let e=s.getReader(),t=await e.read();t.value&&(o=t.value),e.cancel()}if(!o)throw new k(`Workflow run did not send a response`,{slug:A.WEBHOOK_RESPONSE_NOT_SENT});return o}export{V as a,H as i,Z as n,$ as r,X as t};