@warlock.js/ai 5.0.2 → 5.2.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/CHANGELOG.md +200 -179
- package/README.md +4 -0
- package/cjs/index.cjs +1 -1
- package/cjs/index.cjs.map +1 -1
- package/cjs/{magic-string.es-BoSa5xIt.cjs → magic-string.es-BQeqHJ-a.cjs} +22 -17
- package/cjs/magic-string.es-BQeqHJ-a.cjs.map +1 -0
- package/cjs/matcher-logic-07fFOz7r.cjs.map +1 -1
- package/cjs/{matchers-DnV47KR_.cjs → matchers-CINm4ojZ.cjs} +27 -27
- package/cjs/matchers-CINm4ojZ.cjs.map +1 -0
- package/esm/agent/agent-input-builder.mjs.map +1 -1
- package/esm/agent/agent-stream.d.mts.map +1 -1
- package/esm/agent/agent-stream.mjs.map +1 -1
- package/esm/agent/agent.d.mts.map +1 -1
- package/esm/agent/agent.mjs.map +1 -1
- package/esm/agent/json-stream-guard.mjs.map +1 -1
- package/esm/agent/signature.mjs.map +1 -1
- package/esm/agent/snapshot.mjs.map +1 -1
- package/esm/agent/spawn-sub-agent.d.mts.map +1 -1
- package/esm/batch/batch.d.mts.map +1 -1
- package/esm/batch/batch.mjs.map +1 -1
- package/esm/checkpoint/memory.d.mts.map +1 -1
- package/esm/checkpoint/pg.mjs.map +1 -1
- package/esm/checkpoint/redis.mjs.map +1 -1
- package/esm/config.d.mts.map +1 -1
- package/esm/eval/dataset.d.mts.map +1 -1
- package/esm/eval/dataset.mjs.map +1 -1
- package/esm/eval/eval-runner.d.mts.map +1 -1
- package/esm/eval/eval-runner.mjs.map +1 -1
- package/esm/eval/judge-scorer.d.mts.map +1 -1
- package/esm/eval/regression.d.mts.map +1 -1
- package/esm/eval/regression.mjs.map +1 -1
- package/esm/eval/report-json.d.mts.map +1 -1
- package/esm/eval/report-junit.mjs.map +1 -1
- package/esm/eval/scorers.d.mts.map +1 -1
- package/esm/eval/scorers.mjs.map +1 -1
- package/esm/guard/detectors/injection.mjs.map +1 -1
- package/esm/guard/detectors/moderation.mjs.map +1 -1
- package/esm/guard/detectors/pii.mjs.map +1 -1
- package/esm/guard/detectors/topic.mjs.map +1 -1
- package/esm/human/human-approval.mjs.map +1 -1
- package/esm/human/resume.d.mts.map +1 -1
- package/esm/human/stores/memory.d.mts.map +1 -1
- package/esm/human/stores/pg.mjs.map +1 -1
- package/esm/human/stores/redis.mjs.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/memory/derive-id.mjs.map +1 -1
- package/esm/memory/episodic-memory.mjs.map +1 -1
- package/esm/memory/memory.mjs.map +1 -1
- package/esm/memory/procedural-memory.mjs.map +1 -1
- package/esm/memory/semantic-memory.mjs.map +1 -1
- package/esm/memory/working-memory.mjs.map +1 -1
- package/esm/middleware/builtins/budget.mjs.map +1 -1
- package/esm/middleware/builtins/semantic-cache.mjs.map +1 -1
- package/esm/middleware/helpers/compose.d.mts.map +1 -1
- package/esm/middleware/helpers/for-tool.mjs.map +1 -1
- package/esm/middleware/pipeline.d.mts.map +1 -1
- package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
- package/esm/middleware/utils/namespaced-state.d.mts.map +1 -1
- package/esm/mock/mock-agent.d.mts.map +1 -1
- package/esm/mock/mock-agent.mjs.map +1 -1
- package/esm/mock/mock-model.d.mts.map +1 -1
- package/esm/mock/mock-model.mjs.map +1 -1
- package/esm/mock/mock-router.d.mts.map +1 -1
- package/esm/model/fallback-model.mjs.map +1 -1
- package/esm/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.6.0/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.mjs +19 -14
- package/esm/node_modules/.pnpm/@jridgewell_sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_expect@4.1.10/node_modules/@vitest}/expect/dist/index.mjs +8 -8
- package/esm/node_modules/.pnpm/@vitest_expect@4.1.10/node_modules/@vitest/expect/dist/index.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.1.10/node_modules/@vitest}/pretty-format/dist/index.mjs +4 -4
- package/esm/node_modules/.pnpm/@vitest_pretty-format@4.1.10/node_modules/@vitest/pretty-format/dist/index.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/chunk-artifact.mjs +5 -5
- package/esm/node_modules/.pnpm/@vitest_runner@4.1.10/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.1.10/node_modules/@vitest}/snapshot/dist/index.mjs +7 -7
- package/esm/node_modules/.pnpm/@vitest_snapshot@4.1.10/node_modules/@vitest/snapshot/dist/index.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_spy@4.1.10/node_modules/@vitest}/spy/dist/index.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_spy@4.1.10/node_modules/@vitest/spy/dist/index.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/diff.mjs +4 -4
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/diff.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/display.mjs +3 -3
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/display.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/error.mjs +2 -2
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/error.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/helpers.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/helpers.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/offset.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/offset.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/serialize.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/serialize.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/source-map.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/source-map.mjs.map +1 -0
- package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/timers.mjs +1 -1
- package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/timers.mjs.map +1 -0
- package/esm/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.mjs +1 -1
- package/esm/node_modules/.pnpm/chai@6.2.2/node_modules/chai/index.mjs.map +1 -0
- package/esm/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.mjs +3 -3
- package/esm/node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs.map +1 -0
- package/esm/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.1.1/node_modules/tinyrainbow}/dist/index.mjs +1 -1
- package/esm/node_modules/.pnpm/tinyrainbow@3.1.1/node_modules/tinyrainbow/dist/index.mjs.map +1 -0
- package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs +1 -1
- package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +1 -0
- package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/rpc.MzXet3jl.mjs +1 -1
- package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +1 -0
- package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/test.DNmyFkvJ.mjs +11 -11
- package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +1 -0
- package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/utils.BX5Fg8C4.mjs +2 -2
- package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +1 -0
- package/esm/object-stream/parse-partial-json.mjs.map +1 -1
- package/esm/object-stream/stream-object.d.mts.map +1 -1
- package/esm/object-stream/stream-object.mjs.map +1 -1
- package/esm/observe/observer-registry.d.mts.map +1 -1
- package/esm/orchestrator/as-tool.d.mts.map +1 -1
- package/esm/orchestrator/checkpoint.mjs.map +1 -1
- package/esm/orchestrator/compaction.mjs.map +1 -1
- package/esm/orchestrator/emitter.d.mts.map +1 -1
- package/esm/orchestrator/emitter.mjs.map +1 -1
- package/esm/orchestrator/execution.d.mts.map +1 -1
- package/esm/orchestrator/execution.mjs.map +1 -1
- package/esm/orchestrator/memory.mjs.map +1 -1
- package/esm/orchestrator/orchestrator-stream.d.mts.map +1 -1
- package/esm/orchestrator/orchestrator-stream.mjs.map +1 -1
- package/esm/orchestrator/orchestrator.d.mts.map +1 -1
- package/esm/orchestrator/orchestrator.mjs.map +1 -1
- package/esm/orchestrator/session-lock.d.mts.map +1 -1
- package/esm/orchestrator/signature.mjs.map +1 -1
- package/esm/planner/dag-scheduler.mjs.map +1 -1
- package/esm/planner/plan-prompt.mjs.map +1 -1
- package/esm/planner/planner-run.mjs.map +1 -1
- package/esm/planner/planner.d.mts.map +1 -1
- package/esm/planner/planner.mjs.map +1 -1
- package/esm/planner/signature.mjs.map +1 -1
- package/esm/planner/snapshot.mjs.map +1 -1
- package/esm/prompt/prompt-langfuse-sync.mjs.map +1 -1
- package/esm/prompt/prompt-validate.mjs.map +1 -1
- package/esm/prompt/prompt.mjs.map +1 -1
- package/esm/prompts/prompts-manager.d.mts.map +1 -1
- package/esm/prompts/prompts-manager.mjs.map +1 -1
- package/esm/prompts/prompts-validate.mjs.map +1 -1
- package/esm/rag/chunk/chunk.mjs.map +1 -1
- package/esm/rag/chunk/markdown.mjs.map +1 -1
- package/esm/rag/chunk/sentence.mjs.map +1 -1
- package/esm/rag/hybrid/bm25.mjs.map +1 -1
- package/esm/rag/hybrid/hybrid-rank.mjs.map +1 -1
- package/esm/rag/hybrid/rrf.mjs.map +1 -1
- package/esm/rag/loaders/load-html.mjs.map +1 -1
- package/esm/rag/loaders/load-pdf.d.mts.map +1 -1
- package/esm/rag/loaders/load-pdf.mjs.map +1 -1
- package/esm/rag/loaders/load-text.mjs.map +1 -1
- package/esm/rag/rerank/keyword-reranker.mjs.map +1 -1
- package/esm/rag/rerank/llm-reranker.mjs.map +1 -1
- package/esm/rag/retrieve.mjs.map +1 -1
- package/esm/rag/store/cache-vector-store.mjs.map +1 -1
- package/esm/rag/store/pg-vector-store.mjs.map +1 -1
- package/esm/rag/transforms/multi-query.mjs.map +1 -1
- package/esm/security/outbound-policy.mjs.map +1 -1
- package/esm/security/private-ip.mjs.map +1 -1
- package/esm/security/redact.d.mts.map +1 -1
- package/esm/security/redact.mjs.map +1 -1
- package/esm/serve/serve.d.mts.map +1 -1
- package/esm/serve/serve.mjs.map +1 -1
- package/esm/serve/stream-to-sse.d.mts.map +1 -1
- package/esm/skills/catalog.mjs.map +1 -1
- package/esm/skills/skills.mjs.map +1 -1
- package/esm/skills/sources/directory-source.mjs.map +1 -1
- package/esm/skills/sources/parse-frontmatter.mjs.map +1 -1
- package/esm/skills/sources/url-source.mjs.map +1 -1
- package/esm/skills/store/mock-skills-store.mjs.map +1 -1
- package/esm/skills/store/procedural-skill-store.mjs.map +1 -1
- package/esm/snapshot/memory.d.mts.map +1 -1
- package/esm/snapshot/pg.mjs.map +1 -1
- package/esm/speech/speech.mjs.map +1 -1
- package/esm/supervisor/as-tool.d.mts.map +1 -1
- package/esm/supervisor/cancellation.mjs.map +1 -1
- package/esm/supervisor/emitter.d.mts.map +1 -1
- package/esm/supervisor/emitter.mjs.map +1 -1
- package/esm/supervisor/entries.mjs.map +1 -1
- package/esm/supervisor/execution.d.mts.map +1 -1
- package/esm/supervisor/execution.mjs.map +1 -1
- package/esm/supervisor/fan-out.mjs.map +1 -1
- package/esm/supervisor/router-factory.mjs.map +1 -1
- package/esm/supervisor/router-prompt.mjs.map +1 -1
- package/esm/supervisor/signature.mjs.map +1 -1
- package/esm/supervisor/snapshot.mjs.map +1 -1
- package/esm/supervisor/supervisor-stream.d.mts.map +1 -1
- package/esm/supervisor/supervisor-stream.mjs.map +1 -1
- package/esm/supervisor/supervisor.d.mts.map +1 -1
- package/esm/supervisor/supervisor.mjs.map +1 -1
- package/esm/system-prompt/refined-system-prompt.d.mts.map +1 -1
- package/esm/system-prompt/refined-system-prompt.mjs.map +1 -1
- package/esm/system-prompt/system-prompt.d.mts.map +1 -1
- package/esm/system-prompt/system-prompt.mjs.map +1 -1
- package/esm/team/team.d.mts.map +1 -1
- package/esm/testing/matcher-logic.mjs.map +1 -1
- package/esm/testing/matchers.mjs +1 -1
- package/esm/testing/register-lazy.d.mts.map +1 -1
- package/esm/tool/executable-as-tool.d.mts.map +1 -1
- package/esm/tool/tool.d.mts.map +1 -1
- package/esm/tool/tool.mjs.map +1 -1
- package/esm/transcribe/audio-input.mjs.map +1 -1
- package/esm/transcribe/transcribe.mjs.map +1 -1
- package/esm/utils/extract-json-payload.mjs.map +1 -1
- package/esm/utils/generate-run-id.mjs.map +1 -1
- package/esm/utils/prepare-attachment-part.mjs.map +1 -1
- package/esm/utils/run-context.d.mts.map +1 -1
- package/esm/utils/safe-json-parse.d.mts.map +1 -1
- package/esm/vcr/cassette-io.mjs.map +1 -1
- package/esm/vcr/hash-request.mjs.map +1 -1
- package/esm/vcr/vcr.mjs.map +1 -1
- package/esm/workflow/cancellation.mjs.map +1 -1
- package/esm/workflow/emitter.mjs.map +1 -1
- package/esm/workflow/engine.mjs.map +1 -1
- package/esm/workflow/retry.mjs.map +1 -1
- package/esm/workflow/router.mjs.map +1 -1
- package/esm/workflow/signature.d.mts.map +1 -1
- package/esm/workflow/signature.mjs.map +1 -1
- package/esm/workflow/snapshot.mjs.map +1 -1
- package/esm/workflow/step-runner.mjs.map +1 -1
- package/esm/workflow/step.d.mts.map +1 -1
- package/esm/workflow/step.mjs.map +1 -1
- package/esm/workflow/workflow.d.mts.map +1 -1
- package/esm/workflow/workflow.mjs.map +1 -1
- package/llms-full.txt +2 -0
- package/package.json +7 -4
- package/skills/ai-basics/SKILL.md +2 -0
- package/cjs/magic-string.es-BoSa5xIt.cjs.map +0 -1
- package/cjs/matchers-DnV47KR_.cjs.map +0 -1
- package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +0 -1
- package/esm/node_modules/@vitest/expect/dist/index.mjs.map +0 -1
- package/esm/node_modules/@vitest/pretty-format/dist/index.mjs.map +0 -1
- package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +0 -1
- package/esm/node_modules/@vitest/snapshot/dist/index.mjs.map +0 -1
- package/esm/node_modules/@vitest/spy/dist/index.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/diff.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/display.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/error.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/helpers.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/offset.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/serialize.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/source-map.mjs.map +0 -1
- package/esm/node_modules/@vitest/utils/dist/timers.mjs.map +0 -1
- package/esm/node_modules/chai/index.mjs.map +0 -1
- package/esm/node_modules/magic-string/dist/magic-string.es.mjs.map +0 -1
- package/esm/node_modules/tinyrainbow/dist/index.mjs.map +0 -1
- package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +0 -1
- package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +0 -1
- package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +0 -1
- package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +0 -1
- /package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/index.mjs +0 -0
- /package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/utils.mjs +0 -0
package/esm/vcr/vcr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vcr.mjs","names":[],"sources":["../../../../../../../ai/src/vcr/vcr.ts"],"sourcesContent":["import type { Message } from \"../contracts/conversation-message.type\";\nimport type {\n ModelCallOptions,\n ModelCapabilities,\n ModelContract,\n ModelResponse,\n ModelStreamChunk,\n} from \"../contracts/model.contract\";\nimport type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport { redact } from \"../security/redact\";\nimport { emptyCassette, loadCassette, saveCassette } from \"./cassette-io\";\nimport { VcrCassetteMissError } from \"./errors\";\nimport { DEFAULT_HASH_OPTIONS, hashRequest } from \"./hash-request\";\nimport type { Cassette, CassetteEntry, VcrMode, VcrModel, VcrOptions } from \"./vcr.type\";\n\n/**\n * Internal decorator that wraps an inner `ModelContract`, intercepting only\n * `complete()`/`stream()` and delegating every identity getter to the inner\n * model. Drives the record/replay state machine over a single in-memory\n * {@link Cassette}.\n *\n * **Why a class.** It holds mutable per-instance state (the loaded cassette,\n * the dirty flag, the load promise) behind a stable `ModelContract` surface;\n * the public API is the `vcr()` factory, never `new`.\n */\nclass Vcr implements VcrModel {\n private readonly mode: VcrMode;\n private readonly path: string;\n private readonly hashOptions: readonly string[];\n\n /** Loaded + newly recorded entries. Mutated in place as we record. */\n private loadedCassette: Cassette;\n\n /** Set when an entry is recorded so `save()` knows there's work to flush. */\n private dirty = false;\n\n /** One-shot lazy load of the on-disk cassette, shared across calls. */\n private loadPromise: Promise<void> | undefined;\n\n /** Persisted-body privacy controls (S2). */\n private readonly recordRequest: NonNullable<VcrOptions[\"recordRequest\"]>;\n private readonly redactRequestHook: VcrOptions[\"redactRequest\"];\n private readonly redactResponseHook: VcrOptions[\"redactResponse\"];\n private readonly redactErrorHook: VcrOptions[\"redactError\"];\n\n /** Verbatim-recording warning fires at most once per instance. */\n private warnedVerbatim = false;\n\n public constructor(\n private readonly inner: ModelContract,\n options: VcrOptions,\n ) {\n this.path = options.path;\n this.mode = options.mode ?? \"auto\";\n this.hashOptions = options.hashOptions ?? DEFAULT_HASH_OPTIONS;\n this.recordRequest = options.recordRequest ?? \"verbatim\";\n this.redactRequestHook = options.redactRequest;\n this.redactResponseHook = options.redactResponse;\n this.redactErrorHook = options.redactError;\n this.loadedCassette = emptyCassette(inner.name, inner.provider);\n }\n\n /** Inner model identifier — delegated verbatim. */\n public get name(): string {\n return this.inner.name;\n }\n\n /** Inner provider — delegated verbatim. */\n public get provider(): string {\n return this.inner.provider;\n }\n\n /** Inner capability flags — delegated verbatim. */\n public get capabilities(): ModelCapabilities | undefined {\n return this.inner.capabilities;\n }\n\n /** Inner pricing — delegated verbatim so cost accounting is unchanged. */\n public get pricing(): ModelPricing | undefined {\n return this.inner.pricing;\n }\n\n /** Loaded/recorded cassette, exposed for assertions. */\n public get cassette(): Cassette {\n return this.loadedCassette;\n }\n\n /**\n * Load the on-disk cassette exactly once. Pure `record` mode skips the\n * read — it always writes fresh — but the in-memory cassette still starts\n * empty so a record run never accidentally replays a stale entry.\n */\n private async ensureLoaded(): Promise<void> {\n if (this.loadPromise) {\n return this.loadPromise;\n }\n\n this.loadPromise =\n this.mode === \"record\"\n ? Promise.resolve()\n : (async () => {\n this.loadedCassette = await loadCassette(\n this.path,\n this.inner.name,\n this.inner.provider,\n );\n })();\n\n return this.loadPromise;\n }\n\n /** Find a recorded entry whose hash matches the current request. */\n private findEntry(hash: string): CassetteEntry | undefined {\n return this.loadedCassette.entries.find((entry) => entry.requestHash === hash);\n }\n\n /** Re-throw a recorded error by reconstructing a plain `Error`. */\n private throwRecordedError(entry: CassetteEntry): never {\n const error = new Error(entry.error?.message ?? \"Recorded error\");\n\n error.name = entry.error?.name ?? \"Error\";\n\n throw error;\n }\n\n /**\n * Non-streaming call. In `replay` a miss throws; in `auto`/`record` a miss\n * calls the inner model and records the outcome (response or error).\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n await this.ensureLoaded();\n\n const hash = hashRequest(messages, options, this.hashOptions);\n\n if (this.mode !== \"record\") {\n const entry = this.findEntry(hash);\n\n if (entry) {\n if (entry.error) {\n this.throwRecordedError(entry);\n }\n\n if (entry.response) {\n return entry.response;\n }\n }\n\n if (this.mode === \"replay\") {\n throw new VcrCassetteMissError(\n `No cassette entry for this request (model \"${this.inner.name}\", hash ${hash}).`,\n { requestHash: hash, path: this.path },\n );\n }\n }\n\n try {\n const response = await this.inner.complete(messages, options);\n\n this.record({ requestHash: hash, request: { messages, options }, response });\n\n return response;\n } catch (error) {\n this.record({\n requestHash: hash,\n request: { messages, options },\n error: { name: (error as Error).name, message: (error as Error).message },\n });\n\n throw error;\n }\n }\n\n /**\n * Streaming call. On replay the stored `chunks` are re-yielded in order\n * (reproducing the `delta`/`tool-call`/`done` sequence) or the stored\n * error is re-thrown. On record the inner stream is buffered into\n * `chunks[]` while being re-emitted, then recorded once exhausted.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n await this.ensureLoaded();\n\n const hash = hashRequest(messages, options, this.hashOptions);\n\n if (this.mode !== \"record\") {\n const entry = this.findEntry(hash);\n\n if (entry) {\n if (entry.error) {\n this.throwRecordedError(entry);\n }\n\n if (entry.chunks) {\n for (const chunk of entry.chunks) {\n yield chunk;\n }\n\n return;\n }\n }\n\n if (this.mode === \"replay\") {\n throw new VcrCassetteMissError(\n `No cassette entry for this request (model \"${this.inner.name}\", hash ${hash}).`,\n { requestHash: hash, path: this.path },\n );\n }\n }\n\n const chunks: ModelStreamChunk[] = [];\n\n try {\n for await (const chunk of this.inner.stream(messages, options)) {\n chunks.push(chunk);\n\n yield chunk;\n }\n } catch (error) {\n this.record({\n requestHash: hash,\n request: { messages, options },\n error: { name: (error as Error).name, message: (error as Error).message },\n });\n\n throw error;\n }\n\n this.record({ requestHash: hash, request: { messages, options }, chunks });\n }\n\n /**\n * Append an entry to the in-memory cassette and mark it dirty, applying\n * the configured request/response/error redaction first (S2). Pure\n * `replay` never reaches this path, so no replay run is ever dirtied.\n */\n private record(entry: CassetteEntry): void {\n this.loadedCassette.entries.push(this.applyRedaction(entry));\n this.dirty = true;\n this.maybeWarnVerbatim();\n }\n\n /**\n * Apply the persisted-body privacy controls to an entry before it is\n * stored. The request body follows `recordRequest`; response/error\n * redactors are applied only when supplied. Replay matching is by the\n * recomputed hash (kept verbatim), so none of this affects replay.\n */\n private applyRedaction(entry: CassetteEntry): CassetteEntry {\n const out: CassetteEntry = {\n requestHash: entry.requestHash,\n request: entry.request,\n };\n\n if (this.recordRequest === \"hash-only\") {\n out.request = { messages: [] };\n } else if (this.recordRequest === \"redacted\") {\n out.request = this.redactRequestHook\n ? this.redactRequestHook(entry.request)\n : redact(entry.request);\n }\n\n if (entry.response) {\n out.response = this.redactResponseHook\n ? this.redactResponseHook(entry.response)\n : entry.response;\n }\n if (entry.chunks) {\n out.chunks = entry.chunks;\n }\n if (entry.error) {\n out.error = this.redactErrorHook\n ? this.redactErrorHook(entry.error)\n : entry.error;\n }\n\n return out;\n }\n\n /**\n * Warn once (outside tests) when the cassette is recording verbatim\n * request bodies — they may carry prompts, tool args, and PII, so the\n * file is not safe to commit until sanitized.\n */\n private maybeWarnVerbatim(): void {\n if (this.warnedVerbatim || this.recordRequest !== \"verbatim\") return;\n if (process.env.VITEST || process.env.NODE_ENV === \"test\") return;\n\n this.warnedVerbatim = true;\n console.warn(\n `[warlock-ai] VCR is recording verbatim request bodies to \"${this.path}\" — prompts, tool args, and any PII are stored unredacted. ` +\n 'Sanitize before committing, or set recordRequest: \"redacted\" | \"hash-only\".',\n );\n }\n\n /**\n * Flush newly recorded entries to `path`. No-op when nothing was recorded\n * (pure replay, or a record/auto run that only ever hit cached entries).\n */\n public async save(): Promise<void> {\n if (!this.dirty) {\n return;\n }\n\n await saveCassette(this.path, this.loadedCassette);\n this.dirty = false;\n }\n}\n\n/**\n * Wrap any `ModelContract` in a record/replay decorator backed by a JSON\n * cassette on disk.\n *\n * **What it does.** Intercepts only `complete()`/`stream()` — the single\n * seam every agent trip funnels through — and delegates `name`, `provider`,\n * `capabilities`, and `pricing` to the inner model untouched. On a call it\n * computes a stable hash over `{ messages, picked options }` and, depending\n * on `mode`:\n *\n * - **`record`** — always calls the inner model and appends a cassette entry.\n * - **`replay`** — returns the matching entry (or re-yields its chunks /\n * re-throws its error); a miss throws `VcrCassetteMissError`, never a live\n * call.\n * - **`auto`** (default) — replays a hit, records a miss.\n *\n * Composes *below* `fallbackModel` and works with any adapter because it\n * depends only on `ModelContract`. Call `save()` to flush new entries.\n *\n * @example\n * const model = vcr(liveModel, { path: \"./cassettes/support.json\" });\n * const response = await model.complete(messages);\n * await model.save(); // first run records; later runs replay deterministically.\n */\nexport function vcr(model: ModelContract, options: VcrOptions): VcrModel {\n return new Vcr(model, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,IAAM,MAAN,MAA8B;CAuB5B,AAAO,YACL,AAAiB,OACjB,SACA;EAFiB;eAfH;wBAYS;EAMvB,KAAK,OAAO,QAAQ;EACpB,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,cAAc,QAAQ,eAAe;EAC1C,KAAK,gBAAgB,QAAQ,iBAAiB;EAC9C,KAAK,oBAAoB,QAAQ;EACjC,KAAK,qBAAqB,QAAQ;EAClC,KAAK,kBAAkB,QAAQ;EAC/B,KAAK,iBAAiB,cAAc,MAAM,MAAM,MAAM,QAAQ;CAChE;;CAGA,IAAW,OAAe;EACxB,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAW,eAA8C;EACvD,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAW,UAAoC;EAC7C,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAW,WAAqB;EAC9B,OAAO,KAAK;CACd;;;;;;CAOA,MAAc,eAA8B;EAC1C,IAAI,KAAK,aACP,OAAO,KAAK;EAGd,KAAK,cACH,KAAK,SAAS,WACV,QAAQ,QAAQ,KACf,YAAY;GACX,KAAK,iBAAiB,MAAM,aAC1B,KAAK,MACL,KAAK,MAAM,MACX,KAAK,M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I,QAAQ,KAAK,kBACb,KAAK,gBAAgB,MAAM,KAAK,IAChC,MAAM;EAGZ,OAAO;CACT;;;;;;CAOA,AAAQ,oBAA0B;EAChC,IAAI,KAAK,kBAAkB,KAAK,kBAAkB,YAAY;EAC9D,IAAI,QAAQ,IAAI,UAAU,QAAQ,IAAI,aAAa,QAAQ;EAE3D,KAAK,iBAAiB;EACtB,QAAQ,KACN,6DAA6D,KAAK,KAAK,uIAEzE;CACF;;;;;CAMA,MAAa,OAAsB;EACjC,IAAI,CAAC,KAAK,OACR;EAGF,MAAM,aAAa,KAAK,MAAM,KAAK,cAAc;EACjD,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,IAAI,OAAsB,SAA+B;CACvE,OAAO,IAAI,IAAI,OAAO,OAAO;AAC/B"}
|
|
1
|
+
{"version":3,"file":"vcr.mjs","names":[],"sources":["../../../../../../../ai/src/vcr/vcr.ts"],"sourcesContent":["import type { Message } from \"../contracts/conversation-message.type\";\nimport type {\n ModelCallOptions,\n ModelCapabilities,\n ModelContract,\n ModelResponse,\n ModelStreamChunk,\n} from \"../contracts/model.contract\";\nimport type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport { redact } from \"../security/redact\";\nimport { emptyCassette, loadCassette, saveCassette } from \"./cassette-io\";\nimport { VcrCassetteMissError } from \"./errors\";\nimport { DEFAULT_HASH_OPTIONS, hashRequest } from \"./hash-request\";\nimport type { Cassette, CassetteEntry, VcrMode, VcrModel, VcrOptions } from \"./vcr.type\";\n\n/**\n * Internal decorator that wraps an inner `ModelContract`, intercepting only\n * `complete()`/`stream()` and delegating every identity getter to the inner\n * model. Drives the record/replay state machine over a single in-memory\n * {@link Cassette}.\n *\n * **Why a class.** It holds mutable per-instance state (the loaded cassette,\n * the dirty flag, the load promise) behind a stable `ModelContract` surface;\n * the public API is the `vcr()` factory, never `new`.\n */\nclass Vcr implements VcrModel {\n private readonly mode: VcrMode;\n private readonly path: string;\n private readonly hashOptions: readonly string[];\n\n /** Loaded + newly recorded entries. Mutated in place as we record. */\n private loadedCassette: Cassette;\n\n /** Set when an entry is recorded so `save()` knows there's work to flush. */\n private dirty = false;\n\n /** One-shot lazy load of the on-disk cassette, shared across calls. */\n private loadPromise: Promise<void> | undefined;\n\n /** Persisted-body privacy controls (S2). */\n private readonly recordRequest: NonNullable<VcrOptions[\"recordRequest\"]>;\n private readonly redactRequestHook: VcrOptions[\"redactRequest\"];\n private readonly redactResponseHook: VcrOptions[\"redactResponse\"];\n private readonly redactErrorHook: VcrOptions[\"redactError\"];\n\n /** Verbatim-recording warning fires at most once per instance. */\n private warnedVerbatim = false;\n\n public constructor(\n private readonly inner: ModelContract,\n options: VcrOptions,\n ) {\n this.path = options.path;\n this.mode = options.mode ?? \"auto\";\n this.hashOptions = options.hashOptions ?? DEFAULT_HASH_OPTIONS;\n this.recordRequest = options.recordRequest ?? \"verbatim\";\n this.redactRequestHook = options.redactRequest;\n this.redactResponseHook = options.redactResponse;\n this.redactErrorHook = options.redactError;\n this.loadedCassette = emptyCassette(inner.name, inner.provider);\n }\n\n /** Inner model identifier — delegated verbatim. */\n public get name(): string {\n return this.inner.name;\n }\n\n /** Inner provider — delegated verbatim. */\n public get provider(): string {\n return this.inner.provider;\n }\n\n /** Inner capability flags — delegated verbatim. */\n public get capabilities(): ModelCapabilities | undefined {\n return this.inner.capabilities;\n }\n\n /** Inner pricing — delegated verbatim so cost accounting is unchanged. */\n public get pricing(): ModelPricing | undefined {\n return this.inner.pricing;\n }\n\n /** Loaded/recorded cassette, exposed for assertions. */\n public get cassette(): Cassette {\n return this.loadedCassette;\n }\n\n /**\n * Load the on-disk cassette exactly once. Pure `record` mode skips the\n * read — it always writes fresh — but the in-memory cassette still starts\n * empty so a record run never accidentally replays a stale entry.\n */\n private async ensureLoaded(): Promise<void> {\n if (this.loadPromise) {\n return this.loadPromise;\n }\n\n this.loadPromise =\n this.mode === \"record\"\n ? Promise.resolve()\n : (async () => {\n this.loadedCassette = await loadCassette(\n this.path,\n this.inner.name,\n this.inner.provider,\n );\n })();\n\n return this.loadPromise;\n }\n\n /** Find a recorded entry whose hash matches the current request. */\n private findEntry(hash: string): CassetteEntry | undefined {\n return this.loadedCassette.entries.find((entry) => entry.requestHash === hash);\n }\n\n /** Re-throw a recorded error by reconstructing a plain `Error`. */\n private throwRecordedError(entry: CassetteEntry): never {\n const error = new Error(entry.error?.message ?? \"Recorded error\");\n\n error.name = entry.error?.name ?? \"Error\";\n\n throw error;\n }\n\n /**\n * Non-streaming call. In `replay` a miss throws; in `auto`/`record` a miss\n * calls the inner model and records the outcome (response or error).\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n await this.ensureLoaded();\n\n const hash = hashRequest(messages, options, this.hashOptions);\n\n if (this.mode !== \"record\") {\n const entry = this.findEntry(hash);\n\n if (entry) {\n if (entry.error) {\n this.throwRecordedError(entry);\n }\n\n if (entry.response) {\n return entry.response;\n }\n }\n\n if (this.mode === \"replay\") {\n throw new VcrCassetteMissError(\n `No cassette entry for this request (model \"${this.inner.name}\", hash ${hash}).`,\n { requestHash: hash, path: this.path },\n );\n }\n }\n\n try {\n const response = await this.inner.complete(messages, options);\n\n this.record({ requestHash: hash, request: { messages, options }, response });\n\n return response;\n } catch (error) {\n this.record({\n requestHash: hash,\n request: { messages, options },\n error: { name: (error as Error).name, message: (error as Error).message },\n });\n\n throw error;\n }\n }\n\n /**\n * Streaming call. On replay the stored `chunks` are re-yielded in order\n * (reproducing the `delta`/`tool-call`/`done` sequence) or the stored\n * error is re-thrown. On record the inner stream is buffered into\n * `chunks[]` while being re-emitted, then recorded once exhausted.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n await this.ensureLoaded();\n\n const hash = hashRequest(messages, options, this.hashOptions);\n\n if (this.mode !== \"record\") {\n const entry = this.findEntry(hash);\n\n if (entry) {\n if (entry.error) {\n this.throwRecordedError(entry);\n }\n\n if (entry.chunks) {\n for (const chunk of entry.chunks) {\n yield chunk;\n }\n\n return;\n }\n }\n\n if (this.mode === \"replay\") {\n throw new VcrCassetteMissError(\n `No cassette entry for this request (model \"${this.inner.name}\", hash ${hash}).`,\n { requestHash: hash, path: this.path },\n );\n }\n }\n\n const chunks: ModelStreamChunk[] = [];\n\n try {\n for await (const chunk of this.inner.stream(messages, options)) {\n chunks.push(chunk);\n\n yield chunk;\n }\n } catch (error) {\n this.record({\n requestHash: hash,\n request: { messages, options },\n error: { name: (error as Error).name, message: (error as Error).message },\n });\n\n throw error;\n }\n\n this.record({ requestHash: hash, request: { messages, options }, chunks });\n }\n\n /**\n * Append an entry to the in-memory cassette and mark it dirty, applying\n * the configured request/response/error redaction first (S2). Pure\n * `replay` never reaches this path, so no replay run is ever dirtied.\n */\n private record(entry: CassetteEntry): void {\n this.loadedCassette.entries.push(this.applyRedaction(entry));\n this.dirty = true;\n this.maybeWarnVerbatim();\n }\n\n /**\n * Apply the persisted-body privacy controls to an entry before it is\n * stored. The request body follows `recordRequest`; response/error\n * redactors are applied only when supplied. Replay matching is by the\n * recomputed hash (kept verbatim), so none of this affects replay.\n */\n private applyRedaction(entry: CassetteEntry): CassetteEntry {\n const out: CassetteEntry = {\n requestHash: entry.requestHash,\n request: entry.request,\n };\n\n if (this.recordRequest === \"hash-only\") {\n out.request = { messages: [] };\n } else if (this.recordRequest === \"redacted\") {\n out.request = this.redactRequestHook\n ? this.redactRequestHook(entry.request)\n : redact(entry.request);\n }\n\n if (entry.response) {\n out.response = this.redactResponseHook\n ? this.redactResponseHook(entry.response)\n : entry.response;\n }\n if (entry.chunks) {\n out.chunks = entry.chunks;\n }\n if (entry.error) {\n out.error = this.redactErrorHook\n ? this.redactErrorHook(entry.error)\n : entry.error;\n }\n\n return out;\n }\n\n /**\n * Warn once (outside tests) when the cassette is recording verbatim\n * request bodies — they may carry prompts, tool args, and PII, so the\n * file is not safe to commit until sanitized.\n */\n private maybeWarnVerbatim(): void {\n if (this.warnedVerbatim || this.recordRequest !== \"verbatim\") return;\n if (process.env.VITEST || process.env.NODE_ENV === \"test\") return;\n\n this.warnedVerbatim = true;\n console.warn(\n `[warlock-ai] VCR is recording verbatim request bodies to \"${this.path}\" — prompts, tool args, and any PII are stored unredacted. ` +\n 'Sanitize before committing, or set recordRequest: \"redacted\" | \"hash-only\".',\n );\n }\n\n /**\n * Flush newly recorded entries to `path`. No-op when nothing was recorded\n * (pure replay, or a record/auto run that only ever hit cached entries).\n */\n public async save(): Promise<void> {\n if (!this.dirty) {\n return;\n }\n\n await saveCassette(this.path, this.loadedCassette);\n this.dirty = false;\n }\n}\n\n/**\n * Wrap any `ModelContract` in a record/replay decorator backed by a JSON\n * cassette on disk.\n *\n * **What it does.** Intercepts only `complete()`/`stream()` — the single\n * seam every agent trip funnels through — and delegates `name`, `provider`,\n * `capabilities`, and `pricing` to the inner model untouched. On a call it\n * computes a stable hash over `{ messages, picked options }` and, depending\n * on `mode`:\n *\n * - **`record`** — always calls the inner model and appends a cassette entry.\n * - **`replay`** — returns the matching entry (or re-yields its chunks /\n * re-throws its error); a miss throws `VcrCassetteMissError`, never a live\n * call.\n * - **`auto`** (default) — replays a hit, records a miss.\n *\n * Composes *below* `fallbackModel` and works with any adapter because it\n * depends only on `ModelContract`. Call `save()` to flush new entries.\n *\n * @example\n * const model = vcr(liveModel, { path: \"./cassettes/support.json\" });\n * const response = await model.complete(messages);\n * await model.save(); // first run records; later runs replay deterministically.\n */\nexport function vcr(model: ModelContract, options: VcrOptions): VcrModel {\n return new Vcr(model, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,IAAM,MAAN,MAA8B;CAuB5B,AAAO,YACL,AAAiB,OACjB,SACA;EAFiB;eAfH;wBAYS;EAMvB,KAAK,OAAO,QAAQ;EACpB,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,cAAc,QAAQ,eAAe;EAC1C,KAAK,gBAAgB,QAAQ,iBAAiB;EAC9C,KAAK,oBAAo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A,AAAQ,OAAO,OAA4B;EACzC,KAAK,eAAe,QAAQ,KAAK,KAAK,eAAe,KAAK,CAAC;EAC3D,KAAK,QAAQ;EACb,KAAK,kBAAkB;CACzB;;;;;;;CAQA,AAAQ,eAAe,OAAqC;EAC1D,MAAM,MAAqB;GACzB,aAAa,MAAM;GACnB,SAAS,MAAM;EACjB;EAEA,IAAI,KAAK,kBAAkB,aACzB,IAAI,UAAU,EAAE,UAAU,CAAC,EAAE;OACxB,IAAI,KAAK,kBAAkB,YAChC,IAAI,UAAU,KAAK,oBACf,KAAK,kBAAkB,MAAM,OAAO,IACpC,OAAO,MAAM,OAAO;EAG1B,IAAI,MAAM,UACR,IAAI,WAAW,KAAK,qBAChB,KAAK,mBAAmB,MAAM,QAAQ,IACtC,MAAM;EAEZ,IAAI,MAAM,QACR,IAAI,SAAS,MAAM;EAErB,IAAI,MAAM,OACR,IAAI,QAAQ,KAAK,kBACb,KAAK,gBAAgB,MAAM,KAAK,IAChC,MAAM;EAGZ,OAAO;CACT;;;;;;CAOA,AAAQ,oBAA0B;EAChC,IAAI,KAAK,kBAAkB,KAAK,kBAAkB,YAAY;EAC9D,IAAI,QAAQ,IAAI,UAAU,QAAQ,IAAI,aAAa,QAAQ;EAE3D,KAAK,iBAAiB;EACtB,QAAQ,KACN,6DAA6D,KAAK,KAAK,uIAEzE;CACF;;;;;CAMA,MAAa,OAAsB;EACjC,IAAI,CAAC,KAAK,OACR;EAGF,MAAM,aAAa,KAAK,MAAM,KAAK,cAAc;EACjD,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,IAAI,OAAsB,SAA+B;CACvE,OAAO,IAAI,IAAI,OAAO,OAAO;AAC/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancellation.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/cancellation.ts"],"sourcesContent":["import { WorkflowCancelledError } from \"../errors\";\n\n/**\n * Build a `WorkflowCancelledError` from an `AbortSignal`, extracting\n * a human-readable reason from `signal.reason` (string | Error | any).\n * Used both at between-step boundaries and inside the retry backoff\n * sleep.\n */\nexport function createCancelledError(\n signal: AbortSignal | undefined,\n): WorkflowCancelledError {\n const reason = signal?.reason;\n const reasonText =\n typeof reason === \"string\"\n ? reason\n : reason instanceof Error\n ? reason.message\n : reason === undefined\n ? \"\"\n : String(reason);\n\n return new WorkflowCancelledError(\n `workflow cancelled${reasonText ? `: ${reasonText}` : \"\"}`,\n { cancelledAt: new Date().toISOString(), reason: reasonText },\n );\n}\n\n/**\n * Promise-based sleep that resolves after `ms` milliseconds, or\n * rejects with `WorkflowCancelledError` if the signal fires. The\n * timer is cleared on abort so we never leak a pending setTimeout.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(createCancelledError(signal));\n return;\n }\n\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(createCancelledError(signal));\n };\n\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgB,qBACd,QACwB;CACxB,MAAM,SAAS,QAAQ;CACvB,MAAM,aACJ,OAAO,WAAW,WACd,SACA,kBAAkB,QAChB,OAAO,UACP,WAAW,SACT,KACA,OAAO,MAAM;CAEvB,OAAO,IAAI,uBACT,qBAAqB,aAAa,KAAK,eAAe,MACtD;EAAE,8BAAa,IAAI,KAAK,
|
|
1
|
+
{"version":3,"file":"cancellation.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/cancellation.ts"],"sourcesContent":["import { WorkflowCancelledError } from \"../errors\";\n\n/**\n * Build a `WorkflowCancelledError` from an `AbortSignal`, extracting\n * a human-readable reason from `signal.reason` (string | Error | any).\n * Used both at between-step boundaries and inside the retry backoff\n * sleep.\n */\nexport function createCancelledError(\n signal: AbortSignal | undefined,\n): WorkflowCancelledError {\n const reason = signal?.reason;\n const reasonText =\n typeof reason === \"string\"\n ? reason\n : reason instanceof Error\n ? reason.message\n : reason === undefined\n ? \"\"\n : String(reason);\n\n return new WorkflowCancelledError(\n `workflow cancelled${reasonText ? `: ${reasonText}` : \"\"}`,\n { cancelledAt: new Date().toISOString(), reason: reasonText },\n );\n}\n\n/**\n * Promise-based sleep that resolves after `ms` milliseconds, or\n * rejects with `WorkflowCancelledError` if the signal fires. The\n * timer is cleared on abort so we never leak a pending setTimeout.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(createCancelledError(signal));\n return;\n }\n\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(createCancelledError(signal));\n };\n\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgB,qBACd,QACwB;CACxB,MAAM,SAAS,QAAQ;CACvB,MAAM,aACJ,OAAO,WAAW,WACd,SACA,kBAAkB,QAChB,OAAO,UACP,WAAW,SACT,KACA,OAAO,MAAM;CAEvB,OAAO,IAAI,uBACT,qBAAqB,aAAa,KAAK,eAAe,MACtD;EAAE,8BAAa,IAAI,KAAK,GAAE,YAAY;EAAG,QAAQ;CAAW,CAC9D;AACF;;;;;;AAOA,SAAgB,MAAM,IAAY,QAAqC;CACrE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,QAAQ,SAAS;GACnB,OAAO,qBAAqB,MAAM,CAAC;GACnC;EACF;EAEA,MAAM,QAAQ,iBAAiB;GAC7B,QAAQ,oBAAoB,SAAS,OAAO;GAC5C,QAAQ;EACV,GAAG,EAAE;EAEL,MAAM,gBAAgB;GACpB,aAAa,KAAK;GAClB,OAAO,qBAAqB,MAAM,CAAC;EACrC;EAEA,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emitter.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/emitter.ts"],"sourcesContent":["import type { WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type {\n WorkflowEventHandler,\n WorkflowEventHandlers,\n} from \"../contracts/workflow/workflow.contract\";\n\ntype AnyHandler = WorkflowEventHandler<keyof WorkflowEventMap>;\n\n/**\n * The emit surface the workflow engine and step-runner depend on.\n * They never construct run identity themselves — they hand a bare\n * payload to a sink that injects `runId` / `rootRunId` before\n * delegating to the real three-tier `WorkflowEmitter`.\n *\n * `WorkflowEmitter` is factory-scoped (shared across every\n * `execute()`), so it cannot own per-run identity. A per-run sink\n * (see `runScopedEmitter`) closes that gap without touching the ~15\n * `emit` call sites in `engine.ts` / `step-runner.ts`.\n */\nexport interface WorkflowEventSink {\n emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WithoutIdentity<WorkflowEventMap[K]>,\n executionHandlers?: WorkflowEventHandlers,\n ): void;\n}\n\n/**\n * Three-tier workflow event emitter — factory (definition) → instance →\n * per-execution. All matching handlers fire, in layer order. Handler\n * errors are swallowed so listener bugs can never derail the workflow.\n */\nexport class WorkflowEmitter {\n private readonly factoryHandlers?: WorkflowEventHandlers;\n private readonly instanceHandlers = new Map<\n keyof WorkflowEventMap,\n Set<AnyHandler>\n >();\n\n public constructor(factoryHandlers?: WorkflowEventHandlers) {\n this.factoryHandlers = factoryHandlers;\n }\n\n public on<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): () => void {\n let bucket = this.instanceHandlers.get(event);\n if (!bucket) {\n bucket = new Set();\n this.instanceHandlers.set(event, bucket);\n }\n bucket.add(handler as AnyHandler);\n return () => this.off(event, handler);\n }\n\n public off<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): void {\n this.instanceHandlers.get(event)?.delete(handler as AnyHandler);\n }\n\n public emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WorkflowEventMap[K],\n executionHandlers?: WorkflowEventHandlers,\n ): void {\n // Layer 1 — factory\n invoke(this.factoryHandlers?.[event], payload);\n\n // Layer 2 — instance (set-based, possibly many handlers)\n const bucket = this.instanceHandlers.get(event);\n if (bucket) {\n for (const handler of bucket) invoke(handler, payload);\n }\n\n // Layer 3 — per-execution\n invoke(executionHandlers?.[event], payload);\n }\n}\n\nfunction invoke<K extends keyof WorkflowEventMap>(\n handler: ((payload: WorkflowEventMap[K]) => void) | undefined,\n payload: WorkflowEventMap[K],\n): void {\n if (typeof handler !== \"function\") return;\n try {\n handler(payload);\n } catch {\n // Swallow — listener bugs must not derail workflow execution.\n }\n}\n"],"mappings":";;;;;;AAiCA,IAAa,kBAAb,MAA6B;CAO3B,AAAO,YAAY,iBAAyC;0CALxB,IAAI,IAGtC;EAGA,KAAK,kBAAkB;CACzB;CAEA,AAAO,GACL,OACA,SACY;EACZ,IAAI,SAAS,KAAK,iBAAiB,IAAI,KAAK;EAC5C,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,IAAI;GACjB,KAAK,iBAAiB,IAAI,OAAO,MAAM;EACzC;EACA,OAAO,IAAI,OAAqB;EAChC,aAAa,KAAK,IAAI,OAAO,OAAO;CACtC;CAEA,AAAO,IACL,OACA,SACM;EACN,KAAK,iBAAiB,IAAI,KAAK,
|
|
1
|
+
{"version":3,"file":"emitter.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/emitter.ts"],"sourcesContent":["import type { WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type {\n WorkflowEventHandler,\n WorkflowEventHandlers,\n} from \"../contracts/workflow/workflow.contract\";\n\ntype AnyHandler = WorkflowEventHandler<keyof WorkflowEventMap>;\n\n/**\n * The emit surface the workflow engine and step-runner depend on.\n * They never construct run identity themselves — they hand a bare\n * payload to a sink that injects `runId` / `rootRunId` before\n * delegating to the real three-tier `WorkflowEmitter`.\n *\n * `WorkflowEmitter` is factory-scoped (shared across every\n * `execute()`), so it cannot own per-run identity. A per-run sink\n * (see `runScopedEmitter`) closes that gap without touching the ~15\n * `emit` call sites in `engine.ts` / `step-runner.ts`.\n */\nexport interface WorkflowEventSink {\n emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WithoutIdentity<WorkflowEventMap[K]>,\n executionHandlers?: WorkflowEventHandlers,\n ): void;\n}\n\n/**\n * Three-tier workflow event emitter — factory (definition) → instance →\n * per-execution. All matching handlers fire, in layer order. Handler\n * errors are swallowed so listener bugs can never derail the workflow.\n */\nexport class WorkflowEmitter {\n private readonly factoryHandlers?: WorkflowEventHandlers;\n private readonly instanceHandlers = new Map<\n keyof WorkflowEventMap,\n Set<AnyHandler>\n >();\n\n public constructor(factoryHandlers?: WorkflowEventHandlers) {\n this.factoryHandlers = factoryHandlers;\n }\n\n public on<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): () => void {\n let bucket = this.instanceHandlers.get(event);\n if (!bucket) {\n bucket = new Set();\n this.instanceHandlers.set(event, bucket);\n }\n bucket.add(handler as AnyHandler);\n return () => this.off(event, handler);\n }\n\n public off<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): void {\n this.instanceHandlers.get(event)?.delete(handler as AnyHandler);\n }\n\n public emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WorkflowEventMap[K],\n executionHandlers?: WorkflowEventHandlers,\n ): void {\n // Layer 1 — factory\n invoke(this.factoryHandlers?.[event], payload);\n\n // Layer 2 — instance (set-based, possibly many handlers)\n const bucket = this.instanceHandlers.get(event);\n if (bucket) {\n for (const handler of bucket) invoke(handler, payload);\n }\n\n // Layer 3 — per-execution\n invoke(executionHandlers?.[event], payload);\n }\n}\n\nfunction invoke<K extends keyof WorkflowEventMap>(\n handler: ((payload: WorkflowEventMap[K]) => void) | undefined,\n payload: WorkflowEventMap[K],\n): void {\n if (typeof handler !== \"function\") return;\n try {\n handler(payload);\n } catch {\n // Swallow — listener bugs must not derail workflow execution.\n }\n}\n"],"mappings":";;;;;;AAiCA,IAAa,kBAAb,MAA6B;CAO3B,AAAO,YAAY,iBAAyC;0CALxB,IAAI,IAGtC;EAGA,KAAK,kBAAkB;CACzB;CAEA,AAAO,GACL,OACA,SACY;EACZ,IAAI,SAAS,KAAK,iBAAiB,IAAI,KAAK;EAC5C,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,IAAI;GACjB,KAAK,iBAAiB,IAAI,OAAO,MAAM;EACzC;EACA,OAAO,IAAI,OAAqB;EAChC,aAAa,KAAK,IAAI,OAAO,OAAO;CACtC;CAEA,AAAO,IACL,OACA,SACM;EACN,KAAK,iBAAiB,IAAI,KAAK,GAAG,OAAO,OAAqB;CAChE;CAEA,AAAO,KACL,OACA,SACA,mBACM;EAEN,OAAO,KAAK,kBAAkB,QAAQ,OAAO;EAG7C,MAAM,SAAS,KAAK,iBAAiB,IAAI,KAAK;EAC9C,IAAI,QACF,KAAK,MAAM,WAAW,QAAQ,OAAO,SAAS,OAAO;EAIvD,OAAO,oBAAoB,QAAQ,OAAO;CAC5C;AACF;AAEA,SAAS,OACP,SACA,SACM;CACN,IAAI,OAAO,YAAY,YAAY;CACnC,IAAI;EACF,QAAQ,OAAO;CACjB,QAAQ,CAER;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/engine.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type {\n WorkflowReport,\n WorkflowResult,\n} from \"../contracts/result/workflow-result.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowSnapshot } from \"../contracts/workflow/workflow-snapshot.type\";\nimport type {\n WorkflowDefinition,\n WorkflowEventHandlers,\n} from \"../contracts/workflow/workflow.contract\";\nimport {\n AIError,\n MaxStepsExceededError,\n RoutingError,\n SchemaValidationError,\n WorkflowCancelledError,\n WorkflowError,\n} from \"../errors\";\nimport { stampReportLineage } from \"../utils\";\nimport { createCancelledError } from \"./cancellation\";\nimport type { WorkflowEmitter } from \"./emitter\";\nimport { mapNextStep, nextDeclaredStep, resolveNextStep } from \"./router\";\nimport { runScopedEmitter } from \"./run-scoped-emitter\";\nimport { persistSnapshot } from \"./snapshot\";\nimport { cloneState, deepFreeze } from \"./state\";\nimport { executeStep, finalizeSnapshot, toAIError } from \"./step-runner\";\n\nexport { loadSnapshotForResume } from \"./snapshot\";\n\nconst DEFAULT_MAX_STEPS = 100;\nconst DEFAULT_LOOP_WARN = 5;\nconst LOG_MODULE_BASE = \"ai.workflow\";\n\ntype EngineParams<TOutput> = {\n definition: WorkflowDefinition<any, TOutput, any, any>;\n signature: string;\n emitter: WorkflowEmitter;\n input: unknown;\n /**\n * Request-scoped envelope, frozen and exposed as `ctx.context` to\n * every step. Never persisted in snapshots; resume callers supply\n * it fresh via `WorkflowResumeOptions.context`. Defaults to a\n * frozen empty object when caller omits it.\n */\n context?: unknown;\n runId: string;\n signal?: AbortSignal;\n executionHandlers?: WorkflowEventHandlers;\n resumeFrom?: WorkflowSnapshot;\n /**\n * Opaque session identifier propagated onto every report node this\n * run produces — including agent reports from child steps. Threaded\n * from `WorkflowRunOptions.sessionId`. Omitted leaves the field\n * undefined throughout the tree.\n */\n sessionId?: string;\n};\n\n/**\n * Main workflow driver. Walks the declared steps, handling routing,\n * cancellation, retries, parallel execution, and snapshot\n * persistence. Delegates the step lifecycle to `step-runner.ts`,\n * routing to `router.ts`, persistence to `snapshot.ts`. Never throws\n * — every failure funnels into `result.error`.\n */\nexport async function runWorkflow<TOutput>(\n params: EngineParams<TOutput>,\n): Promise<WorkflowResult<TOutput>> {\n const { definition, signature, input, runId, signal } = params;\n // Bind the factory-scoped emitter to THIS run's identity. Every\n // `emitter.emit(...)` below — and the one threaded into\n // `executeStep` — now stamps `runId` / `rootRunId` automatically.\n const emitter = runScopedEmitter(params.emitter, {\n runId,\n rootRunId: runId,\n });\n\n // Freeze the envelope once at run start. Default to `{}` so step\n // code can always read `ctx.context` without an undefined guard.\n const context = Object.freeze(params.context ?? {});\n const maxSteps = definition.maxSteps ?? DEFAULT_MAX_STEPS;\n const loopWarnAfter = definition.loopWarnAfter ?? DEFAULT_LOOP_WARN;\n\n const logger = log;\n const logModule = `${LOG_MODULE_BASE}.${definition.name}`;\n\n const stepByName = new Map<string, StepDefinition>();\n for (const s of definition.steps) stepByName.set(s.name, s);\n\n const state: Record<string, unknown> = params.resumeFrom\n ? { ...params.resumeFrom.state }\n : {};\n const steps: Record<string, StepSnapshot> = params.resumeFrom\n ? { ...params.resumeFrom.steps }\n : {};\n const enteredCount = new Map<string, number>();\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n const startedAt = params.resumeFrom?.startedAt ?? new Date().toISOString();\n const startedAtDate = new Date(startedAt);\n const runStartPerf = performance.now();\n\n let error: AIError | undefined;\n let status: \"completed\" | \"failed\" | \"cancelled\" = \"completed\";\n let cancelledAt: string | undefined;\n let lastGoto: string | null = null;\n // Captured when a step throws after retries exhaust (and `onFailure`\n // didn't recover). Used to point the final snapshot's `next` at the\n // failed step so `resume()` re-runs it after the cause is fixed.\n let failedStepName: string | undefined;\n\n const buildContext = (current?: {\n state: Record<string, unknown>;\n agentResult?: unknown;\n }): WorkflowContext => ({\n input,\n context,\n steps: steps as Readonly<Record<string, StepSnapshot>>,\n state: current?.state ?? state,\n agentResult: current?.agentResult as WorkflowContext[\"agentResult\"],\n runId,\n signal,\n startedAt: startedAtDate,\n });\n\n emitter.emit(\n \"workflow.starting\",\n { workflowName: definition.name, input },\n params.executionHandlers,\n );\n logger.info(logModule, \"starting\", \"workflow starting\", { runId });\n\n let currentName: string | null = resolveInitialStep(\n definition,\n params.resumeFrom,\n );\n let stepCount = 0;\n\n try {\n while (currentName !== null) {\n if (signal?.aborted) throw createCancelledError(signal);\n\n stepCount += 1;\n if (stepCount > maxSteps) {\n throw new MaxStepsExceededError(\n `workflow \"${definition.name}\" exceeded maxSteps=${maxSteps}`,\n { maxSteps },\n );\n }\n\n const entered = (enteredCount.get(currentName) ?? 0) + 1;\n enteredCount.set(currentName, entered);\n if (entered === loopWarnAfter) {\n emitter.emit(\n \"workflow.loop.warning\",\n { step: currentName, enteredCount: entered, lastGoto },\n params.executionHandlers,\n );\n logger.warn(logModule, \"loop.warning\", \"loop warning\", {\n step: currentName,\n enteredCount: entered,\n });\n }\n\n const step = stepByName.get(currentName);\n if (!step) {\n throw new RoutingError(\n `workflow \"${definition.name}\": unknown step \"${currentName}\"`,\n { stepName: currentName },\n );\n }\n\n const snapshot = await executeStep({\n step,\n state,\n emitter,\n executionHandlers: params.executionHandlers,\n logger,\n logModule,\n signal,\n buildContext,\n usage,\n workflowDefaultRetry: definition.defaultRetry,\n runId,\n sessionId: params.sessionId,\n });\n\n Object.assign(state, snapshot.state);\n steps[step.name] = finalizeSnapshot(snapshot);\n // Parallel children — flat-path addressing alongside nested.\n if (snapshot.steps) {\n for (const [childName, childSnap] of Object.entries(snapshot.steps)) {\n steps[childName] = childSnap;\n }\n }\n\n // Failure path: retries exhausted. Give `onFailure` a chance to\n // recover; otherwise checkpoint at the failed step (so resume\n // re-runs it) and throw — workflow halts.\n if (snapshot.status === \"failed\" && snapshot.error) {\n const failureRoute = await resolveFailureRoute({\n step,\n definition,\n error: snapshot.error,\n ctx: buildContext({ state, agentResult: snapshot.executionResult }),\n });\n\n if (failureRoute === undefined) {\n // No recovery — persist with `next: step.name` so resume\n // re-runs this step after the user fixes the cause.\n const persistOutcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: step.name,\n status: \"running\",\n });\n if (!persistOutcome.ok) {\n const persistErr = toAIError(persistOutcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(\n logModule,\n \"persist.failed\",\n \"snapshot persist failed\",\n {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n },\n );\n }\n failedStepName = step.name;\n throw snapshot.error;\n }\n\n // onFailure routed — workflow continues. Checkpoint at the\n // routed target (or `null` for `end`) so resume picks up there.\n const failureNext = failureRoute === \"end\" ? null : failureRoute;\n if (failureNext !== null && !stepByName.has(failureNext)) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" onFailure routed to unknown target \"${failureNext}\"`,\n { stepName: step.name, targetName: failureNext },\n );\n }\n\n const failurePersist = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: failureNext,\n status: \"running\",\n });\n if (!failurePersist.ok) {\n const persistErr = toAIError(failurePersist.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(\n logModule,\n \"persist.failed\",\n \"snapshot persist failed\",\n {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n },\n );\n }\n\n if (signal?.aborted) throw createCancelledError(signal);\n\n if (failureRoute === \"end\") {\n currentName = null;\n break;\n }\n\n lastGoto = failureRoute;\n currentName = failureRoute;\n continue;\n }\n\n // Resolve next step for checkpoint accuracy BEFORE routing errors\n // bubble — so the snapshot records where resume should resume from.\n const resolved = await resolveNextStep({\n step,\n definition,\n ctx: buildContext({ state, agentResult: snapshot.executionResult }),\n });\n\n const nextName =\n resolved === \"end\"\n ? null\n : typeof resolved === \"string\"\n ? resolved\n : nextDeclaredStep(definition, step.name);\n\n // Checkpoint after every step with the resolved `next`.\n const outcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: nextName,\n status: \"running\",\n });\n if (!outcome.ok) {\n const persistErr = toAIError(outcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(logModule, \"persist.failed\", \"snapshot persist failed\", {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n });\n }\n\n if (signal?.aborted) throw createCancelledError(signal);\n\n if (resolved === \"end\") {\n currentName = null;\n break;\n }\n\n if (typeof resolved === \"string\") {\n if (!stepByName.has(resolved)) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" goto unknown target \"${resolved}\"`,\n { stepName: step.name, targetName: resolved },\n );\n }\n lastGoto = resolved;\n currentName = resolved;\n continue;\n }\n\n currentName = nextName;\n lastGoto = currentName;\n }\n } catch (err) {\n if (err instanceof WorkflowCancelledError) {\n status = \"cancelled\";\n cancelledAt = err.cancelledAt;\n error = err;\n } else if (err instanceof AIError) {\n status = \"failed\";\n error = err;\n } else {\n status = \"failed\";\n error = new WorkflowError(\n err instanceof Error ? err.message : String(err),\n { cause: err },\n );\n }\n }\n\n // Note: a `failed` step always throws (caught above) unless its\n // `onFailure` recovered the run. A `completed` workflow may still\n // contain `failed` step snapshots — those are the recovered cases\n // and are intentionally preserved for forensic trace.\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - runStartPerf;\n\n let data: TOutput | undefined;\n if (status === \"completed\" && definition.output) {\n try {\n const extracted = await definition.output.extract(\n buildContext({ state }),\n );\n data = (await validateWorkflowOutput(\n definition.output.schema,\n extracted,\n )) as TOutput;\n } catch (err) {\n status = \"failed\";\n error =\n err instanceof AIError\n ? err\n : new WorkflowError(\n err instanceof Error ? err.message : String(err),\n { cause: err },\n );\n }\n }\n\n // Collect child executable reports from every step that produced one —\n // either the declarative `step.agent` field's own report, or whatever\n // a `run` callback's ambient run-frame captured from a direct\n // `agent.execute(...)` call (step-runner.ts's `withRunFrame` around\n // `step.run`). Order matches step declaration; within a step, the\n // agentReport (if any) precedes its run-captured children.\n const children: BaseReport[] = [];\n for (const stepName in steps) {\n const snap = steps[stepName];\n if (snap.agentReport) {\n children.push(snap.agentReport);\n }\n if (snap.children) {\n children.push(...snap.children);\n }\n }\n\n const report: WorkflowReport = {\n runId,\n rootRunId: runId,\n name: definition.name,\n version: definition.version,\n type: \"workflow\",\n workflowName: definition.name,\n signature,\n status,\n // Stamp the terminal error onto the report so it travels with the tree\n // (observe path has no result envelope to fall back on). A failed `run`\n // step's cause lives in `steps[name].error`, but the workflow-level\n // error is what a consumer reads off the root span. Absent on success.\n ...(error ? { error } : {}),\n startedAt,\n endedAt,\n duration,\n cancelledAt,\n usage,\n children,\n steps,\n state: deepFreeze(cloneState(state)),\n };\n\n // Stamp lineage on the assembled tree exactly once. Walker rewrites\n // any inner self-roots that nested agent reports brought in (each\n // agent's `buildResult` set its own runId as root), propagates\n // sessionId, and writes `reportSchemaVersion` on the root.\n stampReportLineage(report, {\n rootRunId: runId,\n sessionId: params.sessionId,\n });\n\n // On a failed run with a captured `failedStepName`, point `next` at\n // the failed step so `resume()` re-runs it. The pre-throw checkpoint\n // already wrote this value, but the final snapshot would otherwise\n // overwrite it with `null` and force resume to fall back to the\n // first non-completed step (which is the same step in practice, but\n // less informative for tooling reading the snapshot).\n const finalNext = status === \"failed\" ? failedStepName ?? null : null;\n\n const finalOutcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: finalNext,\n status,\n });\n if (!finalOutcome.ok) {\n const persistErr = toAIError(finalOutcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(logModule, \"persist.failed\", \"final snapshot persist failed\", {\n code: persistErr.code,\n message: persistErr.message,\n });\n }\n\n const result: WorkflowResult<TOutput> = {\n type: \"workflow\",\n data,\n report,\n usage,\n error,\n };\n\n if (status === \"cancelled\") {\n emitter.emit(\n \"workflow.cancelled\",\n {\n cancelledAt: cancelledAt ?? endedAt,\n reason: (error as WorkflowCancelledError | undefined)?.reason ?? \"\",\n },\n params.executionHandlers,\n );\n logger.warn(logModule, \"cancelled\", \"workflow cancelled\", { runId });\n }\n\n if (status === \"failed\" && error) {\n emitter.emit(\"workflow.error\", { error }, params.executionHandlers);\n logger.error(logModule, \"error\", \"workflow failed\", {\n runId,\n code: error.code,\n message: error.message,\n });\n }\n\n emitter.emit(\n \"workflow.completed\",\n { result: result as WorkflowResult<unknown> },\n params.executionHandlers,\n );\n logger.info(logModule, \"completed\", \"workflow completed\", {\n runId,\n status,\n duration,\n });\n\n return result;\n}\n\n/**\n * Run a failed step's `onFailure` hook (if present) and translate its\n * result into a route. Returns `undefined` when the workflow should\n * halt with the original error; `\"end\"` for clean termination; or a\n * step name to redirect to. A throw inside `onFailure` is wrapped in\n * `RoutingError` — routing is authoritative, never retried.\n */\nasync function resolveFailureRoute<T>(params: {\n step: StepDefinition;\n definition: WorkflowDefinition<any, T, any, any>;\n error: AIError;\n ctx: WorkflowContext;\n}): Promise<\"end\" | string | undefined> {\n const { step, definition, error, ctx } = params;\n if (!step.onFailure) return undefined;\n\n let outcome;\n try {\n outcome = await step.onFailure(ctx, error);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" onFailure threw`,\n { stepName: step.name, cause: err },\n );\n }\n return mapNextStep(outcome);\n}\n\nfunction resolveInitialStep<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n resumeFrom: WorkflowSnapshot | undefined,\n): string | null {\n if (!resumeFrom) return definition.steps[0]?.name ?? null;\n\n // Prefer the explicitly-recorded `next` (now populated on every\n // checkpoint). Falls back to first step whose snapshot is missing\n // or not in a terminal-success state — covers older snapshots\n // written before `next` was wired.\n if (\n resumeFrom.next &&\n definition.steps.some(s => s.name === resumeFrom.next)\n ) {\n return resumeFrom.next;\n }\n\n for (const step of definition.steps) {\n const snap = resumeFrom.steps[step.name];\n if (!snap || (snap.status !== \"completed\" && snap.status !== \"skipped\")) {\n return step.name;\n }\n }\n\n return null;\n}\n\nasync function validateWorkflowOutput(\n schema: unknown,\n value: unknown,\n): Promise<unknown> {\n if (!schema) return value;\n\n const result = await (\n schema as {\n \"~standard\": { validate: (v: unknown) => Promise<unknown> | unknown };\n }\n )[\"~standard\"].validate(value);\n\n if (\n result &&\n typeof result === \"object\" &&\n \"issues\" in result &&\n (result as { issues: unknown }).issues\n ) {\n throw new SchemaValidationError(\n \"workflow output failed schema validation\",\n {\n issues: (result as { issues: any }).issues,\n },\n );\n }\n\n return (result as { value: unknown }).value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,kBAAkB;;;;;;;;AAkCxB,eAAsB,YACpB,QACkC;CAClC,MAAM,EAAE,YAAY,WAAW,OAAO,OAAO,WAAW;CAIxD,MAAM,UAAU,iBAAiB,OAAO,SAAS;EAC/C;EACA,WAAW;CACb,CAAC;CAID,MAAM,UAAU,OAAO,OAAO,OAAO,WAAW,CAAC,CAAC;CAClD,MAAM,WAAW,WAAW,YAAY;CACxC,MAAM,gBAAgB,WAAW,iBAAiB;CAElD,MAAM,SAAS;CACf,MAAM,YAAY,GAAG,gBAAgB,GAAG,WAAW;CAEnD,MAAM,6BAAa,IAAI,IAA4B;CACnD,KAAK,MAAM,KAAK,WAAW,OAAO,WAAW,IAAI,EAAE,MAAM,CAAC;CAE1D,MAAM,QAAiC,OAAO,aAC1C,EAAE,GAAG,OAAO,WAAW,MAAM,IAC7B,CAAC;CACL,MAAM,QAAsC,OAAO,aAC/C,EAAE,GAAG,OAAO,WAAW,MAAM,IAC7B,CAAC;CACL,MAAM,+BAAe,IAAI,IAAoB;CAC7C,MAAM,QAAe;EAAE,OAAO;EAAG,QAAQ;EAAG,OAAO;CAAE;CAErD,MAAM,YAAY,OAAO,YAAY,8BAAa,IAAI,KAAK,EAAC,CAAC,YAAY;CACzE,MAAM,gBAAgB,IAAI,KAAK,SAAS;CACxC,MAAM,eAAe,YAAY,IAAI;CAErC,IAAI;CACJ,IAAI,SAA+C;CACnD,IA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MAAM,SAAS,MACb,OAGA,YAAY,CAAC,SAAS,KAAK;CAE7B,IACE,UACA,OAAO,WAAW,YAClB,YAAY,UACX,OAA+B,QAEhC,MAAM,IAAI,sBACR,4CACA,EACE,QAAS,OAA2B,OACtC,CACF;CAGF,OAAQ,OAA8B;AACxC"}
|
|
1
|
+
{"version":3,"file":"engine.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/engine.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type {\n WorkflowReport,\n WorkflowResult,\n} from \"../contracts/result/workflow-result.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowSnapshot } from \"../contracts/workflow/workflow-snapshot.type\";\nimport type {\n WorkflowDefinition,\n WorkflowEventHandlers,\n} from \"../contracts/workflow/workflow.contract\";\nimport {\n AIError,\n MaxStepsExceededError,\n RoutingError,\n SchemaValidationError,\n WorkflowCancelledError,\n WorkflowError,\n} from \"../errors\";\nimport { stampReportLineage } from \"../utils\";\nimport { createCancelledError } from \"./cancellation\";\nimport type { WorkflowEmitter } from \"./emitter\";\nimport { mapNextStep, nextDeclaredStep, resolveNextStep } from \"./router\";\nimport { runScopedEmitter } from \"./run-scoped-emitter\";\nimport { persistSnapshot } from \"./snapshot\";\nimport { cloneState, deepFreeze } from \"./state\";\nimport { executeStep, finalizeSnapshot, toAIError } from \"./step-runner\";\n\nexport { loadSnapshotForResume } from \"./snapshot\";\n\nconst DEFAULT_MAX_STEPS = 100;\nconst DEFAULT_LOOP_WARN = 5;\nconst LOG_MODULE_BASE = \"ai.workflow\";\n\ntype EngineParams<TOutput> = {\n definition: WorkflowDefinition<any, TOutput, any, any>;\n signature: string;\n emitter: WorkflowEmitter;\n input: unknown;\n /**\n * Request-scoped envelope, frozen and exposed as `ctx.context` to\n * every step. Never persisted in snapshots; resume callers supply\n * it fresh via `WorkflowResumeOptions.context`. Defaults to a\n * frozen empty object when caller omits it.\n */\n context?: unknown;\n runId: string;\n signal?: AbortSignal;\n executionHandlers?: WorkflowEventHandlers;\n resumeFrom?: WorkflowSnapshot;\n /**\n * Opaque session identifier propagated onto every report node this\n * run produces — including agent reports from child steps. Threaded\n * from `WorkflowRunOptions.sessionId`. Omitted leaves the field\n * undefined throughout the tree.\n */\n sessionId?: string;\n};\n\n/**\n * Main workflow driver. Walks the declared steps, handling routing,\n * cancellation, retries, parallel execution, and snapshot\n * persistence. Delegates the step lifecycle to `step-runner.ts`,\n * routing to `router.ts`, persistence to `snapshot.ts`. Never throws\n * — every failure funnels into `result.error`.\n */\nexport async function runWorkflow<TOutput>(\n params: EngineParams<TOutput>,\n): Promise<WorkflowResult<TOutput>> {\n const { definition, signature, input, runId, signal } = params;\n // Bind the factory-scoped emitter to THIS run's identity. Every\n // `emitter.emit(...)` below — and the one threaded into\n // `executeStep` — now stamps `runId` / `rootRunId` automatically.\n const emitter = runScopedEmitter(params.emitter, {\n runId,\n rootRunId: runId,\n });\n\n // Freeze the envelope once at run start. Default to `{}` so step\n // code can always read `ctx.context` without an undefined guard.\n const context = Object.freeze(params.context ?? {});\n const maxSteps = definition.maxSteps ?? DEFAULT_MAX_STEPS;\n const loopWarnAfter = definition.loopWarnAfter ?? DEFAULT_LOOP_WARN;\n\n const logger = log;\n const logModule = `${LOG_MODULE_BASE}.${definition.name}`;\n\n const stepByName = new Map<string, StepDefinition>();\n for (const s of definition.steps) stepByName.set(s.name, s);\n\n const state: Record<string, unknown> = params.resumeFrom\n ? { ...params.resumeFrom.state }\n : {};\n const steps: Record<string, StepSnapshot> = params.resumeFrom\n ? { ...params.resumeFrom.steps }\n : {};\n const enteredCount = new Map<string, number>();\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n const startedAt = params.resumeFrom?.startedAt ?? new Date().toISOString();\n const startedAtDate = new Date(startedAt);\n const runStartPerf = performance.now();\n\n let error: AIError | undefined;\n let status: \"completed\" | \"failed\" | \"cancelled\" = \"completed\";\n let cancelledAt: string | undefined;\n let lastGoto: string | null = null;\n // Captured when a step throws after retries exhaust (and `onFailure`\n // didn't recover). Used to point the final snapshot's `next` at the\n // failed step so `resume()` re-runs it after the cause is fixed.\n let failedStepName: string | undefined;\n\n const buildContext = (current?: {\n state: Record<string, unknown>;\n agentResult?: unknown;\n }): WorkflowContext => ({\n input,\n context,\n steps: steps as Readonly<Record<string, StepSnapshot>>,\n state: current?.state ?? state,\n agentResult: current?.agentResult as WorkflowContext[\"agentResult\"],\n runId,\n signal,\n startedAt: startedAtDate,\n });\n\n emitter.emit(\n \"workflow.starting\",\n { workflowName: definition.name, input },\n params.executionHandlers,\n );\n logger.info(logModule, \"starting\", \"workflow starting\", { runId });\n\n let currentName: string | null = resolveInitialStep(\n definition,\n params.resumeFrom,\n );\n let stepCount = 0;\n\n try {\n while (currentName !== null) {\n if (signal?.aborted) throw createCancelledError(signal);\n\n stepCount += 1;\n if (stepCount > maxSteps) {\n throw new MaxStepsExceededError(\n `workflow \"${definition.name}\" exceeded maxSteps=${maxSteps}`,\n { maxSteps },\n );\n }\n\n const entered = (enteredCount.get(currentName) ?? 0) + 1;\n enteredCount.set(currentName, entered);\n if (entered === loopWarnAfter) {\n emitter.emit(\n \"workflow.loop.warning\",\n { step: currentName, enteredCount: entered, lastGoto },\n params.executionHandlers,\n );\n logger.warn(logModule, \"loop.warning\", \"loop warning\", {\n step: currentName,\n enteredCount: entered,\n });\n }\n\n const step = stepByName.get(currentName);\n if (!step) {\n throw new RoutingError(\n `workflow \"${definition.name}\": unknown step \"${currentName}\"`,\n { stepName: currentName },\n );\n }\n\n const snapshot = await executeStep({\n step,\n state,\n emitter,\n executionHandlers: params.executionHandlers,\n logger,\n logModule,\n signal,\n buildContext,\n usage,\n workflowDefaultRetry: definition.defaultRetry,\n runId,\n sessionId: params.sessionId,\n });\n\n Object.assign(state, snapshot.state);\n steps[step.name] = finalizeSnapshot(snapshot);\n // Parallel children — flat-path addressing alongside nested.\n if (snapshot.steps) {\n for (const [childName, childSnap] of Object.entries(snapshot.steps)) {\n steps[childName] = childSnap;\n }\n }\n\n // Failure path: retries exhausted. Give `onFailure` a chance to\n // recover; otherwise checkpoint at the failed step (so resume\n // re-runs it) and throw — workflow halts.\n if (snapshot.status === \"failed\" && snapshot.error) {\n const failureRoute = await resolveFailureRoute({\n step,\n definition,\n error: snapshot.error,\n ctx: buildContext({ state, agentResult: snapshot.executionResult }),\n });\n\n if (failureRoute === undefined) {\n // No recovery — persist with `next: step.name` so resume\n // re-runs this step after the user fixes the cause.\n const persistOutcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: step.name,\n status: \"running\",\n });\n if (!persistOutcome.ok) {\n const persistErr = toAIError(persistOutcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(\n logModule,\n \"persist.failed\",\n \"snapshot persist failed\",\n {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n },\n );\n }\n failedStepName = step.name;\n throw snapshot.error;\n }\n\n // onFailure routed — workflow continues. Checkpoint at the\n // routed target (or `null` for `end`) so resume picks up there.\n const failureNext = failureRoute === \"end\" ? null : failureRoute;\n if (failureNext !== null && !stepByName.has(failureNext)) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" onFailure routed to unknown target \"${failureNext}\"`,\n { stepName: step.name, targetName: failureNext },\n );\n }\n\n const failurePersist = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: failureNext,\n status: \"running\",\n });\n if (!failurePersist.ok) {\n const persistErr = toAIError(failurePersist.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(\n logModule,\n \"persist.failed\",\n \"snapshot persist failed\",\n {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n },\n );\n }\n\n if (signal?.aborted) throw createCancelledError(signal);\n\n if (failureRoute === \"end\") {\n currentName = null;\n break;\n }\n\n lastGoto = failureRoute;\n currentName = failureRoute;\n continue;\n }\n\n // Resolve next step for checkpoint accuracy BEFORE routing errors\n // bubble — so the snapshot records where resume should resume from.\n const resolved = await resolveNextStep({\n step,\n definition,\n ctx: buildContext({ state, agentResult: snapshot.executionResult }),\n });\n\n const nextName =\n resolved === \"end\"\n ? null\n : typeof resolved === \"string\"\n ? resolved\n : nextDeclaredStep(definition, step.name);\n\n // Checkpoint after every step with the resolved `next`.\n const outcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: nextName,\n status: \"running\",\n });\n if (!outcome.ok) {\n const persistErr = toAIError(outcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(logModule, \"persist.failed\", \"snapshot persist failed\", {\n step: step.name,\n code: persistErr.code,\n message: persistErr.message,\n });\n }\n\n if (signal?.aborted) throw createCancelledError(signal);\n\n if (resolved === \"end\") {\n currentName = null;\n break;\n }\n\n if (typeof resolved === \"string\") {\n if (!stepByName.has(resolved)) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" goto unknown target \"${resolved}\"`,\n { stepName: step.name, targetName: resolved },\n );\n }\n lastGoto = resolved;\n currentName = resolved;\n continue;\n }\n\n currentName = nextName;\n lastGoto = currentName;\n }\n } catch (err) {\n if (err instanceof WorkflowCancelledError) {\n status = \"cancelled\";\n cancelledAt = err.cancelledAt;\n error = err;\n } else if (err instanceof AIError) {\n status = \"failed\";\n error = err;\n } else {\n status = \"failed\";\n error = new WorkflowError(\n err instanceof Error ? err.message : String(err),\n { cause: err },\n );\n }\n }\n\n // Note: a `failed` step always throws (caught above) unless its\n // `onFailure` recovered the run. A `completed` workflow may still\n // contain `failed` step snapshots — those are the recovered cases\n // and are intentionally preserved for forensic trace.\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - runStartPerf;\n\n let data: TOutput | undefined;\n if (status === \"completed\" && definition.output) {\n try {\n const extracted = await definition.output.extract(\n buildContext({ state }),\n );\n data = (await validateWorkflowOutput(\n definition.output.schema,\n extracted,\n )) as TOutput;\n } catch (err) {\n status = \"failed\";\n error =\n err instanceof AIError\n ? err\n : new WorkflowError(\n err instanceof Error ? err.message : String(err),\n { cause: err },\n );\n }\n }\n\n // Collect child executable reports from every step that produced one —\n // either the declarative `step.agent` field's own report, or whatever\n // a `run` callback's ambient run-frame captured from a direct\n // `agent.execute(...)` call (step-runner.ts's `withRunFrame` around\n // `step.run`). Order matches step declaration; within a step, the\n // agentReport (if any) precedes its run-captured children.\n const children: BaseReport[] = [];\n for (const stepName in steps) {\n const snap = steps[stepName];\n if (snap.agentReport) {\n children.push(snap.agentReport);\n }\n if (snap.children) {\n children.push(...snap.children);\n }\n }\n\n const report: WorkflowReport = {\n runId,\n rootRunId: runId,\n name: definition.name,\n version: definition.version,\n type: \"workflow\",\n workflowName: definition.name,\n signature,\n status,\n // Stamp the terminal error onto the report so it travels with the tree\n // (observe path has no result envelope to fall back on). A failed `run`\n // step's cause lives in `steps[name].error`, but the workflow-level\n // error is what a consumer reads off the root span. Absent on success.\n ...(error ? { error } : {}),\n startedAt,\n endedAt,\n duration,\n cancelledAt,\n usage,\n children,\n steps,\n state: deepFreeze(cloneState(state)),\n };\n\n // Stamp lineage on the assembled tree exactly once. Walker rewrites\n // any inner self-roots that nested agent reports brought in (each\n // agent's `buildResult` set its own runId as root), propagates\n // sessionId, and writes `reportSchemaVersion` on the root.\n stampReportLineage(report, {\n rootRunId: runId,\n sessionId: params.sessionId,\n });\n\n // On a failed run with a captured `failedStepName`, point `next` at\n // the failed step so `resume()` re-runs it. The pre-throw checkpoint\n // already wrote this value, but the final snapshot would otherwise\n // overwrite it with `null` and force resume to fall back to the\n // first non-completed step (which is the same step in practice, but\n // less informative for tooling reading the snapshot).\n const finalNext = status === \"failed\" ? failedStepName ?? null : null;\n\n const finalOutcome = await persistSnapshot({\n definition,\n signature,\n runId,\n startedAt,\n input,\n state,\n steps,\n next: finalNext,\n status,\n });\n if (!finalOutcome.ok) {\n const persistErr = toAIError(finalOutcome.error);\n emitter.emit(\n \"workflow.error\",\n { error: persistErr },\n params.executionHandlers,\n );\n logger.error(logModule, \"persist.failed\", \"final snapshot persist failed\", {\n code: persistErr.code,\n message: persistErr.message,\n });\n }\n\n const result: WorkflowResult<TOutput> = {\n type: \"workflow\",\n data,\n report,\n usage,\n error,\n };\n\n if (status === \"cancelled\") {\n emitter.emit(\n \"workflow.cancelled\",\n {\n cancelledAt: cancelledAt ?? endedAt,\n reason: (error as WorkflowCancelledError | undefined)?.reason ?? \"\",\n },\n params.executionHandlers,\n );\n logger.warn(logModule, \"cancelled\", \"workflow cancelled\", { runId });\n }\n\n if (status === \"failed\" && error) {\n emitter.emit(\"workflow.error\", { error }, params.executionHandlers);\n logger.error(logModule, \"error\", \"workflow failed\", {\n runId,\n code: error.code,\n message: error.message,\n });\n }\n\n emitter.emit(\n \"workflow.completed\",\n { result: result as WorkflowResult<unknown> },\n params.executionHandlers,\n );\n logger.info(logModule, \"completed\", \"workflow completed\", {\n runId,\n status,\n duration,\n });\n\n return result;\n}\n\n/**\n * Run a failed step's `onFailure` hook (if present) and translate its\n * result into a route. Returns `undefined` when the workflow should\n * halt with the original error; `\"end\"` for clean termination; or a\n * step name to redirect to. A throw inside `onFailure` is wrapped in\n * `RoutingError` — routing is authoritative, never retried.\n */\nasync function resolveFailureRoute<T>(params: {\n step: StepDefinition;\n definition: WorkflowDefinition<any, T, any, any>;\n error: AIError;\n ctx: WorkflowContext;\n}): Promise<\"end\" | string | undefined> {\n const { step, definition, error, ctx } = params;\n if (!step.onFailure) return undefined;\n\n let outcome;\n try {\n outcome = await step.onFailure(ctx, error);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" onFailure threw`,\n { stepName: step.name, cause: err },\n );\n }\n return mapNextStep(outcome);\n}\n\nfunction resolveInitialStep<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n resumeFrom: WorkflowSnapshot | undefined,\n): string | null {\n if (!resumeFrom) return definition.steps[0]?.name ?? null;\n\n // Prefer the explicitly-recorded `next` (now populated on every\n // checkpoint). Falls back to first step whose snapshot is missing\n // or not in a terminal-success state — covers older snapshots\n // written before `next` was wired.\n if (\n resumeFrom.next &&\n definition.steps.some(s => s.name === resumeFrom.next)\n ) {\n return resumeFrom.next;\n }\n\n for (const step of definition.steps) {\n const snap = resumeFrom.steps[step.name];\n if (!snap || (snap.status !== \"completed\" && snap.status !== \"skipped\")) {\n return step.name;\n }\n }\n\n return null;\n}\n\nasync function validateWorkflowOutput(\n schema: unknown,\n value: unknown,\n): Promise<unknown> {\n if (!schema) return value;\n\n const result = await (\n schema as {\n \"~standard\": { validate: (v: unknown) => Promise<unknown> | unknown };\n }\n )[\"~standard\"].validate(value);\n\n if (\n result &&\n typeof result === \"object\" &&\n \"issues\" in result &&\n (result as { issues: unknown }).issues\n ) {\n throw new SchemaValidationError(\n \"workflow output failed schema validation\",\n {\n issues: (result as { issues: any }).issues,\n },\n );\n }\n\n return (result as { value: unknown }).value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,kBAAkB;;;;;;;;AAkCxB,eAAsB,YACpB,QACkC;CAClC,MAAM,EAAE,YAAY,WAAW,OAAO,OAAO,WAAW;CAIxD,MAAM,UAAU,iBAAiB,OAAO,SAAS;EAC/C;EACA,WAAW;CACb,CAAC;CAID,MAAM,UAAU,OAAO,OAAO,OAAO,WAAW,CAAC,CAAC;CAClD,MAAM,WAAW,WAAW,YAAY;CACxC,MAAM,gBAAgB,WAAW,iBAAiB;CAElD,MAAM,SAAS;CACf,MAAM,YAAY,GAAG,gBAAgB,GAAG,WAAW;CAEnD,MAAM,6BAAa,IAAI,IAA4B;CACnD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,OAAO;EAAI,CACpC;CACF;CACA,OAAO,YAAY,OAAO;AAC5B;AAEA,SAAS,mBACP,YACA,YACe;CACf,IAAI,CAAC,YAAY,OAAO,WAAW,MAAM,IAAI,QAAQ;CAMrD,IACE,WAAW,QACX,WAAW,MAAM,MAAK,MAAK,EAAE,SAAS,WAAW,IAAI,GAErD,OAAO,WAAW;CAGpB,KAAK,MAAM,QAAQ,WAAW,OAAO;EACnC,MAAM,OAAO,WAAW,MAAM,KAAK;EACnC,IAAI,CAAC,QAAS,KAAK,WAAW,eAAe,KAAK,WAAW,WAC3D,OAAO,KAAK;CAEhB;CAEA,OAAO;AACT;AAEA,eAAe,uBACb,QACA,OACkB;CAClB,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,SAAS,MACb,OAGA,aAAa,SAAS,KAAK;CAE7B,IACE,UACA,OAAO,WAAW,YAClB,YAAY,UACX,OAA+B,QAEhC,MAAM,IAAI,sBACR,4CACA,EACE,QAAS,OAA2B,OACtC,CACF;CAGF,OAAQ,OAA8B;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/retry.ts"],"sourcesContent":["import type {\n RetryBackoff,\n RetryConfig,\n} from \"../contracts/workflow/retry-config.type\";\n\nexport const DEFAULT_BACKOFF_CAP_MS = 30_000;\n\nexport function resolveBackoff(\n attempt: number,\n backoff: RetryBackoff | undefined,\n): number {\n const value = (() => {\n switch (backoff) {\n case \"none\":\n return 0;\n case \"linear\":\n return attempt * 500;\n case \"exponential\":\n case undefined:\n return 500 * 2 ** (attempt - 1);\n default:\n return backoff(attempt);\n }\n })();\n\n return Math.max(0, Math.min(value, DEFAULT_BACKOFF_CAP_MS));\n}\n\nexport function isAbortError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const name = (error as { name?: unknown }).name;\n return name === \"AbortError\";\n}\n\n/**\n * Resolve the effective retry config for a step, merging per-step and\n * workflow-level defaults. `retry: false` disables retries entirely.\n */\nexport function resolveRetryConfig(\n step: { retry?: RetryConfig | false } | undefined,\n workflowDefault: RetryConfig | false | undefined,\n): RetryConfig {\n if (step?.retry === false) return { attempts: 1 };\n if (step?.retry) return step.retry;\n if (workflowDefault === false || workflowDefault === undefined) {\n return { attempts: 1 };\n }\n return workflowDefault;\n}\n"],"mappings":";AAKA,MAAa,yBAAyB;AAEtC,SAAgB,eACd,SACA,SACQ;CACR,MAAM,eAAe;EACnB,QAAQ,SAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,UACH,OAAO,UAAU;GACnB,KAAK;GACL,KAAK,QACH,OAAO,MAAM,MAAM,UAAU;GAC/B,SACE,OAAO,QAAQ,OAAO;EAC1B;CACF,
|
|
1
|
+
{"version":3,"file":"retry.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/retry.ts"],"sourcesContent":["import type {\n RetryBackoff,\n RetryConfig,\n} from \"../contracts/workflow/retry-config.type\";\n\nexport const DEFAULT_BACKOFF_CAP_MS = 30_000;\n\nexport function resolveBackoff(\n attempt: number,\n backoff: RetryBackoff | undefined,\n): number {\n const value = (() => {\n switch (backoff) {\n case \"none\":\n return 0;\n case \"linear\":\n return attempt * 500;\n case \"exponential\":\n case undefined:\n return 500 * 2 ** (attempt - 1);\n default:\n return backoff(attempt);\n }\n })();\n\n return Math.max(0, Math.min(value, DEFAULT_BACKOFF_CAP_MS));\n}\n\nexport function isAbortError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const name = (error as { name?: unknown }).name;\n return name === \"AbortError\";\n}\n\n/**\n * Resolve the effective retry config for a step, merging per-step and\n * workflow-level defaults. `retry: false` disables retries entirely.\n */\nexport function resolveRetryConfig(\n step: { retry?: RetryConfig | false } | undefined,\n workflowDefault: RetryConfig | false | undefined,\n): RetryConfig {\n if (step?.retry === false) return { attempts: 1 };\n if (step?.retry) return step.retry;\n if (workflowDefault === false || workflowDefault === undefined) {\n return { attempts: 1 };\n }\n return workflowDefault;\n}\n"],"mappings":";AAKA,MAAa,yBAAyB;AAEtC,SAAgB,eACd,SACA,SACQ;CACR,MAAM,eAAe;EACnB,QAAQ,SAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,UACH,OAAO,UAAU;GACnB,KAAK;GACL,KAAK,QACH,OAAO,MAAM,MAAM,UAAU;GAC/B,SACE,OAAO,QAAQ,OAAO;EAC1B;CACF,GAAG;CAEH,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,sBAAsB,CAAC;AAC5D;AAEA,SAAgB,aAAa,OAAyB;CACpD,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAEhD,OADc,MAA6B,SAC3B;AAClB;;;;;AAMA,SAAgB,mBACd,MACA,iBACa;CACb,IAAI,MAAM,UAAU,OAAO,OAAO,EAAE,UAAU,EAAE;CAChD,IAAI,MAAM,OAAO,OAAO,KAAK;CAC7B,IAAI,oBAAoB,SAAS,oBAAoB,QACnD,OAAO,EAAE,UAAU,EAAE;CAEvB,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/router.ts"],"sourcesContent":["import type { NextStepResult } from \"../contracts/workflow/next-step-result.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowDefinition } from \"../contracts/workflow/workflow.contract\";\nimport { RoutingError } from \"../errors\";\n\n/**\n * Resolve the next step to run after `step` completes. Tries\n * step-level `nextStep` first, then workflow-level, then falls\n * through (returns `undefined`, engine picks the next declared step).\n *\n * Throws `RoutingError` when either callback throws — routing is\n * authoritative, so a broken router terminates the workflow instead\n * of being retried.\n */\nexport async function resolveNextStep<T>(params: {\n step: StepDefinition;\n definition: WorkflowDefinition<any, T, any, any>;\n ctx: WorkflowContext;\n}): Promise<\"end\" | string | undefined> {\n const { step, definition, ctx } = params;\n\n if (step.nextStep) {\n let outcome: NextStepResult;\n try {\n outcome = await step.nextStep(ctx);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" nextStep threw`,\n { stepName: step.name, cause: err },\n );\n }\n const mapped = mapNextStep(outcome);\n if (mapped !== undefined) return mapped;\n }\n\n if (definition.nextStep) {\n let outcome: NextStepResult;\n try {\n outcome = await definition.nextStep(step.name, ctx);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": workflow-level nextStep threw after \"${step.name}\"`,\n { stepName: step.name, cause: err },\n );\n }\n const mapped = mapNextStep(outcome);\n if (mapped !== undefined) return mapped;\n }\n\n return undefined;\n}\n\nexport function mapNextStep(\n outcome: NextStepResult,\n): \"end\" | string | undefined {\n if (!outcome) return undefined;\n if (\"end\" in outcome && outcome.end === true) return \"end\";\n if (\"goto\" in outcome && typeof outcome.goto === \"string\")\n return outcome.goto;\n return undefined;\n}\n\nexport function nextDeclaredStep<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n currentName: string,\n): string | null {\n const idx = definition.steps.findIndex(s => s.name === currentName);\n if (idx === -1) return null;\n return definition.steps[idx + 1]?.name ?? null;\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,eAAsB,gBAAmB,QAID;CACtC,MAAM,EAAE,MAAM,YAAY,QAAQ;CAElC,IAAI,KAAK,UAAU;EACjB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,KAAK,SAAS,GAAG;EACnC,SAAS,KAAK;GACZ,MAAM,IAAI,aACR,aAAa,WAAW,KAAK,WAAW,KAAK,KAAK,mBAClD;IAAE,UAAU,KAAK;IAAM,OAAO;GAAI,CACpC;EACF;EACA,MAAM,SAAS,YAAY,OAAO;EAClC,IAAI,WAAW,QAAW,OAAO;CACnC;CAEA,IAAI,WAAW,UAAU;EACvB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,WAAW,SAAS,KAAK,MAAM,GAAG;EACpD,SAAS,KAAK;GACZ,MAAM,IAAI,aACR,aAAa,WAAW,KAAK,0CAA0C,KAAK,KAAK,IACjF;IAAE,UAAU,KAAK;IAAM,OAAO;GAAI,CACpC;EACF;EACA,MAAM,SAAS,YAAY,OAAO;EAClC,IAAI,WAAW,QAAW,OAAO;CACnC;AAGF;AAEA,SAAgB,YACd,SAC4B;CAC5B,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,SAAS,WAAW,QAAQ,QAAQ,MAAM,OAAO;CACrD,IAAI,UAAU,WAAW,OAAO,QAAQ,SAAS,UAC/C,OAAO,QAAQ;AAEnB;AAEA,SAAgB,iBACd,YACA,aACe;CACf,MAAM,MAAM,WAAW,MAAM,WAAU,MAAK,EAAE,SAAS,WAAW;CAClE,IAAI,QAAQ,IAAI,OAAO;CACvB,OAAO,WAAW,MAAM,MAAM,
|
|
1
|
+
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/router.ts"],"sourcesContent":["import type { NextStepResult } from \"../contracts/workflow/next-step-result.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowDefinition } from \"../contracts/workflow/workflow.contract\";\nimport { RoutingError } from \"../errors\";\n\n/**\n * Resolve the next step to run after `step` completes. Tries\n * step-level `nextStep` first, then workflow-level, then falls\n * through (returns `undefined`, engine picks the next declared step).\n *\n * Throws `RoutingError` when either callback throws — routing is\n * authoritative, so a broken router terminates the workflow instead\n * of being retried.\n */\nexport async function resolveNextStep<T>(params: {\n step: StepDefinition;\n definition: WorkflowDefinition<any, T, any, any>;\n ctx: WorkflowContext;\n}): Promise<\"end\" | string | undefined> {\n const { step, definition, ctx } = params;\n\n if (step.nextStep) {\n let outcome: NextStepResult;\n try {\n outcome = await step.nextStep(ctx);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": step \"${step.name}\" nextStep threw`,\n { stepName: step.name, cause: err },\n );\n }\n const mapped = mapNextStep(outcome);\n if (mapped !== undefined) return mapped;\n }\n\n if (definition.nextStep) {\n let outcome: NextStepResult;\n try {\n outcome = await definition.nextStep(step.name, ctx);\n } catch (err) {\n throw new RoutingError(\n `workflow \"${definition.name}\": workflow-level nextStep threw after \"${step.name}\"`,\n { stepName: step.name, cause: err },\n );\n }\n const mapped = mapNextStep(outcome);\n if (mapped !== undefined) return mapped;\n }\n\n return undefined;\n}\n\nexport function mapNextStep(\n outcome: NextStepResult,\n): \"end\" | string | undefined {\n if (!outcome) return undefined;\n if (\"end\" in outcome && outcome.end === true) return \"end\";\n if (\"goto\" in outcome && typeof outcome.goto === \"string\")\n return outcome.goto;\n return undefined;\n}\n\nexport function nextDeclaredStep<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n currentName: string,\n): string | null {\n const idx = definition.steps.findIndex(s => s.name === currentName);\n if (idx === -1) return null;\n return definition.steps[idx + 1]?.name ?? null;\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,eAAsB,gBAAmB,QAID;CACtC,MAAM,EAAE,MAAM,YAAY,QAAQ;CAElC,IAAI,KAAK,UAAU;EACjB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,KAAK,SAAS,GAAG;EACnC,SAAS,KAAK;GACZ,MAAM,IAAI,aACR,aAAa,WAAW,KAAK,WAAW,KAAK,KAAK,mBAClD;IAAE,UAAU,KAAK;IAAM,OAAO;GAAI,CACpC;EACF;EACA,MAAM,SAAS,YAAY,OAAO;EAClC,IAAI,WAAW,QAAW,OAAO;CACnC;CAEA,IAAI,WAAW,UAAU;EACvB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,WAAW,SAAS,KAAK,MAAM,GAAG;EACpD,SAAS,KAAK;GACZ,MAAM,IAAI,aACR,aAAa,WAAW,KAAK,0CAA0C,KAAK,KAAK,IACjF;IAAE,UAAU,KAAK;IAAM,OAAO;GAAI,CACpC;EACF;EACA,MAAM,SAAS,YAAY,OAAO;EAClC,IAAI,WAAW,QAAW,OAAO;CACnC;AAGF;AAEA,SAAgB,YACd,SAC4B;CAC5B,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,SAAS,WAAW,QAAQ,QAAQ,MAAM,OAAO;CACrD,IAAI,UAAU,WAAW,OAAO,QAAQ,SAAS,UAC/C,OAAO,QAAQ;AAEnB;AAEA,SAAgB,iBACd,YACA,aACe;CACf,MAAM,MAAM,WAAW,MAAM,WAAU,MAAK,EAAE,SAAS,WAAW;CAClE,IAAI,QAAQ,IAAI,OAAO;CACvB,OAAO,WAAW,MAAM,MAAM,IAAI,QAAQ;AAC5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signature.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/signature.ts"],"mappings":";;;iBAoCgB,gBAAA,
|
|
1
|
+
{"version":3,"file":"signature.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/signature.ts"],"mappings":";;;iBAoCgB,gBAAA,GAAA,CAAoB,UAAA,EAAY,kBAAkB,MAAM,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signature.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/signature.ts"],"sourcesContent":["import type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowDefinition } from \"../contracts/workflow/workflow.contract\";\n\nfunction stepFingerprint(step: StepDefinition): unknown {\n const tag = step.parallel\n ? \"parallel\"\n : step.agent\n ? \"agent\"\n : step.run\n ? \"run\"\n : \"empty\";\n\n const agentName = step.agent?.name;\n\n return {\n n: step.name,\n t: tag,\n a: agentName,\n c: step.parallel?.map(child => stepFingerprint(child)) ?? null,\n };\n}\n\n/**\n * FNV-1a 32-bit hash — deterministic, no crypto dependency.\n */\nfunction hash(input: string): string {\n let h = 0x811c9dc5;\n\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;\n }\n\n return h.toString(16).padStart(8, \"0\");\n}\n\nexport function computeSignature<T>(definition: WorkflowDefinition<any, T, any, any>): string {\n const fingerprint = {\n n: definition.name,\n v: definition.version ?? null,\n s: definition.steps.map(step => stepFingerprint(step)),\n };\n\n return hash(JSON.stringify(fingerprint));\n}\n"],"mappings":";AAGA,SAAS,gBAAgB,MAA+B;CACtD,MAAM,MAAM,KAAK,WACb,aACA,KAAK,QACH,UACA,KAAK,MACH,QACA;CAER,MAAM,YAAY,KAAK,OAAO;CAE9B,OAAO;EACL,GAAG,KAAK;EACR,GAAG;EACH,GAAG;EACH,GAAG,KAAK,UAAU,KAAI,UAAS,gBAAgB,KAAK,CAAC,KAAK;CAC5D;AACF;;;;AAKA,SAAS,KAAK,OAAuB;CACnC,IAAI,IAAI;CAER,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,KAAK,MAAM,WAAW,CAAC;EACvB,IAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,SAAU;CACxE;CAEA,OAAO,EAAE,SAAS,EAAE,
|
|
1
|
+
{"version":3,"file":"signature.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/signature.ts"],"sourcesContent":["import type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowDefinition } from \"../contracts/workflow/workflow.contract\";\n\nfunction stepFingerprint(step: StepDefinition): unknown {\n const tag = step.parallel\n ? \"parallel\"\n : step.agent\n ? \"agent\"\n : step.run\n ? \"run\"\n : \"empty\";\n\n const agentName = step.agent?.name;\n\n return {\n n: step.name,\n t: tag,\n a: agentName,\n c: step.parallel?.map(child => stepFingerprint(child)) ?? null,\n };\n}\n\n/**\n * FNV-1a 32-bit hash — deterministic, no crypto dependency.\n */\nfunction hash(input: string): string {\n let h = 0x811c9dc5;\n\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;\n }\n\n return h.toString(16).padStart(8, \"0\");\n}\n\nexport function computeSignature<T>(definition: WorkflowDefinition<any, T, any, any>): string {\n const fingerprint = {\n n: definition.name,\n v: definition.version ?? null,\n s: definition.steps.map(step => stepFingerprint(step)),\n };\n\n return hash(JSON.stringify(fingerprint));\n}\n"],"mappings":";AAGA,SAAS,gBAAgB,MAA+B;CACtD,MAAM,MAAM,KAAK,WACb,aACA,KAAK,QACH,UACA,KAAK,MACH,QACA;CAER,MAAM,YAAY,KAAK,OAAO;CAE9B,OAAO;EACL,GAAG,KAAK;EACR,GAAG;EACH,GAAG;EACH,GAAG,KAAK,UAAU,KAAI,UAAS,gBAAgB,KAAK,CAAC,KAAK;CAC5D;AACF;;;;AAKA,SAAS,KAAK,OAAuB;CACnC,IAAI,IAAI;CAER,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,KAAK,MAAM,WAAW,CAAC;EACvB,IAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,SAAU;CACxE;CAEA,OAAO,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACvC;AAEA,SAAgB,iBAAoB,YAA0D;CAC5F,MAAM,cAAc;EAClB,GAAG,WAAW;EACd,GAAG,WAAW,WAAW;EACzB,GAAG,WAAW,MAAM,KAAI,SAAQ,gBAAgB,IAAI,CAAC;CACvD;CAEA,OAAO,KAAK,KAAK,UAAU,WAAW,CAAC;AACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/snapshot.ts"],"sourcesContent":["import { resolveDefaultSnapshotStore } from \"../config\";\nimport type { SnapshotStore } from \"../contracts/orchestrator/snapshot-store.contract\";\nimport type { StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { WorkflowSnapshot } from \"../contracts/workflow/workflow-snapshot.type\";\nimport type {\n WorkflowDefinition,\n WorkflowResumeOptions,\n} from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowDriftError, WorkflowError } from \"../errors\";\n\n/**\n * Resolve the effective {@link SnapshotStore}: the workflow's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultSnapshotStore })`.\n *\n * The global default is typed for the supervisor snapshot shape, but\n * every store impl keys purely by `runId` and round-trips whatever\n * envelope it is handed — so it serves a `WorkflowSnapshot` just as\n * well. The cast re-tags the shape at this single boundary; the\n * workflow only ever hands it a `WorkflowSnapshot`.\n */\nfunction resolveSnapshotStore<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n): SnapshotStore<WorkflowSnapshot> | undefined {\n return (\n definition.snapshotStore ??\n (resolveDefaultSnapshotStore() as SnapshotStore<WorkflowSnapshot> | undefined)\n );\n}\n\nexport type PersistParams<T> = {\n definition: WorkflowDefinition<any, T, any, any>;\n signature: string;\n runId: string;\n startedAt: string;\n input: unknown;\n state: Record<string, unknown>;\n steps: Record<string, StepSnapshot>;\n next: string | null;\n status: WorkflowSnapshot[\"status\"];\n};\n\nexport type PersistOutcome = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Write the current run's state to the configured `KVStore`. Returns\n * an outcome object instead of throwing so the engine can surface\n * persistence failures via events + logs without aborting the run.\n * Callers decide whether a failed checkpoint is fatal.\n *\n * No-op (returns `{ ok: true }`) when the workflow has no store\n * configured — the common in-memory test case.\n */\nexport async function persistSnapshot<T>(\n params: PersistParams<T>,\n): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.definition);\n\n if (!store) return { ok: true };\n\n const snapshot: WorkflowSnapshot = {\n runId: params.runId,\n workflowName: params.definition.name,\n signature: params.signature,\n version: params.definition.version,\n input: params.input,\n state: { ...params.state },\n steps: { ...params.steps },\n next: params.next,\n status: params.status,\n startedAt: params.startedAt,\n savedAt: new Date().toISOString(),\n };\n\n try {\n await store.save(snapshot);\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err };\n }\n}\n\n/**\n * Load a prior run's snapshot from the store and run the drift\n * check. Throws `WorkflowError` when no snapshot exists, and\n * `WorkflowDriftError` when the stored signature doesn't match the\n * current definition (unless `force` is set).\n */\nexport async function loadSnapshotForResume<T>(params: {\n definition: WorkflowDefinition<any, T, any, any>;\n signature: string;\n runId: string;\n options?: WorkflowResumeOptions;\n}): Promise<WorkflowSnapshot> {\n const store = resolveSnapshotStore(params.definition);\n\n if (!store) {\n throw new WorkflowError(\n `workflow \"${params.definition.name}\" has no store configured — set \\`snapshotStore\\` on the definition or call \\`ai.config({ defaultSnapshotStore })\\` at boot before calling resume()`,\n );\n }\n\n const snap = (await store.load(params.runId)) ?? null;\n\n if (!snap) {\n throw new WorkflowError(\n `workflow \"${params.definition.name}\": no snapshot for runId \"${params.runId}\"`,\n );\n }\n\n if (!params.options?.force && snap.signature !== params.signature) {\n throw new WorkflowDriftError(\n `workflow \"${params.definition.name}\" signature drift on resume`,\n {\n savedSignature: snap.signature,\n currentSignature: params.signature,\n runId: params.runId,\n },\n );\n }\n\n return snap;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,SAAS,qBACP,YAC6C;CAC7C,OACE,WAAW,iBACV,4BAA4B;AAEjC;;;;;;;;;;AAyBA,eAAsB,gBACpB,QACyB;CACzB,MAAM,QAAQ,qBAAqB,OAAO,UAAU;CAEpD,IAAI,CAAC,OAAO,OAAO,EAAE,IAAI,KAAK;CAE9B,MAAM,WAA6B;EACjC,OAAO,OAAO;EACd,cAAc,OAAO,WAAW;EAChC,WAAW,OAAO;EAClB,SAAS,OAAO,WAAW;EAC3B,OAAO,OAAO;EACd,OAAO,EAAE,GAAG,OAAO,MAAM;EACzB,OAAO,EAAE,GAAG,OAAO,MAAM;EACzB,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,0BAAS,IAAI,KAAK,
|
|
1
|
+
{"version":3,"file":"snapshot.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/snapshot.ts"],"sourcesContent":["import { resolveDefaultSnapshotStore } from \"../config\";\nimport type { SnapshotStore } from \"../contracts/orchestrator/snapshot-store.contract\";\nimport type { StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { WorkflowSnapshot } from \"../contracts/workflow/workflow-snapshot.type\";\nimport type {\n WorkflowDefinition,\n WorkflowResumeOptions,\n} from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowDriftError, WorkflowError } from \"../errors\";\n\n/**\n * Resolve the effective {@link SnapshotStore}: the workflow's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultSnapshotStore })`.\n *\n * The global default is typed for the supervisor snapshot shape, but\n * every store impl keys purely by `runId` and round-trips whatever\n * envelope it is handed — so it serves a `WorkflowSnapshot` just as\n * well. The cast re-tags the shape at this single boundary; the\n * workflow only ever hands it a `WorkflowSnapshot`.\n */\nfunction resolveSnapshotStore<T>(\n definition: WorkflowDefinition<any, T, any, any>,\n): SnapshotStore<WorkflowSnapshot> | undefined {\n return (\n definition.snapshotStore ??\n (resolveDefaultSnapshotStore() as SnapshotStore<WorkflowSnapshot> | undefined)\n );\n}\n\nexport type PersistParams<T> = {\n definition: WorkflowDefinition<any, T, any, any>;\n signature: string;\n runId: string;\n startedAt: string;\n input: unknown;\n state: Record<string, unknown>;\n steps: Record<string, StepSnapshot>;\n next: string | null;\n status: WorkflowSnapshot[\"status\"];\n};\n\nexport type PersistOutcome = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Write the current run's state to the configured `KVStore`. Returns\n * an outcome object instead of throwing so the engine can surface\n * persistence failures via events + logs without aborting the run.\n * Callers decide whether a failed checkpoint is fatal.\n *\n * No-op (returns `{ ok: true }`) when the workflow has no store\n * configured — the common in-memory test case.\n */\nexport async function persistSnapshot<T>(\n params: PersistParams<T>,\n): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.definition);\n\n if (!store) return { ok: true };\n\n const snapshot: WorkflowSnapshot = {\n runId: params.runId,\n workflowName: params.definition.name,\n signature: params.signature,\n version: params.definition.version,\n input: params.input,\n state: { ...params.state },\n steps: { ...params.steps },\n next: params.next,\n status: params.status,\n startedAt: params.startedAt,\n savedAt: new Date().toISOString(),\n };\n\n try {\n await store.save(snapshot);\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err };\n }\n}\n\n/**\n * Load a prior run's snapshot from the store and run the drift\n * check. Throws `WorkflowError` when no snapshot exists, and\n * `WorkflowDriftError` when the stored signature doesn't match the\n * current definition (unless `force` is set).\n */\nexport async function loadSnapshotForResume<T>(params: {\n definition: WorkflowDefinition<any, T, any, any>;\n signature: string;\n runId: string;\n options?: WorkflowResumeOptions;\n}): Promise<WorkflowSnapshot> {\n const store = resolveSnapshotStore(params.definition);\n\n if (!store) {\n throw new WorkflowError(\n `workflow \"${params.definition.name}\" has no store configured — set \\`snapshotStore\\` on the definition or call \\`ai.config({ defaultSnapshotStore })\\` at boot before calling resume()`,\n );\n }\n\n const snap = (await store.load(params.runId)) ?? null;\n\n if (!snap) {\n throw new WorkflowError(\n `workflow \"${params.definition.name}\": no snapshot for runId \"${params.runId}\"`,\n );\n }\n\n if (!params.options?.force && snap.signature !== params.signature) {\n throw new WorkflowDriftError(\n `workflow \"${params.definition.name}\" signature drift on resume`,\n {\n savedSignature: snap.signature,\n currentSignature: params.signature,\n runId: params.runId,\n },\n );\n }\n\n return snap;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,SAAS,qBACP,YAC6C;CAC7C,OACE,WAAW,iBACV,4BAA4B;AAEjC;;;;;;;;;;AAyBA,eAAsB,gBACpB,QACyB;CACzB,MAAM,QAAQ,qBAAqB,OAAO,UAAU;CAEpD,IAAI,CAAC,OAAO,OAAO,EAAE,IAAI,KAAK;CAE9B,MAAM,WAA6B;EACjC,OAAO,OAAO;EACd,cAAc,OAAO,WAAW;EAChC,WAAW,OAAO;EAClB,SAAS,OAAO,WAAW;EAC3B,OAAO,OAAO;EACd,OAAO,EAAE,GAAG,OAAO,MAAM;EACzB,OAAO,EAAE,GAAG,OAAO,MAAM;EACzB,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,0BAAS,IAAI,KAAK,GAAE,YAAY;CAClC;CAEA,IAAI;EACF,MAAM,MAAM,KAAK,QAAQ;EACzB,OAAO,EAAE,IAAI,KAAK;CACpB,SAAS,KAAK;EACZ,OAAO;GAAE,IAAI;GAAO,OAAO;EAAI;CACjC;AACF;;;;;;;AAQA,eAAsB,sBAAyB,QAKjB;CAC5B,MAAM,QAAQ,qBAAqB,OAAO,UAAU;CAEpD,IAAI,CAAC,OACH,MAAM,IAAI,cACR,aAAa,OAAO,WAAW,KAAK,oJACtC;CAGF,MAAM,OAAQ,MAAM,MAAM,KAAK,OAAO,KAAK,KAAM;CAEjD,IAAI,CAAC,MACH,MAAM,IAAI,cACR,aAAa,OAAO,WAAW,KAAK,4BAA4B,OAAO,MAAM,EAC/E;CAGF,IAAI,CAAC,OAAO,SAAS,SAAS,KAAK,cAAc,OAAO,WACtD,MAAM,IAAI,mBACR,aAAa,OAAO,WAAW,KAAK,8BACpC;EACE,gBAAgB,KAAK;EACrB,kBAAkB,OAAO;EACzB,OAAO,OAAO;CAChB,CACF;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"step-runner.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/step-runner.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Logger } from \"@warlock.js/logger\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { AgentReport } from \"../contracts/result/execution-report.type\";\nimport type { AttemptEntry, StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { RetryConfig } from \"../contracts/workflow/retry-config.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowEventHandlers } from \"../contracts/workflow/workflow.contract\";\nimport { mergeUsage } from \"../utils/compute-cost\";\nimport { withoutRunFrame, withRunFrame } from \"../utils/run-context\";\nimport {\n AIError,\n SchemaValidationError,\n StepFailedError,\n WorkflowCancelledError,\n WorkflowError,\n} from \"../errors\";\nimport { createCancelledError, sleep } from \"./cancellation\";\nimport type { WorkflowEventSink } from \"./emitter\";\nimport { isAbortError, resolveBackoff, resolveRetryConfig } from \"./retry\";\nimport { cloneState, deepFreeze } from \"./state\";\n\n/**\n * Mutable snapshot used by the step runner — finalized (deep-frozen)\n * by the engine before being written to `ctx.steps` / `report.steps`.\n */\nexport type MutableStepSnapshot = {\n output: unknown;\n skipped: boolean;\n status: \"completed\" | \"skipped\" | \"failed\";\n startedAt: string;\n endedAt: string;\n duration: number;\n attempts: number;\n attemptHistory: AttemptEntry[];\n error?: AIError;\n state: Record<string, unknown>;\n executionResult?: unknown;\n agentReport?: AgentReport;\n agentUsage?: Usage;\n children?: BaseReport[];\n steps?: Record<string, StepSnapshot>;\n};\n\n/**\n * Narrow an `executionResult` to an `AgentResult` when the step ran\n * an agent. Custom `run` steps return arbitrary values, so the\n * `type: \"agent\"` discriminant keeps us honest.\n */\nfunction asAgentResult(result: unknown): AgentResult<unknown> | undefined {\n if (!result || typeof result !== \"object\") return undefined;\n if ((result as { type?: unknown }).type !== \"agent\") return undefined;\n return result as AgentResult<unknown>;\n}\n\nexport type ExecuteStepParams = {\n step: StepDefinition;\n state: Record<string, unknown>;\n emitter: WorkflowEventSink;\n executionHandlers?: WorkflowEventHandlers;\n logger: Logger;\n logModule: string;\n signal?: AbortSignal;\n buildContext: (current?: {\n state: Record<string, unknown>;\n agentResult?: unknown;\n }) => WorkflowContext;\n usage: Usage;\n workflowDefaultRetry?: RetryConfig | false;\n /**\n * The enclosing workflow's own run-id — the `rootRunId` / `parentRunId`\n * a `run` step's ambient {@link RunFrame} stamps onto anything it\n * captures. `stampReportLineage`'s single authoritative pass (run once\n * on the assembled workflow report) is what makes the exact value here\n * safe to be provisional.\n */\n runId: string;\n /** Propagated onto anything a `run` step's ambient run-frame captures. */\n sessionId?: string;\n};\n\n/**\n * Drive one step's full lifecycle — skip evaluation, parallel\n * dispatch, retry loop around before → run|agent → output → after.\n * Returns a mutable snapshot; the engine deep-freezes it before\n * exposing.\n */\nexport async function executeStep(params: ExecuteStepParams): Promise<MutableStepSnapshot> {\n const { step, emitter, executionHandlers, logger, logModule, signal } = params;\n const startedAt = new Date().toISOString();\n const stepStartPerf = performance.now();\n\n params.step.on?.starting?.({ step: step.name });\n emitter.emit(\"workflow.step.starting\", { step: step.name }, executionHandlers);\n logger.debug(logModule, \"step.starting\", `${step.name} step starting`, {\n step: step.name,\n });\n\n const stepState: Record<string, unknown> = cloneState(params.state);\n\n // SKIP\n try {\n if (step.skip) {\n const shouldSkip = await step.skip(params.buildContext({ state: stepState }));\n if (shouldSkip) {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - stepStartPerf;\n emitter.emit(\"workflow.step.skipped\", { step: step.name }, executionHandlers);\n logger.debug(logModule, \"step.skipped\", `${step.name} step skipped`, {\n step: step.name,\n });\n\n return {\n output: undefined,\n skipped: true,\n status: \"skipped\",\n startedAt,\n endedAt,\n duration,\n attempts: 0,\n attemptHistory: [],\n state: stepState,\n };\n }\n }\n } catch (err) {\n return buildFailedSnapshot(step, stepState, startedAt, stepStartPerf, 1, [\n failedAttempt(1, err, new Date().toISOString(), performance.now()),\n ]);\n }\n\n // PARALLEL\n if (step.parallel && step.parallel.length > 0) {\n return runParallelStep({\n ...params,\n step,\n stepState,\n startedAt,\n startPerf: stepStartPerf,\n });\n }\n\n const retryConfig = resolveRetryConfig(step, params.workflowDefaultRetry);\n\n const attempts: AttemptEntry[] = [];\n const totalAttempts = Math.max(1, retryConfig.attempts ?? 1);\n let lastError: unknown;\n let executionResult: unknown;\n let output: unknown;\n let succeeded = false;\n // Reports a `run` step's callback captured via its ambient run-frame\n // (see below) — reset each attempt so a failed attempt's captures\n // never bleed into a later retry's snapshot.\n let stepChildren: BaseReport[] | undefined;\n\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n if (signal?.aborted) throw createCancelledError(signal);\n\n const attemptStart = new Date().toISOString();\n const attemptStartPerf = performance.now();\n try {\n // Fresh deep-clone per attempt — retries restart cleanly.\n const attemptState: Record<string, unknown> = cloneState(params.state);\n\n if (step.before) {\n await step.before(params.buildContext({ state: attemptState }));\n }\n\n if (step.agent) {\n const agent = step.agent;\n const agentInput = step.input\n ? await step.input(params.buildContext({ state: attemptState }))\n : { prompt: \"\" };\n\n const { prompt, ...agentOpts } = agentInput;\n\n // Run the step's agent inside a nested frame so observe-all does NOT\n // also self-route it as a standalone trace — the workflow already\n // captures it into report.steps (explicit capture, like the supervisor).\n const result = await withoutRunFrame(() =>\n agent.execute(prompt, {\n ...agentOpts,\n signal,\n }),\n );\n\n executionResult = result;\n\n if (result.usage) {\n mergeUsage(params.usage, result.usage);\n }\n\n if (result.error) throw result.error;\n } else if (step.run) {\n // Custom `run` callbacks can call anything — an ambient RunFrame\n // (mirroring the supervisor/team/orchestrator callback pattern)\n // is the only way to observe what they invoke, since (unlike\n // `step.agent` above) there's no single known executable to\n // explicitly capture. Any `agent.execute(...)` the callback\n // invokes DIRECTLY self-attaches its report onto `runChildren`\n // via `captureChildReport` and is suppressed from also\n // self-routing as a standalone observed trace.\n const runChildren: BaseReport[] = [];\n\n try {\n executionResult = await withRunFrame(\n {\n sink: runChildren,\n rootRunId: params.runId,\n parentRunId: params.runId,\n sessionId: params.sessionId,\n },\n () => step.run!(params.buildContext({ state: attemptState })),\n );\n } finally {\n // Runs whether the callback resolved or threw — a callback that\n // calls an agent and THEN throws still gets that call's report\n // preserved on the failed snapshot (forensic trace, same intent\n // as the file's other failed-snapshot preservation). Unconditional\n // reassign (not a conditional-append): a retry whose callback\n // captures nothing must clear a prior failed attempt's captures.\n stepChildren = runChildren.length > 0 ? runChildren : undefined;\n\n for (const child of runChildren) {\n mergeUsage(params.usage, child.usage);\n }\n }\n }\n\n if (step.output) {\n const extracted = await step.output.extract(\n params.buildContext({\n state: attemptState,\n agentResult: executionResult,\n }),\n );\n output = await validateSchema(step.output.schema, extracted);\n } else {\n output = undefined;\n }\n\n if (step.after) {\n await step.after(\n params.buildContext({\n state: attemptState,\n agentResult: executionResult,\n }),\n );\n }\n\n Object.assign(stepState, attemptState);\n\n attempts.push({\n index: attempt,\n startedAt: attemptStart,\n endedAt: new Date().toISOString(),\n duration: performance.now() - attemptStartPerf,\n status: \"success\",\n });\n succeeded = true;\n break;\n } catch (err) {\n if (isAbortError(err) || err instanceof WorkflowCancelledError) {\n throw createCancelledError(signal);\n }\n\n attempts.push({\n index: attempt,\n startedAt: attemptStart,\n endedAt: new Date().toISOString(),\n duration: performance.now() - attemptStartPerf,\n status: \"failed\",\n error: toAIError(err),\n });\n\n lastError = err;\n\n const shouldRetry =\n attempt < totalAttempts &&\n (retryConfig.retryOn ? retryConfig.retryOn(err, attempt) !== false : true);\n\n if (!shouldRetry) break;\n\n emitter.emit(\n \"workflow.step.retrying\",\n {\n step: step.name,\n attempt: attempt + 1,\n totalAttempts,\n lastError: err,\n },\n params.executionHandlers,\n );\n\n step.on?.retrying?.({\n step: step.name,\n attempt: attempt + 1,\n totalAttempts,\n lastError: err,\n });\n\n logger.warn(logModule, \"step.retrying\", `${step.name} step retrying`, {\n step: step.name,\n attempt: attempt + 1,\n });\n\n retryConfig.onRetry?.(attempt + 1, err);\n\n const delay = resolveBackoff(attempt, retryConfig.backoff);\n if (delay > 0) await sleep(delay, signal);\n }\n }\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - stepStartPerf;\n\n if (!succeeded) {\n const aiError = toAIError(lastError);\n const stepError = new StepFailedError(\n `step \"${step.name}\" failed after ${attempts.length} attempt(s): ${aiError.message}`,\n { stepName: step.name, attempts: attempts.length, cause: aiError },\n );\n\n emitter.emit(\n \"workflow.step.failed\",\n { step: step.name, error: stepError, attempts: attempts.length },\n params.executionHandlers,\n );\n\n step.on?.failed?.({\n step: step.name,\n error: stepError,\n attempts: attempts.length,\n });\n\n logger.error(logModule, \"step.failed\", `${step.name} step failed`, {\n step: step.name,\n attempts: attempts.length,\n code: stepError.code,\n });\n\n const failedAgentResult = asAgentResult(executionResult);\n return {\n output: undefined,\n skipped: false,\n status: \"failed\",\n startedAt,\n endedAt,\n duration,\n attempts: attempts.length,\n attemptHistory: attempts,\n error: stepError,\n state: stepState,\n executionResult:\n executionResult && typeof executionResult === \"object\" ? executionResult : undefined,\n agentReport: failedAgentResult?.report,\n agentUsage: failedAgentResult?.usage,\n children: stepChildren,\n };\n }\n\n emitter.emit(\n \"workflow.step.completed\",\n { step: step.name, output, duration },\n params.executionHandlers,\n );\n step.on?.completed?.({ step: step.name, output, duration });\n logger.debug(logModule, \"step.completed\", \"step completed\", {\n step: step.name,\n duration,\n });\n\n const completedAgentResult = asAgentResult(executionResult);\n return {\n output,\n skipped: false,\n status: \"completed\",\n startedAt,\n endedAt,\n duration,\n attempts: attempts.length,\n attemptHistory: attempts,\n state: stepState,\n executionResult:\n executionResult && typeof executionResult === \"object\" ? executionResult : undefined,\n agentReport: completedAgentResult?.report,\n agentUsage: completedAgentResult?.usage,\n children: stepChildren,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Parallel runner\n// ---------------------------------------------------------------------------\n\ntype ParallelParams = ExecuteStepParams & {\n stepState: Record<string, unknown>;\n startedAt: string;\n startPerf: number;\n};\n\nasync function runParallelStep(params: ParallelParams): Promise<MutableStepSnapshot> {\n const { step, emitter, executionHandlers, logger, logModule, signal } = params;\n\n const sharedState = params.stepState;\n const childSnapshots: Record<string, StepSnapshot> = {};\n let firstError: AIError | undefined;\n\n const results = await Promise.all(\n (step.parallel ?? []).map(async (child) => {\n const snap = await executeStep({\n step: child,\n state: sharedState,\n emitter,\n executionHandlers,\n logger,\n logModule,\n signal,\n buildContext: params.buildContext,\n usage: params.usage,\n runId: params.runId,\n sessionId: params.sessionId,\n });\n\n return { child, snap };\n }),\n );\n\n // Merge each child's resulting state into the shared parent state in\n // DECLARATION order — not completion order. Every child cloned the\n // same initial `sharedState` synchronously at dispatch, so the merge\n // here is the only thing that decides conflicting keys; `Promise.all`\n // preserves input order in `results`, so a key written by multiple\n // children deterministically resolves to the last-declared child's\n // value regardless of which settled first (C3). An optional\n // `mergeState` reducer overrides this per key for advanced workflows.\n for (const { child, snap } of results) {\n childSnapshots[child.name] = finalizeSnapshot(snap);\n\n if (step.mergeState) {\n step.mergeState(sharedState, snap.state, child.name);\n } else {\n Object.assign(sharedState, snap.state);\n }\n\n if (snap.status === \"failed\" && !firstError && snap.error) {\n firstError = snap.error;\n }\n }\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - params.startPerf;\n\n let output: unknown;\n\n if (step.output) {\n try {\n const ctx = params.buildContext({ state: sharedState });\n const ctxWithChildren = {\n ...ctx,\n steps: {\n ...ctx.steps,\n [step.name]: {\n ...(childSnapshots as unknown as StepSnapshot),\n steps: childSnapshots,\n status: firstError ? \"failed\" : \"completed\",\n } as StepSnapshot,\n } as Readonly<Record<string, StepSnapshot>>,\n };\n\n const extracted = await step.output.extract(ctxWithChildren);\n output = await validateSchema(step.output.schema, extracted);\n } catch (err) {\n firstError = firstError ?? toAIError(err);\n }\n }\n\n const status: \"completed\" | \"failed\" = firstError ? \"failed\" : \"completed\";\n\n if (status === \"completed\") {\n emitter.emit(\n \"workflow.step.completed\",\n { step: step.name, output, duration },\n executionHandlers,\n );\n step.on?.completed?.({ step: step.name, output, duration });\n } else {\n emitter.emit(\n \"workflow.step.failed\",\n { step: step.name, error: firstError!, attempts: 1 },\n executionHandlers,\n );\n step.on?.failed?.({ step: step.name, error: firstError!, attempts: 1 });\n }\n\n return {\n output,\n skipped: false,\n status,\n startedAt: params.startedAt,\n endedAt,\n duration,\n attempts: 1,\n attemptHistory: [],\n error: firstError,\n state: sharedState,\n steps: childSnapshots,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nexport function finalizeSnapshot(snap: MutableStepSnapshot): StepSnapshot {\n return Object.freeze({\n output: snap.output,\n skipped: snap.skipped,\n status: snap.status,\n startedAt: snap.startedAt,\n endedAt: snap.endedAt,\n duration: snap.duration,\n attempts: snap.attempts,\n attemptHistory: snap.attemptHistory,\n error: snap.error,\n state: deepFreeze(cloneState(snap.state)),\n executionResult: snap.executionResult as StepSnapshot[\"executionResult\"],\n agentReport: snap.agentReport,\n agentUsage: snap.agentUsage,\n children: snap.children,\n steps: snap.steps,\n }) as StepSnapshot;\n}\n\nfunction buildFailedSnapshot(\n step: StepDefinition,\n state: Record<string, unknown>,\n startedAt: string,\n startPerf: number,\n attemptsCount: number,\n attemptHistory: AttemptEntry[],\n): MutableStepSnapshot {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - startPerf;\n const lastErr = attemptHistory[attemptHistory.length - 1]?.error;\n const wrapped = lastErr\n ? new StepFailedError(`step \"${step.name}\" skip threw: ${lastErr.message}`, {\n stepName: step.name,\n attempts: attemptsCount,\n cause: lastErr,\n })\n : new StepFailedError(`step \"${step.name}\" failed`, {\n stepName: step.name,\n attempts: attemptsCount,\n });\n\n return {\n output: undefined,\n skipped: false,\n status: \"failed\",\n startedAt,\n endedAt,\n duration,\n attempts: attemptsCount,\n attemptHistory,\n error: wrapped,\n state,\n };\n}\n\nfunction failedAttempt(\n index: number,\n err: unknown,\n startedAt: string,\n startPerf: number,\n): AttemptEntry {\n return {\n index,\n startedAt,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n status: \"failed\",\n error: toAIError(err),\n };\n}\n\nexport function toAIError(err: unknown): AIError {\n if (err instanceof AIError) return err;\n if (err instanceof Error) return new WorkflowError(err.message, { cause: err });\n return new WorkflowError(String(err));\n}\n\nasync function validateSchema(\n schema: StandardSchemaV1<unknown> | undefined,\n value: unknown,\n): Promise<unknown> {\n if (!schema) return value;\n const result = await schema[\"~standard\"].validate(value);\n\n if (\"issues\" in result && result.issues) {\n throw new SchemaValidationError(\"workflow step output failed schema validation\", {\n issues: result.issues,\n });\n }\n\n return (result as { value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;EACR;EACA;EACA;EACA,UAAU;EACV;EACA,OApBc,UACZ,IAAI,gBAAgB,SAAS,KAAK,KAAK,gBAAgB,QAAQ,WAAW;GACxE,UAAU,KAAK;GACf,UAAU;GACV,OAAO;EACT,CAAC,IACD,IAAI,gBAAgB,SAAS,KAAK,KAAK,WAAW;GAChD,UAAU,KAAK;GACf,UAAU;EACZ,CAAC;EAYH;CACF;AACF;AAEA,SAAS,cACP,OACA,KACA,WACA,WACc;CACd,OAAO;EACL;EACA;EACA,0BAAS,IAAI,KAAK,EAAC,CAAC,YAAY;EAChC,UAAU,YAAY,IAAI,IAAI;EAC9B,QAAQ;EACR,OAAO,UAAU,GAAG;CACtB;AACF;AAEA,SAAgB,UAAU,KAAuB;CAC/C,IAAI,eAAe,SAAS,OAAO;CACnC,IAAI,eAAe,OAAO,OAAO,IAAI,cAAc,IAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC9E,OAAO,IAAI,cAAc,OAAO,GAAG,CAAC;AACtC;AAEA,eAAe,eACb,QACA,OACkB;CAClB,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,SAAS,MAAM,OAAO,YAAY,CAAC,SAAS,KAAK;CAEvD,IAAI,YAAY,UAAU,OAAO,QAC/B,MAAM,IAAI,sBAAsB,iDAAiD,EAC/E,QAAQ,OAAO,OACjB,CAAC;CAGH,OAAQ,OAA8B;AACxC"}
|
|
1
|
+
{"version":3,"file":"step-runner.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/step-runner.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Logger } from \"@warlock.js/logger\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { AgentReport } from \"../contracts/result/execution-report.type\";\nimport type { AttemptEntry, StepSnapshot } from \"../contracts/result/step-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { RetryConfig } from \"../contracts/workflow/retry-config.type\";\nimport type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport type { WorkflowContext } from \"../contracts/workflow/workflow-context.type\";\nimport type { WorkflowEventHandlers } from \"../contracts/workflow/workflow.contract\";\nimport { mergeUsage } from \"../utils/compute-cost\";\nimport { withoutRunFrame, withRunFrame } from \"../utils/run-context\";\nimport {\n AIError,\n SchemaValidationError,\n StepFailedError,\n WorkflowCancelledError,\n WorkflowError,\n} from \"../errors\";\nimport { createCancelledError, sleep } from \"./cancellation\";\nimport type { WorkflowEventSink } from \"./emitter\";\nimport { isAbortError, resolveBackoff, resolveRetryConfig } from \"./retry\";\nimport { cloneState, deepFreeze } from \"./state\";\n\n/**\n * Mutable snapshot used by the step runner — finalized (deep-frozen)\n * by the engine before being written to `ctx.steps` / `report.steps`.\n */\nexport type MutableStepSnapshot = {\n output: unknown;\n skipped: boolean;\n status: \"completed\" | \"skipped\" | \"failed\";\n startedAt: string;\n endedAt: string;\n duration: number;\n attempts: number;\n attemptHistory: AttemptEntry[];\n error?: AIError;\n state: Record<string, unknown>;\n executionResult?: unknown;\n agentReport?: AgentReport;\n agentUsage?: Usage;\n children?: BaseReport[];\n steps?: Record<string, StepSnapshot>;\n};\n\n/**\n * Narrow an `executionResult` to an `AgentResult` when the step ran\n * an agent. Custom `run` steps return arbitrary values, so the\n * `type: \"agent\"` discriminant keeps us honest.\n */\nfunction asAgentResult(result: unknown): AgentResult<unknown> | undefined {\n if (!result || typeof result !== \"object\") return undefined;\n if ((result as { type?: unknown }).type !== \"agent\") return undefined;\n return result as AgentResult<unknown>;\n}\n\nexport type ExecuteStepParams = {\n step: StepDefinition;\n state: Record<string, unknown>;\n emitter: WorkflowEventSink;\n executionHandlers?: WorkflowEventHandlers;\n logger: Logger;\n logModule: string;\n signal?: AbortSignal;\n buildContext: (current?: {\n state: Record<string, unknown>;\n agentResult?: unknown;\n }) => WorkflowContext;\n usage: Usage;\n workflowDefaultRetry?: RetryConfig | false;\n /**\n * The enclosing workflow's own run-id — the `rootRunId` / `parentRunId`\n * a `run` step's ambient {@link RunFrame} stamps onto anything it\n * captures. `stampReportLineage`'s single authoritative pass (run once\n * on the assembled workflow report) is what makes the exact value here\n * safe to be provisional.\n */\n runId: string;\n /** Propagated onto anything a `run` step's ambient run-frame captures. */\n sessionId?: string;\n};\n\n/**\n * Drive one step's full lifecycle — skip evaluation, parallel\n * dispatch, retry loop around before → run|agent → output → after.\n * Returns a mutable snapshot; the engine deep-freezes it before\n * exposing.\n */\nexport async function executeStep(params: ExecuteStepParams): Promise<MutableStepSnapshot> {\n const { step, emitter, executionHandlers, logger, logModule, signal } = params;\n const startedAt = new Date().toISOString();\n const stepStartPerf = performance.now();\n\n params.step.on?.starting?.({ step: step.name });\n emitter.emit(\"workflow.step.starting\", { step: step.name }, executionHandlers);\n logger.debug(logModule, \"step.starting\", `${step.name} step starting`, {\n step: step.name,\n });\n\n const stepState: Record<string, unknown> = cloneState(params.state);\n\n // SKIP\n try {\n if (step.skip) {\n const shouldSkip = await step.skip(params.buildContext({ state: stepState }));\n if (shouldSkip) {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - stepStartPerf;\n emitter.emit(\"workflow.step.skipped\", { step: step.name }, executionHandlers);\n logger.debug(logModule, \"step.skipped\", `${step.name} step skipped`, {\n step: step.name,\n });\n\n return {\n output: undefined,\n skipped: true,\n status: \"skipped\",\n startedAt,\n endedAt,\n duration,\n attempts: 0,\n attemptHistory: [],\n state: stepState,\n };\n }\n }\n } catch (err) {\n return buildFailedSnapshot(step, stepState, startedAt, stepStartPerf, 1, [\n failedAttempt(1, err, new Date().toISOString(), performance.now()),\n ]);\n }\n\n // PARALLEL\n if (step.parallel && step.parallel.length > 0) {\n return runParallelStep({\n ...params,\n step,\n stepState,\n startedAt,\n startPerf: stepStartPerf,\n });\n }\n\n const retryConfig = resolveRetryConfig(step, params.workflowDefaultRetry);\n\n const attempts: AttemptEntry[] = [];\n const totalAttempts = Math.max(1, retryConfig.attempts ?? 1);\n let lastError: unknown;\n let executionResult: unknown;\n let output: unknown;\n let succeeded = false;\n // Reports a `run` step's callback captured via its ambient run-frame\n // (see below) — reset each attempt so a failed attempt's captures\n // never bleed into a later retry's snapshot.\n let stepChildren: BaseReport[] | undefined;\n\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n if (signal?.aborted) throw createCancelledError(signal);\n\n const attemptStart = new Date().toISOString();\n const attemptStartPerf = performance.now();\n try {\n // Fresh deep-clone per attempt — retries restart cleanly.\n const attemptState: Record<string, unknown> = cloneState(params.state);\n\n if (step.before) {\n await step.before(params.buildContext({ state: attemptState }));\n }\n\n if (step.agent) {\n const agent = step.agent;\n const agentInput = step.input\n ? await step.input(params.buildContext({ state: attemptState }))\n : { prompt: \"\" };\n\n const { prompt, ...agentOpts } = agentInput;\n\n // Run the step's agent inside a nested frame so observe-all does NOT\n // also self-route it as a standalone trace — the workflow already\n // captures it into report.steps (explicit capture, like the supervisor).\n const result = await withoutRunFrame(() =>\n agent.execute(prompt, {\n ...agentOpts,\n signal,\n }),\n );\n\n executionResult = result;\n\n if (result.usage) {\n mergeUsage(params.usage, result.usage);\n }\n\n if (result.error) throw result.error;\n } else if (step.run) {\n // Custom `run` callbacks can call anything — an ambient RunFrame\n // (mirroring the supervisor/team/orchestrator callback pattern)\n // is the only way to observe what they invoke, since (unlike\n // `step.agent` above) there's no single known executable to\n // explicitly capture. Any `agent.execute(...)` the callback\n // invokes DIRECTLY self-attaches its report onto `runChildren`\n // via `captureChildReport` and is suppressed from also\n // self-routing as a standalone observed trace.\n const runChildren: BaseReport[] = [];\n\n try {\n executionResult = await withRunFrame(\n {\n sink: runChildren,\n rootRunId: params.runId,\n parentRunId: params.runId,\n sessionId: params.sessionId,\n },\n () => step.run!(params.buildContext({ state: attemptState })),\n );\n } finally {\n // Runs whether the callback resolved or threw — a callback that\n // calls an agent and THEN throws still gets that call's report\n // preserved on the failed snapshot (forensic trace, same intent\n // as the file's other failed-snapshot preservation). Unconditional\n // reassign (not a conditional-append): a retry whose callback\n // captures nothing must clear a prior failed attempt's captures.\n stepChildren = runChildren.length > 0 ? runChildren : undefined;\n\n for (const child of runChildren) {\n mergeUsage(params.usage, child.usage);\n }\n }\n }\n\n if (step.output) {\n const extracted = await step.output.extract(\n params.buildContext({\n state: attemptState,\n agentResult: executionResult,\n }),\n );\n output = await validateSchema(step.output.schema, extracted);\n } else {\n output = undefined;\n }\n\n if (step.after) {\n await step.after(\n params.buildContext({\n state: attemptState,\n agentResult: executionResult,\n }),\n );\n }\n\n Object.assign(stepState, attemptState);\n\n attempts.push({\n index: attempt,\n startedAt: attemptStart,\n endedAt: new Date().toISOString(),\n duration: performance.now() - attemptStartPerf,\n status: \"success\",\n });\n succeeded = true;\n break;\n } catch (err) {\n if (isAbortError(err) || err instanceof WorkflowCancelledError) {\n throw createCancelledError(signal);\n }\n\n attempts.push({\n index: attempt,\n startedAt: attemptStart,\n endedAt: new Date().toISOString(),\n duration: performance.now() - attemptStartPerf,\n status: \"failed\",\n error: toAIError(err),\n });\n\n lastError = err;\n\n const shouldRetry =\n attempt < totalAttempts &&\n (retryConfig.retryOn ? retryConfig.retryOn(err, attempt) !== false : true);\n\n if (!shouldRetry) break;\n\n emitter.emit(\n \"workflow.step.retrying\",\n {\n step: step.name,\n attempt: attempt + 1,\n totalAttempts,\n lastError: err,\n },\n params.executionHandlers,\n );\n\n step.on?.retrying?.({\n step: step.name,\n attempt: attempt + 1,\n totalAttempts,\n lastError: err,\n });\n\n logger.warn(logModule, \"step.retrying\", `${step.name} step retrying`, {\n step: step.name,\n attempt: attempt + 1,\n });\n\n retryConfig.onRetry?.(attempt + 1, err);\n\n const delay = resolveBackoff(attempt, retryConfig.backoff);\n if (delay > 0) await sleep(delay, signal);\n }\n }\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - stepStartPerf;\n\n if (!succeeded) {\n const aiError = toAIError(lastError);\n const stepError = new StepFailedError(\n `step \"${step.name}\" failed after ${attempts.length} attempt(s): ${aiError.message}`,\n { stepName: step.name, attempts: attempts.length, cause: aiError },\n );\n\n emitter.emit(\n \"workflow.step.failed\",\n { step: step.name, error: stepError, attempts: attempts.length },\n params.executionHandlers,\n );\n\n step.on?.failed?.({\n step: step.name,\n error: stepError,\n attempts: attempts.length,\n });\n\n logger.error(logModule, \"step.failed\", `${step.name} step failed`, {\n step: step.name,\n attempts: attempts.length,\n code: stepError.code,\n });\n\n const failedAgentResult = asAgentResult(executionResult);\n return {\n output: undefined,\n skipped: false,\n status: \"failed\",\n startedAt,\n endedAt,\n duration,\n attempts: attempts.length,\n attemptHistory: attempts,\n error: stepError,\n state: stepState,\n executionResult:\n executionResult && typeof executionResult === \"object\" ? executionResult : undefined,\n agentReport: failedAgentResult?.report,\n agentUsage: failedAgentResult?.usage,\n children: stepChildren,\n };\n }\n\n emitter.emit(\n \"workflow.step.completed\",\n { step: step.name, output, duration },\n params.executionHandlers,\n );\n step.on?.completed?.({ step: step.name, output, duration });\n logger.debug(logModule, \"step.completed\", \"step completed\", {\n step: step.name,\n duration,\n });\n\n const completedAgentResult = asAgentResult(executionResult);\n return {\n output,\n skipped: false,\n status: \"completed\",\n startedAt,\n endedAt,\n duration,\n attempts: attempts.length,\n attemptHistory: attempts,\n state: stepState,\n executionResult:\n executionResult && typeof executionResult === \"object\" ? executionResult : undefined,\n agentReport: completedAgentResult?.report,\n agentUsage: completedAgentResult?.usage,\n children: stepChildren,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Parallel runner\n// ---------------------------------------------------------------------------\n\ntype ParallelParams = ExecuteStepParams & {\n stepState: Record<string, unknown>;\n startedAt: string;\n startPerf: number;\n};\n\nasync function runParallelStep(params: ParallelParams): Promise<MutableStepSnapshot> {\n const { step, emitter, executionHandlers, logger, logModule, signal } = params;\n\n const sharedState = params.stepState;\n const childSnapshots: Record<string, StepSnapshot> = {};\n let firstError: AIError | undefined;\n\n const results = await Promise.all(\n (step.parallel ?? []).map(async (child) => {\n const snap = await executeStep({\n step: child,\n state: sharedState,\n emitter,\n executionHandlers,\n logger,\n logModule,\n signal,\n buildContext: params.buildContext,\n usage: params.usage,\n runId: params.runId,\n sessionId: params.sessionId,\n });\n\n return { child, snap };\n }),\n );\n\n // Merge each child's resulting state into the shared parent state in\n // DECLARATION order — not completion order. Every child cloned the\n // same initial `sharedState` synchronously at dispatch, so the merge\n // here is the only thing that decides conflicting keys; `Promise.all`\n // preserves input order in `results`, so a key written by multiple\n // children deterministically resolves to the last-declared child's\n // value regardless of which settled first (C3). An optional\n // `mergeState` reducer overrides this per key for advanced workflows.\n for (const { child, snap } of results) {\n childSnapshots[child.name] = finalizeSnapshot(snap);\n\n if (step.mergeState) {\n step.mergeState(sharedState, snap.state, child.name);\n } else {\n Object.assign(sharedState, snap.state);\n }\n\n if (snap.status === \"failed\" && !firstError && snap.error) {\n firstError = snap.error;\n }\n }\n\n const endedAt = new Date().toISOString();\n const duration = performance.now() - params.startPerf;\n\n let output: unknown;\n\n if (step.output) {\n try {\n const ctx = params.buildContext({ state: sharedState });\n const ctxWithChildren = {\n ...ctx,\n steps: {\n ...ctx.steps,\n [step.name]: {\n ...(childSnapshots as unknown as StepSnapshot),\n steps: childSnapshots,\n status: firstError ? \"failed\" : \"completed\",\n } as StepSnapshot,\n } as Readonly<Record<string, StepSnapshot>>,\n };\n\n const extracted = await step.output.extract(ctxWithChildren);\n output = await validateSchema(step.output.schema, extracted);\n } catch (err) {\n firstError = firstError ?? toAIError(err);\n }\n }\n\n const status: \"completed\" | \"failed\" = firstError ? \"failed\" : \"completed\";\n\n if (status === \"completed\") {\n emitter.emit(\n \"workflow.step.completed\",\n { step: step.name, output, duration },\n executionHandlers,\n );\n step.on?.completed?.({ step: step.name, output, duration });\n } else {\n emitter.emit(\n \"workflow.step.failed\",\n { step: step.name, error: firstError!, attempts: 1 },\n executionHandlers,\n );\n step.on?.failed?.({ step: step.name, error: firstError!, attempts: 1 });\n }\n\n return {\n output,\n skipped: false,\n status,\n startedAt: params.startedAt,\n endedAt,\n duration,\n attempts: 1,\n attemptHistory: [],\n error: firstError,\n state: sharedState,\n steps: childSnapshots,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nexport function finalizeSnapshot(snap: MutableStepSnapshot): StepSnapshot {\n return Object.freeze({\n output: snap.output,\n skipped: snap.skipped,\n status: snap.status,\n startedAt: snap.startedAt,\n endedAt: snap.endedAt,\n duration: snap.duration,\n attempts: snap.attempts,\n attemptHistory: snap.attemptHistory,\n error: snap.error,\n state: deepFreeze(cloneState(snap.state)),\n executionResult: snap.executionResult as StepSnapshot[\"executionResult\"],\n agentReport: snap.agentReport,\n agentUsage: snap.agentUsage,\n children: snap.children,\n steps: snap.steps,\n }) as StepSnapshot;\n}\n\nfunction buildFailedSnapshot(\n step: StepDefinition,\n state: Record<string, unknown>,\n startedAt: string,\n startPerf: number,\n attemptsCount: number,\n attemptHistory: AttemptEntry[],\n): MutableStepSnapshot {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - startPerf;\n const lastErr = attemptHistory[attemptHistory.length - 1]?.error;\n const wrapped = lastErr\n ? new StepFailedError(`step \"${step.name}\" skip threw: ${lastErr.message}`, {\n stepName: step.name,\n attempts: attemptsCount,\n cause: lastErr,\n })\n : new StepFailedError(`step \"${step.name}\" failed`, {\n stepName: step.name,\n attempts: attemptsCount,\n });\n\n return {\n output: undefined,\n skipped: false,\n status: \"failed\",\n startedAt,\n endedAt,\n duration,\n attempts: attemptsCount,\n attemptHistory,\n error: wrapped,\n state,\n };\n}\n\nfunction failedAttempt(\n index: number,\n err: unknown,\n startedAt: string,\n startPerf: number,\n): AttemptEntry {\n return {\n index,\n startedAt,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n status: \"failed\",\n error: toAIError(err),\n };\n}\n\nexport function toAIError(err: unknown): AIError {\n if (err instanceof AIError) return err;\n if (err instanceof Error) return new WorkflowError(err.message, { cause: err });\n return new WorkflowError(String(err));\n}\n\nasync function validateSchema(\n schema: StandardSchemaV1<unknown> | undefined,\n value: unknown,\n): Promise<unknown> {\n if (!schema) return value;\n const result = await schema[\"~standard\"].validate(value);\n\n if (\"issues\" in result && result.issues) {\n throw new SchemaValidationError(\"workflow step output failed schema validation\", {\n issues: result.issues,\n });\n }\n\n return (result as { value: unknown }).value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoDA,SAAS,cAAc,QAAmD;CACxE,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,IAAK,OAA8B,SAAS,SAAS,OAAO;CAC5D,OAAO;AACT;;;;;;;AAkCA,eAAsB,YAAY,QAAyD;CACzF,MAAM,EAAE,MAAM,SAAS,mBAAmB,QAAQ,WAAW,WAAW;CACxE,MAAM,6BAAY,IAAI,KAAK,GAAE,YAAY;CACzC,MAAM,gBAAgB,YAAY,IAAI;CAEtC,OAAO,KAAK,IAAI,WAAW,EAAE,MAAM,KAAK,KAAK,CAAC;CAC9C,QAAQ,KAAK,0BAA0B,EAAE,MAAM,KAAK,KAAK,GAAG,iBAAiB;CAC7E,OAAO,MAAM,WAAW,iBAAiB,GAAG,KAAK,KAAK,iBAAiB,EACrE,MAAM,KAAK,KACb,CAAC;CAED,MAAM,YAAqC,WAAW,OAAO,KAAK;CAGlE,IAAI;EACF,IAAI,KAAK,MAEP;OAAI,MADqB,KAAK,KAAK,OAAO,aAAa,EAAE,OAAO,UAAU,CAAC,CAAC,GAC5D;IACd,MAAM,2BAAU,IAAI,KAAK,GAAE,YAAY;IACvC,MAAM,WAAW,YAAY,IAAI,IAAI;IACrC,QAAQ,KAAK,yBAAyB,EAAE,MAAM,KAAK,KAAK,GAAG,iBAAiB;IAC5E,OAAO,MAAM,WAAW,gBAAgB,GAAG,KAAK,KAAK,gBAAgB,EACnE,MAAM,KAAK,KACb,CAAC;IAED,OAAO;KACL,QAAQ;KACR,SAAS;KACT,QAAQ;KACR;KACA;KACA;KACA,UAAU;KACV,gBAAgB,CAAC;KACjB,OAAO;IACT;GACF;;CAEJ,SAAS,KAAK;EACZ,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ACrC,MAAM,UAAU,eAAe,eAAe,SAAS,IAAI;CAY3D,OAAO;EACL,QAAQ;EACR,SAAS;EACT,QAAQ;EACR;EACA;EACA;EACA,UAAU;EACV;EACA,OApBc,UACZ,IAAI,gBAAgB,SAAS,KAAK,KAAK,gBAAgB,QAAQ,WAAW;GACxE,UAAU,KAAK;GACf,UAAU;GACV,OAAO;EACT,CAAC,IACD,IAAI,gBAAgB,SAAS,KAAK,KAAK,WAAW;GAChD,UAAU,KAAK;GACf,UAAU;EACZ,CAAC;EAYH;CACF;AACF;AAEA,SAAS,cACP,OACA,KACA,WACA,WACc;CACd,OAAO;EACL;EACA;EACA,0BAAS,IAAI,KAAK,GAAE,YAAY;EAChC,UAAU,YAAY,IAAI,IAAI;EAC9B,QAAQ;EACR,OAAO,UAAU,GAAG;CACtB;AACF;AAEA,SAAgB,UAAU,KAAuB;CAC/C,IAAI,eAAe,SAAS,OAAO;CACnC,IAAI,eAAe,OAAO,OAAO,IAAI,cAAc,IAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC9E,OAAO,IAAI,cAAc,OAAO,GAAG,CAAC;AACtC;AAEA,eAAe,eACb,QACA,OACkB;CAClB,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,SAAS,MAAM,OAAO,aAAa,SAAS,KAAK;CAEvD,IAAI,YAAY,UAAU,OAAO,QAC/B,MAAM,IAAI,sBAAsB,iDAAiD,EAC/E,QAAQ,OAAO,OACjB,CAAC;CAGH,OAAQ,OAA8B;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"step.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/step.ts"],"mappings":";;;;;AAeA;;;;;;;;;;iBAAgB,IAAA,4BAEL,MAAA,
|
|
1
|
+
{"version":3,"file":"step.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/step.ts"],"mappings":";;;;;AAeA;;;;;;;;;;iBAAgB,IAAA,4BAEL,MAAA,sCAAA,CAGT,UAAA,EAAY,cAAA,CAAe,MAAA,EAAQ,MAAA,EAAQ,QAAA,IAC1C,cAAA,CAAe,MAAA,EAAQ,MAAA,EAAQ,QAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"step.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/step.ts"],"sourcesContent":["import type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport { WorkflowError } from \"../errors\";\n\n/**\n * `ai.step(def)` — pass-through factory used for authoring. Returns\n * the definition object verbatim so the workflow engine can read it\n * during execution; the factory exists for API symmetry with\n * `ai.workflow()` and to leave room for future validation or\n * metadata annotation.\n *\n * Generics flow from the enclosing `ai.workflow<...>()` call when the\n * step is declared inline inside `steps: [...]`. To author a step\n * outside that context with full typing, pass them explicitly:\n * `ai.step<MyInput, MyState, MyContext>({ ... })`.\n */\nexport function step<\n TInput = unknown,\n TState = Record<string, unknown>,\n TContext = unknown,\n>(\n definition: StepDefinition<TInput, TState, TContext>,\n): StepDefinition<TInput, TState, TContext> {\n validate(definition);\n return definition;\n}\n\nfunction validate<TInput, TState, TContext>(\n def: StepDefinition<TInput, TState, TContext>,\n): void {\n if (!def.name || typeof def.name !== \"string\") {\n throw new WorkflowError(\"ai.step: `name` is required\");\n }\n\n const hasRun = typeof def.run === \"function\";\n const hasAgent = def.agent !== undefined;\n const hasParallel = Array.isArray(def.parallel) && def.parallel.length > 0;\n\n const modes = [hasRun, hasAgent, hasParallel].filter(Boolean).length;\n\n if (modes === 0) {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): must define exactly one of run | agent | parallel`,\n );\n }\n\n if (modes > 1) {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): define only one of run | agent | parallel`,\n );\n }\n\n if (hasAgent && typeof def.input !== \"function\") {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): \\`input(ctx)\\` is required when \\`agent\\` is set`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,KAKd,YAC0C;CAC1C,SAAS,UAAU;CACnB,OAAO;AACT;AAEA,SAAS,SACP,KACM;CACN,IAAI,CAAC,IAAI,QAAQ,OAAO,IAAI,SAAS,UACnC,MAAM,IAAI,cAAc,6BAA6B;CAGvD,MAAM,SAAS,OAAO,IAAI,QAAQ;CAClC,MAAM,WAAW,IAAI,UAAU;CAG/B,MAAM,QAAQ;EAAC;EAAQ;EAFH,MAAM,QAAQ,IAAI,QAAQ,KAAK,IAAI,SAAS,SAAS;CAE7B,
|
|
1
|
+
{"version":3,"file":"step.mjs","names":[],"sources":["../../../../../../../ai/src/workflow/step.ts"],"sourcesContent":["import type { StepDefinition } from \"../contracts/workflow/step.contract\";\nimport { WorkflowError } from \"../errors\";\n\n/**\n * `ai.step(def)` — pass-through factory used for authoring. Returns\n * the definition object verbatim so the workflow engine can read it\n * during execution; the factory exists for API symmetry with\n * `ai.workflow()` and to leave room for future validation or\n * metadata annotation.\n *\n * Generics flow from the enclosing `ai.workflow<...>()` call when the\n * step is declared inline inside `steps: [...]`. To author a step\n * outside that context with full typing, pass them explicitly:\n * `ai.step<MyInput, MyState, MyContext>({ ... })`.\n */\nexport function step<\n TInput = unknown,\n TState = Record<string, unknown>,\n TContext = unknown,\n>(\n definition: StepDefinition<TInput, TState, TContext>,\n): StepDefinition<TInput, TState, TContext> {\n validate(definition);\n return definition;\n}\n\nfunction validate<TInput, TState, TContext>(\n def: StepDefinition<TInput, TState, TContext>,\n): void {\n if (!def.name || typeof def.name !== \"string\") {\n throw new WorkflowError(\"ai.step: `name` is required\");\n }\n\n const hasRun = typeof def.run === \"function\";\n const hasAgent = def.agent !== undefined;\n const hasParallel = Array.isArray(def.parallel) && def.parallel.length > 0;\n\n const modes = [hasRun, hasAgent, hasParallel].filter(Boolean).length;\n\n if (modes === 0) {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): must define exactly one of run | agent | parallel`,\n );\n }\n\n if (modes > 1) {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): define only one of run | agent | parallel`,\n );\n }\n\n if (hasAgent && typeof def.input !== \"function\") {\n throw new WorkflowError(\n `ai.step(\"${def.name}\"): \\`input(ctx)\\` is required when \\`agent\\` is set`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,KAKd,YAC0C;CAC1C,SAAS,UAAU;CACnB,OAAO;AACT;AAEA,SAAS,SACP,KACM;CACN,IAAI,CAAC,IAAI,QAAQ,OAAO,IAAI,SAAS,UACnC,MAAM,IAAI,cAAc,6BAA6B;CAGvD,MAAM,SAAS,OAAO,IAAI,QAAQ;CAClC,MAAM,WAAW,IAAI,UAAU;CAG/B,MAAM,QAAQ;EAAC;EAAQ;EAFH,MAAM,QAAQ,IAAI,QAAQ,KAAK,IAAI,SAAS,SAAS;CAE7B,EAAE,OAAO,OAAO,EAAE;CAE9D,IAAI,UAAU,GACZ,MAAM,IAAI,cACR,YAAY,IAAI,KAAK,sDACvB;CAGF,IAAI,QAAQ,GACV,MAAM,IAAI,cACR,YAAY,IAAI,KAAK,8CACvB;CAGF,IAAI,YAAY,OAAO,IAAI,UAAU,YACnC,MAAM,IAAI,cACR,YAAY,IAAI,KAAK,qDACvB;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/workflow.ts"],"mappings":";;;;;AAyBA;;;iBAAgB,QAAA,+CAGL,MAAA,
|
|
1
|
+
{"version":3,"file":"workflow.d.mts","names":[],"sources":["../../../../../../../ai/src/workflow/workflow.ts"],"mappings":";;;;;AAyBA;;;iBAAgB,QAAA,+CAGL,MAAA,sCAAA,CAGT,UAAA,EAAY,kBAAA,CAAmB,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,QAAA,IACvD,gBAAA,CAAiB,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,QAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow.mjs","names":["combined"],"sources":["../../../../../../../ai/src/workflow/workflow.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type { ExecutionReport } from \"../contracts/result/execution-report.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type {\n WorkflowDefinition,\n WorkflowEventHandler,\n WorkflowExecuteOptions,\n WorkflowInstance,\n WorkflowResumeOptions,\n WorkflowRunOptions,\n} from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowError } from \"../errors\";\nimport { notifyObservers } from \"../observe/resolve-observers\";\nimport type { ToolContract } from \"../tool/tool\";\nimport { asTool } from \"./as-tool\";\nimport { WorkflowEmitter } from \"./emitter\";\nimport { loadSnapshotForResume, runWorkflow } from \"./engine\";\nimport { computeSignature } from \"./signature\";\n\n/**\n * `ai.workflow(def)` — construct a `WorkflowInstance`. Validates the\n * definition, computes a stable structural signature, and wires up the\n * three-tier event subscription model.\n */\nexport function workflow<\n TInput = unknown,\n TOutput = unknown,\n TState = Record<string, unknown>,\n TContext = unknown,\n>(\n definition: WorkflowDefinition<TInput, TOutput, TState, TContext>,\n): WorkflowInstance<TInput, TOutput, TState, TContext> {\n validate(definition);\n const signature = computeSignature(definition);\n const emitter = new WorkflowEmitter(definition.on);\n\n async function execute(\n inputOrOptions: TInput | WorkflowExecuteOptions<TInput, TContext>,\n maybeOptions?: WorkflowRunOptions<TContext>,\n ): Promise<WorkflowResult<TOutput>> {\n const { input, options } = normalizeExecuteArgs<TInput, TContext>(\n inputOrOptions,\n maybeOptions,\n );\n const runId = options?.runId ?? generateRunId();\n const result = await runWorkflow<TOutput>({\n definition,\n signature,\n emitter,\n input,\n context: options?.context,\n runId,\n signal: options?.signal,\n executionHandlers: options?.on,\n sessionId: options?.sessionId,\n });\n\n // Route the finished report to any resolved observers (F1/F3).\n // Gated by `definition.observe` + the global observe-all flag;\n // observer errors are swallowed inside `notifyObservers`. Bridge the\n // pre-existing `WorkflowReport = Omit<BaseReport, \"type\">` drift (the\n // report carries `type: \"workflow\"` at runtime — engine sets it) so\n // this call site adds no new type error beyond the documented baseline.\n await notifyObservers(definition.observe, result.report as unknown as ExecutionReport);\n\n return result;\n }\n\n async function resume(\n runId: string,\n options?: WorkflowResumeOptions<TContext>,\n ): Promise<WorkflowResult<TOutput>> {\n const snapshot = await loadSnapshotForResume({\n definition,\n signature,\n runId,\n options,\n });\n\n const result = await runWorkflow<TOutput>({\n definition,\n signature,\n emitter,\n input: snapshot.input,\n context: options?.context,\n runId,\n signal: options?.signal,\n executionHandlers: options?.on,\n sessionId: options?.sessionId,\n resumeFrom: snapshot,\n });\n\n await notifyObservers(definition.observe, result.report as unknown as ExecutionReport);\n\n return result;\n }\n\n const instance: WorkflowInstance<TInput, TOutput, TState, TContext> = {\n name: definition.name,\n description: definition.description,\n inputSchema: definition.inputSchema,\n signature,\n version: definition.version,\n execute,\n resume,\n on<K extends keyof WorkflowEventMap>(event: K, handler: WorkflowEventHandler<K>) {\n return emitter.on(event, handler);\n },\n off<K extends keyof WorkflowEventMap>(event: K, handler: WorkflowEventHandler<K>) {\n emitter.off(event, handler);\n },\n asTool<TToolInput = TInput>(options: {\n description?: string;\n inputSchema: StandardSchemaV1<TToolInput>;\n }): ToolContract<TToolInput, TOutput> {\n return asTool<TInput, TOutput, TToolInput>(instance, options);\n },\n };\n\n return instance;\n}\n\n/**\n * Resolve the overloaded `execute()` call shape. If the caller passed\n * a single plain object with an `input` field, treat it as the\n * combined `WorkflowExecuteOptions`. Otherwise the first arg is the\n * raw workflow input and the second is the run options.\n *\n * Ambiguity note: if your real workflow `input` is itself an object\n * with a top-level `input` key, prefer `execute(rawInput, options)`\n * explicitly — the single-arg detection heuristic would mis-classify\n * it.\n */\nfunction normalizeExecuteArgs<TInput, TContext>(\n inputOrOptions: TInput | WorkflowExecuteOptions<TInput, TContext>,\n maybeOptions: WorkflowRunOptions<TContext> | undefined,\n): { input: TInput; options?: WorkflowRunOptions<TContext> } {\n if (\n maybeOptions === undefined &&\n inputOrOptions !== null &&\n typeof inputOrOptions === \"object\" &&\n \"input\" in (inputOrOptions as object)\n ) {\n const combined = inputOrOptions as WorkflowExecuteOptions<TInput, TContext>;\n const { input, ...options } = combined;\n return { input, options };\n }\n\n return { input: inputOrOptions as TInput, options: maybeOptions };\n}\n\nfunction validate<TInput, TOutput, TState, TContext>(\n definition: WorkflowDefinition<TInput, TOutput, TState, TContext>,\n): void {\n if (!definition.name || typeof definition.name !== \"string\") {\n throw new WorkflowError(\"ai.workflow: `name` is required\");\n }\n\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowError(`ai.workflow(\"${definition.name}\"): at least one step is required`);\n }\n\n const seen = new Set<string>();\n const walk = (name: string) => {\n if (seen.has(name)) {\n throw new WorkflowError(`ai.workflow(\"${definition.name}\"): duplicate step name \"${name}\"`);\n }\n seen.add(name);\n };\n\n for (const step of definition.steps) {\n walk(step.name);\n\n if (step.parallel) {\n for (const child of step.parallel) {\n walk(child.name);\n }\n }\n }\n}\n\nfunction generateRunId(): string {\n // Non-crypto random — adequate for ephemeral workflow runs.\n return `wf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAgB,SAMd,YACqD;CACrD,SAAS,UAAU;CACnB,MAAM,YAAY,iBAAiB,UAAU;CAC7C,MAAM,UAAU,IAAI,gBAAgB,WAAW,EAAE;CAEjD,eAAe,QACb,gBACA,cACkC;EAClC,MAAM,EAAE,OAAO,YAAY,qBACzB,gBACA,YACF;EACA,MAAM,QAAQ,SAAS,SAAS,cAAc;EAC9C,MAAM,SAAS,MAAM,YAAqB;GACxC;GACA;GACA;GACA;GACA,SAAS,SAAS;GAClB;GACA,QAAQ,SAAS;GACjB,mBAAmB,SAAS;GAC5B,WAAW,SAAS;EACtB,CAAC;EAQD,MAAM,gBAAgB,WAAW,SAAS,OAAO,MAAoC;EAErF,OAAO;CACT;CAEA,eAAe,O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2BAA2B,KAAK,EAAE;EAE5F,KAAK,IAAI,IAAI;CACf;CAEA,KAAK,MAAM,QAAQ,WAAW,OAAO;EACnC,KAAK,KAAK,IAAI;EAEd,IAAI,KAAK,UACP,KAAK,MAAM,SAAS,KAAK,UACvB,KAAK,MAAM,IAAI;CAGrB;AACF;AAEA,SAAS,gBAAwB;CAE/B,OAAO,MAAM,KAAK,IAAI,
|
|
1
|
+
{"version":3,"file":"workflow.mjs","names":["combined"],"sources":["../../../../../../../ai/src/workflow/workflow.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type { ExecutionReport } from \"../contracts/result/execution-report.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type {\n WorkflowDefinition,\n WorkflowEventHandler,\n WorkflowExecuteOptions,\n WorkflowInstance,\n WorkflowResumeOptions,\n WorkflowRunOptions,\n} from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowError } from \"../errors\";\nimport { notifyObservers } from \"../observe/resolve-observers\";\nimport type { ToolContract } from \"../tool/tool\";\nimport { asTool } from \"./as-tool\";\nimport { WorkflowEmitter } from \"./emitter\";\nimport { loadSnapshotForResume, runWorkflow } from \"./engine\";\nimport { computeSignature } from \"./signature\";\n\n/**\n * `ai.workflow(def)` — construct a `WorkflowInstance`. Validates the\n * definition, computes a stable structural signature, and wires up the\n * three-tier event subscription model.\n */\nexport function workflow<\n TInput = unknown,\n TOutput = unknown,\n TState = Record<string, unknown>,\n TContext = unknown,\n>(\n definition: WorkflowDefinition<TInput, TOutput, TState, TContext>,\n): WorkflowInstance<TInput, TOutput, TState, TContext> {\n validate(definition);\n const signature = computeSignature(definition);\n const emitter = new WorkflowEmitter(definition.on);\n\n async function execute(\n inputOrOptions: TInput | WorkflowExecuteOptions<TInput, TContext>,\n maybeOptions?: WorkflowRunOptions<TContext>,\n ): Promise<WorkflowResult<TOutput>> {\n const { input, options } = normalizeExecuteArgs<TInput, TContext>(\n inputOrOptions,\n maybeOptions,\n );\n const runId = options?.runId ?? generateRunId();\n const result = await runWorkflow<TOutput>({\n definition,\n signature,\n emitter,\n input,\n context: options?.context,\n runId,\n signal: options?.signal,\n executionHandlers: options?.on,\n sessionId: options?.sessionId,\n });\n\n // Route the finished report to any resolved observers (F1/F3).\n // Gated by `definition.observe` + the global observe-all flag;\n // observer errors are swallowed inside `notifyObservers`. Bridge the\n // pre-existing `WorkflowReport = Omit<BaseReport, \"type\">` drift (the\n // report carries `type: \"workflow\"` at runtime — engine sets it) so\n // this call site adds no new type error beyond the documented baseline.\n await notifyObservers(definition.observe, result.report as unknown as ExecutionReport);\n\n return result;\n }\n\n async function resume(\n runId: string,\n options?: WorkflowResumeOptions<TContext>,\n ): Promise<WorkflowResult<TOutput>> {\n const snapshot = await loadSnapshotForResume({\n definition,\n signature,\n runId,\n options,\n });\n\n const result = await runWorkflow<TOutput>({\n definition,\n signature,\n emitter,\n input: snapshot.input,\n context: options?.context,\n runId,\n signal: options?.signal,\n executionHandlers: options?.on,\n sessionId: options?.sessionId,\n resumeFrom: snapshot,\n });\n\n await notifyObservers(definition.observe, result.report as unknown as ExecutionReport);\n\n return result;\n }\n\n const instance: WorkflowInstance<TInput, TOutput, TState, TContext> = {\n name: definition.name,\n description: definition.description,\n inputSchema: definition.inputSchema,\n signature,\n version: definition.version,\n execute,\n resume,\n on<K extends keyof WorkflowEventMap>(event: K, handler: WorkflowEventHandler<K>) {\n return emitter.on(event, handler);\n },\n off<K extends keyof WorkflowEventMap>(event: K, handler: WorkflowEventHandler<K>) {\n emitter.off(event, handler);\n },\n asTool<TToolInput = TInput>(options: {\n description?: string;\n inputSchema: StandardSchemaV1<TToolInput>;\n }): ToolContract<TToolInput, TOutput> {\n return asTool<TInput, TOutput, TToolInput>(instance, options);\n },\n };\n\n return instance;\n}\n\n/**\n * Resolve the overloaded `execute()` call shape. If the caller passed\n * a single plain object with an `input` field, treat it as the\n * combined `WorkflowExecuteOptions`. Otherwise the first arg is the\n * raw workflow input and the second is the run options.\n *\n * Ambiguity note: if your real workflow `input` is itself an object\n * with a top-level `input` key, prefer `execute(rawInput, options)`\n * explicitly — the single-arg detection heuristic would mis-classify\n * it.\n */\nfunction normalizeExecuteArgs<TInput, TContext>(\n inputOrOptions: TInput | WorkflowExecuteOptions<TInput, TContext>,\n maybeOptions: WorkflowRunOptions<TContext> | undefined,\n): { input: TInput; options?: WorkflowRunOptions<TContext> } {\n if (\n maybeOptions === undefined &&\n inputOrOptions !== null &&\n typeof inputOrOptions === \"object\" &&\n \"input\" in (inputOrOptions as object)\n ) {\n const combined = inputOrOptions as WorkflowExecuteOptions<TInput, TContext>;\n const { input, ...options } = combined;\n return { input, options };\n }\n\n return { input: inputOrOptions as TInput, options: maybeOptions };\n}\n\nfunction validate<TInput, TOutput, TState, TContext>(\n definition: WorkflowDefinition<TInput, TOutput, TState, TContext>,\n): void {\n if (!definition.name || typeof definition.name !== \"string\") {\n throw new WorkflowError(\"ai.workflow: `name` is required\");\n }\n\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowError(`ai.workflow(\"${definition.name}\"): at least one step is required`);\n }\n\n const seen = new Set<string>();\n const walk = (name: string) => {\n if (seen.has(name)) {\n throw new WorkflowError(`ai.workflow(\"${definition.name}\"): duplicate step name \"${name}\"`);\n }\n seen.add(name);\n };\n\n for (const step of definition.steps) {\n walk(step.name);\n\n if (step.parallel) {\n for (const child of step.parallel) {\n walk(child.name);\n }\n }\n }\n}\n\nfunction generateRunId(): string {\n // Non-crypto random — adequate for ephemeral workflow runs.\n return `wf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAgB,SAMd,YACqD;CACrD,SAAS,UAAU;CACnB,MAAM,YAAY,iBAAiB,UAAU;CAC7C,MAAM,UAAU,IAAI,gBAAgB,WAAW,EAAE;CAEjD,eAAe,QACb,gBACA,cACkC;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AAO,WAAW,SAAS,UACjD,MAAM,IAAI,cAAc,iCAAiC;CAG3D,IAAI,CAAC,MAAM,QAAQ,WAAW,KAAK,KAAK,WAAW,MAAM,WAAW,GAClE,MAAM,IAAI,cAAc,gBAAgB,WAAW,KAAK,kCAAkC;CAG5F,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAAQ,SAAiB;EAC7B,IAAI,KAAK,IAAI,IAAI,GACf,MAAM,IAAI,cAAc,gBAAgB,WAAW,KAAK,2BAA2B,KAAK,EAAE;EAE5F,KAAK,IAAI,IAAI;CACf;CAEA,KAAK,MAAM,QAAQ,WAAW,OAAO;EACnC,KAAK,KAAK,IAAI;EAEd,IAAI,KAAK,UACP,KAAK,MAAM,SAAS,KAAK,UACvB,KAAK,MAAM,IAAI;CAGrB;AACF;AAEA,SAAS,gBAAwB;CAE/B,OAAO,MAAM,KAAK,IAAI,EAAE,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE;AAChF"}
|
package/llms-full.txt
CHANGED
|
@@ -15,6 +15,8 @@ description: 'Start with @warlock.js/ai — provider-agnostic core for agents /
|
|
|
15
15
|
|
|
16
16
|
Provider-agnostic core for building AI primitives in TypeScript. Adapters live in sibling packages — all five first-party adapters ship today: `@warlock.js/ai-openai`, `-anthropic`, `-bedrock`, `-google`, `-ollama`.
|
|
17
17
|
|
|
18
|
+
Server-only: `package.json` declares `"warlock": { "environment": "server" }`. `@warlock.js/web`'s build refuses app client code that value-imports this package; type-only imports are allowed, and server loaders/controllers/modules are unaffected.
|
|
19
|
+
|
|
18
20
|
> This skill is the AI **map** — read it first, then load the specific skill for the task.
|
|
19
21
|
|
|
20
22
|
## The 4-primitive ladder
|
package/package.json
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@warlock.js/ai",
|
|
3
3
|
"description": "Core @warlock.js AI framework — contracts, agent, workflow, supervisor",
|
|
4
|
+
"warlock": {
|
|
5
|
+
"environment": "server"
|
|
6
|
+
},
|
|
4
7
|
"keywords": [
|
|
5
8
|
"warlock",
|
|
6
9
|
"ai"
|
|
@@ -15,9 +18,9 @@
|
|
|
15
18
|
"@standard-schema/spec": "^1.0.0"
|
|
16
19
|
},
|
|
17
20
|
"peerDependencies": {
|
|
18
|
-
"@warlock.js/ai-openai": "5.
|
|
19
|
-
"@warlock.js/cache": "5.
|
|
20
|
-
"@warlock.js/logger": "5.
|
|
21
|
+
"@warlock.js/ai-openai": "5.2.2",
|
|
22
|
+
"@warlock.js/cache": "5.2.2",
|
|
23
|
+
"@warlock.js/logger": "5.2.2",
|
|
21
24
|
"langfuse": "*",
|
|
22
25
|
"openai": "*",
|
|
23
26
|
"pdf-parse": "*",
|
|
@@ -44,7 +47,7 @@
|
|
|
44
47
|
"optional": true
|
|
45
48
|
}
|
|
46
49
|
},
|
|
47
|
-
"version": "5.
|
|
50
|
+
"version": "5.2.2",
|
|
48
51
|
"main": "./cjs/index.cjs",
|
|
49
52
|
"module": "./esm/index.mjs",
|
|
50
53
|
"types": "./esm/index.d.mts",
|