eve 0.51.0 → 0.52.0
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.
- package/CHANGELOG.md +46 -0
- package/dist/src/channel/session.d.ts +2 -1
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +4 -1
- package/dist/src/chunks/{use-eve-agent-C3vUG5g2.js → use-eve-agent-3DZuvuWE.js} +17 -6
- package/dist/src/chunks/{use-eve-agent-B4xN7-fK.js → use-eve-agent-D7apPojZ.js} +17 -6
- package/dist/src/cli/agent-command.js +1 -1
- package/dist/src/cli/commands/agent-instructions.d.ts +3 -1
- package/dist/src/cli/commands/agent-instructions.js +1 -1
- package/dist/src/cli/commands/build.js +1 -1
- package/dist/src/cli/commands/deploy.js +1 -1
- package/dist/src/cli/commands/init-agent-workspace.js +1 -1
- package/dist/src/cli/commands/init-repl.js +1 -1
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/link.js +1 -1
- package/dist/src/cli/commands/preconditions.js +1 -1
- package/dist/src/cli/commands/register-project-commands.d.ts +1 -1
- package/dist/src/cli/commands/register-project-commands.js +1 -1
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/dev/boot-progress.d.ts +3 -0
- package/dist/src/cli/dev/boot-progress.js +1 -0
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +3 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/run.d.ts +4 -0
- package/dist/src/cli/run.js +3 -3
- package/dist/src/cli/telemetry/command.d.ts +9 -0
- package/dist/src/cli/telemetry/command.js +1 -0
- package/dist/src/cli/telemetry/flush.d.ts +2 -0
- package/dist/src/cli/telemetry/flush.js +1 -0
- package/dist/src/cli/telemetry/identity.d.ts +13 -0
- package/dist/src/cli/telemetry/identity.js +1 -0
- package/dist/src/cli/telemetry/index.d.ts +25 -0
- package/dist/src/cli/telemetry/index.js +3 -0
- package/dist/src/cli/telemetry/preference.d.ts +9 -0
- package/dist/src/cli/telemetry/preference.js +1 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-controls.d.ts +3 -0
- package/dist/src/client/session-controls.js +1 -1
- package/dist/src/client/session.d.ts +4 -1
- package/dist/src/client/types.d.ts +3 -2
- package/dist/src/compiled/.vendor-stamp.json +11 -11
- package/dist/src/compiled/@clack/core/LICENSE +9 -0
- package/dist/src/compiled/@clack/core/index.d.ts +363 -0
- package/dist/src/compiled/@clack/core/index.js +20 -0
- package/dist/src/compiled/@eve/catalog/index.js +1 -1
- package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +1 -0
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +34 -92
- package/dist/src/compiled/@vercel/sandbox/api-client/base-client.d.ts +1 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/index.d.ts +1 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +13 -29
- package/dist/src/compiled/@vercel/sandbox/constants.d.ts +11 -1
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -3
- package/dist/src/compiled/@vercel/sandbox/index.js +9 -9
- package/dist/src/compiled/@vercel/sandbox/sandbox-user.d.ts +5 -6
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +79 -67
- package/dist/src/compiled/@vercel/sandbox/session.d.ts +5 -3
- package/dist/src/compiled/@vercel/sandbox/snapshot.d.ts +9 -0
- package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/api-client.d.ts +86 -1
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/index.d.ts +2 -0
- package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/validators.d.ts +26 -1
- package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/constants.d.ts +2 -2
- package/dist/src/compiled/@vercel/{sandbox → sandbox-drives}/drive.d.ts +10 -0
- package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/index.d.ts +3 -2
- package/dist/src/compiled/@vercel/sandbox-drives/index.js +9 -0
- package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/sandbox.d.ts +35 -6
- package/dist/src/compiled/@workflow/core/index.js +1 -1
- package/dist/src/compiled/@workflow/core/private.d.ts +2 -4
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +9 -7
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +13 -0
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +54 -1
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/serialization/types.d.ts +7 -0
- package/dist/src/compiled/@workflow/core/serialization.d.ts +24 -2
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
- package/dist/src/compiled/@workflow/errors/index.d.ts +19 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/analytics.d.ts +46 -2
- package/dist/src/compiled/@workflow/world/events.d.ts +26 -1
- package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/world/runs.d.ts +2 -2
- package/dist/src/compiled/@workflow/world-local/index.js +3 -3
- package/dist/src/compiled/@workflow/world-vercel/index.js +12 -12
- package/dist/src/compiled/_chunks/node/{auth-BSKyPAEP.js → auth-Bx1Aoyfo.js} +1 -1
- package/dist/src/compiled/_chunks/node/{auth-YpKlwhP1.js → auth-CA8ZMfB8.js} +1 -1
- package/dist/src/compiled/_chunks/node/esm-CE0tAvRh.js +7 -0
- package/dist/src/compiled/_chunks/node/version-BC6t2Txc.js +1 -0
- package/dist/src/compiled/_chunks/node/version-DSQqVZ5T.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-BwAadFfB.js → attribute-changes-03lzo29R.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-BIdMK5N8.js +40 -0
- package/dist/src/compiled/_chunks/workflow/dist-DMQ3CtWt.js +3 -0
- package/dist/src/compiled/_chunks/workflow/frames-Boesh7kU.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{private-CZFMABEf.js → private-CKx3PkSS.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{resume-hook-BToMtPbH.js → resume-hook-C6eL-S_T.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/run-BV0S6Zc2.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-Bh3jP9ii.js +1 -0
- package/dist/src/compiled/_chunks/workflow/wait-until-l-cwfJvm.js +15 -0
- package/dist/src/compiled/_chunks/workflow/{ws-transport-PnVVxT0R.js → ws-transport-BagXNxCE.js} +1 -1
- package/dist/src/compiler/compile-from-memory.d.ts +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +38 -20
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +2 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-channel.js +1 -1
- package/dist/src/compiler/normalize-schedule.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/discover/extensions.d.ts +2 -0
- package/dist/src/discover/extensions.js +1 -1
- package/dist/src/discover/filesystem.d.ts +1 -0
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/discover/project.js +1 -1
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/session-cleanup.d.ts +7 -0
- package/dist/src/evals/session-cleanup.js +1 -0
- package/dist/src/evals/session.d.ts +4 -0
- package/dist/src/evals/session.js +1 -1
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.d.ts +1 -0
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/activity-collector.js +1 -1
- package/dist/src/execution/activity-work.d.ts +8 -0
- package/dist/src/execution/activity-work.js +1 -1
- package/dist/src/execution/cancel-indexed-session-tasks-step.d.ts +6 -0
- package/dist/src/execution/cancel-indexed-session-tasks-step.js +1 -0
- package/dist/src/execution/continuation-conflict-step.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -2
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -1
- package/dist/src/execution/inline-turn.d.ts +4 -2
- package/dist/src/execution/inline-turn.js +1 -1
- package/dist/src/execution/next-driver-action.d.ts +0 -3
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/run-session-limits.d.ts +5 -5
- package/dist/src/execution/sandbox/bindings/vercel-create-sdk.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-sdk-types.d.ts +4 -4
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session-activity-projection.js +1 -1
- package/dist/src/execution/session-activity.js +1 -1
- package/dist/src/execution/session-timeout-workflow.js +1 -1
- package/dist/src/execution/session.d.ts +1 -0
- package/dist/src/execution/session.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/child/steps.d.ts +19 -1
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/workflow.d.ts +2 -0
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.js +1 -1
- package/dist/src/execution/tasks/parent/delegate.d.ts +2 -0
- package/dist/src/execution/tasks/parent/delegate.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/subagent-task-projection.d.ts +26 -0
- package/dist/src/execution/tasks/parent/subagent-task-projection.js +1 -0
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.d.ts +3 -0
- package/dist/src/execution/tools/sleep-workflow.js +1 -0
- package/dist/src/execution/tools/sleep.d.ts +1 -5
- package/dist/src/execution/tools/sleep.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.d.ts +1 -7
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/workflow/ask.d.ts +1 -2
- package/dist/src/execution/tools/workflow/ask.js +1 -1
- package/dist/src/execution/tools/workflow/body.d.ts +6 -1
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/cancel.js +1 -1
- package/dist/src/execution/tools/workflow/messages.d.ts +9 -8
- package/dist/src/execution/tools/workflow/messages.js +1 -1
- package/dist/src/execution/tools/workflow/owner-inbox.d.ts +2 -2
- package/dist/src/execution/tools/workflow/owner-inbox.js +1 -1
- package/dist/src/execution/tools/workflow/owner.d.ts +5 -11
- package/dist/src/execution/tools/workflow/owner.js +1 -1
- package/dist/src/execution/tools/workflow/run-control.d.ts +0 -4
- package/dist/src/execution/tools/workflow/run-control.js +1 -1
- package/dist/src/execution/tools/workflow/start.d.ts +5 -14
- package/dist/src/execution/tools/workflow/start.js +1 -1
- package/dist/src/execution/tools/workflow/workflow.d.ts +1 -1
- package/dist/src/execution/tools/workflow/workflow.js +1 -1
- package/dist/src/execution/turn-cancellation-control.d.ts +1 -0
- package/dist/src/execution/turn-cancellation-control.js +1 -1
- package/dist/src/execution/turn-cancellation-token.d.ts +1 -0
- package/dist/src/execution/turn-control-receiver.d.ts +3 -0
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +2 -0
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-workflow-tool-run.d.ts +2 -8
- package/dist/src/execution/turn-workflow-tool-run.js +1 -1
- package/dist/src/execution/turn-workflow.d.ts +1 -0
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-encoder.d.ts +10 -2
- package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v5.d.ts +341 -0
- package/dist/src/execution/wire/session-inbox-wire.v5.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v5.migration.d.ts +3 -0
- package/dist/src/execution/wire/session-inbox-wire.v5.migration.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v6.d.ts +341 -0
- package/dist/src/execution/wire/session-inbox-wire.v6.js +1 -0
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/emission-state.js +1 -1
- package/dist/src/harness/session-limit-continuation.d.ts +5 -5
- package/dist/src/harness/session-limit-continuation.js +1 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +4 -4
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/session-usage-limits.d.ts +48 -0
- package/dist/src/harness/session-usage-limits.js +1 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-client-context.d.ts +9 -0
- package/dist/src/harness/turn-client-context.js +1 -0
- package/dist/src/harness/turn-tag-state.d.ts +17 -20
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +5 -0
- package/dist/src/harness/workflow-tool-runs.d.ts +0 -1
- package/dist/src/harness/workflow-tool-runs.js +1 -1
- package/dist/src/internal/application/build-output-environment.d.ts +1 -0
- package/dist/src/internal/application/build-output-environment.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/application/paths.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/eve-project-root.d.ts +8 -0
- package/dist/src/internal/eve-project-root.js +1 -0
- package/dist/src/internal/invocation/workflow-execution.js +1 -1
- package/dist/src/internal/mcp/streamable-http-server.d.ts +29 -1
- package/dist/src/internal/mcp/streamable-http-server.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.d.ts +1 -0
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +2 -0
- package/dist/src/internal/nitro/host/vercel-build-output-config.d.ts +1 -0
- package/dist/src/internal/nitro/host/vercel-build-output-config.js +1 -1
- package/dist/src/internal/project-context.d.ts +13 -8
- package/dist/src/internal/project-context.js +1 -1
- package/dist/src/internal/vercel/build-agent-workspace.d.ts +1 -1
- package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
- package/dist/src/internal/vercel/eve-service-contribution.d.ts +1 -0
- package/dist/src/internal/vercel/eve-service-contribution.js +1 -1
- package/dist/src/internal/workflow/reference.d.ts +2 -0
- package/dist/src/internal/workflow/reference.js +1 -0
- package/dist/src/internal/workflow/runtime.d.ts +6 -0
- package/dist/src/internal/workflow/runtime.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.d.ts +1 -3
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.d.ts +1 -11
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +1 -3
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +2 -2
- package/dist/src/protocol/message.d.ts +3 -2
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/channels/slack/activity-plan.d.ts +4 -0
- package/dist/src/public/channels/slack/activity-plan.js +1 -0
- package/dist/src/public/channels/slack/activity.d.ts +45 -2
- package/dist/src/public/channels/slack/activity.js +2 -1
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/index.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/memory/index.js +1 -1
- package/dist/src/public/models/openai/chatgpt/model.js +2 -2
- package/dist/src/public/models/openai/chatgpt/transport.js +1 -1
- package/dist/src/public/nuxt/index.js +1 -1
- package/dist/src/public/nuxt/module.d.ts +3 -2
- package/dist/src/public/nuxt/module.js +1 -1
- package/dist/src/public/sandbox/vercel-sandbox.d.ts +9 -5
- package/dist/src/public/sandbox/vercel.d.ts +1 -1
- package/dist/src/public/sandbox/vercel.js +1 -1
- package/dist/src/public/tools/index.d.ts +3 -1
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/self-modification/agent.d.ts +22 -0
- package/dist/src/self-modification/agent.js +1 -0
- package/dist/src/self-modification/extension/classify-registry-item.d.ts +19 -0
- package/dist/src/self-modification/extension/classify-registry-item.js +1 -0
- package/dist/src/self-modification/extension/eve-add.d.ts +56 -0
- package/dist/src/self-modification/extension/eve-add.js +2 -0
- package/dist/src/self-modification/extension/extension.d.ts +2 -0
- package/dist/src/self-modification/extension/extension.js +1 -0
- package/dist/src/self-modification/extension/instructions.d.ts +4 -0
- package/dist/src/self-modification/extension/instructions.js +23 -0
- package/dist/src/self-modification/extension/source-lock.d.ts +2 -0
- package/dist/src/self-modification/extension/source-lock.js +1 -0
- package/dist/src/self-modification/extension/tools/edit_file.d.ts +16 -0
- package/dist/src/self-modification/extension/tools/edit_file.js +1 -0
- package/dist/src/self-modification/extension/tools/registry_add.d.ts +52 -0
- package/dist/src/self-modification/extension/tools/registry_add.js +1 -0
- package/dist/src/self-modification/extension/tools/search_models.d.ts +22 -0
- package/dist/src/self-modification/extension/tools/search_models.js +1 -0
- package/dist/src/self-modification/extension/tools/search_registry.d.ts +103 -0
- package/dist/src/self-modification/extension/tools/search_registry.js +1 -0
- package/dist/src/self-modification/filesystem.d.ts +6 -0
- package/dist/src/self-modification/filesystem.js +1 -0
- package/dist/src/self-modification/sandbox.d.ts +2 -0
- package/dist/src/self-modification/sandbox.js +1 -0
- package/dist/src/services/dev-client/target.d.ts +3 -1
- package/dist/src/setup/boxes/select-model.d.ts +3 -21
- package/dist/src/setup/boxes/select-model.js +1 -1
- package/dist/src/setup/cli/prompt-ui.js +4 -4
- package/dist/src/setup/cli/select-component.d.ts +1 -1
- package/dist/src/setup/cli/select-component.js +1 -1
- package/dist/src/setup/flows/model.d.ts +3 -0
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/update/web-options.js +1 -1
- package/dist/src/shared/action-types.d.ts +35 -22
- package/dist/src/shared/action-types.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +13 -0
- package/dist/src/shared/agent-turn-outcome.d.ts +2 -0
- package/dist/src/shared/agent-turn-outcome.js +1 -1
- package/dist/src/shared/extension-package-contract.d.ts +2 -0
- package/dist/src/shared/extension-package-contract.js +1 -1
- package/dist/src/shared/gateway-model-catalog.d.ts +21 -0
- package/dist/src/shared/gateway-model-catalog.js +1 -0
- package/dist/src/shared/sandbox-network-policy.d.ts +1 -1
- package/dist/src/shared/token-usage.d.ts +11 -15
- package/dist/src/shared/token-usage.js +1 -1
- package/dist/src/shared/workflow-tool-context.d.ts +2 -0
- package/dist/src/shared/workflow-tool-context.js +1 -0
- package/dist/src/subagents/callback-route.js +1 -1
- package/dist/src/subagents/event-proxy-step.js +1 -1
- package/dist/src/subagents/start-remote.js +1 -1
- package/dist/src/subagents/token-budget.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/types.d.ts +18 -1
- package/dist/src/tasks/types.js +1 -1
- package/dist/src/tools/behavior.d.ts +5 -0
- package/dist/src/tools/definition.d.ts +16 -12
- package/dist/src/tools/definition.js +1 -1
- package/dist/src/tools/dynamic.d.ts +2 -2
- package/dist/src/tools/provided/sleep.d.ts +4 -4
- package/dist/src/tools/provided/sleep.js +1 -1
- package/dist/src/tools/task.d.ts +28 -80
- package/dist/src/tools/task.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +60 -0
- package/dist/src/tools/workflow-definition.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +24 -19
- package/docs/channels/eve.mdx +1 -1
- package/docs/channels/mcp.mdx +25 -3
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/execution-model-and-durability.mdx +13 -2
- package/docs/concepts/sessions-runs-and-streaming.md +9 -1
- package/docs/guides/client/messages.mdx +1 -1
- package/docs/guides/client/streaming.mdx +1 -1
- package/docs/guides/deployment/vercel.mdx +3 -1
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/memory/overview.mdx +41 -12
- package/docs/reference/cli.md +31 -33
- package/docs/reference/meta.json +1 -4
- package/docs/reference/telemetry.md +56 -0
- package/docs/reference/typescript-api.md +38 -35
- package/docs/sandbox.mdx +1 -1
- package/docs/tools/overview.mdx +59 -18
- package/docs/tools/workflows.mdx +146 -70
- package/package.json +38 -19
- package/dist/src/compiled/@vercel/sandbox-delete/api-client/index.d.ts +0 -2
- package/dist/src/compiled/@vercel/sandbox-delete/index.js +0 -9
- package/dist/src/compiled/@vercel/sandbox-stable/LICENSE +0 -201
- package/dist/src/compiled/@vercel/sandbox-stable/_async-retry.d.ts +0 -8
- package/dist/src/compiled/@vercel/sandbox-stable/_workflow-serde.d.ts +0 -5
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/api-client.d.ts +0 -1456
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/api-error.d.ts +0 -29
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/base-client.d.ts +0 -39
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/file-writer.d.ts +0 -66
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/index.d.ts +0 -2
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/validators.d.ts +0 -899
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/with-retry.d.ts +0 -10
- package/dist/src/compiled/@vercel/sandbox-stable/auth/error.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-stable/auth/file.d.ts +0 -18
- package/dist/src/compiled/@vercel/sandbox-stable/auth/index.d.ts +0 -6
- package/dist/src/compiled/@vercel/sandbox-stable/auth/oauth.d.ts +0 -111
- package/dist/src/compiled/@vercel/sandbox-stable/auth/poll-for-token.d.ts +0 -28
- package/dist/src/compiled/@vercel/sandbox-stable/auth/project.d.ts +0 -40
- package/dist/src/compiled/@vercel/sandbox-stable/command.d.ts +0 -292
- package/dist/src/compiled/@vercel/sandbox-stable/constants.d.ts +0 -5
- package/dist/src/compiled/@vercel/sandbox-stable/execution-context.d.ts +0 -116
- package/dist/src/compiled/@vercel/sandbox-stable/filesystem.d.ts +0 -258
- package/dist/src/compiled/@vercel/sandbox-stable/index.d.ts +0 -12
- package/dist/src/compiled/@vercel/sandbox-stable/index.js +0 -1
- package/dist/src/compiled/@vercel/sandbox-stable/network-policy.d.ts +0 -169
- package/dist/src/compiled/@vercel/sandbox-stable/proxy.d.ts +0 -55
- package/dist/src/compiled/@vercel/sandbox-stable/sandbox-user.d.ts +0 -212
- package/dist/src/compiled/@vercel/sandbox-stable/sandbox.d.ts +0 -1216
- package/dist/src/compiled/@vercel/sandbox-stable/session.d.ts +0 -433
- package/dist/src/compiled/@vercel/sandbox-stable/snapshot.d.ts +0 -229
- package/dist/src/compiled/@vercel/sandbox-stable/utils/get-credentials.d.ts +0 -21
- package/dist/src/compiled/@vercel/sandbox-stable/utils/paginator.d.ts +0 -16
- package/dist/src/compiled/@vercel/sandbox-stable/utils/resolveSignal.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-stable/utils/sandbox-snapshot.d.ts +0 -11
- package/dist/src/compiled/@vercel/sandbox-stable/utils/types.d.ts +0 -11
- package/dist/src/compiled/_chunks/node/decode_jwt-Col8JOnf.js +0 -7
- package/dist/src/compiled/_chunks/node/version-BYHw-SDY.js +0 -1
- package/dist/src/compiled/_chunks/node/version-DH6yRy-M.js +0 -1
- package/dist/src/compiled/_chunks/workflow/dist-CgbVZs5l.js +0 -40
- package/dist/src/compiled/_chunks/workflow/dist-DjojkP5e.js +0 -3
- package/dist/src/compiled/_chunks/workflow/frames-CZ9eHShe.js +0 -3
- package/dist/src/compiled/_chunks/workflow/run-DzyAoGh4.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-3_A5uOp-.js +0 -1
- package/dist/src/compiled/_chunks/workflow/wait-until-BtySPYD0.js +0 -15
- package/dist/src/harness/session-token-limits.d.ts +0 -41
- package/dist/src/harness/session-token-limits.js +0 -1
- package/dist/src/harness/turn-sleep.d.ts +0 -12
- package/dist/src/harness/turn-sleep.js +0 -1
- package/dist/src/internal/agent-workspace.d.ts +0 -15
- package/dist/src/internal/agent-workspace.js +0 -1
- package/dist/src/node_modules/.pnpm/@clack_core@1.3.1/node_modules/@clack/core/dist/index.js +0 -16
- package/dist/src/node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js +0 -1
- package/dist/src/node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js +0 -1
- package/dist/src/node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js +0 -1
- package/dist/src/node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js +0 -5
- package/dist/src/node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js +0 -1
- package/dist/src/public/workflow/index.d.ts +0 -5
- package/dist/src/public/workflow/index.js +0 -1
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/LICENSE +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/_async-retry.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/_workflow-serde.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/api-error.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/base-client.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/file-writer.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/api-client/with-retry.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/error.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/file.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/index.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/oauth.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/poll-for-token.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/auth/project.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/command.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/execution-context.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/filesystem.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/network-policy.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/proxy.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/sandbox-user.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/session.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/snapshot.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/utils/get-credentials.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/utils/paginator.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/utils/resolveSignal.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/utils/sandbox-snapshot.d.ts +0 -0
- /package/dist/src/compiled/@vercel/{sandbox-delete → sandbox-drives}/utils/types.d.ts +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as e,i as t,t as n}from"../../_chunks/workflow/rolldown-runtime-8V8biNmG.js";import{t as r}from"../../_chunks/workflow/global-singleton-BNinwFrL.js";import{$ as i,$t as a,An as o,At as s,Bn as c,Bt as l,Cn as u,Cr as d,D as f,Dn as p,Dr as m,Dt as h,E as g,En as _,Er as v,Fn as y,Ft as b,G as x,Gn as S,Gt as C,H as ee,Hn as w,Ht as T,I as E,In as D,It as O,J as k,Jn as A,Jt as j,K as M,Kn as N,Kt as te,L as P,Ln as F,Lt as ne,Mn as I,Mr as re,Mt as ie,Nn as ae,Nr as oe,Nt as se,O as L,On as ce,Ot as R,Pn as le,Pr as ue,Pt as de,Q as z,Qt as B,R as V,Rn as H,Rt as U,Sn as fe,Sr as pe,St as me,T as he,Tn as ge,Tr as _e,U as ve,Un as ye,Ut as be,V as xe,Vn as Se,Vt as Ce,W,Wn as we,Wt as Te,X as Ee,Xn as De,Xt as Oe,Y as ke,Yn as Ae,Yt as je,Z as G,Zt as Me,_ as Ne,_n as Pe,_t as Fe,a as Ie,an as Le,at as Re,b as ze,bn as Be,c as Ve,cn as He,d as Ue,dn as We,dr as Ge,dt as Ke,en as qe,et as Je,f as Ye,fn as Xe,ft as K,g as Ze,gn as Qe,gr as $e,gt as et,h as tt,hn as nt,hr as rt,i as it,in as at,ir as ot,it as st,j as ct,jn as lt,jt as ut,k as dt,kn as ft,kt as pt,l as mt,ln as ht,lt as gt,m as _t,mn as vt,mt as yt,nn as bt,nt as xt,o as St,on as Ct,or as wt,ot as Tt,p as Et,pn as Dt,pt as Ot,q as kt,qn as At,qt as jt,r as Mt,rn as Nt,rr as Pt,rt as Ft,s as It,sn as Lt,st as Rt,t as zt,tn as Bt,tr as Vt,tt as Ht,u as Ut,un as Wt,v as Gt,vn as Kt,vt as qt,wn as Jt,wr as Yt,wt as Xt,x as Zt,xn as Qt,y as $t,yn as en,yt as tn,z as nn,zn as rn,zt as an}from"../../_chunks/workflow/wait-until-BtySPYD0.js";import{A as q,C as on,M as sn,N as cn,O as J,_ as ln,a as un,c as dn,d as Y,i as X,j as fn,k as pn,l as mn,m as hn,n as gn,o as _n,r as Z,s as vn,t as yn,u as bn,v as xn,x as Sn}from"../../_chunks/workflow/dist-DjojkP5e.js";import{a as Cn,c as wn,d as Tn,f as En,i as Dn,l as Q,n as On,s as kn,t as An,u as jn}from"../../_chunks/workflow/private-CZFMABEf.js";import{a as Mn,n as Nn}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{d as Pn,l as Fn,n as In,s as Ln,u as Rn}from"../../_chunks/workflow/attribute-changes-BwAadFfB.js";import{D as zn,O as Bn,T as Vn,X as Hn,a as Un,c as Wn,it as Gn,nt as Kn,o as qn,p as Jn,s as Yn,tt as Xn,w as Zn}from"../../_chunks/workflow/dist-CgbVZs5l.js";import{n as Qn,r as $n,t as er}from"../../_chunks/workflow/resume-hook-BToMtPbH.js";import{a as tr,c as nr,d as rr,f as ir,i as ar,l as or,m as sr,n as cr,o as lr,p as ur,r as dr,s as fr,t as pr,u as mr}from"../../_chunks/workflow/run-DzyAoGh4.js";import{t as hr}from"../../_chunks/workflow/run-id-BdE0MZz9.js";import{createRequire as gr}from"node:module";import{createHash as _r}from"node:crypto";import{types as vr}from"node:util";import yr from"node:assert/strict";import{pathToFileURL as br}from"node:url";import{Script as xr,createContext as Sr,runInContext as Cr}from"node:vm";function wr(e=process.env){return e.WORKFLOW_TARGET_WORLD||(e.VERCEL_DEPLOYMENT_ID?`vercel`:`local`)}function Tr(e){return e===`vercel`||e===`@workflow/world-vercel`}var Er=e(sn(),1);function Dr(e){return e instanceof Rn||e instanceof Fn||e instanceof Pn||e instanceof In}const Or=`The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.`;function kr(e,t){let n=t??ir(e);return hn.is(e)?{attribution:`user`,errorCode:n,hint:`A value passed across a workflow/step boundary could not be serialized. See the error message for the offending path and the Learn More link for details.`}:Dr(e)?{attribution:`user`,errorCode:n,hint:`A workflow-only or step-only API was called from the wrong context. The error message includes the exact API and how to move the call.`}:yn.is(e)?{attribution:`sdk`,errorCode:n,hint:Or}:n===q.DEPLOYMENT_MISMATCH?{attribution:`sdk`,errorCode:n,hint:`The run was delivered to a deployment other than the deployment it is pinned to, and was stopped to protect against code-skew errors after the runtime failed to re-route it there. Verify that the run's deployment is still available and that queue callbacks route to it.`}:e instanceof J?{attribution:`sdk`,errorCode:n,hint:`This is an internal workflow SDK error, not a bug in your code. If it keeps happening, please report it with the stack trace and the runId.`}:n===q.REPLAY_TIMEOUT?{attribution:`sdk`,errorCode:n,hint:'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only — step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.'}:n===q.MAX_DELIVERIES_EXCEEDED?{attribution:`sdk`,errorCode:n,hint:`The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure — check the most recent stack traces for the underlying cause.`}:n===q.MAX_EVENTS_EXCEEDED?{attribution:`user`,errorCode:n,hint:`The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function — e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.`}:n===q.CORRUPTED_EVENT_LOG?{attribution:`sdk`,errorCode:n,hint:Or}:n===q.WORLD_CONTRACT_ERROR?{attribution:`sdk`,errorCode:n,hint:`The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.`}:{attribution:`user`,errorCode:n}}function Ar(e){if(e===null)return!0;let t=typeof e;return!(t===`object`||t===`function`)}var jr=class{preparer;preparedPayloads=new Map;primitiveStepResults=new Map;encryptionKey;nextUnscannedEventIndex=0;constructor(e,t=xe){this.preparer=t,this.encryptionKey=Promise.resolve(e)}prepareEvent(e){this.prepareEventIfMissing(e)?.catch(()=>{})}async prewarm(e,t){let n=[],r=this.startPreparation(this.workflowInputKey(e.runId),e.input);r&&n.push(r);for(let e=this.nextUnscannedEventIndex;e<t.length;e++){let r=t[e],i=this.prepareEventIfMissing(r);i&&n.push(i)}this.nextUnscannedEventIndex=t.length,await Promise.allSettled(n)}resetScan(){this.nextUnscannedEventIndex=0}prepareWorkflowInput(e){return this.consumePreparation(this.workflowInputKey(e.runId),e.input)}prepareEventPayload(e,t,n){return this.consumePreparation(this.eventPayloadKey(e,t),n)}async getStepResult(e,t){if(this.primitiveStepResults.has(e))return this.primitiveStepResults.get(e);let n=await t();return Ar(n)&&this.primitiveStepResults.set(e,n),n}consumePreparation(e,t){if(!(t instanceof Uint8Array))return this.runPreparation(t);let n=this.ensurePreparation(e,t);return n.catch(()=>{this.preparedPayloads.get(e)===n&&this.preparedPayloads.delete(e)}),n}ensurePreparation(e,t){let n=this.preparedPayloads.get(e);if(n)return n;let r=this.runPreparation(t);return this.preparedPayloads.set(e,r),r}async runPreparation(e){return this.preparer(e,await this.encryptionKey)}prepareEventIfMissing(e){let t,n;switch(e.eventType){case`run_created`:return this.startPreparation(this.workflowInputKey(e.runId),e.eventData.input);case`run_started`:return this.startPreparation(this.workflowInputKey(e.runId),e.eventData?.input);case`step_completed`:t=`result`,n=e.eventData?.result;break;case`step_failed`:t=`error`,n=e.eventData?.error;break;case`hook_received`:t=`payload`,n=e.eventData?.payload;break;default:return}return this.startPreparation(this.eventPayloadKey(e.eventId,t),n)}startPreparation(e,t){if(!(!(t instanceof Uint8Array)||this.preparedPayloads.has(e)))return this.ensurePreparation(e,t)}workflowInputKey(e){return`run:${e}:input`}eventPayloadKey(e,t){return`event:${e}:${t}`}};const Mr=`cinst_${Yn()}`;function Nr(){return Bn(`WORKFLOW_MAX_QUEUE_DELIVERIES`,48,{integer:!0,min:1,max:48})}const Pr=24e4,Fr=3e4,Ir=78e4,Lr=r(`@workflow/core//envWarnings`,1,()=>({replayTimeoutValues:new Set,maxInlineStepsValues:new Set,maxEventsValues:new Set}));function Rr(e,t,n){Lr.replayTimeoutValues.has(e)||(Lr.replayTimeoutValues.add(e),G.warn(t,n))}function zr(){let e=process.env.WORKFLOW_REPLAY_TIMEOUT_MS;if(!e)return Pr;let t=Number(e);return!Number.isFinite(t)||t<=0?(Rr(e,`Ignoring WORKFLOW_REPLAY_TIMEOUT_MS: not a positive finite number; using default`,{raw:e,defaultMs:Pr}),Pr):t<3e4?(Rr(e,`WORKFLOW_REPLAY_TIMEOUT_MS below minimum; clamped`,{raw:e,clampedMs:Fr,minMs:Fr}),Fr):t>78e4?(Rr(e,`WORKFLOW_REPLAY_TIMEOUT_MS above maximum; clamped`,{raw:e,clampedMs:Ir,maxMs:Ir}),Ir):t}function Br(){return Bn(`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`,3,{integer:!0})}function Vr(){let e=process.env.WORKFLOW_MAX_INLINE_STEPS;if(!e)return 3;let t=Number(e);return!Number.isInteger(t)||t<=0?(Lr.maxInlineStepsValues.has(e)||(Lr.maxInlineStepsValues.add(e),G.warn(`Ignoring WORKFLOW_MAX_INLINE_STEPS: not a positive integer; using default`,{raw:e,defaultValue:3})),3):t<1?1:t>16?(Lr.maxInlineStepsValues.has(e)||(Lr.maxInlineStepsValues.add(e),G.warn(`WORKFLOW_MAX_INLINE_STEPS above maximum; clamped`,{raw:e,clampedValue:16,maxValue:16})),16):t}function Hr(){return process.env.WORKFLOW_RESILIENT_STEP_DISPATCH===`1`}function Ur(){let e=process.env.WORKFLOW_BATCH_TRANSITIONS;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Wr(){let e=process.env.WORKFLOW_MAX_EVENTS_OVERRIDE;if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0){Lr.maxEventsValues.has(e)||(Lr.maxEventsValues.add(e),G.warn(`Ignoring WORKFLOW_MAX_EVENTS_OVERRIDE: not a positive integer; using server limit`,{raw:e}));return}return t}function Gr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`1`||e.toLowerCase()===`true`}function Kr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`0`||e.toLowerCase()===`false`}function qr(){let e=process.env.WORKFLOW_TURBO;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Jr(){let e=process.env.WORKFLOW_RETAINED_VM;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Yr(){let e=process.env.WORKFLOW_INLINE_OWNERSHIP;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Xr(){return Bn(`WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`,860,{integer:!0,min:1,max:900})}function Zr(){return Bn(`WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`,3,{integer:!0})}function Qr(){return Bn(`WORKFLOW_PRECONDITION_MAX_INPROCESS_RESTARTS`,3,{integer:!0})}function $r(){return Bn(`WORKFLOW_PRECONDITION_MAX_REINVOCATIONS`,5,{integer:!0})}function ei(){return Bn(`WORKFLOW_PRECONDITION_REINVOKE_DELAY_SECONDS`,2,{integer:!0})}function ti(){return Bn(`WORKFLOW_DEPLOYMENT_MISMATCH_MAX_RETRIES`,3,{integer:!0,min:0})}const ni=e=>`eventData`in e&&e.eventData&&`ownerMessageId`in e.eventData&&typeof e.eventData.ownerMessageId==`string`?e.eventData.ownerMessageId:void 0;function ri(e,t,n){if(!e)return 0;let r=0,i=new Map;for(let n of e){if(n.eventType!==`step_started`||n.correlationId!==t)continue;let e=ni(n);e===void 0?r++:i.set(e,(i.get(e)??0)+1)}if(n===void 0){let e=r;for(let t of i.values())e+=t;return e}if(n.type===`ownedBy`)return i.get(n.messageId)??0;let a=0;for(let e of i.values())e>a&&(a=e);return r+a}const ii={outcome:`continue`};function ai(e,t,n){return{outcome:e,spanAttributes:{...w(t),...Qt(n),...Be(e===`rerouted`)}}}async function oi({world:e,run:t,requestId:n,retryCount:r=0,reenqueue:i,isDeploymentUnavailableError:a,beforeStop:o}){if(e.capabilities?.deploymentAffinity!==!0)return ii;let s=await e.getDeploymentId();if(t.deploymentId===s)return ii;await o?.();let c=ti(),l={workflowRunId:t.runId,pinnedDeploymentId:t.deploymentId,actualDeploymentId:s,retryCount:r,maxRetries:c},u=async(r,i)=>{let a=new Sn(t.runId,t.deploymentId,s,{recoveryAttempts:r,cause:i});try{await e.events.create(t.runId,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(a,t.runId,void 0,void 0,(t.specVersion??0)>=5),errorCode:q.DEPLOYMENT_MISMATCH}},{requestId:n})}catch(e){if(!Z.is(e)&&!Y.is(e))throw e}return ai(`failed`,t.deploymentId,r)};if(i&&r<c){let e=r+1,n=Math.min(2**r,8);try{return await i({deploymentId:t.deploymentId,specVersion:t.specVersion,deploymentMismatchRetryCount:e,delaySeconds:n}),G.warn(`Workflow run received by a deployment it is not pinned to; re-routing to its own deployment`,{...l,attempt:e,delaySeconds:n}),ai(`rerouted`,t.deploymentId,e)}catch(t){if(!a?.(t))throw t;return G.error(`Cannot re-route a misrouted workflow run to its own deployment; failing the run`,{...l,attempt:e,errorMessage:t instanceof Error?t.message:String(t)}),u(0,t)}}return G.error(r>0?`Workflow run kept arriving at a deployment it is not pinned to after re-routing; failing the run`:`Workflow run received by a deployment it is not pinned to; failing the run`,l),u(r)}function si(){throw Error(`Unsupported in eve: @workflow/core createWorld(). eve selects and wires the workflow world explicitly at build time.`)}function ci(){try{return gr(br(process.cwd()+`/package.json`).href)}catch{return gr(import.meta.url)}}const li=Symbol.for(`@workflow/world//cache`),ui=Symbol.for(`@workflow/world//stubbedCache`),di=Symbol.for(`@workflow/world//cachePromise`),fi=Symbol.for(`@workflow/world//stubbedCachePromise`),$=globalThis;function pi(e){if(typeof e.createWorld==`function`)return e.createWorld();if(typeof e.default==`function`)return e.default();if(e.default&&typeof e.default==`object`)return e.default;throw Error(`Invalid target world module: must export createWorld(), a default factory, or a default World instance.`)}function mi(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return br(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return br(process.cwd()+`/`+e).href;try{return br(ci().resolve(e)).href}catch{return e}}const hi=async()=>{let e=wr();if(Tr(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),si()}if(e===`local`)return si({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=ci()(e)}catch{t=await import(mi(e))}if(typeof t==`function`)return t();try{return await pi(t)}catch{throw Error(`Invalid target world module: ${e}, must export a createWorld function or a default function that returns a World instance.`)}},gi=async()=>{if($[ui])return Ge($[ui]),$[ui];$[fi]||($[fi]=hi().catch(e=>{throw $[fi]=void 0,e}));let e=await $[fi];return Ge(e),$[ui]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},_i=async()=>$[li]?(Ge($[li]),$[li]):($[di]||($[di]=hi().catch(e=>{throw $[di]=void 0,e})),$[li]=await $[di],Ge($[li]),$[li]),vi=e=>{$[li]=e,$[ui]=e,$[di]=void 0,$[fi]=void 0},yi=Symbol.for(`@workflow/world//getWorldFn`);globalThis[yi]??=_i;var bi=class{limitMs;elapsedMs=0;intervalStart;constructor(e=zr()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}},xi=class extends Error{name=`ReplayTimeoutRetryError`};async function Si(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a,slotSnapshot:o}=e,s=G.forRun(t,n),c=Br();if(i<=c)throw s.warn(`Workflow replay exceeded timeout; retrying delivery`,{timeoutMs:a,attempt:i,maxRetries:c}),new xi(`Workflow replay exceeded maximum duration (${a/1e3}s)`);let l=await _i(),u=kr(void 0,q.REPLAY_TIMEOUT);s.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:c,errorCode:u.errorCode,errorAttribution:u.attribution});let d=Et(l,t),f=new X(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await l.events.create(t,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(f,t,await d()),errorCode:q.REPLAY_TIMEOUT}},{requestId:r,...o})}var Ci=class{divergenceCount;active=!1;reported=!1;constructor(e){this.divergenceCount=e}static inert(){return new wi}activate(){this.active=!0}async withEventCreate(e,t){if(!this.active||this.reported)return t(e);this.reported=!0;try{return await t({...e,replayDivergenceCount:this.divergenceCount})}catch(e){throw this.reported=!1,e}}},wi=class extends Ci{constructor(){super(0)}activate(){}};function Ti(e,t){if(e&&!(!Number.isFinite(e.resumeRequestedAtMs)||!Number.isFinite(e.queuePublishRequestedAtMs)))return{trigger:`hook`,...e.strategy===`lazy`||e.strategy===`parallel`||e.strategy===`sequential`?{strategy:e.strategy}:{},resumeRequestedAtMs:e.resumeRequestedAtMs,queuePublishRequestedAtMs:e.queuePublishRequestedAtMs,consumerStartedAtMs:e.consumerStartedAtMs??NaN,...e.replayStartedAtMs===void 0?{}:{replayStartedAtMs:e.replayStartedAtMs},...e.nextStepEncounteredAtMs===void 0?{}:{nextStepEncounteredAtMs:e.nextStepEncounteredAtMs},...e.setupSource===`hook_preload`||e.setupSource===`run_started`||e.setupSource===`event_load`?{setupSource:e.setupSource}:{},stepExecution:t}}function Ei(e){if(e&&Number.isFinite(e.consumerStartedAtMs))return{resumeRequestedAtMs:e.resumeRequestedAtMs,queuePublishRequestedAtMs:e.queuePublishRequestedAtMs,...e.strategy===void 0?{}:{strategy:e.strategy},consumerStartedAtMs:e.consumerStartedAtMs,...e.replayStartedAtMs===void 0?{}:{replayStartedAtMs:e.replayStartedAtMs},...e.nextStepEncounteredAtMs===void 0?{}:{nextStepEncounteredAtMs:e.nextStepEncounteredAtMs},...e.setupSource===void 0?{}:{setupSource:e.setupSource}}}function Di(e){let t=[e.resumeRequestedAtMs,e.queuePublishRequestedAtMs,e.consumerStartedAtMs,e.replayStartedAtMs,e.nextStepEncounteredAtMs,e.stepClaimStartedAtMs,...e.stepClaimCompletedAtMs===void 0?[]:[e.stepClaimCompletedAtMs],e.stepCodeStartedAtMs];for(let e of t)if(typeof e!=`number`||!Number.isFinite(e))return;for(let e=1;e<t.length;e++)if(t[e]<t[e-1])return;return t}function Oi(e){let{tracking:t}=e;if(!t||e.attempt!==1||t.replayStartedAtMs===void 0||t.nextStepEncounteredAtMs===void 0||e.stepClaimStartedAtMs===void 0)return;let n={resumeRequestedAtMs:t.resumeRequestedAtMs,queuePublishRequestedAtMs:t.queuePublishRequestedAtMs,consumerStartedAtMs:t.consumerStartedAtMs,replayStartedAtMs:t.replayStartedAtMs,nextStepEncounteredAtMs:t.nextStepEncounteredAtMs,stepClaimStartedAtMs:e.stepClaimStartedAtMs,stepClaimCompletedAtMs:e.stepClaimCompletedAtMs,stepCodeStartedAtMs:e.stepCodeStartedAtMs};if(!Di(n))return;let{resumeRequestedAtMs:r,queuePublishRequestedAtMs:i,consumerStartedAtMs:a,replayStartedAtMs:o,nextStepEncounteredAtMs:s,stepClaimStartedAtMs:c,stepClaimCompletedAtMs:u,stepCodeStartedAtMs:d}=n;return{...jt(d-r),...ne(i-r),...U(a-i),...l(o-a),...an(s-o),...be(c-s),...u===void 0?{}:T(u-c),...C(d-(u??c)),...j(t.trigger),...t.strategy===void 0?{}:te(t.strategy),...t.setupSource===void 0?{}:Ce(t.setupSource),...Te(t.stepExecution)}}function ki(e){let t=e.startsWith(`wrun_`)?e.slice(5):e;try{return Un(hr(t).ulid)}catch{return}}function Ai(e){return vr.isNativeError(e)?e.name:`Error`}function ji(e){return vr.isNativeError(e)?e.stack??``:``}function Mi(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function Ni(e){if(!Mi(e)||X.is(e))return e;let t=new X(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function Pi(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Fi(e){if(vr.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function Ii(e){if(Pi(e))try{let t=await Ii(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await Ii(e);return{...t,message:`Promise rejection: ${t.message}`}}return Fi(e)}const Li=r(`@workflow/core//devServerPort`,1,()=>({getPort:void 0,cachedPort:void 0,inFlight:void 0}));async function Ri(){if(Li.cachedPort!==void 0)return Li.cachedPort;if(Li.inFlight)return Li.inFlight;if(!Li.getPort)try{let e=[`@workflow/utils`,`get-port`].join(`/`),t=gr(br(process.cwd()+`/package.json`).href)(e);Li.getPort=t.getPort}catch{Li.getPort=async()=>void 0}let e=Li.getPort??(async()=>void 0);return Li.inFlight=e().then(e=>(typeof e==`number`&&(Li.cachedPort=e),e)).finally(()=>{Li.inFlight=void 0}),Li.inFlight}const zi=new Set([`step_created`,`step_started`,`step_completed`,`step_failed`,`step_retrying`,`hook_received`,`wait_created`,`wait_completed`]);function Bi(e){let{events:t}=e,n=e.invocationStartedClean&&e.runCreatedAtMs!==void 0&&!e.suspensionHasWaits,r;if(n)for(let e of t){if(zi.has(e.eventType)){n=!1;break}if(e.eventType===`attr_set`){let t=+(e.occurredAt??e.createdAt);r=r===void 0?t:Math.min(r,t)}}let i,a,o,s=t[t.length-1];if(!e.suspensionHasWaits&&!e.suspensionCreatedHooks&&s&&(s.eventType===`step_completed`||s.eventType===`step_failed`)){i=+(s.occurredAt??s.createdAt);let e=new Set;for(let n of t)(n.eventType===`step_completed`||n.eventType===`step_failed`)&&n.correlationId!==void 0&&e.add(n.correlationId);a=e.size,o=t.length}let c=n&&e.runStartedReceivedAtMs!==void 0;if(!(!n&&i===void 0))return{...n?{ttfsAnchorMs:e.runCreatedAtMs,preStepBlockingMs:r===void 0?e.preStepBlockingMs:e.preStepBlockingBeforeAttrMs??0,...r===void 0?{}:{preStepAttrStartMs:r}}:{},...c?{rsfsAnchorMs:e.runStartedReceivedAtMs}:{},...i===void 0?{}:{prevStepEndMs:i,stepCount:a,eventCount:o},replayMs:e.replayMs,turbo:e.turbo,retained:e.retained}}function Vi(e){let{tracking:t}=e;if(!t||e.attempt!==1)return;let n=t.preStepAttrStartMs??e.stepCodeStartedAtMs,r=t.ttfsAnchorMs===void 0?void 0:n-t.ttfsAnchorMs-(t.preStepBlockingMs??0),i=r!==void 0&&r>=-6e4?Math.max(0,r):void 0,a=t.prevStepEndMs===void 0?void 0:e.stepCodeStartedAtMs-t.prevStepEndMs,o=a!==void 0&&a>=-6e4?Math.max(0,a):void 0,s=t.rsfsAnchorMs!==void 0&&e.stepStartPostSentAtMs!==void 0?Math.max(0,e.stepStartPostSentAtMs-t.rsfsAnchorMs):void 0,c=t.replayMs===void 0?void 0:Math.max(0,t.replayMs);if(i===void 0&&o===void 0)return;let l=[];return t.turbo&&l.push(`turbo`),e.lazyStepStart&&l.push(`lazyStepStart`),e.optimisticStart&&l.push(`optimisticStart`),e.preclaimedStart&&l.push(`preclaimedStart`),t.retained&&l.push(`retained`),{...i===void 0?{}:{ttfs:i},...o===void 0?{}:{stso:o},...o!==void 0&&t.stepCount!==void 0?{stepCount:t.stepCount}:{},...o!==void 0&&t.eventCount!==void 0?{eventCount:t.eventCount}:{},...s===void 0?{}:{rsfs:s},...c===void 0?{}:{finalSchedulingReplay:c},optimizations:l}}const Hi=`__workflowUnserializableStepInput`;function Ui(){return{args:[`[input unavailable: step argument serialization failed]`],closureVars:[],thisVal:void 0,[Hi]:!0}}function Wi(e){return typeof e==`object`&&!!e&&e[Hi]===!0}function Gi(e,t){if(t&&!(!e.events||e.cursor===void 0))return{events:e.events,cursor:e.cursor,hasMore:e.hasMore??!1}}async function Ki(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:i,stepId:o,stepName:s}=e,c=!!process.env.VERCEL_URL,l=(e.runSpecVersion??0)>=5,u=e.replayRecoveryReporter??Ci.inert(),d=e.slotSnapshot?.eventCount,f=e=>{if(d===void 0)return;let t=[];e.event&&t.push(Jn(e.event.eventId));let n=Ye(e.events??[]);n!==void 0&&t.push(n);for(let e of t)e>d&&(d=e)},p=async(e,r)=>{let i=await u.withEventCreate(d===void 0?r:{eventCount:d,...r},r=>t.events.create(n,e,r));return f(i),i},m={computeInstanceId:Mr,...e.requestId?{requestId:e.requestId}:{}};return K(`step.execute ${oe(s)}`,{},async u=>{if(u?.setAttributes({...at(s),...ce(r),...Se(n),...Bt(o)}),yr(!(e.lazyStepInput!==void 0&&e.preclaimedStart),`executeStep: lazyStepInput and preclaimedStart are mutually exclusive`),e.preclaimedStart&&e.preclaimedStart.owned===!1)return G.debug(`Pre-claimed step start lost, skipping`,{stepName:s,stepId:o,workflowRunId:n}),u?.setAttributes({...Dt(!0),...Xe(`running`)}),{type:`skipped`};let d=Et(t,n),f=On(s);if(!f||typeof f!=`function`){let t=`Step "${s}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`;if(G.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:s,stepId:o}),e.lazyStepInput!==void 0)try{e.runReadyBarrier&&await e.runReadyBarrier.catch(()=>{}),await p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},m)}catch(e){if(Z.is(e))return{type:`skipped`};if(Y.is(e))return{type:`gone`};throw e}try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(new X(t),n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...a(!0)}),{type:`failed`}}let h=f.maxRetries??3;if(u?.setAttributes({...Nt(h)}),e.authoritativeAttempt!==void 0&&e.authoritativeAttempt>h+1){let t=h,r=`Step "${s}" exceeded max retries (${t} ${cn(`retry`,`retries`,t)})`;z.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,stepId:o,attempt:e.authoritativeAttempt,maxRetries:h});try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(new X(r),n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return G.info(`Tried failing step for exceeded retries, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e instanceof Error?e.message:String(e)}),{type:`skipped`};if(Y.is(e))return{type:`gone`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}let g=e=>{if(ln.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return G.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(Y.is(e))return G.info(`Workflow run "${n}" has already completed, skipping step "${o}": ${e.message}`),{type:`gone`};if(Z.is(e))return G.debug(`Step in terminal state, skipping`,{stepName:s,stepId:o,workflowRunId:n,error:e instanceof Error?e.message:String(e)}),u?.setAttributes({...Dt(!0),...Xe(`completed`)}),{type:`skipped`};if(xn.is(e)){let t=Math.max(1,e.retryAfter??1);return G.debug(`Step retryAfter timestamp not yet reached`,{stepName:s,stepId:o,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}},_=e.preclaimedStart===void 0&&e.lazyStepInput!==void 0&&e.suppressOptimisticStart!==!0&&(Gr()||e.forceOptimisticStart===!0&&!Kr()),v,y=m,x,S,C,ee=async()=>{if(!C)return;let e=await C;if(e.ok)return;let t=g(e.err);if(!t)throw e.err;return t};if(e.preclaimedStart?.owned)v=e.preclaimedStart.step,x=e.preclaimedStart.batchPostSentAtMs,S=e.preclaimedStart.claimCompletedAtMs;else if(_){C=(e.runReadyBarrier??Promise.resolve()).then(()=>(x=Date.now(),p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},y))).then(()=>({ok:!0}),e=>({ok:!1,err:e}));let t=new Date;v={runId:n,stepId:o,stepName:s,status:`running`,input:e.lazyStepInput,attempt:1,startedAt:t,createdAt:t,updatedAt:t}}else try{let t=e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId};x=Date.now();let n=await p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:e.lazyStepInput===void 0?{stepName:s,...t}:{stepName:s,workflowName:r,input:e.lazyStepInput,...t}},y);S=Date.now(),v=n.step}catch(e){let t=g(e);if(t)return t;throw e}G.debug(`Step execution details`,{stepName:s,stepId:v.stepId,status:v.status,attempt:v.attempt}),u?.setAttributes({...vt(v.status)});let w;if(v.attempt>h+1&&v.error){let e=v.attempt-1,t=`Step "${s}" exceeded max retries (${e} ${cn(`retry`,`retries`,e)})`;z.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,retryCount:e});let r=new X(t);if(v.error!=null)try{r.cause=await P(v.error,n,await d())}catch{}try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(r,n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}let T=[],D=[],k=!0,A,j=()=>{if(!A||A.rsfs!==void 0)return;let t=e.latencyTracking?.rsfsAnchorMs;t===void 0||x===void 0||(A.rsfs=Math.max(0,x-t),u&&u.setAttributes({...We(A.rsfs)}))};try{let t=v.attempt;if(!v.startedAt)throw new J(`Step "${o}" has no "startedAt" timestamp`);let a=v.startedAt,p=e.encryptionKey??await d(),m=await K(`step.hydrate`,{},async t=>{let r=Date.now(),i=await E(v.input,n,p,D,globalThis,{},e.workflowDeploymentId),a=Date.now()-r;return t?.setAttributes({...je(i.args.length),...de(a)}),i});if(Wi(m)){let{message:e,hint:t}=Ee(`step arguments`,void 0);throw new hn(e,{hint:t})}let h=m.args,g=m.thisVal??null,y=Nn(c?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Ri()??3e3}`),C,M=!1,N=Date.now();A=Vi({tracking:e.latencyTracking,stepCodeStartedAtMs:N,attempt:t,lazyStepStart:e.lazyStepInput!==void 0,optimisticStart:_,preclaimedStart:e.preclaimedStart!==void 0,stepStartPostSentAtMs:x}),A&&u?.setAttributes({...A.ttfs===void 0?{}:Qe(A.ttfs),...A.stso===void 0?{}:nt(A.stso),...A.rsfs===void 0?{}:We(A.rsfs),...A.finalSchedulingReplay===void 0?{}:qe(A.finalSchedulingReplay),...bt(A.optimizations??[])});let te=()=>{let n=e.resumeTracking;if(!n||n.reported)return;let r=Oi({tracking:n,attempt:t,stepClaimStartedAtMs:x,stepClaimCompletedAtMs:S,stepCodeStartedAtMs:Date.now()});r&&(n.reported=!0,u?.setAttributes(r))},P=`ok`,F=performance.now();try{w=await K(`step.execute`,{},async()=>await ke.run({stepMetadata:{stepName:s,stepId:o,stepStartedAt:new Date(+a),attempt:t},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+i),url:y,features:{encryption:!!p}},workflowDeploymentId:e.workflowDeploymentId,rootRunId:e.rootRunId,ops:D,preCompletionOps:T,closureVars:m.closureVars,encryptionKey:p,runReadyBarrier:_?e.runReadyBarrier:void 0},()=>(te(),f.apply(g,h))))}catch(e){P=`error`,C=e,M=!0}finally{gt(performance.now()-F,P)}let ne=Date.now()-N;if(he(...h,g,m.closureVars),M)throw C;if(u?.setAttributes({...b(ne)}),w=await K(`step.dehydrate`,{},async t=>{let r=Date.now(),i=await dt(w,n,p,D,globalThis,!1,!1,l,_?e.runReadyBarrier:void 0),a=Date.now()-r;return t?.setAttributes({...O(a),...Lt(typeof i)}),i}),D.length>0){let e=Promise.all(D);zt(e,e=>{G.warn(`Background flush of step stream ops failed`,{workflowRunId:n,stepId:o,error:e instanceof Error?e.message:String(e)})}),k=await Promise.race([e.then(()=>!0,e=>{if(e?.name===`AbortError`||e?.name===`ResponseAborted`)return!0;throw e}),new Promise(e=>setTimeout(()=>e(!1),500))])}if(_){let e=await ee();if(e)return e;j()}T.length>0&&await Promise.all(T).catch(()=>{})}catch(e){if(_){let e=await ee();if(e)return e;j()}T.length>0&&await Promise.all(T).catch(()=>{});let t=Ni(e),r=await Ii(t),i=r.stack||ji(t)||``;t instanceof Error&&u?.recordException?.(t);let c=X.is(t);if(u?.setAttributes({...B(Ai(t)),...Me(r.message),...qt(Ai(t)),...et(c?`fatal`:bn.is(t)?`retryable`:`transient`),...Fe(!c)}),Y.is(e))return z.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};if(c){z.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:s,errorStack:i}),vr.isNativeError(t)&&i&&(t.stack=i);try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(t,n,await d(),[],globalThis,l),...A}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...a(!0)}),{type:`failed`}}let f=v.attempt;if(u?.setAttributes({...Oe(f),...Nt(h)}),f>=h+1){let t=v.attempt-1;z.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:s,attempt:v.attempt,retryCount:t,errorStack:i});let a=new X(`Step "${s}" failed after ${h} ${cn(`retry`,`retries`,h)}: ${r.message}`);a.cause=e,i&&(a.stack=i);try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(a,n,await d(),[],globalThis,l),...A}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}bn.is(e)?z.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:s,attempt:f,message:e.message}):z.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:s,attempt:f,errorStack:i}),vr.isNativeError(e)&&i&&(e.stack=i);try{await p({eventType:`step_retrying`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await L(e,n,await d(),[],globalThis,l),...bn.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(Z.is(e))return G.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}let m=Math.max(1,bn.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return u?.setAttributes({...ht(m),...Wt(!0)}),{type:`retry`,timeoutSeconds:m}}let M;try{M=await p({eventType:`step_completed`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,result:w,...A}},e.inlineDeltaSinceCursor===void 0?void 0:{sinceCursor:e.inlineDeltaSinceCursor})}catch(e){if(Z.is(e))return G.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};if(Y.is(e))return z.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};throw e}let N=Gi(M,e.inlineDeltaSinceCursor!==void 0);return u?.setAttributes({...vt(`completed`),...Lt(typeof w)}),D.length>0&&z.debug(`Step has pending ops`,{workflowRunId:n,stepName:s,opsCount:D.length}),{type:`completed`,hasPendingOps:!k,inlineDelta:N}})}function qi(e){return e.hasCreatedEvent===!0&&e.ownerMessageId!==void 0&&e.sawRetrying!==!0}function Ji(e,t){if(e.lastStartedAt===void 0)return 0;let n=Xr(),r=e.lastStartedAt+n*1e3-t;return Math.min(n,Math.max(0,Math.ceil(r/1e3)))}function Yi(e){return`${e.correlationId}:backstop:${e.lastStartedAt}`}function Xi(e,t,n){let r=new Map,i=new Set;for(let t of e)if(t.correlationId!==void 0)if(t.eventType===`step_started`){let e=`eventData`in t&&t.eventData&&`ownerMessageId`in t.eventData&&typeof t.eventData.ownerMessageId==`string`?t.eventData.ownerMessageId:void 0;r.set(t.correlationId,e)}else t.eventType===`step_retrying`&&i.add(t.correlationId);for(let e of t)if(e!==void 0&&!i.has(e)&&r.get(e)===n)return!0;return!1}const Zi=r(`@workflow/core//stepSingleFlight`,1,()=>({inFlight:new Map}));async function Qi(e,t,n){let r=`${e}:${t}`,i=Zi.inFlight.get(r);if(i){G.warn(`Step execution already in flight in this process; awaiting its settlement instead of executing again`,{workflowRunId:e,stepId:t});try{await i}catch{}return{type:`skipped`}}let a=n();Zi.inFlight.set(r,a);try{return await a}finally{Zi.inFlight.delete(r)}}async function $i({runId:e,hookEvent:t,queueItem:n,requestId:r,createEvent:i}){try{return(await i(t,{requestId:r})).event?.eventType===`hook_conflict`?{hasHookConflict:!0,hasAwaitedHookCreation:!1}:{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0}}catch(t){if(Z.is(t))return G.info(`Hook already exists, continuing`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0};if(Y.is(t))return G.info(`Workflow run already completed, skipping hook`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:!1};if(ta(t)){let e=new X(`createHook failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}throw t}}async function ea({suspension:e,world:t,run:n,span:r,requestId:i,eventLog:a,runReadyBarrier:o,replayRecoveryReporter:s,stepDispatch:c,ownerMessageId:l,allowDeferredBatchWork:u}){let d=n.runId,h=async()=>{if(o)try{await o}catch{}},g=async e=>{let t=(await Promise.allSettled(e)).filter(e=>e.status===`rejected`).map(e=>e.reason);if(t.length!==0)throw t.find(e=>dn.is(e))??t[0]},_=s??Ci.inert(),v=(e,n)=>_.withEventCreate(n,n=>t.events.create(d,e,n)),y=0,b=async(e,t)=>{if(!a)return v(e,t);let n=a,r=await v(e,{...t,...$t(n.events)}),i=Mt(n.events,r);return y+=i.added,i.truncated?G.debug(`Dropped a truncated skipped-slot report`,{workflowRunId:d,eventType:e.eventType,eventId:r.event?.eventId,offered:i.offered}):i.added>0&&G.debug(`Suspension write skipped occupied slots`,{workflowRunId:d,eventType:e.eventType,eventId:r.event?.eventId,reported:i.added}),r},x=e.items.filter(e=>e.type===`step`),C=e.items.filter(e=>e.type===`hook`),ee=e.items.filter(e=>e.type===`wait`),w=e.items.filter(e=>e.type===`attribute`),T=C.filter(e=>!e.hasCreatedEvent),E=new Map;for(let e of C){if(e.hasCreatedEvent&&!e.disposed)continue;let t=E.get(e.token);t?t.push(e):E.set(e.token,[e])}let D=await t.getEncryptionKeyForRun?.(n),O=D?await m(D):void 0,k=(n.specVersion??0)>=5,A=0,j=[];async function M(t,n){let r={executions:[]};try{return await f(t,d,O,e.globalThis,!1,k,r)}finally{A+=r.totalExecutions??r.executions.length,j.push(...r.executions.slice(0,5-j.length).map(e=>({...n,...e})))}}async function te(e){let t={eventType:`hook_disposed`,specVersion:7,correlationId:e.correlationId,eventData:{token:e.token}};try{await b(t,{requestId:i})}catch(t){if(Z.is(t))G.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(Y.is(t))G.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(_n.is(t))G.info(`Hook not found for disposal, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}}let P=!1,F=!1,ne=0;if(E.size>0){let e=Date.now();await h(),await g([...E.values()].map(async e=>{for(let t of e){let e=!1;if(!t.hasCreatedEvent){let n=t.metadata===void 0?void 0:await M(t.metadata,{source:`hook_metadata`,correlationId:t.correlationId}),r={eventType:`hook_created`,specVersion:7,correlationId:t.correlationId,eventData:{token:t.token,tokenRetentionUntil:t.tokenRetentionUntil,metadata:n,isWebhook:t.isWebhook??!1,...t.isSystem&&{isSystem:!0}}},a=await $i({runId:d,hookEvent:r,queueItem:t,requestId:i,createEvent:b});P||=a.hasHookConflict,F||=a.hasAwaitedHookCreation,e=a.hasHookConflict}t.disposed&&!e&&await te(t)}})),ne=Date.now()-e}let I=C.filter(e=>e.abortRequested&&!e.disposed);I.length>0&&(await h(),await g(I.map(async e=>{try{let n=await M({aborted:!0,reason:e.abortReason},{source:`hook_abort`,correlationId:e.correlationId});await b({eventType:`hook_received`,specVersion:7,correlationId:e.correlationId,eventData:{token:e.token,payload:n}});try{let r=kt(e.token);await t.streams.write(d,r,n),await t.streams.close(d,r)}catch{G.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:d,correlationId:e.correlationId})}}catch(t){if(Z.is(t)||Y.is(t))G.info(`Workflow run already completed, skipping abort`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})));let re=new Set(x.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),ie=new Set,ae=new Set,oe=async(t,r)=>{G.warn(`Step arguments failed to serialize; failing the step so the workflow can observe the error`,{workflowRunId:d,correlationId:t.correlationId,stepName:t.stepName,error:r.message}),await h();let a=await f(Ui(),d,O,e.globalThis,!1,k);try{await b({eventType:`step_created`,specVersion:7,correlationId:t.correlationId,eventData:{stepName:t.stepName,workflowName:n.workflowName,input:a}},{requestId:i})}catch(e){if(Z.is(e))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else if(Y.is(e))return;else throw e}try{await b({eventType:`step_failed`,specVersion:7,correlationId:t.correlationId,eventData:{stepName:t.stepName,error:await L(r,d,O,[],e.globalThis,k)}},{requestId:i})}catch(e){if(Z.is(e)||Y.is(e))G.info(`Tried failing step, but step or run has already finished.`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else throw e}ae.add(t.correlationId),se.delete(t.correlationId)},se=new Set(F===!1?x.filter(e=>re.has(e.correlationId)).slice(0,Vr()).map(e=>e.correlationId):[]),ce=new Map,R=[],le=new Set,ue=c!==void 0&&Hr()&&(n.specVersion??0)>=3,de=Ur()&&typeof t.events.createBatch==`function`&&(n.specVersion??0)>=6&&!ue&&C.length===0&&w.length===0,z=[],B=[],V=ee.filter(e=>!e.hasCreatedEvent).length,H=de&&l!==void 0&&se.size>0&&(se.size>=2||re.size-se.size+V>=1),U=new Map,fe,pe,me=()=>(pe??=c?.getTraceCarrier()??Promise.resolve({}),pe),he=0,ge=0;for(let e of x)if(re.has(e.correlationId)){let r=H&&se.has(e.correlationId),a=ge;ge+=r?2:1;let o=(async()=>{let o;try{o=await M({args:e.args,closureVars:e.closureVars,thisVal:e.thisVal},{source:`step_input`,correlationId:e.correlationId})}catch(t){if(!hn.is(t)||!c)throw t;await oe(e,t);return}if(se.has(e.correlationId)){ce.set(e.correlationId,{correlationId:e.correlationId,stepName:e.stepName,dehydratedInput:o}),r&&(z.push({order:a,kind:`inline-created`,correlationId:e.correlationId,event:{eventType:`step_created`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,workflowName:n.workflowName,input:o}}}),z.push({order:a+1,kind:`inline-started`,correlationId:e.correlationId,event:{eventType:`step_started`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,...l===void 0?{}:{ownerMessageId:l}}}}));return}let s={eventType:`step_created`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,workflowName:n.workflowName,input:o}};if(ue&&o instanceof Uint8Array&&o.byteLength<=131072){await h();let n=await me(),[r,a]=await Promise.allSettled([b(s,{requestId:i}),Ze(t,c.queueName,{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:n,requestedAt:new Date,stepInput:{input:o}},{idempotencyKey:ze(e.correlationId,e.stepName)})]);if(a.status===`rejected`)throw a.reason;if(le.add(e.correlationId),r.status===`rejected`){let t=r.reason;if(Z.is(t))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(ur(t))he++,G.warn(`Step creation event write failed, but the step was dispatched via the queue. The step_created event will be ensured by the queue consumer.`,{workflowRunId:d,correlationId:e.correlationId,stepName:e.stepName,error:t instanceof Error?t.message:String(t)});else throw t}else ie.add(e.correlationId);return}if(de){z.push({order:a,kind:`step`,correlationId:e.correlationId,stepName:e.stepName,event:s});return}try{await h(),await b(s,{requestId:i}),ie.add(e.correlationId)}catch(t){if(Z.is(t))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})();R.push(o),de&&B.push(o.catch(()=>{}))}for(let e of ee)if(!e.hasCreatedEvent){let t={eventType:`wait_created`,specVersion:7,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};if(de){z.push({order:ge++,kind:`wait`,correlationId:e.correlationId,event:t});continue}R.push((async()=>{try{await h(),await b(t,{requestId:i})}catch(t){if(Z.is(t))G.info(`Wait already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})())}let _e;de&&R.push((async()=>{if(await Promise.all(B),z.length===0)return;let e=[...z].sort((e,t)=>e.order-t.order);if(await h(),e.length===1){let[t]=e;try{await b(t.event,{requestId:i}),t.kind===`step`&&ie.add(t.correlationId)}catch(e){if(Z.is(e))G.info(t.kind===`step`?`Step already exists, continuing`:`Wait already exists, continuing`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else throw e}return}let n=a?(Ye(a.events)??0)+1:void 0,r=[];{let t=[];for(let n=0;n<e.length;n++){let i=e[n],a=e[n+1],o=i.kind===`inline-created`&&a?.kind===`inline-started`&&a.correlationId===i.correlationId,s=o?2:1;t.length>0&&t.length+s>32&&(r.push(t),t=[]),t.push(i),o&&(t.push(a),n++)}t.length>0&&r.push(t)}let o=c!==void 0;if(o)for(let t of e)t.kind===`step`&&le.add(t.correlationId);let s=0,l,f=async e=>{let n=Date.now(),{results:r}=await t.events.createBatch(d,e.map(e=>({event:e.event,...e.kind===`inline-started`?{computeInstanceId:Mr}:{}})),{requestId:i}),a=Date.now();for(let[t,i]of r.entries()){let r=e[t];if(i.error===void 0){if(r.kind===`step`)ie.add(r.correlationId);else if(r.kind===`inline-started`){let e=ce.get(r.correlationId);if(e===void 0)throw new pn(`no dehydrated input for pre-claimed step ${r.correlationId}`,{status:500});let t=new Date,o=i.step?.startedAt?{...i.step,startedAt:i.step.startedAt}:{runId:d,stepId:r.correlationId,stepName:e.stepName,status:`running`,attempt:1,createdAt:t,updatedAt:t,startedAt:t};U.set(r.correlationId,{owned:!0,step:{...o,input:e.dehydratedInput},batchPostSentAtMs:n,claimCompletedAtMs:a})}continue}if(i.status===409){if(r.kind===`inline-created`||r.kind===`inline-started`){U.set(r.correlationId,{owned:!1}),G.info(`Inline step pre-claim lost, continuing`,{workflowRunId:d,correlationId:r.correlationId,message:i.message});continue}G.info(r.kind===`step`?`Step already exists, continuing`:`Wait already exists, continuing`,{workflowRunId:d,correlationId:r.correlationId,message:i.message});continue}throw new pn(`batched ${r.event.eventType} for ${r.correlationId} failed: ${i.error}: ${i.message}`,{status:i.status})}let o=Ye(r.flatMap(e=>e.error===void 0&&e.event?[e.event]:[]));o!==void 0&&(fe===void 0||o>fe)&&(fe=o),s+=r.filter(e=>e.error===void 0).length,o!==void 0&&(l===void 0||o>l)&&(l=o)},p=async e=>{if(!o)return;let n=e.filter(e=>e.kind===`step`);if(n.length===0)return;let r=await me();await Promise.all(n.map(e=>Ze(t,c.queueName,{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:r,requestedAt:new Date},{idempotencyKey:ze(e.correlationId,e.stepName)})))},m=r.map(e=>f(e)),g=r.map(async(e,t)=>{await m[t],await p(e)}),_=(async()=>{let e=await Promise.allSettled([...m,...g]);if(n!==void 0&&l!==void 0){let e=l-n+1-s;e>0&&G.debug(`Batched fan-out committed above snapshot`,{workflowRunId:d,expectedFirstSlot:n,maxCommittedSlot:l,committedCount:s,interleaved:e})}let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason})(),v=r.flatMap((e,t)=>e.some(e=>e.kind===`inline-started`)?[m[t]]:[]);if(u){if(_.catch(()=>{}),_e=_,v.length>0)try{await Promise.all(v)}catch(e){throw await _.catch(()=>{}),e}}else await _})());for(let e of w)R.push((async()=>{try{await h(),await b({eventType:`attr_set`,specVersion:7,correlationId:e.correlationId,eventData:{changes:e.changes,writer:{type:`workflow`},...e.allowReservedAttributes?{allowReservedAttributes:!0}:{}}},{requestId:i})}catch(t){if(Z.is(t))G.info(`Workflow attribute event already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(ta(t)){let e=new X(`setAttributes failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}else throw t}})());await g(R);let ve=[];for(let e of se){let t=ce.get(e);t&&ve.push(t)}let be=Date.now(),xe;for(let e of ee){let t=e.resumeAt.getTime(),n=Math.max(1e3,t-be),r=Math.ceil(n/1e3);(!xe||r<xe.seconds)&&(xe={seconds:r,correlationId:e.correlationId})}return r?.setAttributes({...ye(`workflow_suspended`),...S(x.length),...p(T.length),...De(ee.length),...ae.size>0?N(ae.size):{},...he>0?Ct(he):{}}),{pendingSteps:x,createdStepCorrelationIds:ie,failedStepCorrelationIds:ae,queuedStepCorrelationIds:le,lazyInlineSteps:ve,inlineClaims:U,batchCommittedSlotCeiling:fe,deferredBatchWork:_e,waitTimeout:P?void 0:xe,hasHookConflict:P,hasAwaitedHookCreation:F,hasAttributeEvents:w.length>0,hasHookEvents:T.length>0,hookCreationMs:ne,serializationBlockerCount:A,serializationBlockers:j,reportedEventCount:y}}function ta(e){return e instanceof Kn||e instanceof Error&&e.name===`AttributeValidationError`||pn.is(e)&&e.status===400}const na=()=>Bn(`WORKFLOW_WAIT_CONTINUATION_MAX_DELAY_SECONDS`,82800,{integer:!0,min:1}),ra=()=>Bn(`WORKFLOW_NEAR_ELAPSED_WAIT_THRESHOLD_SECONDS`,2);function ia(e,t,n=Date.now(),r=0){let i=aa(e,t,n);return r<=0?i:{delaySeconds:i.delaySeconds,idempotencyKey:`${i.idempotencyKey}:a${r}`}}function aa(e,t,n){let r=na();if(e<=Math.min(ra(),r))return{delaySeconds:e,idempotencyKey:`${t}:${Math.floor(n/1e3)}`};let i=Math.ceil(e/r);return{delaySeconds:Math.min(e,r),idempotencyKey:i===1?t:`${t}:hop-${i}`}}var oa=44,sa=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,ca=new Uint8Array(64),la=new Uint8Array(128);for(let e=0;e<sa.length;e++){let t=sa.charCodeAt(e);ca[e]=t,la[t]=e}function ua(e,t){let n=0,r=0,i=0;do i=la[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function da(e,t){return e.pos>=t?!1:e.peek()!==oa}var fa=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function pa(e){let{length:t}=e,n=new fa(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=ua(n,i),i<u&&(l=!1),u=i,da(n,e)?(a=ua(n,a),o=ua(n,o),s=ua(n,s),da(n,e)?(c=ua(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||ma(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function ma(e){e.sort(ha)}function ha(e,t){return e[0]-t[0]}const ga=/^[\w+.-]+:\/\//,_a=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,va=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function ya(e){return ga.test(e)}function ba(e){return e.startsWith(`//`)}function xa(e){return e.startsWith(`/`)}function Sa(e){return e.startsWith(`file:`)}function Ca(e){return/^[.?#]/.test(e)}function wa(e){let t=_a.exec(e);return Ea(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function Ta(e){let t=va.exec(e),n=t[2];return Ea(`file:`,``,t[1]||``,``,xa(n)?n:`/`+n,t[3]||``,t[4]||``)}function Ea(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function Da(e){if(ba(e)){let t=wa(`http:`+e);return t.scheme=``,t.type=6,t}if(xa(e)){let t=wa(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(Sa(e))return Ta(e);if(ya(e))return wa(e);let t=wa(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function Oa(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function ka(e,t){Aa(t,t.type),e.path===`/`?e.path=t.path:e.path=Oa(t.path)+e.path}function Aa(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function ja(e,t){if(!e&&!t)return``;let n=Da(e),r=n.type;if(t&&r!==7){let e=Da(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:ka(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}Aa(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?Ca(t||e)&&!Ca(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function Ma(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Na(e,t){let n=Ma(e),r=t?t+`/`:``;return e=>ja(r+(e||``),n)}var Pa=0,Fa=1,Ia=2,La=3,Ra=4;function za(e,t){let n=Ba(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=Ba(e,r+1))e[r]=Ha(e[r],t);return e}function Ba(e,t){for(let n=t;n<e.length;n++)if(!Va(e[n]))return n;return e.length}function Va(e){for(let t=1;t<e.length;t++)if(e[t][Pa]<e[t-1][Pa])return!1;return!0}function Ha(e,t){return t||(e=e.slice()),e.sort(Ua)}function Ua(e,t){return e[Pa]-t[Pa]}var Wa=!1;function Ga(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][Pa]-t;if(a===0)return Wa=!0,i;a<0?n=i+1:r=i-1}return Wa=!1,n-1}function Ka(e,t,n){for(let r=n+1;r<e.length&&e[r][Pa]===t;n=r++);return n}function qa(e,t,n){for(let r=n-1;r>=0&&e[r][Pa]===t;n=r--);return n}function Ja(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function Ya(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return Wa=o!==-1&&e[o][Pa]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=Ga(e,t,s,c)}function Xa(e){return typeof e==`string`?JSON.parse(e):e}var Za="`line` must be greater than 0 (lines start at line 1)",Qa="`column` must be greater than or equal to 0 (columns start at column 0)",$a=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=Xa(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Na(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=za(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=Ja(),this._bySources=void 0,this._bySourceMemos=void 0}};function eo(e){return e}function to(e){var t;return(t=eo(e))._decoded||(t._decoded=pa(eo(e)._encoded))}function no(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(Za);if(r<0)throw Error(Qa);let a=to(e);if(n>=a.length)return ro(null,null,null,null);let o=a[n],s=io(o,eo(e)._decodedMemo,n,r,i||1);if(s===-1)return ro(null,null,null,null);let c=o[s];if(c.length===1)return ro(null,null,null,null);let{names:l,resolvedSources:u}=e;return ro(u[c[Fa]],c[Ia]+1,c[La],c.length===5?l[c[Ra]]:null)}function ro(e,t,n,r){return{source:e,line:t,column:n,name:r}}function io(e,t,n,r,i){let a=Ya(e,r,t,n);return Wa?a=(i===-1?Ka:qa)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function ao(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function oo(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&ao(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}const so=r(`@workflow/core//sourceMapTracers`,1,()=>({byCode:new Map}));function co(e){let t=so.byCode.get(e);if(t!==void 0)return so.byCode.delete(e),so.byCode.set(e,t),t;let n=null,r=oo(e);if(r)try{let e=Buffer.from(r,`base64`).toString(`utf-8`);n=new $a(JSON.parse(e))}catch{n=null}for(so.byCode.set(e,n);so.byCode.size>8;){let e=so.byCode.keys().next().value;if(e===void 0)break;so.byCode.delete(e)}return n}function lo(e,t,n){if(!e.includes(t))return e;let r=co(n);if(!r)return e;try{return e.split(`
|
|
2
|
-
`).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,i,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=
|
|
3
|
-
`)}catch{return e}}function uo(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function fo(e){return function(t,n){let r=function(...r){let{promise:i,resolve:a,reject:o}=En(),s=`step_${e.generateUlid()}`,c={type:`step`,correlationId:s,stepName:t,args:r};this!==void 0&&this!==null&&this!==globalThis&&(c.thisVal=this);let l=n?.();return l&&(c.closureVars=l),e.invocationsQueue.set(s,c),z.debug(`Step consumer setup`,{correlationId:s,stepName:t,args:r}),e.eventsConsumer.subscribe(n=>{if(!n)return wn(e),W.NotConsumed;if(z.debug(`Step consumer event processing`,{correlationId:s,stepName:t,args:r.join(`, `),incomingCorrelationId:n.correlationId,isMatch:s===n.correlationId,eventType:n.eventType}),n.correlationId!==s)return W.NotConsumed;let i=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof i==`string`&&i!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: step event ${n.eventType} for ${s} belongs to "${i}", but the current step consumer is "${t}"`,{eventId:n.eventId}))}),W.Finished;if(n.eventType===`step_created`){let r=e.invocationsQueue.get(s);return!r||r.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{o(new mn(`Replay divergence: step ${s} (${t}) created but not found in invocation queue`,{eventId:n.eventId}))}),W.Finished):(r.hasCreatedEvent=!0,W.Consumed)}if(n.eventType===`step_started`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.ownerMessageId=`eventData`in n&&n.eventData&&`ownerMessageId`in n.eventData&&typeof n.eventData.ownerMessageId==`string`?n.eventData.ownerMessageId:void 0,t.lastStartedAt=+n.createdAt),W.Consumed}if(n.eventType===`step_retrying`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.sawRetrying=!0,t.ownerMessageId=void 0),W.Consumed}if(n.eventType===`step_failed`){e.invocationsQueue.delete(n.correlationId);let t=e.eventsConsumer.eventIndex,r=Cn(e,t,`step`),i,a=An(e,t,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let t=await e.replayPayloadCache.prepareEventPayload(n.eventId,`error`,n.eventData.error);i=await P(n.eventData.error,e.runId,e.encryptionKey,e.globalThis,{},t)}catch(e){z.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),i=new X(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`)}finally{e.pendingDeliveries--}a.then(()=>{r.markDelivered(),o(i)})}),W.Finished}if(n.eventType===`step_completed`){e.invocationsQueue.delete(n.correlationId);let t=n.eventId,r=n.eventData.result,i=e.eventsConsumer.eventIndex,s=Cn(e,i,`step`),c,l=An(e,i,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{c={ok:!0,value:await e.replayPayloadCache.getStepResult(t,async()=>{let n=await e.replayPayloadCache.prepareEventPayload(t,`result`,r);return await V(r,e.runId,e.encryptionKey,e.globalThis,{},n)})}}catch(e){c={ok:!1,error:e}}finally{e.pendingDeliveries--}l.then(()=>{s.markDelivered(),c.ok?a(c.value):o(c.error)})}),W.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: Unexpected event type for step ${s} (name: ${t}) "${n.eventType}"`,{eventId:n.eventId}))}),W.Finished}),i},i=t.split(`//`).pop();return Object.defineProperty(r,"name",{value:i}),Object.defineProperty(r,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&(wt(n),Object.defineProperty(r,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1})),Object.defineProperty(r,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),r}}var po=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),mo=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),ho=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),go=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),_o=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),vo=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),yo=n(((e,n)=>{(function(e,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var t;return p&&(t=p.randomBytes)?t=t(a):(t=new Uint8Array(a),(e.crypto||e.msCrypto).getRandomValues(t)),b(t)}catch{var n=e.navigator,i=n&&n.plugins;return[+new Date,e,i,e.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=t(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:e,[],Math)})),bo=e(n(((e,t)=>{var n=po(),r=mo(),i=ho(),a=go(),o=_o(),s=vo(),c=yo();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const xo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,So=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)So[xo.charCodeAt(e)]=e;function Co(e){return e===9||e===10||e===12||e===13||e===32}function wo(e,t){for(;t<e.length&&Co(e.charCodeAt(t));)t++;return t}function To(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=So[r.charCodeAt(0)],a=So[r.charCodeAt(1)],o=So[r.charCodeAt(2)],s=So[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function Eo(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=wo(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...To(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=wo(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=wo(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...To(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||So[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...To(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function Do(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function Oo(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=xo[n>>2&63],i+=xo[(n&3)<<4|o>>4&15],t+1<a?i+=xo[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=xo[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function ko(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function Ao(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Oo(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return ko(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Eo(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Do(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Eo(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Do(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function jo(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}const Mo={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function No(e){if(vr.isTypedArray(e)||vr.isDataView(e)){if(vr.isSharedArrayBuffer(e.buffer))throw TypeError(`crypto.subtle.digest does not accept SharedArrayBuffer-backed views`);return e}if(!vr.isArrayBuffer(e))throw TypeError(`data must be an ArrayBuffer or ArrayBufferView`);return new Uint8Array(e)}function Po(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,bo.default)(n),i=Sr(),a=Cr(`globalThis`,i);a.Math.random=r;let o=a.Date;a.Date=function(...e){return new.target===void 0?new o(t).toString():Reflect.construct(o,e.length===0?[t]:e,new.target)},a.Date.prototype=o.prototype,Object.setPrototypeOf(a.Date,o),a.Date.now=()=>t;let s=globalThis.crypto,c=s.subtle;function l(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let u=jo(r),d=a;delete d.Atomics.waitAsync,delete d.WebAssembly.compile,delete d.WebAssembly.instantiate,delete d.WebAssembly.compileStreaming,delete d.WebAssembly.instantiateStreaming,delete d.WeakRef,delete d.FinalizationRegistry;let f=async(e,t)=>{let n=typeof e==`string`?e:e.name,r=Mo[n.toUpperCase()];if(!r)throw new DOMException(`Unrecognized algorithm name: ${n}`,`NotSupportedError`);let i=_r(r).update(No(t)).digest(),a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),a};return a.crypto=new Proxy(s,{get(e,t){return t===`getRandomValues`?l:t===`randomUUID`?u:t===`subtle`?new Proxy(c,{get(e,t){if(t===`digest`)return f;let n=e[t];return typeof n==`function`?()=>{throw new J(`\`crypto.subtle.${String(t)}()\` is not available inside a workflow function. Move it to a step function where full Node.js crypto is available.`)}:n}}):e[t]}}),a.process={env:Object.freeze({...process.env})},a.DOMException=globalThis.DOMException,a.Headers=globalThis.Headers,a.TextEncoder=globalThis.TextEncoder,a.TextDecoder=globalThis.TextDecoder,a.console=globalThis.console,a.URL=globalThis.URL,a.URLSearchParams=globalThis.URLSearchParams,a.structuredClone=globalThis.structuredClone,a.atob=globalThis.atob,a.btoa=globalThis.btoa,Ao(a.Uint8Array),a.Symbol.dispose??=Symbol.for(`Symbol.dispose`),a.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),a.exports={},a.module={exports:a.exports},{context:i,globalThis:a,updateTimestamp:e=>{t=e}}}const Fo=r(`@workflow/core//vmScriptCache`,1,()=>({byCode:new Map}));function Io(e){let t=Fo.byCode.get(e);if(t!==void 0)return Fo.byCode.delete(e),Fo.byCode.set(e,t),t}function Lo(e,t){let n=Io(e);if(n===void 0)for(n=new Map,Fo.byCode.set(e,n);Fo.byCode.size>8;){let e=Fo.byCode.keys().next().value;if(e===void 0)break;Fo.byCode.delete(e)}let r=n.get(t),i=r!==void 0;return r===void 0&&(r=new xr(e,{filename:t}),n.set(t,r)),{script:r,cacheHit:i}}function Ro(e){return async function(t,n={}){let{promise:r,resolve:i}=En(),a=`attr_${e.generateUlid()}`,o={type:`attribute`,correlationId:a,changes:t,...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}};return e.invocationsQueue.set(a,o),e.eventsConsumer.subscribe(r=>r?r.correlationId===a?r.eventType!==`attr_set`||r.eventData.writer.type!==`workflow`||JSON.stringify(r.eventData.changes)!==JSON.stringify(t)||r.eventData.allowReservedAttributes===!0!=(n.allowReservedAttributes===!0)?(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: Unexpected attribute event for ${a}`,{eventId:r.eventId}))}),W.Finished):(e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),W.Finished):W.NotConsumed:(wn(e),W.NotConsumed)),r}}function zo(e,t){if(typeof t!=`string`)return null;let n=Pt(Vt,e.globalThis),r=n?.[ot];return typeof r==`function`?r.call(n,{runId:t}):null}function Bo(e){return function(t={}){if(t.token===``)throw Error("`createHook()` was called with an empty string token. Pass a non-empty token, or omit the `token` option to use a generated one.");if(t.isWebhook===!0&&t.experimental_minRetention!==void 0)throw Error("Webhook hooks do not support `experimental_minRetention`. Use a non-webhook `createHook()` with `resumeHook()`.");if(t.experimental_minRetention!==void 0&&e.worldCapabilities?.hookRetention?.active!==!0)throw new X("The configured World does not support `experimental_minRetention` for Hooks.");let n=`hook_${e.generateUlid()}`,r=t.token??e.generateNanoid(),a=t.experimental_minRetention===void 0?void 0:fn(t.experimental_minRetention),o=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:r,tokenRetentionUntil:a,metadata:t.metadata,isWebhook:o});let s=[],c=[],l=[],u=!1,d=!1,f=!1,p=!1,m=null,h=null,g=new Set;i.debug(`Hook consumer setup`,{correlationId:n,token:r}),e.eventsConsumer.subscribe(t=>{if(!t)return u=!0,(c.length>0&&s.length===0||l.length>0&&!d&&!p)&&wn(e),W.NotConsumed;if(t.correlationId!==n)return W.NotConsumed;let i=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof i==`string`&&i!==r)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: hook event ${t.eventType} for ${n} belongs to token "${i}", but the current hook consumer expects "${r}"`,{eventId:t.eventId}))}),W.Finished;if(t.eventType===`hook_created`){let r=e.invocationsQueue.get(n);r&&r.type===`hook`&&(r.hasCreatedEvent=!0,r.tokenRetentionUntil=t.eventData.tokenRetentionUntil),d=!0;let i=l.slice();return l.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of i)e.resolve(null)}),W.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new un(r.eventData.token,r.eventData.conflictingRunId);p=!0,m=i,h=zo(e,r.eventData.conflictingRunId);let a=c.slice();c.length=0;let o=l.slice();return l.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i);for(let e of o)h?e.resolve(h):e.reject(i)}),W.Consumed}if(t.eventType===`hook_received`){let n=t.resumeId;if(typeof n==`string`){if(g.has(n))return W.Consumed;g.add(n)}let r=e.eventsConsumer.eventIndex,i=c.length>0,a=Cn(e,r,`hook`,{armed:i});if(i){let n=An(e,r,`hook`),i=c.shift();if(i){e.pendingDeliveries++;let r;e.promiseQueue=e.promiseQueue.then(async()=>{try{let n=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);r={ok:!0,value:await V(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},n)}}catch(e){r={ok:!1,error:e}}finally{e.pendingDeliveries--}n.then(()=>{a.markDelivered(),r.ok?i.resolve(r.value):i.reject(r.error)})})}}else{let n,i=En();e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);n={ok:!0,value:await V(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},r)}}catch(e){n={ok:!1,error:e}}finally{e.pendingDeliveries--,i.resolve()}}),s.push({claim:()=>(a.arm(),i.promise.then(()=>An(e,r,`hook`)).then(()=>{if(a.markDelivered(),n&&!n.ok)throw n.error;return n.value}))})}return W.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),f=!0,W.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: Unexpected event type for hook ${n} (token: ${r}) "${t.eventType}"`,{eventId:t.eventId}))}),W.Finished)});let _=!1;function v(){let t=En();if(p&&m)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(m)}),t.promise;if(s.length>0){let e=s.shift();if(e)return e.claim()}return u&&wn(e),c.push(t),t.promise}function y(){let t=En();if(d)return e.promiseQueue=e.promiseQueue.then(()=>{t.resolve(null)}),t.promise;if(p)return e.promiseQueue=e.promiseQueue.then(()=>{h?t.resolve(h):t.reject(m)}),t.promise;let r=e.invocationsQueue.get(n);return r&&r.type===`hook`&&(r.hasConflictAwaiter=!0),u&&wn(e),l.push(t),t.promise}function b(){if(_||(_=!0,f))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),c.length>0&&(c.length=0,wn(e)),i.debug(`Hook disposed`,{correlationId:n,token:r})}let x={token:r,getConflict(){return y()},then(e,t){return v().then(e,t)},async*[Symbol.asyncIterator](){for(;!_;)yield await this},dispose:b,[Symbol.dispose]:b},S=e.globalThis.Symbol.dispose;return S&&S!==Symbol.dispose&&(x[S]=b),x}}function Vo(e){return async function(t){let{promise:n,resolve:r}=En(),i=`wait_${e.generateUlid()}`,a=fn(t),o={type:`wait`,correlationId:i,resumeAt:a};return e.invocationsQueue.set(i,o),e.eventsConsumer.subscribe(t=>{if(!t)return kn(e,()=>{e.onWorkflowError(new jn(e.invocationsQueue,e.globalThis))}),W.NotConsumed;if(t.correlationId!==i)return W.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(i);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),W.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let r=e.invocationsQueue.get(i),o=r&&r.type===`wait`?r.resumeAt:a,s=new Date(n),c=s.getTime(),l=o.getTime(),u=Number.isFinite(c)?s.toISOString():String(n);if(c!==l)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: wait_completed event for ${i} has resumeAt "${u}", but the current wait consumer expects "${o.toISOString()}"`,{eventId:t.eventId}))}),W.Finished}e.invocationsQueue.delete(i);let o=e.eventsConsumer.eventIndex,s=Cn(e,o,`wait`),c=An(e,o,`wait`);return e.promiseQueue.then(()=>c).then(()=>{s.markDelivered(),r()}),W.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new mn(`Replay divergence: Unexpected event type for wait ${i} "${t.eventType}"`,{eventId:t.eventId}))}),W.Finished}),n}}async function Ho(e,t,n,r,i,a){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await _i();await ea({suspension:new jn(t,n),world:e,run:r,runReadyBarrier:a})}catch(t){G.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}function Uo(e,t){let n=re(t)?.moduleSpecifier||t,r=`globalThis.__private_workflows?.get(${JSON.stringify(t)})`;return K(`workflow.bundle.compile`,async t=>{let i=Lo(e,n),a=Lo(r,n);return t?.setAttributes({...en(i.cacheHit)}),{bundleScript:i.script,workflowLookupScript:a.script}})}function Wo(e){return Ko(`replay`,e.workflowRun,e.events,async t=>{let{session:n,execution:r}=await Jo(e);return t?.setAttributes({...Pe(n.argumentCount)}),qo(await r,t)})}function Go(e,t){return Ko(`retained`,e.workflowRun,t,async n=>{n?.setAttributes({...Pe(e.argumentCount)});let r=await e.resume(t);return r.type===`replay`?r:qo(r,n)})}function Ko(e,t,n,r){return K(`workflow.run ${t.workflowName}`,i=>(i?.setAttributes({...ce(t.workflowName),...Se(t.runId),...ye(t.status),...ge(n.length),..._(e)}),r(i)))}function qo(e,t){return e.type===`completed`?t?.setAttributes({...y(e.resultType)}):t&&(Je(e.suspension,t),e.parked&&t.setAttributes({...ae(e.parked.count),...lt(e.parked.eventId),...I(e.parked.eventType)})),e}async function Jo(e){let t=await Ke(`workflow.vm.create_context`);return Yo(e,t.end).catch(e=>{throw t.fail(e),e})}async function Yo({workflowCode:e,workflowRun:t,events:n,encryptionKey:r,replayPayloadCache:i,compiledWorkflowScripts:a,runReadyBarrier:o,worldCapabilities:s},c){let l=t.startedAt;if(!l)throw new J(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let u=ki(t.runId)??+t.createdAt,f=Nn(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Ri()??3e3}`),{context:p,globalThis:m,updateTimestamp:h}=Po({seed:`${t.runId}:${t.workflowName}:${t.deploymentId}`,fixedTimestamp:u}),g=En(),_={type:`running`,interruption:g},y=e=>{switch(_.type){case`running`:{let{interruption:t}=_;_=jn.is(e)?{type:`suspended`,suspension:e}:{type:`replay`},A.suspensionGeneration++,t.reject(e);return}case`suspended`:_={type:`replay`};return;case`replay`:case`completed`:return}},b=qn(()=>m.Math.random()),S=0,C=()=>(S+=1,b(u)),w=uo(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*m.Math.random())),T={current:Promise.resolve()},E={current:()=>!0},D=u,O=new x(n,{onConsumedEvent:e=>{let t=+e.createdAt;t>D&&(D=t,h(t))},onUnconsumedEvent:e=>{y(new mn(`Replay could not consume event: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}.`,{eventId:e.eventId}))},onDuplicateEvent:(e,n)=>{let r={workflowRunId:t.runId,eventId:e.eventId,eventType:e.eventType,firstEventType:n,correlationId:e.correlationId};if(n!==e.eventType){G.debug(`Ignoring inert event that decides an already-decided outcome differently`,r);return}G.debug(`Ignoring inert event that repeats a class already in the event log`,r)},getPromiseQueue:()=>T.current,isDeliveryIdle:()=>E.current()}),A={runId:t.runId,encryptionKey:r,worldCapabilities:s,globalThis:m,onWorkflowError:y,eventsConsumer:O,generateUlid:C,generateNanoid:w,get mintCount(){return S},invocationsQueue:new Map,get promiseQueue(){return T.current},set promiseQueue(e){T.current=e},pendingDeliveries:0,suspensionGeneration:0,pendingDeliveryBarriers:new Map,replayPayloadCache:i};E.current=()=>Dn(A);let j=!1;A.eventsConsumer.subscribe(e=>e?e.eventType===`run_created`?W.Consumed:e.eventType===`run_started`?j?W.NotConsumed:(j=!0,W.Consumed):e.eventType===`attr_set`&&e.eventData.writer.type===`step`?W.Consumed:W.NotConsumed:W.NotConsumed);let M=fo(A),N=Bo(A),te=Vo(A),P=Ro(A);m[v]=M,m[Yt]=P,m[pe]=N,m[_e]=te,m[d]=e=>k(t.runId,e),m[Ln]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new m.Date(+l),url:f,features:{encryption:!!r}},m[$e]=C,m.fetch=()=>{throw new m.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${gn.FETCH_IN_WORKFLOW_FUNCTION}`)};let F=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;m.setTimeout=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.setInterval=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearTimeout=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearInterval=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.setImmediate=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearImmediate=()=>{throw new J(F,{slug:gn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.AbortController=ve(A);let ne=ee();m.AbortSignal={abort:ne.abort,any:ne.any,timeout:ne.timeout};class I{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof m.URL){let t=String(e);try{new m.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new m.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new m.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new m.Headers(t.headers):(typeof e==`string`||e instanceof m.URL)&&(this.headers=new m.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(m.ReadableStream.prototype,{[rt]:{value:n,writable:!1}})}clone(){Q()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}m.Request=I,Object.defineProperties(I.prototype,{arrayBuffer:{value:M(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:M(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:M(`__builtin_response_text`),writable:!0,configurable:!0}});class re{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new m.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(m.ReadableStream.prototype,{[rt]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new m.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new re(n,{...t,headers:r})}static error(){Q()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new m.Headers;n.set(`Location`,String(e));let r=Object.create(re.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}m.Response=re,Object.defineProperties(re.prototype,{arrayBuffer:{value:M(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:M(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:M(`__builtin_response_text`),writable:!0,configurable:!0}});class ie{constructor(){Q()}get locked(){return!1}cancel(){Q()}getReader(){Q()}pipeThrough(){Q()}pipeTo(){Q()}tee(){Q()}values(){Q()}static from(){Q()}[Symbol.asyncIterator](){Q()}}m.ReadableStream=ie;class ae{constructor(){Q()}get locked(){return!1}abort(){Q()}close(){Q()}getWriter(){Q()}}m.WritableStream=ae;class oe{readable;writable;constructor(){Q()}}m.TransformStream=oe,m.console=globalThis.console;let se=Symbol.for(`@vercel/request-context`);m[se]=globalThis[se],c();let{bundleScript:L,workflowLookupScript:ce}=a??await Uo(e,t.workflowName),R=await K(`workflow.bundle.evaluate`,async()=>(L.runInContext(p),ce.runInContext(p)));if(typeof R!=`function`)throw new on(t.workflowName);let le=[];A.promiseQueue=A.promiseQueue.then(async()=>{le=await K(`workflow.input.hydrate`,async()=>{let e=await i.prepareWorkflowInput(t);return nn(t.input,t.runId,r,m,{},e)})}),await A.promiseQueue;let ue=async e=>{throw jn.is(e)||mn.is(e)?(_.type===`running`&&(_={type:`replay`}),e):(_={type:`completed`},await Ho(t.runId,A.invocationsQueue,m,t,`failed`,o),e)},de=async(e,n)=>{let i;try{i=await Promise.race([e,n.promise])}catch(e){return _.type===`suspended`&&e===_.suspension?{type:`suspended`,suspension:_.suspension,session:H,parked:O.parkedSummary}:ue(e)}_={type:`completed`};let a=O.strandedEvent;if(a)return ue(new mn(`Replay finished without consuming event: eventType=${a.eventType}, correlationId=${a.correlationId}, eventId=${a.eventId}.`,{eventId:a.eventId}));try{let e=await ct(i,t.runId,r,m,!1,(t.specVersion??0)>=5);return await Ho(t.runId,A.invocationsQueue,m,t,`completed`,o),{type:`completed`,output:e,resultType:typeof i}}catch(e){return ue(e)}},z=await Ft(),B=await Ke(`workflow.replay.execute`),V=z.run(async()=>R(...le)),H={workflowRun:t,argumentCount:le.length,async resume(e){switch(_.type){case`suspended`:{let t=O.events;if(!(e.length>t.length&&t.every((t,n)=>t.eventId===e[n].eventId)))return _={type:`replay`},{type:`replay`};let n=En();return _={type:`running`,interruption:n},A.suspensionGeneration++,z.refresh(),O.append(e.slice(t.length)),de(V,n)}case`replay`:return{type:`replay`};case`completed`:case`running`:throw new J(`Cannot resume ${_.type} workflow "${t.runId}"`)}}},U=de(V,g);return U.then(B.end,B.fail),{session:H,execution:U}}function Xo(e){let t=Wr();return t===void 0?e:e===void 0?t:Math.min(e,t)}function Zo({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.environment;if(!i)return!1;let a=e.getEnvironment?.();return!a||a===i?!1:(r.error(`Refusing to run this workflow: it was created in the "${i}" environment but this deployment runs in "${a}". Executing it here would create a second copy of the same run id in both environments — one pending forever, one running — so the queue message is being discarded without executing and without retrying. The client that called start() wrote the run to its own environment but addressed the queue message to a deployment in another one. Check that the environment that client authenticates as (WORKFLOW_VERCEL_ENV for CLI and CI clients, or the OIDC token's environment inside a deployment) matches the environment of the deployment it targets. The run it created is still pending in "${i}" and will not run.`,{workflowRunId:n,creatorEnvironment:i,currentEnvironment:a,pinnedDeploymentId:t?.deploymentId}),!0)}async function Qo({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.deploymentId;if(!i)return;let a;try{a=await e.getDeploymentId()}catch{return}!a||a===i||r.error(`Queue message was delivered to a deployment it was not pinned to. The run was created targeting a different deployment, so this invocation may be replaying against code the run was not started on. Continuing — this is expected if the Workflow SDK version changed mid-run in local development, where the deployment id is derived from that version.`,{workflowRunId:n,pinnedDeploymentId:i,currentDeploymentId:a})}function $o(e){return J.is(e)?q.RUNTIME_ERROR:sr(e)?q.WORLD_CONTRACT_ERROR:null}function es(e){return!pn.is(e)||e.status!==void 0&&e.status!==404?!1:/step/i.test(e.message)&&/not found/i.test(e.message)}async function ts({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){G.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=Et(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(i,n,await o(),globalThis,(t?.specVersion??0)>=5),errorCode:a}},{requestId:r})}catch(e){if(Z.is(e)||Y.is(e))return;if(sr(e)){G.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:q.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function ns(e,t){return e.find(e=>e.runId===t&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`))}function rs(e,t){let n=ns(e,t);return n?(G.debug(`Run reached terminal event, exiting`,{workflowRunId:t,eventType:n.eventType,eventId:n.eventId}),!0):!1}function is(e,t){let n=0;for(let r of e)t.has(r)||n++;return n}function as(e,t){return e?.[Gn]??t}function os(e){let t=new Set,n=new Set;for(let r of e)switch(r.eventType){case`hook_created`:t.add(r.correlationId);break;case`hook_disposed`:t.delete(r.correlationId);break;case`wait_created`:n.add(r.correlationId);break;case`wait_completed`:n.delete(r.correlationId);break}return{openHook:t.size>0,openWait:n.size>0}}function ss({suspension:e,serializationBlockerCount:t,hasOpenWait:n}){return Jr()?t>0?{retain:!1,reason:`serialization_executed_workflow_code`}:e.stepCount===0&&e.attributeCount===0?{retain:!1,reason:`no_replay_driver`}:e.items.every(e=>{switch(e.type){case`step`:case`hook`:case`attribute`:return!0;case`wait`:return!1;default:throw Error(`Unknown workflow suspension item`)}})?n()?{retain:!1,reason:`open_wait`}:{retain:!0}:{retain:!1,reason:`unsupported_suspension_item`}:{retain:!1,reason:`disabled`}}function cs(e,t){return{serializationBlockerCount:t,serializationBlockers:e.map(({source:e,correlationId:t,kind:n,detail:r})=>({source:e,correlationId:t,kind:n,detail:r&&r.length>160?`${r.slice(0,160)}…`:r})),serializationBlockersTruncated:t>e.length}}function ls(e){return e.cursor===null?{type:`loadAll`}:{type:`loadAfter`,events:e.events,cursor:e.cursor}}function us(e,t){it(e.events,t.events),e.cursor=t.cursor??e.cursor}async function ds(e,t){let n=process.env.WORKFLOW_V2_TIMEOUT_MS;if(n!==void 0&&n!==``){let e=Number(n);if(Number.isFinite(e)&&e>0)return e}let r=await e.getRuntimeDeadline?.();if(r!==void 0){let e=r.getTime();if(!Number.isNaN(e)){let n=Math.floor(e-t);if(n>=(0,Er.default)(`25m`))return(0,Er.default)(`10m`);if(n>=(0,Er.default)(`10m`))return(0,Er.default)(`5m`)}}return(0,Er.default)(`2m`)}function fs(e,t){Mn(t?.basePath);let n=zn(t?.namespace),r=Vn(`workflow`,n),i=t=>t.createQueueHandler(r,async(i,a)=>{let c=Date.now(),l=_t(i);if(l){await It(l,t.specVersion);return}let{runId:d,traceCarrier:f,requestedAt:p,stepId:m,stepName:h,replayDivergence:_,preconditionReinvocations:v,deploymentMismatchRetryCount:y,runInput:b,hookInput:x,stepInput:S,hookResumeTiming:C,waitContinuation:ee}=Zn.parse(i),w=Ti(C,m===void 0?`inline`:`dispatched`);w&&m===void 0&&(w.consumerStartedAtMs=c),w&&!Number.isFinite(w.consumerStartedAtMs)&&(w=void 0);let T=Rt(f)?f:void 0,{requestId:E}=a,D=a.queueName.slice(r.length),O=G.forRun(d,D),k=Nr();if(a.attempt>k){let e=kr(void 0,q.MAX_DELIVERIES_EXCEEDED);O.error(`Workflow handler exceeded max deliveries (${a.attempt}/${k})`,{attempt:a.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await _i(),t=Et(e,d),n=new X(`Workflow exceeded maximum queue deliveries (${a.attempt}/${k})`);await e.events.create(d,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(n,d,await t()),errorCode:q.MAX_DELIVERIES_EXCEEDED}},{requestId:E})}catch(e){if(Z.is(e)||Y.is(e))return;O.error(`Failed to mark run as failed after ${a.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:a.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let j=Tt(),N=()=>st(j,T),te=await xt(j,T),P=new bi,F=j===`continuous`?T:void 0,ne=await Re(`CONSUMER`);return await Ot(F,async()=>await yt({workflowRunId:d,workflowName:D},async()=>{let t=await K(`workflow.route.get_world`,async()=>_i());if(!Zo({world:t,runInput:b,runId:d,runLogger:O}))return await Qo({world:t,runInput:b,runId:d,runLogger:O}),K(`workflow.execute ${ue(D)}`,{kind:ne,links:te},async r=>{r?.setAttributes({...ce(D),...ft(`execute_v2`),...se(`vercel-queue`),...s(a.queueName),...ut(a.messageId),...ie(`process`),...Ie({requestedAt:p}),...Se(d),...A(!!T),...At(j)});let i=Date.now(),c=await ds(t,i),l=0,f=_?new Ci(_.count):Ci.inert(),k,te,F=await Ht(t=>{if(!(!t||rr(t)))return te!==t.workflowName&&(te=t.workflowName,k=Uo(e,t.workflowName),k.catch(()=>{})),k}),ne=Tn(()=>{let e=Ne(t,d);return e.catch(()=>{}),e}),I,ae=e=>{if(!(!e||rr(e)))return I||=new jr(ne.value),I},oe=e=>{e.eventType===`run_created`&&(ae(e.eventData),F(e.eventData)),I?.prepareEvent(e)},L=async(e,n)=>{let r=de(e,n),i={...ue(),...n},a=await f.withEventCreate(r===void 0?i:{...i,sinceCursor:r},n=>t.events.create(d,e,n));return r!==void 0&&z(r,a),a},R=(e,t)=>K(`workflow.replay.load`,async n=>{let r=0;n?.setAttributes({...Se(d),...le(e)});try{let e=await t(e=>{r++,oe(e)});return r=e.events?.length??r,e}finally{n?.setAttributes(ge(r))}}),ue=()=>B.type===`loadAll`?{}:$t(B.events),de=(e,t)=>{if(!(be||B.type!==`ready`||t?.sinceCursor!==void 0||t?.preloadEvents===!0||Hn(e.eventType)))return B.cursor??void 0},z=(e,t)=>{B.type!==`ready`||B.cursor!==e||t.events===void 0||t.hasMore===!0||us(B,{events:t.events,cursor:t.cursor})},B={type:`loadAll`},V,H,U=-1,pe,he,_e=0,ve,be=qr()&&b!==void 0&&a.attempt===1&&m===void 0&&!_;r?.setAttributes(Ae(be));let xe,Ce=async()=>{if(xe)try{await xe}catch{}},W=async e=>{let n=$o(e);return n?(await ts({world:t,workflowRun:V,runId:d,requestId:E,err:e,errorCode:n,logMessage:`Fatal runtime error during workflow setup`}),!0):!1},Te=new Set,Ee=e=>{Te.size>0&&G.error(`Invariant violation: acking the workflow message while owned inline steps are still executing — crash recovery for these steps is broken`,{workflowRunId:d,ackPath:e,stepIds:[...Te]})},De=async()=>({runId:d,traceCarrier:await N(),requestedAt:new Date}),Oe=async(e,r)=>{if(Ee(`reinvoke`),!be)return{timeoutSeconds:e};await Ze(t,St(D,n),{...await De(),...r},e>0?{delaySeconds:e}:void 0)},ke=0,je=null,Me=e=>{let t=je;if(!t)return;je=null;let n=new Set(e.map(e=>e.eventId)),r=is(n,t.ids),i=is(t.ids,n),a=i>0?`shrank`:r>0?`grew`:`unchanged`;G.warn(`Restarted replay reloaded its event log after a stale-snapshot rejection`,{workflowRunId:d,outcome:a,added:r,dropped:i,eventsBefore:t.ids.size,eventsAfter:n.size,preconditionRestarts:t.restart,reason:t.reason,source:t.source,loopIteration:l})},Pe=(e,t,{allowDelta:n=!0}={})=>{if(ke>=Qr())return!1;ke++,Ve=null;let i=n&&ke===1?tt(t,d):null,a=i!==null&&B.type!==`loadAll`;return je=B.type===`loadAll`?null:{ids:new Set(B.events.map(e=>e.eventId)),restart:ke,reason:e,source:a?`inline-delta`:`full-reload`},i&&B.type!==`loadAll`?(us(B,i),B={...B,type:`ready`}):(B={type:`loadAll`},I?.resetScan()),G.warn(`Event creation rejected as stale; restarting replay in-process`,{workflowRunId:d,reason:e,loopIteration:l,preconditionRestarts:ke,source:a?`inline-delta`:`full-reload`}),r?.setAttributes({"workflow.precondition_restarts":ke}),!0},Fe=async(e,t)=>{let n=(v??0)+1,i=$r();return n>i?{reinvoked:!1,error:new J(`Event creation was rejected as stale after ${i} re-invocations of ${Qr()} in-process replay restarts each: this run cannot observe its own event log completely enough to make progress. Last rejection (${e}): ${t instanceof Error?t.message:String(t)}`,{cause:t})}:(G.warn(`Event creation rejected as stale after in-process restarts; re-invoking run for a fresh replay`,{workflowRunId:d,reason:e,loopIteration:l,preconditionReinvocations:n,maxReinvocations:i}),r?.setAttributes({"workflow.precondition_reinvocations":n}),{reinvoked:!0,result:await Oe(ei(),{preconditionReinvocations:n})})},Re=async(e,i,a)=>{let{outcome:o,spanAttributes:s}=await oi({world:t,run:e,requestId:E,retryCount:y,beforeStop:a,isDeploymentUnavailableError:t.isDeploymentUnavailableError,reenqueue:async({deploymentId:e,specVersion:r,deploymentMismatchRetryCount:a,delaySeconds:o})=>{await Ze(t,St(D,n),{...await i(),deploymentMismatchRetryCount:a},{deploymentId:e,specVersion:r,delaySeconds:o})}});return s&&r?.setAttributes(s),o};if(m&&h)try{let e=async()=>{if(!S)return`ok`;try{await t.events.create(d,{eventType:`step_created`,specVersion:7,correlationId:m,eventData:{stepName:h,workflowName:D,input:S.input}},{requestId:E,viaStepDispatch:!0}),r?.setAttributes(Le(!0)),G.warn(`Materialized step_created from the queue message — the producer’s direct write did not land`,{workflowRunId:d,stepId:m,stepName:h})}catch(e){if(Z.is(e))return`ok`;if(Y.is(e))return`gone`;throw e}return`ok`},[i,o]=await Promise.all([t.runs.get(d,{resolveData:`none`}),S&&a.attempt>1?e():`ok`]);if(o===`gone`){G.debug(`Run already finished, skipping background step`,{workflowRunId:d});return}if(i.status!==`running`){G.debug(`Run already finished, skipping background step`,{workflowRunId:d,status:i.status});return}if(await Re(i,async()=>({...await De(),stepId:m,stepName:h,...C?{hookResumeTiming:C}:{}}))!==`continue`)return;let s=i.startedAt?+i.startedAt:Date.now(),c=a.attempt,l=On(h)?.maxRetries??3;a.attempt>l+1&&(c=ri((await Ue(d)).events,m,{type:`totalAttempts`})+1);let u=w;w=void 0,P.pause();let f;try{let n=()=>Ki({world:t,workflowRunId:d,workflowDeploymentId:i.deploymentId,workflowName:D,workflowStartedAt:s,requestId:E,rootRunId:as(i.attributes,d),stepId:m,stepName:h,runSpecVersion:i.specVersion,authoritativeAttempt:c,...u?{resumeTracking:u}:{}});f=await Qi(d,m,async()=>{try{return await n()}catch(t){if(!S||!es(t))throw t;return await e()===`gone`?{type:`gone`}:await n()}})}finally{P.resume()}if(f.type===`retry`||f.type===`throttled`)return{timeoutSeconds:f.timeoutSeconds};if(f.type===`completed`&&f.hasPendingOps){await Ze(t,St(D,n),{runId:d,traceCarrier:await N(),requestedAt:new Date});return}if(f.type===`completed`||f.type===`failed`||f.type===`skipped`){let e=await Ue(d);B=ls(e);let n=new Set,r=new Set;for(let t of e.events)t.eventType===`step_created`?n.add(t.correlationId):(t.eventType===`step_completed`||t.eventType===`step_failed`)&&r.add(t.correlationId);let o=new Set;for(let e of n)r.has(e)||o.add(e);if(o.size>0)if(Yr()&&Xi(e.events,o,a.messageId))G.debug(`Background step done; falling through to recover an inline step owned by this message`,{workflowRunId:d});else{G.debug(`Background step done but other steps pending, returning`,{workflowRunId:d});return}F(i),G.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:d});let c=e.events.find(e=>e.eventType===`run_created`),l;if(c)l=c.eventData.input;else{if(!Wn(i.specVersion))throw new J(`Workflow run "${d}" has no "run_created" event`);let e=await t.runs.get(d,{resolveData:`all`});if(e.status!==`running`)return;l=e.input}V={...i,input:l,status:`running`,output:void 0,error:void 0,completedAt:void 0},U=s}else return}catch(e){let n=$o(e);if(!n)throw e;await ts({world:t,workflowRun:V,runId:d,requestId:E,err:e,errorCode:n,logMessage:`Fatal error while preparing background workflow step`});return}if(!V&&x?.deploymentId!==void 0&&t.capabilities?.deploymentAffinity===!0){let e=x.deploymentId,n;try{n=await t.getDeploymentId()}catch{n=void 0}if(n!==void 0&&n!==e&&await Re(await t.runs.get(d,{resolveData:`none`}),async()=>({...await De(),hookInput:x,...C?{hookResumeTiming:C}:{}}),Ce)!==`continue`)return}let Be=!1;if(!V&&x&&x.resumeId!==void 0&&x.payloadDigest!==void 0){let e=x,t;try{t=new Date(Un(e.resumeId))}catch{t=void 0}try{r?.addEvent(`workflow.hook_received.create.start`,{"workflow.hook_received.preload_events":!0});let n=await R(`hook_preload`,n=>L({eventType:`hook_received`,specVersion:7,correlationId:e.hookId,eventData:{token:e.token,payload:e.payload}},{requestId:E,occurredAt:t,resumeId:e.resumeId,resumePayloadDigest:e.payloadDigest,preloadEvents:!0,replayEventObserver:n}));if(Be=!0,n.run!==void 0&&n.run.startedAt!==void 0&&n.event!==void 0&&n.events!==void 0&&n.events.length>0&&n.cursor!=null&&n.hasMore===!1&&typeof n.maxEvents==`number`&&n.events.some(e=>e.eventType===`run_created`)&&n.events.some(e=>e.eventType===`run_started`)&&n.events.some(t=>t.eventType===`hook_received`&&t.resumeId===e.resumeId)&&n.run?.startedAt&&n.events){let e=n.events.find(e=>e.runId===d&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`));if(e){r?.setAttributes({...ye(e.eventType===`run_completed`?`completed`:e.eventType===`run_failed`?`failed`:`cancelled`),...Xt(`hook_received_stream`)}),G.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:d,eventType:e.eventType});return}V=n.run,F(V),H=Xo(n.maxEvents),he=Date.now(),w&&(w.setupSource=`hook_preload`),B={type:`ready`,events:n.events,cursor:n.cursor},U=+n.run.startedAt,r?.setAttributes({...ye(n.run.status),...we(U),...Xt(`hook_received_stream`)})}else r?.setAttributes(Xt(`hook_received_fallback`))}catch(e){if(_n.is(e)||Y.is(e)){G.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:d,message:e.message});return}if(await W(e))return;throw e}}if(!V){let e={eventType:`run_started`,specVersion:b?.specVersion??7,...b?{eventData:{input:b.input,deploymentId:b.deploymentId,workflowName:b.workflowName,executionContext:b.executionContext,attributes:b.attributes,allowReservedAttributes:b.allowReservedAttributes}}:{}};if(be&&b){r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":!0});let t=L(e,{requestId:E,skipPreload:!0});xe=t;try{F(b),ae(b)}catch(e){if(await Ce(),!await W(e))throw e;return}t.then(e=>{let t=Xo(e.maxEvents);t!==void 0&&(H=t)}).catch(()=>{}),B={type:`ready`,events:[],cursor:null};let n=new Date;V={runId:d,status:`running`,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,attributes:b.attributes??{},startedAt:n,createdAt:n,updatedAt:n},U=+n,he=+n,r?.setAttributes({...ye(`running`),...we(U)})}else try{r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":!1});let t=R(`run_started`,t=>L(e,{requestId:E,replayEventObserver:t}));try{F(b),ae(b)}catch(e){try{await t}catch{}throw e}let n=await t;if(V=n.run,H=Xo(n.maxEvents),he=Date.now(),w&&(w.setupSource=`run_started`),n.events?.length){let e={events:[...n.events],cursor:n.cursor??null};B=n.hasMore?ls(e):{...e,type:`ready`}}if(U=+n.run.startedAt,r?.setAttributes({...ye(n.run.status),...we(U)}),n.run.status!==`running`){G.info(`Workflow already completed or failed, skipping`,{workflowRunId:d,status:n.run.status});return}F(V)}catch(e){if(Z.is(e)||Y.is(e)){G.info(`Run already finished during setup, skipping`,{workflowRunId:d,message:e.message});return}else{if(!await W(e))throw e;return}}}if(yr(V,`Workflow run must be loaded before replay`),w&&w.setupSource===void 0&&(w.setupSource=`event_load`),await Re(V,async()=>({...await De(),...x?{hookInput:x}:{},...C?{hookResumeTiming:C}:{}}),Ce)!==`continue`)return;if(x&&!Be&&!(x.resumeId!==void 0&&B.type!==`loadAll`&&B.events.some(e=>e.eventType===`hook_received`&&e.resumeId===x.resumeId))){let e;try{e=x.resumeId===void 0?void 0:new Date(Un(x.resumeId))}catch{e=void 0}let n;try{let i=await t.events.create(d,{eventType:`hook_received`,specVersion:7,correlationId:x.hookId,eventData:{token:x.token,payload:x.payload}},{requestId:E,occurredAt:e,resumeId:x.resumeId,resumePayloadDigest:x.payloadDigest});r?.setAttributes(me(!0));let a=i.event;n=a?{...a,eventData:{token:x.token,payload:x.payload}}:void 0}catch(e){if(_n.is(e)||Y.is(e))return;throw e}B.type!==`loadAll`&&n?(mt(B.events,n),oe(n)):B={type:`loadAll`}}let Ve=null;for(;;){if(l++,P.isExhausted()){await Si({runId:d,workflowName:D,requestId:E,attempt:a.attempt,limitMs:P.configuredLimitMs,slotSnapshot:ue()});return}if(Date.now()-i>=c){G.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:d,loopIteration:l,elapsedMs:Date.now()-i}),await Ze(t,St(D,n),{runId:d,traceCarrier:await N(),requestedAt:new Date});return}let s=0,p=!1;try{if(rr(V)){G.debug(`Using QuickJS VM engine`,{workflowRunId:d,loopIteration:l}),await Ce(),B.type===`loadAfter`&&(us(B,await Ue(d,B.cursor)),B={...B,type:`ready`});let{runWorkflowWithQuickJS:t}=await import(`../../_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js`),i=await t({workflowCode:e,workflowName:D,workflowRun:V,preloadedEvents:B.type===`ready`?B.events:void 0,preloadedEventsComplete:B.type===`ready`,runInput:b,parentSpan:r,maxEventsLimit:H,namespace:n,nextTraceCarrier:N,waitContinuation:ee,deliveryAttempt:a.attempt,ownerMessageId:a.messageId,requestId:E});return i?.timeoutSeconds===void 0?void 0:await Oe(i.timeoutSeconds)}if(B.type!==`ready`){let e=await Ue(d,B.type===`loadAfter`?B.cursor:void 0);B.type===`loadAfter`?(us(B,e),B={...B,type:`ready`}):B={...e,type:`ready`}}if(yr(B.type===`ready`),Me(B.events),rs(B.events,d))return;let i=Date.now(),o=new Set(B.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),c=B.events.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!o.has(e.correlationId)&&i>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:7,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of c)try{let t=await L(e,{requestId:E});Mt(B.events,t)}catch(t){if(Z.is(t)){G.info(`Wait already completed, skipping`,{workflowRunId:d,correlationId:e.correlationId});continue}throw t}yr(B.type===`ready`);let u=new Set(B.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),m=c.filter(e=>!u.has(e.correlationId));if(m.length>0)if(B.cursor){let e=await Ue(d,B.cursor),t=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));m.every(e=>t.has(e.correlationId))?us(B,e):B={...await Ue(d),type:`ready`}}else B={...await Ue(d),type:`ready`};if(Ut()){let e=await Gt(d,{events:B.events,cursor:B.cursor});if(B={...e.log,type:`ready`},e.gap!==void 0)throw new yn(`Event log for run ${d} has a hole at slot ${e.gap.firstMissingSlot}: ${e.gap.missingCount} of the ${e.gap.maxSlot} slots up to the log's maximum hold no event.`)}if(rs(B.events,d))return;if(H!==void 0){let e=B.events.reduce((e,t)=>Xn(t)?e:e+1,0);if(e>=H)throw new vn(e,H)}pe??=B.events.every(e=>e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`||Xn(e)),G.debug(`Starting workflow execution`,{workflowRunId:d,loopIteration:l,eventCount:B.events.length,executionMode:Ve?`retained`:`replay`}),s=Date.now(),w&&(w.replayStartedAtMs??=s);let h=ae(V);yr(h,`Node workflow replay requires payload preparation`);let g=h.prewarm(V,B.events),_=Ve?await Go(Ve,B.events):{type:`replay`};if(p=Ve!==null&&_.type!==`replay`,_.type===`replay`){Ve=null;let n=F(V);yr(n,`Node workflow replay requires compiled scripts`),_=await Wo({workflowCode:e,workflowRun:V,events:B.events,encryptionKey:await ne.value,replayPayloadCache:h,compiledWorkflowScripts:await n,runReadyBarrier:xe,worldCapabilities:t.capabilities})}if(await g,_.type===`suspended`)throw Ve=_.session,_.suspension;let v=_.output;G.debug(`Workflow execution completed`,{workflowRunId:d,loopIteration:l,replayMs:Date.now()-s,executionMode:Ve?`retained`:`replay`}),f.activate();try{await Ce(),await L({eventType:`run_completed`,specVersion:7,eventData:{output:v}},{requestId:E})}catch(e){if(Z.is(e)||Y.is(e)){G.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}throw e}r?.setAttributes({...ye(`completed`)});return}catch(i){if(jn.is(i)){f.activate();let e=Date.now(),c=e-s;w&&i.stepCount>0&&(w.nextStepEncounteredAtMs??=e),G.debug(`Workflow suspended`,{workflowRunId:d,loopIteration:l,replayMs:c,steps:i.stepCount,hooks:i.hookCount,waits:i.waitCount});let m=M(i.stepCount,i.hookCount,i.waitCount);m&&G.debug(m);let h=Date.now();yr(B.type===`ready`,`Workflow suspended before its event log was loaded`);let _;try{_=await ea({suspension:i,world:t,run:V,span:r,requestId:E,eventLog:B,runReadyBarrier:xe,replayRecoveryReporter:f,stepDispatch:{queueName:St(D,n),getTraceCarrier:N},ownerMessageId:a.messageId,allowDeferredBatchWork:!0})}catch(e){if(dn.is(e)){if(Pe(`suspension-create`,e))continue;let t=await Fe(`suspension-create`,e);if(t.reinvoked)return t.result;throw t.error}if(!X.is(e))throw e;let t=ir(e);G.error(`Non-retryable error while committing workflow suspension; failing run`,{workflowRunId:d,errorCode:t,errorName:e.name,errorMessage:e.message});try{await Ce(),await L({eventType:`run_failed`,specVersion:7,eventData:{error:await g(e,d,await ne.value,globalThis,(V?.specVersion??0)>=5),errorCode:t}},{requestId:E})}catch(e){if(Z.is(e)||Y.is(e)){G.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}throw e}r?.setAttributes({...ye(`failed`),...fe(t),...Jt(e.name),...u(e.message),...qt(e.name)});return}let v=Tn(()=>(yr(B.type===`ready`),os(B.events))),y=Ve?ss({suspension:i,serializationBlockerCount:_.serializationBlockerCount,hasOpenWait:()=>v.value.openWait}):void 0;if(y?.retain===!1&&(Ve=null),_e+=_.hookCreationMs,_.hasAttributeEvents&&ve===void 0&&(ve=_e),G.debug(`Suspension handled`,{workflowRunId:d,suspensionMs:Date.now()-h,pendingSteps:_.pendingSteps.length,timeoutSeconds:_.waitTimeout?.seconds,hasHookConflict:_.hasHookConflict,hasAwaitedHookCreation:_.hasAwaitedHookCreation,hasAttributeEvents:_.hasAttributeEvents,...y?{workflowVmRetention:y.retain?`retained`:`replay`}:{},...y?.retain===!1?{workflowVmRetentionReason:y.reason}:{},..._.serializationBlockerCount>0?cs(_.serializationBlockers,_.serializationBlockerCount):{}}),_.hasHookConflict)return await Oe(0);if(_.hasAttributeEvents){B=ls(B);continue}if(_.failedStepCorrelationIds.size>0){await _.deferredBatchWork,Ve=null,B=ls(B);continue}let b=_.pendingSteps,x=_.lazyInlineSteps,S=new Set(x.map(e=>e.correlationId)),C=await N(),T=[],O=Yr(),k=Date.now(),A=[],j=0,te=w!==void 0&&x.length===0&&!b.some(e=>!S.has(e.correlationId)&&O&&qi(e)&&e.ownerMessageId===a.messageId);for(let e of b){if(S.has(e.correlationId)||_.queuedStepCorrelationIds.has(e.correlationId))continue;let r=O&&qi(e);if(r&&e.ownerMessageId===a.messageId){A.push(e);continue}let i=r?Ji(e,k):0;if(i>0){j++,G.debug(`Pending step is inline-owned by a live invocation; ensuring delayed backstop wake instead of immediate requeue`,{workflowRunId:d,stepId:e.correlationId,ownerMessageId:e.ownerMessageId,backstopDelaySeconds:i}),T.push(Ze(t,St(D,n),{runId:d,traceCarrier:C,requestedAt:new Date},{delaySeconds:i,idempotencyKey:Yi(e)}));continue}let o=te?Ei(w):void 0;o&&(te=!1,w=void 0),T.push(Ze(t,St(D,n),{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:C,requestedAt:new Date,...o?{hookResumeTiming:o}:{}},{idempotencyKey:ze(e.correlationId,e.stepName)}))}if(_.waitTimeout){let e=ee?.correlationId===_.waitTimeout.correlationId?ee.attempt+1:0;T.push(Ze(t,St(D,n),{runId:d,traceCarrier:C,requestedAt:new Date,waitContinuation:{correlationId:_.waitTimeout.correlationId,attempt:e}},ia(_.waitTimeout.seconds,_.waitTimeout.correlationId,Date.now(),e)))}let F=Promise.all(T);F.catch(()=>{});let I=[...x.map(e=>{let t=_.inlineClaims.get(e.correlationId);return t?{correlationId:e.correlationId,stepName:e.stepName,preclaimedStart:t}:{correlationId:e.correlationId,stepName:e.stepName,lazyStepInput:e.dehydratedInput}}),...A.map(e=>({correlationId:e.correlationId,stepName:e.stepName}))];if((j>0||A.length>0)&&r?.setAttributes({...A.length>0?o(A.length):{},...j>0?Kt(j):{}}),A.length>0&&G.warn(`Re-executing inline steps owned by this queue message — a previous delivery crashed mid-body and this redelivery is recovering them`,{workflowRunId:d,stepIds:A.map(e=>e.correlationId)}),I.length===0)return await Promise.all([F,_.deferredBatchWork]),_.hasAwaitedHookCreation?await Oe(0):void 0;let re=v.value,ie=typeof B.cursor==`string`&&i.stepCount===1&&i.waitCount===0&&b.length===1&&x.length===1&&A.length===0&&!_.waitTimeout&&!re.openWait,ae=re.openHook||i.hookCount>0||_.hasHookEvents,oe=be&&!_.hasAttributeEvents&&!_.waitTimeout&&!_.hasHookEvents&&!_.hasAwaitedHookCreation&&!re.openHook&&!re.openWait,se=Bi({events:B.events,invocationStartedClean:pe===!0,runCreatedAtMs:ki(d)??(be?void 0:+V.createdAt),runStartedReceivedAtMs:he,replayMs:c,preStepBlockingMs:_e,preStepBlockingBeforeAttrMs:ve,suspensionHasWaits:i.waitCount>0||_.waitTimeout!==void 0,suspensionCreatedHooks:i.hookCount>0||_.hasHookEvents,turbo:be,retained:p}),ce=$t(B.events),R=_.batchCommittedSlotCeiling,le=R!==void 0&&R>(ce.eventCount??0)?{eventCount:R}:ce,ue=w;w=void 0,P.pause();let de,z=I.map((e,n)=>{let r=()=>(yr(B.type===`ready`),Ki({world:t,workflowRunId:d,workflowDeploymentId:V.deploymentId,workflowName:D,workflowStartedAt:U,requestId:E,rootRunId:as(V.attributes,d),stepId:e.correlationId,stepName:e.stepName,runSpecVersion:V.specVersion,authoritativeAttempt:e.lazyStepInput!==void 0||e.preclaimedStart!==void 0?1:ri(B.events,e.correlationId,{type:`ownedBy`,messageId:a.messageId})+1,lazyStepInput:e.lazyStepInput,preclaimedStart:e.preclaimedStart,ownerMessageId:a.messageId,forceOptimisticStart:oe,suppressOptimisticStart:ae,runReadyBarrier:xe,slotSnapshot:le,...n===0&&(e.lazyStepInput!==void 0||e.preclaimedStart!==void 0)&&se?{latencyTracking:se}:{},...ue?{resumeTracking:ue}:{},...ie&&B.cursor?{inlineDeltaSinceCursor:B.cursor}:{},replayRecoveryReporter:f}));return Te.add(e.correlationId),(e.lazyStepInput===void 0&&e.preclaimedStart===void 0?Qi(d,e.correlationId,r):r()).finally(()=>Te.delete(e.correlationId))});for(let e of z)e.catch(()=>{});try{try{await Promise.all([F,_.deferredBatchWork])}catch(e){throw await Promise.allSettled(z),e}de=await Promise.all(z)}catch(e){if(dn.is(e)){if(Pe(`inline-claim`,e,{allowDelta:!(await Promise.allSettled(z)).some(e=>e.status===`fulfilled`&&(e.value.type===`completed`||e.value.type===`failed`||e.value.type===`retry`))}))continue;let t=await Fe(`inline-claim`,e);if(t.reinvoked)return t.result;throw t.error}throw e}finally{P.resume()}let H=[],me=!1,ge;for(let e=0;e<I.length;e++){let t=de[e],n=I[e];t.type===`retry`?H.push({step:n,delaySeconds:t.timeoutSeconds}):t.type===`throttled`?ge=Math.max(ge??0,t.timeoutSeconds):t.type===`completed`&&t.hasPendingOps&&(me=!0)}if(ge!==void 0)return await Oe(ge);if(H.length>0){let e=await N();await Promise.all(H.map(({step:r,delaySeconds:i})=>Ze(t,St(D,n),{runId:d,stepId:r.correlationId,stepName:r.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:i,idempotencyKey:ze(r.correlationId,r.stepName)})))}if(me){G.debug(`Breaking loop: inline step has pending ops`,{workflowRunId:d,loopIteration:l}),await Ze(t,St(D,n),{runId:d,traceCarrier:await N(),requestedAt:new Date});return}if(H.length>0)return;if(I.length===1){let e=de[0];if(e.type===`completed`&&e.inlineDelta){us(B,e.inlineDelta),B=e.inlineDelta.hasMore?ls(B):{...B,type:`ready`};continue}}B=ls(B)}else{let o=i;if(dn.is(i)){if(Pe(`replay-write`,i))continue;let e=await Fe(`replay-write`,i);if(e.reinvoked)return e.result;o=e.error}if(ur(i))throw O.warn(`Transient world error during replay; redelivering via queue instead of failing the run`,{errorName:i instanceof Error?i.name:`UnknownError`,errorMessage:i instanceof Error?i.message:String(i),deliveryAttempt:a.attempt}),i;let c;if(mn.is(i)){let e=(_?.count??0)+1,r=Zr();if(e<=r){O.warn(`Workflow replay diverged; queueing a recovery replay before declaring the event log corrupted`,{errorCode:q.REPLAY_DIVERGENCE,divergenceEventId:i.eventId,priorDivergenceEventId:_?.eventId,divergenceCount:e,deliveryAttempt:a.attempt,maxRecoveryReplays:r,errorMessage:i.message}),await Ze(t,St(D,n),{runId:d,traceCarrier:await N(),requestedAt:new Date,replayDivergence:{eventId:i.eventId,count:e}});return}c=e,o=new yn(`Workflow replay diverged ${e} times after ${r} recovery replays; latest divergent event was ${i.eventId}. Last divergence: ${i.message}`,{cause:i})}else s>0&&f.activate();o instanceof Error&&r?.recordException?.(o);let l=await Ii(o),p=l.name||Ai(o),m=l.message,h=l.stack||ji(o);if(h){let t=re(D)?.moduleSpecifier||D;h=lo(h,t,e)}let v=ir(o);G.error(`Error while running workflow`,{workflowRunId:d,errorCode:v,errorName:p,errorStack:h}),vr.isNativeError(o)&&h&&(o.stack=h);try{await Ce(),await L({eventType:`run_failed`,specVersion:7,eventData:{error:await g(o,d,await ne.value,globalThis,(V?.specVersion??0)>=5),errorCode:v}},{requestId:E,...c===void 0?{}:{replayDivergenceCount:c}})}catch(e){if(Z.is(e)||Y.is(e)){G.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}if(sr(e)){G.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:d,errorCode:q.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...ye(`failed`),...fe(v),...Jt(p),...u(m),...qt(p)});return}}}})}))}),a,l=0,d=Date.now(),f=typeof t?.routeModuleBodyStartedAt==`number`?d-t.routeModuleBodyStartedAt:void 0;return Zt(async e=>{l+=1;let t=a!==void 0;return K(`workflow.route.flow`,{kind:await Re(`SERVER`),attributes:{...c(`flow`),...tn(Mr),...F(t),...H(l),...D(Date.now()-d),...f===void 0?{}:rn(f),...h(e.method),...pt(`/.well-known/workflow/v1/flow`)}},async t=>{a||=await K(`workflow.route.init`,async()=>{let e=await K(`workflow.route.get_world_handlers`,async()=>_i());return i(e)});let n=await a(e);return n instanceof Response&&t?.setAttributes(R(n.status)),n})})}export{pr as Run,jn as WorkflowSuspension,dr as cancelRun,ar as cancelRuns,hi as createWorld,pi as createWorldFromModule,er as getHookByToken,cr as getRun,_i as getWorld,gi as getWorldHandlers,Ve as healthCheck,tr as listStreams,lr as readStream,fr as recreateRunFromExisting,nr as reenqueueRun,Qn as resumeHook,$n as resumeWebhook,vi as setWorld,mr as start,or as wakeUpRun,fs as workflowEntrypoint};
|
|
1
|
+
import{a as e,i as t,t as n}from"../../_chunks/workflow/rolldown-runtime-8V8biNmG.js";import{t as r}from"../../_chunks/workflow/global-singleton-BNinwFrL.js";import{$ as i,$t as a,An as o,At as s,Bn as c,Bt as l,Cn as u,Cr as d,D as f,Dn as p,Dr as m,Dt as h,E as g,En as _,Er as v,Fn as y,Ft as b,G as x,Gn as S,Gt as C,H as ee,Hn as w,Ht as T,I as E,In as D,It as O,J as te,Jn as k,Jt as A,K as j,Kn as M,Kt as ne,L as N,Ln as P,Lt as F,Mn as I,Mr as L,Mt as re,Nn as ie,Nr as ae,Nt as oe,O as R,On as se,Ot as ce,Pn as z,Pr as le,Pt as ue,Q as B,Qt as V,R as H,Rn as U,Rt as de,Sn as fe,Sr as pe,St as me,T as he,Tn as ge,Tr as _e,U as ve,Un as ye,Ut as be,V as xe,Vn as Se,Vt as Ce,W,Wn as we,Wt as Te,X as Ee,Xn as De,Xt as Oe,Y as ke,Yn as Ae,Yt as je,Z as G,Zt as Me,_ as Ne,_n as Pe,_t as Fe,a as Ie,an as Le,at as Re,b as ze,bn as Be,c as Ve,cn as He,d as Ue,dn as We,dr as Ge,dt as Ke,en as qe,et as Je,f as Ye,fn as Xe,ft as K,g as Ze,gn as Qe,gr as $e,gt as et,h as tt,hn as nt,hr as rt,i as it,in as at,ir as ot,it as st,j as ct,jn as lt,jt as ut,k as dt,kn as ft,kt as pt,l as mt,ln as ht,lt as gt,m as _t,mn as vt,mt as yt,nn as bt,nt as xt,o as St,on as Ct,or as wt,ot as Tt,p as Et,pn as Dt,pt as Ot,q as kt,qn as At,qt as jt,r as Mt,rn as Nt,rr as Pt,rt as Ft,s as It,sn as Lt,st as Rt,t as zt,tn as Bt,tr as Vt,tt as Ht,u as Ut,un as Wt,v as Gt,vn as Kt,vt as qt,wn as Jt,wr as Yt,wt as Xt,x as Zt,xn as Qt,y as $t,yn as en,yt as tn,z as nn,zn as rn,zt as an}from"../../_chunks/workflow/wait-until-l-cwfJvm.js";import{A as on,M as sn,N as cn,P as ln,S as un,a as dn,c as fn,d as q,i as J,j as Y,k as X,l as pn,m as mn,n as hn,o as gn,r as Z,s as _n,t as vn,u as yn,v as bn,w as xn,y as Sn}from"../../_chunks/workflow/dist-DMQ3CtWt.js";import{a as Cn,c as wn,d as Tn,f as En,i as Dn,l as Q,n as On,t as kn,u as An}from"../../_chunks/workflow/private-CKx3PkSS.js";import{a as jn,n as Mn}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{d as Nn,l as Pn,n as Fn,s as In,u as Ln}from"../../_chunks/workflow/attribute-changes-03lzo29R.js";import{D as Rn,O as zn,T as Bn,Z as Vn,a as Hn,at as Un,c as Wn,nt as Gn,o as Kn,p as qn,s as Jn,st as Yn,w as Xn}from"../../_chunks/workflow/dist-BIdMK5N8.js";import{n as Zn,r as Qn,t as $n}from"../../_chunks/workflow/resume-hook-C6eL-S_T.js";import{a as er,c as tr,d as nr,f as rr,i as ir,l as ar,m as or,n as sr,o as cr,p as lr,r as ur,s as dr,t as fr,u as pr}from"../../_chunks/workflow/run-BV0S6Zc2.js";import{t as mr}from"../../_chunks/workflow/run-id-BdE0MZz9.js";import{createRequire as hr}from"node:module";import{createHash as gr}from"node:crypto";import{types as _r}from"node:util";import vr from"node:assert/strict";import{pathToFileURL as yr}from"node:url";import{Script as br,createContext as xr,runInContext as Sr}from"node:vm";function Cr(e=process.env){return e.WORKFLOW_TARGET_WORLD||(e.VERCEL_DEPLOYMENT_ID?`vercel`:`local`)}function wr(e){return e===`vercel`||e===`@workflow/world-vercel`}var Tr=e(cn(),1);function Er(e){return e instanceof Ln||e instanceof Pn||e instanceof Nn||e instanceof Fn}const Dr=`The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.`;function Or(e,t){let n=t??rr(e);return mn.is(e)?{attribution:`user`,errorCode:n,hint:`A value passed across a workflow/step boundary could not be serialized. See the error message for the offending path and the Learn More link for details.`}:Er(e)?{attribution:`user`,errorCode:n,hint:`A workflow-only or step-only API was called from the wrong context. The error message includes the exact API and how to move the call.`}:vn.is(e)?{attribution:`sdk`,errorCode:n,hint:Dr}:n===Y.DEPLOYMENT_MISMATCH?{attribution:`sdk`,errorCode:n,hint:`The run was delivered to a deployment other than the deployment it is pinned to, and was stopped to protect against code-skew errors after the runtime failed to re-route it there. Verify that the run's deployment is still available and that queue callbacks route to it.`}:e instanceof X?{attribution:`sdk`,errorCode:n,hint:`This is an internal workflow SDK error, not a bug in your code. If it keeps happening, please report it with the stack trace and the runId.`}:n===Y.REPLAY_TIMEOUT?{attribution:`sdk`,errorCode:n,hint:'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only — step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.'}:n===Y.MAX_DELIVERIES_EXCEEDED?{attribution:`sdk`,errorCode:n,hint:`The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure — check the most recent stack traces for the underlying cause.`}:n===Y.MAX_EVENTS_EXCEEDED?{attribution:`user`,errorCode:n,hint:`The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function — e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.`}:n===Y.CORRUPTED_EVENT_LOG?{attribution:`sdk`,errorCode:n,hint:Dr}:n===Y.STREAM_ERROR?{attribution:`sdk`,errorCode:n,hint:`Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure, not an error in your workflow code; please retry the run and report persistent failures with the runId.`}:n===Y.WORLD_CONTRACT_ERROR?{attribution:`sdk`,errorCode:n,hint:`The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.`}:{attribution:`user`,errorCode:n}}function kr(e){if(e===null)return!0;let t=typeof e;return!(t===`object`||t===`function`)}var Ar=class{preparer;preparedPayloads=new Map;primitiveStepResults=new Map;encryptionKey;nextUnscannedEventIndex=0;constructor(e,t=xe){this.preparer=t,this.encryptionKey=Promise.resolve(e)}prepareEvent(e){this.prepareEventIfMissing(e)?.catch(()=>{})}async prewarm(e,t){let n=[],r=this.startPreparation(this.workflowInputKey(e.runId),e.input);r&&n.push(r);for(let e=this.nextUnscannedEventIndex;e<t.length;e++){let r=t[e],i=this.prepareEventIfMissing(r);i&&n.push(i)}this.nextUnscannedEventIndex=t.length,await Promise.allSettled(n)}resetScan(){this.nextUnscannedEventIndex=0}prepareWorkflowInput(e){return this.consumePreparation(this.workflowInputKey(e.runId),e.input)}prepareEventPayload(e,t,n){return this.consumePreparation(this.eventPayloadKey(e,t),n)}async getStepResult(e,t){if(this.primitiveStepResults.has(e))return this.primitiveStepResults.get(e);let n=await t();return kr(n)&&this.primitiveStepResults.set(e,n),n}consumePreparation(e,t){if(!(t instanceof Uint8Array))return this.runPreparation(t);let n=this.ensurePreparation(e,t);return n.catch(()=>{this.preparedPayloads.get(e)===n&&this.preparedPayloads.delete(e)}),n}ensurePreparation(e,t){let n=this.preparedPayloads.get(e);if(n)return n;let r=this.runPreparation(t);return this.preparedPayloads.set(e,r),r}async runPreparation(e){return this.preparer(e,await this.encryptionKey)}prepareEventIfMissing(e){let t,n;switch(e.eventType){case`run_created`:return this.startPreparation(this.workflowInputKey(e.runId),e.eventData.input);case`run_started`:return this.startPreparation(this.workflowInputKey(e.runId),e.eventData?.input);case`step_completed`:t=`result`,n=e.eventData?.result;break;case`step_failed`:t=`error`,n=e.eventData?.error;break;case`hook_received`:t=`payload`,n=e.eventData?.payload;break;default:return}return this.startPreparation(this.eventPayloadKey(e.eventId,t),n)}startPreparation(e,t){if(!(!(t instanceof Uint8Array)||this.preparedPayloads.has(e)))return this.ensurePreparation(e,t)}workflowInputKey(e){return`run:${e}:input`}eventPayloadKey(e,t){return`event:${e}:${t}`}};const jr=`cinst_${Jn()}`;function Mr(){return zn(`WORKFLOW_MAX_QUEUE_DELIVERIES`,48,{integer:!0,min:1,max:48})}const Nr=24e4,Pr=3e4,Fr=78e4,Ir=r(`@workflow/core//envWarnings`,1,()=>({replayTimeoutValues:new Set,maxInlineStepsValues:new Set,maxEventsValues:new Set}));function Lr(e,t,n){Ir.replayTimeoutValues.has(e)||(Ir.replayTimeoutValues.add(e),G.warn(t,n))}function Rr(){let e=process.env.WORKFLOW_REPLAY_TIMEOUT_MS;if(!e)return Nr;let t=Number(e);return!Number.isFinite(t)||t<=0?(Lr(e,`Ignoring WORKFLOW_REPLAY_TIMEOUT_MS: not a positive finite number; using default`,{raw:e,defaultMs:Nr}),Nr):t<3e4?(Lr(e,`WORKFLOW_REPLAY_TIMEOUT_MS below minimum; clamped`,{raw:e,clampedMs:Pr,minMs:Pr}),Pr):t>78e4?(Lr(e,`WORKFLOW_REPLAY_TIMEOUT_MS above maximum; clamped`,{raw:e,clampedMs:Fr,maxMs:Fr}),Fr):t}function zr(){return zn(`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`,3,{integer:!0})}function Br(){let e=process.env.WORKFLOW_MAX_INLINE_STEPS;if(!e)return 3;let t=Number(e);return!Number.isInteger(t)||t<=0?(Ir.maxInlineStepsValues.has(e)||(Ir.maxInlineStepsValues.add(e),G.warn(`Ignoring WORKFLOW_MAX_INLINE_STEPS: not a positive integer; using default`,{raw:e,defaultValue:3})),3):t<1?1:t>16?(Ir.maxInlineStepsValues.has(e)||(Ir.maxInlineStepsValues.add(e),G.warn(`WORKFLOW_MAX_INLINE_STEPS above maximum; clamped`,{raw:e,clampedValue:16,maxValue:16})),16):t}function Vr(){return process.env.WORKFLOW_RESILIENT_STEP_DISPATCH===`1`}function Hr(){let e=process.env.WORKFLOW_BATCH_TRANSITIONS;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Ur(){let e=process.env.WORKFLOW_MAX_EVENTS_OVERRIDE;if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0){Ir.maxEventsValues.has(e)||(Ir.maxEventsValues.add(e),G.warn(`Ignoring WORKFLOW_MAX_EVENTS_OVERRIDE: not a positive integer; using server limit`,{raw:e}));return}return t}function Wr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`1`||e.toLowerCase()===`true`}function Gr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`0`||e.toLowerCase()===`false`}function Kr(){let e=process.env.WORKFLOW_TURBO;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function qr(){let e=process.env.WORKFLOW_RETAINED_VM;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Jr(){let e=process.env.WORKFLOW_INLINE_OWNERSHIP;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function Yr(){return zn(`WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`,860,{integer:!0,min:1,max:900})}function Xr(){return zn(`WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`,3,{integer:!0})}function Zr(){return zn(`WORKFLOW_PRECONDITION_MAX_INPROCESS_RESTARTS`,3,{integer:!0})}function Qr(){return zn(`WORKFLOW_PRECONDITION_MAX_REINVOCATIONS`,5,{integer:!0})}function $r(){return zn(`WORKFLOW_PRECONDITION_REINVOKE_DELAY_SECONDS`,2,{integer:!0})}function ei(){return zn(`WORKFLOW_DEPLOYMENT_MISMATCH_MAX_RETRIES`,3,{integer:!0,min:0})}const ti=e=>`eventData`in e&&e.eventData&&`ownerMessageId`in e.eventData&&typeof e.eventData.ownerMessageId==`string`?e.eventData.ownerMessageId:void 0;function ni(e,t,n){if(!e)return 0;let r=0,i=new Map;for(let n of e){if(n.eventType!==`step_started`||n.correlationId!==t)continue;let e=ti(n);e===void 0?r++:i.set(e,(i.get(e)??0)+1)}if(n===void 0){let e=r;for(let t of i.values())e+=t;return e}if(n.type===`ownedBy`)return i.get(n.messageId)??0;let a=0;for(let e of i.values())e>a&&(a=e);return r+a}const ri={outcome:`continue`};function ii(e,t,n){return{outcome:e,spanAttributes:{...w(t),...Qt(n),...Be(e===`rerouted`)}}}async function ai({world:e,run:t,requestId:n,retryCount:r=0,reenqueue:i,isDeploymentUnavailableError:a,beforeStop:o}){if(e.capabilities?.deploymentAffinity!==!0)return ri;let s=await e.getDeploymentId();if(t.deploymentId===s)return ri;await o?.();let c=ei(),l={workflowRunId:t.runId,pinnedDeploymentId:t.deploymentId,actualDeploymentId:s,retryCount:r,maxRetries:c},u=async(r,i)=>{let a=new un(t.runId,t.deploymentId,s,{recoveryAttempts:r,cause:i});try{await e.events.create(t.runId,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(a,t.runId,void 0,void 0,(t.specVersion??0)>=5),errorCode:Y.DEPLOYMENT_MISMATCH}},{requestId:n})}catch(e){if(!Z.is(e)&&!q.is(e))throw e}return ii(`failed`,t.deploymentId,r)};if(i&&r<c){let e=r+1,n=Math.min(2**r,8);try{return await i({deploymentId:t.deploymentId,specVersion:t.specVersion,deploymentMismatchRetryCount:e,delaySeconds:n}),G.warn(`Workflow run received by a deployment it is not pinned to; re-routing to its own deployment`,{...l,attempt:e,delaySeconds:n}),ii(`rerouted`,t.deploymentId,e)}catch(t){if(!a?.(t))throw t;return G.error(`Cannot re-route a misrouted workflow run to its own deployment; failing the run`,{...l,attempt:e,errorMessage:t instanceof Error?t.message:String(t)}),u(0,t)}}return G.error(r>0?`Workflow run kept arriving at a deployment it is not pinned to after re-routing; failing the run`:`Workflow run received by a deployment it is not pinned to; failing the run`,l),u(r)}function oi(){throw Error(`Unsupported in eve: @workflow/core createWorld(). eve selects and wires the workflow world explicitly at build time.`)}function si(){try{return hr(yr(process.cwd()+`/package.json`).href)}catch{return hr(import.meta.url)}}const ci=Symbol.for(`@workflow/world//cache`),li=Symbol.for(`@workflow/world//stubbedCache`),ui=Symbol.for(`@workflow/world//cachePromise`),di=Symbol.for(`@workflow/world//stubbedCachePromise`),$=globalThis;function fi(e){if(typeof e.createWorld==`function`)return e.createWorld();if(typeof e.default==`function`)return e.default();if(e.default&&typeof e.default==`object`)return e.default;throw Error(`Invalid target world module: must export createWorld(), a default factory, or a default World instance.`)}function pi(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return yr(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return yr(process.cwd()+`/`+e).href;try{return yr(si().resolve(e)).href}catch{return e}}const mi=async()=>{let e=Cr();if(wr(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),oi()}if(e===`local`)return oi({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=si()(e)}catch{t=await import(pi(e))}if(typeof t==`function`)return t();try{return await fi(t)}catch{throw Error(`Invalid target world module: ${e}, must export a createWorld function or a default function that returns a World instance.`)}},hi=async()=>{if($[li])return Ge($[li]),$[li];$[di]||($[di]=mi().catch(e=>{throw $[di]=void 0,e}));let e=await $[di];return Ge(e),$[li]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},gi=async()=>$[ci]?(Ge($[ci]),$[ci]):($[ui]||($[ui]=mi().catch(e=>{throw $[ui]=void 0,e})),$[ci]=await $[ui],Ge($[ci]),$[ci]),_i=e=>{$[ci]=e,$[li]=e,$[ui]=void 0,$[di]=void 0},vi=Symbol.for(`@workflow/world//getWorldFn`);globalThis[vi]??=gi;var yi=class{limitMs;elapsedMs=0;intervalStart;constructor(e=Rr()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}},bi=class extends Error{name=`ReplayTimeoutRetryError`};async function xi(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a,slotSnapshot:o}=e,s=G.forRun(t,n),c=zr();if(i<=c)throw s.warn(`Workflow replay exceeded timeout; retrying delivery`,{timeoutMs:a,attempt:i,maxRetries:c}),new bi(`Workflow replay exceeded maximum duration (${a/1e3}s)`);let l=await gi(),u=Or(void 0,Y.REPLAY_TIMEOUT);s.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:c,errorCode:u.errorCode,errorAttribution:u.attribution});let d=Et(l,t),f=new J(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await l.events.create(t,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(f,t,await d()),errorCode:Y.REPLAY_TIMEOUT}},{requestId:r,...o})}var Si=class{divergenceCount;active=!1;reported=!1;constructor(e){this.divergenceCount=e}static inert(){return new Ci}activate(){this.active=!0}async withEventCreate(e,t){if(!this.active||this.reported)return t(e);this.reported=!0;try{return await t({...e,replayDivergenceCount:this.divergenceCount})}catch(e){throw this.reported=!1,e}}},Ci=class extends Si{constructor(){super(0)}activate(){}};function wi(e,t){if(e&&!(!Number.isFinite(e.resumeRequestedAtMs)||!Number.isFinite(e.queuePublishRequestedAtMs)))return{trigger:`hook`,...e.strategy===`lazy`||e.strategy===`parallel`||e.strategy===`sequential`?{strategy:e.strategy}:{},resumeRequestedAtMs:e.resumeRequestedAtMs,queuePublishRequestedAtMs:e.queuePublishRequestedAtMs,consumerStartedAtMs:e.consumerStartedAtMs??NaN,...e.replayStartedAtMs===void 0?{}:{replayStartedAtMs:e.replayStartedAtMs},...e.nextStepEncounteredAtMs===void 0?{}:{nextStepEncounteredAtMs:e.nextStepEncounteredAtMs},...e.setupSource===`hook_preload`||e.setupSource===`run_started`||e.setupSource===`event_load`?{setupSource:e.setupSource}:{},stepExecution:t}}function Ti(e){if(e&&Number.isFinite(e.consumerStartedAtMs))return{resumeRequestedAtMs:e.resumeRequestedAtMs,queuePublishRequestedAtMs:e.queuePublishRequestedAtMs,...e.strategy===void 0?{}:{strategy:e.strategy},consumerStartedAtMs:e.consumerStartedAtMs,...e.replayStartedAtMs===void 0?{}:{replayStartedAtMs:e.replayStartedAtMs},...e.nextStepEncounteredAtMs===void 0?{}:{nextStepEncounteredAtMs:e.nextStepEncounteredAtMs},...e.setupSource===void 0?{}:{setupSource:e.setupSource}}}function Ei(e){let t=[e.resumeRequestedAtMs,e.queuePublishRequestedAtMs,e.consumerStartedAtMs,e.replayStartedAtMs,e.nextStepEncounteredAtMs,e.stepClaimStartedAtMs,...e.stepClaimCompletedAtMs===void 0?[]:[e.stepClaimCompletedAtMs],e.stepCodeStartedAtMs];for(let e of t)if(typeof e!=`number`||!Number.isFinite(e))return;for(let e=1;e<t.length;e++)if(t[e]<t[e-1])return;return t}function Di(e){let{tracking:t}=e;if(!t||e.attempt!==1||t.replayStartedAtMs===void 0||t.nextStepEncounteredAtMs===void 0||e.stepClaimStartedAtMs===void 0)return;let n={resumeRequestedAtMs:t.resumeRequestedAtMs,queuePublishRequestedAtMs:t.queuePublishRequestedAtMs,consumerStartedAtMs:t.consumerStartedAtMs,replayStartedAtMs:t.replayStartedAtMs,nextStepEncounteredAtMs:t.nextStepEncounteredAtMs,stepClaimStartedAtMs:e.stepClaimStartedAtMs,stepClaimCompletedAtMs:e.stepClaimCompletedAtMs,stepCodeStartedAtMs:e.stepCodeStartedAtMs};if(!Ei(n))return;let{resumeRequestedAtMs:r,queuePublishRequestedAtMs:i,consumerStartedAtMs:a,replayStartedAtMs:o,nextStepEncounteredAtMs:s,stepClaimStartedAtMs:c,stepClaimCompletedAtMs:u,stepCodeStartedAtMs:d}=n;return{...jt(d-r),...F(i-r),...de(a-i),...l(o-a),...an(s-o),...be(c-s),...u===void 0?{}:T(u-c),...C(d-(u??c)),...A(t.trigger),...t.strategy===void 0?{}:ne(t.strategy),...t.setupSource===void 0?{}:Ce(t.setupSource),...Te(t.stepExecution)}}function Oi(e){let t=e.startsWith(`wrun_`)?e.slice(5):e;try{return Hn(mr(t).ulid)}catch{return}}function ki(e){return _r.isNativeError(e)?e.name:`Error`}function Ai(e){return _r.isNativeError(e)?e.stack??``:``}function ji(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function Mi(e){if(!ji(e)||J.is(e))return e;let t=new J(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function Ni(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Pi(e){if(_r.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function Fi(e){if(Ni(e))try{let t=await Fi(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await Fi(e);return{...t,message:`Promise rejection: ${t.message}`}}return Pi(e)}const Ii=r(`@workflow/core//devServerPort`,1,()=>({getPort:void 0,cachedPort:void 0,inFlight:void 0}));async function Li(){if(Ii.cachedPort!==void 0)return Ii.cachedPort;if(Ii.inFlight)return Ii.inFlight;if(!Ii.getPort)try{let e=[`@workflow/utils`,`get-port`].join(`/`),t=hr(yr(process.cwd()+`/package.json`).href)(e);Ii.getPort=t.getPort}catch{Ii.getPort=async()=>void 0}let e=Ii.getPort??(async()=>void 0);return Ii.inFlight=e().then(e=>(typeof e==`number`&&(Ii.cachedPort=e),e)).finally(()=>{Ii.inFlight=void 0}),Ii.inFlight}const Ri=new Set([`step_created`,`step_started`,`step_completed`,`step_failed`,`step_retrying`,`hook_received`,`wait_created`,`wait_completed`]);function zi(e){let{events:t}=e,n=e.invocationStartedClean&&e.runCreatedAtMs!==void 0&&!e.suspensionHasWaits,r;if(n)for(let e of t){if(Ri.has(e.eventType)){n=!1;break}if(e.eventType===`attr_set`){let t=+(e.occurredAt??e.createdAt);r=r===void 0?t:Math.min(r,t)}}let i,a,o,s=t[t.length-1];if(!e.suspensionHasWaits&&!e.suspensionCreatedHooks&&s&&(s.eventType===`step_completed`||s.eventType===`step_failed`)){i=+(s.occurredAt??s.createdAt);let e=new Set;for(let n of t)(n.eventType===`step_completed`||n.eventType===`step_failed`)&&n.correlationId!==void 0&&e.add(n.correlationId);a=e.size,o=t.length}let c=n&&e.runStartedReceivedAtMs!==void 0;if(!(!n&&i===void 0))return{...n?{ttfsAnchorMs:e.runCreatedAtMs,preStepBlockingMs:r===void 0?e.preStepBlockingMs:e.preStepBlockingBeforeAttrMs??0,...r===void 0?{}:{preStepAttrStartMs:r}}:{},...c?{rsfsAnchorMs:e.runStartedReceivedAtMs}:{},...i===void 0?{}:{prevStepEndMs:i,stepCount:a,eventCount:o},replayMs:e.replayMs,turbo:e.turbo,retained:e.retained}}function Bi(e){let{tracking:t}=e;if(!t||e.attempt!==1)return;let n=t.preStepAttrStartMs??e.stepCodeStartedAtMs,r=t.ttfsAnchorMs===void 0?void 0:n-t.ttfsAnchorMs-(t.preStepBlockingMs??0),i=r!==void 0&&r>=-6e4?Math.max(0,r):void 0,a=t.prevStepEndMs===void 0?void 0:e.stepCodeStartedAtMs-t.prevStepEndMs,o=a!==void 0&&a>=-6e4?Math.max(0,a):void 0,s=t.rsfsAnchorMs!==void 0&&e.stepStartPostSentAtMs!==void 0?Math.max(0,e.stepStartPostSentAtMs-t.rsfsAnchorMs):void 0,c=t.replayMs===void 0?void 0:Math.max(0,t.replayMs);if(i===void 0&&o===void 0)return;let l=[];return t.turbo&&l.push(`turbo`),e.lazyStepStart&&l.push(`lazyStepStart`),e.optimisticStart&&l.push(`optimisticStart`),e.preclaimedStart&&l.push(`preclaimedStart`),t.retained&&l.push(`retained`),{...i===void 0?{}:{ttfs:i},...o===void 0?{}:{stso:o},...o!==void 0&&t.stepCount!==void 0?{stepCount:t.stepCount}:{},...o!==void 0&&t.eventCount!==void 0?{eventCount:t.eventCount}:{},...s===void 0?{}:{rsfs:s},...c===void 0?{}:{finalSchedulingReplay:c},optimizations:l}}const Vi=`__workflowUnserializableStepInput`;function Hi(){return{args:[`[input unavailable: step argument serialization failed]`],closureVars:[],thisVal:void 0,[Vi]:!0}}function Ui(e){return typeof e==`object`&&!!e&&e[Vi]===!0}function Wi(e,t){if(t&&!(!e.events||e.cursor===void 0))return{events:e.events,cursor:e.cursor,hasMore:e.hasMore??!1}}async function Gi(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:i,stepId:o,stepName:s}=e,c=!!process.env.VERCEL_URL,l=(e.runSpecVersion??0)>=5,u=e.replayRecoveryReporter??Si.inert(),d=e.slotSnapshot?.eventCount,f=e=>{if(d===void 0)return;let t=[];e.event&&t.push(qn(e.event.eventId));let n=Ye(e.events??[]);n!==void 0&&t.push(n);for(let e of t)e>d&&(d=e)},p=async(e,r)=>{let i=await u.withEventCreate(d===void 0?r:{eventCount:d,...r},r=>t.events.create(n,e,r));return f(i),i},m={computeInstanceId:jr,...e.requestId?{requestId:e.requestId}:{}};return K(`step.execute ${ae(s)}`,{},async u=>{if(u?.setAttributes({...at(s),...se(r),...Se(n),...Bt(o)}),vr(!(e.lazyStepInput!==void 0&&e.preclaimedStart),`executeStep: lazyStepInput and preclaimedStart are mutually exclusive`),e.preclaimedStart&&e.preclaimedStart.owned===!1)return G.debug(`Pre-claimed step start lost, skipping`,{stepName:s,stepId:o,workflowRunId:n}),u?.setAttributes({...Dt(!0),...Xe(`running`)}),{type:`skipped`};let d=Et(t,n),f=On(s);if(!f||typeof f!=`function`){let t=`Step "${s}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`;if(G.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:s,stepId:o}),e.lazyStepInput!==void 0)try{e.runReadyBarrier&&await e.runReadyBarrier.catch(()=>{}),await p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},m)}catch(e){if(Z.is(e))return{type:`skipped`};if(q.is(e))return{type:`gone`};throw e}try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(new J(t),n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...a(!0)}),{type:`failed`}}let h=f.maxRetries??3;if(u?.setAttributes({...Nt(h)}),e.authoritativeAttempt!==void 0&&e.authoritativeAttempt>h+1){let t=h,r=`Step "${s}" exceeded max retries (${t} ${ln(`retry`,`retries`,t)})`;B.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,stepId:o,attempt:e.authoritativeAttempt,maxRetries:h});try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(new J(r),n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return G.info(`Tried failing step for exceeded retries, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e instanceof Error?e.message:String(e)}),{type:`skipped`};if(q.is(e))return{type:`gone`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}let g=e=>{if(bn.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return G.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(q.is(e))return G.info(`Workflow run "${n}" has already completed, skipping step "${o}": ${e.message}`),{type:`gone`};if(Z.is(e))return G.debug(`Step in terminal state, skipping`,{stepName:s,stepId:o,workflowRunId:n,error:e instanceof Error?e.message:String(e)}),u?.setAttributes({...Dt(!0),...Xe(`completed`)}),{type:`skipped`};if(Sn.is(e)){let t=Math.max(1,e.retryAfter??1);return G.debug(`Step retryAfter timestamp not yet reached`,{stepName:s,stepId:o,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}},_=e.preclaimedStart===void 0&&e.lazyStepInput!==void 0&&e.suppressOptimisticStart!==!0&&(Wr()||e.forceOptimisticStart===!0&&!Gr()),v,y=m,x,S,C,ee=async()=>{if(!C)return;let e=await C;if(e.ok)return;let t=g(e.err);if(!t)throw e.err;return t};if(e.preclaimedStart?.owned)v=e.preclaimedStart.step,x=e.preclaimedStart.batchPostSentAtMs,S=e.preclaimedStart.claimCompletedAtMs;else if(_){C=(e.runReadyBarrier??Promise.resolve()).then(()=>(x=Date.now(),p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},y))).then(()=>({ok:!0}),e=>({ok:!1,err:e}));let t=new Date;v={runId:n,stepId:o,stepName:s,status:`running`,input:e.lazyStepInput,attempt:1,startedAt:t,createdAt:t,updatedAt:t}}else try{let t=e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId};x=Date.now();let n=await p({eventType:`step_started`,specVersion:7,correlationId:o,eventData:e.lazyStepInput===void 0?{stepName:s,...t}:{stepName:s,workflowName:r,input:e.lazyStepInput,...t}},y);S=Date.now(),v=n.step}catch(e){let t=g(e);if(t)return t;throw e}G.debug(`Step execution details`,{stepName:s,stepId:v.stepId,status:v.status,attempt:v.attempt}),u?.setAttributes({...vt(v.status)});let w;if(v.attempt>h+1&&v.error){let e=v.attempt-1,t=`Step "${s}" exceeded max retries (${e} ${ln(`retry`,`retries`,e)})`;B.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,retryCount:e});let r=new J(t);if(v.error!=null)try{r.cause=await N(v.error,n,await d())}catch{}try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(r,n,await d(),[],globalThis,l)}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}let T=[],D=[],te=!0,k,A=()=>{if(!k||k.rsfs!==void 0)return;let t=e.latencyTracking?.rsfsAnchorMs;t===void 0||x===void 0||(k.rsfs=Math.max(0,x-t),u&&u.setAttributes({...We(k.rsfs)}))};try{let t=v.attempt;if(!v.startedAt)throw new X(`Step "${o}" has no "startedAt" timestamp`);let a=v.startedAt,p=e.encryptionKey??await d(),m=await K(`step.hydrate`,{},async t=>{let r=Date.now(),i=await E(v.input,n,p,D,globalThis,{},e.workflowDeploymentId),a=Date.now()-r;return t?.setAttributes({...je(i.args.length),...ue(a)}),i});if(Ui(m)){let{message:e,hint:t}=Ee(`step arguments`,void 0);throw new mn(e,{hint:t})}let h=m.args,g=m.thisVal??null,y=Mn(c?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Li()??3e3}`),C,j=!1,M=Date.now();k=Bi({tracking:e.latencyTracking,stepCodeStartedAtMs:M,attempt:t,lazyStepStart:e.lazyStepInput!==void 0,optimisticStart:_,preclaimedStart:e.preclaimedStart!==void 0,stepStartPostSentAtMs:x}),k&&u?.setAttributes({...k.ttfs===void 0?{}:Qe(k.ttfs),...k.stso===void 0?{}:nt(k.stso),...k.rsfs===void 0?{}:We(k.rsfs),...k.finalSchedulingReplay===void 0?{}:qe(k.finalSchedulingReplay),...bt(k.optimizations??[])});let ne=()=>{let n=e.resumeTracking;if(!n||n.reported)return;let r=Di({tracking:n,attempt:t,stepClaimStartedAtMs:x,stepClaimCompletedAtMs:S,stepCodeStartedAtMs:Date.now()});r&&(n.reported=!0,u?.setAttributes(r))},N=`ok`,P=performance.now();try{w=await K(`step.execute`,{},async()=>await ke.run({stepMetadata:{stepName:s,stepId:o,stepStartedAt:new Date(+a),attempt:t},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+i),url:y,features:{encryption:!!p}},workflowDeploymentId:e.workflowDeploymentId,rootRunId:e.rootRunId,ops:D,preCompletionOps:T,closureVars:m.closureVars,encryptionKey:p,runReadyBarrier:_?e.runReadyBarrier:void 0},()=>(ne(),f.apply(g,h))))}catch(e){N=`error`,C=e,j=!0}finally{gt(performance.now()-P,N)}let F=Date.now()-M;if(he(...h,g,m.closureVars),j)throw C;if(u?.setAttributes({...b(F)}),w=await K(`step.dehydrate`,{},async t=>{let r=Date.now(),i=await dt(w,n,p,D,globalThis,!1,!1,l,_?e.runReadyBarrier:void 0),a=Date.now()-r;return t?.setAttributes({...O(a),...Lt(typeof i)}),i}),D.length>0){let e=Promise.all(D);zt(e,e=>{G.warn(`Background flush of step stream ops failed`,{workflowRunId:n,stepId:o,error:e instanceof Error?e.message:String(e)})}),te=await Promise.race([e.then(()=>!0,e=>{if(e?.name===`AbortError`||e?.name===`ResponseAborted`)return!0;throw e}),new Promise(e=>setTimeout(()=>e(!1),500))])}if(_){let e=await ee();if(e)return e;A()}T.length>0&&await Promise.all(T).catch(()=>{})}catch(e){if(_){let e=await ee();if(e)return e;A()}T.length>0&&await Promise.all(T).catch(()=>{});let t=Mi(e),r=await Fi(t),i=r.stack||Ai(t)||``;t instanceof Error&&u?.recordException?.(t);let c=J.is(t);if(u?.setAttributes({...V(ki(t)),...Me(r.message),...qt(ki(t)),...et(c?`fatal`:yn.is(t)?`retryable`:`transient`),...Fe(!c)}),q.is(e))return B.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};if(c){B.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:s,errorStack:i}),_r.isNativeError(t)&&i&&(t.stack=i);try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(t,n,await d(),[],globalThis,l),...k}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...a(!0)}),{type:`failed`}}let f=v.attempt;if(u?.setAttributes({...Oe(f),...Nt(h)}),f>=h+1){let t=v.attempt-1;B.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:s,attempt:v.attempt,retryCount:t,errorStack:i});let a=new J(`Step "${s}" failed after ${h} ${ln(`retry`,`retries`,h)}: ${r.message}`);a.cause=e,i&&(a.stack=i);try{await p({eventType:`step_failed`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(a,n,await d(),[],globalThis,l),...k}})}catch(e){if(Z.is(e))return G.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...vt(`failed`),...He(!0)}),{type:`failed`}}yn.is(e)?B.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:s,attempt:f,message:e.message}):B.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:s,attempt:f,errorStack:i}),_r.isNativeError(e)&&i&&(e.stack=i);try{await p({eventType:`step_retrying`,specVersion:7,correlationId:o,eventData:{stepName:s,error:await R(e,n,await d(),[],globalThis,l),...yn.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(Z.is(e))return G.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};throw e}let m=Math.max(1,yn.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return u?.setAttributes({...ht(m),...Wt(!0)}),{type:`retry`,timeoutSeconds:m}}let j;try{j=await p({eventType:`step_completed`,specVersion:7,correlationId:o,eventData:{stepName:s,workflowName:r,result:w,...k}},e.inlineDeltaSinceCursor===void 0?void 0:{sinceCursor:e.inlineDeltaSinceCursor})}catch(e){if(Z.is(e))return G.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:s,message:e.message}),{type:`skipped`};if(q.is(e))return B.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};throw e}let M=Wi(j,e.inlineDeltaSinceCursor!==void 0);return u?.setAttributes({...vt(`completed`),...Lt(typeof w)}),D.length>0&&B.debug(`Step has pending ops`,{workflowRunId:n,stepName:s,opsCount:D.length}),{type:`completed`,hasPendingOps:!te,inlineDelta:M}})}function Ki(e){return e.hasCreatedEvent===!0&&e.ownerMessageId!==void 0&&e.sawRetrying!==!0}function qi(e,t){if(e.lastStartedAt===void 0)return 0;let n=Yr(),r=e.lastStartedAt+n*1e3-t;return Math.min(n,Math.max(0,Math.ceil(r/1e3)))}function Ji(e){return`${e.correlationId}:backstop:${e.lastStartedAt}`}function Yi(e,t,n){let r=new Map,i=new Set;for(let t of e)if(t.correlationId!==void 0)if(t.eventType===`step_started`){let e=`eventData`in t&&t.eventData&&`ownerMessageId`in t.eventData&&typeof t.eventData.ownerMessageId==`string`?t.eventData.ownerMessageId:void 0;r.set(t.correlationId,e)}else t.eventType===`step_retrying`&&i.add(t.correlationId);for(let e of t)if(e!==void 0&&!i.has(e)&&r.get(e)===n)return!0;return!1}const Xi=r(`@workflow/core//stepSingleFlight`,1,()=>({inFlight:new Map}));async function Zi(e,t,n){let r=`${e}:${t}`,i=Xi.inFlight.get(r);if(i){G.warn(`Step execution already in flight in this process; awaiting its settlement instead of executing again`,{workflowRunId:e,stepId:t});try{await i}catch{}return{type:`skipped`}}let a=n();Xi.inFlight.set(r,a);try{return await a}finally{Xi.inFlight.delete(r)}}async function Qi({runId:e,hookEvent:t,queueItem:n,requestId:r,sinceCursor:i,createEvent:a}){try{return(await a(t,{requestId:r,...i===void 0?{}:{sinceCursor:i}})).event?.eventType===`hook_conflict`?{hasHookConflict:!0,hasAwaitedHookCreation:!1}:{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0}}catch(t){if(Z.is(t))return G.info(`Hook already exists, continuing`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0};if(q.is(t))return G.info(`Workflow run already completed, skipping hook`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:!1};if(ea(t)){let e=new J(`createHook failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}throw t}}async function $i({suspension:e,world:t,run:n,span:r,requestId:i,eventLog:a,runReadyBarrier:o,replayRecoveryReporter:s,stepDispatch:c,ownerMessageId:l,allowDeferredBatchWork:u}){let d=n.runId,h=async()=>{if(o)try{await o}catch{}},g=async e=>{let t=(await Promise.allSettled(e)).filter(e=>e.status===`rejected`).map(e=>e.reason);if(t.length!==0)throw t.find(e=>fn.is(e))??t[0]},_=s??Si.inert(),v=(e,n)=>_.withEventCreate(n,n=>t.events.create(d,e,n)),y=0,b=0,x=!1,C=async(e,t)=>{if(b++,!a)return v(e,t);let n=a,r=await v(e,{...t,...$t(n.events)});if(typeof t?.sinceCursor==`string`)return n.cursor===t.sinceCursor&&r.events!==void 0&&r.hasMore!==!0&&(it(n,{events:r.events,cursor:r.cursor}),x=!0),r;let i=Mt(n.events,r);return y+=i.added,i.truncated?G.debug(`Dropped a truncated skipped-slot report`,{workflowRunId:d,eventType:e.eventType,eventId:r.event?.eventId,offered:i.offered}):i.added>0&&G.debug(`Suspension write skipped occupied slots`,{workflowRunId:d,eventType:e.eventType,eventId:r.event?.eventId,reported:i.added}),r},ee=e.items.filter(e=>e.type===`step`),w=e.items.filter(e=>e.type===`hook`),T=e.items.filter(e=>e.type===`wait`),E=e.items.filter(e=>e.type===`attribute`),D=w.filter(e=>!e.hasCreatedEvent),O=new Map;for(let e of w){if(e.hasCreatedEvent&&!e.disposed)continue;let t=O.get(e.token);t?t.push(e):O.set(e.token,[e])}let te=await t.getEncryptionKeyForRun?.(n),k=te?await m(te):void 0,A=(n.specVersion??0)>=5,j=0,ne=[];async function N(t,n){let r={executions:[]};try{return await f(t,d,k,e.globalThis,!1,A,r)}finally{j+=r.totalExecutions??r.executions.length,ne.push(...r.executions.slice(0,5-ne.length).map(e=>({...n,...e})))}}async function P(e){let t={eventType:`hook_disposed`,specVersion:7,correlationId:e.correlationId,eventData:{token:e.token}};try{await C(t,{requestId:i})}catch(t){if(Z.is(t))G.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(q.is(t))G.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(gn.is(t))G.info(`Hook not found for disposal, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}}let F=[],I=[],L=0,re=D.length===1&&typeof a?.cursor==`string`?a.cursor:void 0;if(O.size>0){let e=Date.now();await h(),await g([...O.values()].map(async e=>{for(let t of e){let e=!1;if(!t.hasCreatedEvent){let n=t.metadata===void 0?void 0:await N(t.metadata,{source:`hook_metadata`,correlationId:t.correlationId}),r={eventType:`hook_created`,specVersion:7,correlationId:t.correlationId,eventData:{token:t.token,tokenRetentionUntil:t.tokenRetentionUntil,metadata:n,isWebhook:t.isWebhook??!1,...t.isSystem&&{isSystem:!0}}},a=await Qi({runId:d,hookEvent:r,queueItem:t,requestId:i,sinceCursor:re,createEvent:C});a.hasHookConflict&&F.push(t.correlationId),a.hasAwaitedHookCreation&&I.push(t.correlationId),e=a.hasHookConflict}t.disposed&&!e&&await P(t)}})),L=Date.now()-e}let ie=w.filter(e=>e.abortRequested&&!e.disposed);ie.length>0&&(await h(),await g(ie.map(async e=>{try{let n=await N({aborted:!0,reason:e.abortReason},{source:`hook_abort`,correlationId:e.correlationId});await C({eventType:`hook_received`,specVersion:7,correlationId:e.correlationId,eventData:{token:e.token,payload:n}});try{let r=kt(e.token);await t.streams.write(d,r,n),await t.streams.close(d,r)}catch{G.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:d,correlationId:e.correlationId})}}catch(t){if(Z.is(t)||q.is(t))G.info(`Workflow run already completed, skipping abort`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})));let ae=new Set(ee.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),oe=new Set,se=new Set,ce=async(t,r)=>{G.warn(`Step arguments failed to serialize; failing the step so the workflow can observe the error`,{workflowRunId:d,correlationId:t.correlationId,stepName:t.stepName,error:r.message}),await h();let a=await f(Hi(),d,k,e.globalThis,!1,A);try{await C({eventType:`step_created`,specVersion:7,correlationId:t.correlationId,eventData:{stepName:t.stepName,workflowName:n.workflowName,input:a}},{requestId:i})}catch(e){if(Z.is(e))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else if(q.is(e))return;else throw e}try{await C({eventType:`step_failed`,specVersion:7,correlationId:t.correlationId,eventData:{stepName:t.stepName,error:await R(r,d,k,[],e.globalThis,A)}},{requestId:i})}catch(e){if(Z.is(e)||q.is(e))G.info(`Tried failing step, but step or run has already finished.`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else throw e}se.add(t.correlationId),z.delete(t.correlationId)},z=new Set(I.length===0?ee.filter(e=>ae.has(e.correlationId)).slice(0,Br()).map(e=>e.correlationId):[]),le=new Map,ue=[],B=new Set,V=c!==void 0&&Vr()&&(n.specVersion??0)>=3,H=Hr()&&typeof t.events.createBatch==`function`&&(n.specVersion??0)>=6&&!V&&w.length===0&&E.length===0,U=[],de=[],fe=T.filter(e=>!e.hasCreatedEvent).length,pe=H&&l!==void 0&&z.size>0&&(z.size>=2||ae.size-z.size+fe>=1),me=new Map,he,ge,_e=()=>(ge??=c?.getTraceCarrier()??Promise.resolve({}),ge),ve=0,be=0;for(let e of ee)if(ae.has(e.correlationId)){let r=pe&&z.has(e.correlationId),a=be;be+=r?2:1;let o=(async()=>{let o;try{o=await N({args:e.args,closureVars:e.closureVars,thisVal:e.thisVal},{source:`step_input`,correlationId:e.correlationId})}catch(t){if(!mn.is(t)||!c)throw t;await ce(e,t);return}if(z.has(e.correlationId)){le.set(e.correlationId,{correlationId:e.correlationId,stepName:e.stepName,dehydratedInput:o}),r&&(U.push({order:a,kind:`inline-created`,correlationId:e.correlationId,event:{eventType:`step_created`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,workflowName:n.workflowName,input:o}}}),U.push({order:a+1,kind:`inline-started`,correlationId:e.correlationId,event:{eventType:`step_started`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,...l===void 0?{}:{ownerMessageId:l}}}}));return}let s={eventType:`step_created`,specVersion:7,correlationId:e.correlationId,eventData:{stepName:e.stepName,workflowName:n.workflowName,input:o}};if(V&&o instanceof Uint8Array&&o.byteLength<=131072){await h();let n=await _e(),[r,a]=await Promise.allSettled([C(s,{requestId:i}),Ze(t,c.queueName,{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:n,requestedAt:new Date,stepInput:{input:o}},{idempotencyKey:ze(e.correlationId,e.stepName)})]);if(a.status===`rejected`)throw a.reason;if(B.add(e.correlationId),r.status===`rejected`){let t=r.reason;if(Z.is(t))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(lr(t))ve++,G.warn(`Step creation event write failed, but the step was dispatched via the queue. The step_created event will be ensured by the queue consumer.`,{workflowRunId:d,correlationId:e.correlationId,stepName:e.stepName,error:t instanceof Error?t.message:String(t)});else throw t}else oe.add(e.correlationId);return}if(H){U.push({order:a,kind:`step`,correlationId:e.correlationId,stepName:e.stepName,event:s});return}try{await h(),await C(s,{requestId:i}),oe.add(e.correlationId)}catch(t){if(Z.is(t))G.info(`Step already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})();ue.push(o),H&&de.push(o.catch(()=>{}))}for(let e of T)if(!e.hasCreatedEvent){let t={eventType:`wait_created`,specVersion:7,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};if(H){U.push({order:be++,kind:`wait`,correlationId:e.correlationId,event:t});continue}ue.push((async()=>{try{await h(),await C(t,{requestId:i})}catch(t){if(Z.is(t))G.info(`Wait already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else throw t}})())}let xe;H&&ue.push((async()=>{if(await Promise.all(de),U.length===0)return;let e=[...U].sort((e,t)=>e.order-t.order);if(await h(),e.length===1){let[t]=e;try{await C(t.event,{requestId:i}),t.kind===`step`&&oe.add(t.correlationId)}catch(e){if(Z.is(e))G.info(t.kind===`step`?`Step already exists, continuing`:`Wait already exists, continuing`,{workflowRunId:d,correlationId:t.correlationId,message:e.message});else throw e}return}let n=a?(Ye(a.events)??0)+1:void 0,r=[];{let t=[];for(let n=0;n<e.length;n++){let i=e[n],a=e[n+1],o=i.kind===`inline-created`&&a?.kind===`inline-started`&&a.correlationId===i.correlationId,s=o?2:1;t.length>0&&t.length+s>32&&(r.push(t),t=[]),t.push(i),o&&(t.push(a),n++)}t.length>0&&r.push(t)}let o=c!==void 0;if(o)for(let t of e)t.kind===`step`&&B.add(t.correlationId);let s=0,l,f=async e=>{let n=Date.now(),{results:r}=await t.events.createBatch(d,e.map(e=>({event:e.event,...e.kind===`inline-started`?{computeInstanceId:jr}:{}})),{requestId:i}),a=Date.now();for(let[t,i]of r.entries()){let r=e[t];if(i.error===void 0){if(r.kind===`step`)oe.add(r.correlationId);else if(r.kind===`inline-started`){let e=le.get(r.correlationId);if(e===void 0)throw new on(`no dehydrated input for pre-claimed step ${r.correlationId}`,{status:500});let t=new Date,o=i.step?.startedAt?{...i.step,startedAt:i.step.startedAt}:{runId:d,stepId:r.correlationId,stepName:e.stepName,status:`running`,attempt:1,createdAt:t,updatedAt:t,startedAt:t};me.set(r.correlationId,{owned:!0,step:{...o,input:e.dehydratedInput},batchPostSentAtMs:n,claimCompletedAtMs:a})}continue}if(i.status===409){if(r.kind===`inline-created`||r.kind===`inline-started`){me.set(r.correlationId,{owned:!1}),G.info(`Inline step pre-claim lost, continuing`,{workflowRunId:d,correlationId:r.correlationId,message:i.message});continue}G.info(r.kind===`step`?`Step already exists, continuing`:`Wait already exists, continuing`,{workflowRunId:d,correlationId:r.correlationId,message:i.message});continue}throw new on(`batched ${r.event.eventType} for ${r.correlationId} failed: ${i.error}: ${i.message}`,{status:i.status})}let o=Ye(r.flatMap(e=>e.error===void 0&&e.event?[e.event]:[]));o!==void 0&&(he===void 0||o>he)&&(he=o),s+=r.filter(e=>e.error===void 0).length,o!==void 0&&(l===void 0||o>l)&&(l=o)},p=async e=>{if(!o)return;let n=e.filter(e=>e.kind===`step`);if(n.length===0)return;let r=await _e();await Promise.all(n.map(e=>Ze(t,c.queueName,{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:r,requestedAt:new Date},{idempotencyKey:ze(e.correlationId,e.stepName)})))},m=r.map(e=>f(e)),g=r.map(async(e,t)=>{await m[t],await p(e)}),_=(async()=>{let e=await Promise.allSettled([...m,...g]);if(n!==void 0&&l!==void 0){let e=l-n+1-s;e>0&&G.debug(`Batched fan-out committed above snapshot`,{workflowRunId:d,expectedFirstSlot:n,maxCommittedSlot:l,committedCount:s,interleaved:e})}let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason})(),v=r.flatMap((e,t)=>e.some(e=>e.kind===`inline-started`)?[m[t]]:[]);if(u){if(_.catch(()=>{}),xe=_,v.length>0)try{await Promise.all(v)}catch(e){throw await _.catch(()=>{}),e}}else await _})());for(let e of E)ue.push((async()=>{try{await h(),await C({eventType:`attr_set`,specVersion:7,correlationId:e.correlationId,eventData:{changes:e.changes,writer:{type:`workflow`},...e.allowReservedAttributes?{allowReservedAttributes:!0}:{}}},{requestId:i})}catch(t){if(Z.is(t))G.info(`Workflow attribute event already exists, continuing`,{workflowRunId:d,correlationId:e.correlationId,message:t.message});else if(ea(t)){let e=new J(`setAttributes failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}else throw t}})());await g(ue);let Se=[];for(let e of z){let t=le.get(e);t&&Se.push(t)}let Ce=Date.now(),W;for(let e of T){let t=e.resumeAt.getTime(),n=Math.max(1e3,t-Ce),r=Math.ceil(n/1e3);(!W||r<W.seconds)&&(W={seconds:r,correlationId:e.correlationId})}return r?.setAttributes({...ye(`workflow_suspended`),...S(ee.length),...p(D.length),...De(T.length),...se.size>0?M(se.size):{},...ve>0?Ct(ve):{}}),{pendingSteps:ee,createdStepCorrelationIds:oe,failedStepCorrelationIds:se,queuedStepCorrelationIds:B,lazyInlineSteps:Se,inlineClaims:me,batchCommittedSlotCeiling:he,deferredBatchWork:xe,waitTimeout:F.length>0?void 0:W,hasHookConflict:F.length>0,hookConflictCorrelationIds:F,hasAwaitedHookCreation:I.length>0,awaitedHookCorrelationIds:I,eventLogCarriedForward:x&&b===1,hasAttributeEvents:E.length>0,hasHookEvents:D.length>0,hookCreationMs:L,serializationBlockerCount:j,serializationBlockers:ne,reportedEventCount:y}}function ea(e){return e instanceof Un||e instanceof Error&&e.name===`AttributeValidationError`||on.is(e)&&e.status===400}const ta=()=>zn(`WORKFLOW_WAIT_CONTINUATION_MAX_DELAY_SECONDS`,82800,{integer:!0,min:1}),na=()=>zn(`WORKFLOW_NEAR_ELAPSED_WAIT_THRESHOLD_SECONDS`,2);function ra(e,t,n=Date.now(),r=0){let i=ia(e,t,n);return r<=0?i:{delaySeconds:i.delaySeconds,idempotencyKey:`${i.idempotencyKey}:a${r}`}}function ia(e,t,n){let r=ta();if(e<=Math.min(na(),r))return{delaySeconds:e,idempotencyKey:`${t}:${Math.floor(n/1e3)}`};let i=Math.ceil(e/r);return{delaySeconds:Math.min(e,r),idempotencyKey:i===1?t:`${t}:hop-${i}`}}var aa=44,oa=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,sa=new Uint8Array(64),ca=new Uint8Array(128);for(let e=0;e<oa.length;e++){let t=oa.charCodeAt(e);sa[e]=t,ca[t]=e}function la(e,t){let n=0,r=0,i=0;do i=ca[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function ua(e,t){return e.pos>=t?!1:e.peek()!==aa}var da=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function fa(e){let{length:t}=e,n=new da(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=la(n,i),i<u&&(l=!1),u=i,ua(n,e)?(a=la(n,a),o=la(n,o),s=la(n,s),ua(n,e)?(c=la(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||pa(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function pa(e){e.sort(ma)}function ma(e,t){return e[0]-t[0]}const ha=/^[\w+.-]+:\/\//,ga=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,_a=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function va(e){return ha.test(e)}function ya(e){return e.startsWith(`//`)}function ba(e){return e.startsWith(`/`)}function xa(e){return e.startsWith(`file:`)}function Sa(e){return/^[.?#]/.test(e)}function Ca(e){let t=ga.exec(e);return Ta(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function wa(e){let t=_a.exec(e),n=t[2];return Ta(`file:`,``,t[1]||``,``,ba(n)?n:`/`+n,t[3]||``,t[4]||``)}function Ta(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function Ea(e){if(ya(e)){let t=Ca(`http:`+e);return t.scheme=``,t.type=6,t}if(ba(e)){let t=Ca(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(xa(e))return wa(e);if(va(e))return Ca(e);let t=Ca(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function Da(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Oa(e,t){ka(t,t.type),e.path===`/`?e.path=t.path:e.path=Da(t.path)+e.path}function ka(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function Aa(e,t){if(!e&&!t)return``;let n=Ea(e),r=n.type;if(t&&r!==7){let e=Ea(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:Oa(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}ka(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?Sa(t||e)&&!Sa(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function ja(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Ma(e,t){let n=ja(e),r=t?t+`/`:``;return e=>Aa(r+(e||``),n)}var Na=0,Pa=1,Fa=2,Ia=3,La=4;function Ra(e,t){let n=za(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=za(e,r+1))e[r]=Va(e[r],t);return e}function za(e,t){for(let n=t;n<e.length;n++)if(!Ba(e[n]))return n;return e.length}function Ba(e){for(let t=1;t<e.length;t++)if(e[t][Na]<e[t-1][Na])return!1;return!0}function Va(e,t){return t||(e=e.slice()),e.sort(Ha)}function Ha(e,t){return e[Na]-t[Na]}var Ua=!1;function Wa(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][Na]-t;if(a===0)return Ua=!0,i;a<0?n=i+1:r=i-1}return Ua=!1,n-1}function Ga(e,t,n){for(let r=n+1;r<e.length&&e[r][Na]===t;n=r++);return n}function Ka(e,t,n){for(let r=n-1;r>=0&&e[r][Na]===t;n=r--);return n}function qa(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function Ja(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return Ua=o!==-1&&e[o][Na]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=Wa(e,t,s,c)}function Ya(e){return typeof e==`string`?JSON.parse(e):e}var Xa="`line` must be greater than 0 (lines start at line 1)",Za="`column` must be greater than or equal to 0 (columns start at column 0)",Qa=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=Ya(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Ma(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=Ra(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=qa(),this._bySources=void 0,this._bySourceMemos=void 0}};function $a(e){return e}function eo(e){var t;return(t=$a(e))._decoded||(t._decoded=fa($a(e)._encoded))}function to(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(Xa);if(r<0)throw Error(Za);let a=eo(e);if(n>=a.length)return no(null,null,null,null);let o=a[n],s=ro(o,$a(e)._decodedMemo,n,r,i||1);if(s===-1)return no(null,null,null,null);let c=o[s];if(c.length===1)return no(null,null,null,null);let{names:l,resolvedSources:u}=e;return no(u[c[Pa]],c[Fa]+1,c[Ia],c.length===5?l[c[La]]:null)}function no(e,t,n,r){return{source:e,line:t,column:n,name:r}}function ro(e,t,n,r,i){let a=Ja(e,r,t,n);return Ua?a=(i===-1?Ga:Ka)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function io(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function ao(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&io(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}const oo=r(`@workflow/core//sourceMapTracers`,1,()=>({byCode:new Map}));function so(e){let t=oo.byCode.get(e);if(t!==void 0)return oo.byCode.delete(e),oo.byCode.set(e,t),t;let n=null,r=ao(e);if(r)try{let e=Buffer.from(r,`base64`).toString(`utf-8`);n=new Qa(JSON.parse(e))}catch{n=null}for(oo.byCode.set(e,n);oo.byCode.size>8;){let e=oo.byCode.keys().next().value;if(e===void 0)break;oo.byCode.delete(e)}return n}function co(e,t,n){if(!e.includes(t))return e;let r=so(n);if(!r)return e;try{return e.split(`
|
|
2
|
+
`).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,i,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=to(r,{line:c,column:l});if(u.source&&u.line!==null){let e=i||u.name||`anonymous`,t=u.column===null?l:u.column;return` at ${e} (${u.source}:${u.line}:${t})`}return e}).join(`
|
|
3
|
+
`)}catch{return e}}function lo(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function uo(e){return function(t,n){let r=function(...r){let{promise:i,resolve:a,reject:o}=En(),s=`step_${e.generateUlid()}`,c={type:`step`,correlationId:s,stepName:t,args:r};this!==void 0&&this!==null&&this!==globalThis&&(c.thisVal=this);let l=n?.();return l&&(c.closureVars=l),e.invocationsQueue.set(s,c),B.debug(`Step consumer setup`,{correlationId:s,stepName:t,args:r}),e.eventsConsumer.subscribe(n=>{if(!n)return wn(e),W.NotConsumed;if(B.debug(`Step consumer event processing`,{correlationId:s,stepName:t,args:r.join(`, `),incomingCorrelationId:n.correlationId,isMatch:s===n.correlationId,eventType:n.eventType}),n.correlationId!==s)return W.NotConsumed;let i=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof i==`string`&&i!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: step event ${n.eventType} for ${s} belongs to "${i}", but the current step consumer is "${t}"`,{eventId:n.eventId}))}),W.Finished;if(n.eventType===`step_created`){let r=e.invocationsQueue.get(s);return!r||r.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{o(new pn(`Replay divergence: step ${s} (${t}) created but not found in invocation queue`,{eventId:n.eventId}))}),W.Finished):(r.hasCreatedEvent=!0,W.Consumed)}if(n.eventType===`step_started`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.ownerMessageId=`eventData`in n&&n.eventData&&`ownerMessageId`in n.eventData&&typeof n.eventData.ownerMessageId==`string`?n.eventData.ownerMessageId:void 0,t.lastStartedAt=+n.createdAt),W.Consumed}if(n.eventType===`step_retrying`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.sawRetrying=!0,t.ownerMessageId=void 0),W.Consumed}if(n.eventType===`step_failed`){e.invocationsQueue.delete(n.correlationId);let t=e.eventsConsumer.eventIndex,r=Cn(e,t,`step`),i,a=kn(e,t,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let t=await e.replayPayloadCache.prepareEventPayload(n.eventId,`error`,n.eventData.error);i=await N(n.eventData.error,e.runId,e.encryptionKey,e.globalThis,{},t)}catch(e){B.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),i=new J(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`)}finally{e.pendingDeliveries--}a.then(()=>{r.markDelivered(),o(i)})}),W.Finished}if(n.eventType===`step_completed`){e.invocationsQueue.delete(n.correlationId);let t=n.eventId,r=n.eventData.result,i=e.eventsConsumer.eventIndex,s=Cn(e,i,`step`),c,l=kn(e,i,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{c={ok:!0,value:await e.replayPayloadCache.getStepResult(t,async()=>{let n=await e.replayPayloadCache.prepareEventPayload(t,`result`,r);return await H(r,e.runId,e.encryptionKey,e.globalThis,{},n)})}}catch(e){c={ok:!1,error:e}}finally{e.pendingDeliveries--}l.then(()=>{s.markDelivered(),c.ok?a(c.value):o(c.error)})}),W.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: Unexpected event type for step ${s} (name: ${t}) "${n.eventType}"`,{eventId:n.eventId}))}),W.Finished}),i},i=t.split(`//`).pop();return Object.defineProperty(r,"name",{value:i}),Object.defineProperty(r,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&(wt(n),Object.defineProperty(r,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1})),Object.defineProperty(r,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),r}}var fo=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),po=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),mo=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),ho=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),go=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),_o=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),vo=n(((e,n)=>{(function(e,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var t;return p&&(t=p.randomBytes)?t=t(a):(t=new Uint8Array(a),(e.crypto||e.msCrypto).getRandomValues(t)),b(t)}catch{var n=e.navigator,i=n&&n.plugins;return[+new Date,e,i,e.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=t(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:e,[],Math)})),yo=e(n(((e,t)=>{var n=fo(),r=po(),i=mo(),a=ho(),o=go(),s=_o(),c=vo();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const bo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,xo=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)xo[bo.charCodeAt(e)]=e;function So(e){return e===9||e===10||e===12||e===13||e===32}function Co(e,t){for(;t<e.length&&So(e.charCodeAt(t));)t++;return t}function wo(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=xo[r.charCodeAt(0)],a=xo[r.charCodeAt(1)],o=xo[r.charCodeAt(2)],s=xo[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function To(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=Co(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...wo(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=Co(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=Co(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...wo(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||xo[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...wo(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function Eo(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function Do(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=bo[n>>2&63],i+=bo[(n&3)<<4|o>>4&15],t+1<a?i+=bo[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=bo[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function Oo(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function ko(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Do(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Oo(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=To(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Eo(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=To(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Eo(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function Ao(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}const jo={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function Mo(e){if(_r.isTypedArray(e)||_r.isDataView(e)){if(_r.isSharedArrayBuffer(e.buffer))throw TypeError(`crypto.subtle.digest does not accept SharedArrayBuffer-backed views`);return e}if(!_r.isArrayBuffer(e))throw TypeError(`data must be an ArrayBuffer or ArrayBufferView`);return new Uint8Array(e)}function No(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,yo.default)(n),i=xr(),a=Sr(`globalThis`,i);a.Math.random=r;let o=a.Date;a.Date=function(...e){return new.target===void 0?new o(t).toString():Reflect.construct(o,e.length===0?[t]:e,new.target)},a.Date.prototype=o.prototype,Object.setPrototypeOf(a.Date,o),a.Date.now=()=>t;let s=globalThis.crypto,c=s.subtle;function l(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let u=Ao(r),d=a;delete d.Atomics.waitAsync,delete d.WebAssembly.compile,delete d.WebAssembly.instantiate,delete d.WebAssembly.compileStreaming,delete d.WebAssembly.instantiateStreaming,delete d.WeakRef,delete d.FinalizationRegistry;let f=async(e,t)=>{let n=typeof e==`string`?e:e.name,r=jo[n.toUpperCase()];if(!r)throw new DOMException(`Unrecognized algorithm name: ${n}`,`NotSupportedError`);let i=gr(r).update(Mo(t)).digest(),a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),a};return a.crypto=new Proxy(s,{get(e,t){return t===`getRandomValues`?l:t===`randomUUID`?u:t===`subtle`?new Proxy(c,{get(e,t){if(t===`digest`)return f;let n=e[t];return typeof n==`function`?()=>{throw new X(`\`crypto.subtle.${String(t)}()\` is not available inside a workflow function. Move it to a step function where full Node.js crypto is available.`)}:n}}):e[t]}}),a.process={env:Object.freeze({...process.env})},a.DOMException=globalThis.DOMException,a.Headers=globalThis.Headers,a.TextEncoder=globalThis.TextEncoder,a.TextDecoder=globalThis.TextDecoder,a.console=globalThis.console,a.URL=globalThis.URL,a.URLSearchParams=globalThis.URLSearchParams,a.structuredClone=globalThis.structuredClone,a.atob=globalThis.atob,a.btoa=globalThis.btoa,ko(a.Uint8Array),a.Symbol.dispose??=Symbol.for(`Symbol.dispose`),a.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),a.exports={},a.module={exports:a.exports},{context:i,globalThis:a,updateTimestamp:e=>{t=e}}}const Po=r(`@workflow/core//vmScriptCache`,1,()=>({byCode:new Map}));function Fo(e){let t=Po.byCode.get(e);if(t!==void 0)return Po.byCode.delete(e),Po.byCode.set(e,t),t}function Io(e,t){let n=Fo(e);if(n===void 0)for(n=new Map,Po.byCode.set(e,n);Po.byCode.size>8;){let e=Po.byCode.keys().next().value;if(e===void 0)break;Po.byCode.delete(e)}let r=n.get(t),i=r!==void 0;return r===void 0&&(r=new br(e,{filename:t}),n.set(t,r)),{script:r,cacheHit:i}}function Lo(e){return async function(t,n={}){let{promise:r,resolve:i}=En(),a=`attr_${e.generateUlid()}`,o={type:`attribute`,correlationId:a,changes:t,...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}};return e.invocationsQueue.set(a,o),e.eventsConsumer.subscribe(r=>r?r.correlationId===a?r.eventType!==`attr_set`||r.eventData.writer.type!==`workflow`||JSON.stringify(r.eventData.changes)!==JSON.stringify(t)||r.eventData.allowReservedAttributes===!0!=(n.allowReservedAttributes===!0)?(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: Unexpected attribute event for ${a}`,{eventId:r.eventId}))}),W.Finished):(e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),W.Finished):W.NotConsumed:(wn(e),W.NotConsumed)),r}}function Ro(e,t){if(typeof t!=`string`)return null;let n=Pt(Vt,e.globalThis),r=n?.[ot];return typeof r==`function`?r.call(n,{runId:t}):null}function zo(e){return function(t={}){if(t.token===``)throw Error("`createHook()` was called with an empty string token. Pass a non-empty token, or omit the `token` option to use a generated one.");if(t.isWebhook===!0&&t.experimental_minRetention!==void 0)throw Error("Webhook hooks do not support `experimental_minRetention`. Use a non-webhook `createHook()` with `resumeHook()`.");if(t.experimental_minRetention!==void 0&&e.worldCapabilities?.hookRetention?.active!==!0)throw new J("The configured World does not support `experimental_minRetention` for Hooks.");let n=`hook_${e.generateUlid()}`,r=t.token??e.generateNanoid(),a=t.experimental_minRetention===void 0?void 0:sn(t.experimental_minRetention),o=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:r,tokenRetentionUntil:a,metadata:t.metadata,isWebhook:o});let s=[],c=[],l=[],u=!1,d=!1,f=!1,p=!1,m=null,h=null,g=new Set;i.debug(`Hook consumer setup`,{correlationId:n,token:r}),e.eventsConsumer.subscribe(t=>{if(!t)return u=!0,(c.length>0&&s.length===0||l.length>0&&!d&&!p)&&wn(e),W.NotConsumed;if(t.correlationId!==n)return W.NotConsumed;let i=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof i==`string`&&i!==r)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: hook event ${t.eventType} for ${n} belongs to token "${i}", but the current hook consumer expects "${r}"`,{eventId:t.eventId}))}),W.Finished;if(t.eventType===`hook_created`){let r=e.invocationsQueue.get(n);r&&r.type===`hook`&&(r.hasCreatedEvent=!0,r.tokenRetentionUntil=t.eventData.tokenRetentionUntil),d=!0;let i=l.slice();return l.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of i)e.resolve(null)}),W.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new dn(r.eventData.token,r.eventData.conflictingRunId);p=!0,m=i,h=Ro(e,r.eventData.conflictingRunId);let a=c.slice();c.length=0;let o=l.slice();return l.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i);for(let e of o)h?e.resolve(h):e.reject(i)}),W.Consumed}if(t.eventType===`hook_received`){let n=t.resumeId;if(typeof n==`string`){if(g.has(n))return W.Consumed;g.add(n)}let r=e.eventsConsumer.eventIndex,i=c.length>0,a=Cn(e,r,`hook`,{armed:i});if(i){let n=kn(e,r,`hook`),i=c.shift();if(i){e.pendingDeliveries++;let r;e.promiseQueue=e.promiseQueue.then(async()=>{try{let n=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);r={ok:!0,value:await H(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},n)}}catch(e){r={ok:!1,error:e}}finally{e.pendingDeliveries--}n.then(()=>{a.markDelivered(),r.ok?i.resolve(r.value):i.reject(r.error)})})}}else{let n,i=En();e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);n={ok:!0,value:await H(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},r)}}catch(e){n={ok:!1,error:e}}finally{e.pendingDeliveries--,i.resolve()}}),s.push({claim:()=>(a.arm(),i.promise.then(()=>kn(e,r,`hook`)).then(()=>{if(a.markDelivered(),n&&!n.ok)throw n.error;return n.value}))})}return W.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),f=!0,W.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: Unexpected event type for hook ${n} (token: ${r}) "${t.eventType}"`,{eventId:t.eventId}))}),W.Finished)});let _=!1;function v(){let t=En();if(p&&m)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(m)}),t.promise;if(s.length>0){let e=s.shift();if(e)return e.claim()}return u&&wn(e),c.push(t),t.promise}function y(){let t=En();if(d)return e.promiseQueue=e.promiseQueue.then(()=>{t.resolve(null)}),t.promise;if(p)return e.promiseQueue=e.promiseQueue.then(()=>{h?t.resolve(h):t.reject(m)}),t.promise;let r=e.invocationsQueue.get(n);return r&&r.type===`hook`&&(r.hasConflictAwaiter=!0),u&&wn(e),l.push(t),t.promise}function b(){if(_||(_=!0,f))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),c.length>0&&(c.length=0,wn(e)),i.debug(`Hook disposed`,{correlationId:n,token:r})}let x={token:r,getConflict(){return y()},then(e,t){return v().then(e,t)},async*[Symbol.asyncIterator](){for(;!_;)yield await this},dispose:b,[Symbol.dispose]:b},S=e.globalThis.Symbol.dispose;return S&&S!==Symbol.dispose&&(x[S]=b),x}}function Bo(e){return async function(t){let{promise:n,resolve:r}=En(),i=`wait_${e.generateUlid()}`,a=sn(t),o={type:`wait`,correlationId:i,resumeAt:a};return e.invocationsQueue.set(i,o),e.eventsConsumer.subscribe(t=>{if(!t)return wn(e),W.NotConsumed;if(t.correlationId!==i)return W.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(i);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),W.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let r=e.invocationsQueue.get(i),o=r&&r.type===`wait`?r.resumeAt:a,s=new Date(n),c=s.getTime(),l=o.getTime(),u=Number.isFinite(c)?s.toISOString():String(n);if(c!==l)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: wait_completed event for ${i} has resumeAt "${u}", but the current wait consumer expects "${o.toISOString()}"`,{eventId:t.eventId}))}),W.Finished}e.invocationsQueue.delete(i);let o=e.eventsConsumer.eventIndex,s=Cn(e,o,`wait`),c=kn(e,o,`wait`);return e.promiseQueue.then(()=>c).then(()=>{s.markDelivered(),r()}),W.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new pn(`Replay divergence: Unexpected event type for wait ${i} "${t.eventType}"`,{eventId:t.eventId}))}),W.Finished}),n}}async function Vo(e,t,n,r,i,a){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await gi();await $i({suspension:new An(t,n),world:e,run:r,runReadyBarrier:a})}catch(t){G.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}function Ho(e,t){let n=L(t)?.moduleSpecifier||t,r=`globalThis.__private_workflows?.get(${JSON.stringify(t)})`;return K(`workflow.bundle.compile`,async t=>{let i=Io(e,n),a=Io(r,n);return t?.setAttributes({...en(i.cacheHit)}),{bundleScript:i.script,workflowLookupScript:a.script}})}function Uo(e){return Go(`replay`,e.workflowRun,e.events,async t=>{let{session:n,execution:r}=await qo(e);return t?.setAttributes({...Pe(n.argumentCount)}),Ko(await r,t)})}function Wo(e,t){return Go(`retained`,e.workflowRun,t,async n=>{n?.setAttributes({...Pe(e.argumentCount)});let r=await e.resume(t);return r.type===`replay`?r:Ko(r,n)})}function Go(e,t,n,r){return K(`workflow.run ${t.workflowName}`,i=>(i?.setAttributes({...se(t.workflowName),...Se(t.runId),...ye(t.status),...ge(n.length),..._(e)}),r(i)))}function Ko(e,t){return e.type===`completed`?t?.setAttributes({...y(e.resultType)}):t&&(Je(e.suspension,t),e.parked&&t.setAttributes({...ie(e.parked.count),...lt(e.parked.eventId),...I(e.parked.eventType)})),e}async function qo(e){let t=await Ke(`workflow.vm.create_context`);return Jo(e,t.end).catch(e=>{throw t.fail(e),e})}async function Jo({workflowCode:e,workflowRun:t,events:n,encryptionKey:r,replayPayloadCache:i,compiledWorkflowScripts:a,runReadyBarrier:o,worldCapabilities:s},c){let l=t.startedAt;if(!l)throw new X(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let u=Oi(t.runId)??+t.createdAt,f=Mn(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Li()??3e3}`),{context:p,globalThis:m,updateTimestamp:h}=No({seed:`${t.runId}:${t.workflowName}:${t.deploymentId}`,fixedTimestamp:u}),g=En(),_={type:`running`,interruption:g},y=e=>{switch(_.type){case`running`:{let{interruption:t}=_;_=An.is(e)?{type:`suspended`,suspension:e}:{type:`replay`},k.suspensionGeneration++,t.reject(e);return}case`suspended`:_={type:`replay`};return;case`replay`:case`completed`:return}},b=Kn(()=>m.Math.random()),S=0,C=()=>(S+=1,b(u)),w=lo(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*m.Math.random())),T={current:Promise.resolve()},E={current:()=>!0},D=u,O=new x(n,{onConsumedEvent:e=>{let t=+e.createdAt;t>D&&(D=t,h(t))},onUnconsumedEvent:e=>{y(new pn(`Replay could not consume event: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}.`,{eventId:e.eventId}))},onDuplicateEvent:(e,n)=>{let r={workflowRunId:t.runId,eventId:e.eventId,eventType:e.eventType,firstEventType:n,correlationId:e.correlationId};if(n!==e.eventType){G.debug(`Ignoring inert event that decides an already-decided outcome differently`,r);return}G.debug(`Ignoring inert event that repeats a class already in the event log`,r)},getPromiseQueue:()=>T.current,isDeliveryIdle:()=>E.current()}),k={runId:t.runId,encryptionKey:r,worldCapabilities:s,globalThis:m,onWorkflowError:y,eventsConsumer:O,generateUlid:C,generateNanoid:w,get mintCount(){return S},invocationsQueue:new Map,get promiseQueue(){return T.current},set promiseQueue(e){T.current=e},pendingDeliveries:0,suspensionGeneration:0,pendingDeliveryBarriers:new Map,replayPayloadCache:i};E.current=()=>Dn(k);let A=!1;k.eventsConsumer.subscribe(e=>e?e.eventType===`run_created`?W.Consumed:e.eventType===`run_started`?A?W.NotConsumed:(A=!0,W.Consumed):e.eventType===`attr_set`&&e.eventData.writer.type===`step`?W.Consumed:W.NotConsumed:W.NotConsumed);let j=uo(k),M=zo(k),ne=Bo(k),N=Lo(k);m[v]=j,m[Yt]=N,m[pe]=M,m[_e]=ne,m[d]=e=>te(t.runId,e),m[In]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new m.Date(+l),url:f,features:{encryption:!!r}},m[$e]=C,m.fetch=()=>{throw new m.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${hn.FETCH_IN_WORKFLOW_FUNCTION}`)};let P=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;m.setTimeout=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.setInterval=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearTimeout=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearInterval=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.setImmediate=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.clearImmediate=()=>{throw new X(P,{slug:hn.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},m.AbortController=ve(k);let F=ee();m.AbortSignal={abort:F.abort,any:F.any,timeout:F.timeout};class I{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof m.URL){let t=String(e);try{new m.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new m.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new m.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new m.Headers(t.headers):(typeof e==`string`||e instanceof m.URL)&&(this.headers=new m.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(m.ReadableStream.prototype,{[rt]:{value:n,writable:!1}})}clone(){Q()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}m.Request=I,Object.defineProperties(I.prototype,{arrayBuffer:{value:j(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:j(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:j(`__builtin_response_text`),writable:!0,configurable:!0}});class L{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new m.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(m.ReadableStream.prototype,{[rt]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new m.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new L(n,{...t,headers:r})}static error(){Q()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new m.Headers;n.set(`Location`,String(e));let r=Object.create(L.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}m.Response=L,Object.defineProperties(L.prototype,{arrayBuffer:{value:j(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:j(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:j(`__builtin_response_text`),writable:!0,configurable:!0}});class re{constructor(){Q()}get locked(){return!1}cancel(){Q()}getReader(){Q()}pipeThrough(){Q()}pipeTo(){Q()}tee(){Q()}values(){Q()}static from(){Q()}[Symbol.asyncIterator](){Q()}}m.ReadableStream=re;class ie{constructor(){Q()}get locked(){return!1}abort(){Q()}close(){Q()}getWriter(){Q()}}m.WritableStream=ie;class ae{readable;writable;constructor(){Q()}}m.TransformStream=ae,m.console=globalThis.console;let oe=Symbol.for(`@vercel/request-context`);m[oe]=globalThis[oe],c();let{bundleScript:R,workflowLookupScript:se}=a??await Ho(e,t.workflowName),ce=await K(`workflow.bundle.evaluate`,async()=>(R.runInContext(p),se.runInContext(p)));if(typeof ce!=`function`)throw new xn(t.workflowName);let z=[];k.promiseQueue=k.promiseQueue.then(async()=>{z=await K(`workflow.input.hydrate`,async()=>{let e=await i.prepareWorkflowInput(t);return nn(t.input,t.runId,r,m,{},e)})}),await k.promiseQueue;let le=async e=>{throw An.is(e)||pn.is(e)?(_.type===`running`&&(_={type:`replay`}),e):(_={type:`completed`},await Vo(t.runId,k.invocationsQueue,m,t,`failed`,o),e)},ue=async(e,n)=>{let i;try{i=await Promise.race([e,n.promise])}catch(e){return _.type===`suspended`&&e===_.suspension?{type:`suspended`,suspension:_.suspension,session:U,parked:O.parkedSummary}:le(e)}_={type:`completed`};let a=O.strandedEvent;if(a)return le(new pn(`Replay finished without consuming event: eventType=${a.eventType}, correlationId=${a.correlationId}, eventId=${a.eventId}.`,{eventId:a.eventId}));try{let e=await ct(i,t.runId,r,m,!1,(t.specVersion??0)>=5);return await Vo(t.runId,k.invocationsQueue,m,t,`completed`,o),{type:`completed`,output:e,resultType:typeof i}}catch(e){return le(e)}},B=await Ft(),V=await Ke(`workflow.replay.execute`),H=B.run(async()=>ce(...z)),U={workflowRun:t,argumentCount:z.length,async resume(e){switch(_.type){case`suspended`:{let t=O.events;if(!(e.length>t.length&&t.every((t,n)=>t.eventId===e[n].eventId)))return _={type:`replay`},{type:`replay`};let n=En();return _={type:`running`,interruption:n},k.suspensionGeneration++,B.refresh(),O.append(e.slice(t.length)),ue(H,n)}case`replay`:return{type:`replay`};case`completed`:case`running`:throw new X(`Cannot resume ${_.type} workflow "${t.runId}"`)}}},de=ue(H,g);return de.then(V.end,V.fail),{session:U,execution:de}}function Yo(e){let t=Ur();return t===void 0?e:e===void 0?t:Math.min(e,t)}function Xo({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.environment;if(!i)return!1;let a=e.getEnvironment?.();return!a||a===i?!1:(r.error(`Refusing to run this workflow: it was created in the "${i}" environment but this deployment runs in "${a}". Executing it here would create a second copy of the same run id in both environments — one pending forever, one running — so the queue message is being discarded without executing and without retrying. The client that called start() wrote the run to its own environment but addressed the queue message to a deployment in another one. Check that the environment that client authenticates as (WORKFLOW_VERCEL_ENV for CLI and CI clients, or the OIDC token's environment inside a deployment) matches the environment of the deployment it targets. The run it created is still pending in "${i}" and will not run.`,{workflowRunId:n,creatorEnvironment:i,currentEnvironment:a,pinnedDeploymentId:t?.deploymentId}),!0)}async function Zo({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.deploymentId;if(!i)return;let a;try{a=await e.getDeploymentId()}catch{return}!a||a===i||r.error(`Queue message was delivered to a deployment it was not pinned to. The run was created targeting a different deployment, so this invocation may be replaying against code the run was not started on. Continuing — this is expected if the Workflow SDK version changed mid-run in local development, where the deployment id is derived from that version.`,{workflowRunId:n,pinnedDeploymentId:i,currentDeploymentId:a})}function Qo(e){return X.is(e)?Y.RUNTIME_ERROR:or(e)?Y.WORLD_CONTRACT_ERROR:null}function $o(e){return!on.is(e)||e.status!==void 0&&e.status!==404?!1:/step/i.test(e.message)&&/not found/i.test(e.message)}async function es({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){G.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=Et(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(i,n,await o(),globalThis,(t?.specVersion??0)>=5),errorCode:a}},{requestId:r})}catch(e){if(Z.is(e)||q.is(e))return;if(or(e)){G.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:Y.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function ts(e,t){return e.find(e=>e.runId===t&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`))}function ns(e,t){let n=ts(e,t);return n?(G.debug(`Run reached terminal event, exiting`,{workflowRunId:t,eventType:n.eventType,eventId:n.eventId}),!0):!1}function rs(e,t){let n=0;for(let r of e)t.has(r)||n++;return n}function is(e,t){return e?.[Yn]??t}function as(e){let t=new Set,n=new Set;for(let r of e)switch(r.eventType){case`hook_created`:t.add(r.correlationId);break;case`hook_disposed`:t.delete(r.correlationId);break;case`wait_created`:n.add(r.correlationId);break;case`wait_completed`:n.delete(r.correlationId);break}return{openHook:t.size>0,openWait:n.size>0}}function os({suspension:e,serializationBlockerCount:t,hookContinuation:n=!1}){return qr()?t>0?{retain:!1,reason:`serialization_executed_workflow_code`}:n?{retain:!0}:e.stepCount===0&&e.attributeCount===0?{retain:!1,reason:`no_replay_driver`}:{retain:!0}:{retain:!1,reason:`disabled`}}function ss(e,t){return{serializationBlockerCount:t,serializationBlockers:e.map(({source:e,correlationId:t,kind:n,detail:r})=>({source:e,correlationId:t,kind:n,detail:r&&r.length>160?`${r.slice(0,160)}…`:r})),serializationBlockersTruncated:t>e.length}}function cs(e){return e.cursor===null?{type:`loadAll`}:{type:`loadAfter`,events:e.events,cursor:e.cursor}}async function ls(e,t){let n=process.env.WORKFLOW_V2_TIMEOUT_MS;if(n!==void 0&&n!==``){let e=Number(n);if(Number.isFinite(e)&&e>0)return e}let r=await e.getRuntimeDeadline?.();if(r!==void 0){let e=r.getTime();if(!Number.isNaN(e)){let n=Math.floor(e-t);if(n>=(0,Tr.default)(`25m`))return(0,Tr.default)(`10m`);if(n>=(0,Tr.default)(`10m`))return(0,Tr.default)(`5m`)}}return(0,Tr.default)(`2m`)}function us(e,t){jn(t?.basePath);let n=Rn(t?.namespace),r=Bn(`workflow`,n),i=t=>t.createQueueHandler(r,async(i,a)=>{let c=Date.now(),l=_t(i);if(l){await It(l,t.specVersion);return}let{runId:d,traceCarrier:f,requestedAt:p,stepId:m,stepName:h,replayDivergence:_,preconditionReinvocations:v,deploymentMismatchRetryCount:y,runInput:b,hookInput:x,stepInput:S,hookResumeTiming:C,waitContinuation:ee}=Xn.parse(i),w=wi(C,m===void 0?`inline`:`dispatched`);w&&m===void 0&&(w.consumerStartedAtMs=c),w&&!Number.isFinite(w.consumerStartedAtMs)&&(w=void 0);let T=Rt(f)?f:void 0,{requestId:E}=a,D=a.queueName.slice(r.length),O=G.forRun(d,D),te=Mr();if(a.attempt>te){let e=Or(void 0,Y.MAX_DELIVERIES_EXCEEDED);O.error(`Workflow handler exceeded max deliveries (${a.attempt}/${te})`,{attempt:a.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await gi(),t=Et(e,d),n=new J(`Workflow exceeded maximum queue deliveries (${a.attempt}/${te})`);await e.events.create(d,{eventType:`run_failed`,specVersion:7,eventData:{error:await g(n,d,await t()),errorCode:Y.MAX_DELIVERIES_EXCEEDED}},{requestId:E})}catch(e){if(Z.is(e)||q.is(e))return;O.error(`Failed to mark run as failed after ${a.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:a.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let A=Tt(),M=()=>st(A,T),ne=await xt(A,T),N=new yi,P=A===`continuous`?T:void 0,F=await Re(`CONSUMER`);return await Ot(P,async()=>await yt({workflowRunId:d,workflowName:D},async()=>{let t=await K(`workflow.route.get_world`,async()=>gi());if(!Xo({world:t,runInput:b,runId:d,runLogger:O}))return await Zo({world:t,runInput:b,runId:d,runLogger:O}),K(`workflow.execute ${le(D)}`,{kind:F,links:ne},async r=>{r?.setAttributes({...se(D),...ft(`execute_v2`),...oe(`vercel-queue`),...s(a.queueName),...ut(a.messageId),...re(`process`),...Ie({requestedAt:p}),...Se(d),...k(!!T),...At(A)});let i=Date.now(),c=await ls(t,i),l=0,f=_?new Si(_.count):Si.inert(),te,ne,P=await Ht(t=>{if(!(!t||nr(t)))return ne!==t.workflowName&&(ne=t.workflowName,te=Ho(e,t.workflowName),te.catch(()=>{})),te}),F=Tn(()=>{let e=Ne(t,d);return e.catch(()=>{}),e}),I,ie=e=>{if(!(!e||nr(e)))return I||=new Ar(F.value),I},ae=e=>{e.eventType===`run_created`&&(ie(e.eventData),P(e.eventData)),I?.prepareEvent(e)},R=async(e,n)=>{let r=ue(e,n),i={...le(),...n},a=await f.withEventCreate(r===void 0?i:{...i,sinceCursor:r},n=>t.events.create(d,e,n));return r!==void 0&&B(r,a),a},ce=(e,t)=>K(`workflow.replay.load`,async n=>{let r=0;n?.setAttributes({...Se(d),...z(e)});try{let e=await t(e=>{r++,ae(e)});return r=e.events?.length??r,e}finally{n?.setAttributes(ge(r))}}),le=()=>V.type===`loadAll`?{}:$t(V.events),ue=(e,t)=>{if(!(be||V.type!==`ready`||t?.sinceCursor!==void 0||t?.preloadEvents===!0||Vn(e.eventType)))return V.cursor??void 0},B=(e,t)=>{V.type!==`ready`||V.cursor!==e||t.events===void 0||t.hasMore===!0||it(V,{events:t.events,cursor:t.cursor})},V={type:`loadAll`},H,U,de=-1,pe,he,_e=0,ve,be=Kr()&&b!==void 0&&a.attempt===1&&m===void 0&&!_;r?.setAttributes(Ae(be));let xe,Ce=async()=>{if(xe)try{await xe}catch{}},W=async e=>{let n=Qo(e);return n?(await es({world:t,workflowRun:H,runId:d,requestId:E,err:e,errorCode:n,logMessage:`Fatal runtime error during workflow setup`}),!0):!1},Te=new Set,Ee=e=>{Te.size>0&&G.error(`Invariant violation: acking the workflow message while owned inline steps are still executing — crash recovery for these steps is broken`,{workflowRunId:d,ackPath:e,stepIds:[...Te]})},De=async()=>({runId:d,traceCarrier:await M(),requestedAt:new Date}),Oe=async(e,r)=>{if(Ee(`reinvoke`),!be)return{timeoutSeconds:e};await Ze(t,St(D,n),{...await De(),...r},e>0?{delaySeconds:e}:void 0)},ke=0,je=null,Me=e=>{let t=je;if(!t)return;je=null;let n=new Set(e.map(e=>e.eventId)),r=rs(n,t.ids),i=rs(t.ids,n),a=i>0?`shrank`:r>0?`grew`:`unchanged`;G.warn(`Restarted replay reloaded its event log after a stale-snapshot rejection`,{workflowRunId:d,outcome:a,added:r,dropped:i,eventsBefore:t.ids.size,eventsAfter:n.size,preconditionRestarts:t.restart,reason:t.reason,source:t.source,loopIteration:l})},Pe=(e,t,{allowDelta:n=!0}={})=>{if(ke>=Zr())return!1;ke++,Ve=null;let i=n&&ke===1?tt(t,d):null,a=i!==null&&V.type!==`loadAll`;return je=V.type===`loadAll`?null:{ids:new Set(V.events.map(e=>e.eventId)),restart:ke,reason:e,source:a?`inline-delta`:`full-reload`},i&&V.type!==`loadAll`?(it(V,i),V={...V,type:`ready`}):(V={type:`loadAll`},I?.resetScan()),G.warn(`Event creation rejected as stale; restarting replay in-process`,{workflowRunId:d,reason:e,loopIteration:l,preconditionRestarts:ke,source:a?`inline-delta`:`full-reload`}),r?.setAttributes({"workflow.precondition_restarts":ke}),!0},Fe=async(e,t)=>{let n=(v??0)+1,i=Qr();return n>i?{reinvoked:!1,error:new X(`Event creation was rejected as stale after ${i} re-invocations of ${Zr()} in-process replay restarts each: this run cannot observe its own event log completely enough to make progress. Last rejection (${e}): ${t instanceof Error?t.message:String(t)}`,{cause:t})}:(G.warn(`Event creation rejected as stale after in-process restarts; re-invoking run for a fresh replay`,{workflowRunId:d,reason:e,loopIteration:l,preconditionReinvocations:n,maxReinvocations:i}),r?.setAttributes({"workflow.precondition_reinvocations":n}),{reinvoked:!0,result:await Oe($r(),{preconditionReinvocations:n})})},Re=async(e,i,a)=>{let{outcome:o,spanAttributes:s}=await ai({world:t,run:e,requestId:E,retryCount:y,beforeStop:a,isDeploymentUnavailableError:t.isDeploymentUnavailableError,reenqueue:async({deploymentId:e,specVersion:r,deploymentMismatchRetryCount:a,delaySeconds:o})=>{await Ze(t,St(D,n),{...await i(),deploymentMismatchRetryCount:a},{deploymentId:e,specVersion:r,delaySeconds:o})}});return s&&r?.setAttributes(s),o};if(m&&h)try{let e=async()=>{if(!S)return`ok`;try{await t.events.create(d,{eventType:`step_created`,specVersion:7,correlationId:m,eventData:{stepName:h,workflowName:D,input:S.input}},{requestId:E,viaStepDispatch:!0}),r?.setAttributes(Le(!0)),G.warn(`Materialized step_created from the queue message — the producer’s direct write did not land`,{workflowRunId:d,stepId:m,stepName:h})}catch(e){if(Z.is(e))return`ok`;if(q.is(e))return`gone`;throw e}return`ok`},[i,o]=await Promise.all([t.runs.get(d,{resolveData:`none`}),S&&a.attempt>1?e():`ok`]);if(o===`gone`){G.debug(`Run already finished, skipping background step`,{workflowRunId:d});return}if(i.status!==`running`){G.debug(`Run already finished, skipping background step`,{workflowRunId:d,status:i.status});return}if(await Re(i,async()=>({...await De(),stepId:m,stepName:h,...C?{hookResumeTiming:C}:{}}))!==`continue`)return;let s=i.startedAt?+i.startedAt:Date.now(),c=a.attempt,l=On(h)?.maxRetries??3;a.attempt>l+1&&(c=ni((await Ue(d)).events,m,{type:`totalAttempts`})+1);let u=w;w=void 0,N.pause();let f;try{let n=()=>Gi({world:t,workflowRunId:d,workflowDeploymentId:i.deploymentId,workflowName:D,workflowStartedAt:s,requestId:E,rootRunId:is(i.attributes,d),stepId:m,stepName:h,runSpecVersion:i.specVersion,authoritativeAttempt:c,...u?{resumeTracking:u}:{}});f=await Zi(d,m,async()=>{try{return await n()}catch(t){if(!S||!$o(t))throw t;return await e()===`gone`?{type:`gone`}:await n()}})}finally{N.resume()}if(f.type===`retry`||f.type===`throttled`)return{timeoutSeconds:f.timeoutSeconds};if(f.type===`completed`&&f.hasPendingOps){await Ze(t,St(D,n),{runId:d,traceCarrier:await M(),requestedAt:new Date});return}if(f.type===`completed`||f.type===`failed`||f.type===`skipped`){let e=await Ue(d);V=cs(e);let n=new Set,r=new Set;for(let t of e.events)t.eventType===`step_created`?n.add(t.correlationId):(t.eventType===`step_completed`||t.eventType===`step_failed`)&&r.add(t.correlationId);let o=new Set;for(let e of n)r.has(e)||o.add(e);if(o.size>0)if(Jr()&&Yi(e.events,o,a.messageId))G.debug(`Background step done; falling through to recover an inline step owned by this message`,{workflowRunId:d});else{G.debug(`Background step done but other steps pending, returning`,{workflowRunId:d});return}P(i),G.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:d});let c=e.events.find(e=>e.eventType===`run_created`),l;if(c)l=c.eventData.input;else{if(!Wn(i.specVersion))throw new X(`Workflow run "${d}" has no "run_created" event`);let e=await t.runs.get(d,{resolveData:`all`});if(e.status!==`running`)return;l=e.input}H={...i,input:l,status:`running`,output:void 0,error:void 0,completedAt:void 0},de=s}else return}catch(e){let n=Qo(e);if(!n)throw e;await es({world:t,workflowRun:H,runId:d,requestId:E,err:e,errorCode:n,logMessage:`Fatal error while preparing background workflow step`});return}if(!H&&x?.deploymentId!==void 0&&t.capabilities?.deploymentAffinity===!0){let e=x.deploymentId,n;try{n=await t.getDeploymentId()}catch{n=void 0}if(n!==void 0&&n!==e&&await Re(await t.runs.get(d,{resolveData:`none`}),async()=>({...await De(),hookInput:x,...C?{hookResumeTiming:C}:{}}),Ce)!==`continue`)return}let Be=!1;if(!H&&x&&x.resumeId!==void 0&&x.payloadDigest!==void 0){let e=x,t;try{t=new Date(Hn(e.resumeId))}catch{t=void 0}try{r?.addEvent(`workflow.hook_received.create.start`,{"workflow.hook_received.preload_events":!0});let n=await ce(`hook_preload`,n=>R({eventType:`hook_received`,specVersion:7,correlationId:e.hookId,eventData:{token:e.token,payload:e.payload}},{requestId:E,occurredAt:t,resumeId:e.resumeId,resumePayloadDigest:e.payloadDigest,preloadEvents:!0,replayEventObserver:n}));if(Be=!0,n.run!==void 0&&n.run.startedAt!==void 0&&n.event!==void 0&&n.events!==void 0&&n.events.length>0&&n.cursor!=null&&n.hasMore===!1&&typeof n.maxEvents==`number`&&n.events.some(e=>e.eventType===`run_created`)&&n.events.some(e=>e.eventType===`run_started`)&&n.events.some(t=>t.eventType===`hook_received`&&t.resumeId===e.resumeId)&&n.run?.startedAt&&n.events){let e=n.events.find(e=>e.runId===d&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`));if(e){r?.setAttributes({...ye(e.eventType===`run_completed`?`completed`:e.eventType===`run_failed`?`failed`:`cancelled`),...Xt(`hook_received_stream`)}),G.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:d,eventType:e.eventType});return}H=n.run,P(H),U=Yo(n.maxEvents),he=Date.now(),w&&(w.setupSource=`hook_preload`),V={type:`ready`,events:n.events,cursor:n.cursor},de=+n.run.startedAt,r?.setAttributes({...ye(n.run.status),...we(de),...Xt(`hook_received_stream`)})}else r?.setAttributes(Xt(`hook_received_fallback`))}catch(e){if(gn.is(e)||q.is(e)){G.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:d,message:e.message});return}if(await W(e))return;throw e}}if(!H){let e={eventType:`run_started`,specVersion:b?.specVersion??7,...b?{eventData:{input:b.input,deploymentId:b.deploymentId,workflowName:b.workflowName,executionContext:b.executionContext,attributes:b.attributes,allowReservedAttributes:b.allowReservedAttributes}}:{}};if(be&&b){r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":!0});let t=R(e,{requestId:E,skipPreload:!0});xe=t;try{P(b),ie(b)}catch(e){if(await Ce(),!await W(e))throw e;return}t.then(e=>{let t=Yo(e.maxEvents);t!==void 0&&(U=t)}).catch(()=>{}),V={type:`ready`,events:[],cursor:null};let n=new Date;H={runId:d,status:`running`,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,attributes:b.attributes??{},startedAt:n,createdAt:n,updatedAt:n},de=+n,he=+n,r?.setAttributes({...ye(`running`),...we(de)})}else try{r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":!1});let t=ce(`run_started`,t=>R(e,{requestId:E,replayEventObserver:t}));try{P(b),ie(b)}catch(e){try{await t}catch{}throw e}let n=await t;if(H=n.run,U=Yo(n.maxEvents),he=Date.now(),w&&(w.setupSource=`run_started`),n.events?.length){let e={events:[...n.events],cursor:n.cursor??null};V=n.hasMore?cs(e):{...e,type:`ready`}}if(de=+n.run.startedAt,r?.setAttributes({...ye(n.run.status),...we(de)}),n.run.status!==`running`){G.info(`Workflow already completed or failed, skipping`,{workflowRunId:d,status:n.run.status});return}P(H)}catch(e){if(Z.is(e)||q.is(e)){G.info(`Run already finished during setup, skipping`,{workflowRunId:d,message:e.message});return}else{if(!await W(e))throw e;return}}}if(vr(H,`Workflow run must be loaded before replay`),w&&w.setupSource===void 0&&(w.setupSource=`event_load`),await Re(H,async()=>({...await De(),...x?{hookInput:x}:{},...C?{hookResumeTiming:C}:{}}),Ce)!==`continue`)return;if(x&&!Be&&!(x.resumeId!==void 0&&V.type!==`loadAll`&&V.events.some(e=>e.eventType===`hook_received`&&e.resumeId===x.resumeId))){let e;try{e=x.resumeId===void 0?void 0:new Date(Hn(x.resumeId))}catch{e=void 0}let n;try{let i=await t.events.create(d,{eventType:`hook_received`,specVersion:7,correlationId:x.hookId,eventData:{token:x.token,payload:x.payload}},{requestId:E,occurredAt:e,resumeId:x.resumeId,resumePayloadDigest:x.payloadDigest});r?.setAttributes(me(!0));let a=i.event;n=a?{...a,eventData:{token:x.token,payload:x.payload}}:void 0}catch(e){if(gn.is(e)||q.is(e))return;throw e}V.type!==`loadAll`&&n?(mt(V.events,n),ae(n)):V={type:`loadAll`}}let Ve=null,He=new Set;for(;;){if(l++,N.isExhausted()){await xi({runId:d,workflowName:D,requestId:E,attempt:a.attempt,limitMs:N.configuredLimitMs,slotSnapshot:le()});return}if(Date.now()-i>=c){G.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:d,loopIteration:l,elapsedMs:Date.now()-i}),await Ze(t,St(D,n),{runId:d,traceCarrier:await M(),requestedAt:new Date});return}let s=0,p=!1;try{if(nr(H)){G.debug(`Using QuickJS VM engine`,{workflowRunId:d,loopIteration:l}),await Ce(),V.type===`loadAfter`&&(it(V,await Ue(d,V.cursor)),V={...V,type:`ready`});let{runWorkflowWithQuickJS:t}=await import(`../../_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js`),i=await t({workflowCode:e,workflowName:D,workflowRun:H,preloadedEvents:V.type===`ready`?V.events:void 0,preloadedEventsComplete:V.type===`ready`,runInput:b,parentSpan:r,maxEventsLimit:U,namespace:n,nextTraceCarrier:M,waitContinuation:ee,deliveryAttempt:a.attempt,ownerMessageId:a.messageId,requestId:E});return i?.timeoutSeconds===void 0?void 0:await Oe(i.timeoutSeconds)}if(V.type!==`ready`){let e=await Ue(d,V.type===`loadAfter`?V.cursor:void 0);V.type===`loadAfter`?(it(V,e),V={...V,type:`ready`}):V={...e,type:`ready`}}if(vr(V.type===`ready`),Me(V.events),ns(V.events,d))return;let i=Date.now(),o=new Set(V.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),c=V.events.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!o.has(e.correlationId)&&i>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:7,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of c)try{let t=await R(e,{requestId:E});Mt(V.events,t)}catch(t){if(Z.is(t)){G.info(`Wait already completed, skipping`,{workflowRunId:d,correlationId:e.correlationId});continue}throw t}vr(V.type===`ready`);let u=new Set(V.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),m=c.filter(e=>!u.has(e.correlationId));if(m.length>0)if(V.cursor){let e=await Ue(d,V.cursor),t=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));m.every(e=>t.has(e.correlationId))?it(V,e):V={...await Ue(d),type:`ready`}}else V={...await Ue(d),type:`ready`};if(Ut()){let e=await Gt(d,{events:V.events,cursor:V.cursor});if(V={...e.log,type:`ready`},e.gap!==void 0)throw new vn(`Event log for run ${d} has a hole at slot ${e.gap.firstMissingSlot}: ${e.gap.missingCount} of the ${e.gap.maxSlot} slots up to the log's maximum hold no event.`)}if(ns(V.events,d))return;if(U!==void 0){let e=V.events.reduce((e,t)=>Gn(t)?e:e+1,0);if(e>=U)throw new _n(e,U)}pe??=V.events.every(e=>e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`||Gn(e)),G.debug(`Starting workflow execution`,{workflowRunId:d,loopIteration:l,eventCount:V.events.length,executionMode:Ve?`retained`:`replay`}),s=Date.now(),w&&(w.replayStartedAtMs??=s);let h=ie(H);vr(h,`Node workflow replay requires payload preparation`);let g=h.prewarm(H,V.events),_=Ve?await Wo(Ve,V.events):{type:`replay`};if(p=Ve!==null&&_.type!==`replay`,_.type===`replay`){Ve=null;let n=P(H);vr(n,`Node workflow replay requires compiled scripts`),_=await Uo({workflowCode:e,workflowRun:H,events:V.events,encryptionKey:await F.value,replayPayloadCache:h,compiledWorkflowScripts:await n,runReadyBarrier:xe,worldCapabilities:t.capabilities})}if(await g,_.type===`suspended`)throw Ve=_.session,_.suspension;let v=_.output;G.debug(`Workflow execution completed`,{workflowRunId:d,loopIteration:l,replayMs:Date.now()-s,executionMode:Ve?`retained`:`replay`}),f.activate();try{await Ce(),await R({eventType:`run_completed`,specVersion:7,eventData:{output:v}},{requestId:E})}catch(e){if(Z.is(e)||q.is(e)){G.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}throw e}r?.setAttributes({...ye(`completed`)});return}catch(i){if(An.is(i)){f.activate();let e=Date.now(),c=e-s;w&&i.stepCount>0&&(w.nextStepEncounteredAtMs??=e),G.debug(`Workflow suspended`,{workflowRunId:d,loopIteration:l,replayMs:c,steps:i.stepCount,hooks:i.hookCount,waits:i.waitCount});let m=j(i.stepCount,i.hookCount,i.waitCount);m&&G.debug(m);let h=Date.now();vr(V.type===`ready`,`Workflow suspended before its event log was loaded`);let _;try{_=await $i({suspension:i,world:t,run:H,span:r,requestId:E,eventLog:V,runReadyBarrier:xe,replayRecoveryReporter:f,stepDispatch:{queueName:St(D,n),getTraceCarrier:M},ownerMessageId:a.messageId,allowDeferredBatchWork:!0})}catch(e){if(fn.is(e)){if(Pe(`suspension-create`,e))continue;let t=await Fe(`suspension-create`,e);if(t.reinvoked)return t.result;throw t.error}if(!J.is(e))throw e;let t=rr(e);G.error(`Non-retryable error while committing workflow suspension; failing run`,{workflowRunId:d,errorCode:t,errorName:e.name,errorMessage:e.message});try{await Ce(),await R({eventType:`run_failed`,specVersion:7,eventData:{error:await g(e,d,await F.value,globalThis,(H?.specVersion??0)>=5),errorCode:t}},{requestId:E})}catch(e){if(Z.is(e)||q.is(e)){G.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}throw e}r?.setAttributes({...ye(`failed`),...fe(t),...Jt(e.name),...u(e.message),...qt(e.name)});return}let v=Tn(()=>(vr(V.type===`ready`),as(V.events))),y=Ve?os({suspension:i,serializationBlockerCount:_.serializationBlockerCount,hookContinuation:_.hasAwaitedHookCreation||_.hasHookConflict}):void 0;y?.retain===!1&&(Ve=null),_e+=_.hookCreationMs,_.hasAttributeEvents&&ve===void 0&&(ve=_e),G.debug(`Suspension handled`,{workflowRunId:d,suspensionMs:Date.now()-h,pendingSteps:_.pendingSteps.length,timeoutSeconds:_.waitTimeout?.seconds,hasHookConflict:_.hasHookConflict,hasAwaitedHookCreation:_.hasAwaitedHookCreation,hasAttributeEvents:_.hasAttributeEvents,...y?{workflowVmRetention:y.retain?`retained`:`replay`}:{},...y?.retain===!1?{workflowVmRetentionReason:y.reason}:{},..._.serializationBlockerCount>0?ss(_.serializationBlockers,_.serializationBlockerCount):{}});let b=(e,t)=>{if(!Ve)return!1;let n=e.filter(e=>!He.has(e));if(n.length===0)return!1;for(let e of n)He.add(e);let i=_.eventLogCarriedForward&&!v.value.openWait;return i||(vr(V.type===`ready`),V=cs(V)),G.debug(`Continuing over a hook write in-process`,{workflowRunId:d,loopIteration:l,settles:t,hookIds:n,carriedForward:_.eventLogCarriedForward,readBeforeResume:!i}),r?.setAttributes({"workflow.hook_write_continuations":He.size}),!0};if(_.hasHookConflict){if(b(_.hookConflictCorrelationIds,`hook_conflict`))continue;return await Oe(0)}if(_.hasAttributeEvents){V=cs(V);continue}if(_.failedStepCorrelationIds.size>0){await _.deferredBatchWork,Ve=null,V=cs(V);continue}let x=_.pendingSteps,S=_.lazyInlineSteps,C=new Set(S.map(e=>e.correlationId)),T=await M(),O=[],te=Jr(),k=Date.now(),A=[],ne=0,P=w!==void 0&&S.length===0&&!x.some(e=>!C.has(e.correlationId)&&te&&Ki(e)&&e.ownerMessageId===a.messageId);for(let e of x){if(C.has(e.correlationId)||_.queuedStepCorrelationIds.has(e.correlationId))continue;let r=te&&Ki(e);if(r&&e.ownerMessageId===a.messageId){A.push(e);continue}let i=r?qi(e,k):0;if(i>0){ne++,G.debug(`Pending step is inline-owned by a live invocation; ensuring delayed backstop wake instead of immediate requeue`,{workflowRunId:d,stepId:e.correlationId,ownerMessageId:e.ownerMessageId,backstopDelaySeconds:i}),O.push(Ze(t,St(D,n),{runId:d,traceCarrier:T,requestedAt:new Date},{delaySeconds:i,idempotencyKey:Ji(e)}));continue}let o=P?Ti(w):void 0;o&&(P=!1,w=void 0),O.push(Ze(t,St(D,n),{runId:d,stepId:e.correlationId,stepName:e.stepName,traceCarrier:T,requestedAt:new Date,...o?{hookResumeTiming:o}:{}},{idempotencyKey:ze(e.correlationId,e.stepName)}))}if(_.waitTimeout){let e=ee?.correlationId===_.waitTimeout.correlationId?ee.attempt+1:0;O.push(Ze(t,St(D,n),{runId:d,traceCarrier:T,requestedAt:new Date,waitContinuation:{correlationId:_.waitTimeout.correlationId,attempt:e}},ra(_.waitTimeout.seconds,_.waitTimeout.correlationId,Date.now(),e)))}let I=Promise.all(O);I.catch(()=>{});let L=[...S.map(e=>{let t=_.inlineClaims.get(e.correlationId);return t?{correlationId:e.correlationId,stepName:e.stepName,preclaimedStart:t}:{correlationId:e.correlationId,stepName:e.stepName,lazyStepInput:e.dehydratedInput}}),...A.map(e=>({correlationId:e.correlationId,stepName:e.stepName}))];if((ne>0||A.length>0)&&r?.setAttributes({...A.length>0?o(A.length):{},...ne>0?Kt(ne):{}}),A.length>0&&G.warn(`Re-executing inline steps owned by this queue message — a previous delivery crashed mid-body and this redelivery is recovering them`,{workflowRunId:d,stepIds:A.map(e=>e.correlationId)}),L.length===0){if(await Promise.all([I,_.deferredBatchWork]),_.hasAwaitedHookCreation){if(b(_.awaitedHookCorrelationIds,`hook_created`))continue;return await Oe(0)}return}let re=v.value,ie=typeof V.cursor==`string`&&i.stepCount===1&&i.waitCount===0&&x.length===1&&S.length===1&&A.length===0&&!_.waitTimeout&&!re.openWait,ae=re.openHook||i.hookCount>0||_.hasHookEvents,oe=be&&!_.hasAttributeEvents&&!_.waitTimeout&&!_.hasHookEvents&&!_.hasAwaitedHookCreation&&!re.openHook&&!re.openWait,se=zi({events:V.events,invocationStartedClean:pe===!0,runCreatedAtMs:Oi(d)??(be?void 0:+H.createdAt),runStartedReceivedAtMs:he,replayMs:c,preStepBlockingMs:_e,preStepBlockingBeforeAttrMs:ve,suspensionHasWaits:i.waitCount>0||_.waitTimeout!==void 0,suspensionCreatedHooks:i.hookCount>0||_.hasHookEvents,turbo:be,retained:p}),ce=$t(V.events),z=_.batchCommittedSlotCeiling,le=z!==void 0&&z>(ce.eventCount??0)?{eventCount:z}:ce,ue=w;w=void 0,N.pause();let B,U=L.map((e,n)=>{let r=()=>(vr(V.type===`ready`),Gi({world:t,workflowRunId:d,workflowDeploymentId:H.deploymentId,workflowName:D,workflowStartedAt:de,requestId:E,rootRunId:is(H.attributes,d),stepId:e.correlationId,stepName:e.stepName,runSpecVersion:H.specVersion,authoritativeAttempt:e.lazyStepInput!==void 0||e.preclaimedStart!==void 0?1:ni(V.events,e.correlationId,{type:`ownedBy`,messageId:a.messageId})+1,lazyStepInput:e.lazyStepInput,preclaimedStart:e.preclaimedStart,ownerMessageId:a.messageId,forceOptimisticStart:oe,suppressOptimisticStart:ae,runReadyBarrier:xe,slotSnapshot:le,...n===0&&(e.lazyStepInput!==void 0||e.preclaimedStart!==void 0)&&se?{latencyTracking:se}:{},...ue?{resumeTracking:ue}:{},...ie&&V.cursor?{inlineDeltaSinceCursor:V.cursor}:{},replayRecoveryReporter:f}));return Te.add(e.correlationId),(e.lazyStepInput===void 0&&e.preclaimedStart===void 0?Zi(d,e.correlationId,r):r()).finally(()=>Te.delete(e.correlationId))});for(let e of U)e.catch(()=>{});try{try{await Promise.all([I,_.deferredBatchWork])}catch(e){throw await Promise.allSettled(U),e}B=await Promise.all(U)}catch(e){if(fn.is(e)){if(Pe(`inline-claim`,e,{allowDelta:!(await Promise.allSettled(U)).some(e=>e.status===`fulfilled`&&(e.value.type===`completed`||e.value.type===`failed`||e.value.type===`retry`))}))continue;let t=await Fe(`inline-claim`,e);if(t.reinvoked)return t.result;throw t.error}throw e}finally{N.resume()}let me=[],ge=!1,Se;for(let e=0;e<L.length;e++){let t=B[e],n=L[e];t.type===`retry`?me.push({step:n,delaySeconds:t.timeoutSeconds}):t.type===`throttled`?Se=Math.max(Se??0,t.timeoutSeconds):t.type===`completed`&&t.hasPendingOps&&(ge=!0)}if(Se!==void 0)return await Oe(Se);if(me.length>0){let e=await M();await Promise.all(me.map(({step:r,delaySeconds:i})=>Ze(t,St(D,n),{runId:d,stepId:r.correlationId,stepName:r.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:i,idempotencyKey:ze(r.correlationId,r.stepName)})))}if(ge){G.debug(`Breaking loop: inline step has pending ops`,{workflowRunId:d,loopIteration:l}),await Ze(t,St(D,n),{runId:d,traceCarrier:await M(),requestedAt:new Date});return}if(me.length>0)return;if(L.length===1){let e=B[0];if(e.type===`completed`&&e.inlineDelta){it(V,e.inlineDelta),V=e.inlineDelta.hasMore?cs(V):{...V,type:`ready`};continue}}V=cs(V)}else{let o=i;if(fn.is(i)){if(Pe(`replay-write`,i))continue;let e=await Fe(`replay-write`,i);if(e.reinvoked)return e.result;o=e.error}if(lr(i))throw O.warn(`Transient world error during replay; redelivering via queue instead of failing the run`,{errorName:i instanceof Error?i.name:`UnknownError`,errorMessage:i instanceof Error?i.message:String(i),deliveryAttempt:a.attempt}),i;let c;if(pn.is(i)){let e=(_?.count??0)+1,r=Xr();if(e<=r){O.warn(`Workflow replay diverged; queueing a recovery replay before declaring the event log corrupted`,{errorCode:Y.REPLAY_DIVERGENCE,divergenceEventId:i.eventId,priorDivergenceEventId:_?.eventId,divergenceCount:e,deliveryAttempt:a.attempt,maxRecoveryReplays:r,errorMessage:i.message}),await Ze(t,St(D,n),{runId:d,traceCarrier:await M(),requestedAt:new Date,replayDivergence:{eventId:i.eventId,count:e}});return}c=e,o=new vn(`Workflow replay diverged ${e} times after ${r} recovery replays; latest divergent event was ${i.eventId}. Last divergence: ${i.message}`,{cause:i})}else s>0&&f.activate();o instanceof Error&&r?.recordException?.(o);let l=await Fi(o),p=l.name||ki(o),m=l.message,h=l.stack||Ai(o);if(h){let t=L(D)?.moduleSpecifier||D;h=co(h,t,e)}let v=rr(o);G.error(`Error while running workflow`,{workflowRunId:d,errorCode:v,errorName:p,errorStack:h}),_r.isNativeError(o)&&h&&(o.stack=h);try{await Ce(),await R({eventType:`run_failed`,specVersion:7,eventData:{error:await g(o,d,await F.value,globalThis,(H?.specVersion??0)>=5),errorCode:v}},{requestId:E,...c===void 0?{}:{replayDivergenceCount:c}})}catch(e){if(Z.is(e)||q.is(e)){G.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:d,message:e.message});return}if(or(e)){G.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:d,errorCode:Y.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...ye(`failed`),...fe(v),...Jt(p),...u(m),...qt(p)});return}}}})}))}),a,l=0,d=Date.now(),f=typeof t?.routeModuleBodyStartedAt==`number`?d-t.routeModuleBodyStartedAt:void 0;return Zt(async e=>{l+=1;let t=a!==void 0;return K(`workflow.route.flow`,{kind:await Re(`SERVER`),attributes:{...c(`flow`),...tn(jr),...P(t),...U(l),...D(Date.now()-d),...f===void 0?{}:rn(f),...h(e.method),...pt(`/.well-known/workflow/v1/flow`)}},async t=>{a||=await K(`workflow.route.init`,async()=>{let e=await K(`workflow.route.get_world_handlers`,async()=>gi());return i(e)});let n=await a(e);return n instanceof Response&&t?.setAttributes(ce(n.status)),n})})}export{fr as Run,An as WorkflowSuspension,ur as cancelRun,ir as cancelRuns,mi as createWorld,fi as createWorldFromModule,$n as getHookByToken,sr as getRun,gi as getWorld,hi as getWorldHandlers,Ve as healthCheck,er as listStreams,cr as readStream,dr as recreateRunFromExisting,tr as reenqueueRun,Zn as resumeHook,Qn as resumeWebhook,_i as setWorld,pr as start,ar as wakeUpRun,us as workflowEntrypoint};
|