eve 0.17.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/src/chunks/{use-eve-agent-BEOUv37s.js → use-eve-agent-Bh1NmXO9.js} +8 -5
  3. package/dist/src/chunks/{use-eve-agent-C25KOe9i.js → use-eve-agent-Dvy_Wjvq.js} +8 -5
  4. package/dist/src/cli/dev/tui/tui.d.ts +2 -0
  5. package/dist/src/cli/dev/tui/tui.js +1 -1
  6. package/dist/src/cli/dev/url-target.d.ts +14 -0
  7. package/dist/src/cli/dev/url-target.js +1 -0
  8. package/dist/src/cli/run.js +3 -3
  9. package/dist/src/client/client.js +1 -1
  10. package/dist/src/compiled/.vendor-stamp.json +3 -3
  11. package/dist/src/compiled/@workflow/core/classify-error.d.ts +15 -0
  12. package/dist/src/compiled/@workflow/core/index.js +2 -2
  13. package/dist/src/compiled/@workflow/core/runtime.js +27 -27
  14. package/dist/src/compiled/@workflow/core/serialization.d.ts +12 -3
  15. package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +10 -0
  16. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  17. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  18. package/dist/src/compiled/_chunks/workflow/{attribute-changes-DUxG-Gic.js → attribute-changes-zAifvEhb.js} +1 -1
  19. package/dist/src/compiled/_chunks/workflow/{resume-hook-CUCPW67D.js → resume-hook-C15uJ2ik.js} +1 -1
  20. package/dist/src/compiled/_chunks/workflow/run-BJUPZ0Ni.js +1 -0
  21. package/dist/src/compiled/_chunks/workflow/{sleep-Dxuzj5to.js → sleep-C8B-TYir.js} +1 -1
  22. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  23. package/dist/src/execution/remote-agent-dispatch.js +1 -1
  24. package/dist/src/execution/subagent-invocation.d.ts +20 -5
  25. package/dist/src/execution/subagent-invocation.js +2 -2
  26. package/dist/src/execution/subagent-tool.d.ts +7 -0
  27. package/dist/src/execution/subagent-tool.js +1 -1
  28. package/dist/src/internal/application/package.js +1 -1
  29. package/dist/src/internal/http/basic-auth.d.ts +1 -0
  30. package/dist/src/internal/http/basic-auth.js +1 -0
  31. package/dist/src/services/dev-client/client-options.d.ts +5 -1
  32. package/dist/src/services/dev-client/client-options.js +1 -1
  33. package/dist/src/setup/scaffold/create/project.js +1 -1
  34. package/dist/src/svelte/index.js +1 -1
  35. package/dist/src/svelte/use-eve-agent.js +1 -1
  36. package/dist/src/vue/index.js +1 -1
  37. package/dist/src/vue/use-eve-agent.js +1 -1
  38. package/docs/guides/dev-tui.md +7 -1
  39. package/docs/reference/cli.md +10 -1
  40. package/package.json +5 -5
  41. package/dist/src/compiled/_chunks/workflow/run-CVlF84yI.js +0 -1
@@ -93,7 +93,16 @@ export declare const FRAMED_STREAM_MAX_TOTAL_RECONNECTS = 1000;
93
93
  */
94
94
  export declare function createReconnectingFramedStream(runId: string, name: string, startIndex?: number): ReadableStream<Uint8Array>;
95
95
  export declare class WorkflowServerWritableStream extends WritableStream<Uint8Array> {
96
- constructor(runId: string, name: string);
96
+ /**
97
+ * @param runReadyBarrier Turbo mode only: a promise that resolves once the
98
+ * backgrounded `run_started` has landed. When the step body runs
99
+ * optimistically (before `run_started` is durable), the first chunk write to
100
+ * a brand-new stream would otherwise reach the World before the run exists
101
+ * and be rejected as run-not-found. Awaiting this once before the first
102
+ * flush/close orders the write after the run's creation. `undefined` outside
103
+ * turbo and on the await path, where the run was already durable.
104
+ */
105
+ constructor(runId: string, name: string, runReadyBarrier?: Promise<unknown>);
97
106
  }
98
107
  export type { ByteStreamFraming, Reducers, Revivers, SerializableSpecial, } from './serialization/types.js';
99
108
  import type { ByteStreamFraming, Reducers, Revivers } from './serialization/types.js';
@@ -112,7 +121,7 @@ import type { ByteStreamFraming, Reducers, Revivers } from './serialization/type
112
121
  * to `false` for backwards compatibility with older runs.
113
122
  * @returns
114
123
  */
115
- export declare function getExternalReducers(global: Record<string, any> | undefined, ops: Promise<void>[], runId: string, cryptoKey: EncryptionKeyParam, framedByteStreams?: boolean): Partial<Reducers>;
124
+ export declare function getExternalReducers(global: Record<string, any> | undefined, ops: Promise<void>[], runId: string, cryptoKey: EncryptionKeyParam, framedByteStreams?: boolean, runReadyBarrier?: Promise<unknown>): Partial<Reducers>;
116
125
  /**
117
126
  * Reducers for serialization boundary from within the workflow execution
118
127
  * environment, passing return value to the client side and into step arguments.
@@ -380,7 +389,7 @@ export declare function hydrateStepArguments(value: Uint8Array | unknown, runId:
380
389
  * backwards compatibility with older runs.
381
390
  * @returns The dehydrated value as binary data (Uint8Array) with format prefix
382
391
  */
383
- export declare function dehydrateStepReturnValue(value: unknown, runId: string, key: CryptoKey | undefined, ops?: Promise<any>[], global?: Record<string, any>, v1Compat?: boolean, framedByteStreams?: boolean, compression?: boolean): Promise<Uint8Array | unknown>;
392
+ export declare function dehydrateStepReturnValue(value: unknown, runId: string, key: CryptoKey | undefined, ops?: Promise<any>[], global?: Record<string, any>, v1Compat?: boolean, framedByteStreams?: boolean, compression?: boolean, runReadyBarrier?: Promise<unknown>): Promise<Uint8Array | unknown>;
384
393
  /**
385
394
  * Called from the step handler when a step throws. Dehydrates the thrown
386
395
  * value from within the step execution environment into a format that can
@@ -51,6 +51,16 @@ export type StepContext = {
51
51
  closureVars?: Record<string, any>;
52
52
  encryptionKey?: CryptoKey;
53
53
  writables?: Map<string, CachedWritable>;
54
+ /**
55
+ * Turbo mode only: a promise that resolves once the backgrounded
56
+ * `run_started` has landed (the run exists). Set when the step body runs
57
+ * optimistically — before `run_started`/`step_started` are confirmed — so a
58
+ * direct step-body world write (e.g. `experimental_setAttributes`, which
59
+ * resolves to a host-side `attr_set` create) can gate on it and never race
60
+ * ahead of the run's creation. `undefined` outside turbo and on the await
61
+ * path, where `run_started` was already durable before the body ran.
62
+ */
63
+ runReadyBarrier?: Promise<unknown>;
54
64
  };
55
65
  export declare const contextStorage: AsyncLocalStorage<StepContext>;
56
66
  //# sourceMappingURL=context-storage.d.ts.map
@@ -1,2 +1,2 @@
1
- export declare const version = "5.0.0-beta.24";
1
+ export declare const version = "5.0.0-beta.26";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- import{c as e,i as t}from"../../_chunks/workflow/dist-Dxrjttr2.js";import{dn as n,fn as r,fr as i,lr as a,mr as o,nn as s,on as c,t as l,tn as u,un as d,ur as f}from"../../_chunks/workflow/attribute-changes-DUxG-Gic.js";import{t as p}from"../../_chunks/workflow/sleep-Dxuzj5to.js";import{t as m}from"../../_chunks/workflow/run-CVlF84yI.js";async function h(e,n={}){let i=l(e,n);if(i.length===0)return;let a=n.allowReservedAttributes===!0,o=globalThis[r];if(!o)throw new t("experimental_setAttributes() called outside a workflow runtime context. It must be called from within a workflow body (`use workflow`).");await o(i,a?{allowReservedAttributes:!0}:{})}s(u,m);function g(e){let t=globalThis[d];return t||f(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,g),t(e)}function _(e){let{respondWith:t,token:n,...r}=e??{};if(n!==void 0)throw Error("`createWebhook()` does not accept a `token` option. Webhook tokens are always randomly generated. Use `createHook()` with `resumeHook()` for deterministic token patterns.");let i;t!==void 0&&(i={respondWith:t});let a=g({...r,metadata:i,isWebhook:!0}),{url:s}=o();return a.url=`${s}/.well-known/workflow/v1/webhook/${encodeURIComponent(a.token)}`,a}function v(){function e(t,n){i(`defineHook().resume()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,e)}return{create(e){return g(e)},resume:e}}function y(e={}){let{namespace:t}=e,r=globalThis[n](t);return Object.create(globalThis.WritableStream.prototype,{[c]:{value:r,writable:!1}})}function b(){a(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,b)}function x(){i(`resumeHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,x)}export{t as FatalError,e as RetryableError,g as createHook,_ as createWebhook,v as defineHook,h as experimental_setAttributes,b as getStepMetadata,o as getWorkflowMetadata,y as getWritable,x as resumeHook,p as sleep};
1
+ import{c as e,i as t}from"../../_chunks/workflow/dist-Dxrjttr2.js";import{dn as n,fn as r,fr as i,lr as a,mr as o,nn as s,on as c,t as l,tn as u,un as d,ur as f}from"../../_chunks/workflow/attribute-changes-zAifvEhb.js";import{t as p}from"../../_chunks/workflow/sleep-C8B-TYir.js";import{t as m}from"../../_chunks/workflow/run-BJUPZ0Ni.js";async function h(e,n={}){let i=l(e,n);if(i.length===0)return;let a=n.allowReservedAttributes===!0,o=globalThis[r];if(!o)throw new t("experimental_setAttributes() called outside a workflow runtime context. It must be called from within a workflow body (`use workflow`).");await o(i,a?{allowReservedAttributes:!0}:{})}s(u,m);function g(e){let t=globalThis[d];return t||f(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,g),t(e)}function _(e){let{respondWith:t,token:n,...r}=e??{};if(n!==void 0)throw Error("`createWebhook()` does not accept a `token` option. Webhook tokens are always randomly generated. Use `createHook()` with `resumeHook()` for deterministic token patterns.");let i;t!==void 0&&(i={respondWith:t});let a=g({...r,metadata:i,isWebhook:!0}),{url:s}=o();return a.url=`${s}/.well-known/workflow/v1/webhook/${encodeURIComponent(a.token)}`,a}function v(){function e(t,n){i(`defineHook().resume()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,e)}return{create(e){return g(e)},resume:e}}function y(e={}){let{namespace:t}=e,r=globalThis[n](t);return Object.create(globalThis.WritableStream.prototype,{[c]:{value:r,writable:!1}})}function b(){a(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,b)}function x(){i(`resumeHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,x)}export{t as FatalError,e as RetryableError,g as createHook,_ as createWebhook,v as defineHook,h as experimental_setAttributes,b as getStepMetadata,o as getWorkflowMetadata,y as getWritable,x as resumeHook,p as sleep};
@@ -56,4 +56,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
56
56
  `)?e.split(`
57
57
  `).map((e,t)=>t===0?e:` ${e}`).join(`
58
58
  `):e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var Wv=class e extends Error{steps;globalThis;stepCount;hookCount;waitCount;attributeCount;hookDisposedCount;abortCount;constructor(e,t){let n=[...e.values()],r=0,i=0,o=0,s=0,c=0,l=0;for(let e of n)e.type===`step`?r++:e.type===`hook`?e.disposed?c++:e.abortRequested?l++:i++:e.type===`wait`?o++:e.type===`attribute`&&s++;let u=[];r>0&&u.push(`${r} ${a(`step`,`steps`,r)}`),i>0&&u.push(`${i} ${a(`hook`,`hooks`,i)}`),o>0&&u.push(`${o} ${a(`wait`,`waits`,o)}`),s>0&&u.push(`${s} ${a(`attribute write`,`attribute writes`,s)}`),c>0&&u.push(`${c} hook ${a(`disposal`,`disposals`,c)}`);let d=a(`has`,`have`,r+i+o+s+c),f=+(r>0)+ +(i>0)+ +(o>0)+ +(s>0)+ +(c>0),p;p=f>1?`processed`:r>0?`run`:i>0||o>0?`created`:s>0?`written`:c>0?`processed`:`received`;let m=u.length>0?`${u.join(` and `)} ${d} not been ${p} yet`:`0 steps have not been run yet`;super(m),this.name=`WorkflowSuspension`,this.steps=n,this.globalThis=t,this.stepCount=r,this.hookCount=i,this.waitCount=o,this.attributeCount=s,this.hookDisposedCount=c,this.abortCount=l}static is(t){return t instanceof e}};function Gv(){throw new v(`This API is not available inside a workflow function. Workflow functions run in a deterministic VM; move the call to a step function for full Node.js access.`)}function $(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Kv=$(`workflow.name`),qv=$(`workflow.operation`),Jv=$(`workflow.run.id`),Yv=$(`workflow.run.status`),Xv=$(`workflow.started_at`),Zv=$(`workflow.events.count`),Qv=$(`workflow.arguments.count`),$v=$(`workflow.result.type`),ey=$(`workflow.trace.propagated`),ty=$(`workflow.trace.mode`),ny=$(`workflow.turbo`),ry=$(`workflow.error.name`),iy=$(`workflow.error.message`),ay=$(`workflow.error.code`),oy=$(`workflow.steps.created`),sy=$(`workflow.hooks.created`),cy=$(`workflow.waits.created`),ly=$(`workflow.route.type`),uy=$(`workflow.route.handler_cached`),dy=$(`workflow.route.invocation_count`),fy=$(`workflow.route.entrypoint_age_ms`),py=$(`workflow.route.module_body_init_ms`),my=$(`step.name`),hy=$(`step.id`),gy=$(`step.attempt`),_y=$(`step.status`),vy=$(`step.max_retries`),yy=$(`step.skipped`),by=$(`step.skip_reason`),xy=$(`step.arguments.count`),Sy=$(`step.result.type`),Cy=$(`step.error.name`),wy=$(`step.error.message`),Ty=$(`step.fatal_error`),Ey=$(`step.retry.exhausted`),Dy=$(`step.retry.timeout_seconds`),Oy=$(`step.retry.will_retry`),ky=$(`messaging.system`),Ay=$(`messaging.destination.name`),jy=$(`messaging.message.id`),My=$(`messaging.operation.type`),Ny=$(`workflow.queue.overhead_ms`),Py=$(`deployment.id`),Fy=$(`workflow.hook.token`),Iy=$(`workflow.hook.id`),Ly=$(`workflow.hook.found`),Ry=$(`workflow.suspension.state`),zy=$(`workflow.suspension.hook_count`),By=$(`workflow.suspension.step_count`),Vy=$(`workflow.suspension.wait_count`),Hy=$(`http.request.method`),Uy=$(`http.route`),Wy=$(`http.response.status_code`),Gy=$(`error.type`),Ky=$(`workflow.events.pages_loaded`),qy=$(`workflow.queue.deserialize_time_ms`),Jy=$(`workflow.queue.execution_time_ms`),Yy=$(`workflow.queue.serialize_time_ms`),Xy=$(`workflow.serialization.operation`),Zy=$(`workflow.serialization.compressed`),Qy=$(`workflow.serialization.codec`),$y=$(`workflow.serialization.uncompressed_bytes`),eb=$(`workflow.serialization.stored_bytes`),tb=$(`workflow.serialization.compression_ratio`),nb=$(`peer.service`),rb=$(`rpc.system`),ib=$(`rpc.service`),ab=$(`rpc.method`),ob=$(`error.retryable`),sb=$(`error.category`),cb=new Set;function lb(){let e=process.env.WORKFLOW_TRACE_MODE;return e===`continuous`?`continuous`:(e&&e!==`linked`&&!cb.has(e)&&(cb.add(e),Ab.warn(`Unrecognized WORKFLOW_TRACE_MODE value "${e}"; expected "linked" or "continuous". Falling back to "linked".`)),`linked`)}function ub(e){return e!==void 0&&Object.keys(e).length>0}function db(e,t){return e===`linked`&&ub(t)?Promise.resolve(t):pb()}async function fb(e,t){if(e!==`linked`)return wb();let n=await Tb(ub(t)?t:void 0);return n?[n]:void 0}async function pb(){let e=await gb.value;if(!e)return{};let t={};return e.propagation.inject(e.context.active(),t),t}async function mb(e){let t=await gb.value;if(t)return t.propagation.extract(t.context.active(),e)}async function hb(e,t){if(!e)return t();let n=await gb.value;if(!n)return t();let r=await mb(e);return r?n.context.with(r,async()=>await t()):t()}const gb=o(async()=>{try{return await import(`./src-CQuMexnO.js`).then(t=>e(t.t(),1))}catch{return Ab.info(`OpenTelemetry not available, tracing will be disabled`),null}}),_b=o(async()=>{let e=await gb.value;return e?e.trace.getTracer(`workflow`):null});async function vb(e,...t){let[n,r]=await Promise.all([_b.value,gb.value]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),yb(t,r,e),t}finally{e.end()}})}function yb(e,t,n){!e||!Wv.is(e)||(n.setStatus({code:t.SpanStatusCode.OK}),n.setAttributes({...Ry(`suspended`),...By(e.stepCount),...zy(e.hookCount),...Vy(e.waitCount)}))}async function bb(e){let[t,n]=await Promise.all([mb(e),gb.value]);if(!(!t||!n))return n.trace.getSpanContext(t)}async function xb(){return await Cb(e=>e.trace.getActiveSpan())}async function Sb(e){return Cb(t=>t.SpanKind[e])}async function Cb(e){let t=await gb.value;if(t)return await e(t)}function wb(){return Cb(e=>{let t=e.trace.getActiveSpan()?.spanContext();if(t)return[{context:t}]})}async function Tb(e){if(!e)return;let[t,n]=await Promise.all([bb(e),gb.value]);if(!(!t||!n)&&n.trace.isSpanContextValid(t))return{context:t}}async function Eb(e,t){let n=await gb.value;if(!n)return t();let r=n.propagation.createBaggage({"workflow.run_id":{value:e.workflowRunId},"workflow.name":{value:e.workflowName}}),i=n.propagation.setBaggage(n.context.active(),r);return n.context.with(i,()=>t())}function Db(e,t){if(!t)return!1;let n=!1;for(let r of t.split(`,`)){let t=r.trim();if(!t)continue;let i=t.startsWith(`-`),a=i?t.slice(1):t;RegExp(`^${a.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`)}$`).test(e)&&(n=!i)}return n}function Ob(e,t={}){let n=r=>{let i=n=>t.debugNamespace??`workflow:${e}:${n}`,a=t=>{let n=i(t);return(i,a)=>{let o=Object.keys(r).length>0,s=a&&Object.keys(a).length>0,c=o||s?{...r,...a??{}}:void 0;(t===`error`||t===`warn`)&&(t===`error`?console.error:console.warn)(Iv(`[workflow-sdk]`,i,c)),Db(n,process.env.DEBUG)&&(console.debug(`[${n}] ${i}`,c??``),xb().then(n=>{n?.addEvent(`${t}.${e}`,{message:i,...c})}).catch(()=>{}))}};return{debug:a(`debug`),info:a(`info`),warn:a(`warn`),error:a(`error`),child:e=>n({...r,...e}),forRun:(e,t,i)=>n({...r,workflowRunId:e,...t===void 0?{}:{workflowName:t},...i??{}})}};return n({})}const kb=Ob(`step`),Ab=Ob(`runtime`),jb=Ob(`webhook`),Mb=Ob(`events`);Ob(`adapter`),Ob(`build`,{debugNamespace:`workflow:build`});function Nb(e){if(m.is(e))throw e}function Pb(e,t){let n=e.includes(`return value`)?`returning`:`passing`,r=`Failed to serialize ${e}`;t instanceof qg&&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 qg&&t.value!==void 0&&Ab.error(`Serialization failed`,{context:e,problematicValue:t.value}),{message:r,hint:i}}async function Fb(e,t,n){try{let r=pv.serialize(e,`client`,n);return Pv(await jv(gv(Q.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats),t)}catch(e){Nb(e);let{message:t,hint:n}=Pb(`client value`,e);throw new h(t,{hint:n,cause:e})}}async function Ib(e,t,n){let r=await Mv(await Fv(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(r,`client`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=vv(r);if(i===Q.DEVALUE_V1)return pv.deserialize(a,`client`,n);throw Error(`Unsupported serialization format: ${i}`)}async function Lb(e,t,n){try{let r=pv.serialize(e,`step`,n);return Pv(await jv(gv(Q.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats),t)}catch(e){Nb(e);let{message:t,hint:n}=Pb(`step value`,e);throw new h(t,{hint:n,cause:e})}}async function Rb(e,t,n){let r=await Mv(await Fv(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(r,`step`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=vv(r);if(i===Q.DEVALUE_V1)return pv.deserialize(a,`step`,n);throw Error(`Unsupported serialization format: ${i}`)}function zb(e,t){if(!(e instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(e,`workflow`,t);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:n,payload:r}=vv(e);if(n===Q.DEVALUE_V1)return pv.deserialize(r,`workflow`,t);throw Error(`Unsupported serialization format: ${n}`)}const Bb=Symbol.for(`WORKFLOW_STEP_CONTEXT_STORAGE`),Vb=globalThis[Bb]??(globalThis[Bb]=new ne);function Hb(e,t,n){if(e===0&&t===0&&n===0)return null;let r=[];e>0&&r.push(`${e} ${a(`step`,`steps`,e)}`),t>0&&r.push(`${t} ${a(`hook`,`hooks`,t)}`),n>0&&r.push(`${n} ${a(`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 o=i.join(` and `);return`${r.join(` and `)} to be enqueued\n Workflow will suspend and resume when ${o}`}function Ub(e,t){let n=`${e.replace(`wrun_`,`strm_`)}_user`;return t?`${n}_${Buffer.from(t,`utf-8`).toString(`base64url`)}`:n}function Wb(e){return`strm_${e}_system_abort`}function Gb(e){if(!e.startsWith(`abrt_`))throw Error(`Invalid abort hook token format: expected "abrt_" prefix, got "${e}"`);return Wb(e.slice(5))}var Kb;(function(e){e[e.Consumed=0]=`Consumed`,e[e.NotConsumed=1]=`NotConsumed`,e[e.Finished=2]=`Finished`})(Kb||={});var qb=class{eventIndex;events=[];callbacks=[];onConsumedEvent;onUnconsumedEvent;getPromiseQueue;pendingUnconsumedCheck=null;pendingUnconsumedTimeout=null;unconsumedCheckVersion=0;constructor(e,t){this.events=e,this.eventIndex=0,this.onConsumedEvent=t.onConsumedEvent,this.onUnconsumedEvent=t.onUnconsumedEvent,this.getPromiseQueue=t.getPromiseQueue}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){Mb.error(`onConsumedEvent callback threw an error`,{error:e})}}consume=()=>{for(;;){let e=this.events[this.eventIndex]??null;if(!this.consumeOne(e)){this.handleUnconsumed(e);return}}};consumeOne(e){for(let t=0;t<this.callbacks.length;t++){let n=this.callbacks[t],r=Kb.NotConsumed;try{r=n(e)}catch(e){Mb.error(`EventConsumer callback threw an error`,{error:e})}if(!(r!==Kb.Consumed&&r!==Kb.Finished))return e!==null&&this.notifyConsumedEvent(e),this.eventIndex++,r===Kb.Finished&&this.callbacks.splice(t,1),e!==null}return!1}handleUnconsumed(e){if(e!==null){let t=++this.unconsumedCheckVersion;this.pendingUnconsumedCheck=this.getPromiseQueue().then(()=>new Promise(e=>setTimeout(e,0))).then(()=>this.getPromiseQueue()).then(()=>{this.pendingUnconsumedTimeout=setTimeout(()=>{this.pendingUnconsumedTimeout=null,this.unconsumedCheckVersion===t&&(this.pendingUnconsumedCheck=null,this.onUnconsumedEvent(e))},100)})}}},Jb=class{aborted=!1;reason=void 0;[X];[Z];#e=[];#t=null;get onabort(){return this.#t}set onabort(e){this.#t=e,e&&this.aborted&&e.call(this)}constructor(e,t){this[X]=e,this[Z]=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 Yb(e){return class{signal;[X];[Z];constructor(){let t=e.generateUlid(),n=Wb(t),r=`abrt_${t}`;this[X]=n,this[Z]=r,this.signal=new Jb(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 Kb.NotConsumed;let n=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof n==`string`&&n!==this[Z])return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new _(`Replay divergence: abort hook event ${t.eventType} for ${i} belongs to token "${n}", but the current abort hook expects "${this[Z]}"`,{eventId:t.eventId}))}),Kb.Finished;if(t.eventType===`hook_created`){let t=e.invocationsQueue.get(i);return t&&t.type===`hook`&&(t.hasCreatedEvent=!0),Kb.Consumed}if(t.eventType===`hook_received`){let n=t.eventData?.payload;return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{let t;try{if(n!==void 0)try{let r=await zx(n,e.runId,e.encryptionKey,e.globalThis);r&&typeof r==`object`&&`reason`in r&&(t=r.reason)}catch{}this.signal._setAborted(t)}finally{e.pendingDeliveries--}}),e.invocationsQueue.delete(i),Kb.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(i),Kb.Finished):Kb.NotConsumed})}abort(t){if(!this.signal.aborted){this.signal._setAborted(t);for(let[,n]of e.invocationsQueue)if(n.type===`hook`&&n.token===this[Z]){n.abortRequested=!0,n.abortReason=t;break}}}}}function Xb(){return{abort(e){let t=new Jb(``,``);return t._setAborted(e??new DOMException(`The operation was aborted.`,`AbortError`)),t},any(e){let t=new Jb(``,``),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 Zb=Ih();function Qb(e){try{return e.getReader({mode:`byob`}).releaseLock(),`bytes`}catch{}}function $b(e){return Nb(e),e instanceof h&&e.cause!==void 0||e instanceof v&&e.cause!==void 0?e.cause:e}async function ex(e,t){if(e.recorded)try{let n=await xb();if(!n)return;let r=e.uncompressedBytes??0,i=e.storedBytes??0;n.setAttributes({...Xy(t),...Zy(e.compressed??!1),...Qy(e.codec??`none`),...$y(r),...eb(i),...e.compressed&&r>0?tb(1-i/r):{}})}catch{}}function tx(e,t){let n=new TextEncoder,r={resolved:!1,key:void 0};return new TransformStream({async transform(i,a){try{r.resolved||=(r.key=await Nv(t),!0);let o=l_(i,e),s=n.encode(o),c=gv(Q.DEVALUE_V1,s);if(r.key){let e=await m_(r.key,c);c=gv(Q.ENCRYPTED,e)}let l=new Uint8Array(4+c.length);new DataView(l.buffer).setUint32(0,c.length,!1),l.set(c,4),a.enqueue(l)}catch(e){if(m.is(e)){a.error(e);return}let{message:t,hint:n}=Pb(`stream chunk`,e);a.error(new h(t,{hint:n,cause:e}))}}})}function nx(e,t){let n=new TextDecoder,r=new Uint8Array,i={resolved:!1,key:void 0};function a(e){let t=new Uint8Array(r.length+e.length);t.set(r,0),t.set(e,r.length),r=t}async function o(a){for(i.resolved||=(i.key=await Nv(t),!0);r.length>=4;){let t=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,!1);if(r.length<4+t)break;let o=r.slice(4,4+t);r=r.slice(4+t);let{format:s,payload:c}=vv(o);if(s===Q.ENCRYPTED){if(!i.key){a.error(new m(`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:c.byteLength,formatPrefix:`encr`}}));return}let e;try{e=await h_(i.key,c)}catch(e){throw m.is(e)&&e.context&&(e.context.formatPrefix=s),e}({format:s,payload:c}=vv(e))}if(s===Q.DEVALUE_V1){let t=n.decode(c);a.enqueue(s_(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){a(t),await o(i);return}}else if(r.length>0){a(t),await o(i);return}let s=n.decode(t).split(`
59
- `);for(let t of s)t.length>0&&i.enqueue(s_(t,e))},async flush(e){r.length>0&&await o(e)}})}const rx=1e8;function ix(){return new TransformStream({transform(e,t){if(e.length===0)return;if(e.length>rx){t.error(new v(`Byte-stream chunk of ${e.length} bytes exceeds the maximum framed chunk size (${rx}). 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 ax(){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>rx){r.error(new v(`Byte-stream frame length ${t} exceeds maximum (${rx}). 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 v(`Byte-stream ended with ${e.length} bytes of incomplete frame data. The stream was truncated mid-frame.`,{slug:`serialization-failed`}))}})}var ox=class extends ReadableStream{#e;constructor(e,t,n){if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);super({type:`bytes`,pull:async r=>{let i=this.#e;if(!i){let r=await(await T_()).streams.get(e,t,n);i=this.#e=r.getReader()}if(!i){r.error(Error(`Failed to get reader`));return}let a=await i.read();a.done?(this.#e=void 0,r.close()):r.enqueue(a.value)},cancel:async e=>{this.#e&&=(await this.#e.cancel(e).catch(()=>{}),void 0)}})}};function sx(e,t,n){let r=n===void 0||n>=0,i=n??0,a=0,o=0,s=0,c,l=new Uint8Array;async function u(){let o=await T_(),s=r?i+a:n;c=(await o.streams.get(e,t,s)).getReader()}async function d(){for(c&&=(await c.cancel().catch(()=>{}),void 0),i+=a,a=0,l=new Uint8Array;;){if(o++,s++,o>50)throw Error(`Stream "${t}" exceeded maximum reconnection attempts (50)`);if(s>1e3)throw Error(`Stream "${t}" exceeded maximum total reconnection attempts (1000)`);try{await u();return}catch{}}}return new ReadableStream({pull:async e=>{for(;;){if(!c)try{await u()}catch(t){e.error(t);return}let t;try{t=await c.read()}catch(t){if(!r){e.error(t);return}try{await d()}catch(t){e.error(t);return}continue}if(t.done||!t.value){c=void 0,e.close();return}let n=t.value;if(n.length>0){let e=new Uint8Array(l.length+n.length);e.set(l,0),e.set(n,l.length),l=e}let i=!1;for(;l.length>=4;){let t=4+new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,!1);if(l.length<t)break;e.enqueue(l.slice(0,t)),l=l.slice(t),a++,i=!0}if(i){o=0;return}}},cancel:async()=>{c&&=(await c.cancel().catch(e=>{console.warn(`Error closing ReadableStream reader:`,e)}),void 0)}})}var cx=class extends WritableStream{constructor(e,t){if(typeof e!=`string`)throw new v(`"runId" must be a string, got "${typeof e}"`);if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);let n=T_(),r=[],i=null,a=null,o,s=async()=>{if(i&&=(clearTimeout(i),null),r.length===0)return;let a=r.slice(),s=await n;if(o===void 0&&(o=s.streamFlushIntervalMs??10),typeof s.streams.writeMulti==`function`&&a.length>1)await s.streams.writeMulti(e,t,a);else for(let n of a)await s.streams.write(e,t,n);r=[]},c=[],l=()=>{i||=setTimeout(()=>{i=null;let e=c;c=[],a=s().then(()=>{for(let t of e)t.resolve()},t=>{for(let n of e)n.reject(t)})},o??10)};super({async write(e){a&&=(await a,null),r.push(e),l(),await new Promise((e,t)=>{c.push({resolve:e,reject:t})})},async close(){a&&=(await a,null),await s(),await(await n).streams.close(e,t)},abort(e){i&&=(clearTimeout(i),null),r=[];let t=c;c=[];let n=e??Error(`Stream aborted`);for(let e of t)e.reject(n)}})}};function lx(e=globalThis){return{...J_(),...ov(),...iv(e),Request:t=>{if(!(t instanceof e.Request))return!1;let n={method:t.method,url:t.url,headers:t.headers,body:t.body,duplex:t.duplex},r=t[B_];return r&&(n.responseWritable=r),t.signal&&(t.signal.aborted||t.signal[X])&&(n.signal=t.signal),n},Response:t=>t instanceof e.Response?{type:t.type,url:t.url,status:t.status,statusText:t.statusText,headers:t.headers,body:t.body,redirected:t.redirected}:!1}}function ux(e,t,n,r,i,a){let o=t[X],s=t[Z];if(!o){let e=(n[N_]||Zb)();o=Wb(e),s=`abrt_${e}`,t[X]=o,t[Z]=s,t.signal&&(t.signal[X]=o,t.signal[Z]=s)}return fx(e,o,i,a,r),{streamName:o,hookToken:s,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function dx(e,t){let n=t[X]??t.signal?.[X],r=t[Z]??t.signal?.[Z];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 fx(e,t,n,r,i){e.aborted||e[H_]||(e[H_]=!0,e.addEventListener(`abort`,()=>{i.push((async()=>{try{let i=await Nv(r),a=await Mx({aborted:!0,reason:e.reason},n,i),o=new cx(n,t).getWriter();await o.write(a),await o.close()}catch{}})())},{once:!0}))}function px(e=globalThis,t,n,r,i=!1){return{...lx(e),ReadableStream:a=>{if(!(a instanceof e.ReadableStream))return!1;if(a.locked)throw new h(`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 o=`strm_${(e[N_]||Zb)()}`,s=Qb(a),c=new cx(n,o);s===`bytes`?i?t.push(a.pipeThrough(ix()).pipeTo(c)):t.push(a.pipeTo(c)):t.push(a.pipeThrough(tx(px(e,t,n,r,i),r)).pipeTo(c));let l={name:o};return s&&(l.type=s),s===`bytes`&&i&&(l.framing=`framed-v1`),l},WritableStream:r=>{if(!(r instanceof e.WritableStream))return!1;let i=r[P_],a=r[L_];if(typeof i==`string`&&typeof a==`string`){let e={name:i,runId:a},t=r[R_];return typeof t==`string`&&(e.deploymentId=t),e}let o=`strm_${(e[N_]||Zb)()}`,s=new ox(n,o);return t.push(s.pipeTo(r)),{name:o}},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function mx(e=globalThis){return{...lx(e),ReadableStream:t=>{if(!(t instanceof e.ReadableStream))return!1;let n=t[z_];if(n!==void 0)return{bodyInit:n};let r=t[P_];if(!r)throw new v("ReadableStream `name` is not set");let i={name:r},a=t[F_];a&&(i.type=a);let o=t[I_];return o&&(i.framing=o),i},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let n=t[P_];if(!n)throw new v("WritableStream `name` is not set");let r={name:n},i=t[L_];typeof i==`string`&&(r.runId=i);let a=t[R_];return typeof a==`string`&&(r.deploymentId=a),r},AbortController:t=>{if(!t||!t.signal)return!1;let n=t,r=n[X]??n.signal?.[X],i=e.AbortController&&typeof e.AbortController==`function`&&t instanceof e.AbortController;return!r&&!i?!1:dx(t.signal,n)},AbortSignal:t=>{let n=t?.[X],r=e.AbortSignal&&typeof e.AbortSignal==`function`&&t instanceof e.AbortSignal;return!n&&!r?!1:dx(t,t)}}}function hx(e=globalThis,t,n,r,i=!1){return{...lx(e),ReadableStream:a=>{if(!(a instanceof e.ReadableStream))return!1;if(a.locked)throw new h(`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 o=a[P_],s=a[F_],c=a[I_];if(!o){o=`strm_${(e[N_]||Zb)()}`,s=Qb(a),c=s===`bytes`&&i?`framed-v1`:c;let l=new cx(n,o);s===`bytes`?c===`framed-v1`?t.push(a.pipeThrough(ix()).pipeTo(l)):t.push(a.pipeTo(l)):t.push(a.pipeThrough(tx(hx(e,t,n,r,i),r)).pipeTo(l))}let l={name:o};return s&&(l.type=s),c&&(l.framing=c),l},WritableStream:i=>{if(!(i instanceof e.WritableStream))return!1;let a=i[P_],o=i[L_];a||(a=`strm_${(e[N_]||Zb)()}`,t.push(new ox(n,a).pipeThrough(nx(Tx(e,t,n,r),r)).pipeTo(i)));let s={name:a};typeof o==`string`&&(s.runId=o);let c=i[R_];return typeof c==`string`&&(s.deploymentId=c),s},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function gx(e,t,n,r){let i=new AbortController;return r.push((async()=>{try{let r=new ox(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(r.releaseLock(),a.value&&!a.done)try{let n=Vb.getStore(),r=await Nx(a.value,t,n?.encryptionKey);e.abort(r?.reason)}catch{e.abort()}}catch{}})()),i}function _x(e,t,n){let r=e,i=e.signal;r[X]=t.streamName,r[Z]=t.hookToken,i[X]=t.streamName,i[Z]=t.hookToken,n&&(r[U_]=n,i[U_]=n)}function vx(e,t){let n=e,r=t;n[X]!==void 0&&(r[X]=n[X]),n[Z]!==void 0&&(r[Z]=n[Z]),n[U_]!==void 0&&(r[U_]=n[U_])}function yx(e,t,n){let r=new AbortController;e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e);let i=r.abort.bind(r);return r.abort=t=>{if(r.signal.aborted)return;i(t);let n=Vb.getStore();if(n&&(n.ops.push((async()=>{try{let r=await Mx({aborted:!0,reason:t},n.workflowMetadata.workflowRunId,n.encryptionKey),i=new cx(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-CUCPW67D.js`).then(e=>e.i);await n(e.hookToken,{aborted:!0,reason:t})}catch{}})();n.preCompletionOps.push(r)}},r}function bx(e,t,n){let r=new AbortController;return e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e),r.signal}function xx(e=globalThis){return{...Y_(e),...av(e)}}async function Sx(e,t){let n=await T_();if(!n.getEncryptionKeyForRun)return;let r=t?await n.getEncryptionKeyForRun(e,{deploymentId:t}):await n.getEncryptionKeyForRun(await n.runs.get(e));return r?await p_(r,[`encrypt`]):void 0}function Cx(e=globalThis,t,n,r){return{...xx(e),StepFunction:()=>{throw new h(`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 h(`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&&vx(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:i=>{if(`bodyInit`in i){let t=i.bodyInit;return new e.Response(t).body}if(i.type===`bytes`){let r=new ox(n,i.name,i.startIndex),a=g_();t.push(a.promise);let{readable:o,writable:s}=i.framing===`framed-v1`?ax():new e.TransformStream;return x_(r,s,a).catch(()=>{}),b_(o,a),o}else{let a=sx(n,i.name,i.startIndex),o=nx(Cx(e,t,n,r),r),s=g_();return t.push(s.promise),x_(a,o.writable,s).catch(()=>{}),b_(o.readable,s),o.readable}},WritableStream:i=>{let a=typeof i.runId==`string`?i.runId:n,o=a===n?r:Sx(a,i.deploymentId),s=tx(px(e,t,a,o),o),c=new cx(a,i.name),l=g_();return t.push(l.promise),x_(s.readable,c,l).catch(()=>{}),y_(s.writable,l),Object.defineProperty(s.writable,P_,{value:i.name,writable:!1}),Object.defineProperty(s.writable,L_,{value:a,writable:!1}),typeof i.deploymentId==`string`&&Object.defineProperty(s.writable,R_,{value:i.deploymentId,writable:!1}),s.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}function wx(e=globalThis){return{...xx(e),...sv(e),Request:t=>{Object.setPrototypeOf(t,e.Request.prototype);let n=t.responseWritable;return n&&(t[B_]=n,delete t.responseWritable,t.respondWith=()=>{throw new h("`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 h(`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,{[z_]:{value:t.bodyInit,writable:!1}}):Object.create(e.ReadableStream.prototype,{[P_]:{value:t.name,writable:!1},[F_]:{value:t.type,writable:!1},[I_]:{value:t.framing,writable:!1}}),WritableStream:t=>{let n={[P_]:{value:t.name,writable:!1}};return typeof t.runId==`string`&&(n[L_]={value:t.runId,writable:!1}),typeof t.deploymentId==`string`&&(n[R_]={value:t.deploymentId,writable:!1}),Object.create(e.WritableStream.prototype,n)},AbortController:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),{[X]:e.streamName,[Z]:e.hookToken,signal:t,abort:()=>{}}},AbortSignal:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),t}}}function Tx(e=globalThis,t,n,r,i){return{...xx(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=y(t);if(!o)throw new h(`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=Vb.getStore();if(!e)throw new v(`Cannot call step function with closure variables outside step context`);let r={...e,closureVars:n};return Vb.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 h(`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&&vx(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 ox(n,a.name);if(a.type===`bytes`){let n=g_();t.push(n.promise);let{readable:r,writable:i}=a.framing===`framed-v1`?ax():new e.TransformStream;return x_(o,i,n).catch(()=>{}),b_(r,n),r}else{let a=nx(Tx(e,t,n,r,i),r),s=g_();return t.push(s.promise),x_(o,a.writable,s).catch(()=>{}),b_(a.readable,s),a.readable}},WritableStream:a=>{let o=typeof a.runId==`string`?a.runId:n,s=typeof a.deploymentId==`string`?a.deploymentId:o===n?i:void 0,c=o===n?r:Sx(o,s),l=tx(hx(e,t,o,c),c),u=new cx(o,a.name),d=g_();return t.push(d.promise),x_(l.readable,u,d).catch(()=>{}),y_(l.writable,d),Object.defineProperty(l.writable,P_,{value:a.name,writable:!1}),Object.defineProperty(l.writable,L_,{value:o,writable:!1}),s&&Object.defineProperty(l.writable,R_,{value:s,writable:!1}),l.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}async function Ex(e,t){return await Pv(e,t)}async function Dx(e,t){return Fv(e,t)}async function Ox(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,px(i,r,t,n,o)));try{let a={},c=await Fb(e,n,{global:i,extraReducers:Vx(px(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow arguments`,t);throw new h(n,{hint:r,cause:t})}}async function kx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}async function Ax(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow return value`,t);throw new h(n,{hint:r,cause:t})}}async function jx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Ib(e,n,{global:i,extraRevivers:{...Hx(Cx(i,r,t,n)),...a},compressionStats:o});return await ex(o,`deserialize`),s}async function Mx(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step arguments`,t);throw new h(n,{hint:r,cause:t})}}async function Nx(e,t,n,r=[],i=globalThis,a={},o){let s={},c=await Rb(e,n,{global:i,extraRevivers:{...Hx(Tx(i,r,t,n,o)),...a},compressionStats:s});return await ex(s,`deserialize`),c}async function Px(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,hx(i,r,t,n,o)));try{let a={},c=await Lb(e,n,{global:i,extraReducers:Vx(hx(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step return value`,t);throw new h(n,{hint:r,cause:t})}}async function Fx(e,t,n,r=[],i=globalThis,a=!1){try{let o=l_(e,hx(i,r,t,n)),s=new TextEncoder().encode(o),c=gv(Q.DEVALUE_V1,s),l={},u=await Ex(await jv(c,a,l),n);return await ex(l,`serialize`),u}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step error`,t);throw new h(n,{hint:r,cause:t})}}async function Ix(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);if(await ex(a,`deserialize`),!(o instanceof Uint8Array))return c_(o,{...wx(r),...i});let{format:s,payload:c}=vv(o);if(s===Q.DEVALUE_V1)return s_(new TextDecoder().decode(c),{...wx(r),...i});throw Error(`Unsupported serialization format: ${s}`)}async function Lx(e,t,n,r=globalThis,i=!1){try{let t=l_(e,mx(r)),a=new TextEncoder().encode(t),o=gv(Q.DEVALUE_V1,a),s={},c=await Ex(await jv(o,i,s),n);return await ex(s,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`run error`,t);throw new h(n,{hint:r,cause:t})}}async function Rx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Mv(await Dx(e,n),o);if(await ex(o,`deserialize`),!(s instanceof Uint8Array))return c_(s,{...Cx(i,r,t,n),...a});let{format:c,payload:l}=vv(s);if(c===Q.DEVALUE_V1)return s_(new TextDecoder().decode(l),{...Cx(i,r,t,n),...a});throw Error(`Unsupported serialization format: ${c}`)}async function zx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}const Bx=[`ReadableStream`,`WritableStream`,`Request`,`Response`,`StepFunction`,`AbortController`,`AbortSignal`];function Vx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}function Hx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}const Ux=[{format:Q.ENCRYPTED,minVersion:`4.2.0-beta.64`},{format:Q.GZIP,minVersion:`5.0.0-beta.18`},{format:Q.ZSTD,minVersion:`5.0.0-beta.18`}],Wx=[{capability:`framedByteStreams`,minVersion:`5.0.0-beta.15`}],Gx=new Set([Q.DEVALUE_V1]);function Kx(e){if(!e||!f_.default.valid(e))return{supportedFormats:Gx,framedByteStreams:!1};let t=new Set(Gx);for(let{format:n,minVersion:r}of Ux)f_.default.gte(e,r)&&t.add(n);let n={supportedFormats:t,framedByteStreams:!1};for(let{capability:t,minVersion:r}of Wx)f_.default.gte(e,r)&&(n[t]=!0);return n}const qx=`5.0.0-beta.24`,Jx=/^[a-zA-Z0-9_\-./@]+$/;function Yx(e,t){if(!Jx.test(e))throw Error(`Invalid workflow name "${e}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);return`${ah(`workflow`,ih(t))}${e}`}const Xx=Ih();function Zx(e){return`__health_check__${e}`}function Qx(e){let t=fh.safeParse(e);if(t.success)return t.data}function $x(e){return`wrun_hc_${e}`}async function eS(e,t,n){let r=await T_(),i=Zx(e.correlationId),a=JSON.stringify({healthy:!0,endpoint:t,correlationId:e.correlationId,specVersion:n??5,workflowCoreVersion:qx,timestamp:Date.now()}),o=$x(e.correlationId);await r.streams.write(o,i,a),await r.streams.close(o,i)}async function tS(e,t){let n=[],r=!1,i=!1;for(;!r&&!i;){let a=e.read(),o=new Promise(e=>setTimeout(()=>{i=!0,e({done:!0,value:void 0})},t)),s=await Promise.race([a,o]);r=s.done,s.value&&n.push(s.value)}return{chunks:n,timedOut:i}}function nS(e){if(e.length===0)return null;let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;let i=new TextDecoder().decode(n),a;try{a=JSON.parse(i)}catch{return i.length>0?{healthy:!0}:null}if(typeof a!=`object`||!a||!(`healthy`in a)||typeof a.healthy!=`boolean`)return null;let o=a,s={healthy:o.healthy};return typeof o.specVersion==`number`&&(s.specVersion=o.specVersion),typeof o.workflowCoreVersion==`string`&&(s.workflowCoreVersion=o.workflowCoreVersion),s}async function rS(e,t,n){let r=n?.timeout??3e4,i=Xx(),a=Zx(i),o=`${ah(t,ih(n?.namespace))}health_check`,s=Date.now();try{for(await e.queue(o,{__healthCheck:!0,correlationId:i},{specVersion:1,deploymentId:n?.deploymentId});Date.now()-s<r;)try{let t=(await e.streams.get($x(i),a)).getReader(),{chunks:n,timedOut:r}=await tS(t,500);if(r){try{t.cancel()}catch{}await new Promise(e=>setTimeout(e,100));continue}let o=nS(n);if(o)return{...o,latencyMs:Date.now()-s};await new Promise(e=>setTimeout(e,100))}catch{await new Promise(e=>setTimeout(e,100))}return{healthy:!1,error:`Health check timed out after ${r}ms`}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}function iS(e,t){return new d(`Event pagination ${t} for workflow run "${e}".`,{code:u.WORLD_CONTRACT_ERROR})}function aS(e,t,n){if(t){if(n.has(t))throw iS(e,`did not advance`);n.add(t)}}function oS(e,t,n){for(let r of n)t.has(r.eventId)||(t.add(r.eventId),e.push(r))}function sS(e,t,n,r){if(t){if(n===null)throw iS(e,`returned more pages without a cursor`);if(r.has(n))throw iS(e,`repeated a cursor`)}}function cS(e,t,n){return t!==null&&!n&&d.is(e)&&e.status===400}async function lS(e,t){let n=t!==void 0;return vb(n?`workflow.loadNewEvents`:`workflow.loadEvents`,async r=>{r?.setAttributes({...Jv(e)});let i=[],a=new Set,o=new Set,s=t??null,c=!0,l=0,u=!1,d=await T_(),f=Date.now();for(;c;){let t=Date.now(),r=s;aS(e,r,o);let f;try{f=await d.events.list({runId:e,pagination:{sortOrder:`asc`,cursor:r??void 0}})}catch(t){if(cS(t,r,u)){Ab.warn(`Event cursor was rejected; retrying with a full event reload.`,{workflowRunId:e}),i.length=0,a.clear(),o.clear(),s=null,u=!0;continue}throw t}oS(i,a,f.data),c=f.hasMore,sS(e,c,f.cursor,o),s=f.cursor??s,l++,Ab.debug(`Loaded event page`,{workflowRunId:e,incremental:n,page:l,pageEvents:f.data.length,totalEvents:i.length,hasMore:c,pageMs:Date.now()-t})}return Ab.debug(`Event load complete`,{workflowRunId:e,incremental:n,totalEvents:i.length,pagesLoaded:l,totalMs:Date.now()-f}),r?.setAttributes({...Zv(i.length),...Ky(l)}),{events:i,cursor:s}})}const uS={"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, OPTIONS, GET, HEAD`,"Access-Control-Allow-Headers":`Content-Type`};function dS(e,t){return async n=>{let r=new URL(n.url);return r.searchParams.has(`__health`)?n.method===`OPTIONS`?new Response(null,{status:204,headers:uS}):new Response(JSON.stringify({healthy:!0,endpoint:r.pathname,specVersion:t??5,workflowCoreVersion:qx}),{status:200,headers:{"Content-Type":`application/json`,...uS}}):await e(n)}}async function fS(e,...t){let n=t[0];await vb(`queue.publish`,{attributes:{...ky(`vercel-queue`),...Ay(n),...My(`publish`),...nb(`vercel-queue`),...rb(`vercel-queue`),...ib(`vqs`),...ab(`publish`)},kind:await Sb(`PRODUCER`)},async n=>{let{messageId:r}=await e.queue(...t);r&&n?.setAttributes(jy(r))})}function pS(e){if(e.requestedAt)try{return Ny(Date.now()-e.requestedAt.getTime())}catch{return}}function mS(e,t){let n;return()=>(n||=(async()=>{let n=await e.getEncryptionKeyForRun?.(t);return n?await p_(n):void 0})(),n)}function hS(t){import(`./functions-CnVBREsg.js`).then(t=>e(t.default,1)).then(({waitUntil:e})=>{e(t)})}function gS(e,t){hS(e.catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))try{t(e)}catch{}}))}async function _S(e){let t=e();return hS(t.catch(()=>{})),t}function vS(e,t={}){if(typeof e!=`object`||!e||Array.isArray(e))throw new g(`experimental_setAttributes requires a plain object, got ${e===null?`null`:Array.isArray(e)?`array`:typeof e}`);let n=Object.entries(e).map(([e,t])=>({key:e,value:t===void 0?null:t}));if(n.length===0)return n;let r=t.allowReservedAttributes===!0;try{Am(n,{allowReservedAttributes:r})}catch(e){throw e instanceof Em?new g(e.message):e}return n}export{sb as $,Nf as $n,Wv as $t,jx as A,xh as An,Qv as At,kb as B,oh as Bn,uy as Bt,Cx as C,Uh as Cn,Sy as Ct,Ix as D,Ih as Dn,by as Dt,Nx as E,Ah as En,Oy as Et,Hb as F,sh as Fn,sy as Ft,lb as G,Nm as Gn,Yv as Gt,fb as H,eh as Hn,py as Ht,Gb as I,ph as In,Kv as It,pb as J,jm as Jn,ty as Jt,ub as K,q as Kn,Xv as Kt,Ub as L,nh as Ln,qv as Lt,Yb as M,gh as Mn,iy as Mt,Kb as N,_h as Nn,ry as Nt,zx as O,Ch as On,yy as Ot,qb as P,mh as Pn,Zv as Pt,Py as Q,am as Qn,Gv as Qt,Vb as R,uh as Rn,$v as Rt,px as S,Wh as Sn,my as St,Rx as T,Vh as Tn,Dy as Tt,db as U,$m as Un,ly as Ut,jb as V,ih as Vn,dy as Vt,Sb as W,Pm as Wn,Jv as Wt,hb as X,wm as Xn,ny as Xt,vb as Y,Am as Yn,ey as Yt,Eb as Z,bm as Zn,cy as Zt,Mx as _,T_ as _n,Te as _r,wy as _t,Yx as a,N_ as an,R as ar,Hy as at,Ox as b,y_ as bn,hy as bt,lS as c,L_ as cn,Oe as cr,Ay as ct,fS as d,M_ as dn,je as dr,ky as dt,Q as en,Uf as er,ob as et,dS as f,k_ as fn,Me as fr,qy as ft,Lx as g,E_ as gn,Ce as gr,gy as gt,cx as h,D_ as hn,we as hr,xy as ht,pS as i,z_ as in,H as ir,Fy as it,Xb as j,yh as jn,ay as jt,kx as k,bh as kn,_y as kt,mS as l,B_ as ln,Ae as lr,jy as lt,Kx as m,O_ as mn,De as mr,Yy as mt,gS as n,K_ as nn,B as nr,Ly as nt,eS as o,P_ as on,Yf as or,Wy as ot,qx as p,j_ as pn,Ee as pr,Jy as pt,Tb as q,Em as qn,oy as qt,_S as r,q_ as rn,V as rr,Iy as rt,rS as s,R_ as sn,ed as sr,Uy as st,vS as t,G_ as tn,bf as tr,Gy as tt,Qx as u,A_ as un,ke as ur,My as ut,Fx as v,g_ as vn,Cy as vt,tx as w,Bh as wn,Ey as wt,Ax as x,p_ as xn,vy as xt,Px as y,x_ as yn,Ty as yt,Ab as z,ah as zn,fy as zt};
59
+ `);for(let t of s)t.length>0&&i.enqueue(s_(t,e))},async flush(e){r.length>0&&await o(e)}})}const rx=1e8;function ix(){return new TransformStream({transform(e,t){if(e.length===0)return;if(e.length>rx){t.error(new v(`Byte-stream chunk of ${e.length} bytes exceeds the maximum framed chunk size (${rx}). 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 ax(){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>rx){r.error(new v(`Byte-stream frame length ${t} exceeds maximum (${rx}). 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 v(`Byte-stream ended with ${e.length} bytes of incomplete frame data. The stream was truncated mid-frame.`,{slug:`serialization-failed`}))}})}var ox=class extends ReadableStream{#e;constructor(e,t,n){if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);super({type:`bytes`,pull:async r=>{let i=this.#e;if(!i){let r=await(await T_()).streams.get(e,t,n);i=this.#e=r.getReader()}if(!i){r.error(Error(`Failed to get reader`));return}let a=await i.read();a.done?(this.#e=void 0,r.close()):r.enqueue(a.value)},cancel:async e=>{this.#e&&=(await this.#e.cancel(e).catch(()=>{}),void 0)}})}};function sx(e,t,n){let r=n===void 0||n>=0,i=n??0,a=0,o=0,s=0,c,l=new Uint8Array;async function u(){let o=await T_(),s=r?i+a:n;c=(await o.streams.get(e,t,s)).getReader()}async function d(){for(c&&=(await c.cancel().catch(()=>{}),void 0),i+=a,a=0,l=new Uint8Array;;){if(o++,s++,o>50)throw Error(`Stream "${t}" exceeded maximum reconnection attempts (50)`);if(s>1e3)throw Error(`Stream "${t}" exceeded maximum total reconnection attempts (1000)`);try{await u();return}catch{}}}return new ReadableStream({pull:async e=>{for(;;){if(!c)try{await u()}catch(t){e.error(t);return}let t;try{t=await c.read()}catch(t){if(!r){e.error(t);return}try{await d()}catch(t){e.error(t);return}continue}if(t.done||!t.value){c=void 0,e.close();return}let n=t.value;if(n.length>0){let e=new Uint8Array(l.length+n.length);e.set(l,0),e.set(n,l.length),l=e}let i=!1;for(;l.length>=4;){let t=4+new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,!1);if(l.length<t)break;e.enqueue(l.slice(0,t)),l=l.slice(t),a++,i=!0}if(i){o=0;return}}},cancel:async()=>{c&&=(await c.cancel().catch(e=>{console.warn(`Error closing ReadableStream reader:`,e)}),void 0)}})}var cx=class extends WritableStream{constructor(e,t,n){if(typeof e!=`string`)throw new v(`"runId" must be a string, got "${typeof e}"`);if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);let r=T_(),i=n,a=async()=>{if(i){try{await i}catch{}i=void 0}},o=[],s=null,c=null,l,u=async()=>{if(s&&=(clearTimeout(s),null),o.length===0)return;await a();let n=o.slice(),i=await r;if(l===void 0&&(l=i.streamFlushIntervalMs??10),typeof i.streams.writeMulti==`function`&&n.length>1)await i.streams.writeMulti(e,t,n);else for(let r of n)await i.streams.write(e,t,r);o=[]},d=[],f=()=>{s||=setTimeout(()=>{s=null;let e=d;d=[],c=u().then(()=>{for(let t of e)t.resolve()},t=>{for(let n of e)n.reject(t)})},l??10)};super({async write(e){c&&=(await c,null),o.push(e),f(),await new Promise((e,t)=>{d.push({resolve:e,reject:t})})},async close(){c&&=(await c,null),await u(),await a(),await(await r).streams.close(e,t)},abort(e){s&&=(clearTimeout(s),null),o=[];let t=d;d=[];let n=e??Error(`Stream aborted`);for(let e of t)e.reject(n)}})}};function lx(e=globalThis){return{...J_(),...ov(),...iv(e),Request:t=>{if(!(t instanceof e.Request))return!1;let n={method:t.method,url:t.url,headers:t.headers,body:t.body,duplex:t.duplex},r=t[B_];return r&&(n.responseWritable=r),t.signal&&(t.signal.aborted||t.signal[X])&&(n.signal=t.signal),n},Response:t=>t instanceof e.Response?{type:t.type,url:t.url,status:t.status,statusText:t.statusText,headers:t.headers,body:t.body,redirected:t.redirected}:!1}}function ux(e,t,n,r,i,a){let o=t[X],s=t[Z];if(!o){let e=(n[N_]||Zb)();o=Wb(e),s=`abrt_${e}`,t[X]=o,t[Z]=s,t.signal&&(t.signal[X]=o,t.signal[Z]=s)}return fx(e,o,i,a,r),{streamName:o,hookToken:s,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function dx(e,t){let n=t[X]??t.signal?.[X],r=t[Z]??t.signal?.[Z];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 fx(e,t,n,r,i){e.aborted||e[H_]||(e[H_]=!0,e.addEventListener(`abort`,()=>{i.push((async()=>{try{let i=await Nv(r),a=await Mx({aborted:!0,reason:e.reason},n,i),o=new cx(n,t).getWriter();await o.write(a),await o.close()}catch{}})())},{once:!0}))}function px(e=globalThis,t,n,r,i=!1,a){return{...lx(e),ReadableStream:o=>{if(!(o instanceof e.ReadableStream))return!1;if(o.locked)throw new h(`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 s=`strm_${(e[N_]||Zb)()}`,c=Qb(o),l=new cx(n,s,a);c===`bytes`?i?t.push(o.pipeThrough(ix()).pipeTo(l)):t.push(o.pipeTo(l)):t.push(o.pipeThrough(tx(px(e,t,n,r,i,a),r)).pipeTo(l));let u={name:s};return c&&(u.type=c),c===`bytes`&&i&&(u.framing=`framed-v1`),u},WritableStream:r=>{if(!(r instanceof e.WritableStream))return!1;let i=r[P_],a=r[L_];if(typeof i==`string`&&typeof a==`string`){let e={name:i,runId:a},t=r[R_];return typeof t==`string`&&(e.deploymentId=t),e}let o=`strm_${(e[N_]||Zb)()}`,s=new ox(n,o);return t.push(s.pipeTo(r)),{name:o}},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function mx(e=globalThis){return{...lx(e),ReadableStream:t=>{if(!(t instanceof e.ReadableStream))return!1;let n=t[z_];if(n!==void 0)return{bodyInit:n};let r=t[P_];if(!r)throw new v("ReadableStream `name` is not set");let i={name:r},a=t[F_];a&&(i.type=a);let o=t[I_];return o&&(i.framing=o),i},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let n=t[P_];if(!n)throw new v("WritableStream `name` is not set");let r={name:n},i=t[L_];typeof i==`string`&&(r.runId=i);let a=t[R_];return typeof a==`string`&&(r.deploymentId=a),r},AbortController:t=>{if(!t||!t.signal)return!1;let n=t,r=n[X]??n.signal?.[X],i=e.AbortController&&typeof e.AbortController==`function`&&t instanceof e.AbortController;return!r&&!i?!1:dx(t.signal,n)},AbortSignal:t=>{let n=t?.[X],r=e.AbortSignal&&typeof e.AbortSignal==`function`&&t instanceof e.AbortSignal;return!n&&!r?!1:dx(t,t)}}}function hx(e=globalThis,t,n,r,i=!1,a){return{...lx(e),ReadableStream:o=>{if(!(o instanceof e.ReadableStream))return!1;if(o.locked)throw new h(`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 s=o[P_],c=o[F_],l=o[I_];if(!s){s=`strm_${(e[N_]||Zb)()}`,c=Qb(o),l=c===`bytes`&&i?`framed-v1`:l;let u=new cx(n,s,a);c===`bytes`?l===`framed-v1`?t.push(o.pipeThrough(ix()).pipeTo(u)):t.push(o.pipeTo(u)):t.push(o.pipeThrough(tx(hx(e,t,n,r,i,a),r)).pipeTo(u))}let u={name:s};return c&&(u.type=c),l&&(u.framing=l),u},WritableStream:i=>{if(!(i instanceof e.WritableStream))return!1;let a=i[P_],o=i[L_];a||(a=`strm_${(e[N_]||Zb)()}`,t.push(new ox(n,a).pipeThrough(nx(Tx(e,t,n,r),r)).pipeTo(i)));let s={name:a};typeof o==`string`&&(s.runId=o);let c=i[R_];return typeof c==`string`&&(s.deploymentId=c),s},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function gx(e,t,n,r){let i=new AbortController;return r.push((async()=>{try{let r=new ox(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(r.releaseLock(),a.value&&!a.done)try{let n=Vb.getStore(),r=await Nx(a.value,t,n?.encryptionKey);e.abort(r?.reason)}catch{e.abort()}}catch{}})()),i}function _x(e,t,n){let r=e,i=e.signal;r[X]=t.streamName,r[Z]=t.hookToken,i[X]=t.streamName,i[Z]=t.hookToken,n&&(r[U_]=n,i[U_]=n)}function vx(e,t){let n=e,r=t;n[X]!==void 0&&(r[X]=n[X]),n[Z]!==void 0&&(r[Z]=n[Z]),n[U_]!==void 0&&(r[U_]=n[U_])}function yx(e,t,n){let r=new AbortController;e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e);let i=r.abort.bind(r);return r.abort=t=>{if(r.signal.aborted)return;i(t);let n=Vb.getStore();if(n&&(n.ops.push((async()=>{try{let r=await Mx({aborted:!0,reason:t},n.workflowMetadata.workflowRunId,n.encryptionKey),i=new cx(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-C15uJ2ik.js`).then(e=>e.i);await n(e.hookToken,{aborted:!0,reason:t})}catch{}})();n.preCompletionOps.push(r)}},r}function bx(e,t,n){let r=new AbortController;return e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e),r.signal}function xx(e=globalThis){return{...Y_(e),...av(e)}}async function Sx(e,t){let n=await T_();if(!n.getEncryptionKeyForRun)return;let r=t?await n.getEncryptionKeyForRun(e,{deploymentId:t}):await n.getEncryptionKeyForRun(await n.runs.get(e));return r?await p_(r,[`encrypt`]):void 0}function Cx(e=globalThis,t,n,r){return{...xx(e),StepFunction:()=>{throw new h(`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 h(`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&&vx(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:i=>{if(`bodyInit`in i){let t=i.bodyInit;return new e.Response(t).body}if(i.type===`bytes`){let r=new ox(n,i.name,i.startIndex),a=g_();t.push(a.promise);let{readable:o,writable:s}=i.framing===`framed-v1`?ax():new e.TransformStream;return x_(r,s,a).catch(()=>{}),b_(o,a),o}else{let a=sx(n,i.name,i.startIndex),o=nx(Cx(e,t,n,r),r),s=g_();return t.push(s.promise),x_(a,o.writable,s).catch(()=>{}),b_(o.readable,s),o.readable}},WritableStream:i=>{let a=typeof i.runId==`string`?i.runId:n,o=a===n?r:Sx(a,i.deploymentId),s=tx(px(e,t,a,o),o),c=new cx(a,i.name),l=g_();return t.push(l.promise),x_(s.readable,c,l).catch(()=>{}),y_(s.writable,l),Object.defineProperty(s.writable,P_,{value:i.name,writable:!1}),Object.defineProperty(s.writable,L_,{value:a,writable:!1}),typeof i.deploymentId==`string`&&Object.defineProperty(s.writable,R_,{value:i.deploymentId,writable:!1}),s.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}function wx(e=globalThis){return{...xx(e),...sv(e),Request:t=>{Object.setPrototypeOf(t,e.Request.prototype);let n=t.responseWritable;return n&&(t[B_]=n,delete t.responseWritable,t.respondWith=()=>{throw new h("`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 h(`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,{[z_]:{value:t.bodyInit,writable:!1}}):Object.create(e.ReadableStream.prototype,{[P_]:{value:t.name,writable:!1},[F_]:{value:t.type,writable:!1},[I_]:{value:t.framing,writable:!1}}),WritableStream:t=>{let n={[P_]:{value:t.name,writable:!1}};return typeof t.runId==`string`&&(n[L_]={value:t.runId,writable:!1}),typeof t.deploymentId==`string`&&(n[R_]={value:t.deploymentId,writable:!1}),Object.create(e.WritableStream.prototype,n)},AbortController:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),{[X]:e.streamName,[Z]:e.hookToken,signal:t,abort:()=>{}}},AbortSignal:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),t}}}function Tx(e=globalThis,t,n,r,i){return{...xx(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=y(t);if(!o)throw new h(`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=Vb.getStore();if(!e)throw new v(`Cannot call step function with closure variables outside step context`);let r={...e,closureVars:n};return Vb.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 h(`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&&vx(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 ox(n,a.name);if(a.type===`bytes`){let n=g_();t.push(n.promise);let{readable:r,writable:i}=a.framing===`framed-v1`?ax():new e.TransformStream;return x_(o,i,n).catch(()=>{}),b_(r,n),r}else{let a=nx(Tx(e,t,n,r,i),r),s=g_();return t.push(s.promise),x_(o,a.writable,s).catch(()=>{}),b_(a.readable,s),a.readable}},WritableStream:a=>{let o=typeof a.runId==`string`?a.runId:n,s=typeof a.deploymentId==`string`?a.deploymentId:o===n?i:void 0,c=o===n?r:Sx(o,s),l=tx(hx(e,t,o,c),c),u=new cx(o,a.name),d=g_();return t.push(d.promise),x_(l.readable,u,d).catch(()=>{}),y_(l.writable,d),Object.defineProperty(l.writable,P_,{value:a.name,writable:!1}),Object.defineProperty(l.writable,L_,{value:o,writable:!1}),s&&Object.defineProperty(l.writable,R_,{value:s,writable:!1}),l.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}async function Ex(e,t){return await Pv(e,t)}async function Dx(e,t){return Fv(e,t)}async function Ox(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,px(i,r,t,n,o)));try{let a={},c=await Fb(e,n,{global:i,extraReducers:Vx(px(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow arguments`,t);throw new h(n,{hint:r,cause:t})}}async function kx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}async function Ax(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow return value`,t);throw new h(n,{hint:r,cause:t})}}async function jx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Ib(e,n,{global:i,extraRevivers:{...Hx(Cx(i,r,t,n)),...a},compressionStats:o});return await ex(o,`deserialize`),s}async function Mx(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step arguments`,t);throw new h(n,{hint:r,cause:t})}}async function Nx(e,t,n,r=[],i=globalThis,a={},o){let s={},c=await Rb(e,n,{global:i,extraRevivers:{...Hx(Tx(i,r,t,n,o)),...a},compressionStats:s});return await ex(s,`deserialize`),c}async function Px(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1,c){if(a)return $_(l_(e,hx(i,r,t,n,o,c)));try{let a={},l=await Lb(e,n,{global:i,extraReducers:Vx(hx(i,r,t,n,o,c)),compression:s,compressionStats:a});return await ex(a,`serialize`),l}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step return value`,t);throw new h(n,{hint:r,cause:t})}}async function Fx(e,t,n,r=[],i=globalThis,a=!1){try{let o=l_(e,hx(i,r,t,n)),s=new TextEncoder().encode(o),c=gv(Q.DEVALUE_V1,s),l={},u=await Ex(await jv(c,a,l),n);return await ex(l,`serialize`),u}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step error`,t);throw new h(n,{hint:r,cause:t})}}async function Ix(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);if(await ex(a,`deserialize`),!(o instanceof Uint8Array))return c_(o,{...wx(r),...i});let{format:s,payload:c}=vv(o);if(s===Q.DEVALUE_V1)return s_(new TextDecoder().decode(c),{...wx(r),...i});throw Error(`Unsupported serialization format: ${s}`)}async function Lx(e,t,n,r=globalThis,i=!1){try{let t=l_(e,mx(r)),a=new TextEncoder().encode(t),o=gv(Q.DEVALUE_V1,a),s={},c=await Ex(await jv(o,i,s),n);return await ex(s,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`run error`,t);throw new h(n,{hint:r,cause:t})}}async function Rx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Mv(await Dx(e,n),o);if(await ex(o,`deserialize`),!(s instanceof Uint8Array))return c_(s,{...Cx(i,r,t,n),...a});let{format:c,payload:l}=vv(s);if(c===Q.DEVALUE_V1)return s_(new TextDecoder().decode(l),{...Cx(i,r,t,n),...a});throw Error(`Unsupported serialization format: ${c}`)}async function zx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}const Bx=[`ReadableStream`,`WritableStream`,`Request`,`Response`,`StepFunction`,`AbortController`,`AbortSignal`];function Vx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}function Hx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}const Ux=[{format:Q.ENCRYPTED,minVersion:`4.2.0-beta.64`},{format:Q.GZIP,minVersion:`5.0.0-beta.18`},{format:Q.ZSTD,minVersion:`5.0.0-beta.18`}],Wx=[{capability:`framedByteStreams`,minVersion:`5.0.0-beta.15`}],Gx=new Set([Q.DEVALUE_V1]);function Kx(e){if(!e||!f_.default.valid(e))return{supportedFormats:Gx,framedByteStreams:!1};let t=new Set(Gx);for(let{format:n,minVersion:r}of Ux)f_.default.gte(e,r)&&t.add(n);let n={supportedFormats:t,framedByteStreams:!1};for(let{capability:t,minVersion:r}of Wx)f_.default.gte(e,r)&&(n[t]=!0);return n}const qx=`5.0.0-beta.26`,Jx=/^[a-zA-Z0-9_\-./@]+$/;function Yx(e,t){if(!Jx.test(e))throw Error(`Invalid workflow name "${e}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);return`${ah(`workflow`,ih(t))}${e}`}const Xx=Ih();function Zx(e){return`__health_check__${e}`}function Qx(e){let t=fh.safeParse(e);if(t.success)return t.data}function $x(e){return`wrun_hc_${e}`}async function eS(e,t,n){let r=await T_(),i=Zx(e.correlationId),a=JSON.stringify({healthy:!0,endpoint:t,correlationId:e.correlationId,specVersion:n??5,workflowCoreVersion:qx,timestamp:Date.now()}),o=$x(e.correlationId);await r.streams.write(o,i,a),await r.streams.close(o,i)}async function tS(e,t){let n=[],r=!1,i=!1;for(;!r&&!i;){let a=e.read(),o=new Promise(e=>setTimeout(()=>{i=!0,e({done:!0,value:void 0})},t)),s=await Promise.race([a,o]);r=s.done,s.value&&n.push(s.value)}return{chunks:n,timedOut:i}}function nS(e){if(e.length===0)return null;let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;let i=new TextDecoder().decode(n),a;try{a=JSON.parse(i)}catch{return i.length>0?{healthy:!0}:null}if(typeof a!=`object`||!a||!(`healthy`in a)||typeof a.healthy!=`boolean`)return null;let o=a,s={healthy:o.healthy};return typeof o.specVersion==`number`&&(s.specVersion=o.specVersion),typeof o.workflowCoreVersion==`string`&&(s.workflowCoreVersion=o.workflowCoreVersion),s}async function rS(e,t,n){let r=n?.timeout??3e4,i=Xx(),a=Zx(i),o=`${ah(t,ih(n?.namespace))}health_check`,s=Date.now();try{for(await e.queue(o,{__healthCheck:!0,correlationId:i},{specVersion:1,deploymentId:n?.deploymentId});Date.now()-s<r;)try{let t=(await e.streams.get($x(i),a)).getReader(),{chunks:n,timedOut:r}=await tS(t,500);if(r){try{t.cancel()}catch{}await new Promise(e=>setTimeout(e,100));continue}let o=nS(n);if(o)return{...o,latencyMs:Date.now()-s};await new Promise(e=>setTimeout(e,100))}catch{await new Promise(e=>setTimeout(e,100))}return{healthy:!1,error:`Health check timed out after ${r}ms`}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}function iS(e,t){return new d(`Event pagination ${t} for workflow run "${e}".`,{code:u.WORLD_CONTRACT_ERROR})}function aS(e,t,n){if(t){if(n.has(t))throw iS(e,`did not advance`);n.add(t)}}function oS(e,t,n){for(let r of n)t.has(r.eventId)||(t.add(r.eventId),e.push(r))}function sS(e,t,n,r){if(t){if(n===null)throw iS(e,`returned more pages without a cursor`);if(r.has(n))throw iS(e,`repeated a cursor`)}}function cS(e,t,n){return t!==null&&!n&&d.is(e)&&e.status===400}async function lS(e,t){let n=t!==void 0;return vb(n?`workflow.loadNewEvents`:`workflow.loadEvents`,async r=>{r?.setAttributes({...Jv(e)});let i=[],a=new Set,o=new Set,s=t??null,c=!0,l=0,u=!1,d=await T_(),f=Date.now();for(;c;){let t=Date.now(),r=s;aS(e,r,o);let f;try{f=await d.events.list({runId:e,pagination:{sortOrder:`asc`,cursor:r??void 0}})}catch(t){if(cS(t,r,u)){Ab.warn(`Event cursor was rejected; retrying with a full event reload.`,{workflowRunId:e}),i.length=0,a.clear(),o.clear(),s=null,u=!0;continue}throw t}oS(i,a,f.data),c=f.hasMore,sS(e,c,f.cursor,o),s=f.cursor??s,l++,Ab.debug(`Loaded event page`,{workflowRunId:e,incremental:n,page:l,pageEvents:f.data.length,totalEvents:i.length,hasMore:c,pageMs:Date.now()-t})}return Ab.debug(`Event load complete`,{workflowRunId:e,incremental:n,totalEvents:i.length,pagesLoaded:l,totalMs:Date.now()-f}),r?.setAttributes({...Zv(i.length),...Ky(l)}),{events:i,cursor:s}})}const uS={"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, OPTIONS, GET, HEAD`,"Access-Control-Allow-Headers":`Content-Type`};function dS(e,t){return async n=>{let r=new URL(n.url);return r.searchParams.has(`__health`)?n.method===`OPTIONS`?new Response(null,{status:204,headers:uS}):new Response(JSON.stringify({healthy:!0,endpoint:r.pathname,specVersion:t??5,workflowCoreVersion:qx}),{status:200,headers:{"Content-Type":`application/json`,...uS}}):await e(n)}}async function fS(e,...t){let n=t[0];await vb(`queue.publish`,{attributes:{...ky(`vercel-queue`),...Ay(n),...My(`publish`),...nb(`vercel-queue`),...rb(`vercel-queue`),...ib(`vqs`),...ab(`publish`)},kind:await Sb(`PRODUCER`)},async n=>{let{messageId:r}=await e.queue(...t);r&&n?.setAttributes(jy(r))})}function pS(e){if(e.requestedAt)try{return Ny(Date.now()-e.requestedAt.getTime())}catch{return}}function mS(e,t){let n;return()=>(n||=(async()=>{let n=await e.getEncryptionKeyForRun?.(t);return n?await p_(n):void 0})(),n)}function hS(t){import(`./functions-CnVBREsg.js`).then(t=>e(t.default,1)).then(({waitUntil:e})=>{e(t)})}function gS(e,t){hS(e.catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))try{t(e)}catch{}}))}async function _S(e){let t=e();return hS(t.catch(()=>{})),t}function vS(e,t={}){if(typeof e!=`object`||!e||Array.isArray(e))throw new g(`experimental_setAttributes requires a plain object, got ${e===null?`null`:Array.isArray(e)?`array`:typeof e}`);let n=Object.entries(e).map(([e,t])=>({key:e,value:t===void 0?null:t}));if(n.length===0)return n;let r=t.allowReservedAttributes===!0;try{Am(n,{allowReservedAttributes:r})}catch(e){throw e instanceof Em?new g(e.message):e}return n}export{sb as $,Nf as $n,Wv as $t,jx as A,xh as An,Qv as At,kb as B,oh as Bn,uy as Bt,Cx as C,Uh as Cn,Sy as Ct,Ix as D,Ih as Dn,by as Dt,Nx as E,Ah as En,Oy as Et,Hb as F,sh as Fn,sy as Ft,lb as G,Nm as Gn,Yv as Gt,fb as H,eh as Hn,py as Ht,Gb as I,ph as In,Kv as It,pb as J,jm as Jn,ty as Jt,ub as K,q as Kn,Xv as Kt,Ub as L,nh as Ln,qv as Lt,Yb as M,gh as Mn,iy as Mt,Kb as N,_h as Nn,ry as Nt,zx as O,Ch as On,yy as Ot,qb as P,mh as Pn,Zv as Pt,Py as Q,am as Qn,Gv as Qt,Vb as R,uh as Rn,$v as Rt,px as S,Wh as Sn,my as St,Rx as T,Vh as Tn,Dy as Tt,db as U,$m as Un,ly as Ut,jb as V,ih as Vn,dy as Vt,Sb as W,Pm as Wn,Jv as Wt,hb as X,wm as Xn,ny as Xt,vb as Y,Am as Yn,ey as Yt,Eb as Z,bm as Zn,cy as Zt,Mx as _,T_ as _n,Te as _r,wy as _t,Yx as a,N_ as an,R as ar,Hy as at,Ox as b,y_ as bn,hy as bt,lS as c,L_ as cn,Oe as cr,Ay as ct,fS as d,M_ as dn,je as dr,ky as dt,Q as en,Uf as er,ob as et,dS as f,k_ as fn,Me as fr,qy as ft,Lx as g,E_ as gn,Ce as gr,gy as gt,cx as h,D_ as hn,we as hr,xy as ht,pS as i,z_ as in,H as ir,Fy as it,Xb as j,yh as jn,ay as jt,kx as k,bh as kn,_y as kt,mS as l,B_ as ln,Ae as lr,jy as lt,Kx as m,O_ as mn,De as mr,Yy as mt,gS as n,K_ as nn,B as nr,Ly as nt,eS as o,P_ as on,Yf as or,Wy as ot,qx as p,j_ as pn,Ee as pr,Jy as pt,Tb as q,Em as qn,oy as qt,_S as r,q_ as rn,V as rr,Iy as rt,rS as s,R_ as sn,ed as sr,Uy as st,vS as t,G_ as tn,bf as tr,Gy as tt,Qx as u,A_ as un,ke as ur,My as ut,Fx as v,g_ as vn,Cy as vt,tx as w,Bh as wn,Ey as wt,Ax as x,p_ as xn,vy as xt,Px as y,x_ as yn,Ty as yt,Ab as z,ah as zn,fy as zt};
@@ -1 +1 @@
1
- import{r as e}from"./chunk-BHKSVoKr.js";import{n as t,o as n,w as r}from"./dist-Dxrjttr2.js";import{E as i,It as a,Wt as o,Y as s,_n as c,a as l,en as u,it as d,kn as f,ln as p,m,n as h,nt as g,q as _,r as v,rt as y,xn as b,y as x,z as S}from"./attribute-changes-DUxG-Gic.js";var C=e({getHookByToken:()=>T,resumeHook:()=>E,resumeWebhook:()=>D});async function w(e){let t=await c(),n=await t.hooks.getByToken(e),r=await t.runs.get(n.runId),a=await t.getEncryptionKeyForRun?.(r),o=a?await b(a):void 0;return n.metadata!==void 0&&(n.metadata=await i(n.metadata,n.runId,o)),{hook:n,run:r,encryptionKey:o}}async function T(e){let{hook:t}=await w(e);return t}async function E(e,t,n){return await v(()=>s(`hook.resume`,async r=>{let i=await c();try{let s,c,p;if(typeof e==`string`){let t=await w(e);s=t.hook,c=t.run,p=n??t.encryptionKey}else if(s=e,c=await i.runs.get(s.runId),n)p=n;else{let e=await i.getEncryptionKeyForRun?.(c);p=e?await b(e):void 0}r?.setAttributes({...d(s.token),...y(s.hookId),...o(s.runId)});let g=c.executionContext?.workflowCoreVersion,v=m(typeof g==`string`?g:void 0);v.supportedFormats.has(u.ENCRYPTED)||(p=void 0);let C=(c.specVersion??0)>=5&&v.supportedFormats.has(u.GZIP),T=[],E=f(s.specVersion),D=await x(t,s.runId,p,T,globalThis,E,v.framedByteStreams,C);h(Promise.all(T),e=>{e!==void 0&&S.warn(`Background flush of hook payload ops failed`,{workflowRunId:s.runId,hookId:s.hookId,error:e instanceof Error?e.message:String(e)})}),await i.events.create(s.runId,{eventType:`hook_received`,specVersion:5,correlationId:s.hookId,eventData:{...E?{}:{token:s.token},payload:D}},{v1Compat:E}),r?.setAttributes({...a(c.workflowName)});let O=await _(c.executionContext?.traceCarrier);return O&&r?.addLink?.(O),await i.queue(l(c.workflowName),{runId:s.runId,traceCarrier:c.executionContext?.traceCarrier??void 0},{deploymentId:c.deploymentId,specVersion:c.specVersion??1}),s}catch(t){throw r?.setAttributes({...d(typeof e==`string`?e:e.token),...g(!1)}),t}}))}async function D(e,i){let{hook:a,encryptionKey:o}=await w(e);if(a.isWebhook===!1)throw new n(e);let s,c;if(a.metadata&&typeof a.metadata==`object`&&`respondWith`in a.metadata)if(a.metadata.respondWith===`manual`){let{readable:e,writable:t}=new TransformStream;c=e,i[p]=t}else if(a.metadata.respondWith instanceof Response)s=a.metadata.respondWith;else throw new r(`Invalid \`respondWith\` value: ${a.metadata.respondWith}`,{slug:t.WEBHOOK_INVALID_RESPOND_WITH_VALUE});else s=new Response(null,{status:202});if(await E(a,i,o),c){let e=c.getReader(),t=await e.read();t.value&&(s=t.value),e.cancel()}if(!s)throw new r(`Workflow run did not send a response`,{slug:t.WEBHOOK_RESPONSE_NOT_SENT});return s}export{C as i,E as n,D as r,T as t};
1
+ import{r as e}from"./chunk-BHKSVoKr.js";import{n as t,o as n,w as r}from"./dist-Dxrjttr2.js";import{E as i,It as a,Wt as o,Y as s,_n as c,a as l,en as u,it as d,kn as f,ln as p,m,n as h,nt as g,q as _,r as v,rt as y,xn as b,y as x,z as S}from"./attribute-changes-zAifvEhb.js";var C=e({getHookByToken:()=>T,resumeHook:()=>E,resumeWebhook:()=>D});async function w(e){let t=await c(),n=await t.hooks.getByToken(e),r=await t.runs.get(n.runId),a=await t.getEncryptionKeyForRun?.(r),o=a?await b(a):void 0;return n.metadata!==void 0&&(n.metadata=await i(n.metadata,n.runId,o)),{hook:n,run:r,encryptionKey:o}}async function T(e){let{hook:t}=await w(e);return t}async function E(e,t,n){return await v(()=>s(`hook.resume`,async r=>{let i=await c();try{let s,c,p;if(typeof e==`string`){let t=await w(e);s=t.hook,c=t.run,p=n??t.encryptionKey}else if(s=e,c=await i.runs.get(s.runId),n)p=n;else{let e=await i.getEncryptionKeyForRun?.(c);p=e?await b(e):void 0}r?.setAttributes({...d(s.token),...y(s.hookId),...o(s.runId)});let g=c.executionContext?.workflowCoreVersion,v=m(typeof g==`string`?g:void 0);v.supportedFormats.has(u.ENCRYPTED)||(p=void 0);let C=(c.specVersion??0)>=5&&v.supportedFormats.has(u.GZIP),T=[],E=f(s.specVersion),D=await x(t,s.runId,p,T,globalThis,E,v.framedByteStreams,C);h(Promise.all(T),e=>{e!==void 0&&S.warn(`Background flush of hook payload ops failed`,{workflowRunId:s.runId,hookId:s.hookId,error:e instanceof Error?e.message:String(e)})}),await i.events.create(s.runId,{eventType:`hook_received`,specVersion:5,correlationId:s.hookId,eventData:{...E?{}:{token:s.token},payload:D}},{v1Compat:E}),r?.setAttributes({...a(c.workflowName)});let O=await _(c.executionContext?.traceCarrier);return O&&r?.addLink?.(O),await i.queue(l(c.workflowName),{runId:s.runId,traceCarrier:c.executionContext?.traceCarrier??void 0},{deploymentId:c.deploymentId,specVersion:c.specVersion??1}),s}catch(t){throw r?.setAttributes({...d(typeof e==`string`?e:e.token),...g(!1)}),t}}))}async function D(e,i){let{hook:a,encryptionKey:o}=await w(e);if(a.isWebhook===!1)throw new n(e);let s,c;if(a.metadata&&typeof a.metadata==`object`&&`respondWith`in a.metadata)if(a.metadata.respondWith===`manual`){let{readable:e,writable:t}=new TransformStream;c=e,i[p]=t}else if(a.metadata.respondWith instanceof Response)s=a.metadata.respondWith;else throw new r(`Invalid \`respondWith\` value: ${a.metadata.respondWith}`,{slug:t.WEBHOOK_INVALID_RESPOND_WITH_VALUE});else s=new Response(null,{status:202});if(await E(a,i,o),c){let e=c.getReader(),t=await e.read();t.value&&(s=t.value),e.cancel()}if(!s)throw new r(`Workflow run did not send a response`,{slug:t.WEBHOOK_RESPONSE_NOT_SENT});return s}export{C as i,E as n,D as r,T as t};
@@ -0,0 +1 @@
1
+ import{d as e}from"./dist-FLIfyJ4Y.js";import{C as t,E as n,S as r,T as i,b as a,d as o,m as s,p as c,r as l,s as u,t as d,w as f,x as p,y as m}from"./dist-Dxrjttr2.js";import{A as h,At as g,C as _,Dn as v,Gt as ee,It as y,J as b,L as x,Lt as S,Q as C,T as w,Wt as T,Y as E,_n as D,a as O,b as k,en as A,gn as j,hn as M,k as N,kn as P,m as F,n as I,p as L,r as R,s as z,t as B,xn as V,z as H}from"./attribute-changes-zAifvEhb.js";const U=new Set([`PARSE_ERROR`,`SCHEMA_VALIDATION`,n.WORLD_CONTRACT_ERROR]),W=new Set([`TRANSPORT`,`TIMEOUT`]),G=[f.is,c.is,m.is,o.is];function K(e){if(!i.is(e)||e.status!==void 0)return!1;let t=`cause`in e?e.cause:void 0;return e.code!==void 0&&U.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 s.is(e)?!0:i.is(e)?e.status!==void 0&&e.status>=500?!0:e.code!==void 0&&W.has(e.code):!1}function J(e){if(u.is(e))return n.REPLAY_DIVERGENCE;if(d.is(e))return n.CORRUPTED_EVENT_LOG;if(K(e)||q(e))return n.WORLD_CONTRACT_ERROR;for(let t of G)if(t(e))return n.RUNTIME_ERROR;return n.USER_ERROR}const Y=v();let X=!1;async function Z(t,n,r){"use step";return await R(()=>{let i=t?.workflowId;if(!i)throw new f(`'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`});return E(`workflow.start ${e(i)}`,async e=>{e?.setAttributes({...y(i),...S(`start`)});let t=[],a=r??{};Array.isArray(n)?t=n:typeof n==`object`&&(a=n),e?.setAttributes({...g(t.length)});let o=a?.world??await D(),s=await o.getDeploymentId(),c=a.deploymentId??s;c===`latest`&&(o.resolveLatestDeploymentId?c=await o.resolveLatestDeploymentId():(X||(X=!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:s})),c=s));let u,d;if(c===s)u=!0,d=!0;else if(typeof o.streams?.get!=`function`)u=!1,d=!1;else{let e=F((await z(o,`workflow`,{deploymentId:c,timeout:2e3}).catch(()=>void 0))?.workflowCoreVersion);u=e.framedByteStreams,d=e.supportedFormats.has(A.GZIP)}let p=[],m=`wrun_${Y()}`,h=await b(),_=a.specVersion??o.specVersion??2,v=P(_),x=a.allowReservedAttributes===!0,w;if(a.attributes&&Object.keys(a.attributes).length>0){if(_<4)throw new f(`Initial workflow attributes require a World that supports spec version 4 or later.`);for(let[e,t]of Object.entries(a.attributes))if(typeof t!=`string`)throw new f(`Initial workflow attribute ${JSON.stringify(e)} must be a string value.`);let e=B(a.attributes,{allowReservedAttributes:x});w=Object.fromEntries(e.map(({key:e,value:t})=>[e,t]))}let E=w?{attributes:w,...x?{allowReservedAttributes:!0}:{}}:{},j=await o.getEncryptionKeyForRun?.(m,{...a,deploymentId:c}),M=j?await V(j):void 0,N=await k(t,m,M,p,globalThis,v,u,d&&_>=5),R={traceCarrier:h,workflowCoreVersion:L,features:{encryption:!!M}},[U,W]=await Promise.allSettled([o.events.create(m,{eventType:`run_created`,specVersion:_,eventData:{deploymentId:c,workflowName:i,input:N,executionContext:R,...E}},{v1Compat:v}),o.queue(O(i),{runId:m,traceCarrier:h,..._>=3?{runInput:{input:N,deploymentId:c,workflowName:i,specVersion:_,executionContext:R,...E}}:{}},{deploymentId:c,specVersion:_})]);if(W.status===`rejected`)throw W.reason;let G=!1;if(U.status===`rejected`){let e=U.reason;if(!l.is(e))if(q(e))G=!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:m,error:e.message});else throw e}else{let e=U.value;if(!e.run)throw new f(`Missing 'run' in server response for 'run_created' event`);if(!v&&e.run.runId!==m)throw new f(`Server returned different runId than requested: expected ${m}, got ${e.run.runId}`)}return I(Promise.all(p),e=>{H.warn(`Background flush of workflow argument streams failed`,{workflowRunId:m,error:e instanceof Error?e.message:String(e)})}),e?.setAttributes({...T(m),...C(c),...U.status===`fulfilled`&&U.value.run?ee(U.value.run.status):{}}),new $(m,{resilientStart:G})})})}const te=e=>Array.isArray(e)?e:[e];async function ne(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await V(i):void 0,o=te(await N(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})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function re(e,t){try{let n=(await e.runs.get(t,{resolveData:`none`})).specVersion??1,r=P(n),i={eventType:`run_cancelled`,specVersion:n};await e.events.create(t,i,{v1Compat:r})}catch(e){throw Error(`Failed to cancel run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function ie(e,t){try{let n=await e.runs.get(t,{resolveData:`none`});await e.queue(O(n.workflowName),{runId:t},{deploymentId:n.deploymentId,specVersion:n.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Q(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`}),i=P(r.specVersion),a=[],o=null;do{let n=await e.events.list({runId:t,pagination:{limit:1e3,...o?{cursor:o}:{}},resolveData:`none`});a.push(...n.data),o=n.hasMore?n.cursor:null}while(o);let s=a.filter(e=>e.eventType===`wait_created`),c=new Set(a.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),u=s.filter(e=>!c.has(e.correlationId));if(n?.correlationIds&&n.correlationIds.length>0){let e=new Set(n.correlationIds);u=u.filter(t=>t.correlationId&&e.has(t.correlationId))}let d=[],f=0;for(let n of u){if(!n.correlationId)continue;let a=i?{eventType:`wait_completed`,correlationId:n.correlationId}:{eventType:`wait_completed`,correlationId:n.correlationId,specVersion:r.specVersion,eventData:{resumeAt:n.eventData.resumeAt}};try{await e.events.create(t,a,{v1Compat:i}),f++}catch(e){l.is(e)?f++:d.push(e instanceof Error?e:Error(String(e)))}}if(f>0&&await e.queue(O(r.workflowName),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1}),d.length>0)throw AggregateError(d,`Failed to complete ${d.length}/${u.length} pending wait(s) for run ${t}`);return{stoppedCount:f}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function ae(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw Error(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function oe(e,t){try{return await e.streams.list(t)}catch(e){throw Error(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}var $=class e{static[j](e){return{runId:e.runId,resilientStart:e.#r}}static[M](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=D(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(){return this.#n||=(async()=>{let e=await this.#t,t=await e.runs.get(this.runId),n=await e.getEncryptionKeyForRun?.(t);return n?await V(n):void 0})(),this.#n}#a(){return()=>this.#i()}async wakeUp(e){"use step";return Q(await this.#t,this.runId,e)}async cancel(){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:5})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(t.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.status))}get returnValue(){"use step";return this.#o()}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=x(this.runId,i),o=this.#a(),s=_(n,t,this.runId,o).ReadableStream({name:a,startIndex:r}),c=this.#t,l=this.runId;return Object.assign(s,{getTailIndex:async()=>(await(await c).streams.getInfo(l,a)).tailIndex})}async#o(){let e=await this.#t,n=0,i=this.#r?3:0,o=[1e3,3e3,6e3];for(;;)try{let t=await e.runs.get(this.runId);if(t.status===`completed`){let e=await this.#i();return await h(t.output,this.runId,e)}if(t.status===`cancelled`)throw new a(this.runId);if(t.status===`failed`){let e=await this.#i(),n;try{n=await w(t.error,this.runId,e)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new p(this.runId,n,{errorCode:t.errorCode})}throw new r(this.runId,t.status)}catch(e){if(r.is(e)){await new Promise(e=>setTimeout(e,1e3));continue}if(t.is(e)&&n<i){let e=o[n];n++,await new Promise(t=>setTimeout(t,e));continue}throw e}}};function se(e){return new $(e)}export{ae as a,Q as c,q as d,K as f,oe as i,Z as l,se as n,ne as o,re as r,ie as s,$ as t,J as u};
@@ -1 +1 @@
1
- import{pn as e,ur as t}from"./attribute-changes-DUxG-Gic.js";async function n(r){let i=globalThis[e];return i||t(`sleep()`,`https://workflow-sdk.dev/docs/api-reference/workflow/sleep`,n),i(r)}export{n as t};
1
+ import{pn as e,ur as t}from"./attribute-changes-zAifvEhb.js";async function n(r){let i=globalThis[e];return i||t(`sleep()`,`https://workflow-sdk.dev/docs/api-reference/workflow/sleep`,n),i(r)}export{n as t};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),u=getPendingRuntimeActionBatch(s.state);if(u===void 0||u.actions.length===0)return{results:[],sessionState:e.sessionState};let d=await deserializeContext(e.serializedContext),f=d.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:f.turnAgent}),m=d.require(ChannelKey),h=d.get(AuthKey)??null,g=d.get(CapabilitiesKey),_=d.get(ChannelInstrumentationKey),v=d.get(InitiatorAuthKey)??null,y=e.parentWritable.getWriter(),b=buildAdapterContext(m,d),x=p,S=[];try{for(let r of u.actions){let i,a,o,s;switch(r.kind){case`subagent-call`:{let t=createWorkflowRuntime({compiledArtifactsSource:f.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:n,runInput:o}=buildSubagentRunInput({action:r,auth:h,batchEvent:u.event,capabilities:g,channelMetadata:_,initiatorAuth:v,parentContinuationToken:e.parentContinuationToken,session:p}),c=await t.run(o);x=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:n,session:x}),i=c.sessionId,a=r.name,s=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:f.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,remote:n,session:p})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),S.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},s=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let l=await callAdapterEventHandler(m,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:u.event.sequence,sessionId:p.sessionId,toolName:s,turnId:u.event.turnId,workflowId:workflowEntryReference.workflowId}),b);await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(l)))}}finally{y.releaseLock()}return{results:S,sessionState:x===p?e.sessionState:createDurableSessionState({session:x})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),f=getPendingRuntimeActionBatch(s.state);if(f===void 0||f.actions.length===0)return{results:[],sessionState:e.sessionState};let p=await deserializeContext(e.serializedContext),m=p.require(BundleKey),h=hydrateDurableSession({compactionOverrides:{thresholdPercent:m.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:m.turnAgent}),g=p.require(ChannelKey),_=p.get(AuthKey)??null,v=p.get(CapabilitiesKey),y=p.get(ChannelInstrumentationKey),b=p.get(InitiatorAuthKey)??null,x=e.parentWritable.getWriter(),S=buildAdapterContext(g,p),C=h,w=[];try{for(let r of f.actions){let i,a,o,s;switch(r.kind){case`subagent-call`:{let t=m.subagentRegistry.subagentsByNodeId.get(r.nodeId),n=t?.definition.kind===`subagent`?{description:t.definition.description,type:`local`}:{type:`runtime`},o=createWorkflowRuntime({compiledArtifactsSource:m.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:c,runInput:l}=buildSubagentRunInput({action:r,auth:_,batchEvent:f.event,capabilities:v,channelMetadata:y,initiatorAuth:b,parentContinuationToken:e.parentContinuationToken,session:h,source:n}),u=await o.run(l);C=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:c,session:C}),i=u.sessionId,a=r.name,s=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:m.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,remote:n,session:h})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),w.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},s=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let d=await callAdapterEventHandler(g,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:f.event.sequence,sessionId:h.sessionId,toolName:s,turnId:f.event.turnId,workflowId:workflowEntryReference.workflowId}),S);await x.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(d)))}}finally{x.releaseLock()}return{results:w,sessionState:C===h?e.sessionState:createDurableSessionState({session:C})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
@@ -1 +1 @@
1
- import{createEveCallbackRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{formatSubagentInvocation}from"#execution/subagent-invocation.js";async function startRemoteAgentSession(n){let r=n.callbackToken??n.session.continuationToken;if(!r)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!n.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let i=await resolveRemoteAgentRequestHeaders(n.remote),a=await fetch(createRemoteAgentSessionUrl(n.remote),{body:JSON.stringify({callback:{callId:n.action.callId,subagentName:n.action.remoteAgentName,token:r,url:createWorkflowCallbackUrl(n.callbackBaseUrl,createEveCallbackRoutePath(r))},message:formatRemoteAgentCallInputMessage(n.action),mode:`task`,outputSchema:n.action.input.outputSchema??n.remote.outputSchema}),headers:{"content-type":`application/json`,...i},method:`POST`});if(!a.ok)throw Error(`Remote agent "${n.action.remoteAgentName}" create-session request failed with HTTP ${a.status}.`);let o=a.headers.get(EVE_SESSION_ID_HEADER);if(o!==null&&o.length>0)return o;try{let e=await a.json();if(typeof e.sessionId==`string`&&e.sessionId.length>0)return e.sessionId}catch{}throw Error(`Remote agent "${n.action.remoteAgentName}" create-session response did not include a session id.`)}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function createRemoteAgentSessionUrl(e){return new URL(e.path,`${trimTrailingSlash(e.url)}/`).toString()}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.input.message==`string`?e.input.message:``;return formatSubagentInvocation({description:e.description,message:t,name:e.remoteAgentName}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{resolveRemoteAgentForAction,startRemoteAgentSession};
1
+ import{createEveCallbackRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";async function startRemoteAgentSession(n){let r=n.callbackToken??n.session.continuationToken;if(!r)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!n.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let i=await resolveRemoteAgentRequestHeaders(n.remote),a=await fetch(createRemoteAgentSessionUrl(n.remote),{body:JSON.stringify({callback:{callId:n.action.callId,subagentName:n.action.remoteAgentName,token:r,url:createWorkflowCallbackUrl(n.callbackBaseUrl,createEveCallbackRoutePath(r))},message:formatRemoteAgentCallInputMessage({action:n.action,remote:n.remote}),mode:`task`,outputSchema:n.action.input.outputSchema??n.remote.outputSchema}),headers:{"content-type":`application/json`,...i},method:`POST`});if(!a.ok)throw Error(`Remote agent "${n.action.remoteAgentName}" create-session request failed with HTTP ${a.status}.`);let o=a.headers.get(EVE_SESSION_ID_HEADER);if(o!==null&&o.length>0)return o;try{let e=await a.json();if(typeof e.sessionId==`string`&&e.sessionId.length>0)return e.sessionId}catch{}throw Error(`Remote agent "${n.action.remoteAgentName}" create-session response did not include a session id.`)}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function createRemoteAgentSessionUrl(e){return new URL(e.path,`${trimTrailingSlash(e.url)}/`).toString()}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,type:`remote`}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{resolveRemoteAgentForAction,startRemoteAgentSession};
@@ -6,11 +6,26 @@ import type { StepInput } from "#harness/types.js";
6
6
  export interface FormattedSubagentInvocation extends StepInput {
7
7
  readonly message: string;
8
8
  }
9
- /**
10
- * Formats the stable delegated input handed to one child agent invocation.
11
- */
12
- export declare function formatSubagentInvocation(input: {
9
+ type RuntimeSubagentInputFormatRequest = {
10
+ readonly message: string;
11
+ readonly name: string;
12
+ readonly type: "runtime";
13
+ };
14
+ type LocalSubagentInputFormatRequest = {
13
15
  readonly description: string;
14
16
  readonly message: string;
15
17
  readonly name: string;
16
- }): FormattedSubagentInvocation;
18
+ readonly type: "local";
19
+ };
20
+ type RemoteSubagentInputFormatRequest = {
21
+ readonly description: string;
22
+ readonly message: string;
23
+ readonly name: string;
24
+ readonly type: "remote";
25
+ };
26
+ type SubagentInputFormatRequest = RuntimeSubagentInputFormatRequest | LocalSubagentInputFormatRequest | RemoteSubagentInputFormatRequest;
27
+ /**
28
+ * Formats the stable delegated input handed to one child agent invocation.
29
+ */
30
+ export declare function formatSubagentInput(input: SubagentInputFormatRequest): FormattedSubagentInvocation;
31
+ export {};
@@ -1,2 +1,2 @@
1
- function formatSubagentInvocation(e){return{message:[`You are the subagent "${e.name}".`,`Description: ${e.description}`,``,`The caller delegated the following task to you. Complete it and return the final result directly.`,``,`Caller message:`,e.message].join(`
2
- `)}}export{formatSubagentInvocation};
1
+ const formatSubagentInputByType={runtime(e){return formatSubagentPrompt({descriptionLines:[],message:e.message,name:e.name})},local(e){return formatSubagentPrompt({descriptionLines:formatDescriptionLines(e.description),message:e.message,name:e.name})},remote(e){return formatSubagentPrompt({descriptionLines:formatDescriptionLines(e.description),message:e.message,name:e.name})}};function formatSubagentInput(t){switch(t.type){case`runtime`:return formatSubagentInputByType.runtime(t);case`local`:return formatSubagentInputByType.local(t);case`remote`:return formatSubagentInputByType.remote(t);default:return t}}function formatSubagentPrompt(e){return{message:[`You are the subagent "${e.name}".`,...e.descriptionLines,``,`The caller delegated the following task to you. Complete it and return the final result directly.`,``,`Caller message:`,e.message].join(`
2
+ `)}}function formatDescriptionLines(e){return e.trim().length>0?[`Description: ${e}`]:[]}export{formatSubagentInput};
@@ -8,6 +8,12 @@ interface BatchEventMetadata {
8
8
  readonly sequence: number;
9
9
  readonly turnId: string;
10
10
  }
11
+ export type SubagentInputSource = {
12
+ readonly description: string;
13
+ readonly type: "local";
14
+ } | {
15
+ readonly type: "runtime";
16
+ };
11
17
  /**
12
18
  * Result of {@link buildSubagentRunInput}.
13
19
  *
@@ -37,5 +43,6 @@ export declare function buildSubagentRunInput(input: {
37
43
  /** Hook token owned by the workflow currently waiting for this child. */
38
44
  readonly parentContinuationToken?: string;
39
45
  readonly session: HarnessSession;
46
+ readonly source: SubagentInputSource;
40
47
  }): SubagentRunInputBuild;
41
48
  export {};
@@ -1 +1 @@
1
- import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{formatSubagentInvocation}from"#execution/subagent-invocation.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l}=n,u=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),d=l.rootSessionId??l.sessionId;return{childContinuationToken:u,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:u,initiatorAuth:c,input:{message:formatSubagentCallInputMessage(r),outputSchema:r.input.outputSchema},mode:`task`,parent:{callId:r.callId,rootSessionId:d,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}}}}}function formatSubagentCallInputMessage(e){let{message:t}=e.input;return formatSubagentInvocation({description:e.description,message:t,name:e.subagentName}).message}export{buildSubagentRunInput};
1
+ import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId;return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:r.input.outputSchema},mode:`task`,parent:{callId:r.callId,rootSessionId:f,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}}}}}function formatSubagentCallInputMessage(e){let{message:t}=e.action.input;switch(e.source.type){case`local`:return formatSubagentInput({description:e.source.description,message:t,name:e.action.subagentName,type:`local`}).message;case`runtime`:return formatSubagentInput({message:t,name:e.action.subagentName,type:`runtime`}).message;default:return e.source}}export{buildSubagentRunInput};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.17.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.17.1`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -0,0 +1 @@
1
+ export declare function encodeBasicCredentials(username: string, password: string): string;
@@ -0,0 +1 @@
1
+ function encodeBasicCredentials(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{encodeBasicCredentials};
@@ -1,18 +1,22 @@
1
1
  import type { ClientOptions } from "#client/index.js";
2
2
  import type { DevelopmentCredentialGate } from "./credential-gate.js";
3
+ type DevelopmentClientHeaders = Readonly<Record<string, string>>;
3
4
  /**
4
5
  * Builds anonymous {@link ClientOptions} for a development target. Locality is
5
6
  * not an authorization decision, so remote URLs receive no ambient Vercel
6
7
  * credentials through this default path.
7
8
  */
8
9
  export declare function resolveDevelopmentClientOptions(serverUrl: string): ClientOptions;
9
- /** Builds a non-redirecting local client with an explicit per-request bearer source. */
10
+ /** Builds a non-redirecting local client, using ambient bearer auth only when it owns Authorization. */
10
11
  export declare function resolveLocalDevelopmentClientOptions(input: {
12
+ readonly headers?: DevelopmentClientHeaders;
11
13
  readonly serverUrl: string;
12
14
  readonly token: () => Promise<string>;
13
15
  }): ClientOptions;
14
16
  /** Builds non-redirecting client options backed by one verified credential gate. */
15
17
  export declare function resolveRemoteDevelopmentClientOptions(input: {
16
18
  readonly credentials: DevelopmentCredentialGate;
19
+ readonly headers?: DevelopmentClientHeaders;
17
20
  readonly serverUrl: string;
18
21
  }): ClientOptions;
22
+ export {};
@@ -1 +1 @@
1
- function resolveDevelopmentClientOptions(e){return{host:e}}function resolveLocalDevelopmentClientOptions(e){return{auth:{bearer:e.token},host:e.serverUrl,redirect:`manual`}}function resolveRemoteDevelopmentClientOptions(e){let t=new URL(e.serverUrl).origin;if(e.credentials.serverOrigin!==t)throw Error(`Credential gate origin ${e.credentials.serverOrigin} does not match client origin ${t}.`);return{auth:{vercelOidc:{token:()=>e.credentials.resolveToken()}},headers:e.credentials.resolveBypassHeaders,host:e.serverUrl,redirect:`manual`}}export{resolveDevelopmentClientOptions,resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions};
1
+ import{VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER}from"#client/types.js";function hasAuthorizationHeader(e){return e!==void 0&&Object.keys(e).some(e=>e.toLowerCase()===`authorization`)}async function resolveRemoteHeaders(t){if(!t.includeTrustedOidcHeader)return{...await t.credentials.resolveBypassHeaders(),...t.headers};let[n,r]=await Promise.all([t.credentials.resolveBypassHeaders(),t.credentials.resolveToken()]),i={...n,...t.headers},a=r.trim();return a.length>0&&(i[VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER]=a),i}function resolveDevelopmentClientOptions(e){return{host:e}}function resolveLocalDevelopmentClientOptions(e){let t={host:e.serverUrl,redirect:`manual`};if(hasAuthorizationHeader(e.headers))return{...t,headers:e.headers};let n={...t,auth:{bearer:e.token}};return e.headers===void 0?n:{...n,headers:e.headers}}function resolveRemoteDevelopmentClientOptions(e){let t=new URL(e.serverUrl).origin;if(e.credentials.serverOrigin!==t)throw Error(`Credential gate origin ${e.credentials.serverOrigin} does not match client origin ${t}.`);return hasAuthorizationHeader(e.headers)?{headers:()=>resolveRemoteHeaders({credentials:e.credentials,headers:e.headers,includeTrustedOidcHeader:!0}),host:e.serverUrl,redirect:`manual`}:{auth:{vercelOidc:{token:()=>e.credentials.resolveToken()}},headers:e.headers===void 0?e.credentials.resolveBypassHeaders:()=>resolveRemoteHeaders({credentials:e.credentials,headers:e.headers,includeTrustedOidcHeader:!1}),host:e.serverUrl,redirect:`manual`}}export{resolveDevelopmentClientOptions,resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.17.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.17.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -1,3 +1,3 @@
1
- import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-BEOUv37s.js";
1
+ import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-Bh1NmXO9.js";
2
2
 
3
3
  export { defaultMessageReducer, useEveAgent };
@@ -1,3 +1,3 @@
1
- import { t as useEveAgent } from "../chunks/use-eve-agent-BEOUv37s.js";
1
+ import { t as useEveAgent } from "../chunks/use-eve-agent-Bh1NmXO9.js";
2
2
 
3
3
  export { useEveAgent };
@@ -1,3 +1,3 @@
1
- import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-C25KOe9i.js";
1
+ import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-Dvy_Wjvq.js";
2
2
 
3
3
  export { defaultMessageReducer, useEveAgent };
@@ -1,3 +1,3 @@
1
- import { t as useEveAgent } from "../chunks/use-eve-agent-C25KOe9i.js";
1
+ import { t as useEveAgent } from "../chunks/use-eve-agent-Dvy_Wjvq.js";
2
2
 
3
3
  export { useEveAgent };
@@ -128,7 +128,13 @@ Pass a URL and the TUI talks to a running deployment instead of starting a local
128
128
  eve dev https://<your-app>
129
129
  ```
130
130
 
131
- The bare URL is shorthand for `--url`; it cannot be combined with `--host`, `--port`, or `--no-ui`.
131
+ The bare URL is shorthand for `--url`; it cannot be combined with `--host`, `--port`, or `--no-ui`. For HTTP Basic auth, put credentials in the URL; eve sends them as a Basic `Authorization` header and strips them from the server URL before connecting:
132
+
133
+ ```bash
134
+ eve dev https://user:pass@<your-app>
135
+ ```
136
+
137
+ For bearer tokens or custom schemes, repeat `-H, --header` to attach request headers.
132
138
 
133
139
  At startup the TUI asks Vercel to resolve the remote origin under the active scope. A resolved response is the authority for a project-scoped OIDC token—refreshing an expired development token when refresh credentials exist—or an automation-bypass secret. An unresolved host is probed anonymously. The TUI then requests `/eve/v1/info`, with a ten-second timeout. A successful response marks the remote ready. An eve OIDC challenge, Vercel Deployment Protection challenge, or `TRUSTED_SOURCES_ENVIRONMENT_MISMATCH` opens `/vc:login` automatically; ordinary network failures and server errors remain remote-availability errors and do not start an authentication flow. Esc or Ctrl-C cancels the authentication flow.
134
140
 
@@ -91,13 +91,14 @@ eve dev [options]
91
91
  eve dev https://your-app.vercel.app
92
92
  ```
93
93
 
94
- Pass a bare URL as the only argument and the UI connects to that server instead of booting a local one (same as `--url`), which lets you smoke-test a preview or production deployment. The interactive UI turns off in a non-TTY terminal.
94
+ Pass a bare URL and the UI connects to that server instead of booting a local one (same as `--url`), which lets you smoke-test a preview or production deployment. The interactive UI turns off in a non-TTY terminal.
95
95
 
96
96
  | Flag | Type | Default | Description |
97
97
  | ----------------------------------- | ------ | ------------------ | ----------------------------------------------------------------------------------------- |
98
98
  | `--host <host>` | string | all interfaces | Host interface to bind |
99
99
  | `--port <port>` | number | `$PORT`, then 3000 | Port to listen on |
100
100
  | `-u, --url <url>` | string | none | Connect to an existing server URL instead of starting one |
101
+ | `-H, --header <header>` | string | none | Request header for a URL target, in `Name: value` form; repeat for multiple headers |
101
102
  | `--no-ui` | flag | UI on | Start the server without an interactive UI |
102
103
  | `--name <name>` | string | app folder name | Title shown in the terminal UI |
103
104
  | `--input <text>` | string | none | Pre-fill the prompt input; bare local `/model` starts onboarding |
@@ -111,6 +112,14 @@ Pass a bare URL as the only argument and the UI connects to that server instead
111
112
 
112
113
  A fresh `eve init` passes `--input /model`. That bare local input starts onboarding: the TUI installs the Vercel CLI if needed, asks you to log in if needed, then opens `/model`. Other input stays editable in the prompt.
113
114
 
115
+ For a URL target protected by HTTP Basic auth, put the credentials in the URL. Eve sends them as a Basic `Authorization` header and strips them from the server URL before connecting:
116
+
117
+ ```bash
118
+ eve dev https://user:pass@your-app.example.com
119
+ ```
120
+
121
+ For bearer tokens or custom schemes, pass explicit headers with `-H`.
122
+
114
123
  Local dev records the last ready URL per resolved app root in `.eve/dev-server-state.v1.json`. A second interactive `eve dev` reconnects only when that URL is loopback and healthy; each terminal UI creates a fresh client session while sharing the server process. A stale or malformed record is replaced when eve starts a new server. Passing `--host`, `--port`, or a `PORT` environment value skips reconnection and reports a healthy recorded server instead.
115
124
 
116
125
  Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions hold a consistent code revision while new prompts pick up rebuilds. On startup, `eve dev` prunes stale runtime snapshots and old local sandbox templates in the background. For manual cleanup, stop `eve dev` and delete `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eve",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "private": false,
5
5
  "description": "Filesystem-first framework for durable backend AI agents that run anywhere.",
6
6
  "keywords": [
@@ -287,11 +287,11 @@
287
287
  "@vercel/oidc": "3.5.0",
288
288
  "@vercel/sandbox": "2.2.1",
289
289
  "@vercel/sdk": "1.28.1",
290
- "@workflow/core": "5.0.0-beta.24",
290
+ "@workflow/core": "5.0.0-beta.26",
291
291
  "@workflow/errors": "5.0.0-beta.8",
292
- "@workflow/serde": "4.1.0",
293
- "@workflow/world": "5.0.0-beta.13",
294
- "@workflow/world-local": "5.0.0-beta.21",
292
+ "@workflow/serde": "5.0.0-beta.2",
293
+ "@workflow/world": "5.0.0-beta.14",
294
+ "@workflow/world-local": "5.0.0-beta.22",
295
295
  "ai": "^7.0.0",
296
296
  "autoevals": "0.0.132",
297
297
  "chat": "4.31.0",