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
package/lib/client/src/index.ts
CHANGED
|
@@ -30,7 +30,11 @@ export interface RemoteRun {
|
|
|
30
30
|
/** Returns undefined while running; terminal output requires a wire-output schema. No polling/retry is implicit. */
|
|
31
31
|
result<T>(schema: ClientSchema<T>, options?: { readonly signal?: AbortSignal }): Promise<RemoteOutcome<T> | undefined>;
|
|
32
32
|
cancel(options?: { readonly signal?: AbortSignal }): Promise<void>;
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The run's metadata events from `after`. Reconnects transparently (see `EventOptions.reconnect`) until the run's
|
|
35
|
+
* `run.completed`; a stretch the server no longer holds arrives as one `events.gap`.
|
|
36
|
+
*/
|
|
37
|
+
events(options?: EventOptions): AsyncIterable<ClientEvent>;
|
|
34
38
|
}
|
|
35
39
|
export interface RemoteHumanRequest {
|
|
36
40
|
readonly id: string; readonly agentId: string; readonly kind: 'information' | 'correction' | 'plan_selection';
|
|
@@ -78,12 +82,59 @@ export interface ClientOptions {
|
|
|
78
82
|
readonly token: () => string | Promise<string>;
|
|
79
83
|
readonly fetch?: typeof globalThis.fetch;
|
|
80
84
|
readonly maxResponseBytes?: number;
|
|
85
|
+
/** The most media one run submission may carry, base64-encoded (default 16 MiB, the server's default). */
|
|
86
|
+
readonly maxMediaBytes?: number;
|
|
81
87
|
readonly maxEventBytes?: number;
|
|
88
|
+
/** How long a request may take (default 30 s). For event streams it bounds only connecting, not the stream. */
|
|
82
89
|
readonly requestTimeoutMs?: number;
|
|
90
|
+
/** An event stream that delivers nothing, not even the server's keep-alive, for this long is reconnected (default 45 s). */
|
|
91
|
+
readonly eventIdleTimeoutMs?: number;
|
|
92
|
+
/** Consecutive failed event-stream reconnects before `events()` gives up with the last error (default 8). */
|
|
93
|
+
readonly maxReconnectAttempts?: number;
|
|
94
|
+
/** First reconnect delay after a failure, doubled per failure up to 10 s, with jitter (default 250 ms). */
|
|
95
|
+
readonly reconnectDelayMs?: number;
|
|
96
|
+
}
|
|
97
|
+
/** The authenticated token's own identity, and which optional APIs this server offers it. */
|
|
98
|
+
export interface RemoteSession {
|
|
99
|
+
readonly scope: { readonly principalId: string; readonly projectId: string };
|
|
100
|
+
readonly agentIds: readonly string[];
|
|
101
|
+
readonly capabilities: readonly ('runs:read' | 'runs:submit' | 'runs:cancel' | 'operations:read' | 'humans:read' | 'humans:respond'
|
|
102
|
+
| 'workflows:read' | 'workflows:control' | 'workflows:fleet' | 'workflows:migrate')[];
|
|
103
|
+
readonly expiresAtMs: number;
|
|
104
|
+
/** Optional server APIs this token can use, by server option name, for example `workflowIndex` or `runRecords`. */
|
|
105
|
+
readonly features: readonly RemoteFeature[];
|
|
106
|
+
}
|
|
107
|
+
export type RemoteFeature = 'humanRequests' | 'workflowIndex' | 'workflowViews' | 'workflowControls' | 'workflowSignals' | 'workflowResumes'
|
|
108
|
+
| 'workflowPauses' | 'workflowFleet' | 'workflowMigrations' | 'runRecords';
|
|
109
|
+
/** Passed to `onReconnect` before an event stream reconnects. */
|
|
110
|
+
export interface EventReconnect {
|
|
111
|
+
/** Consecutive failed attempts so far (0 when the server simply ended a stream that made progress). */
|
|
112
|
+
readonly attempt: number;
|
|
113
|
+
/** The sequence the stream resumes after. */
|
|
114
|
+
readonly after: number;
|
|
115
|
+
readonly delayMs: number;
|
|
116
|
+
/** The error that ended the previous connection, or null when the server ended it normally. */
|
|
117
|
+
readonly code: string | null;
|
|
118
|
+
}
|
|
119
|
+
export interface EventOptions {
|
|
120
|
+
readonly after?: number; readonly signal?: AbortSignal;
|
|
121
|
+
/**
|
|
122
|
+
* Reconnect from the last sequence when a stream ends or fails, until `run.completed` (default true). With false,
|
|
123
|
+
* one connection is read and its end or failure is returned as is.
|
|
124
|
+
*/
|
|
125
|
+
readonly reconnect?: boolean;
|
|
126
|
+
/** Called before each reconnect, for example to show a "reconnecting" state. Errors it throws are ignored. */
|
|
127
|
+
readonly onReconnect?: (reconnect: EventReconnect) => void;
|
|
83
128
|
}
|
|
84
129
|
export interface MayuraClient {
|
|
130
|
+
/** What the token may do: its scope, agents, capabilities, expiry and the optional APIs the server offers it. */
|
|
131
|
+
session(options?: { readonly signal?: AbortSignal }): Promise<RemoteSession>;
|
|
85
132
|
agents(options?: { readonly signal?: AbortSignal }): Promise<readonly { readonly id: string; readonly version: string }[]>;
|
|
86
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Start a run. `media` holds images or PDFs for an agent that accepts them: bytes (such as `media(...)` from mayura,
|
|
135
|
+
* or a file's bytes), an https URL, or a stored artifact reference.
|
|
136
|
+
*/
|
|
137
|
+
submit(agentId: string, input: unknown, options: { readonly idempotencyKey: string; readonly signal?: AbortSignal; readonly media?: readonly ClientMedia[] }): Promise<RemoteRun>;
|
|
87
138
|
run(id: string): RemoteRun;
|
|
88
139
|
humanRequests(options?: { readonly after?: string; readonly limit?: number; readonly signal?: AbortSignal }): Promise<RemoteHumanRequestPage>;
|
|
89
140
|
humanRequest(id: string, options?: { readonly signal?: AbortSignal }): Promise<RemoteHumanRequest>;
|
|
@@ -116,9 +167,118 @@ export interface MayuraClient {
|
|
|
116
167
|
respondHumanRequest(id: string, requestDigest: string, value: unknown,
|
|
117
168
|
options: { readonly commandId: string; readonly signal?: AbortSignal }): Promise<RemoteHumanRequest>;
|
|
118
169
|
}
|
|
119
|
-
/**
|
|
170
|
+
/** Machine-useful facts a server error may carry; each is validated before it is exposed. */
|
|
171
|
+
export interface ClientErrorDetails {
|
|
172
|
+
/** Wait at least this long before retrying (also sent as Retry-After). */
|
|
173
|
+
readonly retryAfterMs?: number;
|
|
174
|
+
/** The capability the token lacks (CAPABILITY_REQUIRED). */
|
|
175
|
+
readonly capability?: string;
|
|
176
|
+
/** The server option that enables an API the server does not offer (NOT_ENABLED). */
|
|
177
|
+
readonly option?: string;
|
|
178
|
+
/** The size limit that was exceeded (BODY_TOO_LARGE). */
|
|
179
|
+
readonly limitBytes?: number;
|
|
180
|
+
/** The workflow run's revision now (WORKFLOW_CONFLICT, when the token may read the run). */
|
|
181
|
+
readonly currentRevision?: number;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* A failed request. `code` is the Mayura server's error code when the server sent one (for example
|
|
185
|
+
* `IDEMPOTENCY_CONFLICT` or `CAPABILITY_REQUIRED`), or a client code for failures before or around HTTP
|
|
186
|
+
* (`TIMEOUT`, `ABORTED`, `TRANSPORT_FAILED`, `INVALID_RESPONSE`, `HTTP_ERROR` for a non-Mayura error answer, ...).
|
|
187
|
+
* `message` is the server's fixed, data-free explanation, checked to be short printable text, or a client message.
|
|
188
|
+
*/
|
|
189
|
+
/** An image or PDF sent with a run: its bytes, an https URL the model provider fetches, or a stored artifact reference. */
|
|
190
|
+
export type ClientMedia =
|
|
191
|
+
| { readonly mediaType: string; readonly data: Uint8Array; readonly name?: string }
|
|
192
|
+
| { readonly mediaType: string; readonly url: string; readonly name?: string }
|
|
193
|
+
| { readonly artifact: Readonly<Record<string, unknown>>; readonly name?: string };
|
|
194
|
+
|
|
195
|
+
/** Base64 of bytes, without depending on Node.js. */
|
|
196
|
+
function base64(bytes: Uint8Array): string {
|
|
197
|
+
let binary = '';
|
|
198
|
+
for (let index = 0; index < bytes.length; index += 32_768) binary += String.fromCharCode(...bytes.subarray(index, index + 32_768));
|
|
199
|
+
return btoa(binary);
|
|
200
|
+
}
|
|
201
|
+
/** The JSON form of submitted media, and its size once encoded. */
|
|
202
|
+
function mediaBody(items: readonly ClientMedia[], maxBytes: number): { readonly body: ClientJson[]; readonly bytes: number } {
|
|
203
|
+
const refuse = (message: string): never => { throw new ClientError('INVALID_MEDIA', undefined, { message }); };
|
|
204
|
+
if (!Array.isArray(items) || items.length > 32) return refuse('media must be a list of at most 32 items.');
|
|
205
|
+
let bytes = 0; const body: ClientJson[] = [];
|
|
206
|
+
for (const [index, item] of items.entries()) {
|
|
207
|
+
const name = item?.name === undefined ? {} : { name: item.name };
|
|
208
|
+
if (item && 'artifact' in item) { body.push({ artifact: item.artifact as ClientJson, ...name }); bytes += 4_096; continue; }
|
|
209
|
+
if (!item || typeof item.mediaType !== 'string') return refuse(`media ${index + 1} needs a mediaType.`);
|
|
210
|
+
if ('data' in item && item.data instanceof Uint8Array) {
|
|
211
|
+
const data = base64(item.data); bytes += data.length + 256; body.push({ mediaType: item.mediaType, data, ...name });
|
|
212
|
+
} else if ('url' in item && typeof item.url === 'string') { bytes += item.url.length + 256; body.push({ mediaType: item.mediaType, url: item.url, ...name }); }
|
|
213
|
+
else return refuse(`media ${index + 1} needs data (bytes), a url or an artifact reference.`);
|
|
214
|
+
if (bytes > maxBytes) refuse(`the media is larger than this client sends (maxMediaBytes, ${maxBytes} bytes encoded).`);
|
|
215
|
+
}
|
|
216
|
+
return { body, bytes };
|
|
217
|
+
}
|
|
218
|
+
|
|
120
219
|
export class ClientError extends Error {
|
|
121
|
-
|
|
220
|
+
readonly retryAfterMs?: number;
|
|
221
|
+
readonly details: Readonly<ClientErrorDetails>;
|
|
222
|
+
constructor(readonly code: string, readonly status?: number, options: { readonly message?: string; readonly details?: ClientErrorDetails } = {}) {
|
|
223
|
+
super(options.message ?? clientMessages[code] ?? `Mayura request failed (${code}).`); this.name = 'ClientError';
|
|
224
|
+
this.details = Object.freeze({ ...options.details });
|
|
225
|
+
if (options.details?.retryAfterMs !== undefined) this.retryAfterMs = options.details.retryAfterMs;
|
|
226
|
+
Object.freeze(this);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/** Messages for the codes the client itself produces. */
|
|
230
|
+
const clientMessages: Readonly<Record<string, string>> = Object.freeze({
|
|
231
|
+
ABORTED: 'The request was cancelled by its caller.',
|
|
232
|
+
TIMEOUT: 'The server did not answer within requestTimeoutMs, or an event stream stayed silent for eventIdleTimeoutMs.',
|
|
233
|
+
TRANSPORT_FAILED: 'The server could not be reached, or the connection failed. The request may or may not have taken effect.',
|
|
234
|
+
REDIRECT_DENIED: 'The server answered with a redirect, which the client never follows.',
|
|
235
|
+
HTTP_ERROR: 'The server answered with an HTTP error that did not come from Mayura (for example from a proxy).',
|
|
236
|
+
INVALID_RESPONSE: 'The server\'s answer did not have the shape this client expects.',
|
|
237
|
+
INVALID_JSON: 'A value was not bounded plain JSON.',
|
|
238
|
+
RESPONSE_LIMIT: 'The server\'s answer was larger than maxResponseBytes.',
|
|
239
|
+
INVALID_STREAM: 'The event stream broke the protocol (bad frame, order or run).',
|
|
240
|
+
TRUNCATED_STREAM: 'The event stream ended in the middle of an event.',
|
|
241
|
+
STREAM_LIMIT: 'An event frame or chunk was larger than the client allows.',
|
|
242
|
+
OBSERVATION_FAILED: 'The server could not follow the run\'s events from the requested position.',
|
|
243
|
+
INVALID_CONFIG: 'The client options are invalid.',
|
|
244
|
+
INVALID_MEDIA: 'The media could not be sent: each item needs a mediaType and bytes, a url or an artifact reference.',
|
|
245
|
+
INVALID_CREDENTIAL: 'The token callback returned something that is not a valid bearer token.',
|
|
246
|
+
INVALID_REQUEST: 'The request arguments are invalid.',
|
|
247
|
+
INVALID_OUTPUT: 'The run\'s output did not match the schema.',
|
|
248
|
+
});
|
|
249
|
+
/**
|
|
250
|
+
* Error codes a Mayura server (mayura/server and mayura/server-node) sends. Only these are passed through as
|
|
251
|
+
* `ClientError.code`; any other error answer becomes HTTP_ERROR.
|
|
252
|
+
*/
|
|
253
|
+
const serverErrorCodes: ReadonlySet<string> = new Set(['AUTH_REQUIRED', 'AUTH_INVALID', 'AUTH_EXPIRED', 'AUTH_UNAVAILABLE', 'AUTH_LIMIT',
|
|
254
|
+
'IDENTITY_INVALID', 'CAPABILITY_REQUIRED', 'ORIGIN_DENIED', 'PREFLIGHT_DENIED', 'INVALID_DESTINATION', 'INVALID_QUERY', 'INVALID_CURSOR',
|
|
255
|
+
'INVALID_JSON', 'INVALID_REQUEST', 'INVALID_MEDIA', 'IDEMPOTENCY_KEY_REQUIRED', 'UNSUPPORTED_MEDIA_TYPE', 'BODY_TOO_LARGE', 'ROUTE_NOT_FOUND', 'METHOD_NOT_ALLOWED',
|
|
256
|
+
'NOT_ENABLED', 'AGENT_NOT_FOUND', 'RUN_NOT_FOUND', 'HUMAN_REQUEST_NOT_FOUND', 'WORKFLOW_RUN_NOT_FOUND', 'MIGRATION_NOT_FOUND', 'REQUEST_TIMEOUT',
|
|
257
|
+
'IDEMPOTENCY_CONFLICT', 'SUBMISSION_IN_PROGRESS', 'SUBMISSION_OUTCOME_UNKNOWN', 'RUN_EXPIRED', 'WORKFLOW_CONFLICT', 'FLEET_CONFLICT',
|
|
258
|
+
'MIGRATION_REFUSED', 'REQUEST_LIMIT', 'STREAM_LIMIT', 'RUN_LIMIT', 'RUNTIME_LIMIT', 'HUMAN_LIMIT', 'WORKFLOW_LIMIT', 'SERVER_CLOSED',
|
|
259
|
+
'SERVICE_UNAVAILABLE', 'SUBMISSION_JOURNAL_UNAVAILABLE', 'RUN_RECORDS_UNAVAILABLE', 'HUMAN_UNAVAILABLE', 'HUMAN_TRANSPORT_INVALID',
|
|
260
|
+
'WORKFLOW_UNAVAILABLE', 'WORKFLOW_TRANSPORT_INVALID', 'RESPONSE_TOO_LARGE', 'OBSERVATION_FAILED', 'INTERNAL_ERROR', 'HOST_UNAVAILABLE',
|
|
261
|
+
'MISDIRECTED_REQUEST']);
|
|
262
|
+
const capabilityNames: readonly string[] = ['runs:read', 'runs:submit', 'runs:cancel', 'operations:read', 'humans:read', 'humans:respond',
|
|
263
|
+
'workflows:read', 'workflows:control', 'workflows:fleet', 'workflows:migrate'];
|
|
264
|
+
/** A server error body `{ error: { code, message, ...details } }`, or null when it is not one. Nothing else is read from it. */
|
|
265
|
+
function serverError(value: unknown, status: number, retryAfter: string | null): ClientError | null {
|
|
266
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
267
|
+
const error = (value as Record<string, unknown>)['error'];
|
|
268
|
+
if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;
|
|
269
|
+
const raw = error as Record<string, unknown>; const code = raw['code']; const message = raw['message'];
|
|
270
|
+
if (typeof code !== 'string' || !serverErrorCodes.has(code)) return null;
|
|
271
|
+
const details: { -readonly [key in keyof ClientErrorDetails]: ClientErrorDetails[key] } = {};
|
|
272
|
+
const bounded = (item: unknown, maximum: number): item is number => Number.isSafeInteger(item) && (item as number) >= 0 && (item as number) <= maximum;
|
|
273
|
+
if (bounded(raw['retryAfterMs'], 3_600_000)) details.retryAfterMs = raw['retryAfterMs'];
|
|
274
|
+
else if (retryAfter !== null && /^\d{1,4}$/.test(retryAfter)) details.retryAfterMs = Number(retryAfter) * 1_000;
|
|
275
|
+
if (typeof raw['capability'] === 'string' && capabilityNames.includes(raw['capability'])) details.capability = raw['capability'];
|
|
276
|
+
if (typeof raw['option'] === 'string' && /^[a-z][A-Za-z]{0,63}$/.test(raw['option'])) details.option = raw['option'];
|
|
277
|
+
if (bounded(raw['limitBytes'], Number.MAX_SAFE_INTEGER)) details.limitBytes = raw['limitBytes'];
|
|
278
|
+
if (bounded(raw['currentRevision'], Number.MAX_SAFE_INTEGER) && (raw['currentRevision'] as number) >= 1) details.currentRevision = raw['currentRevision'];
|
|
279
|
+
// Only short printable text is shown; anything else falls back to the client's own message for the code.
|
|
280
|
+
const text = typeof message === 'string' && /^[\x20-\x7e]{1,1024}$/.test(message) ? message : undefined;
|
|
281
|
+
return new ClientError(code, status, { ...(text === undefined ? {} : { message: text }), details });
|
|
122
282
|
}
|
|
123
283
|
const encoder = new TextEncoder();
|
|
124
284
|
const migrationIdPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
@@ -271,7 +431,7 @@ function workflowView(value: unknown, expectedId: string): WorkflowViewInput {
|
|
|
271
431
|
const raw = record(value); const expected = ['format', 'definitionId', 'definitionVersion', 'runId', 'revision', 'status', 'nodes', 'steps'];
|
|
272
432
|
if (!Object.isFrozen(raw) || Object.keys(raw).length !== expected.length || expected.some(key => !Object.hasOwn(raw, key))) return fail();
|
|
273
433
|
const format = raw['format']; const nodes = raw['nodes']; const steps = raw['steps'];
|
|
274
|
-
const admittedKinds: Readonly<Record<number, readonly string[]>> = { 2: ['tool', 'join'], 3: ['tool', 'join', 'wait'], 4: ['tool', 'join', 'child'], 5: ['tool', 'join', 'human', 'timer'] };
|
|
434
|
+
const admittedKinds: Readonly<Record<number, readonly string[]>> = { 2: ['tool', 'join'], 3: ['tool', 'join', 'wait'], 4: ['tool', 'join', 'child'], 5: ['tool', 'join', 'human', 'timer', 'signal'] };
|
|
275
435
|
const runStatuses = ['running', 'waiting', 'paused', 'succeeded', 'failed', 'blocked', 'cancelled', 'outcome_unknown'];
|
|
276
436
|
const stepStatuses = ['pending', 'waiting', 'approved', 'dispatching', 'succeeded', 'failed', 'blocked', 'unknown', 'skipped', 'timed_out'];
|
|
277
437
|
if (typeof format !== 'number' || ![2, 3, 4, 5].includes(format) || typeof raw['definitionId'] !== 'string' || !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(raw['definitionId'])
|
|
@@ -325,10 +485,25 @@ function workflowIndexEntry(value: unknown, settled = false): WorkflowIndexEntry
|
|
|
325
485
|
|| typeof raw['status'] !== 'string' || !['running', 'waiting', 'paused', 'succeeded', 'failed', 'blocked', 'cancelled', 'outcome_unknown'].includes(raw['status'])) return fail();
|
|
326
486
|
return raw as unknown as WorkflowIndexEntry;
|
|
327
487
|
}
|
|
488
|
+
const featureNames: readonly string[] = ['humanRequests', 'workflowIndex', 'workflowViews', 'workflowControls', 'workflowSignals', 'workflowResumes',
|
|
489
|
+
'workflowPauses', 'workflowFleet', 'workflowMigrations', 'runRecords'];
|
|
490
|
+
/**
|
|
491
|
+
* Stream failures worth another connection: the network, silence, a cut stream, a server that is busy, restarting or
|
|
492
|
+
* briefly without storage, and an expired identity (the token callback may return a fresh one). Anything else, such as
|
|
493
|
+
* RUN_NOT_FOUND, a missing capability or a protocol violation, is final.
|
|
494
|
+
*/
|
|
495
|
+
function retryableStream(error: ClientError): boolean {
|
|
496
|
+
return ['TRANSPORT_FAILED', 'TIMEOUT', 'TRUNCATED_STREAM', 'RUN_RECORDS_UNAVAILABLE', 'AUTH_EXPIRED'].includes(error.code)
|
|
497
|
+
|| (error.status !== undefined && [408, 429, 502, 503, 504].includes(error.status));
|
|
498
|
+
}
|
|
499
|
+
/** Why a signal ended: the client's own timers abort with a TIMEOUT error; anything else is the caller's cancellation. */
|
|
500
|
+
function stopped(signal: AbortSignal): ClientError {
|
|
501
|
+
return signal.reason instanceof ClientError && signal.reason.code === 'TIMEOUT' ? signal.reason : new ClientError('ABORTED');
|
|
502
|
+
}
|
|
328
503
|
async function race<T>(work: PromiseLike<T>, signal: AbortSignal): Promise<T> {
|
|
329
|
-
if (signal.aborted) { void Promise.resolve(work).catch(() => {}); throw
|
|
504
|
+
if (signal.aborted) { void Promise.resolve(work).catch(() => {}); throw stopped(signal); }
|
|
330
505
|
return await new Promise<T>((resolve, reject) => {
|
|
331
|
-
const abort = (): void => { cleanup(); reject(
|
|
506
|
+
const abort = (): void => { cleanup(); reject(stopped(signal)); };
|
|
332
507
|
const cleanup = (): void => { signal.removeEventListener('abort', abort); };
|
|
333
508
|
signal.addEventListener('abort', abort, { once: true });
|
|
334
509
|
Promise.resolve(work).then(value => { cleanup(); resolve(value); }, () => { cleanup(); reject(new ClientError('TRANSPORT_FAILED')); });
|
|
@@ -343,18 +518,22 @@ export function createClient(options: ClientOptions): MayuraClient {
|
|
|
343
518
|
if (base.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(base.hostname)) throw new ClientError('INVALID_CONFIG');
|
|
344
519
|
if (typeof options.token !== 'function') throw new ClientError('INVALID_CONFIG');
|
|
345
520
|
const token = options.token; const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
346
|
-
const maxBytes = options.maxResponseBytes ?? 4_194_304; const
|
|
347
|
-
if (
|
|
521
|
+
const maxBytes = options.maxResponseBytes ?? 4_194_304; const maxMediaBytes = options.maxMediaBytes ?? 16_777_216;
|
|
522
|
+
if (!Number.isSafeInteger(maxMediaBytes) || maxMediaBytes < 1) throw new ClientError('INVALID_CONFIG');
|
|
523
|
+
const frameBytes = options.maxEventBytes ?? 16_384; const timeout = options.requestTimeoutMs ?? 30_000;
|
|
524
|
+
const idleTimeout = options.eventIdleTimeoutMs ?? 45_000; const reconnectDelay = options.reconnectDelayMs ?? 250; const maxAttempts = options.maxReconnectAttempts ?? 8;
|
|
525
|
+
if ([maxBytes, frameBytes, timeout, idleTimeout, reconnectDelay].some(value => !Number.isSafeInteger(value) || value < 1 || value > 16_777_216)
|
|
526
|
+
|| !Number.isSafeInteger(maxAttempts) || maxAttempts < 0 || maxAttempts > 1_000) throw new ClientError('INVALID_CONFIG');
|
|
348
527
|
|
|
349
528
|
const request = async (path: string, method: 'GET' | 'POST', signal: AbortSignal, body?: ClientJson, key?: string): Promise<Response> => {
|
|
350
|
-
const credential = await race(Promise.resolve().then(() => { if (signal.aborted) throw
|
|
529
|
+
const credential = await race(Promise.resolve().then(() => { if (signal.aborted) throw stopped(signal); return token(); }), signal);
|
|
351
530
|
if (typeof credential !== 'string' || !/^[\x21-\x7e]{1,8192}$/.test(credential)) throw new ClientError('INVALID_CREDENTIAL');
|
|
352
531
|
const headers: Record<string, string> = { Authorization: `Bearer ${credential}` };
|
|
353
532
|
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
354
533
|
if (key !== undefined) headers['Idempotency-Key'] = key;
|
|
355
|
-
if (signal.aborted) throw
|
|
534
|
+
if (signal.aborted) throw stopped(signal);
|
|
356
535
|
const response = await race(Promise.resolve().then(() => {
|
|
357
|
-
if (signal.aborted) throw
|
|
536
|
+
if (signal.aborted) throw stopped(signal);
|
|
358
537
|
return transport(new URL(path, base), {
|
|
359
538
|
method, headers, signal, redirect: 'error', credentials: 'omit', cache: 'no-store',
|
|
360
539
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
@@ -362,37 +541,51 @@ export function createClient(options: ClientOptions): MayuraClient {
|
|
|
362
541
|
}).then(response => {
|
|
363
542
|
if (signal.aborted) {
|
|
364
543
|
void response.body?.cancel().catch(() => {});
|
|
365
|
-
throw
|
|
544
|
+
throw stopped(signal);
|
|
366
545
|
}
|
|
367
546
|
return response;
|
|
368
547
|
}), signal);
|
|
369
|
-
if (response.redirected || (response.url && new URL(response.url).origin !== base.origin)
|
|
370
|
-
void response.body?.cancel().catch(() => {});
|
|
371
|
-
|
|
548
|
+
if (response.redirected || (response.url && new URL(response.url).origin !== base.origin)) {
|
|
549
|
+
void response.body?.cancel().catch(() => {}); throw new ClientError('REDIRECT_DENIED', response.status);
|
|
550
|
+
}
|
|
551
|
+
if (!response.ok) {
|
|
552
|
+
// A Mayura error body names what happened; anything else (a proxy page, a hostile body) is only an HTTP status.
|
|
553
|
+
let failure: ClientError | null = null;
|
|
554
|
+
if (/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '')) {
|
|
555
|
+
try { failure = serverError(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readBytes(response, signal, 16_384))), response.status, response.headers.get('retry-after')); }
|
|
556
|
+
catch (error) { if (error instanceof ClientError && ['ABORTED', 'TIMEOUT'].includes(error.code)) throw error; }
|
|
557
|
+
} else void response.body?.cancel().catch(() => {});
|
|
558
|
+
throw failure ?? new ClientError('HTTP_ERROR', response.status);
|
|
372
559
|
}
|
|
373
560
|
return response;
|
|
374
561
|
};
|
|
375
|
-
|
|
376
|
-
|
|
562
|
+
/** The operation's signal: the caller's cancellation, or TIMEOUT after `ms`. */
|
|
563
|
+
const scope = (external?: AbortSignal, ms: number = timeout) => {
|
|
564
|
+
const controller = new AbortController(); const abort = (): void => { controller.abort(new ClientError('ABORTED')); };
|
|
377
565
|
external?.addEventListener('abort', abort, { once: true }); if (external?.aborted) abort();
|
|
378
|
-
const timer = setTimeout(abort,
|
|
566
|
+
const timer = setTimeout(() => controller.abort(new ClientError('TIMEOUT')), ms);
|
|
379
567
|
return { signal: controller.signal, close() { clearTimeout(timer); external?.removeEventListener('abort', abort); controller.abort(); } };
|
|
380
568
|
};
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
const reader = response.body?.getReader(); if (!reader) return fail();
|
|
569
|
+
const readBytes = async (response: Response, signal: AbortSignal, maximum: number): Promise<Uint8Array> => {
|
|
570
|
+
const reader = response.body?.getReader(); if (!reader) return new Uint8Array();
|
|
384
571
|
const chunks: Uint8Array[] = []; let size = 0; let done = false;
|
|
385
572
|
try {
|
|
386
573
|
while (true) {
|
|
387
574
|
const next = await race(reader.read(), signal); if (next.done) { done = true; break; }
|
|
388
|
-
size += next.value.byteLength; if (size >
|
|
575
|
+
size += next.value.byteLength; if (size > maximum) throw new ClientError('RESPONSE_LIMIT'); chunks.push(next.value);
|
|
389
576
|
}
|
|
390
577
|
const bytes = new Uint8Array(size); let offset = 0;
|
|
391
578
|
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
|
392
|
-
|
|
393
|
-
catch { return fail(); }
|
|
579
|
+
return bytes;
|
|
394
580
|
} finally { if (!done) void reader.cancel().catch(() => {}); reader.releaseLock(); }
|
|
395
581
|
};
|
|
582
|
+
const readJson = async (response: Response, signal: AbortSignal): Promise<Record<string, unknown>> => {
|
|
583
|
+
if (!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '')) { void response.body?.cancel().catch(() => {}); return fail(); }
|
|
584
|
+
if (!response.body) return fail();
|
|
585
|
+
const bytes = await readBytes(response, signal, maxBytes);
|
|
586
|
+
try { return record(json(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), maxBytes)); }
|
|
587
|
+
catch { return fail(); }
|
|
588
|
+
};
|
|
396
589
|
const command = async (path: string, method: 'GET' | 'POST', external?: AbortSignal, body?: ClientJson, key?: string) => {
|
|
397
590
|
const control = scope(external);
|
|
398
591
|
try { return await readJson(await request(path, method, control.signal, body, key), control.signal); }
|
|
@@ -427,6 +620,77 @@ export function createClient(options: ClientOptions): MayuraClient {
|
|
|
427
620
|
...(item['subjectDigest'] === undefined ? {} : { subjectDigest: item['subjectDigest'] as string }),
|
|
428
621
|
...(item['deadlineAtMs'] === undefined ? {} : { deadlineAtMs: item['deadlineAtMs'] as number }) });
|
|
429
622
|
};
|
|
623
|
+
/**
|
|
624
|
+
* One event-stream connection from `after`. Connecting is bounded by requestTimeoutMs; after that the stream may
|
|
625
|
+
* stay open as long as bytes (events or the server's keep-alive comments) keep arriving within eventIdleTimeoutMs.
|
|
626
|
+
*/
|
|
627
|
+
const connection = async function* (id: string, path: string, after: number, external: AbortSignal | undefined): AsyncGenerator<ClientEvent> {
|
|
628
|
+
let cursor = after;
|
|
629
|
+
const controller = new AbortController(); const abort = (): void => { controller.abort(new ClientError('ABORTED')); };
|
|
630
|
+
external?.addEventListener('abort', abort, { once: true }); if (external?.aborted) abort();
|
|
631
|
+
const expire = (): void => { controller.abort(new ClientError('TIMEOUT')); };
|
|
632
|
+
let timer = setTimeout(expire, timeout);
|
|
633
|
+
const alive = (): void => { clearTimeout(timer); timer = setTimeout(expire, idleTimeout); };
|
|
634
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
635
|
+
try {
|
|
636
|
+
const response = await request(`${path}/events?after=${cursor}`, 'GET', controller.signal);
|
|
637
|
+
if (!/^text\/event-stream(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '')) { void response.body?.cancel().catch(() => {}); fail(); }
|
|
638
|
+
reader = response.body?.getReader(); if (!reader) fail();
|
|
639
|
+
alive();
|
|
640
|
+
const decoder = new TextDecoder('utf-8', { fatal: true }); let pending = '';
|
|
641
|
+
while (true) {
|
|
642
|
+
const next = await race(reader.read(), controller.signal); alive();
|
|
643
|
+
if (!next.done && next.value.byteLength > maxBytes) throw new ClientError('STREAM_LIMIT');
|
|
644
|
+
try { pending += next.done ? decoder.decode() : decoder.decode(next.value, { stream: true }); }
|
|
645
|
+
catch { throw new ClientError('INVALID_STREAM'); }
|
|
646
|
+
// Handle LF/CRLF independently of how UTF-8/network chunks were split.
|
|
647
|
+
while (true) {
|
|
648
|
+
const boundary = /\r?\n\r?\n/.exec(pending); if (!boundary || boundary.index === undefined) break;
|
|
649
|
+
const frame = pending.slice(0, boundary.index); pending = pending.slice(boundary.index + boundary[0].length);
|
|
650
|
+
if (encoder.encode(frame).byteLength > frameBytes) throw new ClientError('STREAM_LIMIT');
|
|
651
|
+
let event = ''; let eventId = ''; const data: string[] = [];
|
|
652
|
+
for (const line of frame.split(/\r?\n/)) {
|
|
653
|
+
if (!line || line.startsWith(':')) continue;
|
|
654
|
+
const colon = line.indexOf(':'); const key = colon < 0 ? line : line.slice(0, colon); const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
|
|
655
|
+
if (key === 'event') event = value; else if (key === 'id') eventId = value; else if (key === 'data') data.push(value);
|
|
656
|
+
}
|
|
657
|
+
if (data.length === 0) continue;
|
|
658
|
+
if (event === 'stream.error') {
|
|
659
|
+
// Only a known server code and short printable message are taken from the error frame.
|
|
660
|
+
let reported: ClientError | null = null;
|
|
661
|
+
try { reported = serverError({ error: JSON.parse(data.join('\n')) }, 0, null); } catch { /* Not a Mayura error frame. */ }
|
|
662
|
+
throw reported && ['OBSERVATION_FAILED', 'RUN_RECORDS_UNAVAILABLE'].includes(reported.code)
|
|
663
|
+
? new ClientError(reported.code, undefined, { message: reported.message, details: reported.details }) : new ClientError('OBSERVATION_FAILED');
|
|
664
|
+
}
|
|
665
|
+
let raw: Record<string, unknown>;
|
|
666
|
+
try { raw = record(json(JSON.parse(data.join('\n')), frameBytes)); } catch { throw new ClientError('INVALID_STREAM'); }
|
|
667
|
+
const sequence = natural(raw['sequence']);
|
|
668
|
+
if (!eventTypes.includes(event) || raw['type'] !== event || raw['runId'] !== id || String(sequence) !== eventId || sequence <= cursor) throw new ClientError('INVALID_STREAM');
|
|
669
|
+
const metadata = record(raw['metadata']);
|
|
670
|
+
if (Object.keys(metadata).length > 64 || Object.values(metadata).some(value => !['string', 'number', 'boolean'].includes(typeof value))) throw new ClientError('INVALID_STREAM');
|
|
671
|
+
if (event === 'hook.started' || event === 'hook.completed') hookMetadata(metadata, event === 'hook.completed');
|
|
672
|
+
if (event === 'output.delta' || event === 'output.withheld') outputMetadata(metadata, event === 'output.delta');
|
|
673
|
+
if (event === 'events.gap') {
|
|
674
|
+
if (metadata['from'] !== cursor + 1 || metadata['to'] !== sequence
|
|
675
|
+
|| !Number.isSafeInteger(metadata['from']) || !Number.isSafeInteger(metadata['to']) || (metadata['to'] as number) < (metadata['from'] as number)) throw new ClientError('INVALID_STREAM');
|
|
676
|
+
} else if (sequence !== cursor + 1) throw new ClientError('INVALID_STREAM');
|
|
677
|
+
const timestamp = text(raw['timestamp'], 64); if (!Number.isFinite(Date.parse(timestamp))) throw new ClientError('INVALID_STREAM');
|
|
678
|
+
cursor = sequence;
|
|
679
|
+
yield Object.freeze({ runId: id, sequence, timestamp, type: event as ClientEvent['type'], metadata: Object.freeze(metadata) as ClientEvent['metadata'] });
|
|
680
|
+
}
|
|
681
|
+
if (encoder.encode(pending).byteLength > frameBytes) throw new ClientError('STREAM_LIMIT');
|
|
682
|
+
if (next.done) { if (pending.trim()) throw new ClientError('TRUNCATED_STREAM'); break; }
|
|
683
|
+
}
|
|
684
|
+
} finally {
|
|
685
|
+
clearTimeout(timer); external?.removeEventListener('abort', abort); controller.abort();
|
|
686
|
+
if (reader) { void reader.cancel().catch(() => {}); reader.releaseLock(); }
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
const pause = (ms: number, signal: AbortSignal | undefined): Promise<void> => new Promise<void>((resolve, reject) => {
|
|
690
|
+
const done = (): void => { clearTimeout(timer); signal?.removeEventListener('abort', cancelled); resolve(); };
|
|
691
|
+
const cancelled = (): void => { clearTimeout(timer); reject(new ClientError('ABORTED')); };
|
|
692
|
+
const timer = setTimeout(done, ms); signal?.addEventListener('abort', cancelled, { once: true }); if (signal?.aborted) cancelled();
|
|
693
|
+
});
|
|
430
694
|
const run = (id: string): RemoteRun => {
|
|
431
695
|
runId(id); const path = `/v1/runs/${id}`;
|
|
432
696
|
return Object.freeze({
|
|
@@ -437,7 +701,7 @@ export function createClient(options: ClientOptions): MayuraClient {
|
|
|
437
701
|
if (state.status === 'running') return undefined;
|
|
438
702
|
const outcome = record(raw['outcome']); if (outcome['status'] !== state.status) return fail();
|
|
439
703
|
if (outcome['status'] !== 'succeeded') return Object.freeze({ status: state.status as Exclude<RemoteStatus, 'running' | 'succeeded'>, error: Object.freeze({ code: text(record(outcome['error'])['code'], 128) }), evidence: state.evidence });
|
|
440
|
-
let
|
|
704
|
+
let validationStopped: ClientError | undefined;
|
|
441
705
|
try {
|
|
442
706
|
if (schema['~standard'].version !== 1) throw new Error();
|
|
443
707
|
const control = scope(settings?.signal);
|
|
@@ -445,73 +709,79 @@ export function createClient(options: ClientOptions): MayuraClient {
|
|
|
445
709
|
const validated = await race(Promise.resolve(schema['~standard'].validate(outcome['output'])), control.signal);
|
|
446
710
|
if (validated.issues) throw new Error();
|
|
447
711
|
return Object.freeze({ status: 'succeeded' as const, output: json(validated.value, maxBytes) as T, evidence: state.evidence });
|
|
448
|
-
} catch (error) {
|
|
712
|
+
} catch (error) { if (control.signal.aborted) validationStopped = stopped(control.signal); throw error; }
|
|
449
713
|
finally { control.close(); }
|
|
450
|
-
} catch { throw new ClientError(
|
|
714
|
+
} catch { throw validationStopped ?? new ClientError('INVALID_OUTPUT'); }
|
|
451
715
|
},
|
|
452
716
|
async cancel(settings?: { readonly signal?: AbortSignal }) {
|
|
453
717
|
const value = await command(`${path}/cancel`, 'POST', settings?.signal);
|
|
454
718
|
if (value['id'] !== id || value['cancellationRequested'] !== true) fail();
|
|
455
719
|
},
|
|
456
|
-
async *events(settings?:
|
|
457
|
-
let cursor = natural(settings?.after ?? 0); const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
const
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
// Handle LF/CRLF independently of how UTF-8/network chunks were split.
|
|
470
|
-
while (true) {
|
|
471
|
-
const boundary = /\r?\n\r?\n/.exec(pending); if (!boundary || boundary.index === undefined) break;
|
|
472
|
-
const frame = pending.slice(0, boundary.index); pending = pending.slice(boundary.index + boundary[0].length);
|
|
473
|
-
if (encoder.encode(frame).byteLength > frameBytes) throw new ClientError('STREAM_LIMIT');
|
|
474
|
-
let event = ''; let eventId = ''; const data: string[] = [];
|
|
475
|
-
for (const line of frame.split(/\r?\n/)) {
|
|
476
|
-
if (!line || line.startsWith(':')) continue;
|
|
477
|
-
const colon = line.indexOf(':'); const key = colon < 0 ? line : line.slice(0, colon); const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
|
|
478
|
-
if (key === 'event') event = value; else if (key === 'id') eventId = value; else if (key === 'data') data.push(value);
|
|
479
|
-
}
|
|
480
|
-
if (data.length === 0) continue;
|
|
481
|
-
if (event === 'stream.error') throw new ClientError('OBSERVATION_FAILED');
|
|
482
|
-
let raw: Record<string, unknown>;
|
|
483
|
-
try { raw = record(json(JSON.parse(data.join('\n')), frameBytes)); } catch { throw new ClientError('INVALID_STREAM'); }
|
|
484
|
-
const sequence = natural(raw['sequence']);
|
|
485
|
-
if (!eventTypes.includes(event) || raw['type'] !== event || raw['runId'] !== id || String(sequence) !== eventId || sequence <= cursor) throw new ClientError('INVALID_STREAM');
|
|
486
|
-
const metadata = record(raw['metadata']);
|
|
487
|
-
if (Object.keys(metadata).length > 64 || Object.values(metadata).some(value => !['string', 'number', 'boolean'].includes(typeof value))) throw new ClientError('INVALID_STREAM');
|
|
488
|
-
if (event === 'hook.started' || event === 'hook.completed') hookMetadata(metadata, event === 'hook.completed');
|
|
489
|
-
if (event === 'output.delta' || event === 'output.withheld') outputMetadata(metadata, event === 'output.delta');
|
|
490
|
-
if (event === 'events.gap') {
|
|
491
|
-
if (metadata['from'] !== cursor + 1 || metadata['to'] !== sequence
|
|
492
|
-
|| !Number.isSafeInteger(metadata['from']) || !Number.isSafeInteger(metadata['to']) || (metadata['to'] as number) < (metadata['from'] as number)) throw new ClientError('INVALID_STREAM');
|
|
493
|
-
} else if (sequence !== cursor + 1) throw new ClientError('INVALID_STREAM');
|
|
494
|
-
const timestamp = text(raw['timestamp'], 64); if (!Number.isFinite(Date.parse(timestamp))) throw new ClientError('INVALID_STREAM');
|
|
495
|
-
cursor = sequence;
|
|
496
|
-
yield Object.freeze({ runId: id, sequence, timestamp, type: event as ClientEvent['type'], metadata: Object.freeze(metadata) as ClientEvent['metadata'] });
|
|
720
|
+
async *events(settings?: EventOptions): AsyncIterable<ClientEvent> {
|
|
721
|
+
let cursor = natural(settings?.after ?? 0); const external = settings?.signal; const reconnect = settings?.reconnect !== false;
|
|
722
|
+
if (settings?.onReconnect !== undefined && typeof settings.onReconnect !== 'function') throw new ClientError('INVALID_REQUEST');
|
|
723
|
+
// `failures` counts consecutive failed connections (bounded by maxReconnectAttempts); `quiet` counts streams that
|
|
724
|
+
// ended quickly without events while the run was still running, which only slows reconnection down.
|
|
725
|
+
let failures = 0; let quiet = 0;
|
|
726
|
+
for (;;) {
|
|
727
|
+
const opened = Date.now(); let progressed = false; let failure: ClientError | undefined;
|
|
728
|
+
try {
|
|
729
|
+
for await (const item of connection(id, path, cursor, external)) {
|
|
730
|
+
cursor = item.sequence; progressed = true; failures = 0; quiet = 0;
|
|
731
|
+
yield item;
|
|
732
|
+
if (item.type === 'run.completed') return;
|
|
497
733
|
}
|
|
498
|
-
|
|
499
|
-
|
|
734
|
+
} catch (error) {
|
|
735
|
+
failure = error instanceof ClientError ? error : new ClientError('TRANSPORT_FAILED');
|
|
736
|
+
if (!reconnect || failure.code === 'ABORTED' || !retryableStream(failure)) throw failure;
|
|
500
737
|
}
|
|
501
|
-
|
|
738
|
+
if (!reconnect) return;
|
|
739
|
+
if (external?.aborted) throw new ClientError('ABORTED');
|
|
740
|
+
let delayMs = 0;
|
|
741
|
+
if (failure) {
|
|
742
|
+
failures += 1; if (failures > maxAttempts) throw failure;
|
|
743
|
+
delayMs = Math.max(failure.retryAfterMs ?? 0, Math.min(10_000, reconnectDelay * 2 ** (failures - 1)) * (0.8 + Math.random() * 0.4));
|
|
744
|
+
} else if (!progressed) {
|
|
745
|
+
// The server closed a stream that carried nothing: the run may already be over. If so, drain what is left once.
|
|
746
|
+
if ((await run(id).inspect({ ...(external ? { signal: external } : {}) })).status !== 'running') {
|
|
747
|
+
for await (const item of connection(id, path, cursor, external)) { cursor = item.sequence; yield item; if (item.type === 'run.completed') return; }
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
// A quiet run's streams end after streamDurationMs and resume at once; streams that end quickly back off.
|
|
751
|
+
if (Date.now() - opened < 1_000) { quiet += 1; delayMs = Math.min(10_000, reconnectDelay * 2 ** (quiet - 1)); } else quiet = 0;
|
|
752
|
+
}
|
|
753
|
+
delayMs = Math.round(delayMs);
|
|
754
|
+
try { settings?.onReconnect?.(Object.freeze({ attempt: failures, after: cursor, delayMs, code: failure?.code ?? null })); } catch { /* UI callbacks cannot break the stream. */ }
|
|
755
|
+
if (delayMs > 0) await pause(delayMs, external);
|
|
756
|
+
}
|
|
502
757
|
},
|
|
503
758
|
});
|
|
504
759
|
};
|
|
505
760
|
return Object.freeze({
|
|
506
761
|
run,
|
|
762
|
+
async session(settings?: { readonly signal?: AbortSignal }) {
|
|
763
|
+
const raw = await command('/v1/session', 'GET', settings?.signal); if (Object.keys(raw).length !== 1) return fail();
|
|
764
|
+
const item = record(raw['session']); const scope = record(item['scope']);
|
|
765
|
+
const pattern = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
766
|
+
if (Object.keys(item).length !== 5 || Object.keys(scope).length !== 2 || typeof scope['principalId'] !== 'string' || !pattern.test(scope['principalId'])
|
|
767
|
+
|| typeof scope['projectId'] !== 'string' || !pattern.test(scope['projectId']) || !Array.isArray(item['agentIds']) || item['agentIds'].length > 256
|
|
768
|
+
|| item['agentIds'].some(value => typeof value !== 'string' || !pattern.test(value)) || !Array.isArray(item['capabilities'])
|
|
769
|
+
|| item['capabilities'].some(value => typeof value !== 'string' || !capabilityNames.includes(value)) || !Array.isArray(item['features'])
|
|
770
|
+
|| item['features'].some(value => typeof value !== 'string' || !featureNames.includes(value))) return fail();
|
|
771
|
+
return Object.freeze({ scope: Object.freeze({ principalId: scope['principalId'], projectId: scope['projectId'] }),
|
|
772
|
+
agentIds: Object.freeze([...item['agentIds']] as string[]), capabilities: Object.freeze([...item['capabilities']] as RemoteSession['capabilities'][number][]),
|
|
773
|
+
expiresAtMs: natural(item['expiresAtMs']), features: Object.freeze([...item['features']] as RemoteFeature[]) });
|
|
774
|
+
},
|
|
507
775
|
async agents(settings?: { readonly signal?: AbortSignal }) {
|
|
508
776
|
const raw = await command('/v1/agents', 'GET', settings?.signal);
|
|
509
777
|
if (!Array.isArray(raw['agents']) || raw['agents'].length > 256) return fail();
|
|
510
778
|
return Object.freeze(raw['agents'].map(value => { const item = record(value); return Object.freeze({ id: text(item['id']), version: text(item['version']) }); }));
|
|
511
779
|
},
|
|
512
|
-
async submit(agentId: string, input: unknown, settings: { readonly idempotencyKey: string; readonly signal?: AbortSignal }) {
|
|
780
|
+
async submit(agentId: string, input: unknown, settings: { readonly idempotencyKey: string; readonly signal?: AbortSignal; readonly media?: readonly ClientMedia[] }) {
|
|
513
781
|
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(settings.idempotencyKey)) throw new ClientError('INVALID_IDEMPOTENCY_KEY');
|
|
514
|
-
const
|
|
782
|
+
const media = settings.media === undefined || settings.media.length === 0 ? undefined : mediaBody(settings.media, maxMediaBytes);
|
|
783
|
+
const payload = media ? json({ agentId, input, media: media.body }, maxBytes + media.bytes) : json({ agentId, input }, maxBytes);
|
|
784
|
+
const raw = await command('/v1/runs', 'POST', settings.signal, payload, settings.idempotencyKey);
|
|
515
785
|
if (raw['profile'] !== 'ephemeral') return fail(); return run(runId(raw['id']));
|
|
516
786
|
},
|
|
517
787
|
async humanRequests(settings?: { readonly after?: string; readonly limit?: number; readonly signal?: AbortSignal }) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ClientError, type ClientJson, type MayuraClient } from './index.js';
|
|
2
2
|
|
|
3
3
|
export type WorkflowViewFormat = 2 | 3 | 4 | 5;
|
|
4
|
-
export type WorkflowViewNodeKind = 'tool' | 'join' | 'wait' | 'child' | 'human' | 'timer';
|
|
4
|
+
export type WorkflowViewNodeKind = 'tool' | 'join' | 'wait' | 'child' | 'human' | 'timer' | 'signal';
|
|
5
5
|
export type WorkflowViewRunStatus = 'running' | 'waiting' | 'paused' | 'succeeded' | 'failed' | 'blocked' | 'cancelled' | 'outcome_unknown';
|
|
6
6
|
export type WorkflowViewStepStatus = 'pending' | 'waiting' | 'approved' | 'dispatching' | 'succeeded' | 'failed' | 'blocked' | 'unknown' | 'skipped' | 'timed_out';
|
|
7
7
|
export interface WorkflowViewNode { readonly id: string; readonly kind: WorkflowViewNodeKind; readonly dependsOn: readonly string[] }
|
|
@@ -80,7 +80,7 @@ const terminal = new Set<WorkflowViewStepStatus>(['succeeded', 'failed', 'blocke
|
|
|
80
80
|
const failed = new Set<WorkflowViewStepStatus>(['failed', 'blocked', 'unknown', 'timed_out']);
|
|
81
81
|
const kinds: Readonly<Record<WorkflowViewFormat, ReadonlySet<WorkflowViewNodeKind>>> = Object.freeze({
|
|
82
82
|
2: new Set<WorkflowViewNodeKind>(['tool', 'join']), 3: new Set<WorkflowViewNodeKind>(['tool', 'join', 'wait']),
|
|
83
|
-
4: new Set<WorkflowViewNodeKind>(['tool', 'join', 'child']), 5: new Set<WorkflowViewNodeKind>(['tool', 'join', 'human', 'timer']),
|
|
83
|
+
4: new Set<WorkflowViewNodeKind>(['tool', 'join', 'child']), 5: new Set<WorkflowViewNodeKind>(['tool', 'join', 'human', 'timer', 'signal']),
|
|
84
84
|
});
|
|
85
85
|
function invalid(): never { throw new ClientError('INVALID_WORKFLOW_VIEW'); }
|
|
86
86
|
function fields(value: object, names: readonly string[]): Record<string, PropertyDescriptor> {
|
|
@@ -123,8 +123,8 @@ export function createWorkflowGraphProjection(input: WorkflowViewInput): Workflo
|
|
|
123
123
|
const hasChildRunId = descriptors['childRunId'] !== undefined; const childRunId = descriptors['childRunId']?.value as string | undefined; const node = nodes.get(id);
|
|
124
124
|
const approval = descriptors['approval']?.value as WorkflowViewApproval | undefined;
|
|
125
125
|
if (!node || steps.has(id) || kind !== node.kind || typeof stepStatus !== 'string' || !stepStatuses.has(stepStatus)
|
|
126
|
-
|| (kind === 'human' && !humanStatuses.has(stepStatus)) || (kind === 'timer' && !timerStatuses.has(stepStatus))
|
|
127
|
-
|| (stepStatus === 'timed_out' && kind !== 'human')
|
|
126
|
+
|| ((kind === 'human' || kind === 'signal') && !humanStatuses.has(stepStatus)) || (kind === 'timer' && !timerStatuses.has(stepStatus))
|
|
127
|
+
|| (stepStatus === 'timed_out' && kind !== 'human' && kind !== 'signal')
|
|
128
128
|
|| (hasChildRunId && (kind !== 'child' || typeof childRunId !== 'string' || !digest.test(childRunId)))
|
|
129
129
|
|| (descriptors['approval'] !== undefined && (kind !== 'tool' || stepStatus !== 'waiting' || !pendingApproval(approval)))) return invalid();
|
|
130
130
|
steps.set(id, { id, kind, status: stepStatus, childRunId: childRunId ?? null, approval: approval ?? null });
|
|
@@ -161,9 +161,9 @@ const commandId = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
|
161
161
|
const signalIdentifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
162
162
|
const encoder = new TextEncoder();
|
|
163
163
|
function workflowCommandState(state: WorkflowCommandState): WorkflowCommandState { return Object.freeze({ ...state }); }
|
|
164
|
+
/** Client errors keep their code (the server's own, when it sent one); anything else becomes WORKFLOW_COMMAND_FAILED. */
|
|
164
165
|
function safeWorkflowCommandError(error: unknown): ClientError {
|
|
165
|
-
|
|
166
|
-
return error instanceof ClientError && allowed.has(error.code) ? error : new ClientError('WORKFLOW_COMMAND_FAILED');
|
|
166
|
+
return error instanceof ClientError && /^[A-Z][A-Z0-9_]{1,63}$/.test(error.code) ? error : new ClientError('WORKFLOW_COMMAND_FAILED');
|
|
167
167
|
}
|
|
168
168
|
function approvalIntent(value: unknown, projection: WorkflowGraphProjection): WorkflowApprovalIntent {
|
|
169
169
|
if (!value || typeof value !== 'object' || Array.isArray(value) || ![null, Object.prototype].includes(Object.getPrototypeOf(value)))
|
|
@@ -253,7 +253,8 @@ export function createWorkflowCommandController(options: WorkflowCommandControll
|
|
|
253
253
|
} catch (error) {
|
|
254
254
|
const safe = safeWorkflowCommandError(error);
|
|
255
255
|
if (!disposed) {
|
|
256
|
-
|
|
256
|
+
// Any 409 (WORKFLOW_CONFLICT, MIGRATION_REFUSED, ...) means the run moved on: read it again. The thrown error keeps the server's code.
|
|
257
|
+
const conflict = safe.status === 409 || safe.status === 412;
|
|
257
258
|
publish({ status: conflict ? 'conflict' : 'failed', errorCode: conflict ? 'WORKFLOW_COMMAND_CONFLICT' : safe.code });
|
|
258
259
|
}
|
|
259
260
|
throw safe;
|