eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
14 lines • 25.1 kB
JavaScript
import{mt as e}from"./dist-DjECvUyK.js";import{k as t,p as n}from"./dist-xTushGCp.js";import{n as r,r as i}from"./global-DFW-hO6M.js";function a(e,t){if(typeof t!=`string`)return null;let[n,r,...i]=t.split(`//`);if(n!==e||!r||i.length===0)return null;let a=i.join(`//`),o=a.split(`/`).at(-1)??``,s=``;return s=r.startsWith(`./`)?r.split(`/`).at(-1)??``:(r.split(`@`).slice(0,-1).join(`@`)||r.split(`@`)[0])?.split(`/`).at(-1)??``,[`default`,`__default`].includes(o)&&s&&(o=s),{shortName:o,moduleSpecifier:r,functionName:a}}function o(e){return a(`workflow`,e)}function s(e){return a(`step`,e)}function c(e){return p(s(e),e)}function l(e){return p(o(e),e)}function u(e){return o(e)?.shortName??f(`workflow`,e)??e}function d(e){return s(e)?.shortName??f(`step`,e)??e}function f(e,t){if(!t.startsWith(`${e}--`))return null;let n=t.split(`--`).filter(Boolean),r=n.at(-1)?.split(`-`).filter(Boolean).at(-1)??``;if([`default`,`__default`].includes(r)){let t=n.at(-2)?.split(`-`).filter(Boolean).at(-1);t&&t!==e&&(r=t)}return r||null}function p(e,t){return e?`${e.shortName} (${e.moduleSpecifier})`:t}async function m(e,n=[`encrypt`,`decrypt`]){if(e.byteLength!==32)throw new t(`Encryption key must be exactly 32 bytes, got ${e.byteLength}`);return globalThis.crypto.subtle.importKey(`raw`,e,`AES-GCM`,!1,n)}async function h(e,t,r){let i=globalThis.crypto.getRandomValues(new Uint8Array(12)),a;try{a=await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:i,tagLength:128,...r?{additionalData:r}:{}},e,t)}catch(e){throw new n(`AES-256-GCM encryption failed: ${e instanceof Error?e.message:String(e)}`,{cause:e,context:{operation:`encrypt`,byteLength:t.byteLength}})}let o=new Uint8Array(12+a.byteLength);return o.set(i,0),o.set(new Uint8Array(a),12),o}async function g(e,t,r){if(t.byteLength<28)throw new n(`Encrypted data too short: expected at least 28 bytes, got ${t.byteLength}`,{context:{operation:`decrypt`,byteLength:t.byteLength}});let i=t.subarray(0,12),a=t.subarray(12),o;try{o=await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:i,tagLength:128,...r?{additionalData:r}:{}},e,a)}catch(e){let r=e instanceof Error?e.message:String(e);throw new n(`AES-256-GCM decryption failed: ${r}`,{cause:e,context:{operation:`decrypt`,byteLength:t.byteLength}})}return new Uint8Array(o)}function _(e){let n=e.specVersion;if(!(n!=null&&n>=6&&n<=7))throw new t(`This Workflow runtime supports Worlds with spec version 6 through 7, but the configured World declares spec version ${n??`none`}. Install a World package version compatible with the current Workflow runtime.`)}const v=Symbol.for(`@workflow/world//cache`),y=Symbol.for(`@workflow/world//cachePromise`),ee=Symbol.for(`@workflow/world//getWorldFn`);async function te(){let e=globalThis;if(e[v])return _(e[v]),e[v];if(e[y])return e[v]=await e[y],_(e[v]),e[v];let t=e[ee];if(t){let e=await t();return _(e),e}throw Error("Workflow world runtime was not initialized. Import from the host workflow entrypoints (`workflow`, `workflow/api`, or `workflow/runtime`) so @workflow/core/runtime/world-init can register getWorld before getWorldLazy() is used.")}const b=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),x=new TextEncoder;function ne(e){if(e.byteLength!==32)throw new t(`Run key material must be exactly 32 bytes, got ${e.byteLength}`)}function re(e,n){if(e.byteLength!==32)throw new t(`${n} must be exactly 32 bytes, got ${e.byteLength}`)}async function S(e){ne(e);let t=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveBits`]),n=await globalThis.crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array(32),info:x.encode(`workflow/encp/x25519/v1`)},t,256),r=new Uint8Array(n);return{scalar:r,publicKey:await ie(r)}}async function ie(e){let n=await C(e,!0),r=await globalThis.crypto.subtle.exportKey(`jwk`,n);if(!r.x)throw new t(`X25519 JWK export did not include a public key component ("x")`);let i=se(r.x);if(i.byteLength!==32)throw new t(`X25519 JWK export produced a ${i.byteLength}-byte public key, expected 32`);return i}async function C(e,t){let n=new Uint8Array(b.length+e.byteLength);return n.set(b,0),n.set(e,b.length),globalThis.crypto.subtle.importKey(`pkcs8`,n,{name:`X25519`},t,[`deriveBits`])}function w(e){return globalThis.crypto.subtle.importKey(`raw`,e,{name:`X25519`},!0,[])}const T=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function ae(e){let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;t+=T[r>>2&63],t+=T[(r&3)<<4|i>>4&15],t+=n+1<e.length?T[(i&15)<<2|a>>6&3]:`=`,t+=n+2<e.length?T[a&63]:`=`}return t}function oe(e){let t=e.length;for(;t>0&&e[t-1]===`=`;)t--;let n=e.slice(0,t);if(n.includes(`=`)||n.length%4==1||t!==e.length&&e.length%4!=0)return;let r=0,i=0,a=[];for(let e=0;e<n.length;e++){let t=T.indexOf(n[e]);if(t===-1)return;r=r<<6|t,i+=6,i>=8&&(i-=8,a.push(r>>i&255))}if(!(i>0&&r&(1<<i)-1))return new Uint8Array(a)}function se(e){let n=0,r=0,i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===`=`)break;let s=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.indexOf(o);if(s===-1)throw new t(`Invalid base64url character "${o}" in X25519 JWK key component`);n=n<<6|s,r+=6,r>=8&&(r-=8,i.push(n>>r&255))}return new Uint8Array(i)}async function ce(e,t,n,r){let i=x.encode(`workflow/encp/aes256gcm/v1`),a=new Uint8Array(i.length+t.length+n.length);a.set(i,0),a.set(t,i.length),a.set(n,i.length+t.length);let o=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveBits`]),s=await globalThis.crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array(32),info:a},o,256);return globalThis.crypto.subtle.importKey(`raw`,new Uint8Array(s),`AES-GCM`,!1,r)}async function le(e){re(e,`Recipient public key`);let n;try{n=await w(e)}catch(e){throw new t(`Invalid X25519 recipient public key: ${e instanceof Error?e.message:String(e)}`,{cause:e})}let r=await globalThis.crypto.subtle.generateKey({name:`X25519`},!0,[`deriveBits`]),i=new Uint8Array(await globalThis.crypto.subtle.exportKey(`raw`,r.publicKey)),a;try{a=await globalThis.crypto.subtle.deriveBits({name:`X25519`,public:n},r.privateKey,256)}catch(e){throw new t(`X25519 key agreement failed: the recipient public key is not a valid curve point (low-order point or corrupted key material)`,{cause:e})}return{ephemeralPublicKey:i,contentKey:await ce(new Uint8Array(a),i,e,[`encrypt`])}}async function ue(e,t){if(t.byteLength!==32)throw new n(`Sealed payload has a malformed ephemeral public key: expected 32 bytes, got ${t.byteLength}`,{context:{operation:`decrypt`,byteLength:t.byteLength}});let r;try{let[n,i]=await Promise.all([C(e.scalar,!1),w(t)]);r=await globalThis.crypto.subtle.deriveBits({name:`X25519`,public:i},n,256)}catch(e){throw new n(`X25519 key agreement failed while opening a sealed payload: ${e instanceof Error?e.message:String(e)}`,{cause:e,context:{operation:`decrypt`,byteLength:t.byteLength}})}return ce(new Uint8Array(r),t,e.publicKey,[`decrypt`])}async function de(e,t,n){let{ephemeralPublicKey:r,contentKey:i}=await le(e),a=await h(i,t,n),o=new Uint8Array(r.byteLength+a.byteLength);return o.set(r,0),o.set(a,r.byteLength),o}async function fe(e,t,r){if(t.byteLength<60)throw new n(`Sealed payload too short: expected at least 60 bytes, got ${t.byteLength}`,{context:{operation:`decrypt`,byteLength:t.byteLength}});let i=t.subarray(0,32),a=t.subarray(32);return g(await ue(e,i),a,r)}function pe(e,t){let n;return{async seal(r){n??=le(e);let{ephemeralPublicKey:i,contentKey:a}=await n,o=await h(a,r,t),s=new Uint8Array(i.byteLength+o.byteLength);return s.set(i,0),s.set(o,i.byteLength),s}}}function me(e,t){let r,i;return{async open(a){if(a.byteLength<60)throw new n(`Sealed payload too short: expected at least 60 bytes, got ${a.byteLength}`,{context:{operation:`decrypt`,byteLength:a.byteLength}});let o=a.subarray(0,32),s=a.subarray(32),c=he(o);(c!==r||!i)&&(r=c,i=ue(e,o));let l;try{l=await i}catch(e){throw r=void 0,i=void 0,e}return g(l,s,t)}}}function he(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function ge(e){if(!e)return;let t=oe(e);if(t&&t.byteLength===32)return t}function E(e){return e.length===4&&/^[a-z0-9]{4}$/.test(e)}const D={DEVALUE_V1:`devl`,ENCRYPTED:`encr`,SEALED:`encp`,GZIP:`gzip`,ZSTD:`zstd`},_e=new TextEncoder,O=new TextDecoder;function k(e,t){if(!(t instanceof Uint8Array))return t;let n=_e.encode(e),r=new Uint8Array(4+t.length);return r.set(n,0),r.set(t,4),r}function A(e){if(!(e instanceof Uint8Array)||e.length<4)return null;let t=e.subarray(0,4),n=O.decode(t);return E(n)?n:null}function ve(e){return A(e)===D.ENCRYPTED}function j(e){if(!(e instanceof Uint8Array))return{format:D.DEVALUE_V1,payload:new TextEncoder().encode(JSON.stringify(e))};if(e.length<4)throw Error(`Data too short to contain format prefix: expected at least 4 bytes, got ${e.length}`);let t=e.subarray(0,4),n=O.decode(t);if(!E(n))throw Error(`Invalid format prefix: "${n}". Must be 4 characters of [a-z0-9].`);return{format:n,payload:e.subarray(4)}}const M=Symbol.for(`workflow.serialization.sealTarget`),N=Symbol.for(`workflow.serialization.runKeys`);function ye(e,t){return{[M]:!0,recipientPublicKey:e,aad:t}}function P(e,t,n){return{[N]:!0,aes:e,keyPair:t,aad:n}}async function be(e){let[t,n]=await Promise.all([m(e),S(e)]);return P(t,n)}function F(e){return typeof e==`object`&&!!e&&e[M]===!0}function I(e){return typeof e==`object`&&!!e&&e[N]===!0}function L(e){if(e){if(I(e))return e.aes;if(!F(e))return e}}async function xe(e){return typeof e==`function`?e():e}async function Se(e,t){if(!t||!(e instanceof Uint8Array))return e;if(F(t)){let n=await de(t.recipientPublicKey,e,t.aad);return k(D.SEALED,n)}let n=await h(I(t)?t.aes:t,e);return k(D.ENCRYPTED,n)}async function Ce(e,t){if(!I(t))throw new n(`Sealed data encountered but no run keypair is available. Opening a sealed payload requires the run's own encryption key material; a symmetric key or a seal-only target cannot decrypt it.`,{context:{operation:`decrypt`,byteLength:e.byteLength,formatPrefix:`encp`}});let{payload:r}=j(e);try{return await fe(t.keyPair,r,t.aad)}catch(e){throw n.is(e)&&e.context&&(e.context.formatPrefix=D.SEALED),e}}async function we(e,t){if(!(e instanceof Uint8Array))return e;let r=A(e);if(r===D.SEALED)return Ce(e,t);if(r!==D.ENCRYPTED)return e;let i=L(t);if(!i)throw new n(`Encrypted data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.`,{context:{operation:`decrypt`,byteLength:e.byteLength,formatPrefix:`encr`}});let{payload:a}=j(e);try{return await g(i,a)}catch(e){throw n.is(e)&&e.context&&(e.context.formatPrefix=r),e}}const Te=(()=>{let e=globalThis.process;return e?.env?e.env.FORCE_COLOR&&e.env.FORCE_COLOR!==`0`?!0:!e.env.NO_COLOR&&!!e.stdout?.isTTY:!1})(),R=(e,t)=>n=>Te?`\x1b[${e}m${n}\x1b[${t}m`:n,z={bold:R(1,22),dim:R(2,22),italic:R(3,23),red:R(31,39),blue:R(34,39),cyan:R(36,39),yellow:R(33,39),magenta:R(35,39)},B={info:z.blue,help:z.cyan,warn:z.yellow,error:z.red};function Ee(e){let t=Array.isArray(e)?e.join(`
`):e;return B.info(`${z.bold(`hint:`)} ${t}`)}function De(e){return B.info(`${z.bold(`docs:`)} ${e}`)}function Oe(e){return z.italic(`${z.dim("`")}${e}${z.dim("`")}`)}function V(e){return z.dim(e)}function ke(e){return z.bold(e)}function Ae(e){return z.red(e)}function je(e){return z.magenta(e)}function Me(e,t){let n=[e];return t.forEach((e,r)=>{let i=e.split(`
`),a=r===t.length-1,o=a?`╰▶ `:`├▶ `,s=a?` `:`│ `,c=i.map((e,t)=>`${t===0?o:s}${e}`);n.push(...c)}),n.join(`
`)}function Ne(e,t,n){let[r,...i]=t.split(`
`),a=i.join(`
`),o=a.trim()?a:H(n??{},`errorStack`)??``,s=Pe(r??``,o,n),c=Fe(o),l=[`${e} ${r??``}`];return s&&l.push(s),c&&l.push(c),l.join(`
`)}function Pe(e,t,n){if(!n||Object.keys(n).length===0)return null;let r=new Set;r.add(`errorStack`);let i=H(n,`errorMessage`);i&&(e.includes(i)||t.includes(i))&&r.add(`errorMessage`);let a=new Set([`workflowRunId`,`workflowName`,`stepId`,`stepName`,`errorAttribution`,`errorCode`,`errorName`,`errorMessage`,`errorStack`,`errorCause`,`hint`,`attempt`,`retryCount`]),o=[],s=H(n,`errorName`),u=H(n,`errorAttribution`),d=s!==null&&Le(t,s);if(u||s&&!d){let e=u?u===`sdk`?je(`sdk error`):Ae(`user error`):``,t=s?ke(s):``,n=e&&t?V(` · `):``;o.push(` ${e}${n}${t}`)}let f=H(n,`workflowRunId`),p=H(n,`workflowName`);f?o.push(W(`run`,f,p,l)):p&&o.push(W(`run`,null,p,l));let m=H(n,`stepId`),h=H(n,`stepName`);if((m||h)&&o.push(W(`step`,m,h,c)),n.attempt!==void 0||n.retryCount!==void 0){let e=n.attempt,t=n.retryCount;e!==void 0&&t!==void 0?o.push(` ${U(`retry`)} ${e} ${V(`attempts ·`)} ${t} ${V(`max retries`)}`):e!==void 0&&o.push(` ${U(`retry`)} ${e} ${V(`attempts`)}`)}let g=H(n,`errorCode`);g&&g!==s&&o.push(` ${U(`code`)} ${V(g)}`),i&&!r.has(`errorMessage`)&&o.push(` ${U(`error`)} ${G(i)}`);let _=H(n,`errorCause`);_&&!t.includes(_)&&o.push(` ${U(`cause`)} ${G(_)}`);let v=H(n,`hint`);v&&o.push(` ${Ee(v)}`);let y=Object.entries(n).filter(([e,t])=>!a.has(e)&&!r.has(e)&&t!=null).sort(([e],[t])=>e.localeCompare(t));for(let[e,t]of y)o.push(` ${U(e)} ${G(t)}`);return o.length?o.join(`
`):null}function Fe(e){if(!e)return null;let t=e.split(`
`),n=[],r=0,i=0,a=0,o=()=>{r>0&&(n.push(V(` … ${r} more ${r===1?`frame`:`frames`} in framework internals`)),r=0)};for(let e of t){let t=e.trimStart().startsWith(`at `);if(t&&Ie(e)){r++;continue}if(t&&i>=6){a++;continue}o(),n.push(e),t&&i++}return o(),a>0&&n.push(V(` … ${a} more ${a===1?`frame`:`frames`} (run \`pnpm wf inspect run <id>\` for the full stack)`)),n.join(`
`)}function Ie(e){let t=e.trimStart();return t.startsWith(`at `)?!!(t.includes(`node:internal/`)||t.includes(`node_modules/.pnpm/`)||t.includes(`node_modules__pnpm_`)||t.includes(`_next_dist_`)||t.includes(`node_modules/next/`)||t.includes(`node_modules/@opentelemetry/`)||t.includes(`node_modules/vitest/`)||t.includes(`node_modules/@vitest/`)):!1}function Le(e,t){let n=e.split(`
`,1)[0]?.trim()??``;return n===t||n.startsWith(`${t}:`)}function H(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function U(e){return V(e.padEnd(6))}function W(e,t,n,r){let i=t||V(`—`),a=n&&(e===`run`?o(n):s(n))?`${V(`·`)} ${r(n)}`:``;return` ${U(e)} ${i}${a?` `+a:``}`}function G(e){if(typeof e==`string`)return e.includes(`
`)?e.split(`
`).map((e,t)=>t===0?e:` ${e}`).join(`
`):e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function K(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Re=K(`workflow.name`),ze=K(`workflow.operation`),Be=K(`workflow.run.id`),Ve=K(`workflow.run.status`),He=K(`workflow.started_at`),Ue=K(`workflow.events.count`),We=K(`workflow.execution.mode`),Ge=K(`workflow.bundle.compile.cache_hit`),Ke=K(`workflow.replay.load.source`),qe=K(`workflow.events.parked.count`),Je=K(`workflow.events.parked.event_id`),Ye=K(`workflow.events.parked.event_type`),Xe=K(`workflow.arguments.count`),Ze=K(`workflow.result.type`),Qe=K(`workflow.trace.propagated`),$e=K(`workflow.trace.mode`),et=K(`workflow.turbo`),tt=K(`workflow.error.name`),nt=K(`workflow.error.message`),rt=K(`workflow.error.code`),it=K(`workflow.steps.created`),at=K(`workflow.hooks.created`),ot=K(`workflow.waits.created`),st=K(`workflow.steps.failed_serialization`),ct=K(`workflow.inline_ownership.owned_recovery_steps`),lt=K(`workflow.inline_ownership.backstop_wakes_armed`),ut=K(`workflow.dispatch.republish_skipped`),dt=K(`workflow.route.type`),ft=K(`workflow.route.handler_cached`),pt=K(`workflow.route.invocation_count`),mt=K(`workflow.route.entrypoint_age_ms`),ht=K(`workflow.route.module_body_init_ms`),gt=K(`faas.instance`),_t=K(`step.name`),vt=K(`step.id`),yt=K(`step.attempt`),bt=K(`step.status`),xt=K(`step.max_retries`),St=K(`step.ttfs_ms`),Ct=K(`step.stso_ms`),wt=K(`step.rsfs_ms`),Tt=K(`step.final_scheduling_replay_ms`),Et=K(`step.latency_optimizations`),Dt=K(`workflow.step_start.strategy`),Ot=K(`step.skipped`),kt=K(`step.skip_reason`),At=K(`step.arguments.count`),jt=K(`step.result.type`),Mt=K(`step.error.name`),Nt=K(`step.error.message`),Pt=K(`step.fatal_error`),Ft=K(`step.retry.exhausted`),It=K(`step.retry.timeout_seconds`),Lt=K(`step.retry.will_retry`),Rt=K(`messaging.system`),zt=K(`messaging.destination.name`),Bt=K(`messaging.message.id`),Vt=K(`messaging.operation.type`),Ht=K(`messaging.batch.message_count`),Ut=K(`workflow.queue.overhead_ms`),Wt=K(`deployment.id`),Gt=K(`workflow.deployment.pinned_id`),Kt=K(`workflow.deployment_mismatch.retry_count`),qt=K(`workflow.deployment_mismatch.recovered`),Jt=K(`workflow.hook.token`),Yt=K(`workflow.hook.id`),Xt=K(`workflow.hook.found`),Zt=K(`workflow.hook.resume_committed`),Qt=K(`workflow.hook.wake_published`),$t=K(`workflow.hook.resilient_resume_materialized`),en=K(`workflow.resume_setup_source`),tn=K(`workflow.step.resilient_dispatch_recovered`),nn=K(`workflow.step.resilient_dispatch_materialized`),rn=K(`workflow.step.dispatch_prologue`),an=K(`workflow.resume.total_ms`),on=K(`workflow.resume.phase.producer_prep_ms`),sn=K(`workflow.resume.phase.queue_delivery_ms`),cn=K(`workflow.resume.phase.resume_setup_ms`),ln=K(`workflow.resume.phase.replay_ms`),un=K(`workflow.resume.phase.step_dispatch_ms`),dn=K(`workflow.resume.phase.step_claim_ms`),fn=K(`workflow.resume.phase.step_prepare_ms`),pn=K(`workflow.resume.trigger`),mn=K(`workflow.resume.strategy`),hn=K(`workflow.resume.setup_source`),gn=K(`workflow.resume.step_execution`),_n=K(`workflow.suspension.state`),vn=K(`workflow.suspension.hook_count`),yn=K(`workflow.suspension.step_count`),bn=K(`workflow.suspension.wait_count`),xn=K(`http.request.method`),Sn=K(`http.route`),Cn=K(`http.response.status_code`),wn=K(`error.type`),Tn=K(`workflow.events.pages_loaded`),En=K(`workflow.queue.deserialize_time_ms`),Dn=K(`workflow.queue.execution_time_ms`),On=K(`workflow.queue.serialize_time_ms`),kn=K(`workflow.serialization.operation`),An=K(`workflow.serialization.compressed`),jn=K(`workflow.serialization.codec`),Mn=K(`workflow.serialization.uncompressed_bytes`),Nn=K(`workflow.serialization.stored_bytes`),Pn=K(`workflow.serialization.compression_ratio`),Fn=K(`workflow.serialization.guest_code_executions`),In=K(`workflow.serialization.guest_code_details`),Ln=K(`peer.service`),Rn=K(`rpc.system`),zn=K(`rpc.service`),Bn=K(`rpc.method`),Vn=K(`error.retryable`),Hn=K(`error.category`),Un=e(`@workflow/core//traceModeWarnings`,1,()=>({unrecognized:new Set}));function Wn(){let e=process.env.WORKFLOW_TRACE_MODE;return e===`continuous`?`continuous`:(e&&e!==`linked`&&!Un.unrecognized.has(e)&&(Un.unrecognized.add(e),$.warn(`Unrecognized WORKFLOW_TRACE_MODE value "${e}"; expected "linked" or "continuous". Falling back to "linked".`)),`linked`)}function q(e){return e!==void 0&&Object.keys(e).length>0}function Gn(e,t){return e===`linked`&&q(t)?Promise.resolve(t):qn()}async function Kn(e,t){if(e!==`linked`)return lr();let n=await ur(q(t)?t:void 0);return n?[n]:void 0}async function qn(){let e=await J.value;if(!e)return{};let t={};return e.propagation.inject(e.context.active(),t),t}async function Jn(e){let t=await J.value;if(t)return t.propagation.extract(t.context.active(),e)}async function Yn(e,t){if(!e)return t();let n=await J.value;if(!n)return t();let r=await Jn(e);return r?n.context.with(r,async()=>await t()):t()}const J=i(async()=>{try{return await import(`../../@opentelemetry/api/index.js`)}catch{return $.info(`OpenTelemetry not available, tracing will be disabled`),null}}),Y=i(async()=>{let e=await J.value;if(!e)return null;let t=e.trace.getTracer(`workflow`);return Qn(e,t),t}),Xn=i(async()=>{let e=await J.value;return e?e.metrics.getMeter(`workflow`).createHistogram(`workflow.step.execute.duration`,{description:`Duration of user step execution`,unit:`ms`}):null});let X=!1;function Zn(e){try{return typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e)}catch{return`Unknown error`}}function Qn(e,t){let n=typeof process<`u`&&typeof process.env.DEBUG==`string`&&(process.env.DEBUG.includes(`workflow:`)||process.env.DEBUG===`*`);if(!X&&n){X=!0;try{let n=globalThis[Symbol.for(`opentelemetry.js.api.1`)],r=e.trace.getTracerProvider(),i=r.getDelegate?.()??r,a=t.startSpan(`workflow.otel.probe.core`);console.warn(`[workflow:otel-diag] core`,JSON.stringify({globalRegistrationVersion:n?.version??null,providerCtor:r?.constructor?.name??null,delegateCtor:i?.constructor?.name??null,tracerCtor:t?.constructor?.name??null,probeCtor:a?.constructor?.name??null,probeRecording:a.isRecording()})),a.end()}catch(e){console.warn(`[workflow:otel-diag] core failed:`,e instanceof Error?e.message:e)}}}async function $n(e,...t){let[n,i]=await Promise.all([Y.value,J.value]),{fn:a,opts:o}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!a)throw Error(`Function to trace must be provided`);return!n||!i?await a():n.startActiveSpan(e,o,async e=>{try{let t=await a(e);return e.setStatus({code:i.SpanStatusCode.OK}),t}catch(t){throw r.is(t)?(e.setStatus({code:i.SpanStatusCode.OK}),ar(t,e)):e.setStatus({code:i.SpanStatusCode.ERROR,message:Zn(t)}),t}finally{e.end()}})}async function er(e){let[t,n]=await Promise.all([Y.value,J.value]);if(!t||!n)return{end(){},fail(){}};let r=t.startSpan(e),i=!1,a=e=>{i||(i=!0,r.setStatus(e),r.end())};return{end:()=>a({code:n.SpanStatusCode.OK}),fail:e=>a({code:n.SpanStatusCode.ERROR,message:Zn(e)})}}async function tr(e){let t=await J.value;return t?t.context.bind(t.context.active(),e):e}async function nr(){let e=await J.value;if(!e)return{refresh(){},run:e=>e()};let t=e.context.active(),n={getValue:e=>t.getValue(e),setValue:(e,n)=>t.setValue(e,n),deleteValue:e=>t.deleteValue(e)};return{refresh:()=>{t=e.context.active()},run:t=>e.context.with(n,t)}}async function rr(e,t,n){let r=await Y.value;r&&r.startSpan(e,{...n,startTime:t}).end()}async function ir(e,t){(await Xn.value)?.record(e,{"workflow.step.status":t})}function ar(e,t){t.setAttributes({..._n(`suspended`),...yn(e.stepCount),...vn(e.hookCount),...bn(e.waitCount)})}async function or(e){let[t,n]=await Promise.all([Jn(e),J.value]);if(t&&n)return n.trace.getSpanContext(t)}async function sr(){return await Z(e=>e.trace.getActiveSpan())}async function cr(e){return Z(t=>t.SpanKind[e])}async function Z(e){let t=await J.value;if(t)return await e(t)}function lr(){return Z(e=>{let t=e.trace.getActiveSpan()?.spanContext();if(t)return[{context:t}]})}async function ur(e){if(!e)return;let[t,n]=await Promise.all([or(e),J.value]);if(t&&n&&n.trace.isSpanContextValid(t))return{context:t}}async function dr(e,t){let n=await J.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 fr(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 Q(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)(Ne(`[workflow-sdk]`,i,c)),fr(n,process.env.DEBUG)&&(console.debug(`[${n}] ${i}`,c??``),sr().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 pr=Q(`step`),$=Q(`runtime`),mr=Q(`webhook`),hr=Q(`events`);Q(`adapter`),Q(`build`,{debugNamespace:`workflow:build`});export{un as $,Re as $t,Zt as A,I as An,Ft as At,Vt as B,E as Bn,Xe as Bt,Hn as C,V as Cn,vt as Ct,Xt as D,we as Dn,nn as Dt,gt as E,L as En,_t as Et,Cn as F,j as Fn,Ot as Ft,Ut as G,S as Gn,ut as Gt,Ln as H,me as Hn,Ge as Ht,Sn as I,k as In,Dt as It,sn as J,m as Jn,tt as Jt,On as K,te as Kn,rt as Kt,Ht as L,ve as Ln,bt as Lt,Jt as M,xe as Mn,Lt as Mt,Qt as N,P as Nn,wt as Nt,Yt as O,be as On,tn as Ot,xn as P,ye as Pn,kt as Pt,dn as Q,at as Qt,zt as R,A as Rn,Ct as Rt,Wt as S,Oe as Sn,Tt as St,wn as T,Me as Tn,xt as Tt,En as U,pe as Un,qt as Ut,Rt as V,ae as Vn,lt as Vt,Dn as W,ge as Wn,Kt as Wt,cn as X,d as Xn,Tn as Xt,ln as Y,o as Yn,Ue as Yt,hn as Z,u as Zn,We as Zt,qn as _,st as _n,yt as _t,ar as a,Ke as an,Bn as at,Yn as b,et as bn,Mt as bt,nr as c,ft as cn,jn as ct,cr as d,dt as dn,In as dt,ze as en,gn as et,Wn as f,Be as fn,Fn as ft,ir as g,it as gn,At as gt,rr as h,He as hn,Mn as ht,mr as i,qe as in,pn as it,en as j,F as jn,It as jt,$t as k,Se as kn,jt as kt,sr as l,pt as ln,An as lt,ur as m,Ve as mn,Nn as mt,$ as n,Je as nn,mn as nt,tr as o,Ze as on,zn as ot,q as p,Gt as pn,kn as pt,on as q,_ as qn,nt as qt,pr as r,Ye as rn,an as rt,Kn as s,mt as sn,Rn as st,hr as t,ct as tn,fn as tt,Gn as u,ht as un,Pn as ut,er as v,$e as vn,rn as vt,Vn as w,De as wn,Et as wt,dr as x,ot as xn,Pt as xt,$n as y,Qe as yn,Nt as yt,Bt as z,D as zn,St as zt};