mayura 0.1.0-dev.0 → 1.0.0-rc.2
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/README.md +152 -35
- package/docs/README.md +82 -0
- package/docs/ai-agents.md +73 -0
- package/docs/cli/dev.md +111 -0
- package/docs/cli/init.md +192 -0
- package/docs/cli/operations.md +235 -0
- package/docs/cli/overview.md +129 -0
- package/docs/cli/run.md +182 -0
- package/docs/concepts/agent.md +197 -0
- package/docs/concepts/costs-and-budgets.md +177 -0
- package/docs/concepts/outcomes.md +154 -0
- package/docs/concepts/permissions.md +155 -0
- package/docs/concepts/runtime.md +172 -0
- package/docs/concepts/tools.md +202 -0
- package/docs/concepts/workflows.md +134 -0
- package/docs/guides/approvals-and-human-input.md +278 -0
- package/docs/guides/artifacts.md +123 -0
- package/docs/guides/child-agents.md +158 -0
- package/docs/guides/code-mode.md +233 -0
- package/docs/guides/deployment.md +644 -0
- package/docs/guides/durable-workflows.md +463 -0
- package/docs/guides/guardrails.md +205 -0
- package/docs/guides/helpers.md +176 -0
- package/docs/guides/lifecycle-hooks.md +187 -0
- package/docs/guides/mcp.md +123 -0
- package/docs/guides/memory-and-context.md +293 -0
- package/docs/guides/model-providers.md +371 -0
- package/docs/guides/model-routing.md +138 -0
- package/docs/guides/observability.md +238 -0
- package/docs/guides/operator-console.md +140 -0
- package/docs/guides/react.md +276 -0
- package/docs/guides/sagas-and-loops.md +212 -0
- package/docs/guides/server-and-client.md +559 -0
- package/docs/guides/skills.md +152 -0
- package/docs/guides/storage.md +251 -0
- package/docs/guides/streaming.md +146 -0
- package/docs/guides/terminal.md +166 -0
- package/docs/guides/testing.md +220 -0
- package/docs/guides/vision.md +155 -0
- package/docs/guides/webhooks.md +172 -0
- package/docs/guides/workflow-composition.md +141 -0
- package/docs/guides/workflow-operations.md +269 -0
- package/docs/installation.md +90 -0
- package/docs/introduction.md +74 -0
- package/docs/project/credits.md +78 -0
- package/docs/project/security.md +178 -0
- package/docs/project/support.md +91 -0
- package/docs/project/versioning.md +122 -0
- package/docs/quickstart.md +190 -0
- package/docs/reference/entry-points.md +146 -0
- package/lib/adapter-code-docker/dist/index.d.ts +8 -1
- package/lib/adapter-code-docker/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-docker/dist/index.js +64 -67
- package/lib/adapter-code-docker/dist/index.js.map +1 -1
- package/lib/adapter-code-docker/dist/options.d.ts +15 -0
- package/lib/adapter-code-docker/dist/options.d.ts.map +1 -0
- package/lib/adapter-code-docker/dist/options.js +56 -0
- package/lib/adapter-code-docker/dist/options.js.map +1 -0
- package/lib/adapter-code-docker/image/Dockerfile +4 -2
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-docker/src/index.ts +63 -65
- package/lib/adapter-code-docker/src/options.ts +51 -0
- package/lib/adapter-code-quickjs/dist/index.d.ts +16 -4
- package/lib/adapter-code-quickjs/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-quickjs/dist/index.js +94 -50
- package/lib/adapter-code-quickjs/dist/index.js.map +1 -1
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts +27 -0
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js +66 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker.js +421 -104
- package/lib/adapter-code-quickjs/dist/worker.js.map +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-code-quickjs/src/index.ts +88 -44
- package/lib/adapter-code-quickjs/src/worker-command.ts +68 -0
- package/lib/adapter-code-quickjs/src/worker.ts +315 -89
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/artifacts/dist/contracts.d.ts +6 -2
- package/lib/artifacts/dist/contracts.d.ts.map +1 -1
- package/lib/artifacts/dist/contracts.js.map +1 -1
- package/lib/artifacts/dist/index.d.ts +1 -0
- package/lib/artifacts/dist/index.d.ts.map +1 -1
- package/lib/artifacts/dist/index.js +1 -0
- package/lib/artifacts/dist/index.js.map +1 -1
- package/lib/artifacts/dist/local-store.d.ts.map +1 -1
- package/lib/artifacts/dist/local-store.js +4 -7
- package/lib/artifacts/dist/local-store.js.map +1 -1
- package/lib/artifacts/dist/media.d.ts +11 -0
- package/lib/artifacts/dist/media.d.ts.map +1 -0
- package/lib/artifacts/dist/media.js +18 -0
- package/lib/artifacts/dist/media.js.map +1 -0
- package/lib/artifacts/package.json +1 -1
- package/lib/artifacts/src/contracts.ts +6 -2
- package/lib/artifacts/src/index.ts +1 -0
- package/lib/artifacts/src/local-store.ts +5 -7
- package/lib/artifacts/src/media.ts +20 -0
- package/lib/cli/dist/agent-guide.d.ts +10 -0
- package/lib/cli/dist/agent-guide.d.ts.map +1 -0
- package/lib/cli/dist/agent-guide.js +48 -0
- package/lib/cli/dist/agent-guide.js.map +1 -0
- package/lib/cli/dist/application.d.ts +24 -0
- package/lib/cli/dist/application.d.ts.map +1 -1
- package/lib/cli/dist/application.js +21 -0
- package/lib/cli/dist/application.js.map +1 -1
- package/lib/cli/dist/bin.js +26 -6
- package/lib/cli/dist/bin.js.map +1 -1
- package/lib/cli/dist/dev.d.ts.map +1 -1
- package/lib/cli/dist/dev.js +7 -1
- package/lib/cli/dist/dev.js.map +1 -1
- package/lib/cli/dist/index.d.ts +3 -3
- package/lib/cli/dist/index.d.ts.map +1 -1
- package/lib/cli/dist/index.js +19 -9
- package/lib/cli/dist/index.js.map +1 -1
- package/lib/cli/dist/interactive.d.ts.map +1 -1
- package/lib/cli/dist/interactive.js +52 -11
- package/lib/cli/dist/interactive.js.map +1 -1
- package/lib/cli/dist/operations.d.ts +25 -2
- package/lib/cli/dist/operations.d.ts.map +1 -1
- package/lib/cli/dist/operations.js +125 -12
- package/lib/cli/dist/operations.js.map +1 -1
- package/lib/cli/dist/output.d.ts.map +1 -1
- package/lib/cli/dist/output.js +3 -0
- package/lib/cli/dist/output.js.map +1 -1
- package/lib/cli/dist/providers.d.ts +34 -4
- package/lib/cli/dist/providers.d.ts.map +1 -1
- package/lib/cli/dist/providers.js +26 -5
- package/lib/cli/dist/providers.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/agent-guide.ts +47 -0
- package/lib/cli/src/application.ts +24 -0
- package/lib/cli/src/bin.ts +22 -5
- package/lib/cli/src/dev.ts +5 -1
- package/lib/cli/src/index.ts +18 -10
- package/lib/cli/src/interactive.ts +44 -12
- package/lib/cli/src/operations.ts +82 -12
- package/lib/cli/src/output.ts +3 -0
- package/lib/cli/src/providers.ts +45 -10
- package/lib/cli/starters/approval-workflow/dot-env.example +11 -0
- package/lib/cli/starters/approval-workflow/package.json +1 -2
- package/lib/cli/starters/approval-workflow/src/config.ts +25 -7
- package/lib/cli/starters/approval-workflow/src/intake.ts +1 -2
- package/lib/cli/starters/approval-workflow/src/model.ts +11 -4
- package/lib/cli/starters/approval-workflow/src/workflow.ts +1 -2
- package/lib/cli/starters/cli-agent/README.md +121 -0
- package/lib/cli/starters/cli-agent/dot-env.example +37 -0
- package/lib/cli/starters/cli-agent/dot-github/workflows/ci.yml +13 -0
- package/lib/cli/starters/cli-agent/dot-gitignore +10 -0
- package/lib/cli/starters/cli-agent/mayura.project.json +15 -0
- package/lib/cli/starters/cli-agent/package.json +28 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/SKILL.md +18 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/references/example.md +12 -0
- package/lib/cli/starters/cli-agent/src/assistant.ts +124 -0
- package/lib/cli/starters/cli-agent/src/cli.ts +72 -0
- package/lib/cli/starters/cli-agent/src/config.ts +117 -0
- package/lib/cli/starters/cli-agent/src/model.ts +34 -0
- package/lib/cli/starters/cli-agent/src/workspace.ts +170 -0
- package/lib/cli/starters/cli-agent/test/assistant.test.ts +205 -0
- package/lib/cli/starters/cli-agent/tsconfig.json +20 -0
- package/lib/cli/starters/event-automation/README.md +4 -3
- package/lib/cli/starters/event-automation/dot-env.example +11 -0
- package/lib/cli/starters/event-automation/package.json +1 -2
- package/lib/cli/starters/event-automation/src/config.ts +25 -7
- package/lib/cli/starters/event-automation/src/ingress.ts +3 -5
- package/lib/cli/starters/event-automation/src/model.ts +11 -4
- package/lib/cli/starters/event-automation/src/send-sample.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/main.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/mcp-server.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/tickets.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker-tools.ts +1 -1
- package/lib/cli/starters/event-automation/src/triage.ts +15 -22
- package/lib/cli/starters/event-automation/src/workflows.ts +1 -1
- package/lib/cli/starters/event-automation/test/automation.test.ts +3 -3
- package/lib/cli/starters/research-team/README.md +2 -2
- package/lib/cli/starters/research-team/dot-env.example +11 -0
- package/lib/cli/starters/research-team/package.json +1 -2
- package/lib/cli/starters/research-team/src/config.ts +25 -7
- package/lib/cli/starters/research-team/src/desk.ts +1 -2
- package/lib/cli/starters/research-team/src/library/index.ts +1 -2
- package/lib/cli/starters/research-team/src/model.ts +11 -4
- package/lib/cli/starters/research-team/src/services.ts +1 -1
- package/lib/cli/starters/research-team/src/team.ts +1 -2
- package/lib/cli/starters/research-team/src/workflow.ts +45 -59
- package/lib/cli/starters/support-agent/dot-env.example +11 -0
- package/lib/cli/starters/support-agent/package.json +1 -2
- package/lib/cli/starters/support-agent/src/assistant.ts +5 -5
- package/lib/cli/starters/support-agent/src/config.ts +25 -7
- package/lib/cli/starters/support-agent/src/guardrails.ts +3 -1
- package/lib/cli/starters/support-agent/src/model.ts +11 -4
- package/lib/cli/starters/support-agent/src/returns.ts +1 -2
- package/lib/cli/starters/support-agent/test/support.test.ts +25 -1
- package/lib/cli/templates/basic-agent.ts +1 -2
- package/lib/cli/templates/capability-policy.ts +1 -2
- package/lib/cli/templates/code-mode-workflow.ts +1 -1
- package/lib/cli/templates/durable-approval.ts +1 -1
- package/lib/cli/templates/parallel-research.ts +1 -2
- package/lib/cli/templates/typed-tool-runner.ts +1 -2
- package/lib/client/dist/forms.d.ts.map +1 -1
- package/lib/client/dist/forms.js +3 -4
- package/lib/client/dist/forms.js.map +1 -1
- package/lib/client/dist/headless.d.ts +3 -1
- package/lib/client/dist/headless.d.ts.map +1 -1
- package/lib/client/dist/headless.js +10 -6
- package/lib/client/dist/headless.js.map +1 -1
- package/lib/client/dist/index.d.ts +95 -6
- package/lib/client/dist/index.d.ts.map +1 -1
- package/lib/client/dist/index.js +397 -124
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/dist/workflows.d.ts +1 -1
- package/lib/client/dist/workflows.d.ts.map +1 -1
- package/lib/client/dist/workflows.js +7 -6
- package/lib/client/dist/workflows.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/forms.ts +3 -4
- package/lib/client/src/headless.ts +13 -7
- package/lib/client/src/index.ts +344 -74
- package/lib/client/src/workflows.ts +8 -7
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/dist/index.d.ts +32 -1
- package/lib/code-mode/dist/index.d.ts.map +1 -1
- package/lib/code-mode/dist/index.js +289 -221
- package/lib/code-mode/dist/index.js.map +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode/src/index.ts +288 -184
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/dist/budget.d.ts.map +1 -1
- package/lib/core/dist/budget.js +17 -2
- package/lib/core/dist/budget.js.map +1 -1
- package/lib/core/dist/contracts.d.ts +57 -0
- package/lib/core/dist/contracts.d.ts.map +1 -1
- package/lib/core/dist/contracts.js +36 -0
- package/lib/core/dist/contracts.js.map +1 -1
- package/lib/core/dist/destination.d.ts +12 -0
- package/lib/core/dist/destination.d.ts.map +1 -0
- package/lib/core/dist/destination.js +37 -0
- package/lib/core/dist/destination.js.map +1 -0
- package/lib/core/dist/event-stream.d.ts +1 -1
- package/lib/core/dist/event-stream.d.ts.map +1 -1
- package/lib/core/dist/event-stream.js +7 -0
- package/lib/core/dist/event-stream.js.map +1 -1
- package/lib/core/dist/host.d.ts +3 -0
- package/lib/core/dist/host.d.ts.map +1 -1
- package/lib/core/dist/host.js +3 -0
- package/lib/core/dist/host.js.map +1 -1
- package/lib/core/dist/index.d.ts +2 -0
- package/lib/core/dist/index.d.ts.map +1 -1
- package/lib/core/dist/index.js +2 -0
- package/lib/core/dist/index.js.map +1 -1
- package/lib/core/dist/media.d.ts +98 -0
- package/lib/core/dist/media.d.ts.map +1 -0
- package/lib/core/dist/media.js +227 -0
- package/lib/core/dist/media.js.map +1 -0
- package/lib/core/dist/model-schema.d.ts +37 -0
- package/lib/core/dist/model-schema.d.ts.map +1 -0
- package/lib/core/dist/model-schema.js +154 -0
- package/lib/core/dist/model-schema.js.map +1 -0
- package/lib/core/package.json +1 -1
- package/lib/core/src/budget.ts +17 -2
- package/lib/core/src/contracts.ts +71 -3
- package/lib/core/src/destination.ts +33 -0
- package/lib/core/src/event-stream.ts +5 -1
- package/lib/core/src/host.ts +3 -0
- package/lib/core/src/index.ts +2 -0
- package/lib/core/src/media.ts +228 -0
- package/lib/core/src/model-schema.ts +129 -0
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/memory/dist/index.js +1 -1
- package/lib/memory/dist/index.js.map +1 -1
- package/lib/memory/dist/native.d.ts.map +1 -1
- package/lib/memory/dist/native.js +4 -3
- package/lib/memory/dist/native.js.map +1 -1
- package/lib/memory/package.json +1 -1
- package/lib/memory/src/index.ts +1 -1
- package/lib/memory/src/native.ts +4 -3
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/dist/index.d.ts +36 -3
- package/lib/provider-anthropic/dist/index.d.ts.map +1 -1
- package/lib/provider-anthropic/dist/index.js +128 -78
- package/lib/provider-anthropic/dist/index.js.map +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-anthropic/src/index.ts +152 -76
- package/lib/provider-openai/dist/index.d.ts +71 -4
- package/lib/provider-openai/dist/index.d.ts.map +1 -1
- package/lib/provider-openai/dist/index.js +259 -96
- package/lib/provider-openai/dist/index.js.map +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/provider-openai/src/index.ts +282 -84
- package/lib/runtime/dist/agent.d.ts +18 -1
- package/lib/runtime/dist/agent.d.ts.map +1 -1
- package/lib/runtime/dist/agent.js +59 -3
- package/lib/runtime/dist/agent.js.map +1 -1
- package/lib/runtime/dist/composition.d.ts.map +1 -1
- package/lib/runtime/dist/composition.js +2 -1
- package/lib/runtime/dist/composition.js.map +1 -1
- package/lib/runtime/dist/hooks.d.ts +15 -3
- package/lib/runtime/dist/hooks.d.ts.map +1 -1
- package/lib/runtime/dist/hooks.js.map +1 -1
- package/lib/runtime/dist/index.d.ts +1 -1
- package/lib/runtime/dist/index.d.ts.map +1 -1
- package/lib/runtime/dist/index.js.map +1 -1
- package/lib/runtime/dist/response.d.ts +7 -1
- package/lib/runtime/dist/response.d.ts.map +1 -1
- package/lib/runtime/dist/response.js +23 -2
- package/lib/runtime/dist/response.js.map +1 -1
- package/lib/runtime/dist/router.d.ts +10 -3
- package/lib/runtime/dist/router.d.ts.map +1 -1
- package/lib/runtime/dist/router.js +45 -8
- package/lib/runtime/dist/router.js.map +1 -1
- package/lib/runtime/dist/runtime.d.ts +9 -1
- package/lib/runtime/dist/runtime.d.ts.map +1 -1
- package/lib/runtime/dist/runtime.js +50 -22
- package/lib/runtime/dist/runtime.js.map +1 -1
- package/lib/runtime/package.json +1 -1
- package/lib/runtime/src/agent.ts +69 -3
- package/lib/runtime/src/composition.ts +2 -1
- package/lib/runtime/src/hooks.ts +10 -4
- package/lib/runtime/src/index.ts +1 -1
- package/lib/runtime/src/response.ts +20 -2
- package/lib/runtime/src/router.ts +43 -10
- package/lib/runtime/src/runtime.ts +58 -27
- package/lib/sdk/dist/index.d.ts +9 -1
- package/lib/sdk/dist/index.d.ts.map +1 -1
- package/lib/sdk/dist/index.js +9 -1
- package/lib/sdk/dist/index.js.map +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/sdk/src/index.ts +9 -1
- package/lib/server/dist/index.d.ts +201 -3
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +701 -149
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +611 -135
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/dist/hardening.d.ts +1 -1
- package/lib/server-node/dist/hardening.d.ts.map +1 -1
- package/lib/server-node/dist/hardening.js +4 -2
- package/lib/server-node/dist/hardening.js.map +1 -1
- package/lib/server-node/dist/index.d.ts +2 -1
- package/lib/server-node/dist/index.d.ts.map +1 -1
- package/lib/server-node/dist/index.js.map +1 -1
- package/lib/server-node/dist/probe.js +2 -2
- package/lib/server-node/dist/probe.js.map +1 -1
- package/lib/server-node/dist/production.d.ts +8 -1
- package/lib/server-node/dist/production.d.ts.map +1 -1
- package/lib/server-node/dist/production.js +15 -2
- package/lib/server-node/dist/production.js.map +1 -1
- package/lib/server-node/package.json +1 -1
- package/lib/server-node/src/hardening.ts +5 -3
- package/lib/server-node/src/index.ts +2 -1
- package/lib/server-node/src/probe.ts +2 -2
- package/lib/server-node/src/production.ts +23 -3
- package/lib/skills/dist/index.d.ts +81 -0
- package/lib/skills/dist/index.d.ts.map +1 -0
- package/lib/skills/dist/index.js +311 -0
- package/lib/skills/dist/index.js.map +1 -0
- package/lib/skills/package.json +5 -0
- package/lib/skills/src/index.ts +260 -0
- package/lib/storage/dist/index.d.ts +1 -1
- package/lib/storage/dist/index.d.ts.map +1 -1
- package/lib/storage/dist/index.js.map +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage/src/index.ts +1 -1
- package/lib/storage-contracts/dist/contracts.d.ts +12 -5
- package/lib/storage-contracts/dist/contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/contracts.js +24 -6
- package/lib/storage-contracts/dist/contracts.js.map +1 -1
- package/lib/storage-contracts/dist/index.d.ts +2 -0
- package/lib/storage-contracts/dist/index.d.ts.map +1 -1
- package/lib/storage-contracts/dist/index.js +2 -0
- package/lib/storage-contracts/dist/index.js.map +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js.map +1 -1
- package/lib/storage-contracts/dist/run-records.d.ts +100 -0
- package/lib/storage-contracts/dist/run-records.d.ts.map +1 -0
- package/lib/storage-contracts/dist/run-records.js +464 -0
- package/lib/storage-contracts/dist/run-records.js.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts +17 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.js +94 -0
- package/lib/storage-contracts/dist/schema-digest.js.map +1 -0
- package/lib/storage-contracts/dist/submission-journal.js +1 -1
- package/lib/storage-contracts/dist/submission-journal.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.d.ts +30 -2
- package/lib/storage-contracts/dist/workflow-format5.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.js +57 -5
- package/lib/storage-contracts/dist/workflow-format5.js.map +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-contracts/src/contracts.ts +29 -5
- package/lib/storage-contracts/src/index.ts +2 -0
- package/lib/storage-contracts/src/memory-contracts.ts +1 -1
- package/lib/storage-contracts/src/run-records.ts +365 -0
- package/lib/storage-contracts/src/schema-digest.ts +71 -0
- package/lib/storage-contracts/src/submission-journal.ts +1 -1
- package/lib/storage-contracts/src/workflow-format5.ts +70 -6
- package/lib/storage-postgres/dist/index.d.ts +1 -1
- package/lib/storage-postgres/dist/index.d.ts.map +1 -1
- package/lib/storage-postgres/dist/index.js.map +1 -1
- package/lib/storage-postgres/dist/postgres.d.ts +15 -0
- package/lib/storage-postgres/dist/postgres.d.ts.map +1 -1
- package/lib/storage-postgres/dist/postgres.js +18 -7
- package/lib/storage-postgres/dist/postgres.js.map +1 -1
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-postgres/src/index.ts +1 -1
- package/lib/storage-postgres/src/postgres.ts +34 -8
- package/lib/storage-sql/dist/aggregate-session.js +1 -1
- package/lib/storage-sql/dist/aggregate-session.js.map +1 -1
- package/lib/storage-sql/dist/scheduled-database.js +1 -1
- package/lib/storage-sql/dist/scheduled-database.js.map +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js.map +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sql/src/aggregate-session.ts +1 -1
- package/lib/storage-sql/src/scheduled-database.ts +1 -1
- package/lib/storage-sql/src/workflow-tree-validation.ts +1 -1
- package/lib/storage-sqlite/dist/sqlite-database.js +4 -4
- package/lib/storage-sqlite/dist/sqlite-database.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite-worker.js +2 -2
- package/lib/storage-sqlite/dist/sqlite-worker.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite.js +1 -1
- package/lib/storage-sqlite/dist/sqlite.js.map +1 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/storage-sqlite/src/sqlite-database.ts +4 -4
- package/lib/storage-sqlite/src/sqlite-worker.ts +2 -2
- package/lib/storage-sqlite/src/sqlite.ts +1 -1
- package/lib/terminal/dist/index.d.ts +92 -0
- package/lib/terminal/dist/index.d.ts.map +1 -0
- package/lib/terminal/dist/index.js +397 -0
- package/lib/terminal/dist/index.js.map +1 -0
- package/lib/terminal/package.json +5 -0
- package/lib/terminal/src/index.ts +273 -0
- package/lib/testing/dist/index.d.ts +44 -1
- package/lib/testing/dist/index.d.ts.map +1 -1
- package/lib/testing/dist/index.js +63 -10
- package/lib/testing/dist/index.js.map +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/testing/src/index.ts +83 -10
- package/lib/tools/dist/index.d.ts +32 -4
- package/lib/tools/dist/index.d.ts.map +1 -1
- package/lib/tools/dist/index.js +64 -11
- package/lib/tools/dist/index.js.map +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/tools/src/index.ts +74 -13
- package/lib/workflows/dist/abandoned.d.ts +15 -0
- package/lib/workflows/dist/abandoned.d.ts.map +1 -0
- package/lib/workflows/dist/abandoned.js +33 -0
- package/lib/workflows/dist/abandoned.js.map +1 -0
- package/lib/workflows/dist/agent-step.d.ts +83 -0
- package/lib/workflows/dist/agent-step.d.ts.map +1 -0
- package/lib/workflows/dist/agent-step.js +161 -0
- package/lib/workflows/dist/agent-step.js.map +1 -0
- package/lib/workflows/dist/children-runtime.js +8 -8
- package/lib/workflows/dist/children-runtime.js.map +1 -1
- package/lib/workflows/dist/composite-fleet.js +2 -2
- package/lib/workflows/dist/composite-fleet.js.map +1 -1
- package/lib/workflows/dist/composite-host.d.ts.map +1 -1
- package/lib/workflows/dist/composite-host.js +26 -2
- package/lib/workflows/dist/composite-host.js.map +1 -1
- package/lib/workflows/dist/hook-relay.js +2 -2
- package/lib/workflows/dist/hook-relay.js.map +1 -1
- package/lib/workflows/dist/index.d.ts +1 -1
- package/lib/workflows/dist/index.d.ts.map +1 -1
- package/lib/workflows/dist/index.js.map +1 -1
- package/lib/workflows/dist/leadership.js +3 -3
- package/lib/workflows/dist/leadership.js.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.d.ts +26 -4
- package/lib/workflows/dist/lifecycle-definition.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.js +31 -6
- package/lib/workflows/dist/lifecycle-definition.js.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.js +9 -11
- package/lib/workflows/dist/lifecycle-fleet.js.map +1 -1
- package/lib/workflows/dist/lifecycle-host.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-host.js +26 -2
- package/lib/workflows/dist/lifecycle-host.js.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.d.ts +22 -2
- package/lib/workflows/dist/lifecycle-human-transport.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.js +115 -33
- package/lib/workflows/dist/lifecycle-human-transport.js.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts +62 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.js +268 -64
- package/lib/workflows/dist/lifecycle-runtime.js.map +1 -1
- package/lib/workflows/dist/lifecycle.d.ts +6 -4
- package/lib/workflows/dist/lifecycle.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle.js +2 -0
- package/lib/workflows/dist/lifecycle.js.map +1 -1
- package/lib/workflows/dist/loop-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/loop-runtime.js +38 -26
- package/lib/workflows/dist/loop-runtime.js.map +1 -1
- package/lib/workflows/dist/migration.d.ts +1 -1
- package/lib/workflows/dist/migration.d.ts.map +1 -1
- package/lib/workflows/dist/migration.js +3 -3
- package/lib/workflows/dist/migration.js.map +1 -1
- package/lib/workflows/dist/operator-transports.d.ts +24 -2
- package/lib/workflows/dist/operator-transports.d.ts.map +1 -1
- package/lib/workflows/dist/operator-transports.js +49 -3
- package/lib/workflows/dist/operator-transports.js.map +1 -1
- package/lib/workflows/dist/runtime.d.ts.map +1 -1
- package/lib/workflows/dist/runtime.js +34 -22
- package/lib/workflows/dist/runtime.js.map +1 -1
- package/lib/workflows/dist/saga-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/saga-runtime.js +44 -30
- package/lib/workflows/dist/saga-runtime.js.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.d.ts.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.js +3 -3
- package/lib/workflows/dist/scheduled-helpers.js.map +1 -1
- package/lib/workflows/dist/storage-failure.d.ts +16 -0
- package/lib/workflows/dist/storage-failure.d.ts.map +1 -0
- package/lib/workflows/dist/storage-failure.js +38 -0
- package/lib/workflows/dist/storage-failure.js.map +1 -0
- package/lib/workflows/dist/sweep-position.d.ts +22 -0
- package/lib/workflows/dist/sweep-position.d.ts.map +1 -0
- package/lib/workflows/dist/sweep-position.js +45 -0
- package/lib/workflows/dist/sweep-position.js.map +1 -0
- package/lib/workflows/dist/traces.js +2 -2
- package/lib/workflows/dist/traces.js.map +1 -1
- package/lib/workflows/dist/worker.d.ts +31 -0
- package/lib/workflows/dist/worker.d.ts.map +1 -1
- package/lib/workflows/dist/worker.js +94 -0
- package/lib/workflows/dist/worker.js.map +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workflows/src/abandoned.ts +32 -0
- package/lib/workflows/src/agent-step.ts +199 -0
- package/lib/workflows/src/children-runtime.ts +8 -8
- package/lib/workflows/src/composite-fleet.ts +2 -2
- package/lib/workflows/src/composite-host.ts +21 -3
- package/lib/workflows/src/hook-relay.ts +2 -2
- package/lib/workflows/src/index.ts +2 -1
- package/lib/workflows/src/leadership.ts +3 -3
- package/lib/workflows/src/lifecycle-definition.ts +50 -9
- package/lib/workflows/src/lifecycle-fleet.ts +7 -8
- package/lib/workflows/src/lifecycle-host.ts +21 -5
- package/lib/workflows/src/lifecycle-human-transport.ts +110 -26
- package/lib/workflows/src/lifecycle-runtime.ts +270 -60
- package/lib/workflows/src/lifecycle.ts +7 -0
- package/lib/workflows/src/loop-runtime.ts +34 -25
- package/lib/workflows/src/migration.ts +2 -2
- package/lib/workflows/src/operator-transports.ts +48 -4
- package/lib/workflows/src/runtime.ts +28 -22
- package/lib/workflows/src/saga-runtime.ts +38 -28
- package/lib/workflows/src/scheduled-helpers.ts +3 -3
- package/lib/workflows/src/storage-failure.ts +37 -0
- package/lib/workflows/src/sweep-position.ts +52 -0
- package/lib/workflows/src/traces.ts +2 -2
- package/lib/workflows/src/worker.ts +79 -1
- package/lib/workstream/dist/humans.d.ts +7 -3
- package/lib/workstream/dist/humans.d.ts.map +1 -1
- package/lib/workstream/dist/humans.js +13 -2
- package/lib/workstream/dist/humans.js.map +1 -1
- package/lib/workstream/dist/index.js +2 -2
- package/lib/workstream/dist/index.js.map +1 -1
- package/lib/workstream/dist/timers.js +2 -2
- package/lib/workstream/dist/timers.js.map +1 -1
- package/lib/workstream/dist/webhooks.d.ts +6 -2
- package/lib/workstream/dist/webhooks.d.ts.map +1 -1
- package/lib/workstream/dist/webhooks.js +17 -7
- package/lib/workstream/dist/webhooks.js.map +1 -1
- package/lib/workstream/package.json +1 -1
- package/lib/workstream/src/humans.ts +15 -5
- package/lib/workstream/src/index.ts +2 -2
- package/lib/workstream/src/timers.ts +2 -2
- package/lib/workstream/src/webhooks.ts +21 -8
- package/llms-full.txt +9766 -0
- package/llms.txt +92 -0
- package/package.json +18 -6
|
@@ -2,6 +2,7 @@ import { freezeJson, jsonValue, MayuraError } from '../../core/dist/index.js';
|
|
|
2
2
|
import { createWorkflowCompositeFleetRuntime } from './composite-fleet.js';
|
|
3
3
|
import { assertWorkflowLoop } from './loop-definition.js';
|
|
4
4
|
import { assertWorkflowSaga } from './saga-definition.js';
|
|
5
|
+
import { createSweepPosition } from './sweep-position.js';
|
|
5
6
|
function delay(milliseconds, signal) {
|
|
6
7
|
return new Promise(resolve => {
|
|
7
8
|
if (signal.aborted) {
|
|
@@ -50,6 +51,9 @@ export function createWorkflowCompositeHost(options) {
|
|
|
50
51
|
const runtime = createWorkflowCompositeFleetRuntime(options);
|
|
51
52
|
let cursor = null;
|
|
52
53
|
let closed = false;
|
|
54
|
+
// The sweep continues where the last process left it, rather than starting over (see sweep-position.ts).
|
|
55
|
+
const position = createSweepPosition(options.store, { kind: 'composite', scope: options.scope,
|
|
56
|
+
catalog: [...sagas, ...loops].map(definition => definition.digest) });
|
|
53
57
|
let cycles = 0;
|
|
54
58
|
let failures = 0;
|
|
55
59
|
let lastError = null;
|
|
@@ -68,15 +72,35 @@ export function createWorkflowCompositeHost(options) {
|
|
|
68
72
|
let shardReads = 0;
|
|
69
73
|
const outcomes = [];
|
|
70
74
|
const held = hold ? await hold.isHeld() === true : false;
|
|
71
|
-
if (!held)
|
|
75
|
+
if (!held) {
|
|
76
|
+
const stored = await position.load();
|
|
77
|
+
let restored = false;
|
|
78
|
+
if (stored !== null && cursor === null) {
|
|
79
|
+
cursor = stored;
|
|
80
|
+
restored = true;
|
|
81
|
+
}
|
|
72
82
|
do {
|
|
73
|
-
const
|
|
83
|
+
const page = (from) => runtime.runPage({ sagas, loops }, { cursor: from, limit, maxShardReads: reads });
|
|
84
|
+
let report;
|
|
85
|
+
try {
|
|
86
|
+
report = await page(cursor);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
// A stored position this host cannot use restarts the sweep instead of failing every cycle.
|
|
90
|
+
if (!restored || !(error instanceof MayuraError) || error.code !== 'INVALID_INPUT')
|
|
91
|
+
throw error;
|
|
92
|
+
cursor = null;
|
|
93
|
+
report = await page(cursor);
|
|
94
|
+
}
|
|
95
|
+
restored = false;
|
|
74
96
|
pages += 1;
|
|
75
97
|
examined += report.page.examined;
|
|
76
98
|
shardReads += report.page.shardReads;
|
|
77
99
|
outcomes.push(...report.outcomes);
|
|
78
100
|
cursor = report.page.nextCursor;
|
|
79
101
|
} while (cursor && pages < pageMaximum);
|
|
102
|
+
await position.save(cursor);
|
|
103
|
+
}
|
|
80
104
|
const completedSweep = !held && cursor === null;
|
|
81
105
|
const result = freezeJson(jsonValue({ pages, examined, shardReads, outcomes, completedSweep, held }));
|
|
82
106
|
cycles += 1;
|
|
@@ -1 +1 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C,IAAI,MAAM;QAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IACrJ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;QAC5C,MAAM,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,IAAI,KAAK,SAAS,EAAE,MAAM,EAAE,mBAAmB,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,CAA2C;QAC3K,IAAI,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,GAAG,IAAI,MAAM;YAAE,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC9F,KAAK,EAAE,KAAK,EAAE,OAA8B,EAAE,EAAE;YAC9C,UAAU,EAAE,KAAK,EAAE,CAAC;YAAC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACjE,MAAM,IAAI,CAAC;YAAC,IAAI,MAAM;gBAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YAAC,UAAU,GAAG,SAAS,CAAC;YAAC,MAAM,GAAG,IAAI,CAAC;YAAC,OAAO,MAAM,CAAC;QACnH,CAAC,EAAE,CAAC,CAAC;AACT,CAAC","sourcesContent":["import { freezeJson, jsonValue, MayuraError, type ErrorCode } from '@mayura/core';\nimport type { WorkflowFleetHoldReader } from './fleet-control.js';\nimport type { WorkflowDrainOptions, WorkflowDrainReport } from './drain.js';\nimport { createWorkflowCompositeFleetRuntime, type WorkflowCompositeCursor, type WorkflowCompositeFleetOptions,\n type WorkflowCompositeFleetRuntime, type WorkflowCompositeOutcome } from './composite-fleet.js';\nimport { assertWorkflowLoop, type AnyWorkflowLoop } from './loop-definition.js';\nimport { assertWorkflowSaga, type AnyWorkflowSaga } from './saga-definition.js';\n\nexport interface WorkflowCompositeHostOptions extends WorkflowCompositeFleetOptions {\n readonly sagaDefinitions?: readonly AnyWorkflowSaga[]; readonly loopDefinitions?: readonly AnyWorkflowLoop[];\n readonly intervalMs?: number; readonly maxBackoffMs?: number; readonly maxPagesPerCycle?: number;\n readonly pageLimit?: number; readonly maxShardReads?: number;\n /** Durable fleet hold consulted before every cycle; while held the host drives no run. */\n readonly hold?: WorkflowFleetHoldReader;\n}\nexport interface WorkflowCompositeHostCycle { readonly pages: number; readonly examined: number; readonly shardReads: number;\n readonly outcomes: readonly WorkflowCompositeOutcome[]; readonly completedSweep: boolean; readonly held: boolean }\nexport interface WorkflowCompositeHostStatus { readonly running: boolean; readonly cycles: number;\n readonly consecutiveFailures: number; readonly lastError: ErrorCode | null; readonly lastCycle: WorkflowCompositeHostCycle | null }\nexport interface WorkflowCompositeHost { readonly runtime: WorkflowCompositeFleetRuntime; start(): void;\n runOnce(): Promise<WorkflowCompositeHostCycle>; status(): WorkflowCompositeHostStatus; stop(): Promise<void>; close(): Promise<void>;\n /** Start no further cycle, let admitted effects settle within the deadline, then close the owned runtime. */\n drain(options?: WorkflowDrainOptions): Promise<WorkflowDrainReport> }\n\nfunction delay(milliseconds: number, signal: AbortSignal): Promise<void> { return new Promise(resolve => {\n if (signal.aborted) { resolve(); return; } const timer = setTimeout(done, milliseconds);\n function done(): void { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); }\n signal.addEventListener('abort', done, { once: true }); } ); }\n\n/** Explicitly hosted, restart-safe continuation for indexed saga and loop parents. */\nexport function createWorkflowCompositeHost(options: WorkflowCompositeHostOptions): WorkflowCompositeHost {\n const sagas = Object.freeze([...(options.sagaDefinitions ?? [])]); const loops = Object.freeze([...(options.loopDefinitions ?? [])]);\n if (sagas.length + loops.length < 1 || sagas.length > 128 || loops.length > 128) throw new MayuraError('INVALID_CONFIG', 'A composite host requires a finite definition catalog.');\n const seen = new Set<string>(); for (const value of sagas) { assertWorkflowSaga(value); if (seen.has(value.digest)) throw new MayuraError('INVALID_CONFIG', 'Composite host definitions must be unique.'); seen.add(value.digest); }\n for (const value of loops) { assertWorkflowLoop(value); if (seen.has(value.digest)) throw new MayuraError('INVALID_CONFIG', 'Composite host definitions must be unique.'); seen.add(value.digest); }\n const interval = options.intervalMs ?? 1_000; const backoffMaximum = options.maxBackoffMs ?? 30_000;\n const pageMaximum = options.maxPagesPerCycle ?? 16; const limit = options.pageLimit ?? 32; const reads = options.maxShardReads ?? 32;\n for (const [name, value, maximum] of [['intervalMs', interval, 3_600_000], ['maxBackoffMs', backoffMaximum, 3_600_000],\n ['maxPagesPerCycle', pageMaximum, 256], ['pageLimit', limit, 128], ['maxShardReads', reads, 256]] as const) {\n if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new MayuraError('INVALID_CONFIG', `${name} is outside its finite host bound.`); }\n if (backoffMaximum < interval) throw new MayuraError('INVALID_CONFIG', 'maxBackoffMs must be at least intervalMs.');\n const hold = options.hold; if (hold !== undefined && typeof hold?.isHeld !== 'function') throw new MayuraError('INVALID_CONFIG', 'A fleet hold reader requires isHeld().');\n const runtime = createWorkflowCompositeFleetRuntime(options); let cursor: WorkflowCompositeCursor | null = null; let closed = false;\n let cycles = 0; let failures = 0; let lastError: ErrorCode | null = null; let lastCycle: WorkflowCompositeHostCycle | null = null;\n let controller: AbortController | undefined; let loop: Promise<void> | undefined; let active: Promise<WorkflowCompositeHostCycle> | undefined;\n const runOnce = (): Promise<WorkflowCompositeHostCycle> => { if (closed) return Promise.reject(new MayuraError('CANCELLED', 'Composite host is closed.')); if (active) return active;\n const operation = (async () => { let pages = 0; let examined = 0; let shardReads = 0; const outcomes: WorkflowCompositeOutcome[] = [];\n const held = hold ? await hold.isHeld() === true : false;\n if (!held) do { const report = await runtime.runPage({ sagas, loops }, { cursor, limit, maxShardReads: reads }); pages += 1;\n examined += report.page.examined; shardReads += report.page.shardReads; outcomes.push(...report.outcomes); cursor = report.page.nextCursor; }\n while (cursor && pages < pageMaximum); const completedSweep = !held && cursor === null;\n const result = freezeJson(jsonValue({ pages, examined, shardReads, outcomes, completedSweep, held })) as unknown as WorkflowCompositeHostCycle;\n cycles += 1; failures = 0; lastError = null; lastCycle = result; return result; })();\n active = operation; void operation.finally(() => { if (active === operation) active = undefined; }).catch(() => {}); return operation; };\n const start = (): void => { if (closed) throw new MayuraError('CANCELLED', 'Composite host is closed.'); if (loop) return;\n controller = new AbortController(); const signal = controller.signal; loop = (async () => { while (!signal.aborted) {\n try { await runOnce(); } catch (error) { if (signal.aborted) break; failures += 1; lastError = error instanceof MayuraError ? error.code : 'STORAGE_UNAVAILABLE'; }\n await delay(Math.min(backoffMaximum, interval * (2 ** Math.min(failures, 16))), signal); } })().finally(() => { loop = undefined; }); };\n const stop = async (): Promise<void> => { controller?.abort(); await loop; if (active) await Promise.allSettled([active]); controller = undefined; };\n return Object.freeze({ runtime, start, runOnce,\n status: () => freezeJson(jsonValue({ running: loop !== undefined, cycles, consecutiveFailures: failures, lastError, lastCycle })) as unknown as WorkflowCompositeHostStatus,\n stop, close: async () => { if (closed) return; await stop(); closed = true; runtime.close(); },\n drain: async (options?: WorkflowDrainOptions) => {\n controller?.abort(); const report = await runtime.drain(options);\n await loop; if (active) await Promise.allSettled([active]); controller = undefined; closed = true; return report;\n } });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"composite-host.js","sourceRoot":"","sources":["../src/composite-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAkB,MAAM,cAAc,CAAC;AAGlF,OAAO,EAAE,mCAAmC,EACyB,MAAM,sBAAsB,CAAC;AAClG,OAAO,EAAE,kBAAkB,EAAwB,MAAM,sBAAsB,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAwB,MAAM,sBAAsB,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,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E,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC9F,KAAK,EAAE,KAAK,EAAE,OAA8B,EAAE,EAAE;YAC9C,UAAU,EAAE,KAAK,EAAE,CAAC;YAAC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACjE,MAAM,IAAI,CAAC;YAAC,IAAI,MAAM;gBAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YAAC,UAAU,GAAG,SAAS,CAAC;YAAC,MAAM,GAAG,IAAI,CAAC;YAAC,OAAO,MAAM,CAAC;QACnH,CAAC,EAAE,CAAC,CAAC;AACT,CAAC","sourcesContent":["import { freezeJson, jsonValue, MayuraError, type ErrorCode } from '@mayura/core';\nimport type { WorkflowFleetHoldReader } from './fleet-control.js';\nimport type { WorkflowDrainOptions, WorkflowDrainReport } from './drain.js';\nimport { createWorkflowCompositeFleetRuntime, type WorkflowCompositeCursor, type WorkflowCompositeFleetOptions,\n type WorkflowCompositeFleetRuntime, type WorkflowCompositeOutcome } from './composite-fleet.js';\nimport { assertWorkflowLoop, type AnyWorkflowLoop } from './loop-definition.js';\nimport { assertWorkflowSaga, type AnyWorkflowSaga } from './saga-definition.js';\nimport { createSweepPosition } from './sweep-position.js';\n\nexport interface WorkflowCompositeHostOptions extends WorkflowCompositeFleetOptions {\n readonly sagaDefinitions?: readonly AnyWorkflowSaga[]; readonly loopDefinitions?: readonly AnyWorkflowLoop[];\n readonly intervalMs?: number; readonly maxBackoffMs?: number; readonly maxPagesPerCycle?: number;\n readonly pageLimit?: number; readonly maxShardReads?: number;\n /** Durable fleet hold consulted before every cycle; while held the host drives no run. */\n readonly hold?: WorkflowFleetHoldReader;\n}\nexport interface WorkflowCompositeHostCycle { readonly pages: number; readonly examined: number; readonly shardReads: number;\n readonly outcomes: readonly WorkflowCompositeOutcome[]; readonly completedSweep: boolean; readonly held: boolean }\nexport interface WorkflowCompositeHostStatus { readonly running: boolean; readonly cycles: number;\n readonly consecutiveFailures: number; readonly lastError: ErrorCode | null; readonly lastCycle: WorkflowCompositeHostCycle | null }\nexport interface WorkflowCompositeHost { readonly runtime: WorkflowCompositeFleetRuntime; start(): void;\n runOnce(): Promise<WorkflowCompositeHostCycle>; status(): WorkflowCompositeHostStatus; stop(): Promise<void>; close(): Promise<void>;\n /** Start no further cycle, let admitted effects settle within the deadline, then close the owned runtime. */\n drain(options?: WorkflowDrainOptions): Promise<WorkflowDrainReport> }\n\nfunction delay(milliseconds: number, signal: AbortSignal): Promise<void> { return new Promise(resolve => {\n if (signal.aborted) { resolve(); return; } const timer = setTimeout(done, milliseconds);\n function done(): void { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); }\n signal.addEventListener('abort', done, { once: true }); } ); }\n\n/** Explicitly hosted, restart-safe continuation for indexed saga and loop parents. */\nexport function createWorkflowCompositeHost(options: WorkflowCompositeHostOptions): WorkflowCompositeHost {\n const sagas = Object.freeze([...(options.sagaDefinitions ?? [])]); const loops = Object.freeze([...(options.loopDefinitions ?? [])]);\n if (sagas.length + loops.length < 1 || sagas.length > 128 || loops.length > 128) throw new MayuraError('INVALID_CONFIG', 'A composite host requires a finite definition catalog.');\n const seen = new Set<string>(); for (const value of sagas) { assertWorkflowSaga(value); if (seen.has(value.digest)) throw new MayuraError('INVALID_CONFIG', 'Composite host definitions must be unique.'); seen.add(value.digest); }\n for (const value of loops) { assertWorkflowLoop(value); if (seen.has(value.digest)) throw new MayuraError('INVALID_CONFIG', 'Composite host definitions must be unique.'); seen.add(value.digest); }\n const interval = options.intervalMs ?? 1_000; const backoffMaximum = options.maxBackoffMs ?? 30_000;\n const pageMaximum = options.maxPagesPerCycle ?? 16; const limit = options.pageLimit ?? 32; const reads = options.maxShardReads ?? 32;\n for (const [name, value, maximum] of [['intervalMs', interval, 3_600_000], ['maxBackoffMs', backoffMaximum, 3_600_000],\n ['maxPagesPerCycle', pageMaximum, 256], ['pageLimit', limit, 128], ['maxShardReads', reads, 256]] as const) {\n if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new MayuraError('INVALID_CONFIG', `${name} is outside its finite host bound.`); }\n if (backoffMaximum < interval) throw new MayuraError('INVALID_CONFIG', 'maxBackoffMs must be at least intervalMs.');\n const hold = options.hold; if (hold !== undefined && typeof hold?.isHeld !== 'function') throw new MayuraError('INVALID_CONFIG', 'A fleet hold reader requires isHeld().');\n const runtime = createWorkflowCompositeFleetRuntime(options); let cursor: WorkflowCompositeCursor | null = null; let closed = false;\n // The sweep continues where the last process left it, rather than starting over (see sweep-position.ts).\n const position = createSweepPosition<WorkflowCompositeCursor>(options.store, { kind: 'composite', scope: options.scope,\n catalog: [...sagas, ...loops].map(definition => definition.digest) });\n let cycles = 0; let failures = 0; let lastError: ErrorCode | null = null; let lastCycle: WorkflowCompositeHostCycle | null = null;\n let controller: AbortController | undefined; let loop: Promise<void> | undefined; let active: Promise<WorkflowCompositeHostCycle> | undefined;\n const runOnce = (): Promise<WorkflowCompositeHostCycle> => { if (closed) return Promise.reject(new MayuraError('CANCELLED', 'Composite host is closed.')); if (active) return active;\n const operation = (async () => { let pages = 0; let examined = 0; let shardReads = 0; const outcomes: WorkflowCompositeOutcome[] = [];\n const held = hold ? await hold.isHeld() === true : false;\n if (!held) {\n const stored = await position.load(); let restored = false;\n if (stored !== null && cursor === null) { cursor = stored; restored = true; }\n do {\n const page = (from: WorkflowCompositeCursor | null) => runtime.runPage({ sagas, loops }, { cursor: from, limit, maxShardReads: reads });\n let report: Awaited<ReturnType<typeof page>>;\n try { report = await page(cursor); } catch (error) {\n // A stored position this host cannot use restarts the sweep instead of failing every cycle.\n if (!restored || !(error instanceof MayuraError) || error.code !== 'INVALID_INPUT') throw error;\n cursor = null; report = await page(cursor);\n }\n restored = false; pages += 1;\n examined += report.page.examined; shardReads += report.page.shardReads; outcomes.push(...report.outcomes); cursor = report.page.nextCursor;\n } while (cursor && pages < pageMaximum);\n await position.save(cursor);\n }\n const completedSweep = !held && cursor === null;\n const result = freezeJson(jsonValue({ pages, examined, shardReads, outcomes, completedSweep, held })) as unknown as WorkflowCompositeHostCycle;\n cycles += 1; failures = 0; lastError = null; lastCycle = result; return result; })();\n active = operation; void operation.finally(() => { if (active === operation) active = undefined; }).catch(() => {}); return operation; };\n const start = (): void => { if (closed) throw new MayuraError('CANCELLED', 'Composite host is closed.'); if (loop) return;\n controller = new AbortController(); const signal = controller.signal; loop = (async () => { while (!signal.aborted) {\n try { await runOnce(); } catch (error) { if (signal.aborted) break; failures += 1; lastError = error instanceof MayuraError ? error.code : 'STORAGE_UNAVAILABLE'; }\n await delay(Math.min(backoffMaximum, interval * (2 ** Math.min(failures, 16))), signal); } })().finally(() => { loop = undefined; }); };\n const stop = async (): Promise<void> => { controller?.abort(); await loop; if (active) await Promise.allSettled([active]); controller = undefined; };\n return Object.freeze({ runtime, start, runOnce,\n status: () => freezeJson(jsonValue({ running: loop !== undefined, cycles, consecutiveFailures: failures, lastError, lastCycle })) as unknown as WorkflowCompositeHostStatus,\n stop, close: async () => { if (closed) return; await stop(); closed = true; runtime.close(); },\n drain: async (options?: WorkflowDrainOptions) => {\n controller?.abort(); const report = await runtime.drain(options);\n await loop; if (active) await Promise.allSettled([active]); controller = undefined; closed = true; return report;\n } });\n}\n"]}
|
|
@@ -55,7 +55,7 @@ export function createWorkflowHookRelay(options) {
|
|
|
55
55
|
return await operation();
|
|
56
56
|
}
|
|
57
57
|
catch (error) {
|
|
58
|
-
if (error instanceof MayuraError || (error instanceof StorageError && error.
|
|
58
|
+
if (error instanceof MayuraError || (error instanceof StorageError && error.storageCode === 'CONFLICT'))
|
|
59
59
|
throw error;
|
|
60
60
|
throw new MayuraError('STORAGE_UNAVAILABLE', 'Workflow hook relay storage is unavailable.');
|
|
61
61
|
}
|
|
@@ -84,7 +84,7 @@ export function createWorkflowHookRelay(options) {
|
|
|
84
84
|
return { record, sequence };
|
|
85
85
|
}
|
|
86
86
|
catch (error) {
|
|
87
|
-
if (!(error instanceof StorageError && error.
|
|
87
|
+
if (!(error instanceof StorageError && error.storageCode === 'CONFLICT'))
|
|
88
88
|
throw error;
|
|
89
89
|
const latest = await read(runId);
|
|
90
90
|
return latest.sequence >= sequence ? latest : advance(runId, latest, sequence);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-relay.js","sourceRoot":"","sources":["../src/hook-relay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAuD,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,YAAY,EAA4D,MAAM,2BAA2B,CAAC;AACnH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAgDzC,MAAM,MAAM,GAAiC,CAAC,QAAQ,EAAE,UAAU,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AACpL,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAC1D,MAAM,WAAW,GAAgD,MAAM,CAAC,MAAM,CAAC;IAC7E,oBAAoB,EAAE,qBAAqB,EAAE,8BAA8B,EAAE,qBAAqB;IAClG,mBAAmB,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,oBAAoB;IAC9F,kBAAkB,EAAE,oBAAoB,EAAE,4BAA4B,EAAE,oBAAoB;IAC5F,iBAAiB,EAAE,QAAQ,EAAE,aAAa,EAAE,QAAQ,EAAE,uBAAuB,EAAE,QAAQ,EAAE,kBAAkB,EAAE,QAAQ;IACrH,YAAY,EAAE,QAAQ,EAAE,sBAAsB,EAAE,QAAQ,EAAE,2BAA2B,EAAE,QAAQ,EAAE,2BAA2B,EAAE,QAAQ;IACtI,sBAAsB,EAAE,QAAQ,EAAE,2BAA2B,EA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Q,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;wBACtI,CAAC;wBACD,SAAS,EAAE,CAAC;oBACd,CAAC;oBACD,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC;oBAC1B,6GAA6G;oBAC7G,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC;wBAAE,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC7E,CAAC;gBACD,IAAI,OAAO,GAAG,OAAO,CAAC,QAAQ;oBAAE,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;gBACjF,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK;oBAAE,MAAM;YACjC,CAAC;YACD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;QAClE,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type LifecycleObserver, type Scope } from '@mayura/core';\nimport { evaluateLifecycleObserver, snapshotHookOptions } from '@mayura/core/host';\nimport { StorageError, type AggregateStore, type StoredEvent, type StoredRecord } from '@mayura/storage-contracts';\nimport { digest } from './definition.js';\n\n/** Durable lifecycle points delivered from a workflow run's stored event log. */\nexport type WorkflowHookStage = 'onWait' | 'onResume' | 'onApprovalRequested' | 'onApprovalResolved'\n | 'afterExecution' | 'onError' | 'onCancel' | 'onBlocked' | 'onFinally';\n\n/** Metadata-only view of one stored event. `eventId` is the deduplication identity for at-least-once delivery. */\nexport interface WorkflowHookEvent {\n readonly stage: WorkflowHookStage;\n readonly runId: string;\n readonly sequence: number;\n /** `<relayId>:<runId>:<sequence>:<stage>`; stable across redelivery. */\n readonly eventId: string;\n /** The stored event type, for example `approval.requested` or `lifecycle.timer.fired`. */\n readonly type: string;\n readonly nodeId?: string;\n /** Terminal status, present for terminal stages. */\n readonly status?: string;\n}\nexport type WorkflowHooks = { readonly [S in WorkflowHookStage]?: LifecycleObserver<WorkflowHookEvent, S> } & { readonly timeoutMs?: number };\n\n/** Any workflow runtime: every format exposes its ordered durable log as `events(id, after)`. */\nexport interface WorkflowEventSource { events(id: string, after?: number): Promise<readonly StoredEvent[]> }\n\nexport interface WorkflowHookRelayOptions {\n readonly source: WorkflowEventSource;\n /** Holds one delivery cursor per (relay, run). May be the same store the workflows use. */\n readonly store: AggregateStore;\n readonly scope: Scope;\n /** Separates independent consumers of the same runs, for example `audit` and `notifications`. */\n readonly relayId: string;\n readonly hooks: WorkflowHooks;\n}\nexport interface WorkflowHookDelivery {\n /** Callbacks that completed during this call. */\n readonly delivered: number;\n /** Last stored event whose callbacks all completed; delivery resumes after it. */\n readonly sequence: number;\n /** Present when a callback failed; the next `deliver` retries this event. */\n readonly failure?: { readonly sequence: number; readonly stage: WorkflowHookStage; readonly code: string };\n}\nexport interface WorkflowHookRelay {\n /** Deliver callbacks for stored events after the durable cursor, in order, for at most `limit` events (default 1000). */\n deliver(runId: string, options?: { readonly signal?: AbortSignal; readonly limit?: number }): Promise<WorkflowHookDelivery>;\n /** The durable cursor for a run (0 before any delivery). */\n cursor(runId: string): Promise<number>;\n}\n\nconst stages: readonly WorkflowHookStage[] = ['onWait', 'onResume', 'onApprovalRequested', 'onApprovalResolved', 'afterExecution', 'onError', 'onCancel', 'onBlocked', 'onFinally'];\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;\nconst eventStages: Readonly<Record<string, WorkflowHookStage>> = Object.freeze({\n 'approval.requested': 'onApprovalRequested', 'lifecycle.approval.requested': 'onApprovalRequested',\n 'approval.resolved': 'onApprovalResolved', 'lifecycle.approval.resolved': 'onApprovalResolved',\n 'approval.expired': 'onApprovalResolved', 'lifecycle.approval.expired': 'onApprovalResolved',\n 'wait.registered': 'onWait', 'run.waiting': 'onWait', 'lifecycle.run.waiting': 'onWait', 'workflow.waiting': 'onWait',\n 'run.paused': 'onWait', 'lifecycle.run.paused': 'onWait', 'lifecycle.human.requested': 'onWait', 'lifecycle.timer.scheduled': 'onWait',\n 'saga.forward.waiting': 'onWait', 'saga.compensation.waiting': 'onWait', 'loop.child.waiting': 'onWait',\n 'wait.resolved': 'onResume', 'run.resumed': 'onResume', 'lifecycle.run.resumed': 'onResume',\n 'lifecycle.human.responded': 'onResume', 'lifecycle.timer.fired': 'onResume',\n});\n/** Terminal events of every format; the value is the status used when the event data carries none. */\nconst terminalEvents: Readonly<Record<string, string>> = Object.freeze({\n 'run.completed': 'unknown', 'lifecycle.run.completed': 'unknown', 'workflow.terminated': 'unknown',\n 'run.cancelled': 'cancelled', 'lifecycle.run.cancelled': 'cancelled', 'saga.run.cancelled': 'cancelled', 'loop.run.cancelled': 'cancelled',\n 'saga.run.succeeded': 'succeeded', 'loop.run.succeeded': 'succeeded',\n 'saga.run.failed': 'failed', 'saga.run.compensated': 'compensated',\n 'loop.output.rejected': 'failed', 'loop.condition.rejected': 'failed', 'loop.input.rejected': 'failed', 'loop.child.rejected': 'failed',\n 'loop.child.failed': 'failed', 'loop.limit.exceeded': 'limit_exceeded',\n});\n\n/** The callbacks one stored event produces, in order. Unrelated events produce none. */\nexport function workflowHookStages(type: string, data: JsonObject): readonly { readonly stage: WorkflowHookStage; readonly status?: string }[] {\n const stage = eventStages[type];\n if (stage) return [{ stage }];\n const fallback = terminalEvents[type];\n if (fallback === undefined) return [];\n const status = typeof data['status'] === 'string' && identifier.test(data['status']) ? data['status'] : fallback;\n const terminal: WorkflowHookStage = status === 'succeeded' ? 'afterExecution' : status === 'cancelled' ? 'onCancel' : status === 'blocked' ? 'onBlocked' : 'onError';\n return [{ stage: terminal, status }, { stage: 'onFinally', status }];\n}\n\n/**\n * Durable, recoverable delivery of workflow lifecycle callbacks. Delivery is at-least-once: the cursor advances\n * only after an event's callbacks complete, so a crash or failure redelivers from that event with the same `eventId`.\n */\nexport function createWorkflowHookRelay(options: WorkflowHookRelayOptions): WorkflowHookRelay {\n const { store, source } = options;\n if (!store || typeof store.read !== 'function' || typeof store.create !== 'function' || typeof store.update !== 'function'\n || !source || typeof source.events !== 'function' || typeof options.relayId !== 'string' || !identifier.test(options.relayId)\n || typeof options.scope?.principalId !== 'string' || typeof options.scope?.projectId !== 'string') {\n throw new MayuraError('INVALID_CONFIG', 'A workflow hook relay requires a store, an event source, a scope and a bounded relay identity.');\n }\n const { handlers, timeoutMs } = snapshotHookOptions(options.hooks, stages, 'Workflow hooks require callable handlers for known stages and a bounded timeout.');\n const relayId = options.relayId;\n const scope = digest('mayura:scope:v1', { principalId: options.scope.principalId, projectId: options.scope.projectId });\n const cursorId = (runId: string): string => digest('mayura:workflow-hook-relay:v1', { relayId, runId });\n const guarded = async <T>(operation: () => Promise<T>): Promise<T> => {\n try { return await operation(); }\n catch (error) { if (error instanceof MayuraError || (error instanceof StorageError && error.code === 'CONFLICT')) throw error;\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Workflow hook relay storage is unavailable.'); }\n };\n const read = async (runId: string): Promise<{ record?: StoredRecord; sequence: number }> => {\n const id = cursorId(runId); const record = await guarded(() => store.read(scope, id));\n if (!record) return { sequence: 0 };\n const state = record.state;\n if (record.scope !== scope || record.id !== id || state['format'] !== 1 || state['relayId'] !== relayId || state['runId'] !== runId\n || !Number.isSafeInteger(state['sequence']) || (state['sequence'] as number) < 0) {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Stored hook relay cursor failed integrity validation.');\n }\n return { record, sequence: state['sequence'] as number };\n };\n /** Compare-and-set advance; a concurrent relay that got further wins and this one resumes from its cursor. */\n const advance = async (runId: string, current: { record?: StoredRecord; sequence: number }, sequence: number): Promise<{ record?: StoredRecord; sequence: number }> => {\n const state = { format: 1, relayId, runId, sequence }; const event = { type: 'hook-relay.advanced', data: { sequence } };\n try {\n const record = current.record\n ? await guarded(() => store.update({ scope, id: current.record!.id, expectedVersion: current.record!.version, state, events: [event] }))\n : (await guarded(() => store.create({ scope, id: cursorId(runId), idempotencyKey: cursorId(runId),\n definitionHash: digest('mayura:workflow-hook-relay-format:v1', {}), state, events: [event] }))).record;\n return { record, sequence };\n } catch (error) {\n if (!(error instanceof StorageError && error.code === 'CONFLICT')) throw error;\n const latest = await read(runId);\n return latest.sequence >= sequence ? latest : advance(runId, latest, sequence);\n }\n };\n const validRun = (runId: unknown): string => {\n if (typeof runId !== 'string' || !identifier.test(runId)) throw new MayuraError('INVALID_INPUT', 'A bounded workflow run identity is required.');\n return runId;\n };\n return Object.freeze<WorkflowHookRelay>({\n async cursor(runId) { return (await read(validRun(runId))).sequence; },\n async deliver(runId, deliveryOptions = {}) {\n validRun(runId);\n const limit = deliveryOptions.limit ?? 1_000; const signal = deliveryOptions.signal;\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10_000) throw new MayuraError('INVALID_INPUT', 'Delivery limit must be 1–10000 events.');\n let current = await read(runId); let scanned = 0; let delivered = 0;\n while (scanned < limit) {\n if (signal?.aborted) throw new MayuraError('CANCELLED', 'Workflow hook delivery was cancelled.');\n const page = await guarded(() => source.events(runId, current.sequence));\n if (!Array.isArray(page)) throw new MayuraError('STORAGE_UNAVAILABLE', 'The workflow event source returned an invalid page.');\n let expected = current.sequence; let unsaved = current.sequence;\n for (const stored of page) {\n if (scanned >= limit) break;\n if (!stored || stored.sequence !== expected + 1 || typeof stored.type !== 'string' || !stored.data || typeof stored.data !== 'object') {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'The workflow event source returned events out of order.');\n }\n expected = stored.sequence; scanned++;\n const callbacks = workflowHookStages(stored.type, stored.data).filter(entry => handlers[entry.stage] !== undefined);\n for (const { stage, status } of callbacks) {\n const nodeId = stored.data['nodeId'];\n const event: WorkflowHookEvent = { stage, runId, sequence: stored.sequence, eventId: `${relayId}:${runId}:${stored.sequence}:${stage}`, type: stored.type,\n ...(typeof nodeId === 'string' && identifier.test(nodeId) ? { nodeId } : {}), ...(status === undefined ? {} : { status }) };\n try {\n await evaluateLifecycleObserver({ stage, handler: handlers[stage] as LifecycleObserver<WorkflowHookEvent>, event, timeoutMs, ...(signal ? { signal } : {}) });\n } catch (error) {\n if (unsaved > current.sequence) current = await advance(runId, current, unsaved);\n if (error instanceof MayuraError && error.code === 'CANCELLED') throw error;\n const code = error instanceof MayuraError ? error.code : 'GUARD_UNAVAILABLE';\n return Object.freeze({ delivered, sequence: current.sequence, failure: Object.freeze({ sequence: stored.sequence, stage, code }) });\n }\n delivered++;\n }\n unsaved = stored.sequence;\n // Persist after every callback-bearing event so a crash never repeats completed callbacks of earlier events.\n if (callbacks.length > 0) current = await advance(runId, current, unsaved);\n }\n if (unsaved > current.sequence) current = await advance(runId, current, unsaved);\n if (page.length < 1_000) break;\n }\n return Object.freeze({ delivered, sequence: current.sequence });\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hook-relay.js","sourceRoot":"","sources":["../src/hook-relay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAuD,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,YAAY,EAA4D,MAAM,2BAA2B,CAAC;AACnH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAgDzC,MAAM,MAAM,GAAiC,CAAC,QAAQ,EAAE,UAAU,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AACpL,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAC1D,MAAM,WAAW,GAAgD,MAAM,CAAC,MAAM,CAAC;IAC7E,oBAAoB,EAAE,qBAAqB,EAAE,8BAA8B,EAAE,qBAAqB;IAClG,mBAAmB,EAAE,oB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,QAAQ;gCAAE,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;4BACjF,IAAI,KAAK,YAAY,WAAW,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW;gCAAE,MAAM,KAAK,CAAC;4BAC5E,MAAM,IAAI,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,mBAAmB,CAAC;4BAC7E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;wBACtI,CAAC;wBACD,SAAS,EAAE,CAAC;oBACd,CAAC;oBACD,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC;oBAC1B,6GAA6G;oBAC7G,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC;wBAAE,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC7E,CAAC;gBACD,IAAI,OAAO,GAAG,OAAO,CAAC,QAAQ;oBAAE,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;gBACjF,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK;oBAAE,MAAM;YACjC,CAAC;YACD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;QAClE,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type LifecycleObserver, type Scope } from '@mayura/core';\nimport { evaluateLifecycleObserver, snapshotHookOptions } from '@mayura/core/host';\nimport { StorageError, type AggregateStore, type StoredEvent, type StoredRecord } from '@mayura/storage-contracts';\nimport { digest } from './definition.js';\n\n/** Durable lifecycle points delivered from a workflow run's stored event log. */\nexport type WorkflowHookStage = 'onWait' | 'onResume' | 'onApprovalRequested' | 'onApprovalResolved'\n | 'afterExecution' | 'onError' | 'onCancel' | 'onBlocked' | 'onFinally';\n\n/** Metadata-only view of one stored event. `eventId` is the deduplication identity for at-least-once delivery. */\nexport interface WorkflowHookEvent {\n readonly stage: WorkflowHookStage;\n readonly runId: string;\n readonly sequence: number;\n /** `<relayId>:<runId>:<sequence>:<stage>`; stable across redelivery. */\n readonly eventId: string;\n /** The stored event type, for example `approval.requested` or `lifecycle.timer.fired`. */\n readonly type: string;\n readonly nodeId?: string;\n /** Terminal status, present for terminal stages. */\n readonly status?: string;\n}\nexport type WorkflowHooks = { readonly [S in WorkflowHookStage]?: LifecycleObserver<WorkflowHookEvent, S> } & { readonly timeoutMs?: number };\n\n/** Any workflow runtime: every format exposes its ordered durable log as `events(id, after)`. */\nexport interface WorkflowEventSource { events(id: string, after?: number): Promise<readonly StoredEvent[]> }\n\nexport interface WorkflowHookRelayOptions {\n readonly source: WorkflowEventSource;\n /** Holds one delivery cursor per (relay, run). May be the same store the workflows use. */\n readonly store: AggregateStore;\n readonly scope: Scope;\n /** Separates independent consumers of the same runs, for example `audit` and `notifications`. */\n readonly relayId: string;\n readonly hooks: WorkflowHooks;\n}\nexport interface WorkflowHookDelivery {\n /** Callbacks that completed during this call. */\n readonly delivered: number;\n /** Last stored event whose callbacks all completed; delivery resumes after it. */\n readonly sequence: number;\n /** Present when a callback failed; the next `deliver` retries this event. */\n readonly failure?: { readonly sequence: number; readonly stage: WorkflowHookStage; readonly code: string };\n}\nexport interface WorkflowHookRelay {\n /** Deliver callbacks for stored events after the durable cursor, in order, for at most `limit` events (default 1000). */\n deliver(runId: string, options?: { readonly signal?: AbortSignal; readonly limit?: number }): Promise<WorkflowHookDelivery>;\n /** The durable cursor for a run (0 before any delivery). */\n cursor(runId: string): Promise<number>;\n}\n\nconst stages: readonly WorkflowHookStage[] = ['onWait', 'onResume', 'onApprovalRequested', 'onApprovalResolved', 'afterExecution', 'onError', 'onCancel', 'onBlocked', 'onFinally'];\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;\nconst eventStages: Readonly<Record<string, WorkflowHookStage>> = Object.freeze({\n 'approval.requested': 'onApprovalRequested', 'lifecycle.approval.requested': 'onApprovalRequested',\n 'approval.resolved': 'onApprovalResolved', 'lifecycle.approval.resolved': 'onApprovalResolved',\n 'approval.expired': 'onApprovalResolved', 'lifecycle.approval.expired': 'onApprovalResolved',\n 'wait.registered': 'onWait', 'run.waiting': 'onWait', 'lifecycle.run.waiting': 'onWait', 'workflow.waiting': 'onWait',\n 'run.paused': 'onWait', 'lifecycle.run.paused': 'onWait', 'lifecycle.human.requested': 'onWait', 'lifecycle.timer.scheduled': 'onWait',\n 'saga.forward.waiting': 'onWait', 'saga.compensation.waiting': 'onWait', 'loop.child.waiting': 'onWait',\n 'wait.resolved': 'onResume', 'run.resumed': 'onResume', 'lifecycle.run.resumed': 'onResume',\n 'lifecycle.human.responded': 'onResume', 'lifecycle.timer.fired': 'onResume',\n});\n/** Terminal events of every format; the value is the status used when the event data carries none. */\nconst terminalEvents: Readonly<Record<string, string>> = Object.freeze({\n 'run.completed': 'unknown', 'lifecycle.run.completed': 'unknown', 'workflow.terminated': 'unknown',\n 'run.cancelled': 'cancelled', 'lifecycle.run.cancelled': 'cancelled', 'saga.run.cancelled': 'cancelled', 'loop.run.cancelled': 'cancelled',\n 'saga.run.succeeded': 'succeeded', 'loop.run.succeeded': 'succeeded',\n 'saga.run.failed': 'failed', 'saga.run.compensated': 'compensated',\n 'loop.output.rejected': 'failed', 'loop.condition.rejected': 'failed', 'loop.input.rejected': 'failed', 'loop.child.rejected': 'failed',\n 'loop.child.failed': 'failed', 'loop.limit.exceeded': 'limit_exceeded',\n});\n\n/** The callbacks one stored event produces, in order. Unrelated events produce none. */\nexport function workflowHookStages(type: string, data: JsonObject): readonly { readonly stage: WorkflowHookStage; readonly status?: string }[] {\n const stage = eventStages[type];\n if (stage) return [{ stage }];\n const fallback = terminalEvents[type];\n if (fallback === undefined) return [];\n const status = typeof data['status'] === 'string' && identifier.test(data['status']) ? data['status'] : fallback;\n const terminal: WorkflowHookStage = status === 'succeeded' ? 'afterExecution' : status === 'cancelled' ? 'onCancel' : status === 'blocked' ? 'onBlocked' : 'onError';\n return [{ stage: terminal, status }, { stage: 'onFinally', status }];\n}\n\n/**\n * Durable, recoverable delivery of workflow lifecycle callbacks. Delivery is at-least-once: the cursor advances\n * only after an event's callbacks complete, so a crash or failure redelivers from that event with the same `eventId`.\n */\nexport function createWorkflowHookRelay(options: WorkflowHookRelayOptions): WorkflowHookRelay {\n const { store, source } = options;\n if (!store || typeof store.read !== 'function' || typeof store.create !== 'function' || typeof store.update !== 'function'\n || !source || typeof source.events !== 'function' || typeof options.relayId !== 'string' || !identifier.test(options.relayId)\n || typeof options.scope?.principalId !== 'string' || typeof options.scope?.projectId !== 'string') {\n throw new MayuraError('INVALID_CONFIG', 'A workflow hook relay requires a store, an event source, a scope and a bounded relay identity.');\n }\n const { handlers, timeoutMs } = snapshotHookOptions(options.hooks, stages, 'Workflow hooks require callable handlers for known stages and a bounded timeout.');\n const relayId = options.relayId;\n const scope = digest('mayura:scope:v1', { principalId: options.scope.principalId, projectId: options.scope.projectId });\n const cursorId = (runId: string): string => digest('mayura:workflow-hook-relay:v1', { relayId, runId });\n const guarded = async <T>(operation: () => Promise<T>): Promise<T> => {\n try { return await operation(); }\n catch (error) { if (error instanceof MayuraError || (error instanceof StorageError && error.storageCode === 'CONFLICT')) throw error;\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Workflow hook relay storage is unavailable.'); }\n };\n const read = async (runId: string): Promise<{ record?: StoredRecord; sequence: number }> => {\n const id = cursorId(runId); const record = await guarded(() => store.read(scope, id));\n if (!record) return { sequence: 0 };\n const state = record.state;\n if (record.scope !== scope || record.id !== id || state['format'] !== 1 || state['relayId'] !== relayId || state['runId'] !== runId\n || !Number.isSafeInteger(state['sequence']) || (state['sequence'] as number) < 0) {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Stored hook relay cursor failed integrity validation.');\n }\n return { record, sequence: state['sequence'] as number };\n };\n /** Compare-and-set advance; a concurrent relay that got further wins and this one resumes from its cursor. */\n const advance = async (runId: string, current: { record?: StoredRecord; sequence: number }, sequence: number): Promise<{ record?: StoredRecord; sequence: number }> => {\n const state = { format: 1, relayId, runId, sequence }; const event = { type: 'hook-relay.advanced', data: { sequence } };\n try {\n const record = current.record\n ? await guarded(() => store.update({ scope, id: current.record!.id, expectedVersion: current.record!.version, state, events: [event] }))\n : (await guarded(() => store.create({ scope, id: cursorId(runId), idempotencyKey: cursorId(runId),\n definitionHash: digest('mayura:workflow-hook-relay-format:v1', {}), state, events: [event] }))).record;\n return { record, sequence };\n } catch (error) {\n if (!(error instanceof StorageError && error.storageCode === 'CONFLICT')) throw error;\n const latest = await read(runId);\n return latest.sequence >= sequence ? latest : advance(runId, latest, sequence);\n }\n };\n const validRun = (runId: unknown): string => {\n if (typeof runId !== 'string' || !identifier.test(runId)) throw new MayuraError('INVALID_INPUT', 'A bounded workflow run identity is required.');\n return runId;\n };\n return Object.freeze<WorkflowHookRelay>({\n async cursor(runId) { return (await read(validRun(runId))).sequence; },\n async deliver(runId, deliveryOptions = {}) {\n validRun(runId);\n const limit = deliveryOptions.limit ?? 1_000; const signal = deliveryOptions.signal;\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10_000) throw new MayuraError('INVALID_INPUT', 'Delivery limit must be 1–10000 events.');\n let current = await read(runId); let scanned = 0; let delivered = 0;\n while (scanned < limit) {\n if (signal?.aborted) throw new MayuraError('CANCELLED', 'Workflow hook delivery was cancelled.');\n const page = await guarded(() => source.events(runId, current.sequence));\n if (!Array.isArray(page)) throw new MayuraError('STORAGE_UNAVAILABLE', 'The workflow event source returned an invalid page.');\n let expected = current.sequence; let unsaved = current.sequence;\n for (const stored of page) {\n if (scanned >= limit) break;\n if (!stored || stored.sequence !== expected + 1 || typeof stored.type !== 'string' || !stored.data || typeof stored.data !== 'object') {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'The workflow event source returned events out of order.');\n }\n expected = stored.sequence; scanned++;\n const callbacks = workflowHookStages(stored.type, stored.data).filter(entry => handlers[entry.stage] !== undefined);\n for (const { stage, status } of callbacks) {\n const nodeId = stored.data['nodeId'];\n const event: WorkflowHookEvent = { stage, runId, sequence: stored.sequence, eventId: `${relayId}:${runId}:${stored.sequence}:${stage}`, type: stored.type,\n ...(typeof nodeId === 'string' && identifier.test(nodeId) ? { nodeId } : {}), ...(status === undefined ? {} : { status }) };\n try {\n await evaluateLifecycleObserver({ stage, handler: handlers[stage] as LifecycleObserver<WorkflowHookEvent>, event, timeoutMs, ...(signal ? { signal } : {}) });\n } catch (error) {\n if (unsaved > current.sequence) current = await advance(runId, current, unsaved);\n if (error instanceof MayuraError && error.code === 'CANCELLED') throw error;\n const code = error instanceof MayuraError ? error.code : 'GUARD_UNAVAILABLE';\n return Object.freeze({ delivered, sequence: current.sequence, failure: Object.freeze({ sequence: stored.sequence, stage, code }) });\n }\n delivered++;\n }\n unsaved = stored.sequence;\n // Persist after every callback-bearing event so a crash never repeats completed callbacks of earlier events.\n if (callbacks.length > 0) current = await advance(runId, current, unsaved);\n }\n if (unsaved > current.sequence) current = await advance(runId, current, unsaved);\n if (page.length < 1_000) break;\n }\n return Object.freeze({ delivered, sequence: current.sequence });\n },\n });\n}\n"]}
|
|
@@ -6,7 +6,7 @@ export { composeExternalEffectVerifiers, defineExternalEffectVerifier, type Exte
|
|
|
6
6
|
export { agentAsDurableWorkflow, type DurableAgentWorkflowOptions } from './agents.js';
|
|
7
7
|
export { createWorkflowFleetControl, compositeFleetTarget, graphFleetTarget, lifecycleFleetTarget, treeFleetTarget, type WorkflowFleetControl, type WorkflowFleetControlOptions, type WorkflowFleetHoldReader, type WorkflowFleetHoldState, type WorkflowFleetSweepCursor, type WorkflowFleetSweepOutcome, type WorkflowFleetSweepReport, type WorkflowFleetTarget } from './fleet-control.js';
|
|
8
8
|
export { createWorkflowLeadership, type WorkflowLeadership, type WorkflowLeadershipOptions, type WorkflowLeadershipState } from './leadership.js';
|
|
9
|
-
export { coordinatorUnit, createWorkflowWorker, type WorkflowWorker, type WorkflowWorkerOptions, type WorkflowWorkerStatus, type WorkflowWorkerUnit } from './worker.js';
|
|
9
|
+
export { coordinatorUnit, createWorkflowWorker, type WorkflowWorker, type WorkflowWorkerOnceOptions, type WorkflowWorkerOnceReport, type WorkflowWorkerOptions, type WorkflowWorkerStatus, type WorkflowWorkerUnit } from './worker.js';
|
|
10
10
|
export { createWorkflowHookRelay, workflowHookStages, type WorkflowHookRelay, type WorkflowHookRelayOptions, type WorkflowHookDelivery, type WorkflowHookEvent, type WorkflowHookStage, type WorkflowHooks, type WorkflowEventSource } from './hook-relay.js';
|
|
11
11
|
export { inventoryWorkflowVersions, assertWorkflowVersionsRetained, compositeVersionTarget, type WorkflowVersionInventory, type WorkflowVersionInventoryOptions, type WorkflowVersionEntry, type WorkflowVersionTarget } from './versions.js';
|
|
12
12
|
export { defineWorkflowMigration, createWorkflowMigrationCatalog, type WorkflowMigrationCatalog, planWorkflowMigration, nodeFingerprint, nodeEvidence, type WorkflowMigration, type WorkflowMigrationOptions, type MigrationPlan, type MigrationPlanEntry, type MigrationBlocker, type MigrationAction, type MigrationCommand, type MigrationNode, type MigrationStep, type WorkflowMigrationResult } from './migration.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtJ,OAAO,EAAE,qBAAqB,EAAE,KAAK,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AyB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,KAAK,0BAA0B,EAAE,KAAK,uBAAuB,EACnK,KAAK,oBAAoB,EAAE,KAAK,uBAAuB,EAAE,KAAK,mBAAmB,EAAE,KAAK,0BAA0B,EAAE,KAAK,yBAAyB,EAClJ,KAAK,wBAAwB,EAAE,KAAK,kBAAkB,EAAE,KAAK,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAC5J,KAAK,wBAAwB,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuG,MAAM,iBAAiB,CAAC;AACtJ,OAAO,EAAE,qBAAqB,EAA0E,MAAM,cAAc,CAAC;AAE7H,OAAO,EAAE,8BAA8B,EACuE,MAAM,gBAAgB,CAAC;AACrI,OAAO,EAAE,8BAA8B,EAAE,4BAA4B,EACqC,MAAM,qBAAqB,CAAC;AACtI,OAAO,EAAE,sBAAsB,EAAoC,MAAM,aAAa,CAAC;AACvF,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,eAAe,EAEvB,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,wBAAwB,EAAyF,MAAM,iBAAiB,CAAC;AAClJ,OAAO,EAAE,eAAe,EAAE,oBAAoB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuG,MAAM,iBAAiB,CAAC;AACtJ,OAAO,EAAE,qBAAqB,EAA0E,MAAM,cAAc,CAAC;AAE7H,OAAO,EAAE,8BAA8B,EACuE,MAAM,gBAAgB,CAAC;AACrI,OAAO,EAAE,8BAA8B,EAAE,4BAA4B,EACqC,MAAM,qBAAqB,CAAC;AACtI,OAAO,EAAE,sBAAsB,EAAoC,MAAM,aAAa,CAAC;AACvF,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,eAAe,EAEvB,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,wBAAwB,EAAyF,MAAM,iBAAiB,CAAC;AAClJ,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAEnB,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAkL,MAAM,iBAAiB,CAAC;AAC9P,OAAO,EAAE,yBAAyB,EAAE,8BAA8B,EAAE,sBAAsB,EAA8H,MAAM,eAAe,CAAC;AAC9O,OAAO,EAAE,uBAAuB,EAAE,8BAA8B,EAAiC,qBAAqB,EAAE,eAAe,EAAE,YAAY,EACgB,MAAM,gBAAgB,CAAC;AAC5L,OAAO,EAAE,8BAA8B,EAAE,oBAAoB,EACW,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,kBAAkB,EAEuS,MAAM,0BAA0B,CAAC;AACjd,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,kBAAkB,EAGrE,MAAM,aAAa,CAAC","sourcesContent":["export { defineWorkflow, type Binding, type WorkflowNode, type WorkflowDefinition, type WorkflowOptions, type WorkflowOutput } from './definition.js';\nexport { createWorkflowRuntime, type WorkflowRuntimeOptions, type WorkflowSnapshot, type VerifiedHuman } from './runtime.js';\nexport type { WorkflowDrainOptions, WorkflowDrainReport } from './drain.js';\nexport { createScheduledWorkflowRuntime, type ScheduledWorkflowRuntime, type ScheduledWorkflowRuntimeOptions,\n type ExternalEffectReconciliationRequest, type VerifiedExternalEffect, type ReconcileExternalEffectCommand } from './scheduled.js';\nexport { composeExternalEffectVerifiers, defineExternalEffectVerifier, type ExternalEffectProviderAttestation,\n type ExternalEffectVerificationRouter, type ExternalEffectVerifier, type ExternalEffectVerifierOptions } from './reconciliation.js';\nexport { agentAsDurableWorkflow, type DurableAgentWorkflowOptions } from './agents.js';\nexport { createWorkflowFleetControl, compositeFleetTarget, graphFleetTarget, lifecycleFleetTarget, treeFleetTarget, type WorkflowFleetControl,\n type WorkflowFleetControlOptions, type WorkflowFleetHoldReader, type WorkflowFleetHoldState, type WorkflowFleetSweepCursor,\n type WorkflowFleetSweepOutcome, type WorkflowFleetSweepReport, type WorkflowFleetTarget } from './fleet-control.js';\nexport { createWorkflowLeadership, type WorkflowLeadership, type WorkflowLeadershipOptions, type WorkflowLeadershipState } from './leadership.js';\nexport { coordinatorUnit, createWorkflowWorker, type WorkflowWorker, type WorkflowWorkerOnceOptions, type WorkflowWorkerOnceReport,\n type WorkflowWorkerOptions, type WorkflowWorkerStatus,\n type WorkflowWorkerUnit } from './worker.js';\nexport { createWorkflowHookRelay, workflowHookStages, type WorkflowHookRelay, type WorkflowHookRelayOptions, type WorkflowHookDelivery, type WorkflowHookEvent, type WorkflowHookStage, type WorkflowHooks, type WorkflowEventSource } from './hook-relay.js';\nexport { inventoryWorkflowVersions, assertWorkflowVersionsRetained, compositeVersionTarget, type WorkflowVersionInventory, type WorkflowVersionInventoryOptions, type WorkflowVersionEntry, type WorkflowVersionTarget } from './versions.js';\nexport { defineWorkflowMigration, createWorkflowMigrationCatalog, type WorkflowMigrationCatalog, planWorkflowMigration, nodeFingerprint, nodeEvidence, type WorkflowMigration, type WorkflowMigrationOptions, type MigrationPlan,\n type MigrationPlanEntry, type MigrationBlocker, type MigrationAction, type MigrationCommand, type MigrationNode, type MigrationStep, type WorkflowMigrationResult } from './migration.js';\nexport { createWorkflowMigrationService, pinnedDefinitionHash, type WorkflowMigrationService, type WorkflowMigrationServiceOptions,\n type WorkflowMigrationOfferRecord, type WorkflowMigrationApplyResult } from './migration-service.js';\nexport { createWorkflowCommandJournal, createWorkflowOperatorTransports, lifecycleOperatorTarget, graphOperatorTarget, treeOperatorTarget,\n type WorkflowCommandJournal, type WorkflowCommandJournalOptions, type WorkflowCommandOutcome, type WorkflowCommandResult, type WorkflowOperatorTarget,\n type WorkflowOperatorView, type WorkflowOperatorIndexRecord, type WorkflowOperatorSettledRecord, type WorkflowOperatorTransports, type WorkflowOperatorResult, type WorkflowOperatorControlInput, type WorkflowOperatorStatus, type WorkflowOperatorNodeKind, type WorkflowOperatorStepStatus, type WorkflowOperatorFleetSweepOutcome, type WorkflowOperatorApproval, type WorkflowOperatorTransportOptions, type WorkflowApprovalCredential } from './operator-transports.js';\nexport { createWorkflowTraceExport, workflowStepTraceContext, workflowTraceContext, workflowTraceSpans, type WorkflowTraceAttributeName, type WorkflowTraceAttributes,\n type WorkflowTraceContext, type WorkflowTraceDefinition, type WorkflowTraceExport, type WorkflowTraceExportOptions, type WorkflowTraceExportResult,\n type WorkflowTraceFlushReport, type WorkflowTraceInput, type WorkflowTraceSink, type WorkflowTraceSnapshot, type WorkflowTraceSource, type WorkflowTraceSpan,\n type WorkflowTraceUnitOptions } from './traces.js';\n"]}
|
|
@@ -41,7 +41,7 @@ export function createWorkflowLeadership(options) {
|
|
|
41
41
|
return await operation();
|
|
42
42
|
}
|
|
43
43
|
catch (error) {
|
|
44
|
-
if (error instanceof MayuraError || (error instanceof StorageError && error.
|
|
44
|
+
if (error instanceof MayuraError || (error instanceof StorageError && error.storageCode === 'CONFLICT'))
|
|
45
45
|
throw error;
|
|
46
46
|
throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership storage is unavailable.');
|
|
47
47
|
}
|
|
@@ -73,7 +73,7 @@ export function createWorkflowLeadership(options) {
|
|
|
73
73
|
return publicState(next, true);
|
|
74
74
|
}
|
|
75
75
|
catch (error) {
|
|
76
|
-
if (error instanceof StorageError && error.
|
|
76
|
+
if (error instanceof StorageError && error.storageCode === 'CONFLICT')
|
|
77
77
|
continue;
|
|
78
78
|
confirmed = null;
|
|
79
79
|
throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership lease update could not be confirmed.');
|
|
@@ -98,7 +98,7 @@ export function createWorkflowLeadership(options) {
|
|
|
98
98
|
return;
|
|
99
99
|
}
|
|
100
100
|
catch (error) {
|
|
101
|
-
if (!(error instanceof StorageError && error.
|
|
101
|
+
if (!(error instanceof StorageError && error.storageCode === 'CONFLICT'))
|
|
102
102
|
throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership release could not be confirmed.');
|
|
103
103
|
}
|
|
104
104
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"leadership.js","sourceRoot":"","sources":["../src/leadership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAA+B,MAAM,cAAc,CAAC;AAC/F,OAAO,EAAE,YAAY,EAA0C,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AA6BzC,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAE1D;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IACzE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAAC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC;IACrE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU;WACrH,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;WAChJ,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,KAAK,IAAI,OAAO,GAAG,OAAO;QAAE,MAAM,IAAI,WAA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AC,MAAM,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,QAAQ,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK;oBAAE,OAAO;gBAC3F,IAAI,CAAC;oBAAC,MAAM,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,eAAe,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,WAAW,EAAE,CAAC,EAAE,CAAe;wBACjI,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;oBAAC,OAAO;gBAAC,CAAC;gBACvF,OAAO,KAAK,EAAE,CAAC;oBAAC,IAAI,CAAC,CAAC,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC;wBAAE,MAAM,IAAI,WAAW,CAAC,qBAAqB,EAAE,4CAA4C,CAAC,CAAC;gBAAC,CAAC;YAClL,CAAC;QACH,CAAC;QACD,QAAQ,EAAE,GAAG,EAAE,CAAC,SAAS,KAAK,IAAI,IAAI,GAAG,EAAE,GAAG,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC;KAC9F,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { freezeJson, jsonValue, MayuraError, type JsonObject, type Scope } from '@mayura/core';\nimport { StorageError, type AggregateStore, type StoredRecord } from '@mayura/storage-contracts';\nimport { digest } from './definition.js';\n\nexport interface WorkflowLeadershipState {\n readonly leader: boolean;\n /** Increments on every change of holder; a lower fence can never regain leadership without a new acquisition. */\n readonly fence: number;\n readonly holderId: string | null;\n readonly expiresAtMs: number;\n}\nexport interface WorkflowLeadership {\n /** Acquire, renew or observe the lease in one compare-and-set step. */\n acquire(): Promise<WorkflowLeadershipState>;\n /** Give up the lease immediately if held, so a standby can take over without waiting for expiry. */\n release(): Promise<void>;\n /** Local view: true only while the last confirmed lease has more than a third of its duration left. */\n isLeader(): boolean;\n}\nexport interface WorkflowLeadershipOptions {\n readonly store: AggregateStore;\n readonly scope: Scope;\n /** Separates independent duties in one scope, for example `lifecycle-host` and `composite-host`. */\n readonly role: string;\n readonly holderId: string;\n /** Lease duration; replicas' clocks must agree to within a third of it. Default 15 s, 3 s–10 min. */\n readonly leaseMs?: number;\n readonly now?: () => number;\n}\n\ninterface LeaseState { format: 1; holderId: string; fence: number; expiresAtMs: number }\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;\n\n/**\n * Durable lease for one duty in one scope. It prevents duplicated host work across replicas; it is not the\n * correctness mechanism — format runtimes stay safe under concurrent drivers through their own CAS and claims.\n */\nexport function createWorkflowLeadership(options: WorkflowLeadershipOptions): WorkflowLeadership {\n const { store } = options; const leaseMs = options.leaseMs ?? 15_000;\n if (!store || typeof store.read !== 'function' || typeof store.create !== 'function' || typeof store.update !== 'function'\n || typeof options.role !== 'string' || !identifier.test(options.role) || typeof options.holderId !== 'string' || !identifier.test(options.holderId)\n || !Number.isSafeInteger(leaseMs) || leaseMs < 3_000 || leaseMs > 600_000) throw new MayuraError('INVALID_CONFIG', 'Leadership requires a store, bounded role/holder identities and a 3 s–10 min lease.');\n const scope = digest('mayura:scope:v1', { principalId: options.scope?.principalId, projectId: options.scope?.projectId });\n const id = digest('mayura:workflow-leadership:v1', { scope, role: options.role }); const holderId = options.holderId;\n const now = (): number => {\n const value = (options.now ?? Date.now)();\n if (!Number.isSafeInteger(value) || value < 0) throw new MayuraError('STORAGE_UNAVAILABLE', 'The trusted leadership clock returned an invalid timestamp.');\n return value;\n };\n let confirmed: { fence: number; expiresAtMs: number } | null = null;\n const leaseFrom = (record: StoredRecord | undefined): LeaseState | undefined => {\n if (!record) return undefined; const state = record.state;\n if (record.scope !== scope || record.id !== id || state['format'] !== 1 || typeof state['holderId'] !== 'string' || !identifier.test(state['holderId'])\n || !Number.isSafeInteger(state['fence']) || (state['fence'] as number) < 1 || !Number.isSafeInteger(state['expiresAtMs']) || (state['expiresAtMs'] as number) < 0) {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Stored leadership lease failed integrity validation.');\n }\n return { format: 1, holderId: state['holderId'], fence: state['fence'] as number, expiresAtMs: state['expiresAtMs'] as number };\n };\n const publicState = (lease: LeaseState | undefined, leader: boolean): WorkflowLeadershipState => freezeJson(jsonValue({\n leader, fence: lease?.fence ?? 0, holderId: lease && lease.expiresAtMs > now() ? lease.holderId : null, expiresAtMs: lease?.expiresAtMs ?? 0,\n })) as unknown as WorkflowLeadershipState;\n const guarded = async <T>(operation: () => Promise<T>): Promise<T> => {\n try { return await operation(); }\n catch (error) { if (error instanceof MayuraError || (error instanceof StorageError && error.code === 'CONFLICT')) throw error;\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership storage is unavailable.'); }\n };\n return Object.freeze<WorkflowLeadership>({\n async acquire() {\n for (let attempt = 0; attempt < 8; attempt++) {\n const record = await guarded(() => store.read(scope, id)); const lease = leaseFrom(record); const observedAtMs = now();\n const mine = lease?.holderId === holderId && lease.expiresAtMs > observedAtMs;\n if (lease && !mine && lease.expiresAtMs > observedAtMs) { confirmed = null; return publicState(lease, false); }\n // Renewal keeps the fence; any change of holder (or a lapsed lease) advances it.\n const next: LeaseState = { format: 1, holderId, fence: mine ? lease.fence : (lease?.fence ?? 0) + 1, expiresAtMs: observedAtMs + leaseMs };\n const event = { type: mine ? 'leadership.renewed' : 'leadership.acquired', data: { fence: next.fence } };\n try {\n if (!record) {\n const created = await store.create({ scope, id, idempotencyKey: id, definitionHash: digest('mayura:workflow-leadership-format:v1', {}),\n state: jsonValue(next) as JsonObject, events: [event] });\n if (!created.created) continue;\n } else await store.update({ scope, id, expectedVersion: record.version, state: jsonValue(next) as JsonObject, events: [event] });\n confirmed = { fence: next.fence, expiresAtMs: next.expiresAtMs }; return publicState(next, true);\n } catch (error) {\n if (error instanceof StorageError && error.code === 'CONFLICT') continue;\n confirmed = null; throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership lease update could not be confirmed.');\n }\n }\n confirmed = null; throw new MayuraError('CONFLICT', 'Leadership lease remained contended after bounded retries.');\n },\n async release() {\n const held = confirmed; confirmed = null; if (!held) return;\n for (let attempt = 0; attempt < 8; attempt++) {\n const record = await guarded(() => store.read(scope, id)); const lease = leaseFrom(record);\n if (!record || !lease || lease.holderId !== holderId || lease.fence !== held.fence) return;\n try { await store.update({ scope, id, expectedVersion: record.version, state: jsonValue({ ...lease, expiresAtMs: 0 }) as JsonObject,\n events: [{ type: 'leadership.released', data: { fence: lease.fence } }] }); return; }\n catch (error) { if (!(error instanceof StorageError && error.code === 'CONFLICT')) throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership release could not be confirmed.'); }\n }\n },\n isLeader: () => confirmed !== null && now() < confirmed.expiresAtMs - Math.floor(leaseMs / 3),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"leadership.js","sourceRoot":"","sources":["../src/leadership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAA+B,MAAM,cAAc,CAAC;AAC/F,OAAO,EAAE,YAAY,EAA0C,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AA6BzC,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAE1D;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IACzE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAAC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC;IACrE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU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ent":["import { freezeJson, jsonValue, MayuraError, type JsonObject, type Scope } from '@mayura/core';\nimport { StorageError, type AggregateStore, type StoredRecord } from '@mayura/storage-contracts';\nimport { digest } from './definition.js';\n\nexport interface WorkflowLeadershipState {\n readonly leader: boolean;\n /** Increments on every change of holder; a lower fence can never regain leadership without a new acquisition. */\n readonly fence: number;\n readonly holderId: string | null;\n readonly expiresAtMs: number;\n}\nexport interface WorkflowLeadership {\n /** Acquire, renew or observe the lease in one compare-and-set step. */\n acquire(): Promise<WorkflowLeadershipState>;\n /** Give up the lease immediately if held, so a standby can take over without waiting for expiry. */\n release(): Promise<void>;\n /** Local view: true only while the last confirmed lease has more than a third of its duration left. */\n isLeader(): boolean;\n}\nexport interface WorkflowLeadershipOptions {\n readonly store: AggregateStore;\n readonly scope: Scope;\n /** Separates independent duties in one scope, for example `lifecycle-host` and `composite-host`. */\n readonly role: string;\n readonly holderId: string;\n /** Lease duration; replicas' clocks must agree to within a third of it. Default 15 s, 3 s–10 min. */\n readonly leaseMs?: number;\n readonly now?: () => number;\n}\n\ninterface LeaseState { format: 1; holderId: string; fence: number; expiresAtMs: number }\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;\n\n/**\n * Durable lease for one duty in one scope. It prevents duplicated host work across replicas; it is not the\n * correctness mechanism — format runtimes stay safe under concurrent drivers through their own CAS and claims.\n */\nexport function createWorkflowLeadership(options: WorkflowLeadershipOptions): WorkflowLeadership {\n const { store } = options; const leaseMs = options.leaseMs ?? 15_000;\n if (!store || typeof store.read !== 'function' || typeof store.create !== 'function' || typeof store.update !== 'function'\n || typeof options.role !== 'string' || !identifier.test(options.role) || typeof options.holderId !== 'string' || !identifier.test(options.holderId)\n || !Number.isSafeInteger(leaseMs) || leaseMs < 3_000 || leaseMs > 600_000) throw new MayuraError('INVALID_CONFIG', 'Leadership requires a store, bounded role/holder identities and a 3 s–10 min lease.');\n const scope = digest('mayura:scope:v1', { principalId: options.scope?.principalId, projectId: options.scope?.projectId });\n const id = digest('mayura:workflow-leadership:v1', { scope, role: options.role }); const holderId = options.holderId;\n const now = (): number => {\n const value = (options.now ?? Date.now)();\n if (!Number.isSafeInteger(value) || value < 0) throw new MayuraError('STORAGE_UNAVAILABLE', 'The trusted leadership clock returned an invalid timestamp.');\n return value;\n };\n let confirmed: { fence: number; expiresAtMs: number } | null = null;\n const leaseFrom = (record: StoredRecord | undefined): LeaseState | undefined => {\n if (!record) return undefined; const state = record.state;\n if (record.scope !== scope || record.id !== id || state['format'] !== 1 || typeof state['holderId'] !== 'string' || !identifier.test(state['holderId'])\n || !Number.isSafeInteger(state['fence']) || (state['fence'] as number) < 1 || !Number.isSafeInteger(state['expiresAtMs']) || (state['expiresAtMs'] as number) < 0) {\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Stored leadership lease failed integrity validation.');\n }\n return { format: 1, holderId: state['holderId'], fence: state['fence'] as number, expiresAtMs: state['expiresAtMs'] as number };\n };\n const publicState = (lease: LeaseState | undefined, leader: boolean): WorkflowLeadershipState => freezeJson(jsonValue({\n leader, fence: lease?.fence ?? 0, holderId: lease && lease.expiresAtMs > now() ? lease.holderId : null, expiresAtMs: lease?.expiresAtMs ?? 0,\n })) as unknown as WorkflowLeadershipState;\n const guarded = async <T>(operation: () => Promise<T>): Promise<T> => {\n try { return await operation(); }\n catch (error) { if (error instanceof MayuraError || (error instanceof StorageError && error.storageCode === 'CONFLICT')) throw error;\n throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership storage is unavailable.'); }\n };\n return Object.freeze<WorkflowLeadership>({\n async acquire() {\n for (let attempt = 0; attempt < 8; attempt++) {\n const record = await guarded(() => store.read(scope, id)); const lease = leaseFrom(record); const observedAtMs = now();\n const mine = lease?.holderId === holderId && lease.expiresAtMs > observedAtMs;\n if (lease && !mine && lease.expiresAtMs > observedAtMs) { confirmed = null; return publicState(lease, false); }\n // Renewal keeps the fence; any change of holder (or a lapsed lease) advances it.\n const next: LeaseState = { format: 1, holderId, fence: mine ? lease.fence : (lease?.fence ?? 0) + 1, expiresAtMs: observedAtMs + leaseMs };\n const event = { type: mine ? 'leadership.renewed' : 'leadership.acquired', data: { fence: next.fence } };\n try {\n if (!record) {\n const created = await store.create({ scope, id, idempotencyKey: id, definitionHash: digest('mayura:workflow-leadership-format:v1', {}),\n state: jsonValue(next) as JsonObject, events: [event] });\n if (!created.created) continue;\n } else await store.update({ scope, id, expectedVersion: record.version, state: jsonValue(next) as JsonObject, events: [event] });\n confirmed = { fence: next.fence, expiresAtMs: next.expiresAtMs }; return publicState(next, true);\n } catch (error) {\n if (error instanceof StorageError && error.storageCode === 'CONFLICT') continue;\n confirmed = null; throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership lease update could not be confirmed.');\n }\n }\n confirmed = null; throw new MayuraError('CONFLICT', 'Leadership lease remained contended after bounded retries.');\n },\n async release() {\n const held = confirmed; confirmed = null; if (!held) return;\n for (let attempt = 0; attempt < 8; attempt++) {\n const record = await guarded(() => store.read(scope, id)); const lease = leaseFrom(record);\n if (!record || !lease || lease.holderId !== holderId || lease.fence !== held.fence) return;\n try { await store.update({ scope, id, expectedVersion: record.version, state: jsonValue({ ...lease, expiresAtMs: 0 }) as JsonObject,\n events: [{ type: 'leadership.released', data: { fence: lease.fence } }] }); return; }\n catch (error) { if (!(error instanceof StorageError && error.storageCode === 'CONFLICT')) throw new MayuraError('STORAGE_UNAVAILABLE', 'Leadership release could not be confirmed.'); }\n }\n },\n isLeader: () => confirmed !== null && now() < confirmed.expiresAtMs - Math.floor(leaseMs / 3),\n });\n}\n"]}
|
|
@@ -9,7 +9,11 @@ export interface WorkflowLifecycleHumanNode<S extends Schema = Schema> {
|
|
|
9
9
|
readonly request: {
|
|
10
10
|
readonly kind: WorkflowLifecycleHumanKind;
|
|
11
11
|
readonly schemaId: string;
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* 64-hex SHA-256 of the response contract. Omit it to derive it from `response` when that validator can describe
|
|
14
|
+
* itself as JSON Schema (Zod 4.2 and later can); see `schemaDigest`.
|
|
15
|
+
*/
|
|
16
|
+
readonly schemaDigest?: string;
|
|
13
17
|
readonly prompt: string;
|
|
14
18
|
readonly response: S;
|
|
15
19
|
readonly context?: Binding;
|
|
@@ -25,6 +29,24 @@ export interface WorkflowLifecycleTimerNode {
|
|
|
25
29
|
readonly fireAtMs: Binding;
|
|
26
30
|
readonly when?: Binding;
|
|
27
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Waits, without holding a worker, for one signal delivered from outside the run: from code with the runtime's
|
|
34
|
+
* `signal`, or over the operator API (`client.signalWorkflow`, `mayura workflow-signal`). The payload is validated
|
|
35
|
+
* with `payload` and becomes the step's output, which later steps bind to like any step output. Delivery is
|
|
36
|
+
* idempotent on the signal id. A signal that arrives before the step starts is kept and completes the step when it
|
|
37
|
+
* starts. With `deadlineAtMs`, a step that has no signal by then is `timed_out`, and the run fails.
|
|
38
|
+
*/
|
|
39
|
+
export interface WorkflowLifecycleSignalNode<S extends Schema = Schema> {
|
|
40
|
+
readonly kind: 'signal';
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly dependsOn?: readonly string[];
|
|
43
|
+
/** The name senders address, unique among the definition's signal nodes. Default: the node id. */
|
|
44
|
+
readonly name?: string;
|
|
45
|
+
readonly payload: S;
|
|
46
|
+
/** Binding to an absolute Unix epoch millisecond deadline. */
|
|
47
|
+
readonly deadlineAtMs?: Binding;
|
|
48
|
+
readonly when?: Binding;
|
|
49
|
+
}
|
|
28
50
|
/**
|
|
29
51
|
* A lifecycle node. Any node may declare `when`, a binding over the input or a dependency's output: the node runs
|
|
30
52
|
* only when it resolves to a value other than `null` or `false` (a path that does not resolve counts as `null`).
|
|
@@ -33,7 +55,7 @@ export interface WorkflowLifecycleTimerNode {
|
|
|
33
55
|
*/
|
|
34
56
|
export type WorkflowLifecycleNode = (WorkflowNode & {
|
|
35
57
|
readonly when?: Binding;
|
|
36
|
-
}) | WorkflowLifecycleHumanNode | WorkflowLifecycleTimerNode;
|
|
58
|
+
}) | WorkflowLifecycleHumanNode | WorkflowLifecycleTimerNode | WorkflowLifecycleSignalNode;
|
|
37
59
|
export interface WorkflowLifecycleOptions<I extends Schema, O extends Schema> {
|
|
38
60
|
readonly id: string;
|
|
39
61
|
readonly version: string;
|
|
@@ -58,9 +80,9 @@ export type AnyWorkflowLifecycle = WorkflowLifecycleDefinition;
|
|
|
58
80
|
export type WorkflowLifecycleOutput<D extends AnyWorkflowLifecycle> = InferOutput<D['output']>;
|
|
59
81
|
/** Executable lifecycle definitions must originate from this package instance. */
|
|
60
82
|
export declare function assertWorkflowLifecycle(definition: AnyWorkflowLifecycle): void;
|
|
61
|
-
/** Build the strict data-only format-5 material; response validators are never persisted. */
|
|
83
|
+
/** Build the strict data-only format-5 material; response and payload validators are never persisted. */
|
|
62
84
|
export declare function lifecycleManifest(definition: Pick<AnyWorkflowLifecycle, 'id' | 'version' | 'nodes' | 'result'>): WorkflowLifecycleManifest;
|
|
63
|
-
/** Define an acyclic format-5 graph with explicit human and
|
|
85
|
+
/** Define an acyclic format-5 graph with explicit human, timer and signal suspension nodes. */
|
|
64
86
|
export declare function defineWorkflowLifecycle<I extends Schema, O extends Schema>(options: WorkflowLifecycleOptions<I, O>): WorkflowLifecycleDefinition<I, O>;
|
|
65
87
|
/**
|
|
66
88
|
* Variable-width parallel work in a lifecycle workflow, up to a fixed maximum. `items` names an array (a dependency's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-definition.d.ts","sourceRoot":"","sources":["../src/lifecycle-definition.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AACzG,OAAO,
|
|
1
|
+
{"version":3,"file":"lifecycle-definition.d.ts","sourceRoot":"","sources":["../src/lifecycle-definition.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,KA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,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,GAAG;QAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAC;IACvH,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B,GAAG,qBAAqB,EAAE,CAa1B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assertSchema, MayuraError } from '../../core/dist/index.js';
|
|
2
|
-
import { workflowLifecycleManifest } from '../../storage-contracts/dist/index.js';
|
|
2
|
+
import { schemaDigest, workflowLifecycleManifest } from '../../storage-contracts/dist/index.js';
|
|
3
3
|
import { assertTool } from '../../tools/dist/index.js';
|
|
4
4
|
import { digest } from './definition.js';
|
|
5
5
|
const definitions = new WeakSet();
|
|
@@ -16,7 +16,17 @@ export function assertWorkflowLifecycle(definition) {
|
|
|
16
16
|
if (!definitions.has(definition))
|
|
17
17
|
throw new MayuraError('INVALID_CONFIG', 'Use defineWorkflowLifecycle from this package instance.');
|
|
18
18
|
}
|
|
19
|
-
/**
|
|
19
|
+
/** The schema digest of a human node that does not give one, derived from its response validator. */
|
|
20
|
+
function derivedDigest(node) {
|
|
21
|
+
try {
|
|
22
|
+
return schemaDigest(node.request.response);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new MayuraError('INVALID_CONFIG', `Human step "${node.id}" has no schemaDigest, and its response validator cannot describe itself as JSON Schema. `
|
|
26
|
+
+ 'Give request.schemaDigest (64 hex characters), for example schemaDigest(jsonSchemaOfYourResponse).');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Build the strict data-only format-5 material; response and payload validators are never persisted. */
|
|
20
30
|
export function lifecycleManifest(definition) {
|
|
21
31
|
try {
|
|
22
32
|
return workflowLifecycleManifest({
|
|
@@ -36,10 +46,13 @@ export function lifecycleManifest(definition) {
|
|
|
36
46
|
return { kind: node.kind, id: node.id, dependsOn: node.dependsOn, ...when };
|
|
37
47
|
if (node.kind === 'timer')
|
|
38
48
|
return { kind: node.kind, id: node.id, dependsOn: node.dependsOn ?? [], fireAtMs: node.fireAtMs, ...when };
|
|
49
|
+
if (node.kind === 'signal')
|
|
50
|
+
return { kind: node.kind, id: node.id, dependsOn: node.dependsOn ?? [], name: node.name ?? node.id,
|
|
51
|
+
deadlineAtMs: node.deadlineAtMs ?? null, ...when };
|
|
39
52
|
if (node.kind === 'human')
|
|
40
53
|
return {
|
|
41
54
|
kind: node.kind, id: node.id, dependsOn: node.dependsOn ?? [], requestKind: node.request.kind,
|
|
42
|
-
schemaId: node.request.schemaId, schemaDigest: node.request.schemaDigest, prompt: node.request.prompt,
|
|
55
|
+
schemaId: node.request.schemaId, schemaDigest: node.request.schemaDigest ?? derivedDigest(node), prompt: node.request.prompt,
|
|
43
56
|
context: node.request.context ?? null, subjectDigest: node.request.subjectDigest ?? null,
|
|
44
57
|
deadlineAtMs: node.request.deadlineAtMs ?? null, ...when,
|
|
45
58
|
};
|
|
@@ -48,11 +61,13 @@ export function lifecycleManifest(definition) {
|
|
|
48
61
|
result: definition.result,
|
|
49
62
|
});
|
|
50
63
|
}
|
|
51
|
-
catch {
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof MayuraError && error.code === 'INVALID_CONFIG')
|
|
66
|
+
throw error;
|
|
52
67
|
throw new MayuraError('INVALID_CONFIG', 'Workflow lifecycle metadata is invalid or exceeds its finite bounds.');
|
|
53
68
|
}
|
|
54
69
|
}
|
|
55
|
-
/** Define an acyclic format-5 graph with explicit human and
|
|
70
|
+
/** Define an acyclic format-5 graph with explicit human, timer and signal suspension nodes. */
|
|
56
71
|
export function defineWorkflowLifecycle(options) {
|
|
57
72
|
if (!options || !Array.isArray(options.nodes) || options.nodes.length < 1 || options.nodes.length > 128) {
|
|
58
73
|
throw new MayuraError('INVALID_CONFIG', 'A workflow lifecycle requires 1–128 nodes.');
|
|
@@ -61,8 +76,9 @@ export function defineWorkflowLifecycle(options) {
|
|
|
61
76
|
assertSchema(options.output);
|
|
62
77
|
const tools = new Map();
|
|
63
78
|
const responses = new Map();
|
|
79
|
+
const payloads = new Map();
|
|
64
80
|
for (const node of options.nodes) {
|
|
65
|
-
if (!node || !['tool', 'join', 'human', 'timer'].includes(node.kind)) {
|
|
81
|
+
if (!node || !['tool', 'join', 'human', 'timer', 'signal'].includes(node.kind)) {
|
|
66
82
|
throw new MayuraError('INVALID_CONFIG', 'Unknown workflow lifecycle node kind.');
|
|
67
83
|
}
|
|
68
84
|
if (node.kind === 'tool') {
|
|
@@ -73,6 +89,10 @@ export function defineWorkflowLifecycle(options) {
|
|
|
73
89
|
assertSchema(node.request.response);
|
|
74
90
|
responses.set(node.id, snapshot(node.request.response));
|
|
75
91
|
}
|
|
92
|
+
if (node.kind === 'signal') {
|
|
93
|
+
assertSchema(node.payload);
|
|
94
|
+
payloads.set(node.id, snapshot(node.payload));
|
|
95
|
+
}
|
|
76
96
|
}
|
|
77
97
|
const manifest = lifecycleManifest(options);
|
|
78
98
|
const nodes = Object.freeze(manifest.graph.map(node => {
|
|
@@ -88,6 +108,11 @@ export function defineWorkflowLifecycle(options) {
|
|
|
88
108
|
return Object.freeze({
|
|
89
109
|
kind: node.kind, id: node.id, dependsOn: node.dependsOn, fireAtMs: node.fireAtMs, ...when,
|
|
90
110
|
});
|
|
111
|
+
if (node.kind === 'signal')
|
|
112
|
+
return Object.freeze({
|
|
113
|
+
kind: node.kind, id: node.id, dependsOn: node.dependsOn, name: node.name, payload: payloads.get(node.id),
|
|
114
|
+
...(node.deadlineAtMs === null ? {} : { deadlineAtMs: node.deadlineAtMs }), ...when,
|
|
115
|
+
});
|
|
91
116
|
return Object.freeze({
|
|
92
117
|
kind: node.kind, id: node.id, dependsOn: node.dependsOn, ...when,
|
|
93
118
|
request: Object.freeze({
|