@warlock.js/ai 4.1.15 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/cjs/index.cjs +88 -87
- package/cjs/index.cjs.map +1 -1
- package/esm/agent/agent-config.type.d.mts +1 -1
- package/esm/agent/agent-config.type.d.mts.map +1 -1
- package/esm/agent/agent-input-builder.mjs +1 -1
- package/esm/agent/agent-input-builder.mjs.map +1 -1
- package/esm/agent/agent-log-event.mjs +1 -1
- package/esm/agent/agent-log-event.mjs.map +1 -1
- package/esm/agent/agent-stream.d.mts +1 -1
- package/esm/agent/agent-stream.d.mts.map +1 -1
- package/esm/agent/agent-stream.mjs +1 -1
- package/esm/agent/agent-stream.mjs.map +1 -1
- package/esm/agent/agent-to-stream-event.mjs +1 -1
- package/esm/agent/agent-to-stream-event.mjs.map +1 -1
- package/esm/agent/agent.d.mts +1 -1
- package/esm/agent/agent.d.mts.map +1 -1
- package/esm/agent/agent.mjs +1 -1
- package/esm/agent/agent.mjs.map +1 -1
- package/esm/agent/json-stream-guard.mjs +1 -1
- package/esm/agent/json-stream-guard.mjs.map +1 -1
- package/esm/ai.d.mts +1 -1
- package/esm/ai.d.mts.map +1 -1
- package/esm/ai.mjs +1 -1
- package/esm/ai.mjs.map +1 -1
- package/esm/config.d.mts +1 -1
- package/esm/config.d.mts.map +1 -1
- package/esm/config.mjs +1 -1
- package/esm/config.mjs.map +1 -1
- package/esm/contracts/agent/agent-options.type.d.mts +1 -1
- package/esm/contracts/agent/agent-options.type.d.mts.map +1 -1
- package/esm/contracts/agent/agent.contract.d.mts +1 -1
- package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
- package/esm/contracts/attachment.type.d.mts +1 -1
- package/esm/contracts/attachment.type.d.mts.map +1 -1
- package/esm/contracts/content-part.type.d.mts +1 -1
- package/esm/contracts/content-part.type.d.mts.map +1 -1
- package/esm/contracts/conversation-message.type.d.mts +1 -1
- package/esm/contracts/conversation-message.type.d.mts.map +1 -1
- package/esm/contracts/embedder.contract.d.mts +1 -1
- package/esm/contracts/embedder.contract.d.mts.map +1 -1
- package/esm/contracts/end.type.d.mts +1 -1
- package/esm/contracts/end.type.d.mts.map +1 -1
- package/esm/contracts/end.type.mjs +1 -1
- package/esm/contracts/end.type.mjs.map +1 -1
- package/esm/contracts/events/agent-events.type.d.mts +1 -1
- package/esm/contracts/events/agent-events.type.d.mts.map +1 -1
- package/esm/contracts/events/complete-event.type.d.mts +1 -1
- package/esm/contracts/events/complete-event.type.d.mts.map +1 -1
- package/esm/contracts/events/event-identity.type.d.mts +1 -1
- package/esm/contracts/events/event-identity.type.d.mts.map +1 -1
- package/esm/contracts/events/event-map.type.d.mts +1 -1
- package/esm/contracts/events/event-map.type.d.mts.map +1 -1
- package/esm/contracts/events/supervisor-events.type.d.mts +1 -1
- package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -1
- package/esm/contracts/events/usage-event.type.d.mts +1 -1
- package/esm/contracts/events/usage-event.type.d.mts.map +1 -1
- package/esm/contracts/events/workflow-events.type.d.mts +1 -1
- package/esm/contracts/events/workflow-events.type.d.mts.map +1 -1
- package/esm/contracts/executable.contract.d.mts +1 -1
- package/esm/contracts/executable.contract.d.mts.map +1 -1
- package/esm/contracts/finish-reason.type.d.mts +1 -1
- package/esm/contracts/finish-reason.type.d.mts.map +1 -1
- package/esm/contracts/middleware/middleware-context.type.d.mts +1 -1
- package/esm/contracts/middleware/middleware-context.type.d.mts.map +1 -1
- package/esm/contracts/middleware/middleware-state.type.d.mts +1 -1
- package/esm/contracts/middleware/middleware-state.type.d.mts.map +1 -1
- package/esm/contracts/middleware/middleware.contract.d.mts +1 -1
- package/esm/contracts/middleware/middleware.contract.d.mts.map +1 -1
- package/esm/contracts/model-tool-call-request.type.d.mts +1 -1
- package/esm/contracts/model-tool-call-request.type.d.mts.map +1 -1
- package/esm/contracts/model.contract.d.mts +1 -1
- package/esm/contracts/model.contract.d.mts.map +1 -1
- package/esm/contracts/placeholders.type.d.mts +1 -1
- package/esm/contracts/placeholders.type.d.mts.map +1 -1
- package/esm/contracts/result/agent-result.type.d.mts +1 -1
- package/esm/contracts/result/agent-result.type.d.mts.map +1 -1
- package/esm/contracts/result/attempt-entry.type.d.mts +1 -1
- package/esm/contracts/result/attempt-entry.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.d.mts +1 -1
- package/esm/contracts/result/base-report.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.mjs +1 -1
- package/esm/contracts/result/base-report.type.mjs.map +1 -1
- package/esm/contracts/result/base-result.type.d.mts +1 -1
- package/esm/contracts/result/base-result.type.d.mts.map +1 -1
- package/esm/contracts/result/execute-result.type.d.mts +1 -1
- package/esm/contracts/result/execute-result.type.d.mts.map +1 -1
- package/esm/contracts/result/execution-report.type.d.mts +1 -1
- package/esm/contracts/result/execution-report.type.d.mts.map +1 -1
- package/esm/contracts/result/llm-trip.type.d.mts +1 -1
- package/esm/contracts/result/llm-trip.type.d.mts.map +1 -1
- package/esm/contracts/result/model-pricing.type.d.mts +1 -1
- package/esm/contracts/result/model-pricing.type.d.mts.map +1 -1
- package/esm/contracts/result/session-send-result.type.d.mts +1 -1
- package/esm/contracts/result/session-send-result.type.d.mts.map +1 -1
- package/esm/contracts/result/step-result.type.d.mts +1 -1
- package/esm/contracts/result/step-result.type.d.mts.map +1 -1
- package/esm/contracts/result/supervisor-result.type.d.mts +1 -1
- package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
- package/esm/contracts/result/tool-call.type.d.mts +1 -1
- package/esm/contracts/result/tool-call.type.d.mts.map +1 -1
- package/esm/contracts/result/usage.type.d.mts +1 -1
- package/esm/contracts/result/usage.type.d.mts.map +1 -1
- package/esm/contracts/result/workflow-result.type.d.mts +1 -1
- package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
- package/esm/contracts/sdk-adapter.contract.d.mts +1 -1
- package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -1
- package/esm/contracts/stream/stream-event.type.d.mts +1 -1
- package/esm/contracts/stream/stream-event.type.d.mts.map +1 -1
- package/esm/contracts/stream/stream.contract.d.mts +1 -1
- package/esm/contracts/stream/stream.contract.d.mts.map +1 -1
- package/esm/contracts/streaming-tool-guard-config.type.d.mts +1 -1
- package/esm/contracts/streaming-tool-guard-config.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/ack-entry.type.d.mts +1 -1
- package/esm/contracts/supervisor/ack-entry.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/classifier-context.type.d.mts +1 -1
- package/esm/contracts/supervisor/classifier-context.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/dispatch-context.type.d.mts +1 -1
- package/esm/contracts/supervisor/dispatch-context.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/evaluate-context.type.d.mts +1 -1
- package/esm/contracts/supervisor/evaluate-context.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/intent-entry.type.d.mts +1 -1
- package/esm/contracts/supervisor/intent-entry.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/iteration-snapshot.type.d.mts +1 -1
- package/esm/contracts/supervisor/iteration-snapshot.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/next.type.d.mts +1 -1
- package/esm/contracts/supervisor/next.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/route-context.type.d.mts +1 -1
- package/esm/contracts/supervisor/route-context.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/router-entry.type.d.mts +1 -1
- package/esm/contracts/supervisor/router-entry.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor-config.type.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor-input.type.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor-input.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts.map +1 -1
- package/esm/contracts/supervisor/supervisor.contract.d.mts +1 -1
- package/esm/contracts/supervisor/supervisor.contract.d.mts.map +1 -1
- package/esm/contracts/system-prompt.contract.d.mts +1 -1
- package/esm/contracts/system-prompt.contract.d.mts.map +1 -1
- package/esm/contracts/tool.contract.d.mts +1 -1
- package/esm/contracts/tool.contract.d.mts.map +1 -1
- package/esm/contracts/workflow/next-step-result.type.d.mts +1 -1
- package/esm/contracts/workflow/next-step-result.type.d.mts.map +1 -1
- package/esm/contracts/workflow/retry-config.type.d.mts +1 -1
- package/esm/contracts/workflow/retry-config.type.d.mts.map +1 -1
- package/esm/contracts/workflow/step.contract.d.mts +1 -1
- package/esm/contracts/workflow/step.contract.d.mts.map +1 -1
- package/esm/contracts/workflow/workflow-context.type.d.mts +1 -1
- package/esm/contracts/workflow/workflow-context.type.d.mts.map +1 -1
- package/esm/contracts/workflow/workflow-snapshot.type.d.mts +1 -1
- package/esm/contracts/workflow/workflow-snapshot.type.d.mts.map +1 -1
- package/esm/contracts/workflow/workflow.contract.d.mts +1 -1
- package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
- package/esm/errors/agent-cancelled-error.d.mts +1 -1
- package/esm/errors/agent-cancelled-error.d.mts.map +1 -1
- package/esm/errors/agent-cancelled-error.mjs +1 -1
- package/esm/errors/agent-cancelled-error.mjs.map +1 -1
- package/esm/errors/agent-execution-error.d.mts +1 -1
- package/esm/errors/agent-execution-error.d.mts.map +1 -1
- package/esm/errors/agent-execution-error.mjs +1 -1
- package/esm/errors/agent-execution-error.mjs.map +1 -1
- package/esm/errors/agent-max-trips-error.d.mts +1 -1
- package/esm/errors/agent-max-trips-error.d.mts.map +1 -1
- package/esm/errors/agent-max-trips-error.mjs +1 -1
- package/esm/errors/agent-max-trips-error.mjs.map +1 -1
- package/esm/errors/ai-error.d.mts +1 -1
- package/esm/errors/ai-error.d.mts.map +1 -1
- package/esm/errors/ai-error.mjs +1 -1
- package/esm/errors/ai-error.mjs.map +1 -1
- package/esm/errors/budget-exceeded-error.d.mts +1 -1
- package/esm/errors/budget-exceeded-error.d.mts.map +1 -1
- package/esm/errors/budget-exceeded-error.mjs +1 -1
- package/esm/errors/budget-exceeded-error.mjs.map +1 -1
- package/esm/errors/content-filter-error.d.mts +1 -1
- package/esm/errors/content-filter-error.d.mts.map +1 -1
- package/esm/errors/content-filter-error.mjs +1 -1
- package/esm/errors/content-filter-error.mjs.map +1 -1
- package/esm/errors/context-length-exceeded-error.d.mts +1 -1
- package/esm/errors/context-length-exceeded-error.d.mts.map +1 -1
- package/esm/errors/context-length-exceeded-error.mjs +1 -1
- package/esm/errors/context-length-exceeded-error.mjs.map +1 -1
- package/esm/errors/error-category.type.d.mts +1 -1
- package/esm/errors/error-category.type.d.mts.map +1 -1
- package/esm/errors/error-code.type.d.mts +1 -1
- package/esm/errors/error-code.type.d.mts.map +1 -1
- package/esm/errors/guardrail-violation-error.d.mts +1 -1
- package/esm/errors/guardrail-violation-error.d.mts.map +1 -1
- package/esm/errors/guardrail-violation-error.mjs +1 -1
- package/esm/errors/guardrail-violation-error.mjs.map +1 -1
- package/esm/errors/invalid-request-error.d.mts +1 -1
- package/esm/errors/invalid-request-error.d.mts.map +1 -1
- package/esm/errors/invalid-request-error.mjs +1 -1
- package/esm/errors/invalid-request-error.mjs.map +1 -1
- package/esm/errors/max-iterations-error.d.mts +1 -1
- package/esm/errors/max-iterations-error.d.mts.map +1 -1
- package/esm/errors/max-iterations-error.mjs +1 -1
- package/esm/errors/max-iterations-error.mjs.map +1 -1
- package/esm/errors/max-steps-exceeded-error.d.mts +1 -1
- package/esm/errors/max-steps-exceeded-error.d.mts.map +1 -1
- package/esm/errors/max-steps-exceeded-error.mjs +1 -1
- package/esm/errors/max-steps-exceeded-error.mjs.map +1 -1
- package/esm/errors/provider-auth-error.d.mts +1 -1
- package/esm/errors/provider-auth-error.d.mts.map +1 -1
- package/esm/errors/provider-auth-error.mjs +1 -1
- package/esm/errors/provider-auth-error.mjs.map +1 -1
- package/esm/errors/provider-error.d.mts +1 -1
- package/esm/errors/provider-error.d.mts.map +1 -1
- package/esm/errors/provider-error.mjs +1 -1
- package/esm/errors/provider-error.mjs.map +1 -1
- package/esm/errors/provider-rate-limit-error.d.mts +1 -1
- package/esm/errors/provider-rate-limit-error.d.mts.map +1 -1
- package/esm/errors/provider-rate-limit-error.mjs +1 -1
- package/esm/errors/provider-rate-limit-error.mjs.map +1 -1
- package/esm/errors/provider-timeout-error.d.mts +1 -1
- package/esm/errors/provider-timeout-error.d.mts.map +1 -1
- package/esm/errors/provider-timeout-error.mjs +1 -1
- package/esm/errors/provider-timeout-error.mjs.map +1 -1
- package/esm/errors/quota-exceeded-error.d.mts +1 -1
- package/esm/errors/quota-exceeded-error.d.mts.map +1 -1
- package/esm/errors/quota-exceeded-error.mjs +1 -1
- package/esm/errors/quota-exceeded-error.mjs.map +1 -1
- package/esm/errors/routing-error.d.mts +1 -1
- package/esm/errors/routing-error.d.mts.map +1 -1
- package/esm/errors/routing-error.mjs +1 -1
- package/esm/errors/routing-error.mjs.map +1 -1
- package/esm/errors/schema-validation-error.d.mts +1 -1
- package/esm/errors/schema-validation-error.d.mts.map +1 -1
- package/esm/errors/schema-validation-error.mjs +1 -1
- package/esm/errors/schema-validation-error.mjs.map +1 -1
- package/esm/errors/step-failed-error.d.mts +1 -1
- package/esm/errors/step-failed-error.d.mts.map +1 -1
- package/esm/errors/step-failed-error.mjs +1 -1
- package/esm/errors/step-failed-error.mjs.map +1 -1
- package/esm/errors/supervisor-cancelled-error.d.mts +1 -1
- package/esm/errors/supervisor-cancelled-error.d.mts.map +1 -1
- package/esm/errors/supervisor-cancelled-error.mjs +1 -1
- package/esm/errors/supervisor-cancelled-error.mjs.map +1 -1
- package/esm/errors/supervisor-drift-error.d.mts +1 -1
- package/esm/errors/supervisor-drift-error.d.mts.map +1 -1
- package/esm/errors/supervisor-drift-error.mjs +1 -1
- package/esm/errors/supervisor-drift-error.mjs.map +1 -1
- package/esm/errors/supervisor-failed-error.d.mts +1 -1
- package/esm/errors/supervisor-failed-error.d.mts.map +1 -1
- package/esm/errors/supervisor-failed-error.mjs +1 -1
- package/esm/errors/supervisor-failed-error.mjs.map +1 -1
- package/esm/errors/supervisor-routing-error.d.mts +1 -1
- package/esm/errors/supervisor-routing-error.d.mts.map +1 -1
- package/esm/errors/supervisor-routing-error.mjs +1 -1
- package/esm/errors/supervisor-routing-error.mjs.map +1 -1
- package/esm/errors/tool-execution-error.d.mts +1 -1
- package/esm/errors/tool-execution-error.d.mts.map +1 -1
- package/esm/errors/tool-execution-error.mjs +1 -1
- package/esm/errors/tool-execution-error.mjs.map +1 -1
- package/esm/errors/workflow-cancelled-error.d.mts +1 -1
- package/esm/errors/workflow-cancelled-error.d.mts.map +1 -1
- package/esm/errors/workflow-cancelled-error.mjs +1 -1
- package/esm/errors/workflow-cancelled-error.mjs.map +1 -1
- package/esm/errors/workflow-drift-error.d.mts +1 -1
- package/esm/errors/workflow-drift-error.d.mts.map +1 -1
- package/esm/errors/workflow-drift-error.mjs +1 -1
- package/esm/errors/workflow-drift-error.mjs.map +1 -1
- package/esm/errors/workflow-error.d.mts +1 -1
- package/esm/errors/workflow-error.d.mts.map +1 -1
- package/esm/errors/workflow-error.mjs +1 -1
- package/esm/errors/workflow-error.mjs.map +1 -1
- package/esm/middleware/builtins/budget.d.mts +1 -1
- package/esm/middleware/builtins/budget.d.mts.map +1 -1
- package/esm/middleware/builtins/budget.mjs +1 -1
- package/esm/middleware/builtins/budget.mjs.map +1 -1
- package/esm/middleware/builtins/guardrail.d.mts +1 -1
- package/esm/middleware/builtins/guardrail.d.mts.map +1 -1
- package/esm/middleware/builtins/guardrail.mjs +1 -1
- package/esm/middleware/builtins/guardrail.mjs.map +1 -1
- package/esm/middleware/builtins/semantic-cache.d.mts +1 -1
- package/esm/middleware/builtins/semantic-cache.d.mts.map +1 -1
- package/esm/middleware/builtins/semantic-cache.mjs +1 -1
- package/esm/middleware/builtins/semantic-cache.mjs.map +1 -1
- package/esm/middleware/helpers/compose.d.mts +1 -1
- package/esm/middleware/helpers/compose.d.mts.map +1 -1
- package/esm/middleware/helpers/compose.mjs +1 -1
- package/esm/middleware/helpers/compose.mjs.map +1 -1
- package/esm/middleware/helpers/for-tool.d.mts +1 -1
- package/esm/middleware/helpers/for-tool.d.mts.map +1 -1
- package/esm/middleware/helpers/for-tool.mjs +1 -1
- package/esm/middleware/helpers/for-tool.mjs.map +1 -1
- package/esm/middleware/pipeline.d.mts +1 -1
- package/esm/middleware/pipeline.d.mts.map +1 -1
- package/esm/middleware/pipeline.mjs +1 -1
- package/esm/middleware/pipeline.mjs.map +1 -1
- package/esm/middleware/utils/extract-user-text.d.mts +1 -1
- package/esm/middleware/utils/extract-user-text.d.mts.map +1 -1
- package/esm/middleware/utils/extract-user-text.mjs +1 -1
- package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
- package/esm/middleware/utils/namespaced-state.d.mts +1 -1
- package/esm/middleware/utils/namespaced-state.d.mts.map +1 -1
- package/esm/middleware/utils/namespaced-state.mjs +1 -1
- package/esm/middleware/utils/namespaced-state.mjs.map +1 -1
- package/esm/mock/mock-agent.d.mts +1 -1
- package/esm/mock/mock-agent.d.mts.map +1 -1
- package/esm/mock/mock-agent.mjs +1 -1
- package/esm/mock/mock-agent.mjs.map +1 -1
- package/esm/mock/mock-config.type.d.mts +1 -1
- package/esm/mock/mock-config.type.d.mts.map +1 -1
- package/esm/mock/mock-model.d.mts +1 -1
- package/esm/mock/mock-model.d.mts.map +1 -1
- package/esm/mock/mock-model.mjs +1 -1
- package/esm/mock/mock-model.mjs.map +1 -1
- package/esm/mock/mock-sdk.d.mts +1 -1
- package/esm/mock/mock-sdk.d.mts.map +1 -1
- package/esm/mock/mock-sdk.mjs +1 -1
- package/esm/mock/mock-sdk.mjs.map +1 -1
- package/esm/supervisor/as-tool.d.mts +1 -1
- package/esm/supervisor/as-tool.d.mts.map +1 -1
- package/esm/supervisor/as-tool.mjs +1 -1
- package/esm/supervisor/as-tool.mjs.map +1 -1
- package/esm/supervisor/cancellation.d.mts +1 -1
- package/esm/supervisor/cancellation.d.mts.map +1 -1
- package/esm/supervisor/cancellation.mjs +1 -1
- package/esm/supervisor/cancellation.mjs.map +1 -1
- package/esm/supervisor/decide.mjs +1 -1
- package/esm/supervisor/decide.mjs.map +1 -1
- package/esm/supervisor/emitter.d.mts +1 -1
- package/esm/supervisor/emitter.d.mts.map +1 -1
- package/esm/supervisor/emitter.mjs +1 -1
- package/esm/supervisor/emitter.mjs.map +1 -1
- package/esm/supervisor/entries.d.mts +1 -1
- package/esm/supervisor/entries.d.mts.map +1 -1
- package/esm/supervisor/entries.mjs +1 -1
- package/esm/supervisor/entries.mjs.map +1 -1
- package/esm/supervisor/execution.d.mts +1 -1
- package/esm/supervisor/execution.d.mts.map +1 -1
- package/esm/supervisor/execution.mjs +1 -1
- package/esm/supervisor/execution.mjs.map +1 -1
- package/esm/supervisor/router-prompt.d.mts +1 -1
- package/esm/supervisor/router-prompt.d.mts.map +1 -1
- package/esm/supervisor/router-prompt.mjs +1 -1
- package/esm/supervisor/router-prompt.mjs.map +1 -1
- package/esm/supervisor/signature.d.mts +1 -1
- package/esm/supervisor/signature.d.mts.map +1 -1
- package/esm/supervisor/signature.mjs +1 -1
- package/esm/supervisor/signature.mjs.map +1 -1
- package/esm/supervisor/snapshot.d.mts +1 -1
- package/esm/supervisor/snapshot.d.mts.map +1 -1
- package/esm/supervisor/snapshot.mjs +1 -1
- package/esm/supervisor/snapshot.mjs.map +1 -1
- package/esm/supervisor/supervisor-stream.d.mts +1 -1
- package/esm/supervisor/supervisor-stream.d.mts.map +1 -1
- package/esm/supervisor/supervisor-stream.mjs +1 -1
- package/esm/supervisor/supervisor-stream.mjs.map +1 -1
- package/esm/supervisor/supervisor.d.mts +1 -1
- package/esm/supervisor/supervisor.d.mts.map +1 -1
- package/esm/supervisor/supervisor.mjs +1 -1
- package/esm/supervisor/supervisor.mjs.map +1 -1
- package/esm/system-prompt/instruction.d.mts +1 -1
- package/esm/system-prompt/instruction.d.mts.map +1 -1
- package/esm/system-prompt/instruction.mjs +1 -1
- package/esm/system-prompt/instruction.mjs.map +1 -1
- package/esm/system-prompt/persona.d.mts +1 -1
- package/esm/system-prompt/persona.d.mts.map +1 -1
- package/esm/system-prompt/persona.mjs +1 -1
- package/esm/system-prompt/persona.mjs.map +1 -1
- package/esm/system-prompt/render-placeholders.d.mts +1 -1
- package/esm/system-prompt/render-placeholders.d.mts.map +1 -1
- package/esm/system-prompt/render-placeholders.mjs +1 -1
- package/esm/system-prompt/render-placeholders.mjs.map +1 -1
- package/esm/system-prompt/system-prompt.d.mts +1 -1
- package/esm/system-prompt/system-prompt.d.mts.map +1 -1
- package/esm/system-prompt/system-prompt.mjs +1 -1
- package/esm/system-prompt/system-prompt.mjs.map +1 -1
- package/esm/tool/tool.d.mts +1 -1
- package/esm/tool/tool.d.mts.map +1 -1
- package/esm/tool/tool.mjs +3 -2
- package/esm/tool/tool.mjs.map +1 -1
- package/esm/utils/compute-cost.d.mts +1 -1
- package/esm/utils/compute-cost.d.mts.map +1 -1
- package/esm/utils/compute-cost.mjs +1 -1
- package/esm/utils/compute-cost.mjs.map +1 -1
- package/esm/utils/extract-json-payload.d.mts +1 -1
- package/esm/utils/extract-json-payload.d.mts.map +1 -1
- package/esm/utils/extract-json-payload.mjs +1 -1
- package/esm/utils/extract-json-payload.mjs.map +1 -1
- package/esm/utils/generate-run-id.d.mts +1 -1
- package/esm/utils/generate-run-id.d.mts.map +1 -1
- package/esm/utils/generate-run-id.mjs +1 -1
- package/esm/utils/generate-run-id.mjs.map +1 -1
- package/esm/utils/json-schema.d.mts +1 -1
- package/esm/utils/json-schema.d.mts.map +1 -1
- package/esm/utils/json-schema.mjs +1 -1
- package/esm/utils/json-schema.mjs.map +1 -1
- package/esm/utils/prepare-attachment-part.d.mts +1 -1
- package/esm/utils/prepare-attachment-part.d.mts.map +1 -1
- package/esm/utils/prepare-attachment-part.mjs +1 -1
- package/esm/utils/prepare-attachment-part.mjs.map +1 -1
- package/esm/utils/resolve-attachment.d.mts +1 -1
- package/esm/utils/resolve-attachment.d.mts.map +1 -1
- package/esm/utils/resolve-attachment.mjs +1 -1
- package/esm/utils/resolve-attachment.mjs.map +1 -1
- package/esm/utils/safe-json-parse.d.mts +1 -1
- package/esm/utils/safe-json-parse.d.mts.map +1 -1
- package/esm/utils/safe-json-parse.mjs +1 -1
- package/esm/utils/safe-json-parse.mjs.map +1 -1
- package/esm/utils/stamp-report-lineage.d.mts +1 -1
- package/esm/utils/stamp-report-lineage.d.mts.map +1 -1
- package/esm/utils/stamp-report-lineage.mjs +1 -1
- package/esm/utils/stamp-report-lineage.mjs.map +1 -1
- package/esm/utils/token-count.d.mts +1 -1
- package/esm/utils/token-count.d.mts.map +1 -1
- package/esm/utils/token-count.mjs +1 -1
- package/esm/utils/token-count.mjs.map +1 -1
- package/esm/workflow/as-tool.mjs +1 -1
- package/esm/workflow/as-tool.mjs.map +1 -1
- package/esm/workflow/cancellation.mjs +1 -1
- package/esm/workflow/cancellation.mjs.map +1 -1
- package/esm/workflow/emitter.mjs +1 -1
- package/esm/workflow/emitter.mjs.map +1 -1
- package/esm/workflow/engine.mjs +1 -1
- package/esm/workflow/engine.mjs.map +1 -1
- package/esm/workflow/retry.mjs +1 -1
- package/esm/workflow/retry.mjs.map +1 -1
- package/esm/workflow/router.mjs +1 -1
- package/esm/workflow/router.mjs.map +1 -1
- package/esm/workflow/run-scoped-emitter.mjs +1 -1
- package/esm/workflow/run-scoped-emitter.mjs.map +1 -1
- package/esm/workflow/signature.d.mts +1 -1
- package/esm/workflow/signature.d.mts.map +1 -1
- package/esm/workflow/signature.mjs +1 -1
- package/esm/workflow/signature.mjs.map +1 -1
- package/esm/workflow/snapshot.mjs +1 -1
- package/esm/workflow/snapshot.mjs.map +1 -1
- package/esm/workflow/state.mjs +1 -1
- package/esm/workflow/state.mjs.map +1 -1
- package/esm/workflow/step-runner.mjs +1 -1
- package/esm/workflow/step-runner.mjs.map +1 -1
- package/esm/workflow/step.d.mts +1 -1
- package/esm/workflow/step.d.mts.map +1 -1
- package/esm/workflow/step.mjs +1 -1
- package/esm/workflow/step.mjs.map +1 -1
- package/esm/workflow/workflow.d.mts +1 -1
- package/esm/workflow/workflow.d.mts.map +1 -1
- package/esm/workflow/workflow.mjs +1 -1
- package/esm/workflow/workflow.mjs.map +1 -1
- package/package.json +3 -3
package/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["LOG_MODULE","called","log","invoke","safeStringify","resolveSnapshotStore","LOG_MODULE_BASE","log","toAIError","computeSignature","hash","computeSignature","generateRunId","validate","asTool","createCancelledError","loadSnapshotForResume","createCancelledError","log","createCancelledError","generateRunId","loadSnapshotForResume","asTool","combined"],"sources":["../../../../../@warlock.js/ai/src/errors/ai-error.ts","../../../../../@warlock.js/ai/src/errors/agent-execution-error.ts","../../../../../@warlock.js/ai/src/errors/agent-cancelled-error.ts","../../../../../@warlock.js/ai/src/errors/agent-max-trips-error.ts","../../../../../@warlock.js/ai/src/errors/budget-exceeded-error.ts","../../../../../@warlock.js/ai/src/errors/provider-error.ts","../../../../../@warlock.js/ai/src/errors/content-filter-error.ts","../../../../../@warlock.js/ai/src/errors/context-length-exceeded-error.ts","../../../../../@warlock.js/ai/src/errors/guardrail-violation-error.ts","../../../../../@warlock.js/ai/src/errors/invalid-request-error.ts","../../../../../@warlock.js/ai/src/errors/supervisor-failed-error.ts","../../../../../@warlock.js/ai/src/errors/max-iterations-error.ts","../../../../../@warlock.js/ai/src/errors/workflow-error.ts","../../../../../@warlock.js/ai/src/errors/max-steps-exceeded-error.ts","../../../../../@warlock.js/ai/src/errors/provider-auth-error.ts","../../../../../@warlock.js/ai/src/errors/provider-rate-limit-error.ts","../../../../../@warlock.js/ai/src/errors/provider-timeout-error.ts","../../../../../@warlock.js/ai/src/errors/quota-exceeded-error.ts","../../../../../@warlock.js/ai/src/errors/routing-error.ts","../../../../../@warlock.js/ai/src/errors/schema-validation-error.ts","../../../../../@warlock.js/ai/src/errors/step-failed-error.ts","../../../../../@warlock.js/ai/src/errors/supervisor-cancelled-error.ts","../../../../../@warlock.js/ai/src/errors/supervisor-drift-error.ts","../../../../../@warlock.js/ai/src/errors/supervisor-routing-error.ts","../../../../../@warlock.js/ai/src/errors/tool-execution-error.ts","../../../../../@warlock.js/ai/src/errors/workflow-cancelled-error.ts","../../../../../@warlock.js/ai/src/errors/workflow-drift-error.ts","../../../../../@warlock.js/ai/src/middleware/utils/extract-user-text.ts","../../../../../@warlock.js/ai/src/middleware/utils/namespaced-state.ts","../../../../../@warlock.js/ai/src/middleware/builtins/budget.ts","../../../../../@warlock.js/ai/src/middleware/builtins/guardrail.ts","../../../../../@warlock.js/ai/src/config.ts","../../../../../@warlock.js/ai/src/middleware/builtins/semantic-cache.ts","../../../../../@warlock.js/ai/src/middleware/helpers/compose.ts","../../../../../@warlock.js/ai/src/middleware/helpers/for-tool.ts","../../../../../@warlock.js/ai/src/middleware/pipeline.ts","../../../../../@warlock.js/ai/src/utils/compute-cost.ts","../../../../../@warlock.js/ai/src/utils/extract-json-payload.ts","../../../../../@warlock.js/ai/src/utils/generate-run-id.ts","../../../../../@warlock.js/ai/src/utils/json-schema.ts","../../../../../@warlock.js/ai/src/utils/resolve-attachment.ts","../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts","../../../../../@warlock.js/ai/src/utils/safe-json-parse.ts","../../../../../@warlock.js/ai/src/contracts/result/base-report.type.ts","../../../../../@warlock.js/ai/src/utils/stamp-report-lineage.ts","../../../../../@warlock.js/ai/src/utils/token-count.ts","../../../../../@warlock.js/ai/src/agent/agent-input-builder.ts","../../../../../@warlock.js/ai/src/agent/agent-log-event.ts","../../../../../@warlock.js/ai/src/agent/agent-stream.ts","../../../../../@warlock.js/ai/src/agent/agent-to-stream-event.ts","../../../../../@warlock.js/ai/src/agent/json-stream-guard.ts","../../../../../@warlock.js/ai/src/agent/agent.ts","../../../../../@warlock.js/ai/src/tool/tool.ts","../../../../../@warlock.js/ai/src/supervisor/as-tool.ts","../../../../../@warlock.js/ai/src/supervisor/emitter.ts","../../../../../@warlock.js/ai/src/supervisor/entries.ts","../../../../../@warlock.js/ai/src/contracts/end.type.ts","../../../../../@warlock.js/ai/src/supervisor/cancellation.ts","../../../../../@warlock.js/ai/src/supervisor/router-prompt.ts","../../../../../@warlock.js/ai/src/supervisor/decide.ts","../../../../../@warlock.js/ai/src/supervisor/snapshot.ts","../../../../../@warlock.js/ai/src/supervisor/execution.ts","../../../../../@warlock.js/ai/src/supervisor/signature.ts","../../../../../@warlock.js/ai/src/supervisor/supervisor-stream.ts","../../../../../@warlock.js/ai/src/supervisor/supervisor.ts","../../../../../@warlock.js/ai/src/system-prompt/render-placeholders.ts","../../../../../@warlock.js/ai/src/system-prompt/instruction.ts","../../../../../@warlock.js/ai/src/system-prompt/persona.ts","../../../../../@warlock.js/ai/src/system-prompt/system-prompt.ts","../../../../../@warlock.js/ai/src/workflow/step.ts","../../../../../@warlock.js/ai/src/workflow/as-tool.ts","../../../../../@warlock.js/ai/src/workflow/emitter.ts","../../../../../@warlock.js/ai/src/workflow/cancellation.ts","../../../../../@warlock.js/ai/src/workflow/router.ts","../../../../../@warlock.js/ai/src/workflow/run-scoped-emitter.ts","../../../../../@warlock.js/ai/src/workflow/snapshot.ts","../../../../../@warlock.js/ai/src/workflow/state.ts","../../../../../@warlock.js/ai/src/workflow/retry.ts","../../../../../@warlock.js/ai/src/workflow/step-runner.ts","../../../../../@warlock.js/ai/src/workflow/engine.ts","../../../../../@warlock.js/ai/src/workflow/signature.ts","../../../../../@warlock.js/ai/src/workflow/workflow.ts","../../../../../@warlock.js/ai/src/ai.ts","../../../../../@warlock.js/ai/src/mock/mock-model.ts","../../../../../@warlock.js/ai/src/mock/mock-sdk.ts","../../../../../@warlock.js/ai/src/mock/mock-agent.ts"],"sourcesContent":["import type { ErrorCategory } from \"./error-category.type\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Optional constructor payload shared by every `AIError` subclass.\n *\n * `cause` carries the original thrown value (SDK error, runtime crash,\n * validation failure) so downstream logging and debuggers can still\n * reach it. `context` is a free-form diagnostic bag for provider-raw\n * metadata (status codes, request ids, response headers) that shouldn't\n * be promoted to typed fields but is useful in logs and telemetry.\n *\n * **No `category` here.** Category is fixed per subclass via the\n * class-level `static defaultCategory`. Subclasses ARE their\n * category — `RateLimitError` is always `\"rate-limit\"`, never\n * something else at runtime. Direct `new AIError(...)` callers (the\n * one legitimate override case, since the base catch-all has no\n * specific class) receive a separate 4th constructor argument\n * instead, so the override is structurally unreachable from subclass\n * call sites.\n */\nexport type AIErrorOptions = {\n cause?: unknown;\n context?: Record<string, unknown>;\n};\n\n/**\n * Base class for every error thrown (or surfaced via `result.error`) by\n * `@warlock.js/ai` and its provider adapter packages.\n *\n * **Role.** The single typed error contract across the AI framework.\n * Every thrown error anywhere in `@warlock.js/ai*` is either an\n * `AIError` itself or one of its subclasses — plain `Error` must never\n * leak out. Consumers branch either on the narrow `error.code` (stable\n * string), on `error.category` (coarse dashboard grouping), or on\n * `instanceof` a specific subclass.\n *\n * **Independence.** Deliberately extends the platform `Error` directly\n * — never `HttpError` from `@warlock.js/core`. The AI framework is a\n * standalone product; coupling its error base to a web framework would\n * force every consumer to pull in the HTTP layer even when they only\n * use AI in a CLI, worker, or test.\n *\n * **Fields.**\n * - `code` — stable machine-readable identifier (see `AIErrorCode`).\n * - `category` — coarse `ErrorCategory` for dashboards / retry policy.\n * Resolved at construction from the subclass's `static defaultCategory`\n * (or, for direct `new AIError(...)` calls, from the explicit 4th\n * constructor argument).\n * - `cause` — optional original thrown value (SDK error, nested error,\n * raw value). Preserves root cause through re-wrapping.\n * - `context` — optional free-form diagnostic bag (status, requestId,\n * headers). Consumers treat it as opaque; logs and telemetry read it.\n *\n * **Category override — direct AIError usage only.** Subclasses ARE\n * their category by type; there's no legitimate runtime override at\n * the subclass level. The 4th constructor argument exists ONLY for\n * direct `new AIError(...)` callers, who would otherwise be stuck with\n * the `\"unknown\"` default. Subclasses construct via `super(code,\n * message, options)` and physically cannot reach the override slot\n * through their own typed signatures.\n *\n * @example\n * try {\n * await agent.execute(\"hello\");\n * } catch (error) {\n * if (error instanceof AIError) {\n * console.error(`[${error.code}] (${error.category}) ${error.message}`);\n * }\n * }\n *\n * @example\n * // Direct AIError construction with explicit category — escape hatch\n * // for call sites that lack a specific subclass.\n * throw new AIError(\"UNEXPECTED\", \"transient glitch\", undefined, \"provider\");\n */\nexport class AIError extends Error {\n /**\n * Class-level category for every instance of this error type.\n * Subclasses redeclare with their own concrete `ErrorCategory` so\n * `error.category` is correct without per-call wiring. The base\n * class keeps `\"unknown\"` so untyped direct throws of `AIError`\n * itself remain honest about their lack of dispatch information\n * (and can override via the 4th constructor argument).\n */\n public static readonly defaultCategory: ErrorCategory = \"unknown\";\n\n public readonly code: AIErrorCode;\n public readonly category: ErrorCategory;\n public readonly context?: Record<string, unknown>;\n\n public constructor(\n code: AIErrorCode,\n message: string,\n options?: AIErrorOptions,\n category?: ErrorCategory,\n ) {\n super(message);\n\n this.name = \"AIError\";\n this.code = code;\n this.context = options?.context;\n this.category = category ?? (this.constructor as typeof AIError).defaultCategory;\n\n if (options?.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base for agent runtime failures that aren't schema / tool / provider\n * problems — runtime-structural issues inside the trip loop or\n * authoring-time middleware misconfiguration. Two specialized\n * subclasses cover the two non-generic cases:\n *\n * - {@link AgentCancelledError} (`AGENT_CANCELLED`) — caller-driven\n * abort via `AbortSignal`.\n * - {@link AgentMaxTripsError} (`AGENT_MAX_TRIPS`) — trip loop hit\n * the `maxTrips` cap without a natural stop.\n *\n * Use the base class directly for anything else (unregistered tool\n * dispatch, authoring-time middleware validation, surprise\n * exceptions). The subclasses exist so consumers can branch on a\n * dedicated `instanceof` / category without inferring from `context`\n * flags or parsing the message.\n *\n * @example\n * if (result.error?.code === \"AGENT_EXEC_FAILED\") {\n * logger.warn(\"unexpected agent failure\", result.error.context);\n * }\n */\nexport class AgentExecutionError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"AGENT_EXEC_FAILED\",\n ) {\n super(code, message, options);\n this.name = \"AgentExecutionError\";\n }\n}\n","import { AgentExecutionError } from \"./agent-execution-error\";\nimport type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload for {@link AgentCancelledError}. `cancelledAt` is the\n * ISO-8601 timestamp at which the abort was observed; `reason`\n * carries the value the caller supplied to `controller.abort(reason)`\n * when present.\n */\nexport type AgentCancelledErrorOptions = AIErrorOptions & {\n cancelledAt?: string;\n reason?: string;\n};\n\n/**\n * Agent run was cancelled via `AbortSignal` before it could finish.\n * Between-trip cancellation is guaranteed; mid-trip cancellation is\n * best-effort (the signal is threaded into the provider adapter's\n * HTTP client when supported).\n *\n * Surfaced on `result.error` rather than thrown — `agent.execute()`\n * still returns with `report.status = \"cancelled\"` and partial trip\n * history intact. Consumers branch on the class (not the message) to\n * distinguish caller-initiated stops from other failures.\n *\n * **Why split from `AgentExecutionError`.** Cancellation is a\n * different operational signal from \"the agent crashed\" — retry\n * policy and dashboards typically want different behavior for each.\n * Keeping cancellation in its own class lets the category\n * (`\"cancelled\"`) be set declaratively per type instead of inferred\n * from a `context.cancelled === true` flag.\n *\n * @example\n * const result = await agent.execute(input, { signal });\n * if (result.error instanceof AgentCancelledError) {\n * // caller pulled the plug — don't retry, surface a \"stopped\" UI\n * return { status: \"cancelled\" };\n * }\n */\nexport class AgentCancelledError extends AgentExecutionError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt?: string;\n public readonly reason?: string;\n\n public constructor(message: string, options?: AgentCancelledErrorOptions) {\n super(message, options, \"AGENT_CANCELLED\");\n this.name = \"AgentCancelledError\";\n this.cancelledAt = options?.cancelledAt;\n this.reason = options?.reason;\n }\n}\n","import { AgentExecutionError } from \"./agent-execution-error\";\nimport type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload for {@link AgentMaxTripsError}. `maxTrips` is the cap the\n * agent hit — useful for log/metric attribution and for retry-with-\n * higher-cap recovery strategies.\n */\nexport type AgentMaxTripsErrorOptions = AIErrorOptions & {\n maxTrips: number;\n};\n\n/**\n * Runaway-loop hard guard: the agent's trip loop ran `maxTrips` round\n * trips to the model without the model issuing a natural stop. The\n * loop terminates with this typed error on `result.error` and the\n * full trip history preserved in `result.report.trips` so consumers\n * can see where the loop got stuck.\n *\n * **Not retryable by default.** A run that hit the cap usually\n * indicates either a tool the agent can't satisfy (causing infinite\n * re-asks) or a model that won't commit to an answer. Bumping\n * `maxTrips` and retrying without root-causing the underlying issue\n * just burns more tokens.\n *\n * **Why split from `AgentExecutionError`.** The catch-all base wears\n * too many hats — cancellation vs. max-trips vs. generic crashes had\n * to be disambiguated from `context` flags or message regex. Split\n * subclasses let category dispatch (`\"max-trips\"`) and consumer\n * branching (`instanceof`) work without inference.\n *\n * @example\n * if (result.error instanceof AgentMaxTripsError) {\n * logger.warn(\"agent hit trip cap\", { max: result.error.maxTrips });\n * }\n */\nexport class AgentMaxTripsError extends AgentExecutionError {\n public static readonly defaultCategory: ErrorCategory = \"max-trips\";\n\n public readonly maxTrips: number;\n\n public constructor(message: string, options: AgentMaxTripsErrorOptions) {\n super(message, options, \"AGENT_MAX_TRIPS\");\n this.name = \"AgentMaxTripsError\";\n this.maxTrips = options.maxTrips;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Unit of the budget being enforced. `tokens` for context/output\n * caps, `usd` for monetary caps, `requests` for call-count caps.\n */\nexport type BudgetUnit = \"tokens\" | \"usd\" | \"requests\";\n\n/**\n * Payload for `BudgetExceededError`. All three fields are required so\n * consumers can present the breach numerically without having to\n * reparse the message.\n */\nexport type BudgetExceededErrorOptions = AIErrorOptions & {\n limit: number;\n actual: number;\n unit: BudgetUnit;\n};\n\n/**\n * A user- or framework-configured budget was exceeded mid-execution.\n *\n * **Not thrown yet.** The class is defined here so v2's budget\n * middleware can throw it without a breaking release of the error\n * hierarchy. Shape is locked: `{ limit, actual, unit }`.\n *\n * @example\n * if (error instanceof BudgetExceededError && error.unit === \"usd\") {\n * alertFinance(error.actual, error.limit);\n * }\n */\nexport class BudgetExceededError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"budget\";\n\n public readonly limit: number;\n public readonly actual: number;\n public readonly unit: BudgetUnit;\n\n public constructor(message: string, options: BudgetExceededErrorOptions) {\n super(\"BUDGET_EXCEEDED\", message, options);\n this.name = \"BudgetExceededError\";\n this.limit = options.limit;\n this.actual = options.actual;\n this.unit = options.unit;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Any failure that originated from the model provider (OpenAI, Azure,\n * OpenRouter, local gateway). Base class for the provider subclasses\n * below — raw provider errors caught in an adapter are always wrapped\n * into *some* `ProviderError` so downstream code can branch on\n * `instanceof ProviderError` when any provider-side failure will do.\n *\n * **Subclasses (more specific first).**\n * - `ProviderRateLimitError` — 429 / rate-limit / quota exhaustion.\n * - `ProviderTimeoutError` — connection or request timeout.\n * - `ContextLengthExceededError` — prompt exceeded the model window.\n * - `ContentFilterError` — response blocked by provider safety policy.\n * - `ProviderAuthError` — bad / expired API key.\n * - `InvalidRequestError` — catch-all 4xx not covered above.\n *\n * When no subclass fits (e.g. 5xx server error, unknown network\n * failure), adapters throw plain `ProviderError` with the raw payload\n * captured in `context`.\n *\n * @example\n * if (result.error instanceof ProviderError) {\n * if (result.error instanceof ProviderRateLimitError) {\n * return retryAfter(result.error.retryAfter ?? 1000);\n * }\n * }\n */\nexport class ProviderError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"provider\";\n\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"PROVIDER_ERROR\",\n ) {\n super(code, message, options);\n this.name = \"ProviderError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ContentFilterError`. Both fields optional — providers\n * don't consistently disclose the specific filter reason or\n * categories, especially when the block is pre-generation.\n */\nexport type ContentFilterErrorOptions = AIErrorOptions & {\n reason?: string;\n categories?: string[];\n};\n\n/**\n * Response (or request) was blocked by the provider's safety filter.\n * Not retryable with the same input — reshape the prompt or lean on\n * a less-restrictive model.\n *\n * @example\n * if (result.error instanceof ContentFilterError) {\n * return respondWithPolicyMessage(result.error.reason);\n * }\n */\nexport class ContentFilterError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"content-filter\";\n\n public readonly reason?: string;\n public readonly categories?: string[];\n\n public constructor(message: string, options?: ContentFilterErrorOptions) {\n super(message, options, \"CONTENT_FILTER\");\n this.name = \"ContentFilterError\";\n this.reason = options?.reason;\n this.categories = options?.categories;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ContextLengthExceededError`. All fields are optional —\n * providers inconsistently surface exact token counts and the\n * model's limit. When present, they let callers compute a trim\n * target; when absent, the error still categorizes the failure.\n */\nexport type ContextLengthExceededErrorOptions = AIErrorOptions & {\n limit?: number;\n actual?: number;\n modelName?: string;\n};\n\n/**\n * The request's prompt (messages + tools + schema) exceeded the\n * model's context window. Not retryable without shortening the input.\n *\n * Typically surfaced as OpenAI 400 with `code: \"context_length_exceeded\"`.\n *\n * @example\n * if (result.error instanceof ContextLengthExceededError) {\n * messages = truncateOldestTurns(messages);\n * return agent.execute(input, { history: messages });\n * }\n */\nexport class ContextLengthExceededError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"context-length\";\n\n public readonly limit?: number;\n public readonly actual?: number;\n public readonly modelName?: string;\n\n public constructor(\n message: string,\n options?: ContextLengthExceededErrorOptions,\n ) {\n super(message, options, \"CONTEXT_LENGTH_EXCEEDED\");\n this.name = \"ContextLengthExceededError\";\n this.limit = options?.limit;\n this.actual = options?.actual;\n this.modelName = options?.modelName;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Phase at which a guardrail rejected the content — `\"input\"` when the\n * violation was detected on the outbound prompt (before the model saw\n * it), `\"output\"` when it was detected on the model's response (before\n * the caller saw it).\n */\nexport type GuardrailPhase = \"input\" | \"output\";\n\n/**\n * Payload for `GuardrailViolationError`. `phase` tells the caller\n * whether the prompt or the response tripped the check; `reason` is\n * the free-form explanation the guardrail middleware produced;\n * `guardrail` names the offending middleware so operators can tune a\n * specific rule without hunting through logs.\n */\nexport type GuardrailViolationErrorOptions = AIErrorOptions & {\n phase: GuardrailPhase;\n reason: string;\n guardrail?: string;\n};\n\n/**\n * A guardrail middleware rejected the prompt or response mid-execution.\n *\n * **Role.** The typed abort surface for `ai.middleware.guardrail`.\n * Consumers branch on `error.phase` to distinguish \"the user asked\n * something disallowed\" (`\"input\"`) from \"the model produced something\n * disallowed\" (`\"output\"`) — the two failure modes have very different\n * product responses (block vs. retry, or surface a policy message vs.\n * re-prompt the model).\n *\n * Thrown from inside the middleware pipeline's `trip.before` / `trip.after`\n * hooks; surfaced to the caller via `result.error` like every other\n * `AIError`.\n *\n * @example\n * if (result.error instanceof GuardrailViolationError) {\n * if (result.error.phase === \"input\") {\n * return respondWithPolicyMessage(result.error.reason);\n * }\n * return retryWithSanitizedPrompt();\n * }\n */\nexport class GuardrailViolationError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"guardrail\";\n\n public readonly phase: GuardrailPhase;\n public readonly reason: string;\n public readonly guardrail?: string;\n\n public constructor(message: string, options: GuardrailViolationErrorOptions) {\n super(\"GUARDRAIL_VIOLATION\", message, options);\n\n this.name = \"GuardrailViolationError\";\n this.phase = options.phase;\n this.reason = options.reason;\n this.guardrail = options.guardrail;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider rejected the request as malformed — bad model name,\n * unsupported feature, missing required field, image attached to a\n * non-vision model, etc. The catch-all for 4xx responses that aren't\n * auth, rate-limit, context-length, or content-filter.\n *\n * Also thrown from the agent when user-side validation fails at the\n * boundary (e.g. vision gate, malformed attachment shape) — the\n * category is \"you sent something the provider / agent cannot use\".\n *\n * @example\n * if (result.error instanceof InvalidRequestError) {\n * logger.error(\"bad agent input\", { context: result.error.context });\n * }\n */\nexport class InvalidRequestError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"validation\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_INVALID_REQUEST\");\n this.name = \"InvalidRequestError\";\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base class for every supervisor-specific failure surfaced from\n * `supervisor.execute()` / `supervisor.resume()` / authoring-time\n * `ai.supervisor()` validation.\n *\n * **Role.** Anchor for the `SUPERVISOR_*` code family. Subclasses\n * carry precise codes (`SUPERVISOR_MAX_ITERATIONS`,\n * `SUPERVISOR_INVALID_ROUTE`, …); this base catches everything a\n * supervisor run can produce that isn't already an agent / tool /\n * provider / workflow error bubbling up from a child execution.\n *\n * Child-execution errors (agent, tool, provider, workflow) flow\n * through the supervisor unchanged — they are captured on the\n * relevant branch snapshot and, if fatal, wrapped as the `cause` of a\n * `SupervisorFailedError` only when the supervisor itself has no\n * narrower subclass to throw.\n *\n * @example\n * try {\n * ai.supervisor({\n * route: () => \"triage\",\n * router: routerAgent,\n * intents: { triage },\n * });\n * } catch (error) {\n * if (error instanceof SupervisorFailedError) {\n * console.error(error.code, error.message);\n * }\n * }\n */\nexport class SupervisorFailedError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"SUPERVISOR_FAILED\",\n ) {\n super(code, message, options);\n this.name = \"SupervisorFailedError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type MaxIterationsErrorOptions = AIErrorOptions & {\n maxIterations: number;\n};\n\n/**\n * Hard-cap guard: the supervisor ran `maxIterations` loop turns\n * without reaching a terminal decision (`END`, `satisfied: true`, or\n * cancellation). Terminates the run immediately with a typed error on\n * `result.error` — partial per-iteration snapshots are still\n * available on `result.report.snapshots`.\n *\n * @example\n * const { error, report } = await supervisor.execute(input);\n * if (error?.code === \"SUPERVISOR_MAX_ITERATIONS\") {\n * logger.warn(\"supervisor did not converge\", {\n * iterations: report.iterations,\n * });\n * }\n */\nexport class MaxIterationsError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"max-iterations\";\n\n public readonly maxIterations: number;\n\n public constructor(message: string, options: MaxIterationsErrorOptions) {\n super(message, options, \"SUPERVISOR_MAX_ITERATIONS\");\n this.name = \"MaxIterationsError\";\n this.maxIterations = options.maxIterations;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base class for all workflow-specific failures. Subclasses carry\n * precise codes; this base catches everything `workflow.execute()`\n * can produce beyond agent/tool/provider errors.\n */\nexport class WorkflowError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"WORKFLOW_ERROR\",\n ) {\n super(code, message, options);\n this.name = \"WorkflowError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type MaxStepsExceededErrorOptions = AIErrorOptions & {\n maxSteps: number;\n};\n\n/**\n * Runaway-loop hard guard: workflow executed more step transitions\n * than `maxSteps` allows. Terminates the workflow immediately.\n */\nexport class MaxStepsExceededError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"max-steps\";\n\n public readonly maxSteps: number;\n\n public constructor(message: string, options: MaxStepsExceededErrorOptions) {\n super(message, options, \"WORKFLOW_MAX_STEPS\");\n this.name = \"MaxStepsExceededError\";\n this.maxSteps = options.maxSteps;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider rejected the credential — missing / invalid / expired API\n * key or insufficient permissions on the underlying account. Not\n * retryable; fix the credential and retry.\n *\n * @example\n * if (result.error instanceof ProviderAuthError) {\n * notifyOps(\"rotate API key\", result.error.context);\n * }\n */\nexport class ProviderAuthError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"auth\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_AUTH\");\n this.name = \"ProviderAuthError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ProviderRateLimitError`. `retryAfter` is the server's\n * hint (typically parsed from the `Retry-After` header) in milliseconds.\n */\nexport type ProviderRateLimitErrorOptions = AIErrorOptions & {\n retryAfter?: number;\n};\n\n/**\n * Provider refused the call because the account (or key, or window)\n * is over its rate-limit or quota. Retryable after `retryAfter`\n * milliseconds — consumers are expected to back off before retrying.\n *\n * Covers both transient `429 Too Many Requests` and the billing-level\n * `insufficient_quota` case; the adapter decides which provider\n * signals map here.\n *\n * @example\n * if (result.error instanceof ProviderRateLimitError) {\n * await sleep(result.error.retryAfter ?? 1000);\n * }\n */\nexport class ProviderRateLimitError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"rate-limit\";\n\n public readonly retryAfter?: number;\n\n public constructor(message: string, options?: ProviderRateLimitErrorOptions) {\n super(message, options, \"PROVIDER_RATE_LIMIT\");\n this.name = \"ProviderRateLimitError\";\n this.retryAfter = options?.retryAfter;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider call timed out — either at the transport layer (socket\n * connection) or on the server side (request exceeded the provider's\n * processing deadline). Idempotent retries are usually safe.\n *\n * @example\n * if (result.error instanceof ProviderTimeoutError) {\n * return retry();\n * }\n */\nexport class ProviderTimeoutError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"timeout\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_TIMEOUT\");\n this.name = \"ProviderTimeoutError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider refused the call because the account has exhausted its\n * paid quota (monthly credit, billing cap, subscription tier limit).\n *\n * **Not retryable.** Unlike `ProviderRateLimitError` — where the\n * bucket refills after `retryAfter` milliseconds — this one needs\n * human intervention: top up the account, upgrade the plan, or\n * switch to a different key. Consumers who blindly back-off-and-retry\n * on rate-limit errors would loop forever here, which is why the two\n * are split.\n *\n * Typically surfaced as OpenAI `code: \"insufficient_quota\"`.\n *\n * **Distinct from `BudgetExceededError`.** `QuotaExceededError` is\n * the *provider* telling us their billing cap is hit.\n * `BudgetExceededError` is our *own* middleware enforcing a\n * user-configured ceiling client-side.\n *\n * @example\n * if (result.error instanceof QuotaExceededError) {\n * await pagerDuty.trigger(\"openai quota exhausted\");\n * return fallbackResponse();\n * }\n */\nexport class QuotaExceededError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"quota\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_QUOTA_EXCEEDED\");\n this.name = \"QuotaExceededError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type RoutingErrorOptions = AIErrorOptions & {\n stepName: string;\n targetName?: string;\n};\n\n/**\n * `nextStep` returned an invalid `goto`, or the `nextStep` callback\n * itself threw. Routing is authoritative and has no recovery path —\n * the workflow terminates immediately.\n */\nexport class RoutingError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"routing\";\n\n public readonly stepName: string;\n public readonly targetName?: string;\n\n public constructor(message: string, options: RoutingErrorOptions) {\n super(message, options, \"WORKFLOW_INVALID_GOTO\");\n this.name = \"RoutingError\";\n this.stepName = options.stepName;\n this.targetName = options.targetName;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload passed to `SchemaValidationError`. Subset of\n * `AIErrorOptions` plus the machine-readable validation issues list.\n */\nexport type SchemaValidationErrorOptions = AIErrorOptions & {\n issues?: readonly StandardSchemaV1.Issue[];\n};\n\n/**\n * A `StandardSchemaV1` validation call returned issues, or the input\n * was not valid JSON before validation could even run.\n *\n * Produced in two places today:\n * - Agent output parsing — the final trip text failed `JSON.parse` or\n * the parsed value failed `~standard.validate`.\n * - Tool input validation — the model's raw arguments for a tool call\n * didn't match the tool's `input` schema.\n *\n * `issues` carries the structured validation result when available so\n * consumers can present per-field feedback.\n *\n * @example\n * if (result.error instanceof SchemaValidationError) {\n * for (const issue of result.error.issues ?? []) {\n * console.warn(issue.path, issue.message);\n * }\n * }\n */\nexport class SchemaValidationError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"schema\";\n\n public readonly issues?: readonly StandardSchemaV1.Issue[];\n\n public constructor(message: string, options?: SchemaValidationErrorOptions) {\n super(\"SCHEMA_VALIDATION_FAILED\", message, options);\n this.name = \"SchemaValidationError\";\n this.issues = options?.issues;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type StepFailedErrorOptions = AIErrorOptions & {\n stepName: string;\n attempts: number;\n};\n\n/**\n * A workflow step exhausted its retries (or was not retried) and\n * terminated with an error. `cause` carries the last underlying error.\n */\nexport class StepFailedError extends WorkflowError {\n public readonly stepName: string;\n public readonly attempts: number;\n\n public constructor(message: string, options: StepFailedErrorOptions) {\n super(message, options, \"STEP_FAILED\");\n this.name = \"StepFailedError\";\n this.stepName = options.stepName;\n this.attempts = options.attempts;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorCancelledErrorOptions = AIErrorOptions & {\n /** ISO-8601 timestamp at which the abort was observed by the supervisor. */\n cancelledAt: string;\n /** `controller.abort(reason)` payload when the caller supplied one. */\n reason?: string;\n};\n\n/**\n * Supervisor run was cancelled via `AbortSignal` before it could\n * finish. Between-iteration cancellation is guaranteed; mid-iteration\n * cancellation is best-effort (the signal is also threaded into every\n * in-flight child `execute()` call, but effectiveness depends on the\n * child primitive respecting it).\n *\n * On cancellation the supervisor returns normally with `status:\n * \"cancelled\"` and partial `report.snapshots` — the error is placed\n * on `result.error` rather than thrown.\n */\nexport class SupervisorCancelledError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt: string;\n public readonly reason?: string;\n\n public constructor(\n message: string,\n options: SupervisorCancelledErrorOptions,\n ) {\n super(message, options, \"SUPERVISOR_CANCELLED\");\n this.name = \"SupervisorCancelledError\";\n this.cancelledAt = options.cancelledAt;\n this.reason = options.reason;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorDriftErrorOptions = AIErrorOptions & {\n /** Signature recorded on the snapshot being resumed. */\n savedSignature: string;\n /** Signature computed from the current supervisor definition. */\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `supervisor.resume(runId)` loaded a snapshot whose structural\n * fingerprint does not match the current supervisor definition\n * (agent keys + descriptions + router identity + route presence).\n * The resume is refused — no iteration runs — and the user decides\n * how to recover: discard the snapshot, migrate manually, or call\n * `resume(runId, { force: true })` to bypass the check.\n *\n * Mirrors `WorkflowDriftError` for workflow resume — same rationale,\n * different primitive.\n */\nexport class SupervisorDriftError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: SupervisorDriftErrorOptions) {\n super(message, options, \"SUPERVISOR_DRIFT\");\n this.name = \"SupervisorDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorRoutingErrorOptions = AIErrorOptions & {\n /**\n * The raw value the `route` callback or router agent returned. Keyed\n * `unknown` because a misbehaving router can emit any JSON value —\n * consumers should format it for display, not trust its shape.\n */\n returned: unknown;\n /** Every legal intent key configured on the supervisor at run time. */\n availableKeys: string[];\n};\n\n/**\n * A `route` callback or router agent returned a value that doesn't\n * resolve to a configured agent key, a `string[]` of configured keys,\n * or the `END` sentinel. Routing is authoritative — there is no\n * recovery path, so the supervisor terminates the run immediately.\n *\n * Named `SupervisorRoutingError` (not `RoutingError`) to avoid\n * colliding with `@warlock.js/ai`'s existing workflow `RoutingError`\n * (`WORKFLOW_INVALID_GOTO`). Both carry the same semantic weight —\n * \"routing asked for something I can't dispatch\" — in their\n * respective primitives.\n *\n * @example\n * const { error } = await supervisor.execute(input);\n * if (error?.code === \"SUPERVISOR_INVALID_ROUTE\") {\n * logger.error(\"bad router decision\", {\n * returned: (error as SupervisorRoutingError).returned,\n * available: (error as SupervisorRoutingError).availableKeys,\n * });\n * }\n */\nexport class SupervisorRoutingError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"routing\";\n\n public readonly returned: unknown;\n public readonly availableKeys: string[];\n\n public constructor(message: string, options: SupervisorRoutingErrorOptions) {\n super(message, options, \"SUPERVISOR_INVALID_ROUTE\");\n this.name = \"SupervisorRoutingError\";\n this.returned = options.returned;\n this.availableKeys = options.availableKeys;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload passed to `ToolExecutionError` — identifies which tool\n * failed and, when applicable, which trip it was dispatched from.\n */\nexport type ToolExecutionErrorOptions = AIErrorOptions & {\n toolName: string;\n tripIndex?: number;\n};\n\n/**\n * A registered tool's `execute()` threw during dispatch — the tool\n * code itself failed (not its input schema). The model's request was\n * valid; the implementation crashed.\n *\n * Carries `toolName` so consumers can branch on which tool failed\n * without regex-parsing the message, and `tripIndex` to correlate\n * with the `LLMTrip` entry in `result.report.trips`.\n *\n * @example\n * if (result.error instanceof ToolExecutionError) {\n * metrics.increment(\"tool.failure\", { tool: result.error.toolName });\n * }\n */\nexport class ToolExecutionError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"tool\";\n\n public readonly toolName: string;\n public readonly tripIndex?: number;\n\n public constructor(message: string, options: ToolExecutionErrorOptions) {\n super(\"TOOL_EXEC_FAILED\", message, options);\n this.name = \"ToolExecutionError\";\n this.toolName = options.toolName;\n this.tripIndex = options.tripIndex;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type WorkflowCancelledErrorOptions = AIErrorOptions & {\n cancelledAt: string;\n reason?: string;\n};\n\n/**\n * Workflow was cancelled via `AbortSignal` before it could finish.\n * `cancelledAt` is ISO timestamp at abort; `reason` carries the\n * `controller.abort(reason)` payload when provided.\n */\nexport class WorkflowCancelledError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt: string;\n public readonly reason?: string;\n\n public constructor(message: string, options: WorkflowCancelledErrorOptions) {\n super(message, options, \"WORKFLOW_CANCELLED\");\n this.name = \"WorkflowCancelledError\";\n this.cancelledAt = options.cancelledAt;\n this.reason = options.reason;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type WorkflowDriftErrorOptions = AIErrorOptions & {\n savedSignature: string;\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `workflow.resume(runId)` found a snapshot whose structural signature\n * doesn't match the current workflow definition. Thrown without\n * executing anything. User must discard, force, or migrate manually.\n */\nexport class WorkflowDriftError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: WorkflowDriftErrorOptions) {\n super(message, options, \"WORKFLOW_DRIFT\");\n this.name = \"WorkflowDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n","import type { Message } from \"../../contracts/conversation-message.type\";\n\n/**\n * Pull the text a content-inspection middleware should care about\n * from the outbound message list.\n *\n * **Role.** Built-ins that inspect \"what the user just said\" — the\n * guardrail on `trip.before`, the semantic cache on `trip.before`,\n * future consumers like PII redactors — all need the same string:\n * the most recent `user`-role message's text content. This helper\n * is the single authority on how that string is resolved.\n *\n * **Behavior.**\n * - Walks `messages` from the end backwards so the LAST user turn\n * wins (correct when the agent has history + a fresh prompt).\n * - Returns a plain string directly when `content` is a string.\n * - Joins `text` parts with `\"\\n\"` when `content` is a multipart\n * `ContentPart[]`. Non-text parts (images, audio) are skipped —\n * callers concerned with multimodal content inspect `request`\n * / attachments separately.\n * - Returns `\"\"` when there is no user message at all (e.g. a trip\n * composed entirely of tool results).\n *\n * @example\n * const prompt = extractUserText(context.messages);\n * if (!prompt) return;\n * const verdict = await inputCheck(prompt);\n */\nexport function extractUserText(messages: ReadonlyArray<Message>): string {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n\n if (message.role !== \"user\") {\n continue;\n }\n\n if (typeof message.content === \"string\") {\n return message.content;\n }\n\n if (Array.isArray(message.content)) {\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"\\n\");\n }\n }\n\n return \"\";\n}\n","import type { MiddlewareState } from \"../../contracts/middleware\";\n\n/**\n * Typed accessor over `ctx.state` for a single namespace key. Wraps\n * the raw `Map<string, unknown>` so middleware authors stop typing\n * `as Counters | undefined` on every read.\n *\n * **Role.** Every built-in middleware reads and writes one or two\n * entries in `ctx.state` under its own name. Without a helper,\n * every call-site looks like:\n *\n * ```ts\n * const counters = context.state.get(\"budget.counters\") as Counters | undefined;\n * if (!counters) { ... }\n * counters.tokens += n;\n * ```\n *\n * — cast noise, no type narrowing on `set`, no protection against\n * key typos. `namespacedState<T>` eliminates all three.\n *\n * **Scope.** Deliberately narrow: one key, typed value, four methods\n * (`get` / `set` / `delete` / `has`). Does NOT try to model compound\n * or nested keys — if you need those, use the raw `ctx.state` Map\n * directly, or create a second namespaced accessor for the second key.\n *\n * **Namespace convention.** Use the middleware's `name` as the key\n * (or a `name.<field>` prefix when a middleware needs multiple\n * entries). The pipeline does not enforce this — it is a convention\n * the built-ins follow to avoid collisions between middlewares.\n *\n * @example\n * // Inside a budget middleware:\n * const counters = namespacedState<Counters>(ctx, \"budget\");\n *\n * if (!counters.has()) {\n * counters.set({ tokens: 0, costUSD: 0 });\n * }\n *\n * const current = counters.get()!;\n * current.tokens += response.usage.total;\n */\nexport function namespacedState<T>(\n ctx: { readonly state: MiddlewareState },\n namespace: string,\n): NamespacedStateAccessor<T> {\n return {\n get(): T | undefined {\n return ctx.state.get(namespace) as T | undefined;\n },\n set(value: T): void {\n ctx.state.set(namespace, value);\n },\n delete(): void {\n ctx.state.delete(namespace);\n },\n has(): boolean {\n return ctx.state.has(namespace);\n },\n };\n}\n\n/**\n * Four-method accessor returned by `namespacedState`. Callers hold\n * it for the lifetime of a hook body — it is a thin typed view over\n * `ctx.state`, not a detached snapshot. Reads are live; writes hit\n * the underlying Map immediately and are visible to every other\n * hook that uses the same namespace.\n */\nexport type NamespacedStateAccessor<T> = {\n get(): T | undefined;\n set(value: T): void;\n delete(): void;\n has(): boolean;\n};\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\nimport { BudgetExceededError, type BudgetUnit } from \"../../errors\";\nimport { namespacedState } from \"../utils\";\n\n/**\n * Per-model pricing used to compute USD cost from token counts.\n * Caller-supplied — no bundled table. Keys are model names (the\n * `ModelContract.name` value); values are input / output token\n * prices expressed as **USD per 1K tokens** to match every major\n * provider's published pricing sheet.\n */\nexport type BudgetPricing = Record<\n string,\n {\n /** USD per 1,000 input tokens. */\n inputPer1K: number;\n /** USD per 1,000 output tokens. */\n outputPer1K: number;\n }\n>;\n\n/**\n * Configuration for `budget()`. At least one of `maxTokens` or\n * `maxCostUSD` must be supplied — a budget with no cap is a no-op.\n */\nexport type BudgetOptions = {\n /**\n * Hard cap on cumulative total tokens (input + output, summed\n * across every trip of the run). Inclusive — exceeding triggers\n * the configured `onExceeded`.\n */\n maxTokens?: number;\n /**\n * Hard cap on cumulative USD cost. Requires `pricing` for the\n * agent's configured model — without a pricing entry the USD check\n * silently skips (tokens-only enforcement still applies).\n */\n maxCostUSD?: number;\n /**\n * Per-model pricing table used to compute USD cost. Only consulted\n * when `maxCostUSD` is set. Model names must match the running\n * agent's `ModelContract.name` exactly.\n */\n pricing?: BudgetPricing;\n /**\n * Behavior when a cap is breached. `\"abort\"` throws\n * `BudgetExceededError` — surfaces on `result.error`, stops the\n * run at the next trip boundary. `\"warn\"` logs a warning and\n * lets the run continue (useful for observability-first rollouts\n * before flipping the switch to abort). Default `\"abort\"`.\n */\n onExceeded?: \"abort\" | \"warn\";\n /**\n * Override the middleware name. Useful when two budgets coexist\n * (e.g. a per-request cap plus a session-wide cap via different\n * instances). Default `\"budget\"`.\n */\n name?: string;\n};\n\ntype BudgetCounters = {\n tokens: number;\n costUSD: number;\n warned: boolean;\n};\n\nfunction breach(\n limit: number,\n actual: number,\n unit: BudgetUnit,\n name: string,\n): never {\n throw new BudgetExceededError(\n `budget \"${name}\" exceeded — ${actual} ${unit} (cap: ${limit})`,\n { limit, actual, unit },\n );\n}\n\n/**\n * Enforced token and / or USD budget for an agent run.\n *\n * **Role.** Guards against runaway tool loops, misconfigured\n * prompts, and unexpected provider price swings by capping\n * cumulative usage across every LLM trip of a single execution.\n * Aborts the run with a typed `BudgetExceededError` the moment a cap\n * is breached, rather than letting the damage grow trip by trip.\n *\n * **Scope.** Per-execution. A fresh counter is created at\n * `execute.before` and lives in the middleware state bag until the\n * run ends. Two concurrent `agent.execute()` calls on the same\n * agent therefore enforce the cap independently.\n *\n * **Token accounting.** After each successful trip, the middleware\n * adds `response.usage.total` to its running total and checks\n * against `maxTokens`. Synthetic trips (cache hits) contribute\n * `usage.total` as returned by the cache — cache middleware is\n * expected to surface zero usage on a hit, which naturally excludes\n * those trips from the budget.\n *\n * **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are\n * both present, the middleware converts per-trip input / output\n * tokens to USD and accumulates. Missing pricing silently degrades\n * to tokens-only — explicit rather than guessing.\n *\n * **Warn mode.** `onExceeded: \"warn\"` logs a single warning the first\n * time a cap is breached and lets the run continue. Useful for\n * measuring real-world traffic against a proposed cap before flipping\n * to `\"abort\"` in production.\n *\n * @example\n * const budgetMiddleware = budget({ maxTokens: 50_000 });\n *\n * const myAgent = agent({\n * model,\n * middleware: [budgetMiddleware],\n * });\n *\n * @example\n * // With USD cap and custom pricing\n * const guard = budget({\n * maxCostUSD: 0.5,\n * pricing: {\n * \"gpt-4o\": { inputPer1K: 0.005, outputPer1K: 0.015 },\n * },\n * });\n */\nexport function budget(options: BudgetOptions): AgentMiddleware {\n const name = options.name ?? \"budget\";\n const onExceeded = options.onExceeded ?? \"abort\";\n const hasTokenCap = typeof options.maxTokens === \"number\";\n const hasCostCap = typeof options.maxCostUSD === \"number\";\n\n return {\n name,\n execute: {\n before(context) {\n const counters = namespacedState<BudgetCounters>(context, name);\n counters.set({ tokens: 0, costUSD: 0, warned: false });\n },\n },\n trip: {\n after(context, response) {\n const counters = namespacedState<BudgetCounters>(context, name).get();\n\n if (!counters) {\n return;\n }\n\n counters.tokens += response.usage.total;\n\n if (hasCostCap && options.pricing) {\n const pricing = options.pricing[context.model.name];\n\n if (pricing) {\n const tripCost =\n (response.usage.input / 1000) * pricing.inputPer1K +\n (response.usage.output / 1000) * pricing.outputPer1K;\n counters.costUSD += tripCost;\n }\n }\n\n if (hasTokenCap && counters.tokens > options.maxTokens!) {\n if (onExceeded === \"abort\") {\n breach(options.maxTokens!, counters.tokens, \"tokens\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n\n if (hasCostCap && counters.costUSD > options.maxCostUSD!) {\n if (onExceeded === \"abort\") {\n breach(options.maxCostUSD!, counters.costUSD, \"usd\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n },\n },\n };\n}\n","import type {\n AgentMiddleware,\n MiddlewareTripContext,\n} from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { GuardrailViolationError } from \"../../errors\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Decision returned by a guardrail check function. `ok: true`\n * permits the call; `ok: false` rejects with a human-readable\n * `reason` surfaced on `GuardrailViolationError`.\n */\nexport type GuardrailCheckResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Synchronous or asynchronous check invoked against the outbound\n * prompt (`inputCheck`) or the inbound response (`outputCheck`).\n * Receives the raw text and the surrounding trip context so\n * consumers can classify, route to an external moderation API, or\n * branch on tripIndex / messages history.\n */\nexport type GuardrailCheck = (\n text: string,\n context: MiddlewareTripContext,\n) => GuardrailCheckResult | Promise<GuardrailCheckResult>;\n\n/**\n * Configuration for `guardrail()`. At least one of `inputCheck` or\n * `outputCheck` must be supplied — a guardrail with no checks is a\n * no-op.\n */\nexport type GuardrailOptions = {\n /**\n * Run against the outbound prompt just before the model sees it.\n * Fires every trip with the concatenated last user-message text.\n * Rejection aborts the trip with a `GuardrailViolationError` whose\n * `phase === \"input\"`.\n */\n inputCheck?: GuardrailCheck;\n /**\n * Run against the model's response text after the trip completes.\n * Fires every trip with `response.content`. Rejection aborts with\n * a `GuardrailViolationError` whose `phase === \"output\"`.\n *\n * Output checks run BEFORE any tool dispatch — a rejected response\n * means the tool calls it requested are never invoked.\n */\n outputCheck?: GuardrailCheck;\n /**\n * Override the middleware name — surfaces on\n * `GuardrailViolationError.guardrail` so operators can tell two\n * guardrails apart in logs. Default `\"guardrail\"`.\n */\n name?: string;\n};\n\n/**\n * Pre/post content guardrail for an agent run.\n *\n * **Role.** Inspects outbound prompts and inbound responses against\n * caller-supplied policies, aborting the trip with a typed\n * `GuardrailViolationError` when either trips a check. Consumers\n * distinguish `\"input\"` vs `\"output\"` violations off `error.phase`\n * — the two failure modes have very different product responses\n * (block the user vs re-prompt the model).\n *\n * **Scope.** Per-trip. Fires on every round-trip the agent makes,\n * including repair attempts and tool-follow-up trips. Input checks\n * evaluate the last user-role message; output checks evaluate the\n * raw model response text before any tool call is dispatched.\n *\n * **Composition.** A single middleware instance can carry both\n * `inputCheck` and `outputCheck`, or two separate instances can be\n * registered (useful when input and output policies come from\n * different teams / services). Registration order determines which\n * guardrail's violation surfaces first — the short-circuit throws\n * from the innermost offending hook, and outer guardrails never run\n * after an abort.\n *\n * **Not a sanitizer.** The guardrail either passes a trip unchanged\n * or aborts it. Mutating the prompt / response in-place is out of\n * scope — use a bespoke middleware for content rewriting.\n *\n * @example\n * const policy = guardrail({\n * inputCheck: async (text) =>\n * text.includes(\"SSN\") ? { ok: false, reason: \"pii\" } : { ok: true },\n * outputCheck: async (text) =>\n * text.length > 10_000 ? { ok: false, reason: \"too-long\" } : { ok: true },\n * });\n *\n * const myAgent = agent({ model, middleware: [policy] });\n */\nexport function guardrail(options: GuardrailOptions): AgentMiddleware {\n const name = options.name ?? \"guardrail\";\n const { inputCheck, outputCheck } = options;\n\n return {\n name,\n trip: {\n async before(context) {\n if (!inputCheck) {\n return;\n }\n\n const prompt = extractUserText(context.messages);\n\n if (!prompt) {\n return;\n }\n\n const verdict = await inputCheck(prompt, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected input — ${verdict.reason}`,\n { phase: \"input\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n async after(context, response: ModelResponse) {\n if (!outputCheck) {\n return;\n }\n\n if (!response.content) {\n return;\n }\n\n const verdict = await outputCheck(response.content, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected output — ${verdict.reason}`,\n { phase: \"output\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n },\n };\n}\n","import type { CacheDriver } from \"@warlock.js/cache\";\n\n/**\n * Process-wide `@warlock.js/ai` configuration. **Intentionally tiny.**\n * Lives here only for genuinely cross-cutting defaults that would\n * otherwise force users to wire the same value into every consumer.\n *\n * **What lives here.** A field earns a slot only when it satisfies\n * all three:\n * 1. Multiple unrelated consumers need the same value.\n * 2. The value is infrastructure (drivers, clients, pools), not\n * behavior (kill-switches, mode flags).\n * 3. Per-call override doesn't make sense for the use case.\n *\n * **What does NOT live here.** Logger config (use\n * `@warlock.js/logger` directly). Per-primitive feature flags\n * (live on the relevant config type). Anything that's really one\n * consumer's concern (lives on that consumer).\n *\n * Phase 3.2 deliberately removed the previous `configureAI()` bag\n * because it was growing unbounded. Treat new fields here with the\n * same suspicion.\n */\nexport type AIConfig = {\n /**\n * Default store used by every consumer that supports persistence\n * but didn't supply its own `store` / `snapshotStore`. Most\n * realistic deployments back resume snapshots, semantic cache, and\n * future memory primitives with the same driver — declaring it\n * once here removes the repetition.\n *\n * Per-declaration overrides (`SupervisorConfig.snapshotStore`,\n * `semanticCache({ store })`) win when supplied. Set this once at\n * app boot, *after* you've constructed your driver.\n *\n * @example\n * import { cache } from \"@warlock.js/cache\";\n * import { ai } from \"@warlock.js/ai\";\n *\n * ai.config({\n * defaultStore: cache.driver(\"redis\", { client: redisClient }),\n * });\n */\n defaultStore?: CacheDriver<any, any>;\n};\n\nconst aiConfig: AIConfig = {};\n\n/**\n * Set or extend process-wide AI configuration. Merges over existing\n * values — fields not present in `partial` keep whatever was set\n * before (or stay unset). Call once at app boot, before constructing\n * any agent / supervisor / middleware that should pick up the\n * defaults.\n *\n * Returns the merged config so callers can verify what landed.\n *\n * @example\n * import { cache } from \"@warlock.js/cache\";\n * import { ai } from \"@warlock.js/ai\";\n *\n * ai.config({ defaultStore: cache.driver(\"redis\", { client }) });\n */\nexport function setAIConfig(partial: Partial<AIConfig>): AIConfig {\n Object.assign(aiConfig, partial);\n return { ...aiConfig };\n}\n\n/**\n * Read the current AI config snapshot. Returns a shallow copy so\n * callers can't accidentally mutate the source of truth. Used\n * internally by consumers to resolve their `defaultStore` fallback.\n */\nexport function getAIConfig(): AIConfig {\n return { ...aiConfig };\n}\n\n/**\n * Resolve the effective store for a consumer that didn't receive an\n * explicit one. Returns the global `defaultStore` if set, otherwise\n * `undefined`. Consumers decide whether `undefined` is fatal (semantic\n * cache: yes, throws) or a no-op (snapshot persistence: yes, just\n * skips).\n */\nexport function resolveDefaultStore(): CacheDriver<any, any> | undefined {\n return aiConfig.defaultStore;\n}\n","import type { CacheDriver } from \"@warlock.js/cache\";\nimport { resolveDefaultStore } from \"../../config\";\nimport type { Message } from \"../../contracts/conversation-message.type\";\nimport type { EmbedderContract } from \"../../contracts/embedder.contract\";\nimport type { AgentMiddleware } from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Configuration for `semanticCache()`.\n */\nexport type SemanticCacheOptions = {\n /** Embedder used to produce the query vector from the prompt text. */\n embedder: EmbedderContract;\n /**\n * Vector-capable cache driver from `@warlock.js/cache`. Production\n * deployments pick a driver with a real ANN index (`pg` with\n * pgvector, `redis` with RediSearch). Dev / test environments use\n * `new MemoryCacheDriver()` — zero config, correct, but O(N) per\n * query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * Falls back to `ai.config({ defaultStore })` when omitted. When\n * neither is set, the factory throws at construction time —\n * semantic cache cannot operate without a store.\n */\n store?: CacheDriver<any, any>;\n /**\n * Minimum cosine similarity for a vector hit. Between 0 and 1 —\n * 0.95 is a solid default for question-answering caches.\n */\n threshold: number;\n /**\n * Optional TTL in milliseconds. Entries whose `storedAt` is older\n * than this are treated as misses on read and overwritten on the\n * next write. Default: no expiry — entries live until the store\n * evicts them (per its own TTL/eviction policy).\n */\n ttlMs?: number;\n /**\n * Namespace prefix applied to every key the cache writes. Lets\n * multiple agents share one driver without collision. Default\n * `\"ai.cache\"`.\n */\n namespace?: string;\n /**\n * Middleware name — also the state-bag key prefix inside a single\n * execution. Default `\"semantic-cache\"`.\n */\n name?: string;\n};\n\ntype CachedEntry = {\n response: ModelResponse;\n storedAt: number;\n};\n\ntype PendingWrite = {\n promptKey: string;\n vector: number[];\n};\n\nconst DEFAULT_NAMESPACE = \"ai.cache\";\n\n/**\n * Build a stable fingerprint for a prompt covering the full message\n * list (system + history + user turn). Ensures two prompts sharing\n * the user text but differing in prior context do not collide on\n * the exact-match fast path.\n *\n * FNV-1a variant — cheap, collision-resistant enough for a cache,\n * dependency-free. NOT a cryptographic hash: collisions would\n * surface as wrong cache hits, not a security issue in the current\n * trust model.\n */\nfunction hashPrompt(messages: ReadonlyArray<Message>): string {\n const serialized = messages\n .map((message) => {\n const role = message.role;\n const content = Array.isArray(message.content)\n ? message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"|\")\n : message.content;\n\n return `${role}:${content}`;\n })\n .join(\"||\");\n\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < serialized.length; index++) {\n hash ^= serialized.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return (hash >>> 0).toString(16);\n}\n\nfunction isFresh(entry: CachedEntry, ttlMs: number | undefined): boolean {\n if (ttlMs === undefined) {\n return true;\n }\n\n return Date.now() - entry.storedAt <= ttlMs;\n}\n\n/**\n * Semantic-similarity response cache for an agent run.\n *\n * **Role.** Skips LLM round-trips when the current prompt is\n * semantically close to one the agent has already answered. For\n * FAQ / support-style traffic this often eliminates 60–80% of\n * model calls — the production win is massive for cost and\n * latency.\n *\n * **Delegation to `@warlock.js/cache`.** This middleware does NOT\n * implement similarity search itself. It delegates to the supplied\n * `CacheDriver`. Production deployments pick a driver with an ANN\n * index (`pg` + pgvector, `redis` + RediSearch). Dev / test\n * environments pass `new MemoryCacheDriver()` — zero config, correct,\n * but O(N) per query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * **Two-tier lookup.**\n * 1. *Exact-match key* — a cheap FNV hash over the entire message\n * list. `store.get(hash)` returns the entry without an embedding\n * round trip when the prompt hasn't changed at all.\n * 2. *Vector-match* — on exact-match miss, embed the prompt and\n * call `store.similar(vector, { topK: 1, threshold })`. The\n * driver uses its native similarity index; anything clearing\n * `threshold` is returned as a hit.\n *\n * **Write-on-miss.** When both tiers miss, `trip.before` stashes\n * the prompt hash + vector in `ctx.state`; `trip.after` reads back\n * the pending entry and calls\n * `store.set(hash, entry, { vector })`. If an outer middleware\n * (guardrail) throws in `trip.after` before the cache's `trip.after`\n * runs, the pending entry is never written — bad responses stay out\n * of the cache **as long as the canonical install order is followed**\n * (cache outermost).\n *\n * **Synthetic-response on hit.** Returns a `ModelResponse` with\n * `usage: { input: 0, output: 0, total: 0 }` so budget /\n * observability correctly exclude the saved trip.\n *\n * @example\n * import { semanticCache } from \"@warlock.js/ai\";\n * import { MemoryCacheDriver } from \"@warlock.js/cache\";\n *\n * const store = new MemoryCacheDriver();\n * store.setOptions({});\n *\n * const cache = semanticCache({\n * embedder: openai.embedder({ name: \"text-embedding-3-small\" }),\n * store,\n * threshold: 0.95,\n * ttlMs: 60 * 60 * 1000,\n * });\n *\n * const myAgent = agent({ model, middleware: [cache] });\n */\nexport function semanticCache(options: SemanticCacheOptions): AgentMiddleware {\n const name = options.name ?? \"semantic-cache\";\n const namespace = options.namespace ?? DEFAULT_NAMESPACE;\n const pendingKey = `${name}.pending`;\n\n // Resolve the effective store at factory time, not per-call. Every\n // subsequent hook closes over `store` so the resolution happens once.\n // Throws now (loud, at construction) instead of later during the\n // first trip (silent until the agent actually runs).\n const store = options.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `semanticCache: no store supplied — pass \\`store\\` in options or call \\`ai.config({ defaultStore })\\` at app boot before constructing the middleware`,\n );\n }\n\n // Cache's parseKey replaces \":\" with \".\" so the namespace boundary\n // matches what `similar()` actually returns in `hit.key`. Using a\n // dot here keeps prefix checks aligned with stored keys.\n const keyFor = (hash: string): string => `${namespace}.${hash}`;\n\n return {\n name,\n log: true,\n trip: {\n async before(context) {\n // Only cache the first trip's response. Subsequent trips\n // happen because the previous trip requested tool calls — the\n // message list now carries tool results the original prompt\n // never saw, so a semantic match on the unchanged user text\n // would serve back the prior `tool_calls` response and loop\n // the agent forever. The first turn is also the only one\n // where a \"same question → same final answer\" caching story\n // is sound.\n if (context.tripIndex !== 0) {\n return;\n }\n\n const promptText = extractUserText(context.messages);\n\n if (!promptText) {\n return;\n }\n\n const promptKey = hashPrompt(context.messages);\n const scopedKey = keyFor(promptKey);\n\n const exact = await store.get<CachedEntry>(scopedKey);\n\n if (exact && isFresh(exact, options.ttlMs)) {\n return toSyntheticResponse(exact.response);\n }\n\n const query = await options.embedder.embed(promptText);\n\n const [hit] = await store.similar<CachedEntry>(query.vector, {\n topK: 1,\n threshold: options.threshold,\n });\n\n if (hit && isFresh(hit.value, options.ttlMs)) {\n // Only return hits whose stored key is within this cache's\n // namespace. Drivers shared across namespaces would otherwise\n // leak foreign entries into queries.\n if (hit.key.startsWith(`${namespace}.`)) {\n return toSyntheticResponse(hit.value.response);\n }\n }\n\n const pending: PendingWrite = { promptKey, vector: query.vector };\n context.state.set(pendingKey, pending);\n\n return;\n },\n async after(context, response) {\n const pending = context.state.get(pendingKey) as PendingWrite | undefined;\n\n if (!pending) {\n return;\n }\n\n // Mid-stream tool-call responses must not be cached — the\n // useful answer comes from the trip *after* the tool returns.\n // Crucially, leave the pending entry in place so a later trip\n // (the one that actually finishes with `stop`) can read it\n // and write the final response under the *original* trip-0\n // prompt key. Deleting here would orphan the pending and the\n // post-tool answer would never make it into the store.\n if (response.finishReason === \"tool_calls\") {\n return;\n }\n\n context.state.delete(pendingKey);\n\n const entry: CachedEntry = { response, storedAt: Date.now() };\n\n await store.set(keyFor(pending.promptKey), entry, {\n vector: pending.vector,\n });\n\n return;\n },\n },\n };\n}\n\nfunction toSyntheticResponse(response: ModelResponse): ModelResponse {\n return {\n content: response.content,\n finishReason: response.finishReason,\n usage: { input: 0, output: 0, total: 0 },\n toolCalls: response.toolCalls,\n };\n}\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\n\n/**\n * Flatten one or more middleware sources into a single ordered\n * array suitable for `agent({ middleware: [...] })`.\n *\n * **Role.** As middleware catalogs grow, agent configs accumulate\n * long arrays that mix \"always-on\" stacks (cache + budget + guardrail)\n * with per-concern extras (per-tool rate-limits, audit hooks). A\n * single `compose` call lets callers keep those sources as named\n * variables and flatten at the registration site.\n *\n * **Semantics.** Registration order is preserved across sources —\n * `compose(a, b, c)` produces `[...a, ...b, ...c]`. Because the\n * pipeline's onion is strictly registration-ordered, the flattened\n * order is the execution order. No de-duplication, no sorting, no\n * priority logic — that would hide bugs, not fix them.\n *\n * **Accepts arrays OR individual middlewares.** Both forms are\n * common in callsite code; the helper flattens either.\n *\n * @example\n * const standardStack = [\n * ai.middleware.semanticCache({ ... }),\n * ai.middleware.budget({ maxTokens: 20_000 }),\n * ai.middleware.guardrail({ ... }),\n * ];\n *\n * const toolRateLimits = [\n * toolRateLimit({ tool: \"search_web\", maxCalls: 3 }),\n * toolRateLimit({ tool: \"expensive_api\", maxCalls: 1 }),\n * ];\n *\n * const myAgent = ai.agent({\n * model,\n * middleware: ai.middleware.compose(standardStack, toolRateLimits, auditMiddleware),\n * });\n */\nexport function composeMiddleware(\n ...sources: ReadonlyArray<AgentMiddleware | ReadonlyArray<AgentMiddleware>>\n): AgentMiddleware[] {\n const out: AgentMiddleware[] = [];\n\n for (const source of sources) {\n if (Array.isArray(source)) {\n out.push(...source);\n continue;\n }\n\n out.push(source as AgentMiddleware);\n }\n\n return out;\n}\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\n\n/**\n * Scope a middleware's `tool`-level hooks to only fire for a\n * specific tool name (or a set of names). `execute` and `trip`\n * hooks pass through unchanged.\n *\n * **Role.** Tool-specific concerns — \"rate-limit `search_web`\",\n * \"cache results for `fetch_faq`\" — are common. Rather than adding\n * a `middleware` field to `ai.tool()` (see decisions §27), the\n * framework keeps one contract (`AgentMiddleware`) and offers this\n * helper for the locality problem. The middleware body stays agnostic\n * of the tool name; `forTool` handles the filtering.\n *\n * **What gets filtered.** Only `tool.before` / `tool.after` /\n * `tool.onError`. Each hook is wrapped so that `ctx.tool.name`\n * must be in the allowed set or the wrapped hook is a no-op.\n * `execute` and `trip` hooks are NOT touched — they run normally.\n *\n * **Why not filter execute/trip too?** Because a middleware that\n * reaches across levels (a tool-specific budget that initializes a\n * counter in `execute.before` and checks it in `tool.before`) still\n * needs `execute.before` to fire unconditionally. Scoping all hooks\n * would break cross-level middleware; scoping only `tool` hooks\n * matches the mental model of \"this middleware cares about these\n * tools.\"\n *\n * **Single-name vs multi-name.** A string matches one tool; a string\n * array matches any of the listed tools. No wildcards, no regex —\n * keep it boring.\n *\n * @example\n * // Single tool\n * const scoped = ai.middleware.forTool(\n * \"search_web\",\n * toolRateLimit({ maxCalls: 3 }),\n * );\n *\n * @example\n * // Multiple tools sharing a rule\n * const scoped = ai.middleware.forTool(\n * [\"paid_api\", \"expensive_db\"],\n * toolRateLimit({ maxCalls: 5 }),\n * );\n *\n * ai.agent({\n * model,\n * tools: [webTool, paidApiTool, expensiveDbTool],\n * middleware: [scoped],\n * });\n */\nexport function forTool(\n toolNames: string | ReadonlyArray<string>,\n middleware: AgentMiddleware,\n): AgentMiddleware {\n const allowed = new Set(\n typeof toolNames === \"string\" ? [toolNames] : toolNames,\n );\n const scope =\n allowed.size === 1 ? Array.from(allowed)[0] : Array.from(allowed).join(\"+\");\n\n if (!middleware.tool) {\n return middleware;\n }\n\n const innerBefore = middleware.tool.before;\n const innerAfter = middleware.tool.after;\n const innerOnError = middleware.tool.onError;\n\n return {\n ...middleware,\n name: `${middleware.name}[for:${scope}]`,\n tool: {\n before: innerBefore\n ? async ctx => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerBefore(ctx);\n }\n : undefined,\n after: innerAfter\n ? async (ctx, result) => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerAfter(ctx, result);\n }\n : undefined,\n onError: innerOnError\n ? async (ctx, error) => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerOnError(ctx, error);\n }\n : undefined,\n },\n };\n}\n","import type { Logger } from \"@warlock.js/logger\";\nimport type {\n AgentMiddleware,\n MiddlewareExecuteContext,\n MiddlewareToolContext,\n MiddlewareTripContext,\n} from \"../contracts/middleware\";\n\nconst LOG_MODULE = \"ai.middleware\";\n\n/**\n * The three levels at which agent middleware can hook — mirrors\n * `AgentMiddleware`'s optional `execute` / `trip` / `tool` keys.\n * Kept as a single named union so callers can pass it around without\n * inline-duplicating the literals.\n */\nexport type MiddlewareLevel = \"execute\" | \"trip\" | \"tool\";\n\n/**\n * Shape of the context object for each level. The pipeline is\n * level-parameterized on the ctx type via this mapping so callers\n * get compile-time narrowing when they instantiate `runPipeline`.\n */\nexport type MiddlewareContextByLevel = {\n execute: MiddlewareExecuteContext;\n trip: MiddlewareTripContext;\n tool: MiddlewareToolContext;\n};\n\n/**\n * Run an inner async operation through a stack of agent middlewares\n * at a single level, applying the onion-model before/after/onError\n * semantics documented on `AgentMiddleware`.\n *\n * **Semantics.**\n * - `before` hooks run in registration order (top-down).\n * Returning a defined value from a `before` hook short-circuits the\n * pipeline with that value as the result, skipping `inner()` and\n * all deeper `before` / `after` hooks — but outer middleware\n * `after` hooks (registered earlier) still run on the synthetic\n * value.\n * - `after` hooks run in reverse registration order (bottom-up).\n * Returning a defined value replaces the result before it\n * propagates further out. Returning `void` / `undefined` keeps the\n * existing result.\n * - `onError` hooks also run in reverse (bottom-up) — any error\n * thrown by `inner()`, by a `before` hook, or by an `after` hook\n * unwinds through each frame's `onError` in turn. Returning a\n * defined value from `onError` recovers: the error is cleared and\n * the returned value becomes the new result (which then flows\n * through outer `after` hooks). Returning `void` propagates the\n * error to the next outer frame.\n *\n * **Implementation.** Built by folding the middleware array from the\n * end inward: each middleware produces a closure that wraps the\n * previous closure (the deeper pipeline). The outermost wrap is\n * middleware index 0 — so registration order matches onion order\n * without any reverse iteration at call time.\n *\n * **No magic.** The pipeline does not swallow, retry, or translate\n * errors. Hooks that throw propagate unchanged (subject to `onError`\n * recovery). Pipeline-level logging is debug-only and respects each\n * middleware's `log: false` kill-switch.\n *\n * @example\n * const response = await runPipeline(\n * middlewares,\n * \"trip\",\n * tripContext,\n * () => model.complete(messages, callOptions),\n * logger,\n * );\n */\nexport async function runPipeline<Level extends MiddlewareLevel, TResult>(\n middlewares: ReadonlyArray<AgentMiddleware>,\n level: Level,\n context: MiddlewareContextByLevel[Level],\n inner: () => Promise<TResult>,\n logger?: Logger,\n): Promise<TResult> {\n if (middlewares.length === 0) {\n return inner();\n }\n\n let next: () => Promise<TResult> = inner;\n\n for (let index = middlewares.length - 1; index >= 0; index--) {\n const middleware = middlewares[index];\n const hooks = middleware[level];\n\n if (!hooks) {\n continue;\n }\n\n const previous = next;\n\n next = async () => {\n const logEnabled = middleware.log !== false && logger !== undefined;\n\n if (hooks.before) {\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.before`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n\n const shortCircuit = await (\n hooks.before as (ctx: unknown) => Promise<unknown> | unknown\n )(context);\n\n if (shortCircuit !== undefined) {\n if (logEnabled) {\n logger!.debug(\n LOG_MODULE,\n `${level}.short-circuit`,\n middleware.name,\n {\n middleware: middleware.name,\n level,\n },\n );\n }\n\n return shortCircuit as TResult;\n }\n }\n\n let result: TResult;\n\n try {\n result = await previous();\n } catch (thrown) {\n if (!hooks.onError) {\n throw thrown;\n }\n\n const recovered = await (\n hooks.onError as (\n ctx: unknown,\n error: unknown,\n ) => Promise<unknown> | unknown\n )(context, thrown);\n\n if (recovered === undefined) {\n throw thrown;\n }\n\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.recovered`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n\n result = recovered as TResult;\n }\n\n if (hooks.after) {\n const replacement = await (\n hooks.after as (\n ctx: unknown,\n value: unknown,\n ) => Promise<unknown> | unknown\n )(context, result);\n\n if (replacement !== undefined) {\n result = replacement as TResult;\n }\n\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.after`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n }\n\n return result;\n };\n }\n\n return next();\n}\n","import type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Compute a per-channel USD cost breakdown for a single `Usage` against\n * a model's pricing table. Returns `undefined` when no pricing is\n * configured — the framework treats unpriced runs as \"cost unknown,\"\n * not \"cost zero,\" so dashboards can distinguish free-tier from\n * un-instrumented.\n *\n * **Shape mirrors `ModelPricing`** — `input`, `output`, optional\n * `cachedInput` / `cachedOutput`. Consumers needing a scalar total\n * sum the populated fields. The breakdown is the value-add: it tells\n * downstream tooling HOW the total was reached (input-vs-output\n * share, cache savings) without re-deriving against pricing tables\n * that may have shifted since the report was written.\n *\n * **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`\n * served from the provider's prompt cache and bills at\n * `pricing.cachedInput` (falls back to full `pricing.input` when the\n * provider doesn't publish a cache rate). The remaining `input -\n * cachedTokens` bills at full rate and shows up in `cost.input`. The\n * `cachedOutput` channel is reserved for Anthropic-style cache writes;\n * until an adapter populates `usage.cacheWriteTokens`, the framework\n * leaves it undefined.\n *\n * Pricing values are USD-per-million-tokens. The function divides\n * once at the end to avoid floating-point accumulation error on\n * per-token math.\n *\n * @example\n * const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };\n * const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });\n * // cost = {\n * // input: (60_000 * 0.15) / 1e6 = 0.009,\n * // output: (30_000 * 0.6) / 1e6 = 0.018,\n * // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,\n * // }\n */\nexport function computeCost(usage: Usage, pricing: ModelPricing | undefined): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cachedInput = usage.cachedTokens ?? 0;\n const uncachedInput = Math.max(0, usage.input - cachedInput);\n\n const cost: ModelPricing = {\n input: (uncachedInput * pricing.input) / 1_000_000,\n output: (usage.output * pricing.output) / 1_000_000,\n };\n\n if (cachedInput > 0) {\n const cachedInputRate = pricing.cachedInput ?? pricing.input;\n cost.cachedInput = (cachedInput * cachedInputRate) / 1_000_000;\n }\n\n return cost;\n}\n\n/**\n * Merge a child's cost breakdown into a running parent total. Each\n * channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums\n * independently — an undefined channel on either side is treated as\n * zero contribution rather than dropping the other side's value. A\n * single unpriced child should never erase the cost of its priced\n * siblings.\n *\n * Returns the new parent breakdown, or `undefined` when neither parent\n * nor child carried any cost data (preserves the \"no priced\n * contributor has appeared yet\" signal that distinguishes \"missing\n * pricing\" from \"genuinely zero\").\n */\nexport function accumulateCost(\n parent: ModelPricing | undefined,\n child: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!child) {\n return parent;\n }\n\n if (!parent) {\n return { ...child };\n }\n\n const merged: ModelPricing = {\n input: parent.input + child.input,\n output: parent.output + child.output,\n };\n\n const cachedInput = sumOptional(parent.cachedInput, child.cachedInput);\n if (cachedInput !== undefined) {\n merged.cachedInput = cachedInput;\n }\n\n const cachedOutput = sumOptional(parent.cachedOutput, child.cachedOutput);\n if (cachedOutput !== undefined) {\n merged.cachedOutput = cachedOutput;\n }\n\n return merged;\n}\n\n/**\n * Add two optional numbers, treating either side's `undefined` as\n * zero — but return `undefined` when both are absent. Keeps \"this\n * channel was never reported anywhere\" distinguishable from \"this\n * channel was reported as 0.\"\n */\nfunction sumOptional(parent: number | undefined, child: number | undefined): number | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n return (parent ?? 0) + (child ?? 0);\n}\n","/**\n * Strip markdown code fences from an LLM response before JSON parsing.\n *\n * Models — especially Claude, smaller models, and local models — routinely\n * wrap JSON output in fenced code blocks (` ```json\\n{...}\\n``` `) even when\n * instructed otherwise. Sometimes they also precede the fence with prose\n * (\"Here you go:\\n```json\\n...\\n```\"). This helper finds the first fenced\n * block regardless of language tag and returns its trimmed contents.\n *\n * Returns the trimmed original text unchanged when no fence is present, so\n * clean JSON passes through as a no-op.\n *\n * Deliberately does NOT fall back to \"find first `{` and last `}` and slice\n * between them\" — that heuristic silently corrupts data when prose contains\n * stray braces. Failing loudly at `JSON.parse` is safer.\n *\n * @example\n * extractJsonPayload('```json\\n{\"a\":1}\\n```');\n * // => '{\"a\":1}'\n *\n * @example\n * extractJsonPayload('Here you go:\\n```\\n{\"a\":1}\\n```\\nHope this helps.');\n * // => '{\"a\":1}'\n *\n * @example\n * extractJsonPayload('{\"a\":1}');\n * // => '{\"a\":1}' (no fence → unchanged)\n */\nexport function extractJsonPayload(text: string): string {\n const trimmed = text.trim();\n\n const fenceMatch = trimmed.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n\n if (fenceMatch) {\n return fenceMatch[1].trim();\n }\n\n return trimmed;\n}\n","/**\n * Generates a stable, human-readable run id for any execution node\n * (tool invocation, agent run, workflow run, supervisor run). Format:\n * `${prefix}_${timestamp36}_${random36}` — compact, sortable by\n * prefix, collision-resistant within a run.\n *\n * Shared helper so every primitive emits the same id shape. The\n * prefix is conventionally the primitive kind (`\"tool\"`, `\"agent\"`,\n * `\"workflow\"`, `\"sup\"`) but callers can pass anything; the id is\n * purely for correlation, never parsed.\n *\n * @example\n * const runId = generateRunId(\"tool\");\n * // → \"tool_ld8x3m_7fq2j1kp\"\n */\nexport function generateRunId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${Math.random()\n .toString(36)\n .slice(2, 10)}`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Supported JSON Schema output targets per the Standard JSON Schema V1\n * spec. `openai-strict` is the richest for OpenAI structured outputs —\n * every property listed in `required`, optionals expressed as\n * `[\"T\", \"null\"]`, `additionalProperties: false` everywhere. Other\n * targets produce standards-compliant but looser output.\n */\nexport type JsonSchemaTarget = \"draft-2020-12\" | \"draft-07\" | \"openapi-3.0\" | \"openai-strict\";\n\n/**\n * Options for `extractJsonSchema`. `target` is forwarded to libraries that\n * implement the Standard JSON Schema V1 spec (Seal, and any future lib\n * that follows the spec). Libraries using their own top-level `.jsonSchema`\n * / `._jsonSchema` property ignore the target.\n */\nexport type ExtractJsonSchemaOptions = {\n target?: JsonSchemaTarget | (string & {});\n};\n\n/**\n * Best-effort JSON Schema extraction from a Standard Schema instance.\n *\n * Different libraries expose their JSON representation through different\n * paths:\n * - **Seal / Standard JSON Schema V1**: `[\"~standard\"].jsonSchema.input({ target })`\n * — nested under the spec object, takes a target switch. Default target\n * is `\"openai-strict\"` since the primary consumer is OpenAI's native\n * structured-output mechanism; pass `options.target` to override.\n * - **Zod / similar**: top-level `.jsonSchema` property. Zod v4 actually\n * ships `toJSONSchema` as a module function, not a method, so it does\n * NOT hit this probe — Zod users pass their converted schema via the\n * `AgentExecuteOptions.responseSchema` escape hatch.\n *\n * Deliberately does NOT probe `toJSON` — that's a generic JavaScript\n * serialization hook (Seal's schemas have one that dumps internal rule\n * state) and matching it would return garbage disguised as a JSON Schema.\n *\n * Returns `undefined` when no path matches. The caller then either skips\n * native structured-output wiring or falls back to a schema-less\n * instruction.\n *\n * Shared across every SDK adapter package (OpenAI, Anthropic, Bedrock…)\n * so each provider converts schemas identically.\n *\n * @example\n * const schema = extractJsonSchema(mySealSchema);\n * // { type: \"object\", properties: { ... }, required: [ ... ], additionalProperties: false }\n *\n * @example\n * // Ask for a different target explicitly\n * const draft = extractJsonSchema(mySealSchema, { target: \"draft-2020-12\" });\n */\nexport function extractJsonSchema(\n schema: StandardSchemaV1<unknown> | undefined,\n options: ExtractJsonSchemaOptions = {},\n): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n\n const target = options.target ?? \"openai-strict\";\n\n // 1. Seal / Standard JSON Schema V1 pattern: [\"~standard\"].jsonSchema.input({ target })\n const sealJsonSchema = extractFromSealPath(schema, target);\n\n if (sealJsonSchema) {\n return sealJsonSchema;\n }\n\n // 2. Top-level jsonSchema / _jsonSchema (Zod-like, property or method form)\n const topLevel = extractFromCandidateKeys(schema as unknown as Record<string, unknown>);\n\n if (topLevel) {\n return topLevel;\n }\n\n return undefined;\n}\n\n/**\n * Probe the Standard JSON Schema V1 extension path on `schema[\"~standard\"]`.\n * The spec defines `jsonSchema.input({ target, libraryOptions? })` as a\n * function returning a JSON Schema tailored to the requested target. We\n * pass the caller's target (default `\"openai-strict\"`) so the library\n * produces output ready for OpenAI's native structured-output mode\n * without additional post-processing.\n *\n * Calling `.input()` without a target would throw (or return garbage) per\n * the spec — a failure here returns `undefined` so the fallback probe\n * runs.\n */\nfunction extractFromSealPath(\n schema: StandardSchemaV1<unknown>,\n target: string,\n): Record<string, unknown> | undefined {\n const standardSlot = (schema as unknown as Record<string, unknown>)[\"~standard\"];\n\n if (!standardSlot || typeof standardSlot !== \"object\") {\n return undefined;\n }\n\n const jsonSchemaSlot = (standardSlot as Record<string, unknown>)[\"jsonSchema\"];\n\n if (!jsonSchemaSlot || typeof jsonSchemaSlot !== \"object\") {\n return undefined;\n }\n\n const inputFn = (jsonSchemaSlot as Record<string, unknown>)[\"input\"];\n\n if (typeof inputFn !== \"function\") {\n return undefined;\n }\n\n try {\n const result = (inputFn as (options: { target: string }) => unknown).call(jsonSchemaSlot, {\n target,\n });\n\n if (result && typeof result === \"object\") {\n return result as Record<string, unknown>;\n }\n } catch {\n // fall through — library didn't support the target or threw otherwise\n }\n\n return undefined;\n}\n\n/**\n * Probe well-known top-level keys libraries use to expose their JSON\n * Schema. Supports both method form (rare) and property form (common).\n * Deliberately narrow — `toJSON` is NOT probed here because it's a\n * generic serialization hook that returns library-internal state for\n * many validators (Seal included), not a JSON Schema.\n */\nfunction extractFromCandidateKeys(\n schemaRecord: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const candidateKeys = [\"jsonSchema\", \"_jsonSchema\"] as const;\n\n for (const key of candidateKeys) {\n const value = schemaRecord[key];\n\n if (typeof value === \"function\") {\n try {\n const result = (value as () => unknown).call(schemaRecord);\n\n if (result && typeof result === \"object\") {\n return result as Record<string, unknown>;\n }\n } catch {\n // try next candidate\n }\n\n continue;\n }\n\n if (value && typeof value === \"object\") {\n return value as Record<string, unknown>;\n }\n }\n\n return undefined;\n}\n","import type {\n Attachment,\n AttachmentSource,\n ResolvedAttachment,\n} from \"../contracts/attachment.type\";\nimport { InvalidRequestError } from \"../errors\";\n\nconst REMOTE_URL_PATTERN = /^https?:\\/\\//i;\n\n/**\n * Normalize a user-supplied `Attachment` (or bare `AttachmentSource`)\n * into a `ResolvedAttachment` the agent can hand to file-reading code\n * without re-discriminating the input variant.\n *\n * Resolution rules:\n * - `{ base64, mediaType }` → `{ type: \"base64\", value, mediaType }`.\n * - `StorageFileShape` (`{ url?, absolutePath? }`) → URL wins over\n * absolute path. URL becomes `{ type: \"url\" }`; absolute path\n * becomes `{ type: \"path\" }`.\n * - String starting with `http://` / `https://` → `{ type: \"url\" }`.\n * - Any other string → `{ type: \"path\" }`.\n * - Tagged `{ type: \"image\" | \"text\", source }` → recurses into `source`.\n *\n * Throws `InvalidRequestError` on obviously invalid input (empty\n * string, storage object with neither url nor absolutePath, missing\n * source field).\n *\n * @example\n * resolveAttachment(\"https://cdn.example.com/doc.pdf\");\n * // → { type: \"url\", value: \"https://cdn.example.com/doc.pdf\" }\n *\n * @example\n * resolveAttachment({ type: \"image\", source: \"/tmp/x.png\" });\n * // → { type: \"path\", value: \"/tmp/x.png\" }\n */\nexport function resolveAttachment(attachment: Attachment): ResolvedAttachment {\n if (\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"type\" in attachment\n ) {\n return resolveSource(attachment.source);\n }\n\n return resolveSource(attachment);\n}\n\nfunction resolveSource(source: AttachmentSource): ResolvedAttachment {\n if (typeof source === \"string\") {\n if (!source) {\n throw new InvalidRequestError(\"Cannot resolve empty attachment string\");\n }\n\n if (REMOTE_URL_PATTERN.test(source)) {\n return { type: \"url\", value: source };\n }\n\n return { type: \"path\", value: source };\n }\n\n // StorageFile objects (from @warlock.js/core) can expose a `base64`\n // property alongside `url` / `absolutePath`. Check storage shape\n // first so we don't treat a StorageFile as an inline-bytes payload.\n if (\"url\" in source || \"absolutePath\" in source) {\n const storage = source as { url?: string; absolutePath?: string };\n\n if (storage.absolutePath) {\n return { type: \"path\", value: storage.absolutePath };\n }\n\n if (storage.url) {\n return { type: \"url\", value: storage.url };\n }\n\n throw new InvalidRequestError(\n \"Storage attachment has neither url nor absolutePath\",\n );\n }\n\n if (\"base64\" in source) {\n if (!source.base64 || !source.mediaType) {\n throw new InvalidRequestError(\n \"Inline attachment requires both `base64` and `mediaType`\",\n );\n }\n\n return {\n type: \"base64\",\n value: source.base64,\n mediaType: source.mediaType,\n };\n }\n\n throw new InvalidRequestError(\n \"Unrecognized attachment source — expected a string path/URL, a StorageFile, or `{ base64, mediaType }`\",\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { resolveAttachment } from \"./resolve-attachment\";\n\nconst IMAGE_EXTENSIONS_TO_MEDIA_TYPE: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n};\n\nconst TEXT_EXTENSIONS = new Set([\".txt\"]);\n\ntype AttachmentKind = \"image\" | \"text\";\n\n/**\n * Convert a user-supplied `Attachment` into a provider-ready\n * `ContentPart` the model adapter can consume without doing any I/O of\n * its own.\n *\n * Kind resolution:\n * - Tagged `{ type: \"image\", source }` / `{ type: \"text\", source }`\n * trusts the caller's intent.\n * - Shorthand (raw string / `StorageFileShape`) infers from the file\n * extension. Image extensions (`.png`/`.jpg`/`.jpeg`/`.webp`/`.gif`)\n * map to `\"image\"`. `.txt` maps to `\"text\"`. Anything else throws\n * `InvalidRequestError` — silent inference on ambiguous inputs\n * causes silent bugs.\n *\n * Local paths are read from disk; images are base64-encoded inline,\n * text files are read as UTF-8 strings and returned as a `text`\n * `ContentPart`. Remote URLs for image attachments are passed through\n * unchanged; remote URLs for text attachments are fetched so the\n * adapter never needs network access.\n *\n * @example\n * await prepareAttachmentPart(\"./photo.png\");\n * // → { type: \"image\", source: { base64: \"...\", mediaType: \"image/png\" } }\n *\n * @example\n * await prepareAttachmentPart({ type: \"text\", source: \"./notes.txt\" });\n * // → { type: \"text\", text: \"<file contents>\" }\n */\nexport async function prepareAttachmentPart(\n attachment: Attachment,\n): Promise<ContentPart> {\n const kind = resolveKind(attachment);\n\n if (kind === \"text\") {\n return prepareTextPart(attachment);\n }\n\n return prepareImagePart(attachment);\n}\n\n/**\n * Decide whether the attachment is text or image. Tagged forms win\n * immediately; for shorthand we inspect the extension. Throws if the\n * shorthand doesn't look like anything we recognize.\n */\nfunction resolveKind(attachment: Attachment): AttachmentKind {\n if (isTaggedAttachment(attachment)) {\n return attachment.type;\n }\n\n const path = extractPath(attachment);\n const extension = path ? extname(stripQuery(path)).toLowerCase() : \"\";\n\n if (IMAGE_EXTENSIONS_TO_MEDIA_TYPE[extension]) {\n return \"image\";\n }\n\n if (TEXT_EXTENSIONS.has(extension)) {\n return \"text\";\n }\n\n throw new InvalidRequestError(\n \"Cannot infer attachment type from input — pass an explicit `{ type: 'image' | 'text', source: ... }` or use a recognized extension (.png, .jpg, .jpeg, .webp, .gif, .txt)\",\n );\n}\n\n/**\n * Produce an `image` ContentPart. URLs pass through; paths are\n * read from disk and base64-encoded with an inferred media type.\n * Inline base64 attachments pass through unchanged.\n */\nasync function prepareImagePart(attachment: Attachment): Promise<ContentPart> {\n const inferredMediaType = isTaggedAttachment(attachment)\n ? undefined\n : inferImageMediaType(attachment);\n\n const resolved = resolveAttachment(attachment);\n\n if (resolved.type === \"url\") {\n return { type: \"image\", source: { url: resolved.value } };\n }\n\n if (resolved.type === \"base64\") {\n return {\n type: \"image\",\n source: { base64: resolved.value, mediaType: resolved.mediaType },\n };\n }\n\n const mediaType = inferredMediaType ?? inferImageMediaType(resolved.value);\n\n if (!mediaType) {\n throw new InvalidRequestError(\n `Cannot infer media type for path \"${resolved.value}\" — use a recognized image extension or pass ` +\n \"`{ type: 'image', source: { base64, mediaType } }`\",\n { context: { path: resolved.value } },\n );\n }\n\n const bytes = await readFile(resolved.value);\n\n return {\n type: \"image\",\n source: { base64: bytes.toString(\"base64\"), mediaType },\n };\n}\n\n/**\n * Produce a `text` ContentPart. URLs are fetched as UTF-8, paths are\n * read from disk as UTF-8, inline base64 is decoded to UTF-8. The\n * result joins the conversation as an additional text part the model\n * sees before responding.\n */\nasync function prepareTextPart(attachment: Attachment): Promise<ContentPart> {\n const resolved = resolveAttachment(attachment);\n\n if (resolved.type === \"url\") {\n const response = await fetch(resolved.value);\n\n if (!response.ok) {\n throw new InvalidRequestError(\n `Failed to fetch text attachment \"${resolved.value}\" — status ${response.status}`,\n { context: { url: resolved.value, status: response.status } },\n );\n }\n\n return { type: \"text\", text: await response.text() };\n }\n\n if (resolved.type === \"base64\") {\n const decoded = Buffer.from(resolved.value, \"base64\").toString(\"utf8\");\n\n return { type: \"text\", text: decoded };\n }\n\n const bytes = await readFile(resolved.value, \"utf8\");\n\n return { type: \"text\", text: bytes };\n}\n\nfunction isTaggedAttachment(\n attachment: Attachment,\n): attachment is Extract<Attachment, { type: string }> {\n return (\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"type\" in attachment\n );\n}\n\nfunction inferImageMediaType(input: unknown): string | undefined {\n const path = extractPath(input);\n\n if (!path) {\n return undefined;\n }\n\n const extension = extname(stripQuery(path)).toLowerCase();\n\n return IMAGE_EXTENSIONS_TO_MEDIA_TYPE[extension];\n}\n\nfunction extractPath(input: unknown): string | undefined {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const storage = input as { url?: string; absolutePath?: string };\n return storage.url ?? storage.absolutePath;\n }\n\n return undefined;\n}\n\nfunction stripQuery(path: string): string {\n const queryIndex = path.indexOf(\"?\");\n\n return queryIndex === -1 ? path : path.slice(0, queryIndex);\n}\n","/**\n * Parse a JSON string, returning a caller-supplied fallback when the input\n * is empty or malformed instead of throwing. Useful at provider boundaries\n * where tool-call arguments may arrive as `null`, `\"\"`, or partial JSON\n * during streaming — callers want a safe default, not an exception.\n *\n * @example\n * const args = safeJsonParse<Record<string, unknown>>(toolCall.function.arguments, {});\n */\nexport function safeJsonParse<TValue>(\n data: string | null | undefined,\n defaultValue: TValue,\n): TValue {\n if (!data) {\n return defaultValue;\n }\n\n try {\n return JSON.parse(data) as TValue;\n } catch {\n return defaultValue;\n }\n}\n","import type { AttemptEntry } from \"./attempt-entry.type\";\nimport type { Usage } from \"./usage.type\";\n\n/**\n * Wire-format version stamped on every root `BaseReport`. Bumped only\n * when we make a BREAKING change to the report shape (field removed,\n * required-ness flipped, semantics changed). Additive changes (new\n * optional fields) do not bump.\n *\n * Panoptic and other downstream consumers branch on this to parse\n * old stored reports with their original-shape rules.\n *\n * Current: **1** — initial Panoptic-readiness shape.\n */\nexport const REPORT_SCHEMA_VERSION = 1;\n\n/**\n * Discriminator for the kind of executable that produced a given\n * {@link BaseReport}. Forms a closed union so consumers can narrow on\n * the tree without string-matching on `name`.\n */\nexport type ReportType =\n | \"tool\"\n | \"callback\"\n | \"agent\"\n | \"workflow\"\n | \"supervisor\";\n\n/**\n * Terminal status every executable primitive reports. Unified across\n * tools, agents, workflows, and supervisors so dashboards and\n * generic traversal helpers don't special-case per primitive.\n *\n * - `\"completed\"` — ran to natural end with a usable result.\n * - `\"failed\"` — aborted mid-run or finished without a usable result\n * (crash, schema failure, max-trips, etc.). The\n * accompanying `error` on the envelope carries the typed cause.\n * - `\"cancelled\"` — caller aborted before completion via `AbortSignal`.\n * - `\"max-iterations\"` — supervisor-specific termination when the\n * iteration cap was hit without an explicit `END` / `satisfied`.\n * Harmless on non-supervisor reports; keeping it on the shared\n * union lets consumers write one `switch` for every status.\n */\nexport type ReportStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"max-iterations\";\n\n/**\n * Universal execution report shared by every primitive. Per-primitive\n * report types extend this with their own domain-specific fields\n * (agent trips, workflow steps, supervisor iteration snapshots) while\n * keeping the root fields identical. Recursion happens through\n * {@link BaseReport.children} — any executable this node invoked\n * contributes its own full report here, producing a walkable tree of\n * the entire run.\n *\n * **Usage rollup.** `usage` at every node equals this node's own cost\n * plus the sum of each child's `usage`. Leaves (tools) contribute\n * zero own-cost; composites contribute their direct LLM spend only,\n * with children covering everything delegated.\n *\n * @example\n * function totalCost(report: BaseReport): number {\n * return report.usage.total;\n * }\n *\n * function walk(report: BaseReport, depth = 0): void {\n * console.log(`${\" \".repeat(depth)}${report.type} \"${report.name}\" — ${report.status}`);\n * for (const child of report.children) walk(child, depth + 1);\n * }\n */\nexport type BaseReport = {\n /** Stable id for this execution node. Generated per `execute()`/`invoke()` call. */\n runId: string;\n /**\n * Run-id of the immediate parent execution node, when this node was\n * invoked as part of a larger run (e.g. a tool dispatched by an\n * agent; an agent dispatched by a supervisor; an inner primitive\n * wrapped via `asTool()`). Absent on root nodes.\n *\n * Lets Panoptic and other flat-row consumers reconstruct the tree\n * without traversing `children[]` in memory.\n */\n parentRunId?: string;\n /**\n * Run-id of the top-level execution this node belongs to. Equals\n * `runId` on the root node, and is propagated downward to every\n * descendant. Used to slice flat report tables back into per-run\n * groupings.\n */\n rootRunId: string;\n /** Executable identity — the tool/agent/workflow/supervisor name. */\n name: string;\n /**\n * Dev-curated version string mirrored from the primitive's config\n * (`AgentConfig.version`, `ToolConfig.version`, etc.). Free-form —\n * the framework neither parses nor compares it. Stored verbatim on\n * every report so trip-archive queries can distinguish runs of\n * \"agent X v2.1\" from \"agent X v2.2\" even when name + signature\n * are identical.\n *\n * Stays `undefined` when the dev didn't declare one — never\n * auto-defaulted.\n */\n version?: string;\n /**\n * Caller-supplied identifier that groups multiple `.execute()` calls\n * into one conceptual user session / request. Propagated to every\n * descendant report node so flat queries (\"total spend for session\n * X today\") work without joining the tree.\n *\n * Threaded from `execute()` options on every primitive. Optional —\n * absent when the caller didn't supply one.\n */\n sessionId?: string;\n /** Discriminator for the kind of executable that produced this report. */\n type: ReportType;\n /** Terminal status of this execution. */\n status: ReportStatus;\n /** ISO-8601 wall-clock timestamp when execution began. */\n startedAt: string;\n /** ISO-8601 wall-clock timestamp when execution finished. */\n endedAt: string;\n /** Monotonic duration in milliseconds — `performance.now()` delta. */\n duration: number;\n /** Rolled-up usage: own cost + sum of `children[].usage`. */\n usage: Usage;\n /**\n * Reports of every executable invoked by this node, in invocation\n * order. Empty for leaves (pure tools) and for executables that\n * didn't delegate work.\n */\n children: BaseReport[];\n /**\n * Retry history when middleware (or, for workflow steps, the engine\n * itself) retried this node before it either succeeded or gave up.\n * Absent when zero retries happened — keeps the common-case payload\n * lean. The surviving (final) attempt is NOT duplicated here; its\n * outcome is the report's own `status` / timing.\n */\n attempts?: AttemptEntry[];\n /**\n * Wire-format version of this report shape. Only present on root\n * report nodes — implies the same version for the whole tree.\n * Panoptic / archive consumers branch on this to parse old reports\n * with their original-shape rules.\n *\n * Always equals {@link REPORT_SCHEMA_VERSION} at write time.\n */\n reportSchemaVersion?: number;\n};\n","import type { BaseReport } from \"../contracts/result/base-report.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\n\n/**\n * Options for {@link stampReportLineage}. Every field is optional —\n * the caller supplies whichever pieces it knows. Missing pieces are\n * left untouched (existing values on the report survive).\n */\nexport type LineageStamp = {\n /**\n * The outermost run-id this subtree belongs to. When set, EVERY\n * node in the subtree gets its `rootRunId` rewritten to this\n * value — overrides any inner self-roots produced by nested\n * `buildResult` calls.\n */\n rootRunId: string;\n /**\n * Run-id of the immediate parent of THIS subtree's top node. Each\n * descendant's `parentRunId` is then derived from its own walk\n * position (its parent's `runId`).\n */\n parentRunId?: string;\n /**\n * Caller-supplied session identifier — propagates to every node in\n * the subtree. Skipped when undefined.\n */\n sessionId?: string;\n};\n\n/**\n * Walk a freshly-built report tree and stamp lineage fields onto\n * every node:\n *\n * - `rootRunId` — rewritten to `stamp.rootRunId` everywhere. Composite\n * children built by inner primitives carry their own self-root; this\n * walk overrides it so the outer root wins (single coherent run id\n * across the whole tree).\n * - `parentRunId` — root node gets `stamp.parentRunId`; descendants\n * derive theirs from each parent's own `runId`.\n * - `sessionId` — propagated when provided.\n * - `reportSchemaVersion` — stamped only on the root (the value is the\n * same for the whole tree; storing it on every node would waste\n * space).\n *\n * Designed to run ONCE per top-level `buildResult` call. Each\n * primitive's executor invokes this on the assembled root report just\n * before returning; nested primitives produced their own subtree with\n * a self-root, and this pass relinks everything to the outer caller's\n * lineage.\n *\n * Mutates the report in place — internal use only, before the report\n * is exposed via `result.report`.\n *\n * @example\n * const root = this.buildBareReport();\n * stampReportLineage(root, { rootRunId: this.runId, sessionId: this.options?.sessionId });\n * return { ..., report: root };\n */\nexport function stampReportLineage(root: BaseReport, stamp: LineageStamp): void {\n root.reportSchemaVersion = REPORT_SCHEMA_VERSION;\n\n walk(root, stamp.rootRunId, stamp.parentRunId, stamp.sessionId);\n}\n\nfunction walk(node: BaseReport, rootRunId: string, parentRunId?: string, sessionId?: string): void {\n node.rootRunId = rootRunId;\n\n if (parentRunId !== undefined) {\n node.parentRunId = parentRunId;\n } else {\n delete node.parentRunId;\n }\n\n if (sessionId !== undefined) {\n node.sessionId = sessionId;\n }\n\n for (const child of node.children) {\n walk(child, rootRunId, node.runId, sessionId);\n }\n}\n","/**\n * Approximate the number of tokens in a string.\n *\n * Uses the ~4-characters-per-token heuristic, which is accurate enough for\n * GPT-4 family models and most English text. Use this when a real tokenizer\n * (tiktoken, etc.) isn't available or would add native dependencies.\n *\n * @example\n * const tokens = approximateTokenCount(\"Hello, world!\"); // 4\n */\nexport function approximateTokenCount(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { Placeholders } from \"../contracts/placeholders.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { extractJsonSchema, prepareAttachmentPart } from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\n\n/**\n * Outcome of `buildAgentInputMessages` — the seeded message list and\n * the JSON Schema cached for every trip's\n * `ModelCallOptions.responseSchema`. `responseSchema` is `undefined`\n * when the caller didn't ask for structured output.\n */\nexport type AgentInputBuildResult = {\n messages: Message[];\n responseSchema?: Record<string, unknown>;\n};\n\n/**\n * Assemble the seed conversation for an agent execution. Runs exactly\n * once per run — subsequent trips append to the same message list.\n *\n * Responsibilities (previously three methods on `Execution`):\n * 1. Merge factory + per-call placeholders.\n * 2. Resolve the system prompt (string, contract, or absent).\n * 3. When an output schema is supplied:\n * - cache its JSON Schema form for `ModelCallOptions.responseSchema`\n * so native-structured-output providers enforce it at the token\n * level;\n * - fall back to a soft system-prompt instruction for providers\n * that don't advertise `structuredOutput` capability.\n * 4. Append caller-supplied `history` (e.g. session-level prior turns).\n * 5. Shape the user message — plain string in the common case,\n * multipart `ContentPart[]` when `attachments` are present. Image\n * attachments require model vision capability; mismatch throws\n * `InvalidRequestError` here rather than failing opaquely at the\n * provider.\n *\n * Extracted from the `Execution` class to isolate the declarative\n * input-shaping phase from the stateful trip loop.\n */\nexport async function buildAgentInputMessages<TOutput>(params: {\n config: AgentConfig<TOutput>;\n input: string;\n options?: AgentExecuteOptions<TOutput>;\n}): Promise<AgentInputBuildResult> {\n const { config, input, options } = params;\n\n const placeholders: Placeholders = {\n ...config.placeholders,\n ...options?.placeholders,\n };\n\n const systemPrompt = options?.systemPrompt ?? config.systemPrompt;\n let systemContent = \"\";\n\n if (typeof systemPrompt === \"string\") {\n systemContent = systemPrompt;\n } else if (systemPrompt) {\n systemContent = systemPrompt.resolve(placeholders);\n }\n\n const { responseSchema, instruction } = resolveStructuredOutput({\n outputSchema: options?.output ?? config.output,\n overrideResponseSchema: options?.responseSchema,\n modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput),\n });\n\n if (instruction) {\n systemContent = systemContent ? `${systemContent}\\n\\n${instruction}` : instruction;\n }\n\n const messages: Message[] = [];\n\n if (systemContent) {\n messages.push({ role: \"system\", content: systemContent });\n }\n\n if (options?.history) {\n messages.push(...options.history);\n }\n\n const userContent = await buildUserMessageContent({\n input,\n attachments: options?.attachments,\n modelName: config.model.name,\n modelSupportsVision: Boolean(config.model.capabilities?.vision),\n });\n\n messages.push({ role: \"user\", content: userContent });\n\n return { messages, responseSchema };\n}\n\n/**\n * Build the user message `content` field. Plain string when no\n * attachments (the hot path) — keeps wire payloads small. Multipart\n * `ContentPart[]` when attachments exist: input text first, resolved\n * parts in declaration order.\n */\nasync function buildUserMessageContent(params: {\n input: string;\n attachments?: Attachment[];\n modelName: string;\n modelSupportsVision: boolean;\n}): Promise<string | ContentPart[]> {\n const { input, attachments, modelName, modelSupportsVision } = params;\n\n if (!attachments || attachments.length === 0) {\n return input;\n }\n\n const parts: ContentPart[] = await Promise.all(\n attachments.map((attachment) => prepareAttachmentPart(attachment)),\n );\n\n const hasImage = parts.some((part) => part.type === \"image\");\n\n if (hasImage && !modelSupportsVision) {\n throw new InvalidRequestError(\n `Model \"${modelName}\" does not declare vision capability — image attachments are not supported`,\n { context: { modelName } },\n );\n }\n\n return [{ type: \"text\", text: input }, ...parts];\n}\n\n/**\n * When the caller supplied an `output` schema, resolve two artifacts:\n *\n * - `responseSchema` — extracted JSON Schema to attach on every trip.\n * Adapters that natively support structured output (OpenAI's\n * `response_format: json_schema`) consume it; others ignore it.\n * - `instruction` — a soft fallback appended to the system prompt\n * **only** for models without native structured-output capability.\n * Capable adapters skip it to save tokens and avoid redundancy.\n */\nfunction resolveStructuredOutput(params: {\n outputSchema?: StandardSchemaV1<unknown>;\n overrideResponseSchema?: Record<string, unknown>;\n modelSupportsStructuredOutput: boolean;\n}): {\n responseSchema?: Record<string, unknown>;\n instruction?: string;\n} {\n const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;\n\n if (!outputSchema) {\n return {};\n }\n\n const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);\n\n if (modelSupportsStructuredOutput) {\n return { responseSchema };\n }\n\n const schemaHint = responseSchema\n ? `\\n\\nThe response MUST match this JSON Schema:\\n${JSON.stringify(responseSchema, null, 2)}`\n : \"\";\n\n const instruction = [\n \"You MUST respond with a single valid JSON value only.\",\n \"Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.\",\n schemaHint,\n ]\n .join(\"\")\n .trim();\n\n return { responseSchema, instruction };\n}\n","import type { Logger } from \"@warlock.js/logger\";\nimport type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { LLMTrip } from \"../contracts/result/llm-trip.type\";\nimport type { ToolCall } from \"../contracts/result/tool-call.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Aggregate snapshot the agent-level log entries need at emission time\n * (agent completion + model name + running totals). Passed instead of\n * storing a back-reference to the Execution class — keeps this helper\n * a pure function.\n */\nexport type AgentLogContext = {\n /** Dotted logger module, e.g. `\"ai.agent.my-writer\"`. */\n module: string;\n /** Maximum trips configured for this run — logged once on `agent.starting`. */\n maxTrips: number;\n /** Model identifier — logged once on `agent.starting`. */\n modelName: string;\n /** Final running usage totals at the moment `agent.completed` fires. */\n totalUsage: Usage;\n /** Monotonic duration (ms) since start at the moment `agent.completed` fires. */\n totalDurationMs: number;\n /** All trips recorded so far — logged count on `agent.completed`. */\n trips: LLMTrip[];\n /** All tool calls recorded so far — logged count on `agent.completed`. */\n toolCalls: ToolCall[];\n};\n\n/**\n * Structured logging for agent lifecycle events. Mirrors\n * `Execution.emit`'s call sites without touching class state — the\n * caller passes the ambient snapshot in `ctx`, we route each event to\n * the right logger level and enrich with the per-event forensic\n * detail.\n *\n * Log-level convention:\n * - `info` — lifecycle boundaries (agent starting / completed) users\n * want to see at default verbosity\n * - `debug` — per-trip + per-tool progress (hot-path, opt-in)\n * - `success` — trip completion + tool success (terminal per-step state)\n * - `warn` — tool failures (recoverable, agent loop continues)\n * - `error` — agent-level terminal errors\n *\n * Streaming deltas (`agent.trip.streaming`) are intentionally skipped\n * to avoid token-granularity log spam.\n */\nexport function logAgentEvent<K extends keyof AgentEventMap>(\n logger: Logger,\n ctx: AgentLogContext,\n event: K,\n payload: AgentEventMap[K],\n): void {\n const action = event.replace(/^agent\\./, \"\");\n\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n logger.info(ctx.module, action, \"agent starting\", {\n maxTrips: ctx.maxTrips,\n model: ctx.modelName,\n inputLength: input.length,\n });\n return;\n }\n\n case \"agent.trip.started\": {\n const { tripIndex } = payload as AgentEventMap[\"agent.trip.started\"];\n logger.debug(ctx.module, action, \"trip started\", { tripIndex });\n return;\n }\n\n case \"agent.trip.streaming\": {\n // Deltas are too high-volume to log at token granularity.\n // Skipped on purpose; debug level still fires on trip boundaries.\n return;\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n logger.success(ctx.module, action, \"trip completed\", {\n tripIndex: trip.index,\n duration: trip.duration,\n usage: trip.usage,\n finishReason: trip.finishReason,\n });\n return;\n }\n\n case \"agent.tool.calling\": {\n const { tool, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n logger.debug(ctx.module, action, `calling tool \"${tool.name}\"`, {\n tool: tool.name,\n action: tool.action,\n tripIndex,\n });\n return;\n }\n\n case \"agent.tool.called\": {\n const toolCall = payload as AgentEventMap[\"agent.tool.called\"];\n logger.success(ctx.module, action, `tool \"${toolCall.name}\" finished`, {\n tool: toolCall.name,\n duration: toolCall.duration,\n tripIndex: toolCall.tripIndex,\n });\n return;\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n logger.warn(ctx.module, action, `tool \"${tool.name}\" failed`, {\n tool: tool.name,\n tripIndex,\n error: {\n code: error.code,\n message: error.message,\n name: error.name,\n stack: error.stack,\n },\n });\n return;\n }\n\n case \"agent.completed\": {\n logger.info(ctx.module, action, \"agent completed\", {\n duration: ctx.totalDurationMs,\n usage: ctx.totalUsage,\n trips: ctx.trips.length,\n tools: ctx.toolCalls.length,\n });\n return;\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n logger.error(ctx.module, action, error.message, {\n code: error.code,\n context: error.context,\n });\n return;\n }\n }\n}\n","import type { StreamContract, StreamEvent } from \"../contracts\";\n\n/**\n * Internal async-queue `StreamContract` used by `agent().stream()`.\n *\n * **Role.** The bridge between a streaming `Execution` (which runs in the\n * background, pushing events as they happen) and a consumer that reads\n * those events with `for await` or an `on(...)` handler map.\n *\n * **Responsibility.**\n * - Owns: the event queue, the pending-read promise chain, the terminal\n * `result` promise, and any user-registered event handlers.\n * - Does NOT own: any knowledge of agents, models, or tool calls — it is a\n * generic producer/consumer pipe parameterized by `TResult`. The streaming\n * execution writes via `push()` / `end()` / `fail()`; the consumer reads\n * via the AsyncIterable surface.\n *\n * Events are coalesced into a queue so that a consumer that starts\n * iterating late still sees every event in order — nothing is dropped. The\n * `on()` handlers fire the moment an event is pushed, independent of\n * whether anyone is iterating.\n *\n * @example\n * // Inside agent.stream():\n * const { controller, stream } = createAgentStream<AgentResult<TOutput>>();\n * new Execution(config, input, options, controller).run();\n * return stream;\n *\n * // Consumer:\n * for await (const event of stream) {\n * if (event.type === \"streaming\") process.stdout.write(event.delta);\n * }\n * const result = await stream.result;\n */\nexport type StreamController<TResult> = {\n push(event: StreamEvent): void;\n end(result: TResult): void;\n fail(error: Error): void;\n};\n\ntype PendingRead = {\n resolve(value: IteratorResult<StreamEvent>): void;\n reject(error: Error): void;\n};\n\nexport function createAgentStream<TResult>(): {\n controller: StreamController<TResult>;\n stream: StreamContract<TResult>;\n} {\n const queue: StreamEvent[] = [];\n const pending: PendingRead[] = [];\n const handlers = new Map<StreamEvent[\"type\"], (event: StreamEvent) => void>();\n\n let closed = false;\n let failure: Error | undefined;\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const controller: StreamController<TResult> = {\n push(event) {\n const handler = handlers.get(event.type);\n\n if (handler) {\n try {\n handler(event);\n } catch {\n // User-provided stream handlers must never crash the agent.\n // Swallow — structured logging attaches here in Phase 0.5.\n }\n }\n\n const reader = pending.shift();\n\n if (reader) {\n reader.resolve({ value: event, done: false });\n return;\n }\n\n queue.push(event);\n },\n\n end(finalResult) {\n closed = true;\n resolveResult(finalResult);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.resolve({ value: undefined, done: true });\n }\n },\n\n fail(error) {\n closed = true;\n failure = error;\n rejectResult(error);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.reject(error);\n }\n },\n };\n\n const iterator: AsyncIterator<StreamEvent> = {\n next() {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (closed) {\n if (failure) {\n return Promise.reject(failure);\n }\n\n return Promise.resolve({ value: undefined, done: true });\n }\n\n return new Promise<IteratorResult<StreamEvent>>((resolve, reject) => {\n pending.push({ resolve, reject });\n });\n },\n };\n\n const stream: StreamContract<TResult> = {\n result,\n on(handlerMap) {\n for (const [key, handler] of Object.entries(handlerMap)) {\n if (handler) {\n handlers.set(\n key as StreamEvent[\"type\"],\n handler as (event: StreamEvent) => void,\n );\n }\n }\n\n return stream;\n },\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n\n return { controller, stream };\n}\n","import type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { StreamEventBody } from \"../contracts/stream/stream-event.type\";\n\n/**\n * Map an internal `AgentEventMap` entry into the public `StreamEvent`\n * shape. Event names are the same dot-notation strings on both sides;\n * only the payload shape needs per-event translation — the notable\n * case is `agent.tool.called`, whose event-map payload is a bare\n * `ToolCall` but whose stream wrapper is `{ toolCall }`.\n *\n * Extracted from the `Execution` class in `agent.ts` because it's\n * fully stateless (pure function of event name + payload) and used\n * only from the stream-forwarding path. Keeps the class focused on\n * stateful orchestration.\n */\nexport function agentEventToStreamEvent<K extends keyof AgentEventMap>(\n event: K,\n payload: AgentEventMap[K],\n): StreamEventBody | undefined {\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n return { type: \"agent.starting\", input };\n }\n\n case \"agent.trip.started\": {\n const { tripIndex, input } =\n payload as AgentEventMap[\"agent.trip.started\"];\n return { type: \"agent.trip.started\", tripIndex, input };\n }\n\n case \"agent.trip.streaming\": {\n const { delta, tripIndex } =\n payload as AgentEventMap[\"agent.trip.streaming\"];\n return { type: \"agent.trip.streaming\", delta, tripIndex };\n }\n\n case \"agent.tool.calling\": {\n const { tool, input, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n return { type: \"agent.tool.calling\", tool, input, tripIndex };\n }\n\n case \"agent.tool.called\": {\n const called = payload as AgentEventMap[\"agent.tool.called\"];\n // Split off the agent's enriched ToolCall record from the tool meta\n // so the stream event surface mirrors the bus payload shape.\n const { tool, ...toolCall } = called;\n return { type: \"agent.tool.called\", toolCall, tool };\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n return { type: \"agent.tool.failed\", tool, error, tripIndex };\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n return { type: \"agent.trip.completed\", trip };\n }\n\n case \"agent.completed\": {\n return { type: \"agent.completed\" };\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n return { type: \"agent.error\", error };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ModelToolCallRequest } from \"../contracts/model-tool-call-request.type\";\nimport type { ToolContract } from \"../tool/tool\";\n\n/**\n * Default cap on bytes accumulated in a single suspect buffer before\n * the guard gives up, flushes as text, and resets to pass-through.\n * Real envelope payloads observed in production leaks are well under\n * 1 KB; this is a safety valve against runaway / adversarial input.\n */\nconst DEFAULT_MAX_BUFFER_BYTES = 4096;\n\n/**\n * Fence opener the guard recognizes in pass-through mode. Targets the\n * lowercase form ```` ```json ```` only — that is the form models\n * actually emit in the wild when they fence-wrap a JSON tool envelope.\n * Other languages / casings flush as plain text.\n */\nconst FENCE_OPENER = \"```json\";\n\n/**\n * Closing fence sequence inside `bufferingFence` mode. Three backticks,\n * no language tag.\n */\nconst FENCE_CLOSER = \"```\";\n\n/**\n * Options passed when constructing a `JsonStreamGuard`.\n *\n * The guard is deliberately framework-agnostic of *how* deltas are\n * emitted or how recovered calls are dispatched — callers wire those\n * via `onSafeDelta` / `onRecoveredCall`. This keeps the unit-testable\n * surface tiny and lets the agent loop own all event-emission policy.\n */\nexport type JsonStreamGuardOptions = {\n /** Tools the agent has registered for this trip. Envelope lookups use `.name`. */\n tools: ReadonlyArray<ToolContract<unknown, unknown>>;\n /**\n * Hard cap on a single suspect buffer's size. When exceeded, the\n * buffer is flushed verbatim as text and the guard returns to\n * pass-through. Defaults to {@link DEFAULT_MAX_BUFFER_BYTES}.\n */\n maxBufferBytes?: number;\n /**\n * Called for every chunk of text that survived the guard — exactly\n * what the consumer should treat as the visible delta. May be\n * called many times per `feed()` call, possibly with a single\n * character or with a multi-character flush.\n */\n onSafeDelta: (delta: string) => void;\n /**\n * Called once per envelope the guard successfully classifies as a\n * tool-call recovery. The request carries `recoveredFrom:\n * \"stream-text\"` so downstream consumers can distinguish synthesized\n * calls from real ones.\n */\n onRecoveredCall: (request: ModelToolCallRequest) => void;\n};\n\n/**\n * Per-trip state machine that intercepts streamed text deltas, detects\n * JSON envelopes the model has emitted as plain text (the\n * tool-call-leakage symptom), and synthesizes real `ModelToolCallRequest`\n * entries for them while suppressing the JSON from visible output.\n *\n * **Role.** A `JsonStreamGuard` is the per-trip implementation of the\n * opt-in `streamingToolGuard` config. It sits between the model\n * adapter's `delta` chunks and the agent's `agent.trip.streaming`\n * emit + `content` accumulator — text that survives the guard is what\n * the consumer sees and what the trip records as `output`.\n *\n * **Responsibility.**\n * - Owns: a small character-level state machine (pass-through,\n * brace-buffering, fence-buffering), string-literal-aware brace\n * tracking, fence-opener / fence-closer detection, named-envelope\n * matching against registered tool schemas, buffer-cap enforcement.\n * - Does NOT own: event emission (delegated via callbacks), tool\n * dispatch, `finishReason` normalization, dedupe vs. real tool\n * calls — the agent loop handles all four.\n *\n * **Matcher tier — named envelope only (v1).** A buffer matches when\n * it parses as a JSON object containing both:\n * - a `name` or `tool` key resolving to a registered tool name, AND\n * - an `arguments` or `input` key whose value validates against the\n * resolved tool's `~standard` schema.\n * Bare-object matching (where any registered tool's schema is the\n * sole signal) is deferred until tool input schemas are tight enough\n * to distinguish — `v.record(v.any())` would match everything.\n *\n * **Per-trip lifecycle.** One instance per trip. The agent loop calls\n * `feed(chunk)` for every `delta` chunk and `finalize()` exactly once\n * after the stream's `done` chunk. Mid-stream cancellation: the loop\n * simply stops calling `feed`; any open buffer is discarded with the\n * guard instance.\n *\n * Modeled as a class (see §4.2 of code-style.md — per-call execution\n * state across phases): the machine has 3 states, accumulators for\n * brace depth, string-literal escape tracking, and a synthesized-call\n * counter for stable ids across the trip.\n *\n * @example\n * // Inside the agent's streaming trip body:\n * const guard = new JsonStreamGuard({\n * tools: this.config.tools ?? [],\n * maxBufferBytes: guardConfig.maxBufferBytes,\n * onSafeDelta: (delta) => {\n * content += delta;\n * this.emit(\"agent.trip.streaming\", { delta, tripIndex });\n * },\n * onRecoveredCall: (request) => recoveredCalls.push(request),\n * });\n *\n * for await (const chunk of model.stream(messages, callOptions)) {\n * if (chunk.type === \"delta\") await guard.feed(chunk.content);\n * // ... other chunk types\n * }\n *\n * await guard.finalize();\n */\nexport class JsonStreamGuard {\n private readonly tools: ReadonlyArray<ToolContract<unknown, unknown>>;\n private readonly maxBufferBytes: number;\n private readonly onSafeDelta: (delta: string) => void;\n private readonly onRecoveredCall: (request: ModelToolCallRequest) => void;\n\n private mode: \"passThrough\" | \"bufferingBrace\" | \"bufferingFence\" = \"passThrough\";\n\n /**\n * Characters held back in pass-through mode while we resolve whether\n * a partial fence opener (`` ` ``, `` `` ``, `` ``` ``, `` ```j ``, …)\n * will complete or break. Always a strict prefix of {@link FENCE_OPENER};\n * emptied (and emitted verbatim) the moment a non-matching character\n * arrives.\n */\n private holdback = \"\";\n\n /**\n * Accumulator while `mode === \"bufferingBrace\"` or `\"bufferingFence\"`.\n * In brace mode it carries the JSON including the outermost `{`/`}`.\n * In fence mode it carries everything between the opener and the\n * closer (the opener and closer themselves are NOT in the buffer —\n * they are reconstructed only on a flush-as-text fallback).\n */\n private buffer = \"\";\n\n /**\n * Brace-depth counter for `bufferingBrace` mode. Increments on `{`,\n * decrements on `}` — but only when {@link inString} is false, so a\n * `{` inside a JSON string literal does not skew the depth. Buffer\n * closes when depth returns to zero.\n */\n private braceDepth = 0;\n\n /** True while the scanner is inside a `\"...\"` JSON string literal. */\n private inString = false;\n\n /**\n * True when the previous character inside a string literal was a\n * backslash, so the current character is escaped (`\\\"` does not end\n * the string; `\\\\` resets the flag without escaping anything else).\n */\n private escapeNext = false;\n\n /**\n * Trailing tail of the fence buffer used to detect the closing\n * ```` ``` ```` sequence. Length capped at the closer length; rotated\n * forward as new characters arrive.\n */\n private fenceCloseTail = \"\";\n\n /**\n * Count of envelopes the guard has successfully synthesized this\n * trip. Used to assign deterministic, collision-free ids on\n * recovered `ModelToolCallRequest` entries.\n */\n private recoveredCount = 0;\n\n public constructor(options: JsonStreamGuardOptions) {\n this.tools = options.tools;\n this.maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n this.onSafeDelta = options.onSafeDelta;\n this.onRecoveredCall = options.onRecoveredCall;\n }\n\n /**\n * Feed the next raw delta from the model. Splits the chunk into\n * characters and runs each through the state machine, awaiting\n * envelope classification whenever a buffer closes mid-chunk.\n *\n * The hot path (pass-through prose with no `{` / `` ` ``) is fully\n * synchronous — `await` here only blocks at buffer-close points,\n * which are rare in normal traffic.\n */\n public async feed(chunk: string): Promise<void> {\n for (let i = 0; i < chunk.length; i++) {\n await this.processChar(chunk[i]);\n }\n }\n\n /**\n * Stream ended. Anything still in the holdback was prose\n * misclassified as a partial fence opener — emit it. Anything still\n * in an open buffer never closed — emit it as text too (a leak\n * truncated mid-flight is still text the user partially saw).\n */\n public async finalize(): Promise<void> {\n if (this.holdback.length > 0) {\n this.onSafeDelta(this.holdback);\n this.holdback = \"\";\n }\n\n if (this.mode === \"bufferingBrace\") {\n this.flushBraceBufferAsText();\n return;\n }\n\n if (this.mode === \"bufferingFence\") {\n this.flushFenceBufferAsText();\n }\n }\n\n /**\n * True when at least one envelope was recovered this trip. The\n * agent loop reads this to override `finishReason` from `\"stop\"` to\n * `\"tool_calls\"` when the model reported a natural stop but the\n * guard found tool calls hiding in the text channel.\n */\n public hasRecoveredCalls(): boolean {\n return this.recoveredCount > 0;\n }\n\n /**\n * Route a single character based on the current mode. The\n * `passThrough` branch handles holdback expansion / flushing\n * iteratively (no recursion) so a character that \"breaks\" a fence\n * opener can be re-evaluated as a fresh pass-through input in the\n * same call.\n */\n private async processChar(char: string): Promise<void> {\n if (this.mode === \"bufferingBrace\") {\n await this.processBraceChar(char);\n return;\n }\n\n if (this.mode === \"bufferingFence\") {\n await this.processFenceChar(char);\n return;\n }\n\n let current = char;\n\n while (true) {\n if (this.holdback.length === 0 && current === \"{\") {\n this.openBraceBuffer(current);\n return;\n }\n\n const extended = this.holdback + current;\n\n if (this.isFenceOpenerPrefix(extended)) {\n this.holdback = extended;\n\n if (extended === FENCE_OPENER) {\n this.openFenceBuffer();\n }\n\n return;\n }\n\n if (this.holdback.length === 0) {\n this.onSafeDelta(current);\n return;\n }\n\n this.onSafeDelta(this.holdback);\n this.holdback = \"\";\n }\n }\n\n /**\n * Recognize any strict prefix of {@link FENCE_OPENER} including the\n * full string. Used to decide whether to keep extending the holdback\n * or flush it as plain text.\n */\n private isFenceOpenerPrefix(candidate: string): boolean {\n return candidate.length <= FENCE_OPENER.length && FENCE_OPENER.startsWith(candidate);\n }\n\n /**\n * Enter `bufferingBrace` mode with the seed `{` as the first buffer\n * character and the initial brace depth set to one. Any holdback at\n * this point was already a non-fence sequence so it stays empty.\n */\n private openBraceBuffer(seed: string): void {\n this.mode = \"bufferingBrace\";\n this.buffer = seed;\n this.braceDepth = 1;\n this.inString = false;\n this.escapeNext = false;\n }\n\n /**\n * Enter `bufferingFence` mode immediately after the opener\n * ```` ```json ```` matched in the holdback. Holdback resets;\n * subsequent characters accumulate into the buffer until the\n * closing fence is seen.\n */\n private openFenceBuffer(): void {\n this.mode = \"bufferingFence\";\n this.buffer = \"\";\n this.fenceCloseTail = \"\";\n this.holdback = \"\";\n }\n\n /**\n * Process one character while accumulating a brace-delimited JSON\n * object. Tracks string-literal context so `{` / `}` inside `\"...\"`\n * do not skew brace depth. Closes (and classifies) on balanced\n * braces; flushes-as-text on cap overflow.\n */\n private async processBraceChar(char: string): Promise<void> {\n this.buffer += char;\n\n if (this.inString) {\n if (this.escapeNext) {\n this.escapeNext = false;\n return;\n }\n\n if (char === \"\\\\\") {\n this.escapeNext = true;\n return;\n }\n\n if (char === '\"') {\n this.inString = false;\n }\n\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === '\"') {\n this.inString = true;\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === \"{\") {\n this.braceDepth++;\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === \"}\") {\n this.braceDepth--;\n\n if (this.braceDepth === 0) {\n await this.closeBraceBuffer();\n return;\n }\n\n this.guardBufferCap(\"brace\");\n return;\n }\n\n this.guardBufferCap(\"brace\");\n }\n\n /**\n * Process one character while accumulating a fence-delimited JSON\n * block. The closing fence ```` ``` ```` ends the block; the closing\n * characters are NOT included in the classified buffer (they are\n * re-emitted only when the block flushes back to text).\n */\n private async processFenceChar(char: string): Promise<void> {\n this.fenceCloseTail += char;\n\n if (this.fenceCloseTail.length > FENCE_CLOSER.length) {\n this.fenceCloseTail = this.fenceCloseTail.slice(-FENCE_CLOSER.length);\n }\n\n if (this.fenceCloseTail === FENCE_CLOSER) {\n const innerLength = this.buffer.length - (FENCE_CLOSER.length - 1);\n this.buffer = this.buffer.slice(0, Math.max(0, innerLength));\n\n await this.closeFenceBuffer();\n return;\n }\n\n this.buffer += char;\n this.guardBufferCap(\"fence\");\n }\n\n /**\n * Enforce the buffer-byte cap. When the current buffer exceeds the\n * cap, flush it back to the consumer as plain text and reset to\n * pass-through. Acts as a runaway / adversarial-input safety valve.\n */\n private guardBufferCap(source: \"brace\" | \"fence\"): void {\n if (this.buffer.length <= this.maxBufferBytes) {\n return;\n }\n\n if (source === \"brace\") {\n this.flushBraceBufferAsText();\n return;\n }\n\n this.flushFenceBufferAsText();\n }\n\n /**\n * Run the envelope matcher against the closed brace buffer. On a\n * match, synthesize a recovered `ModelToolCallRequest`; on no\n * match, flush the buffer back as plain text. Resets state to\n * pass-through either way.\n */\n private async closeBraceBuffer(): Promise<void> {\n const closed = this.buffer;\n\n this.resetToPassThrough();\n\n const matched = await this.tryMatchEnvelope(closed);\n\n if (matched) {\n return;\n }\n\n this.onSafeDelta(closed);\n }\n\n /**\n * Run the envelope matcher against the closed fence buffer. On a\n * match, synthesize a recovered call; on no match, flush as text\n * **with** the original opener and closer reconstructed so the\n * customer sees exactly the markdown the model emitted.\n */\n private async closeFenceBuffer(): Promise<void> {\n const closed = this.buffer;\n\n this.resetToPassThrough();\n\n const matched = await this.tryMatchEnvelope(closed);\n\n if (matched) {\n return;\n }\n\n this.onSafeDelta(`${FENCE_OPENER}${closed}${FENCE_CLOSER}`);\n }\n\n /**\n * Emit the brace-buffer verbatim as text and reset to pass-through.\n * Used on cap overflow and on `finalize()` for an unclosed buffer.\n */\n private flushBraceBufferAsText(): void {\n const closed = this.buffer;\n this.resetToPassThrough();\n this.onSafeDelta(closed);\n }\n\n /**\n * Emit the fence-buffer verbatim as text, reconstructing the\n * opener and closer so the original markdown structure is\n * preserved for the consumer.\n */\n private flushFenceBufferAsText(): void {\n const closed = this.buffer;\n this.resetToPassThrough();\n this.onSafeDelta(`${FENCE_OPENER}${closed}`);\n }\n\n /**\n * Reset all per-buffer state back to the pass-through baseline.\n * Called whenever a buffer closes — by recovery, by flush, or by\n * cap overflow — so the next character starts a fresh scan.\n */\n private resetToPassThrough(): void {\n this.mode = \"passThrough\";\n this.buffer = \"\";\n this.braceDepth = 0;\n this.inString = false;\n this.escapeNext = false;\n this.fenceCloseTail = \"\";\n }\n\n /**\n * Attempt to classify a closed buffer as a tool-call envelope. On\n * success, invoke `onRecoveredCall` with a synthesized request and\n * return `true`; on failure return `false` so the caller can flush\n * the buffer back as text.\n */\n private async tryMatchEnvelope(raw: string): Promise<boolean> {\n const parsed = safeParseJson(raw);\n\n if (parsed === undefined || typeof parsed !== \"object\" || parsed === null) {\n return false;\n }\n\n const envelope = parsed as Record<string, unknown>;\n const candidateName = readString(envelope, \"name\") ?? readString(envelope, \"tool\");\n const candidateInput = readObject(envelope, \"arguments\") ?? readObject(envelope, \"input\");\n\n if (!candidateName || !candidateInput) {\n return false;\n }\n\n const tool = this.tools.find((entry) => entry.name === candidateName);\n\n if (!tool || !tool.input) {\n return false;\n }\n\n const schema = tool.input as StandardSchemaV1<unknown>;\n\n let validationResult: StandardSchemaV1.Result<unknown>;\n\n try {\n validationResult = await schema[\"~standard\"].validate(candidateInput);\n } catch {\n return false;\n }\n\n if (validationResult.issues) {\n return false;\n }\n\n this.recoveredCount++;\n\n this.onRecoveredCall({\n id: `synth_${candidateName}_${this.recoveredCount}`,\n name: candidateName,\n input: validationResult.value,\n recoveredFrom: \"stream-text\",\n });\n\n return true;\n }\n}\n\n/**\n * Parse a JSON string returning `undefined` on any failure. Local to\n * the guard so it can distinguish \"not JSON\" from a parsed `null`\n * value, which `safeJsonParse` cannot — a parsed `null` is a valid\n * JSON value but not a valid envelope, and we want the difference.\n */\nfunction safeParseJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a string-typed field from an envelope candidate. Returns\n * `undefined` when the key is missing or the value is non-string —\n * the matcher rejects either case.\n */\nfunction readString(envelope: Record<string, unknown>, key: string): string | undefined {\n const value = envelope[key];\n\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Read an object-typed field from an envelope candidate. Returns\n * `undefined` when the key is missing or the value is not a\n * plain object (rejects arrays, primitives, null) — tool input\n * schemas always validate against an object root.\n */\nfunction readObject(\n envelope: Record<string, unknown>,\n key: string,\n): Record<string, unknown> | undefined {\n const value = envelope[key];\n\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n return value as Record<string, unknown>;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n AgentContract,\n AgentEventHandler,\n AgentEventMap,\n AgentExecuteOptions,\n AgentResult,\n BaseReport,\n CompleteEvent,\n FinishReason,\n LLMTrip,\n Message,\n MiddlewareExecuteContext,\n MiddlewareState,\n MiddlewareToolContext,\n MiddlewareTripContext,\n ModelResponse,\n ModelToolCallRequest,\n StreamContract,\n StreamEventBody,\n StreamingToolGuardConfig,\n ToolCall,\n ToolEventMeta,\n Usage,\n UsageEvent,\n WithoutIdentity,\n} from \"../contracts\";\nimport {\n AgentCancelledError,\n AgentExecutionError,\n AgentMaxTripsError,\n AIError,\n SchemaValidationError,\n} from \"../errors\";\nimport { runPipeline } from \"../middleware\";\nimport type { ToolContract, ToolInvokeResult } from \"../tool/tool\";\nimport {\n accumulateCost,\n computeCost,\n extractJsonPayload,\n generateRunId,\n safeJsonParse,\n stampReportLineage,\n} from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\nimport { buildAgentInputMessages } from \"./agent-input-builder\";\nimport { logAgentEvent } from \"./agent-log-event\";\nimport { createAgentStream, type StreamController } from \"./agent-stream\";\nimport { agentEventToStreamEvent } from \"./agent-to-stream-event\";\nimport { JsonStreamGuard } from \"./json-stream-guard\";\n\nconst LOG_MODULE = \"ai.agent\";\n\n/**\n * Detect abort-flavored errors surfaced by SDK HTTP layers — the\n * DOM `AbortError`, axios `ERR_CANCELED`, node-fetch's own\n * `AbortError`. Used to classify them as cancellation rather than\n * generic agent-execution failures.\n */\nfunction isAbortLike(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n\n const e = err as { name?: unknown; code?: unknown };\n\n return e.name === \"AbortError\" || e.code === \"ERR_CANCELED\" || e.code === \"ABORT_ERR\";\n}\n\n/**\n * Readable synthetic name for agents constructed without an explicit\n * `name`. Format: `anon_<provider>_<model>[_<tool1>+<tool2>+...]` —\n * deterministic (same config → same name across restarts) and\n * human-readable in logs / workflow snapshots.\n *\n * Keeps drift detection honest for the `ai.agent({ model })`\n * one-liner without punishing it with a hashed id nobody can read.\n */\nfunction synthesizeAgentName<T>(config: AgentConfig<T>): string {\n const provider = (config.model as unknown as { provider?: string })?.provider ?? \"unknown\";\n const model = config.model?.name ?? \"unknown\";\n const tools = (config.tools ?? [])\n .map((tool) => tool.name)\n .sort()\n .join(\"+\");\n\n const base = `anon_${sanitize(provider)}_${sanitize(model)}`;\n return tools ? `${base}_${sanitize(tools, { keepPlus: true })}` : base;\n}\n\nfunction sanitize(value: string, opts: { keepPlus?: boolean } = {}): string {\n const allowed = opts.keepPlus ? /[^a-zA-Z0-9._+-]/g : /[^a-zA-Z0-9._-]/g;\n return value.replace(allowed, \"-\");\n}\n\n/**\n * Authoring-time check on the middleware array. Throws an\n * `AgentExecutionError` with `context: { authoring: true }` the\n * moment an invalid entry is found — the agent factory surface is\n * where config bugs should surface, not ten trips into a run.\n *\n * Validates:\n * - Every entry is a non-null object with a non-empty string `name`.\n * - No two entries share the same `name` (would silently collide on\n * `ctx.state` keys and produce impossible-to-debug behavior).\n *\n * Does NOT validate that hook maps contain callable functions —\n * that would catch late-binding bugs but also reject legitimate\n * patterns like `before` being conditionally `undefined`. Runtime\n * dispatch handles missing hooks safely.\n */\nfunction validateMiddleware(middleware: ReadonlyArray<unknown> | undefined): void {\n if (!middleware || middleware.length === 0) {\n return;\n }\n\n const seen = new Set<string>();\n\n for (let index = 0; index < middleware.length; index++) {\n const entry = middleware[index];\n\n if (!entry || typeof entry !== \"object\") {\n throw new AgentExecutionError(\n `middleware[${index}] must be an object; received ${entry === null ? \"null\" : typeof entry}`,\n { context: { authoring: true, index } },\n );\n }\n\n const name = (entry as { name?: unknown }).name;\n\n if (typeof name !== \"string\" || name.length === 0) {\n throw new AgentExecutionError(`middleware[${index}] must have a non-empty string \"name\"`, {\n context: { authoring: true, index },\n });\n }\n\n if (seen.has(name)) {\n throw new AgentExecutionError(\n `duplicate middleware name \"${name}\" — each middleware needs a unique name so ctx.state keys do not collide`,\n { context: { authoring: true, index, name } },\n );\n }\n\n seen.add(name);\n }\n}\n\n/**\n * Creates an executable AI agent from the given configuration.\n *\n * The agent runs a bounded trip loop: each trip calls the model, dispatches\n * any requested tool calls, then loops until the model stops or `maxTrips`\n * is reached. Each `execute()` / `stream()` call spawns a fresh internal\n * `Execution` instance — the factory itself holds no state across calls.\n *\n * `execute()` never throws — any error is attached to the returned result\n * under `result.error`. `stream()` surfaces errors both on the terminal\n * `error` stream event and via the `stream.result` promise.\n *\n * @example\n * const myAgent = agent({\n * model: openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the capital of Egypt?\");\n *\n * @example\n * const stream = myAgent.stream(\"Write a haiku about Cairo.\");\n *\n * for await (const event of stream) {\n * if (event.type === \"streaming\") process.stdout.write(event.delta);\n * }\n *\n * const result = await stream.result;\n */\nexport function agent<TOutput = unknown>(config: AgentConfig<TOutput>): AgentContract<TOutput> {\n // Authoring-time validation of the middleware array. Rejects two\n // classes of bug that would otherwise surface as opaque failures\n // mid-execution: (a) entries that aren't proper middleware\n // objects (null, undefined, missing `name`), and (b) two\n // middlewares sharing the same `name`, which would silently\n // collide on `ctx.state` keys. Fail fast, fail loud — per the\n // authoring-time rules in `domains/ai/conventions/errors.md`.\n validateMiddleware(config.middleware);\n\n // Resolve the agent's identity. Explicit `name` wins; otherwise we\n // synthesize a DETERMINISTIC fingerprint from the config's\n // identity-defining fields (model + provider + tool names). Same\n // config across process restarts produces the same synthetic name,\n // so workflow signature drift detection stays honest for agents\n // composed into workflows without explicit names.\n const isAnonymous = !config.name || typeof config.name !== \"string\";\n const name = isAnonymous ? synthesizeAgentName(config) : (config.name as string);\n const resolvedConfig: AgentConfig<TOutput> = { ...config, name };\n\n // Instance-level handlers registered via `.on()`. Stored here\n // (factory-scope) so every `execute()` / `stream()` call on this\n // agent sees the same set. Each event name gets its own Set so\n // `off()` can remove a specific handler without disturbing others.\n const instanceHandlers = new Map<\n keyof AgentEventMap,\n Set<AgentEventHandler<keyof AgentEventMap>>\n >();\n\n function on<K extends keyof AgentEventMap>(event: K, handler: AgentEventHandler<K>): () => void {\n const existing = instanceHandlers.get(event);\n const bucket = existing ?? new Set<AgentEventHandler<keyof AgentEventMap>>();\n\n if (!existing) {\n instanceHandlers.set(event, bucket);\n }\n\n bucket.add(handler as AgentEventHandler<keyof AgentEventMap>);\n\n return () => off(event, handler);\n }\n\n function off<K extends keyof AgentEventMap>(event: K, handler: AgentEventHandler<K>): void {\n const bucket = instanceHandlers.get(event);\n\n if (!bucket) {\n return;\n }\n\n bucket.delete(handler as AgentEventHandler<keyof AgentEventMap>);\n\n if (bucket.size === 0) {\n instanceHandlers.delete(event);\n }\n }\n\n return {\n name,\n isAnonymous,\n description: config.description,\n async execute(\n input: string,\n options?: AgentExecuteOptions<TOutput>,\n ): Promise<AgentResult<TOutput>> {\n return new Execution<TOutput>(\n resolvedConfig,\n input,\n options,\n undefined,\n instanceHandlers,\n ).run();\n },\n\n stream(\n input: string,\n options?: AgentExecuteOptions<TOutput>,\n ): StreamContract<AgentResult<TOutput>> {\n const { controller, stream } = createAgentStream<AgentResult<TOutput>>();\n\n const execution = new Execution<TOutput>(\n resolvedConfig,\n input,\n options,\n controller,\n instanceHandlers,\n );\n\n void execution.run();\n\n return stream;\n },\n\n on,\n off,\n };\n}\n\n/**\n * Name → handler-set map shared between the `agent()` factory and its\n * per-call `Execution`. Each `.on()` registration mutates this map;\n * every `Execution` reads from the same reference so additions and\n * removals take effect mid-flight.\n */\ntype InstanceHandlerMap = Map<keyof AgentEventMap, Set<AgentEventHandler<keyof AgentEventMap>>>;\n\n/**\n * Per-call driver that owns the full lifecycle of a single\n * `agent.execute()` or `agent.stream()` invocation.\n *\n * **Role.** An `Execution` is the short-lived state container and phase\n * orchestrator for one agent run. The public `agent()` factory stays purely\n * functional — all mutable bookkeeping (trips, tool calls, usage totals,\n * message history, terminal error, parsed output) lives here so each call\n * gets a fresh, isolated instance.\n *\n * **Responsibility.**\n * - Owns: building the initial message list, driving the bounded trip loop,\n * dispatching tool calls safely, parsing the final output against the\n * caller's schema, emitting lifecycle events (to both the user handler\n * and, in stream mode, the `StreamController`), and producing the\n * `AgentResult`.\n * - Does NOT own: how the model produces responses (delegated to\n * `ModelContract.complete` / `ModelContract.stream`), how tools execute\n * (delegated to `ToolContract.invoke`), the async-queue plumbing for\n * streaming (delegated to `createAgentStream`), or any cross-call state\n * (factory-level concerns live in `agent()`).\n *\n * Streaming mode is opt-in via the fourth constructor argument: pass a\n * `StreamController` and every event is mirrored into it while model calls\n * are driven via `model.stream()` instead of `model.complete()`. The public\n * contract of `execute()` says it never throws — `Execution` enforces that\n * by funneling every unexpected error into `this.error` and returning a\n * well-formed result regardless of what went wrong.\n *\n * Not exported — consumers interact only with the `agent()` factory (see\n * §4.2 of code-style.md — \"per-call execution state across phases\").\n *\n * @example\n * // Non-streaming — inside agent.execute():\n * const result = await new Execution(config, input, options).run();\n *\n * @example\n * // Streaming — inside agent.stream():\n * const { controller, stream } = createAgentStream();\n * void new Execution(config, input, options, controller).run();\n * return stream;\n */\nclass Execution<TOutput> {\n private readonly trips: LLMTrip[] = [];\n private readonly toolCalls: ToolCall[] = [];\n private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n private readonly messages: Message[] = [];\n private readonly maxTrips: number;\n private readonly startedAt = new Date();\n private readonly start = performance.now();\n private readonly runId = generateRunId(\"agent\");\n private readonly logger: Logger = log;\n private readonly middleware: ReadonlyArray<\n NonNullable<AgentConfig<TOutput>[\"middleware\"]>[number]\n >;\n private readonly middlewareState: MiddlewareState = new Map();\n\n private error?: AIError;\n private data?: TOutput;\n private responseSchema?: Record<string, unknown>;\n\n public constructor(\n private readonly config: AgentConfig<TOutput>,\n private readonly input: string,\n private readonly options?: AgentExecuteOptions<TOutput>,\n private readonly streamController?: StreamController<AgentResult<TOutput>>,\n private readonly instanceHandlers?: InstanceHandlerMap,\n ) {\n this.maxTrips = config.maxTrips ?? 10;\n this.middleware = config.middleware ?? [];\n }\n\n /**\n * Base middleware context shared by every level. `state` is the\n * single mutable bag threaded through `execute`, `trip`, and `tool`\n * hooks for the lifetime of this execution — fresh per `execute()`\n * call, never reused across runs.\n */\n private buildExecuteContext(): MiddlewareExecuteContext {\n return {\n agent: {\n name: this.config.name ?? this.config.model.name,\n isAnonymous: !this.config.name,\n },\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n input: this.input,\n options: this.options as AgentExecuteOptions<unknown> | undefined,\n state: this.middlewareState,\n signal: this.options?.signal,\n };\n }\n\n /**\n * Entry point for a single agent execution. Wraps the real work\n * (`runCore`) in the `execute`-level middleware pipeline, then\n * emits the terminal `agent.completed` / `agent.error` events and\n * closes the stream (if any) with the post-pipeline result — so\n * middleware that short-circuits or transforms the final result\n * still produces a well-formed public outcome.\n *\n * Must never throw: any error that escapes the pipeline is\n * converted into an `AgentResult` with `error` populated before\n * returning, preserving the `agent.execute()` public contract.\n */\n public async run(): Promise<AgentResult<TOutput>> {\n const context = this.buildExecuteContext();\n\n let result: AgentResult<TOutput>;\n\n try {\n result = (await runPipeline(\n this.middleware,\n \"execute\",\n context,\n () => this.runCore(),\n this.logger,\n )) as AgentResult<TOutput>;\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n result = this.buildResult();\n }\n\n if (result.error) {\n this.emit(\"agent.error\", { error: result.error });\n }\n\n this.emit(\"agent.completed\", { result });\n\n // Fire the `onComplete` hook with a flat payload (runId +\n // durationMs pre-extracted) for audit-log consumers. Awaited but\n // errors swallowed so consumer bugs cannot crash the agent or\n // interfere with the result returned to the caller.\n await this.fireCompleteHook(result);\n\n this.streamController?.end(result);\n\n return result;\n }\n\n /**\n * Inner body wrapped by the `execute`-level pipeline. Drives the\n * full lifecycle — build messages → emit starting → run trip loop\n * → parse output → build result. Catches any unexpected throw and\n * funnels it into `this.error` so the returned result is always\n * well-formed; `execute`-level `after` hooks receive the result,\n * with `error` populated when things went wrong.\n */\n private async runCore(): Promise<AgentResult<TOutput>> {\n try {\n await this.buildInitialMessages();\n\n this.emit(\"agent.starting\", { input: this.input });\n\n await this.runTripLoop();\n\n const parseOutcome = await this.parseOutput();\n\n if (parseOutcome === \"failed\" && this.options?.repair) {\n await this.runRepairLoop();\n }\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n }\n\n return this.buildResult();\n }\n\n /**\n * Resolve the system prompt (string or `SystemPromptContract`), merge\n * placeholders from config + execute options, inject a structured-output\n * instruction when the caller wants typed output but the model can't\n * enforce it natively, prepend any conversation history, and append the\n * user input. Produces the initial `messages` array the first trip sends\n * to the model. Runs exactly once per execution.\n */\n private async buildInitialMessages(): Promise<void> {\n const { messages, responseSchema } = await buildAgentInputMessages({\n config: this.config,\n input: this.input,\n options: this.options,\n });\n this.messages.push(...messages);\n this.responseSchema = responseSchema;\n }\n\n /**\n * Drive sequential trips up to `maxTrips`. Each trip may stop the loop\n * naturally (model returned a non-tool-call finish), abort it (model\n * threw), or continue it (model requested tools). When the loop exits\n * after the cap without a natural stop, records a \"Max trips exceeded\"\n * error so the caller can distinguish runaway tool loops from a real result.\n */\n private async runTripLoop(): Promise<void> {\n for (let tripIndex = 0; tripIndex < this.maxTrips; tripIndex++) {\n if (this.options?.signal?.aborted) {\n this.error = this.makeCancelledError();\n return;\n }\n\n const tripInput = tripIndex === 0 ? this.input : \"[tool results]\";\n const outcome = await this.runTrip(tripIndex, tripInput);\n\n if (outcome === \"error\" || outcome === \"stop\") {\n return;\n }\n }\n\n const lastTrip = this.trips[this.trips.length - 1];\n\n if (lastTrip?.finishReason === \"tool_calls\") {\n this.error = new AgentMaxTripsError(\"Max trips exceeded\", {\n maxTrips: this.maxTrips,\n });\n }\n }\n\n /**\n * Execute one round-trip to the model. Aggregates usage into the running\n * total, dispatches any requested tool calls, appends the assistant +\n * tool-result messages for the next trip, and records an `LLMTrip`.\n * Returns an outcome that tells `runTripLoop` whether to continue, stop,\n * or abort.\n */\n private async runTrip(\n tripIndex: number,\n tripInput: string,\n ): Promise<\"continue\" | \"stop\" | \"error\"> {\n this.emit(\"agent.trip.started\", { tripIndex, input: tripInput });\n\n const tripStartedAt = new Date();\n const tripStart = performance.now();\n\n let response: ModelResponse;\n\n try {\n response = await this.runTripThroughPipeline(tripIndex);\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n\n const failedTrip: LLMTrip = {\n index: tripIndex,\n input: tripInput,\n output: \"\",\n finishReason: \"error\",\n startedAt: tripStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - tripStart,\n usage: { input: 0, output: 0, total: 0 },\n error: this.error,\n };\n\n this.trips.push(failedTrip);\n\n this.emit(\"agent.trip.completed\", { trip: failedTrip });\n this.emit(\"agent.error\", { error: this.error });\n\n return \"error\";\n }\n\n // Attach per-trip cost breakdown using the model's pricing table\n // (when configured). Done at the framework boundary so stored trip\n // records carry historical cost — Panoptic and other archive\n // consumers never re-derive against today's pricing, and the\n // input/output/cached split stays queryable without joining to a\n // pricing table at all.\n if (response.usage.cost === undefined) {\n response.usage.cost = computeCost(response.usage, this.config.model.pricing);\n }\n\n this.usage.input += response.usage.input;\n this.usage.output += response.usage.output;\n this.usage.total += response.usage.total;\n if (response.usage.cachedTokens !== undefined) {\n this.usage.cachedTokens = (this.usage.cachedTokens ?? 0) + response.usage.cachedTokens;\n }\n this.usage.cost = accumulateCost(this.usage.cost, response.usage.cost);\n\n // Fire the `onUsage` hook with a flat, pre-packaged payload so\n // cost-ledger code receives stable identity (runId, model+provider)\n // without joining from elsewhere. Awaited but errors swallowed.\n await this.fireUsageHook(tripIndex, response.usage);\n\n const isToolCallTrip =\n response.finishReason === \"tool_calls\" &&\n response.toolCalls !== undefined &&\n response.toolCalls.length > 0;\n\n const tripToolCalls: ToolCall[] = [];\n\n if (isToolCallTrip) {\n this.messages.push({\n role: \"assistant\",\n content: response.content,\n toolCalls: response.toolCalls,\n });\n\n for (const toolCallRequest of response.toolCalls!) {\n const record = await this.dispatchToolCall(toolCallRequest, tripIndex);\n\n tripToolCalls.push(record);\n }\n }\n\n const trip: LLMTrip = {\n index: tripIndex,\n input: tripInput,\n output: response.content,\n finishReason: response.finishReason,\n startedAt: tripStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - tripStart,\n usage: response.usage,\n toolCalls: tripToolCalls.length > 0 ? tripToolCalls : undefined,\n };\n\n this.trips.push(trip);\n\n this.emit(\"agent.trip.completed\", { trip });\n\n if (!isToolCallTrip) {\n return \"stop\";\n }\n\n // Terminate the trip loop when EVERY tool call this trip is\n // `mode: \"silent\"`. Silent tools don't feed their result back\n // to the model — the prose the model streamed alongside the\n // tool call IS the final reply. The \"all\" rule is load-bearing:\n // if any feedback tool was called too, its result still needs\n // to round-trip, so we must continue.\n //\n // Composite (`asTool`-wrapped) tools never set `mode: \"silent\"`\n // in v1 — silent-composite mechanics are deferred per plan\n // 2026-05-07-silent-tools.md (Q4). They behave as feedback.\n const allSilent = response.toolCalls!.every((request) => {\n const registered = this.config.tools?.find((tool) => tool.name === request.name);\n return registered?.mode === \"silent\";\n });\n\n return allSilent ? \"stop\" : \"continue\";\n }\n\n /**\n * Route `getModelResponse` through the `trip`-level middleware\n * pipeline. `trip.before` hooks can short-circuit the trip by\n * returning a synthetic `ModelResponse` (semantic cache hit).\n * `trip.after` hooks can transform the response before the trip\n * record is built or any tool calls are dispatched. `trip.onError`\n * hooks can recover from provider failures (fallback chain).\n */\n private async runTripThroughPipeline(tripIndex: number): Promise<ModelResponse> {\n const context: MiddlewareTripContext = {\n ...this.buildExecuteContext(),\n tripIndex,\n messages: this.messages,\n };\n\n return (await runPipeline(\n this.middleware,\n \"trip\",\n context,\n () => this.getModelResponse(tripIndex),\n this.logger,\n )) as ModelResponse;\n }\n\n /**\n * Produce the `ModelResponse` for the current trip. In non-streaming\n * mode, delegates straight to `model.complete()`. In streaming mode,\n * drains `model.stream()` while emitting `streaming` events per delta\n * and accumulates the chunks into the same `ModelResponse` shape, so the\n * rest of the trip pipeline (tool dispatch, trip record, usage\n * aggregation) stays identical between the two modes.\n */\n private async getModelResponse(tripIndex: number): Promise<ModelResponse> {\n const callOptions = {\n ...this.config.modelOptions,\n tools: this.config.tools ?? [],\n ...(this.responseSchema ? { responseSchema: this.responseSchema } : {}),\n ...(this.options?.signal ? { signal: this.options.signal } : {}),\n };\n\n if (!this.streamController) {\n return this.config.model.complete(this.messages, callOptions);\n }\n\n let content = \"\";\n let finishReason: FinishReason = \"stop\";\n let usage: Usage = { input: 0, output: 0, total: 0 };\n const toolCalls: ModelToolCallRequest[] = [];\n const recoveredCalls: ModelToolCallRequest[] = [];\n\n const guardConfig = this.resolveStreamingToolGuard();\n const guard = guardConfig\n ? new JsonStreamGuard({\n tools: (this.config.tools ?? []) as ReadonlyArray<ToolContract<unknown, unknown>>,\n maxBufferBytes: guardConfig.maxBufferBytes,\n onSafeDelta: (delta) => {\n content += delta;\n\n this.emit(\"agent.trip.streaming\", { delta, tripIndex });\n },\n onRecoveredCall: (request) => {\n recoveredCalls.push(request);\n },\n })\n : undefined;\n\n for await (const chunk of this.config.model.stream(this.messages, callOptions)) {\n // Mid-stream abort — break out cleanly instead of continuing to\n // consume the iterator. The underlying fetch is already\n // cancelled via `signal` forwarded in callOptions; this covers\n // adapters that don't honor signal natively and keeps mock\n // models consistent under cancellation tests.\n if (this.options?.signal?.aborted) {\n throw this.makeCancelledError();\n }\n\n if (chunk.type === \"delta\") {\n if (guard) {\n await guard.feed(chunk.content);\n } else {\n content += chunk.content;\n\n this.emit(\"agent.trip.streaming\", { delta: chunk.content, tripIndex });\n }\n\n continue;\n }\n\n if (chunk.type === \"tool-call\") {\n toolCalls.push({\n id: chunk.id,\n name: chunk.name,\n input: chunk.input,\n ...(chunk.providerMetadata ? { providerMetadata: chunk.providerMetadata } : {}),\n });\n\n continue;\n }\n\n finishReason = chunk.finishReason;\n usage = chunk.usage;\n }\n\n if (guard) {\n await guard.finalize();\n }\n\n // Dedupe synthesized calls against real ones the provider streamed\n // structurally — the model occasionally emits BOTH channels for\n // the same call (real tool-call chunk + narrated JSON envelope).\n // Real wins; the synthesized duplicate is dropped so dispatch\n // doesn't run twice. See plan 2026-05-22 §Q5.\n const dedupedRecovered = recoveredCalls.filter(\n (recovered) => !isDuplicateToolCall(recovered, toolCalls),\n );\n\n const mergedToolCalls = [...toolCalls, ...dedupedRecovered];\n\n // When the guard recovered any calls but the model reported a\n // natural `\"stop\"`, override to `\"tool_calls\"` so the agent's\n // dispatch loop (`runTrip` → `isToolCallTrip`) actually fires.\n // Without this the guard silently suppresses the leaked JSON but\n // never dispatches the real action — chips never render.\n const resolvedFinishReason: FinishReason =\n dedupedRecovered.length > 0 && finishReason === \"stop\" ? \"tool_calls\" : finishReason;\n\n return {\n content,\n finishReason: resolvedFinishReason,\n usage,\n toolCalls: mergedToolCalls.length > 0 ? mergedToolCalls : undefined,\n };\n }\n\n /**\n * Resolve the effective `streamingToolGuard` for this trip.\n * Per-call options win over the agent-level config when the key is\n * explicitly present on options (including the explicit `undefined`\n * \"disable for this call\" form). Returns `undefined` when no guard\n * should run.\n */\n private resolveStreamingToolGuard(): StreamingToolGuardConfig | undefined {\n if (\n this.options !== undefined &&\n Object.prototype.hasOwnProperty.call(this.options, \"streamingToolGuard\")\n ) {\n return this.options.streamingToolGuard;\n }\n\n return this.config.streamingToolGuard;\n }\n\n /**\n * Dispatch a single tool call requested by the model. Looks up the tool\n * by name, invokes it via the safe `ToolContract.invoke` entry, pushes a\n * matching tool-result message into `this.messages` so the next trip can\n * see it, and emits the right lifecycle event (`tool-called` on success,\n * `tool-calling-failed` when the tool is unregistered or invoke returned\n * an error). Never throws — always returns a `ToolCall` record.\n */\n private async dispatchToolCall(\n toolCallRequest: ModelToolCallRequest,\n tripIndex: number,\n ): Promise<ToolCall> {\n const registeredTool = this.config.tools?.find((tool) => tool.name === toolCallRequest.name);\n\n if (!registeredTool) {\n const error = new AgentExecutionError(`Tool not registered: ${toolCallRequest.name}`, {\n context: { toolName: toolCallRequest.name, tripIndex },\n });\n\n const nowIso = new Date().toISOString();\n\n const record: ToolCall = {\n runId: generateRunId(\"tool\"),\n rootRunId: this.runId,\n name: toolCallRequest.name,\n type: \"tool\",\n status: \"failed\",\n startedAt: nowIso,\n endedAt: nowIso,\n duration: 0,\n usage: { input: 0, output: 0, total: 0 },\n children: [],\n tripIndex,\n input: toolCallRequest.input,\n error,\n ...(toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}),\n };\n\n this.toolCalls.push(record);\n\n this.messages.push({\n role: \"tool\",\n toolCallId: toolCallRequest.id,\n content: JSON.stringify({ error: error.message }),\n });\n\n // Stub meta — there's no real tool to describe. Carries the\n // requested name for log correlation and an explanatory\n // description so consumers don't see an empty string.\n this.emit(\"agent.tool.failed\", {\n tool: {\n name: toolCallRequest.name,\n description: \"(unregistered tool — no description available)\",\n },\n input: toolCallRequest.input,\n error,\n tripIndex,\n });\n\n return record;\n }\n\n // Build the lightweight event meta once. Resolves `action` to a\n // string here so consumers receive plain data rather than having\n // to re-evaluate a callback on every event.\n const toolMeta: ToolEventMeta = {\n name: registeredTool.name,\n description: registeredTool.description,\n action: resolveToolAction(registeredTool, toolCallRequest.input),\n };\n\n this.emit(\"agent.tool.calling\", {\n tool: toolMeta,\n input: toolCallRequest.input,\n tripIndex,\n });\n\n const toolContext: MiddlewareToolContext = {\n ...this.buildExecuteContext(),\n tripIndex,\n messages: this.messages,\n tool: {\n name: registeredTool.name,\n description: registeredTool.description,\n mode: registeredTool.mode,\n },\n request: toolCallRequest,\n };\n\n let invokeResult: ToolInvokeResult<unknown>;\n\n try {\n invokeResult = (await runPipeline(\n this.middleware,\n \"tool\",\n toolContext,\n () => registeredTool.invoke(toolCallRequest.input, this.options?.toolCtx),\n this.logger,\n )) as ToolInvokeResult<unknown>;\n } catch (thrown) {\n // A `tool`-level middleware hook threw. The real invoke never\n // throws (it funnels errors into `result.error`), so only a\n // middleware abort or a bug reaches this branch. Synthesize a\n // failed-invoke record so the tool-call trace stays consistent.\n const error = this.toAIError(thrown);\n const nowIso = new Date().toISOString();\n const emptyUsage: Usage = { input: 0, output: 0, total: 0 };\n\n const failedRunId = generateRunId(\"tool\");\n invokeResult = {\n error,\n usage: emptyUsage,\n report: {\n runId: failedRunId,\n rootRunId: failedRunId,\n name: registeredTool.name,\n version: registeredTool.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: nowIso,\n endedAt: nowIso,\n duration: 0,\n usage: emptyUsage,\n children: [],\n },\n };\n }\n\n // The agent-level ToolCall record merges the tool's own invocation\n // report with agent-side enrichments (tripIndex, input, output,\n // error). When the underlying tool was an `asTool`-wrapped\n // composite, its inner report becomes the sole child of this\n // ToolCall — preserving the full nested tree while keeping this\n // node's own `type` as `\"tool\"` (from the agent's POV it *was* a\n // tool dispatch).\n const innerReport = invokeResult.report;\n const isComposite = innerReport.type !== \"tool\";\n\n const record: ToolCall = {\n runId: innerReport.runId,\n rootRunId: this.runId,\n name: toolCallRequest.name,\n version: registeredTool.version,\n type: \"tool\",\n status: innerReport.status,\n startedAt: innerReport.startedAt,\n endedAt: innerReport.endedAt,\n duration: innerReport.duration,\n usage: invokeResult.usage,\n children: isComposite ? [innerReport] : innerReport.children,\n tripIndex,\n input: toolCallRequest.input,\n output: invokeResult.data,\n error: invokeResult.error,\n ...(toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}),\n };\n\n this.toolCalls.push(record);\n\n // Roll child usage into the agent's accumulator. Leaf tools\n // contribute zero; `asTool`-wrapped composites contribute the\n // full cost of the inner agent/workflow/supervisor run.\n this.usage.input += invokeResult.usage.input;\n this.usage.output += invokeResult.usage.output;\n this.usage.total += invokeResult.usage.total;\n this.usage.cost = accumulateCost(this.usage.cost, invokeResult.usage.cost);\n\n this.messages.push({\n role: \"tool\",\n toolCallId: toolCallRequest.id,\n content: invokeResult.error\n ? JSON.stringify({ error: invokeResult.error.message })\n : JSON.stringify(invokeResult.data ?? null),\n });\n\n if (invokeResult.error) {\n this.emit(\"agent.tool.failed\", {\n tool: toolMeta,\n input: toolCallRequest.input,\n error: invokeResult.error,\n tripIndex,\n });\n } else {\n this.emit(\"agent.tool.called\", { ...record, tool: toolMeta });\n }\n\n return record;\n }\n\n /**\n * Parse the final trip output against the user-supplied schema (if any).\n * Failures populate `this.error` but never throw. Returns an outcome the\n * caller uses to decide whether self-repair is worth attempting:\n *\n * - `\"skipped\"` — no schema, or a prior trip-level error already set\n * `this.error` (model crash, max trips). Not repairable; the failure\n * isn't a parse problem the model can fix by re-asking.\n * - `\"failed\"` — schema present, output text either failed JSON.parse\n * or failed `~standard.validate`. Repairable via `runRepairLoop`.\n * - `\"success\"` — parsed and validated; `this.data` populated.\n */\n private async parseOutput(): Promise<\"success\" | \"failed\" | \"skipped\"> {\n const schema = this.options?.output ?? this.config.output;\n\n if (!schema || this.error) {\n return \"skipped\";\n }\n\n const finalTrip = this.trips[this.trips.length - 1];\n const text = finalTrip?.output ?? \"\";\n\n if (!text) {\n return \"skipped\";\n }\n\n const payload = extractJsonPayload(text);\n const sentinel = Symbol(\"parse-failed\");\n const parsed = safeJsonParse<unknown>(payload, sentinel);\n\n if (parsed === sentinel) {\n this.error = new SchemaValidationError(\"Failed to parse model output as JSON\", {\n context: { text },\n });\n return \"failed\";\n }\n\n const validation = await (schema as StandardSchemaV1<TOutput>)[\"~standard\"].validate(parsed);\n\n if (validation.issues) {\n const summary = validation.issues.map((issue) => issue.message).join(\"; \");\n this.error = new SchemaValidationError(summary, {\n issues: validation.issues,\n });\n return \"failed\";\n }\n\n this.data = validation.value;\n return \"success\";\n }\n\n /**\n * Opt-in self-repair loop for `output` schema failures. Triggered only\n * when `options.repair` is set and `parseOutput()` returned `\"failed\"`.\n *\n * Each attempt:\n * 1. Pushes the bad assistant response into `this.messages` (so the\n * model can see what it just produced).\n * 2. Pushes a corrective user message naming the validation/parse error.\n * 3. Runs another trip — counted against the same `maxTrips` cap as\n * normal trips so a stuck model can't loop forever.\n * 4. Re-parses. Stops on success, on a trip-level error, or when\n * either `maxAttempts` or `maxTrips` is exhausted.\n *\n * Resets `this.error` and `this.data` before each attempt so the final\n * outcome (success or last failure) is what surfaces to the caller.\n */\n private async runRepairLoop(): Promise<void> {\n const maxAttempts = this.options?.repair?.maxAttempts ?? 1;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (this.trips.length >= this.maxTrips) {\n return;\n }\n\n const lastTrip = this.trips[this.trips.length - 1];\n const badResponse = lastTrip?.output ?? \"\";\n const failureReason = this.error?.message ?? \"unknown validation failure\";\n\n this.error = undefined;\n this.data = undefined;\n\n this.messages.push({ role: \"assistant\", content: badResponse });\n\n this.messages.push({\n role: \"user\",\n content: [\n `Your previous response failed validation: ${failureReason}.`,\n \"Respond again with valid JSON only — no prose, no markdown fences, no commentary.\",\n ].join(\" \"),\n });\n\n const tripIndex = this.trips.length;\n\n this.logger.warn(LOG_MODULE, \"repair.attempting\", \"retrying after validation failure\", {\n attempt: attempt + 1,\n maxAttempts,\n reason: failureReason,\n });\n\n const outcome = await this.runTrip(tripIndex, \"[repair attempt]\");\n\n if (outcome === \"error\") {\n return;\n }\n\n const parseOutcome = await this.parseOutput();\n\n if (parseOutcome === \"success\") {\n return;\n }\n }\n }\n\n /**\n * Build the final `AgentResult` snapshot from accumulated state\n * (trips, tool calls, data/error, usage, timing).\n *\n * Pure — no side effects. `run()` owns terminal event emission and\n * stream closure so the post-pipeline result (possibly transformed\n * or short-circuited by an `execute`-level middleware) is what\n * flows out to consumers and listeners.\n *\n * Trips, tool calls, status, and timing live under `report` so the\n * root stays focused on the four things callers reach for most:\n * `data`, `text`, `usage`, `error`.\n */\n private buildResult(): AgentResult<TOutput> {\n const finalTrip = this.trips[this.trips.length - 1];\n const endedAt = new Date();\n\n const agentName = this.config.name ?? this.config.model.name;\n const status: BaseReport[\"status\"] = this.error\n ? this.error instanceof AgentCancelledError\n ? \"cancelled\"\n : \"failed\"\n : \"completed\";\n\n const report = {\n runId: this.runId,\n rootRunId: this.runId,\n name: agentName,\n version: this.config.version,\n type: \"agent\" as const,\n status,\n startedAt: this.startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration: performance.now() - this.start,\n usage: this.usage,\n children: this.toolCalls,\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n trips: this.trips,\n };\n\n // Stamp lineage on the assembled tree exactly once per run.\n // Rewrites any inner self-roots from composite children to this\n // run's id, stamps `reportSchemaVersion` on the root, and\n // propagates `sessionId` to every node.\n stampReportLineage(report, {\n rootRunId: this.runId,\n sessionId: this.options?.sessionId,\n });\n\n return {\n type: \"agent\",\n data: this.data,\n text: finalTrip?.output,\n report,\n usage: this.usage,\n error: this.error,\n };\n }\n\n /**\n * Normalize any thrown value into an `AIError`. `AIError` instances\n * pass through untouched; provider-adapter SDK errors are caught by\n * the adapter and already arrive typed, so this branch mainly\n * handles runtime crashes (TypeError, ReferenceError) inside\n * model.complete / model.stream and non-Error values (`throw \"bad\"`).\n */\n private toAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n // Classify abort-flavored errors (DOMException \"AbortError\",\n // node-fetch's `FetchError` with name \"AbortError\", `ERR_CANCELED`\n // from the OpenAI SDK's axios-ish layer) as cancelled instead of\n // a generic exec failure so callers can route retries correctly.\n if (isAbortLike(thrown)) {\n return this.makeCancelledError();\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new AgentExecutionError(message, { cause: thrown });\n }\n\n /**\n * Build the typed cancelled error that both the trip-loop guard\n * and the mid-stream guard emit. Captures the abort reason when\n * one was supplied to `controller.abort(reason)` so logs and\n * telemetry can see what cancelled the run.\n */\n private makeCancelledError(): AgentCancelledError {\n const reason = this.options?.signal?.reason;\n const reasonText = reason === undefined ? \"\" : String(reason);\n\n return new AgentCancelledError(\"agent execution cancelled\", {\n cause: reason,\n cancelledAt: new Date().toISOString(),\n reason: reasonText,\n });\n }\n\n /**\n * Fire a single event through all three subscription tiers in order\n * — factory → instance → per-call — and mirror it into the\n * `StreamController` when streaming is active. A throwing user\n * handler must never crash the agent, so every dispatch is wrapped\n * in `safeCall`. Stream events are converted from the internal\n * `AgentEventMap` payload to the public `StreamEvent` shape because\n * some of them differ (e.g. the tool-called payload vs stream\n * event).\n */\n private emit<K extends keyof AgentEventMap>(\n event: K,\n payload: WithoutIdentity<AgentEventMap[K]>,\n ): void {\n // Inject run identity once, here, so every subscription tier and\n // the stream see it. `rootRunId === runId` for a standalone run;\n // nested propagation lands in a follow-up.\n const fullPayload = {\n ...payload,\n runId: this.runId,\n rootRunId: this.runId,\n } as AgentEventMap[K];\n\n this.logEvent(event, fullPayload);\n\n const factoryHandler = this.config.on?.[event] as AgentEventHandler<K> | undefined;\n\n if (factoryHandler) {\n safeCall(factoryHandler, fullPayload);\n }\n\n const bucket = this.instanceHandlers?.get(event);\n\n if (bucket) {\n for (const handler of bucket) {\n safeCall(handler as AgentEventHandler<K>, fullPayload);\n }\n }\n\n const perCallHandler = this.options?.on?.[event] as AgentEventHandler<K> | undefined;\n\n if (perCallHandler) {\n safeCall(perCallHandler, fullPayload);\n }\n\n if (this.streamController) {\n const body = this.toStreamEvent(event, fullPayload);\n\n if (body) {\n this.streamController.push({\n runId: this.runId,\n rootRunId: this.runId,\n ...body,\n });\n }\n }\n }\n\n /**\n * Emit a structured log line for a lifecycle event. The action\n * string mirrors the event name with the `agent.` prefix stripped\n * (`agent.trip.started` → `trip.started`) so log grep filters and\n * event handlers read the same vocabulary. Level mapping follows\n * the convention documented on `@warlock.js/logger`'s `Logger`.\n */\n private logEvent<K extends keyof AgentEventMap>(event: K, payload: AgentEventMap[K]): void {\n const agentName = this.config.name || this.config.model.name;\n logAgentEvent(\n this.logger,\n {\n module: `${LOG_MODULE}.${agentName}`,\n maxTrips: this.maxTrips,\n modelName: this.config.model.name,\n totalUsage: this.usage,\n totalDurationMs: performance.now() - this.start,\n trips: this.trips,\n toolCalls: this.toolCalls,\n },\n event,\n payload,\n );\n }\n\n private toStreamEvent<K extends keyof AgentEventMap>(\n event: K,\n payload: AgentEventMap[K],\n ): StreamEventBody | undefined {\n return agentEventToStreamEvent(event, payload);\n }\n\n /**\n * Invoke the `onUsage` hook (when configured) with a flat payload\n * carrying stable identity. Awaits the handler so async ledger\n * writes complete before the next trip starts; swallows any throw\n * so consumer bugs cannot crash the agent. Sync handlers wrapped\n * via `Promise.resolve()` so the await is safe in either case.\n */\n private async fireUsageHook(tripIndex: number, tripUsage: Usage): Promise<void> {\n const handler = this.config.onUsage;\n if (!handler) return;\n\n const event: UsageEvent = {\n runId: this.runId,\n tripIndex,\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n usage: { ...tripUsage },\n timestamp: new Date().toISOString(),\n };\n\n try {\n await Promise.resolve(handler(event));\n } catch (err) {\n this.logger.warn(LOG_MODULE, \"onUsage.hook.error\", \"onUsage handler threw\", {\n runId: this.runId,\n tripIndex,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n /**\n * Invoke the `onComplete` hook (when configured) once at the end\n * of every run. Receives the full `AgentResult` plus pre-extracted\n * `runId` and `durationMs`. Same swallow-and-log error policy as\n * `fireUsageHook`.\n */\n private async fireCompleteHook(result: AgentResult<TOutput>): Promise<void> {\n const handler = this.config.onComplete;\n if (!handler) return;\n\n const event: CompleteEvent<TOutput> = {\n result,\n runId: this.runId,\n durationMs: performance.now() - this.start,\n };\n\n try {\n await Promise.resolve(handler(event));\n } catch (err) {\n this.logger.warn(LOG_MODULE, \"onComplete.hook.error\", \"onComplete handler threw\", {\n runId: this.runId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n}\n\n/**\n * Decide whether a guard-synthesized tool call duplicates a real one\n * the provider already streamed structurally. Match key is\n * `name + key-sorted JSON of input` so identical calls (regardless of\n * argument key order) collapse, but two legitimate calls to the same\n * tool with different inputs still both dispatch.\n */\nfunction isDuplicateToolCall(\n recovered: ModelToolCallRequest,\n realCalls: ReadonlyArray<ModelToolCallRequest>,\n): boolean {\n const recoveredKey = `${recovered.name}|${stableStringify(recovered.input)}`;\n\n for (const real of realCalls) {\n const realKey = `${real.name}|${stableStringify(real.input)}`;\n\n if (realKey === recoveredKey) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * `JSON.stringify` variant that sorts object keys at every nesting\n * level so structurally-equal inputs serialize to identical strings.\n * Used only for dedupe-key comparison; never surfaces to consumers.\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(value, (_key, val) => {\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n const source = val as Record<string, unknown>;\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(source).sort()) {\n sorted[key] = source[key];\n }\n\n return sorted;\n }\n\n return val;\n });\n}\n\n/**\n * Invoke a user-supplied event handler without letting exceptions\n * escape the agent. Thrown errors are swallowed — structured logging\n * attaches here in Phase 0.5 so operators still see the failure.\n */\nfunction safeCall<T>(handler: (payload: T) => void, payload: T): void {\n try {\n handler(payload);\n } catch {\n // Intentionally swallowed — user handlers never crash the agent.\n }\n}\n\n/**\n * Resolve a tool's `action` declaration into a plain string for\n * inclusion in `ToolEventMeta`. Static strings pass through;\n * function-shaped actions are invoked with the validated input.\n *\n * Defensive: if the user's callback throws, swallow and return\n * `undefined` rather than crashing the agent — UI strings are not\n * worth aborting an LLM dispatch over.\n */\nfunction resolveToolAction(\n tool: ToolContract<unknown, unknown>,\n input: unknown,\n): string | undefined {\n if (tool.action === undefined) return undefined;\n if (typeof tool.action === \"string\") return tool.action;\n try {\n return tool.action(input);\n } catch {\n return undefined;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { ToolConfig, ToolContext } from \"../contracts/tool.contract\";\nimport { AIError, SchemaValidationError, ToolExecutionError } from \"../errors\";\nimport { generateRunId } from \"../utils/generate-run-id\";\n\n/**\n * Degraded `ToolContext` supplied when no caller threads one through\n * (`tool.invoke(input)` standalone, batch scripts, tests). Per\n * decisions §35 — mutations on the empty bag are harmless no-ops;\n * production paths under a supervisor receive a real ctx with the\n * iteration's shared bag.\n */\nfunction defaultToolContext(): ToolContext {\n return { artifacts: {} };\n}\n\nconst EMPTY_USAGE: Usage = Object.freeze({ input: 0, output: 0, total: 0 });\n\n/**\n * Result returned by `ToolContract.invoke()`.\n *\n * **Canonical destructure:** `const { data, usage, report, error }` —\n * matches every other executable (`AgentResult`, `WorkflowResult`,\n * `SupervisorResult`) so parent agents can treat every tool dispatch\n * uniformly.\n *\n * **Shape.** `data` / `error` carry the outcome; `usage` and `report`\n * are always present. For leaf tools, `usage` is zero and `report`\n * is a framework-synthesized {@link BaseReport} (`type: \"tool\"`,\n * `children: []`, real timing) so parents never have to nil-check.\n * For composites wrapped via `asTool()`, `usage` and `report` mirror\n * the inner primitive's — the nested tree lives in `report.children`.\n *\n * @example\n * const result = await myTool.invoke({ city: \"Cairo\" });\n * if (result.error) console.error(result.error.message);\n * else console.log(result.data, result.report.duration);\n */\nexport type ToolInvokeResult<TOutput> = {\n /** Successfully-returned output. Undefined if execution or validation failed. */\n data?: TOutput;\n /** Typed AI error produced by validation or execute(), if any. */\n error?: AIError;\n /** Rolled-up usage (zero for leaf tools, populated for composites). */\n usage: Usage;\n /** Recursive execution report — `report.children` carries nested executables. */\n report: BaseReport;\n};\n\n/**\n * A `ToolConfig` augmented with a safe `invoke()` entry point for the agent runtime.\n *\n * @example\n * const wrapped: ToolContract<{ city: string }, { temp: number }> = tool(contract);\n * const result = await wrapped.invoke({ city: \"Cairo\" });\n */\nexport interface ToolContract<TInput = unknown, TOutput = unknown> extends ToolConfig<\n TInput,\n TOutput\n> {\n /**\n * Agent-runtime entry point. Validates raw input against the tool's schema,\n * calls execute(), catches errors, and reports duration.\n * Never throws — errors surface in the returned `error` field as\n * typed `AIError` subclasses.\n *\n * The optional second argument is a `ToolContext` (Phase 5 /\n * decisions §35) — when supplied, threaded into `execute(input, ctx)`\n * so tools can write system-only side data into `ctx.artifacts`.\n * Standalone callers may omit it; the framework supplies a\n * degraded `{ artifacts: {} }` so single-arg legacy handlers keep\n * working unchanged.\n *\n * @example\n * const result = await myTool.invoke(rawLLMArgs);\n * if (result.error) handleError(result.error);\n */\n invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>>;\n}\n\n/**\n * Wraps a raw `ToolConfig` and adds a safe `invoke()` method for the agent runtime.\n * The returned object preserves all original contract fields unchanged.\n *\n * Error categorization:\n * - Input schema rejects model args → `SchemaValidationError` (issues preserved).\n * - Schema's `validate()` itself throws → `SchemaValidationError` wrapping the cause.\n * - `execute()` throws → `ToolExecutionError` wrapping the cause.\n *\n * @example\n * const weatherTool = tool({\n * name: \"getWeather\",\n * description: \"Fetch current weather for a city\",\n * input: z.object({ city: z.string() }),\n * execute: async ({ city }) => ({ temp: 72 }),\n * });\n *\n * const result = await weatherTool.invoke({ city: \"Cairo\" });\n */\n/**\n * Internal factory for `asTool()` wrappers on composite primitives\n * (agent / workflow / supervisor). Unlike the public `tool()` factory\n * (which synthesizes a leaf `BaseReport` every time), this variant\n * lets the composite's own `ExecuteResult` flow through: the inner\n * primitive's `report` becomes the sole child of the outer tool-call\n * node, and the inner `usage` is surfaced so parents can roll it up.\n *\n * The caller supplies `execute()` returning `{ data, usage, report }`\n * from the composite's own `execute()` method. Validation failures\n * and thrown errors still produce a synthesized failed leaf report —\n * the inner-report propagation is strictly a success-path concern.\n *\n * Not exported from the package barrel — used by `agent.asTool()`,\n * `workflow.asTool()`, `supervisor.asTool()` only.\n */\nexport function compositeAsTool<TInput, TOutput>(contract: {\n name: string;\n description?: string;\n version?: string;\n meta?: ToolConfig[\"meta\"];\n input: StandardSchemaV1<TInput>;\n /** Runs the underlying composite and returns its full envelope. */\n execute: (input: TInput) => Promise<{\n data?: TOutput;\n error?: AIError;\n usage: Usage;\n report: BaseReport;\n }>;\n}): ToolContract<TInput, TOutput> {\n // The underlying `ToolConfig<TInput, TOutput>.execute` is typed as\n // `(input) => Promise<TOutput>`, but composite wrappers return an\n // envelope object instead. Surface a contract-shaped view that\n // extracts `.data` on demand for any code that still treats this\n // like a plain tool.\n const publicExecute = async (input: TInput): Promise<TOutput> => {\n const envelope = await contract.execute(input);\n if (envelope.error) throw envelope.error;\n return envelope.data as TOutput;\n };\n\n return {\n name: contract.name,\n description: contract.description ?? `Composite tool \"${contract.name}\".`,\n meta: contract.meta,\n input: contract.input,\n execute: publicExecute,\n\n async invoke(rawInput: unknown, _ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n // Composite tools (asTool-wrapped agent/workflow/supervisor) do\n // NOT relay the ctx into their inner execution — composites\n // have their own state/scope; an inner supervisor gets a fresh\n // artifacts bag. The parameter is accepted for signature parity\n // with `tool()` so callers can use both interchangeably.\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n\n const failLeaf = (error: AIError): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n return {\n error,\n usage: EMPTY_USAGE,\n report: {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n },\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n try {\n const schema = contract.input as StandardSchemaV1<TInput>;\n validationResult = await schema[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n );\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n return failLeaf(\n new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n );\n }\n\n try {\n const composite = await contract.execute(validationResult.value);\n // Surface the inner primitive's full envelope. The outer\n // ToolInvokeResult carries the composite's usage and report\n // verbatim; the agent runtime nests the report as a child of\n // the tool-dispatch node it records.\n return {\n data: composite.data,\n error: composite.error,\n usage: composite.usage,\n report: composite.report,\n };\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n );\n }\n },\n };\n}\n\nexport function tool<TInput, TOutput>(\n contract: ToolConfig<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n return {\n ...contract,\n\n async invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n const handlerCtx = ctx ?? defaultToolContext();\n\n const finish = (partial: { data?: TOutput; error?: AIError }): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n const status: BaseReport[\"status\"] = partial.error ? \"failed\" : \"completed\";\n const report: BaseReport = {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status,\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n };\n\n return {\n ...partial,\n usage: EMPTY_USAGE,\n report,\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n try {\n const schema = contract.input as StandardSchemaV1<TInput>;\n validationResult = await schema[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n });\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n\n return finish({\n error: new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n });\n }\n\n try {\n const output = await contract.execute(validationResult.value, handlerCtx);\n return finish({ data: output });\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n });\n }\n },\n };\n}\n","import type {\n SupervisorAsToolOptions,\n SupervisorContract,\n} from \"../contracts/supervisor/supervisor.contract\";\nimport { SupervisorFailedError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"../tool/tool\";\n\n/**\n * Wrap a `SupervisorContract` as a `ToolContract` so an outer agent\n * can invoke it from its tool-call loop. Mirrors\n * `workflow.asTool()` / `agent.asTool()` — same composition pattern,\n * same error-normalization behavior.\n *\n * Behavior:\n * - The tool's `name` mirrors the supervisor's `name` unless the\n * caller overrides via `options.name`. Supervisors without a\n * meaningful name throw `SupervisorFailedError` — an outer agent\n * can't route to an anonymous tool.\n * - Tool `input` is the supplied schema; the validated value is\n * coerced to a string (via `String()` for non-string values, or\n * `JSON.stringify()` for objects) before being forwarded to\n * `supervisor.execute(input)`. Consumers whose inputs need\n * richer shaping should pre-format the string themselves.\n * - On `result.error`, the supervisor error is thrown so the tool\n * wrapper catches it and produces a `ToolExecutionError` with\n * `cause` set to the original typed supervisor error — the outer\n * agent sees one uniform error class regardless of which\n * primitive failed.\n *\n * **Usage caveat** (mirrors workflow-as-tool): nested usage is not\n * rolled into the outer agent's `result.usage` today — the\n * supervisor's tokens stay on the supervisor result. Sum manually\n * if you need a combined cost number until nested-usage\n * standardization lands.\n *\n * @example\n * const support = ai.supervisor({ ... });\n * const supportTool = support.asTool({\n * name: \"handle_support_ticket\",\n * description: \"Process a customer support ticket end-to-end.\",\n * inputSchema: z.object({ ticket: z.string() }),\n * });\n * const concierge = ai.agent({ model, tools: [supportTool] });\n */\nexport function asTool<TOutput, TToolInput>(\n supervisorInstance: SupervisorContract<TOutput>,\n options: SupervisorAsToolOptions<TToolInput>,\n): ToolContract<TToolInput, TOutput> {\n if (!supervisorInstance.name || typeof supervisorInstance.name !== \"string\") {\n throw new SupervisorFailedError(\n \"supervisor.asTool(): supervisor must have a `name` to be wrapped as a tool\",\n );\n }\n\n return compositeAsTool<TToolInput, TOutput>({\n name: options.name ?? supervisorInstance.name,\n description: options.description ?? `Invoke supervisor \"${supervisorInstance.name}\" as a tool.`,\n input: options.inputSchema,\n execute: async (input) => {\n const coerced = coerceInput(input);\n const result = await supervisorInstance.execute(coerced);\n\n if (result.error) {\n // Surface the typed supervisor error — the outer ToolContract\n // wraps it as a ToolExecutionError with `cause` preserved.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Coerce a tool-input value into the `string` shape supervisor\n * `execute()` expects. Strings pass through; everything else gets\n * JSON-stringified so supervisors invoked via tool wrappers receive a\n * predictable textual input regardless of how the outer agent shaped\n * its call.\n */\nfunction coerceInput(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value === undefined || value === null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","import type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type {\n SupervisorEventHandler,\n SupervisorEventHandlers,\n} from \"../contracts/supervisor/supervisor-config.type\";\n\ntype AnyHandler = SupervisorEventHandler<keyof SupervisorEventMap>;\n\n/**\n * Three-tier supervisor event emitter — factory (definition) → instance\n * → per-execution. Mirrors `WorkflowEmitter` structurally; the only\n * difference is the event map. All matching handlers fire in layer\n * order. Handler errors are swallowed so a listener bug can never\n * derail the run.\n *\n * @example\n * const emitter = new SupervisorEmitter(definition.on);\n * const unsubscribe = emitter.on(\"supervisor.completed\", (payload) => ...);\n * emitter.emit(\"supervisor.starting\", { runId, rootRunId, supervisorName, input }, perCallHandlers);\n */\nexport class SupervisorEmitter {\n private readonly factoryHandlers?: SupervisorEventHandlers;\n private readonly instanceHandlers = new Map<\n keyof SupervisorEventMap,\n Set<AnyHandler>\n >();\n\n public constructor(factoryHandlers?: SupervisorEventHandlers) {\n this.factoryHandlers = factoryHandlers;\n }\n\n public on<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): () => void {\n let bucket = this.instanceHandlers.get(event);\n\n if (!bucket) {\n bucket = new Set();\n this.instanceHandlers.set(event, bucket);\n }\n\n bucket.add(handler as AnyHandler);\n\n return () => this.off(event, handler);\n }\n\n public off<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): void {\n this.instanceHandlers.get(event)?.delete(handler as AnyHandler);\n }\n\n public emit<K extends keyof SupervisorEventMap>(\n event: K,\n payload: SupervisorEventMap[K],\n executionHandlers?: SupervisorEventHandlers,\n ): void {\n invoke(this.factoryHandlers?.[event], payload);\n\n const bucket = this.instanceHandlers.get(event);\n\n if (bucket) {\n for (const handler of bucket) {\n invoke(handler, payload);\n }\n }\n\n invoke(executionHandlers?.[event], payload);\n }\n}\n\nfunction invoke<K extends keyof SupervisorEventMap>(\n handler: ((payload: SupervisorEventMap[K]) => void) | undefined,\n payload: SupervisorEventMap[K],\n): void {\n if (typeof handler !== \"function\") {\n return;\n }\n\n try {\n handler(payload);\n } catch {\n // Listener bugs must not derail the supervisor.\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { EndSentinel } from \"../contracts/end.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { DispatchContext } from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n DispatchRawResult,\n IntentCallback,\n IntentEntry,\n IntentRunEntry,\n SupervisorIntentValue,\n} from \"../contracts/supervisor/intent-entry.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { SupervisorFailedError } from \"../errors\";\n\n/**\n * Normalized internal representation of one entry in a supervisor's\n * `intents` map — resolved at factory time from one of the accepted\n * value forms (bare agent / workflow / callback / object entry).\n *\n * Carrying the explicit `type` discriminator keeps downstream code\n * (execution, signature, router-prompt) from having to re-detect\n * shape on every dispatch. The discriminated union below replaces\n * the flat-shape used in Phase 3 so callbacks can carry their own\n * function reference + dispatch-context-shaped resolvers.\n *\n * Discriminator renamed `kind` → `type` (Q12) for codebase-wide\n * consistency — every other discriminated result/report shape uses\n * `type`.\n */\nexport type ResolvedIntentEntry =\n | ResolvedAgentEntry\n | ResolvedWorkflowEntry\n | ResolvedCallbackEntry;\n\n/**\n * Successor directive function type — the resolver-time projection of\n * `IntentEntry.next` / `IntentRunEntry.next`. Single source of truth\n * across the three resolved variants.\n */\nexport type IntentNext = (ctx: DispatchContext) => string | string[] | EndSentinel | undefined;\n\n/**\n * Resolver-time projection of `IntentEntry.history` /\n * `RouterEntry.history` / `AckEntry.history`. Custom slicer that\n * REPLACES the default `historyWindow.<role>` slice.\n */\nexport type EntryHistorySlicer = (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n\nexport type ResolvedAgentEntry = {\n intent: string;\n type: \"agent\";\n unit: AgentContract<unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n /**\n * Per-dispatch placeholder values for the agent's systemPrompt\n * template. Forwarded as `agent.execute(input, { placeholders })`.\n * Phase 3.4 (Stage 4b) — replaces the dropped `composeAgentInput`\n * mechanism for threading state into agents.\n */\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this intent's slice of supervisor state. Agent\n * output is strip-merged against it; only validated keys appear on\n * `IterationSnapshot.result[intent].output` AND merge into\n * supervisor `state`.\n */\n output?: StandardSchemaV1<unknown>;\n /**\n * Successor directive (Stage 4d / Q24). When present, runs after\n * this branch's slice merges into state to choose the next dispatch\n * (or terminate) without invoking the router.\n */\n next?: IntentNext;\n /**\n * Custom history slicer — replaces the default\n * `historyWindow.agents` slice when supplied. See `IntentEntry.history`.\n */\n history?: EntryHistorySlicer;\n /**\n * Phase 5 / decisions §34. `\"stream\"` runs the agent without\n * structured-output coercion and writes the assembled prose into\n * `state[streamTo]`; `\"structured\"` is the default. Resolved at\n * factory time — `undefined` here is treated as `\"structured\"`.\n */\n mode?: \"structured\" | \"stream\";\n /** State key the assembled stream-mode prose writes into. Set iff `mode === \"stream\"`. */\n streamTo?: string;\n};\n\nexport type ResolvedWorkflowEntry = {\n intent: string;\n type: \"workflow\";\n unit: WorkflowInstance<unknown, unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n history?: EntryHistorySlicer;\n};\n\nexport type ResolvedCallbackEntry = {\n intent: string;\n type: \"callback\";\n /**\n * The callback that actually runs at dispatch time. Always present\n * regardless of whether the user passed bare-function shorthand or\n * the `{ run, ... }` entry form.\n */\n callback: IntentCallback;\n /**\n * Description is required only when the supervisor uses a router.\n * Callback intents under a router are validated separately\n * (see {@link assertRouterDescriptions}); under deterministic\n * `route` mode this field is `undefined`.\n */\n description?: string;\n /**\n * Per-intent input resolver. Receives the upcoming\n * `DispatchContext` and returns the value forwarded as\n * `ctx.input` to the callback.\n */\n input?: (ctx: DispatchContext) => unknown;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this callback's slice of state. Without it, the\n * full return value shallow-merges; with it, return is strip-merged\n * to declared keys before merging.\n */\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n};\n\n/**\n * Validate and normalize the `intents` map into resolved entries.\n * Runs at factory time — throws `SupervisorFailedError` on the first\n * malformed entry so author-time bugs surface immediately rather\n * than mid-run.\n *\n * Validation rules:\n * - Every value must be an agent, a workflow, a callback function,\n * or an object entry with `agent` / `workflow` / `run`.\n * - Object entries with more than one of `{ agent, workflow, run }`\n * throw with code `SUPERVISOR_INTENT_MIXED_DISPATCH`.\n * - Agent / workflow / agent-shaped entries must resolve to a\n * non-empty description from the underlying unit or the entry's\n * `description` override. Bare callback shorthand has no\n * description source — that's enforced separately by\n * {@link assertRouterDescriptions} when a router is configured.\n */\nexport function resolveIntentEntries(\n rawIntents: Record<string, SupervisorIntentValue>,\n supervisorName: string,\n): Map<string, ResolvedIntentEntry> {\n const entries = Object.entries(rawIntents);\n\n if (entries.length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): \\`intents\\` must contain at least one entry`,\n { context: { authoring: true } },\n );\n }\n\n const resolved = new Map<string, ResolvedIntentEntry>();\n\n for (const [intent, value] of entries) {\n if (!intent || typeof intent !== \"string\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): every \\`intents\\` key must be a non-empty string`,\n { context: { authoring: true } },\n );\n }\n\n resolved.set(intent, resolveOne(intent, value, supervisorName));\n }\n\n return resolved;\n}\n\n/**\n * Construction-time guard: when the supervisor is configured with a\n * `router`, every intent must resolve to a non-empty description so\n * the router LLM has a signal for picking it. Bare callback\n * shorthand and `IntentRunEntry` without `description` fail this\n * check; agents and workflows whose underlying primitive lacks a\n * description fail too — same uniform error message.\n *\n * Deterministic `route` callers skip this check entirely.\n */\nexport function assertRouterDescriptions(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): void {\n if (!config.router) {\n return;\n }\n\n for (const [intent, entry] of entries) {\n const description = entry.type === \"callback\" ? entry.description : entry.description;\n\n if (description && description.trim().length > 0) {\n continue;\n }\n\n const fix =\n entry.type === \"callback\"\n ? \"upgrade the bare callback to `{ run, description }`\"\n : \"set `description` on the agent/workflow or via the `IntentEntry` `description` override\";\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): intents[\"${intent}\"] needs a description because a \\`router\\` is configured — ${fix}`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_DESCRIPTION_REQUIRED\",\n );\n }\n}\n\nfunction resolveOne(\n intent: string,\n value: SupervisorIntentValue,\n supervisorName: string,\n): ResolvedIntentEntry {\n // (c) Bare callback shorthand — typeof function. Highest priority\n // so a user passing `(ctx) => …` never accidentally matches the\n // object-shape branches below.\n if (typeof value === \"function\") {\n return {\n intent,\n type: \"callback\",\n callback: value as IntentCallback,\n description: undefined,\n };\n }\n\n if (!value || typeof value !== \"object\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] is not an agent, workflow, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n // Detect mixed-dispatch entries up front. Two of `{ agent, workflow,\n // run }` together is dev confusion, not a feature.\n assertSingleDispatchField(intent, value, supervisorName);\n\n // (d.run) Run-entry — `{ run, description?, input?, output? }`.\n if (\"run\" in value && typeof (value as IntentRunEntry).run === \"function\") {\n const entry = value as IntentRunEntry;\n\n return {\n intent,\n type: \"callback\",\n callback: entry.run,\n description: entry.description,\n input: entry.input,\n placeholders: entry.placeholders,\n output: entry.output,\n next: entry.next,\n };\n }\n\n // (d.agent / a / b) Agent-entry or bare unit. The existing\n // `IntentEntry` shape uses `agent: AgentContract | WorkflowInstance`\n // for both agent and workflow object entries; the resolver still\n // dispatches the underlying unit kind correctly.\n const entryForm = asAgentEntryForm(value);\n const unit = entryForm\n ? entryForm.agent\n : (value as AgentContract<unknown> | WorkflowInstance<unknown, unknown>);\n\n if (!isDispatchableUnit(unit)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] must be an AgentContract, WorkflowInstance, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n const detectedType = detectType(unit);\n const description = resolveAgentLikeDescription(intent, entryForm, unit, supervisorName);\n\n if (detectedType === \"workflow\") {\n if (entryForm?.mode === \"stream\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` on a workflow entry — stream mode is agent-only in v1. Wrap the workflow in an agent or remove the \\`mode\\` field.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_ON_WORKFLOW\",\n );\n }\n\n return {\n intent,\n type: \"workflow\",\n unit: unit as WorkflowInstance<unknown, unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n };\n }\n\n assertStreamModeShape(intent, entryForm, supervisorName);\n\n return {\n intent,\n type: \"agent\",\n unit: unit as AgentContract<unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n mode: entryForm?.mode,\n streamTo: entryForm?.streamTo,\n };\n}\n\n/**\n * Phase 5 / decisions §34 — enforce the two stream-mode invariants at\n * construction time:\n *\n * 1. `mode: \"stream\"` and per-intent `output` are mutually exclusive.\n * Stream agents declare their state contribution via `streamTo`,\n * not via a schema; allowing both would silently pick one and\n * surprise the author.\n * 2. `streamTo` is required when `mode === \"stream\"`. A stream agent\n * that doesn't write somewhere is a black box — fail loud at the\n * factory rather than at run-time when state validation surfaces a\n * missing key.\n */\nfunction assertStreamModeShape(\n intent: string,\n entryForm: IntentEntry | undefined,\n supervisorName: string,\n): void {\n if (!entryForm || entryForm.mode !== \"stream\") {\n return;\n }\n\n if (entryForm.output) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets both \\`mode: \"stream\"\\` and \\`output\\` — stream mode declares its slice via \\`streamTo\\`, not a schema. Drop one.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_AND_OUTPUT\",\n );\n }\n\n if (typeof entryForm.streamTo !== \"string\" || entryForm.streamTo.trim().length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` without a non-empty \\`streamTo\\` — a stream agent must name the state key its assembled prose writes into.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_TO_REQUIRED\",\n );\n }\n}\n\n/**\n * Reject entries that mix dispatch fields. `{ agent, run }` is a\n * common copy-paste bug; we surface it at construction with a clear\n * message rather than silently picking one based on resolution\n * order.\n */\nfunction assertSingleDispatchField(intent: string, value: object, supervisorName: string): void {\n const dispatchKeys = ([\"run\", \"agent\", \"workflow\"] as const).filter((key) => key in value);\n\n if (dispatchKeys.length > 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] has multiple dispatch fields (${dispatchKeys\n .map((key) => `\\`${key}\\``)\n .join(\n \", \",\n )}) — pick one. Two dispatch fields on the same entry is dev confusion, not a feature.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_MIXED_DISPATCH\",\n );\n }\n}\n\n/**\n * Coerce a `SupervisorIntentValue` into the agent-flavored\n * `IntentEntry` form when the caller passed the object form. Returns\n * `undefined` for bare shorthand. The shape check keys on the\n * presence of an `agent` property because both `AgentContract` and\n * `WorkflowInstance` have their own identifying fields\n * (`isAnonymous` for agents, `signature` for workflows) but neither\n * carries a top-level `agent`.\n */\nfunction asAgentEntryForm(value: object): IntentEntry | undefined {\n if (!(\"agent\" in value)) {\n return undefined;\n }\n\n const candidate = (value as { agent: unknown }).agent;\n\n if (!candidate || typeof candidate !== \"object\") {\n return undefined;\n }\n\n return value as IntentEntry;\n}\n\nfunction isDispatchableUnit(\n value: unknown,\n): value is AgentContract<unknown> | WorkflowInstance<unknown, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as { name?: unknown; execute?: unknown };\n\n return typeof candidate.name === \"string\" && typeof candidate.execute === \"function\";\n}\n\nfunction detectType(\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n): \"agent\" | \"workflow\" {\n // Workflows expose a structural `signature` field; agents don't.\n if (typeof (unit as WorkflowInstance<unknown, unknown>).signature === \"string\") {\n return \"workflow\";\n }\n\n return \"agent\";\n}\n\nfunction resolveAgentLikeDescription(\n intent: string,\n entryForm: IntentEntry | undefined,\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n supervisorName: string,\n): string {\n const entryOverride = entryForm?.description;\n\n if (entryOverride && entryOverride.trim().length > 0) {\n return entryOverride;\n }\n\n const unitDescription = (unit as { description?: unknown }).description;\n\n if (typeof unitDescription === \"string\" && unitDescription.trim().length > 0) {\n return unitDescription;\n }\n\n // Empty string sentinel — caller (assertRouterDescriptions) decides\n // whether a missing description is fatal. Under deterministic\n // `route` mode it isn't.\n return \"\";\n}\n\n/**\n * Type guard helper for downstream modules. Narrows a raw\n * `AgentResult | WorkflowResult` based on the resolved entry's kind,\n * so transformers and emitters can pull the right fields without\n * re-checking shape.\n */\nexport function isAgentResult(raw: DispatchRawResult): raw is AgentResult<unknown> {\n return raw.type === \"agent\";\n}\n\nexport function isWorkflowResult(raw: DispatchRawResult): raw is WorkflowResult<unknown> {\n return raw.type === \"workflow\";\n}\n","/**\n * Framework-global termination sentinel. Emitted by any primitive\n * whose control flow is routed through JSON-serializable strings —\n * supervisor (router agent's `next`, deterministic `route` callback),\n * future planner (plan steps), future orchestrator (session\n * directive), any future primitive that needs to say \"stop\" across a\n * wire that can't carry `null`.\n *\n * **Why one shared literal.** Consumers learn one word. Cross-\n * primitive pipes — a planner feeding a supervisor, a supervisor\n * nested as a tool inside an orchestrator — can pass the sentinel\n * through without translation.\n *\n * **Why this specific string.** Brand-prefixed (`__warlock:`) so it\n * can't collide with a realistic user-chosen intent / step / route\n * key (`\"end\"`, `\"done\"`, `\"stop\"` are all valid user keys).\n * Underscore-surrounded so it stands out in logs and snapshots.\n * JSON-safe so a router agent emits it verbatim.\n *\n * **Not used by every primitive.** Workflow's `nextStep` returns\n * `null` to end — a callback-level mechanism that predates this\n * sentinel. Workflows keep `null`; the sentinel is for primitives\n * whose \"end\" must survive a JSON boundary.\n *\n * @example\n * import { END } from \"@warlock.js/ai\";\n *\n * // Supervisor route callback\n * ai.supervisor({\n * intents: { writer, critic },\n * route: (ctx) => (ctx.iteration >= 5 ? END : \"writer\"),\n * });\n *\n * // Router agent output schema\n * const router = ai.agent({\n * model,\n * output: z.object({\n * next: z.union([z.string(), z.array(z.string()), z.literal(END)]),\n * }),\n * });\n */\nexport const END = \"__warlock:end__\" as const;\n\n/**\n * Value type of `END`. Exposed so consumers building Zod / Standard\n * Schema output schemas can write `z.literal(END)` without\n * hard-coding the string, and so generic helpers that accept \"the\n * end sentinel\" can type-narrow correctly.\n */\nexport type EndSentinel = typeof END;\n","import { SupervisorCancelledError } from \"../errors\";\n\n/**\n * Build a `SupervisorCancelledError` from an `AbortSignal`. Extracts a\n * human-readable reason from `signal.reason` whether it was a string,\n * an `Error`, or some other value. Used at between-iteration boundaries\n * and on any mid-iteration cancellation path.\n */\nexport function createCancelledError(\n signal: AbortSignal | undefined,\n): SupervisorCancelledError {\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 SupervisorCancelledError(\n `supervisor cancelled${reasonText ? `: ${reasonText}` : \"\"}`,\n { cancelledAt: new Date().toISOString(), reason: reasonText },\n );\n}\n","import { END } from \"../contracts/end.type\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type { ResolvedIntentEntry } from \"./entries\";\n\n/**\n * Build the per-turn user message the supervisor feeds to the router\n * agent. Carries everything the LLM needs to make a routing decision:\n *\n * - Available intents with descriptions (so the router knows what\n * to pick from).\n * - The reserved `END` sentinel value it can emit to terminate.\n * - Iteration counter + ceiling so the router can pace itself.\n * - Compact history of prior iterations (intent + short output clip).\n * - The supervisor's original input so the router stays anchored.\n *\n * Note the router's own `systemPrompt` is kept persistent across\n * turns — this function produces only the per-turn USER message.\n */\nexport function buildRouterContextMessage(params: {\n entries: Map<string, ResolvedIntentEntry>;\n iteration: number;\n maxIterations: number;\n iterations: IterationSnapshot[];\n input: SupervisorInput;\n /**\n * Per-execute state at the START of this iteration (post-merge of\n * the previous iteration). Rendered as a JSON snippet so the\n * router can pick the next intent based on what's already filled\n * in (Q14).\n */\n state?: Record<string, unknown>;\n /**\n * Reviewer feedback string from the previous iteration's evaluate\n * verdict. Rendered as its own section so the router weighs it\n * alongside the intent list (Q18).\n */\n feedback?: string;\n /**\n * Supervisor-level system prompt text, when configured. Surfaced at\n * the TOP of the router's per-turn user message so the router reads\n * team/domain context before the routing mechanics block. Skipped\n * when the supervisor didn't configure `systemPrompt`.\n */\n supervisorPrompt?: string;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`.\n * Surfaced as its own labeled section near the top of the router's\n * user message so routing decisions are objective-aware. Skipped\n * when no goal was configured.\n */\n goal?: string;\n}): string {\n const {\n entries,\n iteration,\n maxIterations,\n iterations,\n input,\n state,\n feedback,\n supervisorPrompt,\n goal,\n } = params;\n\n const intentLines = [...entries.values()].map(\n entry => `- ${entry.intent}: ${entry.description}`,\n );\n\n const historyLines =\n iterations.length === 0\n ? [\"(none yet)\"]\n : iterations.map(snapshot => formatHistoryLine(snapshot));\n\n const sections: string[] = [];\n\n if (supervisorPrompt) {\n sections.push(supervisorPrompt.trim(), \"\");\n }\n\n if (goal) {\n sections.push(\"Goal:\", goal.trim(), \"\");\n }\n\n sections.push(\n \"Available intents:\",\n ...intentLines,\n \"\",\n \"Reserved values:\",\n `- ${END} = terminate the run`,\n \"\",\n `Iteration: ${iteration + 1} / ${maxIterations}`,\n \"\",\n \"History:\",\n ...historyLines,\n );\n\n if (state && Object.keys(state).length > 0) {\n sections.push(\"\", \"Current state:\", safeStringify(state));\n }\n\n if (feedback) {\n sections.push(\"\", `Reviewer feedback from last iteration: ${feedback}`);\n }\n\n const renderedInput =\n typeof input === \"string\" ? input : safeStringify(input);\n\n sections.push(\"\", `Original input: ${renderedInput}`);\n\n return sections.join(\"\\n\");\n}\n\nfunction formatHistoryLine(snapshot: IterationSnapshot): string {\n const branches = Object.entries(snapshot.result).map(\n ([intent, branch]) => `${intent} → ${clip(branch.output)}`,\n );\n\n return `[${snapshot.iteration}] ${branches.join(\" | \")}`;\n}\n\nfunction clip(value: unknown, maxLength = 160): string {\n if (value === undefined || value === null) {\n return String(value);\n }\n\n const raw = typeof value === \"string\" ? value : safeStringify(value);\n\n if (raw.length <= maxLength) {\n return raw;\n }\n\n return `${raw.slice(0, maxLength - 1)}…`;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return `[unserializable: ${typeof value}]`;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END, type EndSentinel } from \"../contracts/end.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { Next } from \"../contracts/supervisor/next.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { RouterEntry } from \"../contracts/supervisor/router-entry.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport { AIError, SupervisorFailedError, SupervisorRoutingError } from \"../errors\";\nimport type { ResolvedIntentEntry } from \"./entries\";\nimport { buildRouterContextMessage } from \"./router-prompt\";\n\n/**\n * Outcome of one dispatch decision — what the iteration loop needs to\n * act on. `kind: \"end\"` signals termination; `kind: \"dispatch\"` carries\n * the resolved intents (always an array; single-agent dispatch has\n * length 1). `source` records which path made the call so the\n * iteration snapshot can surface it to debuggers.\n */\nexport type DispatchDecision =\n | {\n kind: \"end\";\n source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n raw: Next;\n reasoning?: string;\n durationMs: number;\n usage?: { input: number; output: number; total: number };\n /** Full router-agent report when this decision came from a router. */\n routerReport?: BaseReport;\n }\n | {\n kind: \"dispatch\";\n intents: string[];\n source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n raw: Next;\n reasoning?: string;\n durationMs: number;\n usage?: { input: number; output: number; total: number };\n /** Full router-agent report when this decision came from a router. */\n routerReport?: BaseReport;\n };\n\nexport type DecideParams = {\n config: SupervisorConfig<unknown>;\n entries: Map<string, ResolvedIntentEntry>;\n iteration: number;\n maxIterations: number;\n iterations: IterationSnapshot[];\n input: SupervisorInput;\n /**\n * Per-execute state accumulator at the start of this iteration.\n * Threaded into `RouteContext` for the route callback and\n * rendered into the router prompt so routing decisions can be\n * state-aware (Q14).\n */\n state: Record<string, unknown>;\n /**\n * Frozen request-scoped bag from the `execute({ context })` call —\n * surfaced on `RouteContext.context` for both `route` callbacks\n * and `RouterEntry.placeholders` / `RouterEntry.input` resolvers.\n */\n context: Readonly<Record<string, unknown>>;\n /**\n * Frozen prior-conversation history from `execute({ history })` —\n * surfaced on `RouteContext.history` and forwarded to the router\n * agent as `agent.execute(input, { history })` so router decisions\n * are conversation-aware.\n */\n history: ReadonlyArray<Message>;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`\n * (materialized to plain text at supervisor construction). Surfaced\n * on `RouteContext.goal` for `route` / `RouterEntry` resolvers, and\n * injected into the router agent's per-turn user message via\n * `buildRouterContextMessage`. `undefined` when no goal was set.\n */\n goal: string | undefined;\n evaluateFeedback?: RouteContext[\"evaluateFeedback\"];\n /**\n * Forensic record of the iter-0 classifier (Phase 7). Threaded into\n * `RouteContext.classifier` so route callbacks and router-agent\n * input composers can read the classification trail without\n * re-parsing state.\n */\n classifier?: RouteContext[\"classifier\"];\n signal?: AbortSignal;\n /**\n * Override for the very first iteration — when `initialAgent` is\n * set, the first turn skips `route`/`router` and dispatches the\n * named intent directly. `runIteration` passes `true` only on turn\n * 0 when the config has `initialAgent`.\n */\n useInitialAgent?: boolean;\n};\n\n/**\n * Unified dispatch decision entry — calls either the `route` callback\n * or the `router` agent based on the supervisor's configured mode and\n * normalizes the result into a `DispatchDecision`. Runtime validates\n * every routing value against the configured agent keys; unknown keys\n * surface as `SupervisorRoutingError`.\n */\nexport async function decide(params: DecideParams): Promise<DispatchDecision> {\n if (params.useInitialAgent && params.config.initialAgent) {\n const intent = params.config.initialAgent;\n validateKey(intent, params.entries);\n\n return {\n kind: \"dispatch\",\n intents: [intent],\n source: \"initialAgent\",\n raw: intent,\n durationMs: 0,\n };\n }\n\n if (params.config.route) {\n return decideViaCallback(params);\n }\n\n if (params.config.router) {\n return decideViaRouter(params);\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${params.config.name}\"): neither \\`route\\` nor \\`router\\` is configured — factory validation should have prevented this`,\n { context: { authoring: true } },\n );\n}\n\nasync function decideViaCallback(params: DecideParams): Promise<DispatchDecision> {\n const started = performance.now();\n const ctx: RouteContext = {\n iteration: params.iteration,\n input: params.input,\n state: params.state,\n iterations: params.iterations,\n feedback:\n typeof params.evaluateFeedback?.feedback === \"string\"\n ? params.evaluateFeedback.feedback\n : undefined,\n evaluateFeedback: params.evaluateFeedback,\n context: params.context,\n history: params.history,\n goal: params.goal,\n classifier: params.classifier,\n };\n\n let raw: Next;\n\n try {\n raw = await params.config.route!(ctx);\n } catch (thrown) {\n throw wrapRouteError(params.config.name, thrown);\n }\n\n const durationMs = performance.now() - started;\n\n return normalize(raw, params.entries, \"route\", durationMs);\n}\n\nasync function decideViaRouter(params: DecideParams): Promise<DispatchDecision> {\n const { agent, placeholders, inputOverride, historySlicer } = resolveRouterEntry(\n params.config.router!,\n );\n const started = performance.now();\n\n const routeCtx: RouteContext = {\n iteration: params.iteration,\n input: params.input,\n state: params.state,\n iterations: params.iterations,\n feedback:\n typeof params.evaluateFeedback?.feedback === \"string\"\n ? params.evaluateFeedback.feedback\n : undefined,\n evaluateFeedback: params.evaluateFeedback,\n context: params.context,\n history: params.history,\n goal: params.goal,\n };\n\n const userMessage =\n inputOverride?.(routeCtx) ??\n buildRouterContextMessage({\n entries: params.entries,\n iteration: params.iteration,\n maxIterations: params.maxIterations,\n iterations: params.iterations,\n input: params.input,\n state: params.state,\n feedback: routeCtx.feedback,\n supervisorPrompt: resolveSupervisorPromptText(params.config),\n goal: params.goal,\n });\n\n const resolvedPlaceholders = placeholders?.(routeCtx);\n\n // Inject the canonical router output schema so the supervisor gets\n // a predictable `{ next, reasoning? }` shape regardless of what the\n // user scripted on the router agent. Lets the router stay a plain\n // agent — no supervisor-specific config needed at construction.\n const routerHistory = resolveRouterHistory(\n historySlicer,\n routeCtx,\n params.history,\n params.config.historyWindow?.router,\n );\n\n const routerResult = await agent.execute(userMessage, {\n signal: params.signal,\n output: ROUTER_OUTPUT_SCHEMA as unknown as StandardSchemaV1<{\n next: Next;\n reasoning?: string;\n }>,\n ...(resolvedPlaceholders ? { placeholders: resolvedPlaceholders } : {}),\n ...(routerHistory.length > 0 ? { history: routerHistory } : {}),\n });\n\n const durationMs = performance.now() - started;\n\n if (routerResult.error) {\n throw routerResult.error instanceof AIError\n ? routerResult.error\n : new SupervisorFailedError(`router agent failed`, {\n cause: routerResult.error,\n });\n }\n\n const data = routerResult.data;\n\n if (!data || typeof data !== \"object\") {\n throw new SupervisorRoutingError(\n `router agent returned no structured \\`next\\` — did its output schema include { next, reasoning? }?`,\n { returned: data, availableKeys: [...params.entries.keys()] },\n );\n }\n\n const rawNext = (data as { next?: unknown }).next;\n const reasoning = (data as { reasoning?: unknown }).reasoning;\n\n if (rawNext === undefined) {\n throw new SupervisorRoutingError(`router agent output missing \\`next\\` field`, {\n returned: data,\n availableKeys: [...params.entries.keys()],\n });\n }\n\n const decision = normalize(rawNext as Next, params.entries, \"router\", durationMs);\n\n return {\n ...decision,\n reasoning: typeof reasoning === \"string\" ? reasoning : undefined,\n usage: routerResult.usage,\n routerReport: routerResult.report,\n };\n}\n\n/**\n * Normalize the `router` config field — accepts either a bare\n * `AgentContract` (shorthand) or a full `RouterEntry` — into a\n * uniform `{ agent, placeholders?, inputOverride? }` triple. Centralized\n * so the dispatch path doesn't branch on shape.\n */\nfunction resolveRouterEntry(router: AgentContract<unknown> | RouterEntry): {\n agent: AgentContract<unknown>;\n placeholders?: RouterEntry[\"placeholders\"];\n inputOverride?: RouterEntry[\"input\"];\n historySlicer?: RouterEntry[\"history\"];\n} {\n if (typeof (router as { execute?: unknown }).execute === \"function\") {\n return { agent: router as AgentContract<unknown> };\n }\n\n const entry = router as RouterEntry;\n\n return {\n agent: entry.agent,\n placeholders: entry.placeholders,\n inputOverride: entry.input,\n historySlicer: entry.history,\n };\n}\n\n/**\n * Resolve the supervisor's own `systemPrompt` (string or contract)\n * into plain text. Returns `undefined` when the supervisor didn't\n * configure one. The resolved text is surfaced in the per-turn\n * router user message so the router sees team/domain context without\n * disturbing the router agent's own factory-level system prompt —\n * functionally equivalent to prepending, without requiring an API\n * expansion on `AgentContract` to read the router's system prompt.\n */\nfunction resolveSupervisorPromptText(config: SupervisorConfig<unknown>): string | undefined {\n if (!config.systemPrompt) {\n return undefined;\n }\n\n return typeof config.systemPrompt === \"string\"\n ? config.systemPrompt\n : config.systemPrompt.resolve();\n}\n\n/**\n * Convert the raw routing value (callback return OR router agent\n * `next` field) into a canonical `DispatchDecision`, validating every\n * named intent against the supervisor's `intents` map.\n */\nfunction normalize(\n raw: Next,\n entries: Map<string, ResolvedIntentEntry>,\n source: \"route\" | \"router\",\n durationMs: number,\n): DispatchDecision {\n if (isEnd(raw)) {\n return { kind: \"end\", source, raw, durationMs };\n }\n\n if (typeof raw === \"string\") {\n validateKey(raw, entries);\n\n return {\n kind: \"dispatch\",\n intents: [raw],\n source,\n raw,\n durationMs,\n };\n }\n\n if (Array.isArray(raw)) {\n if (raw.length === 0) {\n throw new SupervisorRoutingError(\n `router returned an empty array — must be a non-empty list of agent intents`,\n { returned: raw, availableKeys: [...entries.keys()] },\n );\n }\n\n for (const intent of raw) {\n if (typeof intent !== \"string\") {\n throw new SupervisorRoutingError(`router returned a non-string inside its fan-out array`, {\n returned: raw,\n availableKeys: [...entries.keys()],\n });\n }\n\n validateKey(intent, entries);\n }\n\n return {\n kind: \"dispatch\",\n intents: raw,\n source,\n raw,\n durationMs,\n };\n }\n\n throw new SupervisorRoutingError(\n `router returned an unsupported value — expected a string, string[], or END`,\n { returned: raw, availableKeys: [...entries.keys()] },\n );\n}\n\nfunction validateKey(intent: string, entries: Map<string, ResolvedIntentEntry>): void {\n if (!entries.has(intent)) {\n throw new SupervisorRoutingError(`router returned unknown agent key \"${intent}\"`, {\n returned: intent,\n availableKeys: [...entries.keys()],\n });\n }\n}\n\nfunction isEnd(value: unknown): value is EndSentinel {\n return value === END;\n}\n\n/**\n * Resolve the history slice forwarded to the router agent. Mirrors\n * `SupervisorExecution.resolveHistoryFor(\"router\", ...)` — duplicated\n * here so the standalone `decide()` function stays callable without\n * threading the execution instance through. Precedence is identical:\n * entry slicer > `historyWindow.router` > full history.\n */\nfunction resolveRouterHistory(\n slicer: RouterEntry[\"history\"] | undefined,\n routeCtx: RouteContext,\n full: ReadonlyArray<Message>,\n window: number | undefined,\n): Message[] {\n if (slicer) {\n const sliced = slicer(routeCtx);\n return sliced ? [...sliced] : [];\n }\n\n if (window === undefined || window < 0) {\n return [...full];\n }\n\n if (window === 0) {\n return [];\n }\n\n return full.slice(-window);\n}\n\n/**\n * JSON Schema form of the canonical router output shape. Surfaced via\n * the Standard JSON Schema V1 extension path (`[\"~standard\"].jsonSchema.input`)\n * so `extractJsonSchema()` can pull it for native structured-output\n * enforcement on capable providers (OpenAI strict json_schema mode,\n * Anthropic tool-use shape, etc.). Without this, the model is told to\n * emit JSON only via soft system-prompt instruction — fragile, and\n * skipped entirely when the model advertises `structuredOutput: true`.\n *\n * `next` is intentionally `string` (not a union with arrays) because\n * OpenAI strict mode rejects polymorphic root types — fan-out via\n * `string[]` is still validated at the framework layer; the model\n * just emits a single intent name (or the END sentinel) and the\n * supervisor's own normalizer handles the rest.\n */\nconst ROUTER_OUTPUT_JSON_SCHEMA = {\n type: \"object\",\n properties: {\n next: {\n type: \"string\",\n description: \"Name of the agent to dispatch next, or the END sentinel to terminate the run.\",\n },\n reasoning: {\n type: \"string\",\n description: \"One-sentence justification for the routing choice.\",\n },\n },\n required: [\"next\", \"reasoning\"],\n additionalProperties: false,\n};\n\n/**\n * Canonical Standard Schema the supervisor injects when calling the\n * router agent. Pragmatic — accepts any `next` shape the router can\n * plausibly emit (`string`, `string[]`, or the `END` literal) plus an\n * optional `reasoning` field. Rejects anything else so a broken\n * router output surfaces cleanly via the agent's own validation path.\n *\n * Exposes `[\"~standard\"].jsonSchema.input()` (Standard JSON Schema V1)\n * so capable providers enforce the shape natively rather than relying\n * on prompt-side coaching.\n */\nconst ROUTER_OUTPUT_SCHEMA: StandardSchemaV1<{\n next: Next;\n reasoning?: string;\n}> = {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-supervisor\",\n jsonSchema: {\n input: () => ROUTER_OUTPUT_JSON_SCHEMA,\n },\n validate(value: unknown): StandardSchemaV1.Result<{ next: Next; reasoning?: string }> {\n if (!value || typeof value !== \"object\") {\n return { issues: [{ message: \"router output must be an object\" }] };\n }\n\n const record = value as { next?: unknown; reasoning?: unknown };\n const rawNext = record.next;\n\n const nextIsValid =\n typeof rawNext === \"string\" ||\n (Array.isArray(rawNext) && rawNext.every((element) => typeof element === \"string\"));\n\n if (!nextIsValid) {\n return {\n issues: [\n {\n message: \"router output `next` must be a string, string[], or the END sentinel\",\n },\n ],\n };\n }\n\n const reasoning = typeof record.reasoning === \"string\" ? record.reasoning : undefined;\n\n return {\n value: { next: rawNext as Next, reasoning },\n };\n },\n } as StandardSchemaV1<{ next: Next; reasoning?: string }>[\"~standard\"] & {\n jsonSchema: { input: () => Record<string, unknown> };\n },\n};\n\nfunction wrapRouteError(supervisorName: string, thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new SupervisorFailedError(\n `\\`route\\` callback threw in supervisor \"${supervisorName}\": ${message}`,\n { cause: thrown },\n );\n}\n","import { resolveDefaultStore } from \"../config\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorResumeOptions } from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type {\n SupervisorSnapshot,\n SupervisorSnapshotStatus,\n} from \"../contracts/supervisor/supervisor-snapshot.type\";\nimport { SupervisorDriftError, SupervisorFailedError } from \"../errors\";\n\n/**\n * Resolve the effective snapshot store: the supervisor's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultStore })`.\n */\nfunction resolveSnapshotStore(config: SupervisorConfig<unknown>) {\n return config.snapshotStore ?? resolveDefaultStore();\n}\n\nexport type PersistParams = {\n config: SupervisorConfig<unknown>;\n signature: string;\n runId: string;\n input: SupervisorInput;\n startedAt: string;\n iteration: number;\n snapshots: IterationSnapshot[];\n status: SupervisorSnapshotStatus;\n};\n\nexport type PersistOutcome = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Write the current run state to the resolved snapshot store. No-op\n * (ok) when neither the supervisor's `snapshotStore` nor the global\n * `defaultStore` is configured. Failures are returned as\n * `{ ok: false }` rather than thrown so the engine can surface them\n * via events/logs without aborting the run — callers decide whether\n * a failed checkpoint is fatal.\n */\nexport async function persistSupervisorSnapshot(\n params: PersistParams,\n): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.config);\n\n if (!store) {\n return { ok: true };\n }\n\n const snapshot: SupervisorSnapshot = {\n runId: params.runId,\n supervisorName: params.config.name,\n signature: params.signature,\n input: params.input,\n iteration: params.iteration,\n snapshots: params.snapshots,\n status: params.status,\n startedAt: params.startedAt,\n savedAt: new Date().toISOString(),\n };\n\n try {\n await store.set(snapshotKey(params.runId), snapshot);\n\n return { ok: true };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * Load a persisted snapshot for `resume()` and run the drift check.\n * Throws `SupervisorFailedError` when no store is configured or when\n * the run is missing; throws `SupervisorDriftError` when the stored\n * signature doesn't match the current definition (unless `force` is\n * set).\n */\nexport async function loadSnapshotForResume(params: {\n config: SupervisorConfig<unknown>;\n signature: string;\n runId: string;\n options?: SupervisorResumeOptions;\n}): Promise<SupervisorSnapshot> {\n const store = resolveSnapshotStore(params.config);\n\n if (!store) {\n throw new SupervisorFailedError(\n `supervisor \"${params.config.name}\" has no store configured — set \\`snapshotStore\\` on the config or call \\`ai.config({ defaultStore })\\` at boot before calling resume()`,\n { context: { runId: params.runId } },\n );\n }\n\n const snapshot =\n (await store.get<SupervisorSnapshot>(snapshotKey(params.runId))) ?? null;\n\n if (!snapshot) {\n throw new SupervisorFailedError(\n `supervisor \"${params.config.name}\": no snapshot for runId \"${params.runId}\"`,\n { context: { runId: params.runId } },\n );\n }\n\n if (!params.options?.force && snapshot.signature !== params.signature) {\n throw new SupervisorDriftError(\n `supervisor \"${params.config.name}\" signature drift on resume`,\n {\n savedSignature: snapshot.signature,\n currentSignature: params.signature,\n runId: params.runId,\n },\n );\n }\n\n return snapshot;\n}\n\n/**\n * Canonical key shape used in the KVStore. Prefixed so supervisor\n * snapshots don't collide with workflow / session snapshots in a\n * shared store.\n */\nexport function snapshotKey(runId: string): string {\n return `supervisor:${runId}`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END } from \"../contracts/end.type\";\nimport type { EventIdentity, WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type {\n SupervisorReport,\n SupervisorResult,\n SupervisorTerminatedBy,\n} from \"../contracts/result/supervisor-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type {\n ClassifierConfig,\n ClassifierContext,\n ClassifierOutput,\n ClassifierRefineContext,\n ClassifierRefineResult,\n ClassifierSnapshot,\n} from \"../contracts/supervisor/classifier-context.type\";\nimport type {\n DispatchContext,\n StreamableExecutable,\n SupervisableExecutable,\n SupervisableExecuteOptions,\n SupervisableResult,\n} from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n EvaluateBranchResult,\n EvaluateContext,\n EvaluateResult,\n} from \"../contracts/supervisor/evaluate-context.type\";\nimport type {\n AckSnapshot,\n AgentBranchSnapshot,\n IterationSnapshot,\n} from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorExecuteOptions } from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type {\n SupervisorSnapshot,\n SupervisorSnapshotStatus,\n} from \"../contracts/supervisor/supervisor-snapshot.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport {\n AIError,\n MaxIterationsError,\n SchemaValidationError,\n SupervisorCancelledError,\n SupervisorFailedError,\n} from \"../errors\";\nimport { stampReportLineage } from \"../utils\";\nimport { createCancelledError } from \"./cancellation\";\nimport { decide, type DispatchDecision } from \"./decide\";\nimport type { SupervisorEmitter } from \"./emitter\";\nimport type { ResolvedCallbackEntry, ResolvedIntentEntry } from \"./entries\";\nimport { isAgentResult, isWorkflowResult } from \"./entries\";\nimport { persistSupervisorSnapshot } from \"./snapshot\";\nimport type { SupervisorStreamController, SupervisorStreamEvent } from \"./supervisor-stream\";\n\nconst DEFAULT_MAX_ITERATIONS = 10;\nconst LOG_MODULE_BASE = \"ai.supervisor\";\n\nexport type SupervisorExecutionParams<TOutput> = {\n config: SupervisorConfig<TOutput>;\n entries: Map<string, ResolvedIntentEntry>;\n signature: string;\n emitter: SupervisorEmitter;\n input: SupervisorInput;\n runId: string;\n options?: SupervisorExecuteOptions;\n streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n resumeFrom?: SupervisorSnapshot;\n};\n\n/**\n * Per-call driver that owns the full lifecycle of one supervisor run.\n *\n * **Role.** Short-lived state container and phase orchestrator —\n * mirrors `agent/Execution` and `workflow/runWorkflow`, one level up.\n *\n * **Responsibility.**\n * - Owns: the iteration loop, per-iteration dispatch (single or\n * fan-out), evaluate scheduling, usage aggregation across router +\n * every branch + evaluate, snapshot collection, event emission\n * through all three tiers, KV-store checkpointing, final result\n * assembly (state validation against the output schema → typed data).\n * - Does NOT own: how child agents produce responses (delegated via\n * `agent.execute` / `workflow.execute`), the routing decision\n * itself (delegated to `decide.ts`), snapshot persistence mechanics\n * (delegated to `snapshot.ts`), the stream queue plumbing\n * (delegated to `supervisor-stream.ts`).\n *\n * `execute()` never throws — every unexpected failure funnels into\n * `this.error` and is returned on `result.error` with an appropriate\n * `SupervisorFailedError` / `MaxIterationsError` / `SupervisorRoutingError`\n * / `SupervisorCancelledError`.\n *\n * @example\n * // Inside supervisor.execute() — never constructed by user code directly:\n * return new SupervisorExecution(params).run();\n */\nexport class SupervisorExecution<TOutput> {\n private readonly config: SupervisorConfig<TOutput>;\n private readonly entries: Map<string, ResolvedIntentEntry>;\n private readonly signature: string;\n private readonly emitter: SupervisorEmitter;\n private readonly input: SupervisorInput;\n private readonly runId: string;\n private readonly options?: SupervisorExecuteOptions;\n private readonly streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n private readonly resumeFrom?: SupervisorSnapshot;\n\n private readonly maxIterations: number;\n private readonly logger: Logger = log;\n private readonly logModule: string;\n\n private readonly snapshots: IterationSnapshot[] = [];\n private readonly childReports: BaseReport[] = [];\n private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n\n private readonly startedAtIso: string;\n private readonly startPerf = performance.now();\n\n private iteration = 0;\n private carriedFeedback?: EvaluateResult;\n /**\n * Per-intent `next` directive (Q24 / Stage 4d) collected at the\n * end of an iteration after evaluate hasn't already steered. When\n * set, `decideDispatch` consumes it on the next iteration's start —\n * skipping the router entirely. Cleared after consumption.\n *\n * Only the dispatch variant is stored; an `END` collection\n * terminates the iteration loop directly inside `runIteration`.\n */\n private carriedNextDispatch?: { intents: string[] };\n private terminatedBy: SupervisorTerminatedBy = \"error\";\n private status: SupervisorReport[\"status\"] = \"failed\";\n private cancelledAtIso?: string;\n private error?: AIError;\n private data?: TOutput;\n private lastDispatchIntents: string[] = [];\n /**\n * Per-execute typed accumulator. Initialized from `config.state`\n * (default `{}`) at construction; rehydrated from the last\n * snapshot's `state` on resume; mutated in-place as each iteration's\n * intents strip-merge their outputs into it.\n */\n private state: Record<string, unknown> = {};\n /**\n * Per-iteration artifacts bag (Phase 5 / decisions §35). Tools\n * dispatched within an iteration mutate `ctx.artifacts` — which\n * points at this object. After the iteration's branches settle and\n * their slices merge into state, this bag validates against\n * `config.artifactsSchema` (if set) and merges via\n * `config.finalizeArtifacts` or auto-spread, then resets to `{}`\n * for the next iteration. The reset is crucial — long runs and\n * orchestrator sessions never accumulate raw artifacts here.\n */\n private currentArtifacts: Record<string, unknown> = {};\n /**\n * Frozen copy of the iteration's `currentArtifacts` bag captured at\n * merge time — BEFORE `finalizeArtifacts` (or auto-spread) reshaped\n * it into state (Phase 8 / decisions §38). Surfaced on the iteration\n * snapshot's `artifacts` field for forensic / telemetry consumers\n * that want the raw tool contributions.\n *\n * Reset to `{}` at the start of every iteration so a snapshot built\n * for an iteration whose tools wrote nothing carries an empty bag,\n * not a stale carry-over.\n */\n private capturedIterationArtifacts: Readonly<Record<string, unknown>> = Object.freeze({});\n /**\n * Classifier (Phase 7 / decisions §37) forensic record. Set on iter\n * 0 when `SupervisorConfig.classifier` is configured AND the run\n * started fresh (resumes don't re-fire classifier — same as ack).\n * Surfaced on `SupervisorReport.classifier` and threaded into\n * `ctx.classifier` on RouteContext / DispatchContext /\n * EvaluateContext from iter 0 onward.\n */\n private classifierSnapshot?: ClassifierSnapshot;\n /**\n * Iter-0 dispatch decision pre-computed by the classifier (Phase 7).\n * When set, `decideDispatch` short-circuits and uses this directly\n * with `source: \"classifier\"`. Cleared after consumption.\n */\n private carriedClassifierDispatch?: { intent: string };\n /** Set true by classifier refine returning END to halt before any dispatch. */\n private classifierHalted = false;\n /**\n * Receptionist forensic record. Set when an `ackAgent` was\n * configured AND the run started fresh (resumes don't re-fire ack).\n * Surfaced on `SupervisorReport.ack`.\n */\n private ackSnapshot?: AckSnapshot;\n /**\n * Read-only request-scoped context surfaced on every `ctx.context`.\n * Shallow-copied + frozen at construction so callbacks see a stable\n * snapshot of the caller's bag and can't mutate the original.\n * Always present — defaults to a frozen `{}` when no context was\n * passed. NOT persisted in snapshots.\n */\n private readonly context: Readonly<Record<string, unknown>>;\n /**\n * Prior conversation messages threaded through every callback context\n * (`ctx.history`) and forwarded verbatim to dispatched agents (and the\n * receptionist `ack` agent) as `agent.execute(input, { history })`.\n * Frozen reference so callbacks see a stable view; not deep-cloned —\n * conversation messages are treated as immutable by convention. NOT\n * persisted in snapshots (re-supply on `resume()`).\n */\n private readonly history: ReadonlyArray<Message>;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`.\n * Materialized to plain text at construction (string passes through;\n * `SystemPromptContract` is `.resolve()`-d). `undefined` when the\n * supervisor was configured without a goal.\n */\n private readonly goal: string | undefined;\n\n public constructor(params: SupervisorExecutionParams<TOutput>) {\n this.config = params.config;\n this.entries = params.entries;\n this.signature = params.signature;\n this.emitter = params.emitter;\n this.input = params.input;\n this.runId = params.runId;\n this.options = params.options;\n this.streamController = params.streamController;\n this.resumeFrom = params.resumeFrom;\n\n this.maxIterations = params.config.maxIterations ?? DEFAULT_MAX_ITERATIONS;\n this.logModule = `${LOG_MODULE_BASE}.${params.config.name}`;\n\n // Shallow-copy + freeze the caller's context. Shallow only —\n // freezing deeply would break valid use cases (mutable DB\n // clients, abort controllers) without delivering meaningful\n // safety beyond what TS `Readonly` already enforces.\n this.context = Object.freeze({ ...(params.options?.context ?? {}) });\n // Freeze the array reference so callbacks can't mutate the slot\n // (`history.push(...)`); messages themselves are passed by reference\n // — supervisors trust the agent layer's read-only convention.\n // Precedence: per-call `options.history` (most explicit) overrides\n // factory-level `config.history` (default for callers who don't\n // supply per-call history). Final fallback is an empty array.\n this.history = Object.freeze([...(params.options?.history ?? params.config.history ?? [])]);\n\n // Resolve `goal` to plain text once, at construction. `string`\n // passes through; `SystemPromptContract` is `.resolve()`-d (it owns\n // its own placeholder substitution). `undefined` when no goal was\n // configured — every `ctx.goal` consumer must guard for absence.\n if (typeof params.config.goal === \"string\") {\n this.goal = params.config.goal;\n } else if (params.config.goal) {\n this.goal = params.config.goal.resolve();\n } else {\n this.goal = undefined;\n }\n\n if (params.resumeFrom) {\n this.snapshots.push(...params.resumeFrom.snapshots);\n this.iteration = params.resumeFrom.iteration + 1;\n this.startedAtIso = params.resumeFrom.startedAt;\n // Resume rehydrates state from the last persisted iteration —\n // every iteration's snapshot carries the post-merge state, so\n // the resume point's state is the last snapshot's state.\n const lastSnapshot = params.resumeFrom.snapshots[params.resumeFrom.snapshots.length - 1];\n this.state = {\n ...(lastSnapshot?.state ??\n (params.config.state as Record<string, unknown> | undefined) ??\n {}),\n };\n } else {\n this.startedAtIso = new Date().toISOString();\n this.state = {\n ...((params.config.state as Record<string, unknown> | undefined) ?? {}),\n };\n }\n }\n\n /**\n * Resolve the history slice forwarded to a child execution (router /\n * dispatched agent / ack). Precedence:\n *\n * 1. Per-entry `history` callback — full override; whatever it\n * returns goes through (after defensive copy).\n * 2. `SupervisorConfig.historyWindow.<role>` — last-N slice of the\n * caller-supplied history.\n * 3. Default — full history for `router`/`agents`, empty for `ack`\n * (receptionists rarely benefit from scroll-back).\n *\n * Always returns a fresh `Message[]` (the agent layer\n * mutates by reference internally, e.g. via `messages.push(...)`).\n */\n private resolveHistoryFor(\n role: \"router\" | \"agents\" | \"ack\",\n routeContext: RouteContext,\n entrySlicer?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>,\n ): Message[] {\n if (entrySlicer) {\n const sliced = entrySlicer(routeContext);\n return sliced ? [...sliced] : [];\n }\n\n const window = this.config.historyWindow?.[role];\n\n if (role === \"ack\") {\n // Default for ack is empty — receptionists rarely need history.\n // Override is opt-in via `historyWindow.ack: N`.\n if (window === undefined || window <= 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n if (window === undefined || window < 0) {\n return [...this.history];\n }\n\n if (window === 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n /**\n * Apply only the global `historyWindow.agents` slice — used by the\n * recursive `ctx.intents.X.execute()` re-entry path where no\n * `RouteContext` is available to feed the per-entry slicer.\n */\n private applyAgentsWindow(): Message[] {\n const window = this.config.historyWindow?.agents;\n\n if (window === undefined || window < 0) {\n return [...this.history];\n }\n\n if (window === 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n /**\n * Entry point. Drives the iteration loop, finalizes the result, and\n * emits terminal events. Returns the uniform\n * `{ data, report, usage, error }` shape and closes the stream if\n * one was attached. Never throws.\n */\n public async run(): Promise<SupervisorResult<TOutput>> {\n this.emit(\"supervisor.starting\", {\n supervisorName: this.config.name,\n input: this.input,\n });\n\n this.logger.info(this.logModule, \"starting\", \"supervisor starting\", {\n runId: this.runId,\n maxIterations: this.maxIterations,\n });\n\n try {\n await this.runIterationLoop();\n } catch (thrown) {\n this.error = toAIError(thrown);\n this.status = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"failed\";\n this.terminatedBy = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"error\";\n\n if (this.error instanceof SupervisorCancelledError) {\n this.cancelledAtIso = this.error.cancelledAt;\n }\n\n if (this.error instanceof MaxIterationsError) {\n this.status = \"max-iterations\";\n this.terminatedBy = \"max-iterations\";\n }\n }\n\n const result = await this.finalize();\n\n if (result.error) {\n if (this.status === \"cancelled\") {\n this.emit(\"supervisor.cancelled\", {\n cancelledAt: this.cancelledAtIso ?? new Date().toISOString(),\n reason: (result.error as SupervisorCancelledError).reason,\n });\n } else {\n this.emit(\"supervisor.error\", { error: result.error });\n }\n }\n\n this.emit(\"supervisor.completed\", { result });\n\n this.streamController?.end(result);\n\n this.logger.info(this.logModule, \"completed\", \"supervisor completed\", {\n runId: this.runId,\n status: this.status,\n iterations: this.snapshots.length,\n duration: performance.now() - this.startPerf,\n });\n\n return result;\n }\n\n /**\n * Drive the iteration loop until a terminal condition fires:\n * `END` / `satisfied:true` / `maxIterations` / signal abort /\n * routing error. Between-iteration cancellation is guaranteed —\n * the signal is checked before every iteration starts.\n */\n private async runIterationLoop(): Promise<void> {\n while (this.iteration < this.maxIterations) {\n this.throwIfCancelled();\n\n const continued = await this.runIteration();\n\n if (!continued) {\n return;\n }\n\n this.iteration += 1;\n }\n\n throw new MaxIterationsError(\n `supervisor \"${this.config.name}\" exceeded maxIterations=${this.maxIterations}`,\n { maxIterations: this.maxIterations },\n );\n }\n\n /**\n * Run one iteration end-to-end: decide → dispatch → evaluate →\n * snapshot. Returns `true` when the loop should continue to the\n * next iteration, `false` when this iteration terminated the run\n * (success or satisfied-verdict). Failures throw — the loop's\n * outer catch converts them into typed errors on the result.\n */\n private async runIteration(): Promise<boolean> {\n const iterationStartedAt = new Date();\n const iterationStart = performance.now();\n const iterationUsage: Usage = { input: 0, output: 0, total: 0 };\n\n // Phase 8 / decisions §38 — reset the captured-artifacts forensic\n // surface at iteration start so a snapshot built for an iteration\n // whose tools wrote nothing carries an empty bag, not a stale\n // carry-over from the prior iteration. `mergeArtifactsIntoState`\n // refreshes this with the live bag (frozen) before merge.\n this.capturedIterationArtifacts = Object.freeze({});\n\n this.emit(\"supervisor.iteration.starting\", { iteration: this.iteration });\n\n // Kick off the receptionist (`ack`) in parallel with phase A's\n // dispatch decision — fires on iter 0 only when the run is fresh\n // (resumes don't re-emit; user already saw the original ack). The\n // promise is NOT awaited inline — `settleAck` probes it\n // non-blockingly later so a slow ack never extends total wall-\n // clock time. If ack hasn't settled by the probe point, its slice\n // is abandoned with a warning + error on the report.\n const ackPromise =\n this.iteration === 0 && !this.resumeFrom && this.config.ack ? this.runAck() : undefined;\n\n // Phase 7 / decisions §37 — classifier prelude. Runs once on iter 0\n // for fresh runs only (resumes inherit the prior classifier output\n // via state + report.classifier). Awaited inline because its\n // output drives the iter-0 dispatch decision; ack remains\n // non-blocking parallel by design.\n if (this.iteration === 0 && !this.resumeFrom && this.config.classifier) {\n await this.runClassifier();\n\n if (this.classifierHalted) {\n // Refine returned END (or classifier-alone mode interpreted\n // an END signal). Settle ack, mark terminated, capture a\n // synthetic decision snapshot, and exit the loop. State may\n // already carry refine's slice — do not clobber.\n await this.settleAck(ackPromise, iterationUsage);\n this.terminatedBy = \"classifier\";\n this.status = \"completed\";\n\n await this.recordTerminalDecisionSnapshot(\n {\n kind: \"end\",\n source: \"classifier\",\n raw: END,\n durationMs: 0,\n },\n iterationStartedAt,\n iterationStart,\n iterationUsage,\n );\n\n return false;\n }\n }\n\n const decision = await this.decideDispatch();\n\n this.aggregateUsage(iterationUsage, decision.usage);\n\n if (decision.kind === \"end\") {\n await this.settleAck(ackPromise, iterationUsage);\n this.terminatedBy = decision.source === \"route\" ? \"route\" : \"router\";\n this.status = \"completed\";\n\n await this.recordTerminalDecisionSnapshot(\n decision,\n iterationStartedAt,\n iterationStart,\n iterationUsage,\n );\n\n return false;\n }\n\n const branchSnapshots = await this.dispatchBranches(decision);\n\n for (const snapshot of branchSnapshots) {\n this.aggregateUsage(iterationUsage, snapshot.usage);\n }\n\n // Settle ack (if kicked off) before phase C merge. Probe is\n // non-blocking — `setImmediate` yields one macrotask cycle so an\n // already-resolved ack wins via microtask priority; otherwise the\n // probe returns NOT_READY and ack is abandoned (slice dropped,\n // warning logged, error captured on `report.ack`). Specialist\n // branches override the receptionist on key collision either way.\n await this.settleAck(ackPromise, iterationUsage);\n\n // Merge branch outputs into supervisor state in decision.intents\n // order so fan-out conflict resolution is deterministic — last\n // intent in the array wins on key collisions (Q15). Errored\n // branches don't contribute. Entries without an `output` schema\n // (agent/workflow) are NOT auto-merged — declaring the slice is\n // opt-in. Callbacks always merge (their full return value when\n // no schema; strip-merged when schema is declared) — they had\n // their schema applied inside runCallback already.\n this.mergeBranchesIntoState(decision.intents, branchSnapshots);\n\n // Phase 5 / decisions §35 — merge tool-side artifacts into state\n // AFTER branch slices land but BEFORE evaluate runs, so the\n // evaluate verdict sees the post-merge state including blocks /\n // citations / soft signals contributed by tools. Resets the bag\n // for the next iteration; long runs and orchestrator sessions\n // never accumulate raw artifacts.\n await this.mergeArtifactsIntoState();\n\n this.lastDispatchIntents = decision.intents;\n\n const evaluateVerdict = await this.runEvaluate(branchSnapshots);\n\n if (evaluateVerdict !== undefined && evaluateVerdict !== null) {\n this.emit(\"supervisor.evaluate.verdict\", {\n iteration: this.iteration,\n verdict: evaluateVerdict,\n });\n }\n\n const iterationEndedAt = new Date();\n const duration = performance.now() - iterationStart;\n\n const snapshot: IterationSnapshot = Object.freeze({\n iteration: this.iteration,\n result: indexByIntent(branchSnapshots),\n decision: {\n source: decision.source,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n },\n evaluateVerdict,\n state: { ...this.state },\n artifacts: this.capturedIterationArtifacts,\n startedAt: iterationStartedAt.toISOString(),\n endedAt: iterationEndedAt.toISOString(),\n duration,\n usage: iterationUsage,\n });\n\n this.snapshots.push(snapshot);\n\n this.emit(\"supervisor.iteration.completed\", {\n iteration: this.iteration,\n snapshot,\n });\n\n await this.checkpoint(\"running\");\n\n if (evaluateVerdict?.satisfied) {\n this.terminatedBy = \"evaluate\";\n this.status = \"completed\";\n\n return false;\n }\n\n this.carriedFeedback = evaluateVerdict;\n\n // Stage 4d (Q24): when evaluate hasn't taken a stance via\n // `reassignTo`, collect each branch's `intent.next(ctx)` to drive\n // the next iteration without a router call. Evaluate's\n // `reassignTo` outranks `next` — if evaluate forced a target,\n // `next` doesn't get to vote.\n const evaluateForcedReassign =\n evaluateVerdict?.reassignTo !== undefined &&\n normalizeReassign(evaluateVerdict.reassignTo).length > 0;\n\n if (!evaluateForcedReassign) {\n const collected = this.collectIntentNext(decision.intents, branchSnapshots);\n\n if (collected?.kind === \"end\") {\n this.terminatedBy = \"route\";\n this.status = \"completed\";\n this.carriedNextDispatch = undefined;\n return false;\n }\n\n if (collected?.kind === \"dispatch\") {\n this.carriedNextDispatch = { intents: collected.intents };\n }\n }\n\n // Phase 7 / decisions §37 — classifier-alone supervisor auto-\n // terminates after iter 0's branch settles. Without router/route,\n // there's no decision source for iter 1; preempt the throw with\n // a clean termination. `intent.next` from iter 0's dispatched\n // intent still wins if it set a continuation (rare, but allowed).\n if (\n this.iteration === 0 &&\n this.config.classifier &&\n !this.config.router &&\n !this.config.route &&\n !this.carriedNextDispatch\n ) {\n this.terminatedBy = \"classifier\";\n this.status = \"completed\";\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Resolve the dispatch decision for this iteration — defers to\n * `decide.ts`. When `carriedFeedback.reassignTo` is set the\n * supervisor overrides the router/route decision with an\n * evaluator-forced dispatch (design §2 — \"Evaluate can override\n * router\").\n */\n private async decideDispatch(): Promise<DispatchDecision> {\n if (this.config.router) {\n this.emit(\"supervisor.router.deciding\", { iteration: this.iteration });\n }\n\n const reassignTo = normalizeReassign(this.carriedFeedback?.reassignTo);\n\n if (reassignTo.length > 0) {\n this.carriedNextDispatch = undefined;\n for (const intent of reassignTo) {\n if (!this.entries.has(intent)) {\n throw new SupervisorFailedError(\n `evaluate.reassignTo targeted unknown agent \"${intent}\"`,\n { context: { available: [...this.entries.keys()] } },\n );\n }\n }\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: reassignTo,\n source: \"route\",\n raw: reassignTo.length === 1 ? reassignTo[0] : reassignTo,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: this.carriedFeedback?.feedback,\n durationMs: 0,\n });\n\n return decision;\n }\n\n // Phase 7 / decisions §37 — classifier prelude (iter 0 only)\n // produced an intent dispatch decision. Skip router/route /\n // initialAgent entirely; classifier's pick wins. Cleared after\n // consumption — iter 1+ falls through to router/route as usual.\n if (this.carriedClassifierDispatch) {\n const carried = this.carriedClassifierDispatch;\n this.carriedClassifierDispatch = undefined;\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: [carried.intent],\n source: \"classifier\",\n raw: carried.intent,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: this.classifierSnapshot?.reasoning,\n durationMs: 0,\n });\n\n return decision;\n }\n\n // Stage 4d: per-intent `next` collected from the previous\n // iteration drives this dispatch — skip router/route entirely.\n if (this.carriedNextDispatch) {\n const carried = this.carriedNextDispatch;\n this.carriedNextDispatch = undefined;\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: carried.intents,\n source: \"route\",\n raw: carried.intents.length === 1 ? carried.intents[0] : carried.intents,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: undefined,\n durationMs: 0,\n });\n\n return decision;\n }\n\n const decision = await decide({\n config: this.config as SupervisorConfig<unknown>,\n entries: this.entries,\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n iterations: this.snapshots,\n input: this.input,\n state: this.state,\n context: this.context,\n history: this.history,\n goal: this.goal,\n evaluateFeedback: this.carriedFeedback,\n classifier: this.classifierSnapshot,\n signal: this.options?.signal,\n useInitialAgent: this.iteration === 0 && !this.resumeFrom,\n });\n\n // Capture the router agent's report into the supervisor's tree so\n // router cost + internals are observable alongside dispatched\n // branches. Only present when decide() went through a router agent.\n if (decision.routerReport) {\n this.childReports.push(decision.routerReport);\n }\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n });\n\n return decision;\n }\n\n /**\n * Dispatch every intent named by the decision in parallel. Per-\n * branch errors don't abort siblings — they're recorded on the\n * branch snapshot and let evaluate (or default termination logic)\n * decide the response.\n */\n private async dispatchBranches(\n decision: DispatchDecision & { kind: \"dispatch\" },\n ): Promise<AgentBranchSnapshot[]> {\n const branches = await Promise.all(decision.intents.map((intent) => this.dispatchOne(intent)));\n\n return branches;\n }\n\n /**\n * Execute a single branch — resolve the input, invoke the\n * agent / workflow / callback, apply the per-intent `output`\n * transformer, and produce an immutable `AgentBranchSnapshot`.\n */\n private async dispatchOne(intent: string): Promise<AgentBranchSnapshot> {\n const entry = this.entries.get(intent)!;\n\n if (entry.type === \"callback\") {\n return this.dispatchCallback(entry);\n }\n\n const routeContext: RouteContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n iterations: this.snapshots,\n feedback:\n typeof this.carriedFeedback?.feedback === \"string\"\n ? this.carriedFeedback.feedback\n : undefined,\n evaluateFeedback: this.carriedFeedback,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n const resolvedInput = this.resolveBranchInput(entry, routeContext);\n const dispatchCtxForPlaceholders = this.seedDispatchContext(\n intent,\n resolvedInput,\n new Set<string>([intent]),\n [],\n );\n const placeholders = entry.placeholders\n ? entry.placeholders(dispatchCtxForPlaceholders)\n : undefined;\n\n this.emit(\"supervisor.agent.starting\", {\n iteration: this.iteration,\n intent,\n input: resolvedInput,\n });\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n let rawResult: AgentResult<unknown> | WorkflowResult<unknown> | undefined;\n let branchError: AIError | undefined;\n let branchUsage: Usage = { input: 0, output: 0, total: 0 };\n\n try {\n rawResult = await this.invokeUnit(entry, resolvedInput, placeholders, routeContext);\n\n if (rawResult.error) {\n branchError = rawResult.error;\n }\n\n branchUsage = rawResult.usage;\n\n // Capture the child's execution report into the supervisor's\n // recursive tree. Each dispatched agent/workflow contributes\n // one BaseReport node; fan-out produces sibling children.\n if (rawResult.report) {\n this.childReports.push(rawResult.report);\n }\n } catch (thrown) {\n branchError = toAIError(thrown);\n }\n\n const sliceOutcome = await this.applyOutputSchema(entry, rawResult);\n const transformedOutput = sliceOutcome.value;\n if (sliceOutcome.error && !branchError) {\n branchError = sliceOutcome.error;\n }\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n const snapshot: AgentBranchSnapshot = Object.freeze({\n intent,\n input: resolvedInput,\n output: transformedOutput,\n usage: branchUsage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: branchError,\n });\n\n if (branchError) {\n this.emit(\"supervisor.agent.failed\", {\n iteration: this.iteration,\n intent,\n error: branchError,\n });\n } else {\n this.emit(\"supervisor.agent.completed\", {\n iteration: this.iteration,\n intent,\n output: transformedOutput,\n usage: branchUsage,\n duration,\n });\n }\n\n return snapshot;\n }\n\n /**\n * Dispatch a callback intent as a top-level branch — produces an\n * `AgentBranchSnapshot` and pushes the synthesized callback report\n * onto the supervisor's recursive children. Delegates the actual\n * callback invocation to {@link runCallback} so nested\n * `ctx.intents.X.execute()` calls can reuse the same machinery.\n *\n * Each branch dispatch starts with a fresh per-branch call stack —\n * sibling fan-out branches don't share cycle-detection state, so\n * branch A and branch B both invoking the same intent isn't a\n * cycle. The branch's own intent name is seeded onto the stack so\n * a callback that re-enters itself via `ctx.intents.X.execute()` trips\n * cycle detection on the first recursion.\n */\n private async dispatchCallback(entry: ResolvedCallbackEntry): Promise<AgentBranchSnapshot> {\n const intent = entry.intent;\n const callStack = new Set<string>([intent]);\n const callbackInput = entry.input\n ? entry.input(this.seedDispatchContext(intent, this.input, callStack, []))\n : this.input;\n const inputForSnapshot =\n typeof callbackInput === \"string\" ? callbackInput : safeStringify(callbackInput);\n\n this.emit(\"supervisor.agent.starting\", {\n iteration: this.iteration,\n intent,\n input: inputForSnapshot,\n });\n\n const outcome = await this.runCallback(entry, callbackInput, callStack, this.childReports);\n\n const snapshot: AgentBranchSnapshot = Object.freeze({\n intent,\n input: inputForSnapshot,\n output: outcome.output,\n usage: outcome.report.usage,\n startedAt: outcome.report.startedAt,\n endedAt: outcome.report.endedAt,\n duration: outcome.report.duration,\n error: outcome.error,\n });\n\n if (outcome.error) {\n this.emit(\"supervisor.agent.failed\", {\n iteration: this.iteration,\n intent,\n error: outcome.error,\n });\n } else {\n this.emit(\"supervisor.agent.completed\", {\n iteration: this.iteration,\n intent,\n output: outcome.output,\n usage: outcome.report.usage,\n duration: outcome.report.duration,\n });\n }\n\n return snapshot;\n }\n\n /**\n * Run a callback intent and produce its leaf report + final\n * output. Used both for top-level branch dispatch (via\n * {@link dispatchCallback}) and for nested `dispatch.byName`\n * recursion. The synthesized report is appended to `reportSink`,\n * which is either `this.childReports` (top-level) or the calling\n * callback's own `children[]` (nested) — that's what gives the\n * unified report tree its compositional shape.\n *\n * Usage on the report rolls up children's usage; the callback\n * itself contributes zero (it's dev code, no token spend).\n */\n private async runCallback(\n entry: ResolvedCallbackEntry,\n input: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<{ output: unknown; error?: AIError; report: BaseReport }> {\n const childReports: BaseReport[] = [];\n const dispatchCtx: DispatchContext = this.seedDispatchContext(\n entry.intent,\n input,\n callStack,\n childReports,\n );\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n let rawOutput: unknown;\n let error: AIError | undefined;\n\n try {\n rawOutput = await entry.callback(dispatchCtx);\n } catch (thrown) {\n error =\n thrown instanceof AIError\n ? thrown\n : new SupervisorFailedError(\n `callback intent \"${entry.intent}\" threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`,\n { cause: thrown },\n );\n }\n\n let transformedOutput: unknown = rawOutput;\n\n if (!error && entry.output) {\n const validation = await entry.output[\"~standard\"].validate(rawOutput);\n if (validation.issues) {\n error = new SchemaValidationError(\n `intent \"${entry.intent}\" output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n transformedOutput = undefined;\n } else {\n transformedOutput = validation.value;\n }\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n const rolledUsage = aggregateChildUsage(childReports);\n\n const report: BaseReport = {\n runId: `${this.runId}.${entry.intent}`,\n rootRunId: this.runId,\n name: entry.intent,\n type: \"callback\",\n status: error ? \"failed\" : \"completed\",\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n usage: rolledUsage,\n children: childReports,\n };\n\n reportSink.push(report);\n\n return { output: transformedOutput, error, report };\n }\n\n /**\n * Build a {@link DispatchContext} with a typed `intents` map of\n * `IntentRunner` closures, each closing over the supplied call\n * stack and report sink. Cycle detection uses the call stack —\n * re-entering an intent already on it throws\n * `SupervisorFailedError` with code `SUPERVISOR_DISPATCH_CYCLE`\n * and the offending chain in the message.\n *\n * Replaces the Phase-3.3 `ctx.dispatch.byName` plumbing with\n * property-access on a typed map (Q5/Q6) — autocomplete, no typo\n * crashes, `.execute()` matches every other primitive's verb.\n */\n private seedDispatchContext(\n intent: string,\n input: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): DispatchContext {\n type RunnerSlot = {\n execute: (input?: unknown) => Promise<unknown>;\n stream: (input?: unknown) => unknown;\n };\n const intentsMap: Record<string, RunnerSlot> = {};\n\n for (const target of this.entries.keys()) {\n intentsMap[target] = {\n execute: (override?: unknown) =>\n this.runIntent(target, override === undefined ? input : override, callStack, reportSink),\n stream: (override?: unknown) =>\n this.streamIntent(\n target,\n override === undefined ? input : override,\n callStack,\n reportSink,\n intent,\n ),\n };\n }\n\n return {\n iteration: this.iteration,\n intent,\n input,\n state: this.state,\n result: {},\n iterations: this.snapshots,\n signal: this.options?.signal ?? new AbortController().signal,\n intents: intentsMap as DispatchContext[\"intents\"],\n context: this.context,\n history: this.history,\n goal: this.goal,\n run: (executable, runInput, runOptions) =>\n this.runInline(executable, runInput, runOptions, callStack, reportSink),\n stream: (executable, runInput, runOptions) =>\n this.streamInline(executable, runInput, runOptions, callStack, reportSink, intent),\n classifier: this.classifierSnapshot,\n } as DispatchContext;\n }\n\n /**\n * Backing implementation for `ctx.intents.X.execute(input?)`.\n * Looks up the named intent in the supervisor's registry, asserts\n * the call wouldn't close a cycle, and runs the dispatchable\n * through the same machinery a top-level branch would — except\n * the resulting report nests under the calling callback's\n * `children[]` rather than the supervisor's top-level child list,\n * and only the final output is returned (no snapshot).\n */\n private async runIntent(\n target: string,\n callerInput: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<unknown> {\n if (callStack.has(target)) {\n const chain = [...callStack, target].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.intents.${target}.execute: cycle detected (${chain})`,\n { context: { intent: target } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n const entry = this.entries.get(target);\n\n if (!entry) {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.execute: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n { context: { intent: target } },\n );\n }\n\n callStack.add(target);\n\n try {\n if (entry.type === \"callback\") {\n const { output, error } = await this.runCallback(entry, callerInput, callStack, reportSink);\n\n if (error) {\n throw error;\n }\n\n return output;\n }\n\n // Agent / workflow path. The unified-report tree gets the\n // child's report under the calling callback's children — we\n // intentionally do NOT also push to `this.childReports` (that\n // would double-count). The agent/workflow's own usage flows\n // up through the callback's roll-up.\n const inputString =\n typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n if (entry.type === \"agent\") {\n // Recursive `ctx.intents.X.execute()` re-entry path — no\n // `RouteContext` constructed here, so the per-entry slicer is\n // skipped; only the global `historyWindow.agents` window\n // applies. The original outer dispatch already passed a sliced\n // view; this sub-call mirrors that behavior.\n const reentryHistory = this.applyAgentsWindow();\n const result = await entry.unit.execute(inputString, {\n signal: this.options?.signal,\n ...(reentryHistory.length > 0 ? { history: reentryHistory } : {}),\n });\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n return result.data ?? result.text ?? undefined;\n }\n\n // workflow\n const result = await entry.unit.execute(inputString as never, {\n signal: this.options?.signal,\n });\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n return result.data;\n } finally {\n callStack.delete(target);\n }\n }\n\n /**\n * Backing implementation for `ctx.intents.X.stream(input?)` (Phase 6\n * / decisions §36). Streaming sibling of {@link runIntent} — same\n * cycle protection, same auto-merge of supervisor-level concerns,\n * but routes through the unit's `.stream()` method when available\n * and bubbles deltas as `supervisor.agent.streaming` under the\n * **calling callback's** intent name (not the dispatched intent's).\n */\n private streamIntent(\n target: string,\n callerInput: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n callerIntent: string,\n ): StreamContract<SupervisableResult> {\n if (callStack.has(target)) {\n const chain = [...callStack, target].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: cycle detected (${chain})`,\n { context: { intent: target } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n const entry = this.entries.get(target);\n\n if (!entry) {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n { context: { intent: target } },\n );\n }\n\n if (entry.type === \"callback\") {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: callback intents are not streamable — use \\`.execute(input?)\\` instead`,\n { context: { intent: target } },\n );\n }\n\n callStack.add(target);\n\n const inputString = typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n return this.streamSupervisedExecutable(\n entry.unit as StreamableExecutable,\n inputString,\n undefined,\n callerIntent,\n reportSink,\n () => callStack.delete(target),\n );\n }\n\n /**\n * Backing implementation for `ctx.run(executable, input, options?)`\n * (Phase 6 / decisions §36). Runs an inline / un-registered\n * executable under supervision: auto-merges `signal`, `toolCtx`,\n * `history` defaults; nests the resulting report under the\n * calling callback's `children[]`. Per-call options REPLACE auto-\n * defaults — standard Warlock convention.\n *\n * Cycle protection by executable `name` matches the registered-\n * intent path so a callback that recurses on the same agent trips\n * the same error, regardless of whether the agent was looked up\n * via `ctx.intents.X.execute()` or passed inline.\n */\n private async runInline(\n executable: SupervisableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<SupervisableResult> {\n const name = executable.name;\n\n if (callStack.has(name)) {\n const chain = [...callStack, name].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.run(\"${name}\"): cycle detected (${chain})`,\n { context: { intent: name } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n callStack.add(name);\n\n try {\n const merged = this.mergeInlineOptions(options);\n const inputForExecutable = this.coerceInlineInput(executable, input);\n const result = (await (\n executable as {\n execute: (input: unknown, options?: unknown) => Promise<SupervisableResult>;\n }\n ).execute(inputForExecutable, merged)) as SupervisableResult;\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n return result;\n } finally {\n callStack.delete(name);\n }\n }\n\n /**\n * Backing implementation for `ctx.stream(executable, input, options?)`\n * (Phase 6 / decisions §36). Streaming sibling of {@link runInline}.\n * Routes through the executable's native `.stream()` method,\n * subscribes to delta events, and bubbles them as\n * `supervisor.agent.streaming` under the calling callback's intent\n * name. The returned `StreamContract` is the executable's own —\n * iteration and `.result` work identically.\n *\n * Cycle protection on entry mirrors {@link runInline}; release runs\n * after `.result` settles so a same-callback recursion is caught\n * regardless of which path closed the cycle.\n */\n private streamInline(\n executable: StreamableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callStack: Set<string>,\n reportSink: BaseReport[],\n callerIntent: string,\n ): StreamContract<SupervisableResult> {\n const name = executable.name;\n\n if (callStack.has(name)) {\n const chain = [...callStack, name].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.stream(\"${name}\"): cycle detected (${chain})`,\n { context: { intent: name } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n callStack.add(name);\n\n return this.streamSupervisedExecutable(\n executable,\n this.coerceInlineInput(executable, input),\n options,\n callerIntent,\n reportSink,\n () => callStack.delete(name),\n );\n }\n\n /**\n * Shared wiring for both `ctx.intents.X.stream()` and\n * `ctx.stream(...)`. Subscribes to the executable's stream, re-\n * emits deltas as `supervisor.agent.streaming` under the calling\n * callback's intent name, and pushes the inner report onto the\n * reportSink once `.result` settles. The returned StreamContract\n * is the executable's own — the framework attaches handlers\n * transparently via `.on(...)`.\n */\n private streamSupervisedExecutable(\n executable: StreamableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callerIntent: string,\n reportSink: BaseReport[],\n release: () => void,\n ): StreamContract<SupervisableResult> {\n const merged = this.mergeInlineOptions(options);\n const stream = (\n executable as {\n stream: (input: unknown, options?: unknown) => StreamContract<SupervisableResult>;\n }\n ).stream(input, merged);\n\n // Bubble inner deltas under the CALLING callback's intent name.\n // Agents fire `agent.trip.streaming`; supervisors fire\n // `supervisor.agent.streaming` already — the inner intent name\n // there is the inner supervisor's specialist, which we replace\n // with the outer callback's name so attribution is consistent.\n const handlers: Record<string, (event: { delta: string }) => void> = {\n \"agent.trip.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: callerIntent,\n delta,\n });\n },\n \"supervisor.agent.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: callerIntent,\n delta,\n });\n },\n };\n\n stream.on(handlers);\n\n // Always release the cycle-protection slot after `.result` settles\n // (success OR failure) so subsequent calls in the same callback\n // see a clean stack. Push report on success.\n void stream.result.then(\n (result) => {\n if (result?.report) {\n reportSink.push(result.report);\n }\n\n release();\n },\n () => release(),\n );\n\n return stream;\n }\n\n /**\n * Build the options object passed into an inline `.execute()` /\n * `.stream()` call. Auto-merges supervisor-level defaults\n * (`signal`, `toolCtx`, `history` window) under the caller's\n * options. Per-call values REPLACE the auto-defaults — when the\n * dev passes `signal: undefined` they explicitly opt out.\n */\n private mergeInlineOptions(\n options: SupervisableExecuteOptions | undefined,\n ): SupervisableExecuteOptions {\n const supplied = (options ?? {}) as Record<string, unknown>;\n const merged: Record<string, unknown> = { ...supplied };\n\n if (!(\"signal\" in supplied)) {\n merged.signal = this.options?.signal;\n }\n\n if (!(\"toolCtx\" in supplied)) {\n merged.toolCtx = {\n artifacts: this.currentArtifacts,\n signal: this.options?.signal,\n };\n }\n\n if (!(\"history\" in supplied)) {\n const window = this.applyAgentsWindow();\n\n if (window.length > 0) {\n merged.history = window;\n }\n }\n\n return merged as SupervisableExecuteOptions;\n }\n\n /**\n * Coerce an arbitrary inline input into the shape the underlying\n * executable expects. Agents take `string`; workflows + supervisors\n * take whatever they declared. We safe-stringify objects only when\n * passing to an agent — workflow / supervisor calls hand the value\n * through unchanged so structured inputs work.\n */\n private coerceInlineInput(executable: SupervisableExecutable, input: unknown): unknown {\n // Agents are the only kind that strictly require string input.\n // Workflows / supervisors accept arbitrary shapes.\n const isAgent =\n !(\"signature\" in executable) &&\n typeof executable.execute === \"function\" &&\n !this.isSupervisor(executable);\n\n if (isAgent && typeof input !== \"string\") {\n return safeStringify(input);\n }\n\n return input;\n }\n\n /**\n * Heuristic detection of `SupervisorContract` — the contract carries\n * a `signature` getter same as workflows, but supervisors expose\n * `resume()` while workflows expose `resume(runId, options)` too.\n * Cleanest distinguisher in the public surface: supervisors carry\n * the `asTool` method name `as` … unfortunately so do workflows.\n * Use the `streamableType` brand if we add one in v2; for now lean\n * on a duck-typed check that's good enough for the ctx.run path\n * (incorrect routing for workflows would still produce a runnable\n * call — workflow.execute accepts the same args either way).\n */\n private isSupervisor(executable: SupervisableExecutable): boolean {\n return (\n typeof (executable as { resume?: unknown; signature?: unknown }).resume === \"function\" &&\n typeof (executable as { signature?: unknown }).signature === \"string\" &&\n typeof (executable as { stream?: unknown }).stream === \"function\"\n );\n }\n\n /**\n * Invoke the underlying dispatchable unit. Agents and workflows\n * both satisfy `ExecutableContract<string, …>` so the call shape\n * is uniform; the `type` discriminator picks which options get\n * threaded through (e.g. per-call stream event bubbling for\n * agents, which we wire inline so child agent tokens surface as\n * `supervisor.agent.streaming`).\n */\n private async invokeUnit(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n input: string,\n placeholders: Record<string, unknown> | undefined,\n routeContext: RouteContext,\n ): Promise<AgentResult<unknown> | WorkflowResult<unknown>> {\n // When the supervisor itself is being streamed by the caller, run\n // the child agent in streaming mode too — that's the only way\n // token deltas surface up the tree as `supervisor.agent.streaming`\n // events. `agent.execute()` always uses `model.complete()` which\n // never fires `agent.trip.streaming`, so wiring a callback there\n // is a silent no-op for tokens. Lifecycle events (trip.started /\n // tool.called / completed) still fire through `.on()` regardless\n // — they're driven by orchestration boundaries, not the wire mode.\n const isStreaming = this.streamController !== undefined;\n\n if (entry.type === \"agent\") {\n // `type` and `unit` aren't a discriminated union on the entry\n // type — narrow manually. `resolveIntentEntries` guarantees\n // `unit` matches `type` at runtime.\n const agent = entry.unit as AgentContract<unknown>;\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: entry.intent,\n delta,\n });\n },\n };\n\n // Phase 5 / decisions §34 — stream-mode intents drop the\n // structured-output schema (factory already rejects coexistence)\n // and always run via `agent.stream()` so token deltas surface as\n // `supervisor.agent.streaming` events regardless of whether the\n // top-level caller streamed the supervisor.\n const isStreamMode = entry.mode === \"stream\";\n\n // Stage 4b/4d: forward `intent.output` as the agent's per-call\n // output schema when declared. The agent then parses model\n // output as structured data; `applyOutputSchema` re-validates\n // (cheap) and strip-merges into supervisor state.\n const resolvedHistory = this.resolveHistoryFor(\"agents\", routeContext, entry.history);\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders } : {}),\n ...(entry.output && !isStreamMode ? { output: entry.output } : {}),\n ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n toolCtx: {\n artifacts: this.currentArtifacts,\n signal: this.options?.signal,\n },\n };\n\n if (isStreamMode || isStreaming) {\n const childStream = agent.stream(input, agentOptions);\n return childStream.result;\n }\n\n return agent.execute(input, agentOptions);\n }\n\n const workflow = entry.unit as WorkflowInstance<unknown, unknown>;\n\n return workflow.execute(input, {\n signal: this.options?.signal,\n on: {\n \"workflow.step.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: entry.intent,\n delta,\n });\n },\n },\n });\n }\n\n /**\n * Build the input string passed to a branch's child execution.\n * Default: pass the supervisor's original `ctx.input` through\n * unchanged. The per-intent `entry.input` override is the escape\n * hatch for the rare case where the agent's user message itself\n * must vary per intent.\n *\n * Q17 lock: dropped `composeAgentInput` + `defaultComposeAgentInput`.\n * Their three jobs (carry original / prior outputs / feedback) all\n * have cleaner homes in the new model — original is the input\n * itself, prior outputs are state (Stage 4b), feedback is a\n * router-only signal (Q18).\n */\n private resolveBranchInput(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n ctx: RouteContext,\n ): string {\n const override = entry.input?.(ctx);\n\n if (typeof override === \"string\") {\n return override;\n }\n\n // Q1: supervisor-level input may be an object payload. Agents\n // need a string — JSON-stringify when no per-intent override\n // converted it. Devs wanting a different shape supply\n // `entry.input(ctx)`.\n return typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input);\n }\n\n /**\n * Strip-merge the agent/workflow's raw output against the per-intent\n * `output` schema (Q11/Q13). Returns the validated slice that:\n *\n * 1. Lands on `IterationSnapshot.result[intent].output` (so\n * consumers see the same shape that hit state).\n * 2. Shallow-merges into `this.state` (handled by the caller).\n *\n * When `entry.output` is omitted the agent's full `data` (or `text`\n * fallback for unstructured agents) flows through unvalidated — but\n * is NOT auto-merged into state. State contribution is opt-in via\n * declaring the slice schema.\n *\n * Validation failure surfaces as a per-branch error on the\n * snapshot; sibling branches still run.\n */\n private async applyOutputSchema(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n raw: AgentResult<unknown> | WorkflowResult<unknown> | undefined,\n ): Promise<{ value: unknown; error?: AIError }> {\n if (!raw) {\n return { value: undefined };\n }\n\n const sourceValue = isAgentResult(raw)\n ? (raw.data ?? raw.text ?? undefined)\n : isWorkflowResult(raw)\n ? raw.data\n : undefined;\n\n // Phase 5 / decisions §34 — stream-mode agents have no `output`\n // schema. The assembled prose comes back as `raw.text` (the agent\n // never produced structured `data` because we dropped the schema\n // in `invokeUnit`). Wrap it as `{ [streamTo]: text }` so the\n // existing strip-merge path lands the prose under the named state\n // key without further special-casing downstream.\n if (entry.type === \"agent\" && entry.mode === \"stream\") {\n const text = typeof sourceValue === \"string\" ? sourceValue : \"\";\n\n return { value: { [entry.streamTo as string]: text } };\n }\n\n if (!entry.output) {\n return { value: sourceValue };\n }\n\n const validation = await entry.output[\"~standard\"].validate(sourceValue);\n\n if (validation.issues) {\n return {\n value: undefined,\n error: new SchemaValidationError(\n `intent \"${entry.intent}\" output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n ),\n };\n }\n\n return { value: validation.value };\n }\n\n /**\n * Fire the receptionist (`ack`) — runs in parallel with phase A on\n * iteration 0 only. Accepts three shapes:\n *\n * - `AckEntry` — `{ agent, placeholders?, input?, output? }`. LLM\n * form. Streams tokens via `supervisor.ack.streaming`; report\n * node pushes onto `childReports[]`.\n * - `AckRunEntry` — `{ run, output? }`. Pure-code callback. Settles\n * without an LLM call. No streaming events; just `.completed`.\n * - `AckCallback` — bare `(ctx) => slice` shorthand for the\n * pure-code form when no schema is declared.\n *\n * Failures are recorded but never abort the run — the receptionist\n * tripping doesn't stop the specialist from doing the actual job.\n * The returned outcome is what `mergeAckIntoState` consumes.\n */\n private async runAck(): Promise<\n | {\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }\n | undefined\n > {\n const ack = this.config.ack;\n if (!ack) return undefined;\n\n const routeContext: RouteContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n iterations: this.snapshots,\n feedback:\n typeof this.carriedFeedback?.feedback === \"string\"\n ? this.carriedFeedback.feedback\n : undefined,\n evaluateFeedback: this.carriedFeedback,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n // Bare-callback shorthand: `ack: (ctx) => slice`.\n if (typeof ack === \"function\") {\n return this.runAckCallback(\n ack as (ctx: RouteContext) => unknown | Promise<unknown>,\n undefined,\n routeContext,\n startedAt,\n startPerf,\n );\n }\n\n // Run-entry form: `ack: { run, output? }`.\n if (\"run\" in ack && typeof (ack as { run?: unknown }).run === \"function\") {\n const runEntry = ack as {\n run: (ctx: RouteContext) => unknown | Promise<unknown>;\n output?: StandardSchemaV1<unknown>;\n };\n return this.runAckCallback(runEntry.run, runEntry.output, routeContext, startedAt, startPerf);\n }\n\n // Agent-entry form: `ack: { agent, placeholders?, input?, output? }`.\n return this.runAckAgent(\n ack as {\n agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n input?: (ctx: RouteContext) => string;\n output?: StandardSchemaV1<unknown>;\n history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n },\n routeContext,\n startedAt,\n startPerf,\n );\n }\n\n /**\n * Pure-code receptionist path — invokes the callback, strip-validates\n * the return value (when an `output` schema is declared), records the\n * snapshot, emits `supervisor.ack.completed`, returns the outcome.\n * No streaming events fire (callbacks settle synchronously from the\n * supervisor's POV).\n */\n private async runAckCallback(\n run: (ctx: RouteContext) => unknown | Promise<unknown>,\n output: StandardSchemaV1<unknown> | undefined,\n routeContext: RouteContext,\n startedAt: Date,\n startPerf: number,\n ): Promise<{\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }> {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n let validatedOutput: unknown;\n let ackError: AIError | undefined;\n\n try {\n const raw = await run(routeContext);\n\n if (output) {\n const validation = await output[\"~standard\"].validate(raw);\n if (validation.issues) {\n ackError = new SchemaValidationError(\n `ack output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n } else {\n validatedOutput = validation.value;\n }\n } else {\n validatedOutput = raw;\n }\n } catch (thrown) {\n ackError = toAIError(thrown);\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n this.ackSnapshot = Object.freeze({\n input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n output: validatedOutput,\n usage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: ackError,\n });\n\n this.emit(\"supervisor.ack.completed\", {\n output: validatedOutput,\n usage,\n duration,\n error: ackError,\n });\n\n return { output: validatedOutput, usage, duration, error: ackError };\n }\n\n /**\n * Agent-driven receptionist path — invokes the agent, streams tokens\n * via `supervisor.ack.streaming`, captures the report node, strip-\n * validates against `output` (when declared), records the snapshot,\n * emits `supervisor.ack.completed`.\n */\n private async runAckAgent(\n ack: {\n agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n input?: (ctx: RouteContext) => string;\n output?: StandardSchemaV1<unknown>;\n history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n },\n routeContext: RouteContext,\n startedAt: Date,\n startPerf: number,\n ): Promise<{\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }> {\n const placeholders = ack.placeholders?.(routeContext);\n const inputForAck =\n ack.input?.(routeContext) ??\n (typeof this.input === \"string\" ? this.input : safeStringify(this.input));\n\n const isStreaming = this.streamController !== undefined;\n\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.ack.streaming\", { delta });\n },\n };\n\n const resolvedHistory = this.resolveHistoryFor(\"ack\", routeContext, ack.history);\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders } : {}),\n ...(ack.output ? { output: ack.output } : {}),\n ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n };\n\n let rawResult: AgentResult<unknown> | undefined;\n let ackError: AIError | undefined;\n let usage: Usage = { input: 0, output: 0, total: 0 };\n\n try {\n if (isStreaming) {\n const childStream = ack.agent.stream(inputForAck, agentOptions);\n rawResult = await childStream.result;\n } else {\n rawResult = await ack.agent.execute(inputForAck, agentOptions);\n }\n\n if (rawResult.error) {\n ackError = rawResult.error;\n }\n\n usage = rawResult.usage ?? usage;\n\n // Ack agent's report node in the supervisor's recursive tree.\n if (rawResult.report) {\n this.childReports.push(rawResult.report);\n }\n } catch (thrown) {\n ackError = toAIError(thrown);\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n // Strip-validate against `ack.output` (when declared) — same\n // contract as per-intent output schemas.\n let validatedOutput: unknown;\n if (rawResult && !ackError && ack.output) {\n const sourceValue = rawResult.data ?? rawResult.text ?? undefined;\n const validation = await ack.output[\"~standard\"].validate(sourceValue);\n if (validation.issues) {\n ackError = new SchemaValidationError(\n `ack output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n } else {\n validatedOutput = validation.value;\n }\n } else if (rawResult && !ackError) {\n validatedOutput = rawResult.data ?? rawResult.text ?? undefined;\n }\n\n this.ackSnapshot = Object.freeze({\n input: inputForAck,\n output: validatedOutput,\n usage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: ackError,\n });\n\n this.emit(\"supervisor.ack.completed\", {\n output: validatedOutput,\n usage,\n duration,\n error: ackError,\n });\n\n return { output: validatedOutput, usage, duration, error: ackError };\n }\n\n /**\n * Probe the ack promise non-blockingly. Yields one macrotask cycle\n * (`setImmediate`) so an already-resolved ack wins via microtask\n * priority; if the probe returns first, the slice is abandoned —\n * warning logged, error captured on `report.ack`, run completes\n * regardless. Specialists own the actual answer; the receptionist\n * was just a reassuring preview.\n */\n private async settleAck(\n ackPromise:\n | Promise<{ output: unknown; usage: Usage; duration: number; error?: AIError } | undefined>\n | undefined,\n iterationUsage: Usage,\n ): Promise<void> {\n if (!ackPromise) return;\n\n const NOT_READY = Symbol(\"ack-not-ready\");\n const probe = await Promise.race([\n ackPromise,\n new Promise<typeof NOT_READY>((resolve) => setTimeout(() => resolve(NOT_READY), 0)),\n ]);\n\n if (probe === NOT_READY) {\n this.logger.warn(\n this.logModule,\n \"ack.abandoned\",\n \"ack receptionist did not settle before iteration completed; slice dropped\",\n );\n const abandonedAt = new Date();\n this.ackSnapshot = Object.freeze({\n input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n output: undefined,\n usage: { input: 0, output: 0, total: 0 },\n startedAt: abandonedAt.toISOString(),\n endedAt: abandonedAt.toISOString(),\n duration: 0,\n error: new SupervisorFailedError(\n \"ack receptionist did not settle before iteration completed\",\n { context: { ackAbandoned: true } },\n ),\n });\n return;\n }\n\n const ackOutcome = probe;\n if (ackOutcome) {\n this.aggregateUsage(iterationUsage, ackOutcome.usage);\n this.mergeAckIntoState(ackOutcome);\n }\n }\n\n /**\n * Merge the receptionist's strip-validated slice into state. Called\n * from `settleAck` BEFORE branch merges so specialists override the\n * receptionist on key collision — the receptionist hedges, the\n * specialist commits.\n */\n private mergeAckIntoState(ackOutcome: { output: unknown; error?: AIError }): void {\n if (ackOutcome.error || !ackOutcome.output) return;\n\n if (typeof ackOutcome.output !== \"object\" || ackOutcome.output === null) return;\n\n const slice = ackOutcome.output as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(slice)) {\n this.state[key] = value;\n }\n }\n\n /**\n * Run the iter-0 classifier prelude (Phase 7 / decisions §37).\n * Resolves the configured classifier (agent / callback / entry\n * form), invokes it, runs the optional `refine` post-process hook,\n * and either:\n *\n * - sets `carriedClassifierDispatch` so the upcoming\n * `decideDispatch` short-circuits to the chosen intent, OR\n * - sets `classifierHalted = true` so `runIteration` terminates\n * before any dispatch (refine returned `END`).\n *\n * Captures the full forensic record on `classifierSnapshot` —\n * surfaced on `SupervisorReport.classifier` and threaded into\n * `ctx.classifier` on every downstream context.\n *\n * Errors in the classifier OR the refine hook abort the run with\n * a `SupervisorFailedError` so issues surface loudly instead of\n * silently falling through to router/route.\n */\n private async runClassifier(): Promise<void> {\n const startedAt = new Date();\n const startPerf = performance.now();\n const startedAtIso = startedAt.toISOString();\n\n this.emit(\"supervisor.classifier.starting\", { iteration: 0 });\n\n const ctx = this.buildClassifierContext();\n const config = this.config.classifier as ClassifierConfig;\n\n let raw: ClassifierOutput | undefined;\n let usage: Usage = { input: 0, output: 0, total: 0 };\n let executionError: AIError | undefined;\n\n try {\n const outcome = await this.invokeClassifier(config, ctx);\n raw = outcome.output;\n usage = outcome.usage;\n } catch (thrown) {\n executionError = toAIError(thrown);\n }\n\n if (executionError || !raw) {\n const error =\n executionError ??\n new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier produced no output`,\n { context: { iteration: 0 } },\n );\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw: raw ?? { intent: \"\" },\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n // Classifier failure aborts the run — no fallback to router/route.\n // Phase 7 / decisions §37.\n throw error;\n }\n\n // Validate the classifier's chosen intent against the registry\n // before running refine — refine may override, but we still want\n // to fail fast on raw classifier output that targets nothing.\n if (!this.entries.has(raw.intent)) {\n const error = new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier picked unknown intent \"${raw.intent}\" — must be a key in \\`intents\\``,\n { context: { iteration: 0, available: [...this.entries.keys()] } },\n \"SUPERVISOR_INVALID_ROUTE\",\n );\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n // Refine pass — optional. Refine receives the classifier output\n // on `ctx.result.data` plus `run` / `stream` for inline secondary\n // classifiers. Returns: undefined (use as-is) | END (halt) |\n // { intent?, ...slice } (override + merge).\n const refineHook = this.resolveRefineHook(config);\n let final: ClassifierOutput = raw;\n let refined = false;\n let halted = false;\n\n if (refineHook) {\n let refineResult: ClassifierRefineResult;\n\n try {\n refineResult = await refineHook(this.buildClassifierRefineContext(ctx, raw));\n } catch (thrown) {\n const error = toAIError(thrown);\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n const interpretation = this.interpretRefineResult(refineResult, raw);\n\n if (interpretation.error) {\n this.classifierSnapshot = {\n intent: undefined,\n refined: true,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error: interpretation.error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error: interpretation.error });\n\n throw interpretation.error;\n }\n\n refined = interpretation.refined;\n halted = interpretation.halted;\n final = interpretation.final ?? raw;\n\n // Merge refine's slice into state BEFORE dispatching — refine\n // can augment state (e.g. detected language) regardless of\n // override-vs-keep decision.\n if (interpretation.sliceToMerge) {\n for (const [key, value] of Object.entries(interpretation.sliceToMerge)) {\n this.state[key] = value;\n }\n }\n }\n\n // Always merge the (possibly refined) classifier output's\n // remaining fields into state — universal locked fields (intent,\n // reasoning, confidence) plus any dev-extended fields. Subject\n // to the supervisor's `output` schema validation at finalize.\n for (const [key, value] of Object.entries(final)) {\n this.state[key] = value;\n }\n\n this.classifierSnapshot = {\n intent: halted ? undefined : final.intent,\n reasoning: final.reasoning,\n confidence: final.confidence,\n refined,\n halted,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.completed\", {\n output: {\n intent: this.classifierSnapshot.intent,\n reasoning: this.classifierSnapshot.reasoning,\n confidence: this.classifierSnapshot.confidence,\n },\n intent: this.classifierSnapshot.intent,\n refined,\n halted,\n duration: this.classifierSnapshot.duration,\n usage,\n });\n\n if (halted) {\n this.classifierHalted = true;\n\n return;\n }\n\n // Validate the FINAL intent against the registry — refine may\n // have overridden to an unknown name. Throw loudly.\n if (!this.entries.has(final.intent)) {\n const error = new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier.refine returned unknown intent \"${final.intent}\" — must be a key in \\`intents\\``,\n { context: { iteration: 0, available: [...this.entries.keys()] } },\n \"SUPERVISOR_INVALID_ROUTE\",\n );\n\n this.classifierSnapshot = { ...this.classifierSnapshot, halted: true, error };\n this.classifierHalted = true;\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n this.carriedClassifierDispatch = { intent: final.intent };\n }\n\n /**\n * Resolve the configured classifier into a callable that returns\n * `{ output, usage }`. Handles the four accepted shapes — bare\n * agent / bare callback / agent-entry / run-entry. Pure shape\n * normalization; no side effects.\n */\n private async invokeClassifier(\n config: ClassifierConfig,\n ctx: ClassifierContext,\n ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n // (a) Bare callback shorthand.\n if (typeof config === \"function\") {\n const output = await (\n config as (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput\n )(ctx);\n\n return { output, usage: { input: 0, output: 0, total: 0 } };\n }\n\n // (b) Run-entry — `{ run, refine? }`.\n if (typeof (config as { run?: unknown }).run === \"function\") {\n const runFn = (\n config as { run: (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput }\n ).run;\n const output = await runFn(ctx);\n\n return { output, usage: { input: 0, output: 0, total: 0 } };\n }\n\n // (c) Agent-entry — `{ agent, placeholders?, input?, history?, refine? }`.\n if (typeof (config as { agent?: { execute?: unknown } }).agent?.execute === \"function\") {\n const entry = config as {\n agent: AgentContract<unknown>;\n placeholders?: (ctx: ClassifierContext) => Record<string, unknown>;\n input?: (ctx: ClassifierContext) => string;\n history?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>;\n };\n\n return this.invokeClassifierAgent(\n entry.agent,\n ctx,\n entry.placeholders,\n entry.input,\n entry.history,\n );\n }\n\n // (d) Bare agent shorthand.\n if (typeof (config as { execute?: unknown }).execute === \"function\") {\n return this.invokeClassifierAgent(config as AgentContract<unknown>, ctx);\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): \\`classifier\\` is not an agent, callback, or entry object`,\n { context: { authoring: true } },\n );\n }\n\n /**\n * Invoke a classifier agent with the supervisor's standard wiring\n * — placeholders, input override, history slicing, signal,\n * streaming bubble. Output schema validation belongs to the agent\n * itself; we just pull the typed `data` (or fall back to parsing\n * `text`) and assert the locked `intent` field.\n */\n private async invokeClassifierAgent(\n agent: AgentContract<unknown>,\n ctx: ClassifierContext,\n placeholders?: (ctx: ClassifierContext) => Record<string, unknown>,\n inputResolver?: (ctx: ClassifierContext) => string,\n historySlicer?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>,\n ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n const inputForAgent =\n inputResolver?.(ctx) ??\n (typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input));\n\n const history = historySlicer ? [...historySlicer(ctx)] : this.applyAgentsWindow();\n\n const isStreaming = this.streamController !== undefined;\n\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.classifier.streaming\", { delta });\n },\n };\n\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders: placeholders(ctx) } : {}),\n ...(history.length > 0 ? { history } : {}),\n };\n\n let result: AgentResult<unknown>;\n\n if (isStreaming) {\n result = await agent.stream(inputForAgent, agentOptions).result;\n } else {\n result = await agent.execute(inputForAgent, agentOptions);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n if (result.report) {\n this.childReports.push(result.report);\n }\n\n const data = result.data ?? result.text ?? undefined;\n const output = this.coerceClassifierOutput(data);\n\n return { output, usage: result.usage };\n }\n\n /**\n * Coerce an agent's output into the locked classifier shape.\n * Accepts a typed object with `intent` (the canonical case) or a\n * plain string (interpreted as the intent name with no reasoning).\n * Throws `SupervisorFailedError` if neither shape matches.\n */\n private coerceClassifierOutput(data: unknown): ClassifierOutput {\n if (typeof data === \"string\") {\n return { intent: data };\n }\n\n if (\n data &&\n typeof data === \"object\" &&\n typeof (data as { intent?: unknown }).intent === \"string\"\n ) {\n const record = data as Record<string, unknown>;\n\n return {\n intent: record.intent as string,\n reasoning: typeof record.reasoning === \"string\" ? (record.reasoning as string) : undefined,\n confidence:\n typeof record.confidence === \"number\" ? (record.confidence as number) : undefined,\n };\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier output missing required \\`intent\\` field — got ${JSON.stringify(data)?.slice(0, 200)}`,\n { context: { iteration: 0 } },\n );\n }\n\n /**\n * Build the read-only context passed to a classifier callback / agent\n * resolvers. No dispatch helpers — registered intents haven't fired\n * yet; pre-running them from the classifier would be confusing.\n */\n private buildClassifierContext(): ClassifierContext {\n return {\n iteration: 0,\n input: this.input,\n state: this.state,\n context: this.context,\n history: this.history,\n signal: this.options?.signal ?? new AbortController().signal,\n goal: this.goal,\n };\n }\n\n /**\n * Build the refine context — extends ClassifierContext with the\n * classifier's just-resolved output plus `run` / `stream` so the\n * refine hook can spin up secondary classifiers / validators\n * inline (Phase 6 features).\n */\n private buildClassifierRefineContext(\n base: ClassifierContext,\n raw: ClassifierOutput,\n ): ClassifierRefineContext {\n const callStack = new Set<string>();\n const reportSink = this.childReports;\n\n return {\n ...base,\n result: { data: raw },\n run: (executable, runInput, runOptions) =>\n this.runInline(executable, runInput, runOptions, callStack, reportSink),\n stream: (executable, runInput, runOptions) =>\n this.streamInline(executable, runInput, runOptions, callStack, reportSink, \"classifier\"),\n };\n }\n\n /**\n * Pull the optional `refine` hook off whichever classifier-config\n * shape was supplied. Bare-callback and bare-agent forms have no\n * refine; only entry forms do.\n */\n private resolveRefineHook(\n config: ClassifierConfig,\n ):\n | ((ctx: ClassifierRefineContext) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n | undefined {\n if (typeof config === \"function\") {\n return undefined;\n }\n\n const refine = (config as { refine?: unknown }).refine;\n\n return typeof refine === \"function\"\n ? (refine as (\n ctx: ClassifierRefineContext,\n ) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n : undefined;\n }\n\n /**\n * Interpret a refine return value into actionable bits — final\n * classifier output to dispatch, slice-to-merge, halted/refined\n * flags, or an error. See {@link ClassifierRefineResult} for the\n * accepted shapes.\n */\n private interpretRefineResult(\n refineResult: ClassifierRefineResult,\n raw: ClassifierOutput,\n ): {\n final?: ClassifierOutput;\n sliceToMerge?: Record<string, unknown>;\n refined: boolean;\n halted: boolean;\n error?: AIError;\n } {\n if (refineResult === undefined) {\n return { final: raw, refined: false, halted: false };\n }\n\n if (refineResult === END) {\n return { refined: true, halted: true };\n }\n\n if (typeof refineResult !== \"object\" || refineResult === null) {\n return {\n refined: false,\n halted: true,\n error: new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier.refine returned an unsupported value — expected undefined, END, or an object`,\n { context: { iteration: 0 } },\n ),\n };\n }\n\n const record = refineResult as Record<string, unknown>;\n const intentField = record.intent;\n const halted = intentField === END;\n const intentOverride = typeof intentField === \"string\" ? intentField : undefined;\n\n // Slice-to-merge is the refine return MINUS the `intent` field\n // (which is dispatch metadata, not state contribution).\n const slice: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n if (key === \"intent\") continue;\n\n slice[key] = value;\n }\n\n const final: ClassifierOutput = {\n ...raw,\n ...(intentOverride ? { intent: intentOverride } : {}),\n };\n\n return {\n final: halted ? undefined : final,\n sliceToMerge: Object.keys(slice).length > 0 ? slice : undefined,\n refined: true,\n halted,\n };\n }\n\n /**\n * Run the `evaluate` callback (when configured) after the\n * iteration's branches settle and outputs have merged into state.\n * Errors in the callback surface as `SupervisorFailedError` so a\n * buggy evaluate doesn't silently swallow the whole run.\n *\n * Phase 3.4 (Stage 4b) — `EvaluateContext.state` carries the\n * post-merge accumulator so verdicts can be state-aware. Q9\n * lifted the router-only restriction; evaluate now runs in both\n * router and route modes.\n */\n private async runEvaluate(branches: AgentBranchSnapshot[]): Promise<EvaluateResult> {\n if (!this.config.evaluate) {\n return undefined;\n }\n\n const evaluateContext: EvaluateContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n result: indexBranchesForEvaluate(branches),\n iterations: this.snapshots,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n try {\n return await (\n this.config.evaluate as (ctx: EvaluateContext) => EvaluateResult | Promise<EvaluateResult>\n )(evaluateContext);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n throw new SupervisorFailedError(`evaluate callback threw: ${message}`, {\n cause: thrown,\n });\n }\n }\n\n /**\n * Merge each branch's output into supervisor `state` in\n * `decision.intents` order — Q15 conflict rule: last intent in\n * the array wins on key collisions. Errored branches don't\n * contribute. Non-object outputs (primitives, null) are skipped\n * with a warning log; they can't shallow-merge into an object.\n *\n * For agent/workflow intents: merging is opt-in via declaring an\n * `output` schema (the strip-merge gate). Without a schema, the\n * raw output stays on the branch snapshot but doesn't pollute\n * state. For callback intents: their return is already strip-merged\n * (or pass-through) inside `runCallback` — we just merge what's on\n * the branch snapshot.\n */\n private mergeBranchesIntoState(intentsOrder: string[], branches: AgentBranchSnapshot[]): void {\n const indexed = new Map<string, AgentBranchSnapshot>();\n for (const branch of branches) {\n indexed.set(branch.intent, branch);\n }\n\n const mergedKeys = new Map<string, string>();\n\n for (const intent of intentsOrder) {\n const branch = indexed.get(intent);\n if (!branch || branch.error) continue;\n\n const entry = this.entries.get(intent);\n\n // For agent/workflow intents, only merge when the slice schema\n // was declared (output present on the entry). For callbacks,\n // their output is always merged (the schema, if any, was\n // applied inside runCallback). Stream-mode agents (Phase 5 /\n // decisions §34) merge unconditionally — `applyOutputSchema`\n // already shaped their slice as `{ [streamTo]: text }`, and\n // they have no `output` schema by construction.\n const isStreamModeAgent = entry?.type === \"agent\" && entry.mode === \"stream\";\n const shouldMerge =\n entry?.type === \"callback\" || (entry && entry.output !== undefined) || isStreamModeAgent;\n\n if (!shouldMerge) continue;\n\n const slice = branch.output;\n\n if (!slice || typeof slice !== \"object\" || Array.isArray(slice)) {\n if (slice !== undefined) {\n this.logger.warn(\n this.logModule,\n \"state.merge.skip\",\n `intent \"${intent}\" output is not a mergeable object — skipping state merge`,\n { intent, type: typeof slice },\n );\n }\n continue;\n }\n\n for (const [key, value] of Object.entries(slice as Record<string, unknown>)) {\n const previousOwner = mergedKeys.get(key);\n if (previousOwner !== undefined && previousOwner !== intent) {\n this.logger.warn(\n this.logModule,\n \"state.merge.conflict\",\n `state key \"${key}\" written by both \"${previousOwner}\" and \"${intent}\" — last-in-decision-array wins (Q15)`,\n { key, previousOwner, currentIntent: intent },\n );\n }\n this.state[key] = value;\n mergedKeys.set(key, intent);\n }\n }\n }\n\n /**\n * Merge the iteration's accumulated `currentArtifacts` bag into\n * supervisor state (Phase 5 / decisions §35). Runs once per\n * iteration after branch slices land and before evaluate.\n *\n * Order of operations:\n *\n * 1. **Empty-bag fast path** — if no tool wrote anything, skip\n * validation and merge entirely; reset the bag for the next\n * iteration is also a no-op (already empty).\n * 2. **Schema validation** — when `config.artifactsSchema` is set,\n * validate the bag against it. Failure aborts the iteration via\n * a thrown `SchemaValidationError`; the iteration loop's outer\n * catch surfaces it on `result.error`. Validation is opt-in\n * (no schema → no validation cost).\n * 3. **Merge** — `config.finalizeArtifacts` when supplied, else\n * auto-spread `state = { ...state, ...artifacts }`. Replace\n * semantics under auto-spread; `finalizeArtifacts` carries\n * full responsibility for concat / dedupe / cross-iteration\n * accumulation when configured.\n * 4. **Reset** — `currentArtifacts = {}`. The next iteration's\n * tool calls start with a fresh empty bag; long runs never\n * accumulate raw artifacts here.\n */\n private async mergeArtifactsIntoState(): Promise<void> {\n const artifacts = this.currentArtifacts;\n const keys = Object.keys(artifacts);\n\n // Phase 8 / decisions §38 — capture the raw bag BEFORE validation\n // or merge so the iteration snapshot surfaces what the tools\n // actually wrote, regardless of what `finalizeArtifacts` did with\n // it. Frozen — consumers should never mutate forensic data.\n // Always run, even on empty bags — snapshot builder reads\n // `capturedIterationArtifacts` regardless.\n this.capturedIterationArtifacts = Object.freeze({ ...artifacts });\n\n if (keys.length === 0) {\n return;\n }\n\n const schema = this.config.artifactsSchema;\n\n if (schema) {\n const validation = await schema[\"~standard\"].validate(artifacts);\n\n if (validation.issues) {\n throw new SchemaValidationError(\n `supervisor \"${this.config.name}\": iteration ${this.iteration} artifacts failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues, context: { iteration: this.iteration } },\n );\n }\n }\n\n const finalize = this.config.finalizeArtifacts as\n | ((\n state: Record<string, unknown>,\n artifacts: Record<string, unknown>,\n ) => Record<string, unknown>)\n | undefined;\n\n if (finalize) {\n const merged = finalize(this.state, artifacts);\n\n // Mutate in place so external references to `this.state`\n // (snapshot copies, evaluate ctx) stay coherent. Drop keys\n // the finalize callback removed; overwrite the rest.\n for (const key of Object.keys(this.state)) {\n if (!(key in merged)) {\n delete this.state[key];\n }\n }\n\n for (const [key, value] of Object.entries(merged)) {\n this.state[key] = value;\n }\n } else {\n for (const [key, value] of Object.entries(artifacts)) {\n this.state[key] = value;\n }\n }\n\n this.currentArtifacts = {};\n }\n\n /**\n * Collect each branch's `intent.next(ctx)` directive after state\n * merge (Stage 4d / Q24). Iterates `decision.intents` order so\n * union resolution is deterministic.\n *\n * Rules:\n * - Errored branch → silent (treated as if no `next` defined).\n * - Branch with no `next` → silent; abstains (does NOT drag the\n * iteration to the router).\n * - Branch returns `END` → supreme; terminates immediately and\n * discards other branches' opinions.\n * - Branch returns `string` or `string[]` → contributes to the\n * union of unique intent names. Validated against the\n * supervisor's registry; unknown keys throw `SupervisorFailedError`.\n * - All branches silent → returns `undefined`; caller falls back\n * to router/route.\n */\n private collectIntentNext(\n intentsOrder: string[],\n branches: AgentBranchSnapshot[],\n ): { kind: \"dispatch\"; intents: string[] } | { kind: \"end\" } | undefined {\n const indexed = new Map<string, AgentBranchSnapshot>();\n for (const branch of branches) {\n indexed.set(branch.intent, branch);\n }\n\n const collected: string[] = [];\n const seen = new Set<string>();\n let anySilent = false;\n\n for (const intent of intentsOrder) {\n const branch = indexed.get(intent);\n if (!branch || branch.error) {\n anySilent = true;\n continue;\n }\n\n const entry = this.entries.get(intent);\n if (!entry?.next) {\n anySilent = true;\n continue;\n }\n\n // Build a per-branch DispatchContext for the resolver. Cycle\n // stack is fresh-and-self-seeded so a `next` that calls\n // `ctx.intents.X.execute()` reuses the per-iteration cycle\n // detection mechanic.\n const dispatchCtx = this.seedDispatchContext(\n intent,\n branch.input,\n new Set<string>([intent]),\n [],\n );\n\n let raw: string | string[] | typeof END | undefined;\n try {\n raw = entry.next(dispatchCtx) as string | string[] | typeof END | undefined;\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n throw new SupervisorFailedError(`intent \"${intent}\" \\`next\\` resolver threw: ${message}`, {\n cause: thrown,\n context: { intent },\n });\n }\n\n if (raw === undefined) {\n anySilent = true;\n continue;\n }\n\n if (raw === END) {\n return { kind: \"end\" };\n }\n\n const proposed = Array.isArray(raw) ? raw : [raw];\n\n for (const target of proposed) {\n if (typeof target !== \"string\") {\n throw new SupervisorFailedError(\n `intent \"${intent}\" \\`next\\` returned a non-string value`,\n { context: { intent } },\n );\n }\n\n if (!this.entries.has(target)) {\n throw new SupervisorFailedError(\n `intent \"${intent}\" \\`next\\` returned unknown intent \"${target}\"`,\n {\n context: { intent, target, available: [...this.entries.keys()] },\n },\n );\n }\n\n if (!seen.has(target)) {\n seen.add(target);\n collected.push(target);\n }\n }\n }\n\n void anySilent;\n\n if (collected.length === 0) {\n // No branch directed the next iteration — fall back to router.\n return undefined;\n }\n\n return { kind: \"dispatch\", intents: collected };\n }\n\n /**\n * Finalize the supervisor result: validate accumulated state\n * against the output schema and build the public `SupervisorResult`.\n * Assemble-only — event emission and stream close happen in\n * `run()` around this call.\n */\n private async finalize(): Promise<SupervisorResult<TOutput>> {\n if (this.status === \"completed\" && !this.error) {\n try {\n this.data = await this.buildTypedData();\n } catch (thrown) {\n this.error = toAIError(thrown);\n this.status = \"failed\";\n this.terminatedBy = \"error\";\n }\n }\n\n const endedAt = new Date();\n\n const finalStatus: SupervisorSnapshotStatus =\n this.status === \"max-iterations\" ? \"failed\" : this.status;\n\n await this.checkpoint(finalStatus);\n\n const report: SupervisorReport = {\n runId: this.runId,\n rootRunId: this.runId,\n name: this.config.name,\n version: this.config.version,\n type: \"supervisor\",\n supervisorName: this.config.name,\n signature: this.signature,\n status: this.status,\n terminatedBy: this.terminatedBy,\n iterations: this.snapshots.length,\n startedAt: this.startedAtIso,\n endedAt: endedAt.toISOString(),\n duration: performance.now() - this.startPerf,\n cancelledAt: this.cancelledAtIso,\n usage: this.usage,\n children: this.childReports,\n snapshots: this.snapshots,\n ack: this.ackSnapshot,\n classifier: this.classifierSnapshot,\n };\n\n // Stamp lineage on the assembled tree exactly once per run.\n // Walker rewrites inner self-roots from every nested agent /\n // workflow / callback report the supervisor absorbed, propagates\n // sessionId, and writes `reportSchemaVersion` on the root.\n stampReportLineage(report, {\n rootRunId: this.runId,\n sessionId: this.options?.sessionId,\n });\n\n return {\n type: \"supervisor\",\n data: this.data,\n report,\n usage: this.usage,\n error: this.error,\n };\n }\n\n /**\n * Build the typed `data` at finalize. Stage 4c — single mode:\n *\n * - When `config.output` is declared, validate the accumulated\n * `state` against it and return the validated value (Q8).\n * `result.data` always matches the schema, or `result.error`\n * carries the validation issues.\n * - When `config.output` is omitted, return the raw state object.\n *\n * Validation failure surfaces as `SchemaValidationError` on\n * `result.error`; the run is still considered semantically\n * \"completed\" (intents ran, evaluate said done) but the typed\n * data slot is empty.\n */\n private async buildTypedData(): Promise<TOutput | undefined> {\n if (this.config.output) {\n return validateOutput<TOutput>(this.config.output, this.state as unknown);\n }\n\n return this.state as TOutput;\n }\n\n /**\n * Record a snapshot for an iteration whose first decision was\n * `END` — no dispatch, no evaluate, just the decision record. Keeps\n * the snapshot log uniform so a late-route-to-END still appears in\n * the forensic history rather than vanishing.\n */\n private async recordTerminalDecisionSnapshot(\n decision: DispatchDecision & { kind: \"end\" },\n iterationStartedAt: Date,\n iterationStart: number,\n iterationUsage: Usage,\n ): Promise<void> {\n const snapshot: IterationSnapshot = Object.freeze({\n iteration: this.iteration,\n result: {},\n decision: {\n source: decision.source,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n },\n state: { ...this.state },\n artifacts: this.capturedIterationArtifacts,\n startedAt: iterationStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - iterationStart,\n usage: iterationUsage,\n });\n\n this.snapshots.push(snapshot);\n\n this.emit(\"supervisor.iteration.completed\", {\n iteration: this.iteration,\n snapshot,\n });\n\n await this.checkpoint(\"running\");\n }\n\n /**\n * Write the current run state to the configured KV store (if any).\n * Persistence failures surface as `supervisor.error` events and\n * logged warnings but never abort the run — checkpoint best-effort\n * by design, matching `workflow` semantics.\n */\n private async checkpoint(status: SupervisorSnapshotStatus): Promise<void> {\n const outcome = await persistSupervisorSnapshot({\n config: this.config as SupervisorConfig<unknown>,\n signature: this.signature,\n runId: this.runId,\n input: this.input,\n startedAt: this.startedAtIso,\n iteration: this.snapshots.length - 1,\n snapshots: this.snapshots,\n status,\n });\n\n if (!outcome.ok) {\n this.logger.warn(this.logModule, \"persist.failed\", \"snapshot persist failed\", {\n runId: this.runId,\n });\n }\n }\n\n /**\n * Between-iteration cancellation check. Called at the top of\n * every iteration; signal abort here means the loop exits before\n * any routing happens.\n */\n private throwIfCancelled(): void {\n if (this.options?.signal?.aborted) {\n throw createCancelledError(this.options.signal);\n }\n }\n\n /**\n * Aggregate one usage record (typically a branch or a router call)\n * into both the run-wide total and the iteration-local total.\n */\n private aggregateUsage(iterationUsage: Usage, partial?: Usage): void {\n if (!partial) {\n return;\n }\n\n this.usage.input += partial.input;\n this.usage.output += partial.output;\n this.usage.total += partial.total;\n\n iterationUsage.input += partial.input;\n iterationUsage.output += partial.output;\n iterationUsage.total += partial.total;\n }\n\n /**\n * Fan an event out through the three-tier emitter AND mirror it\n * into the stream controller when streaming. Event names map 1:1\n * to stream event types so consumers iterating the stream see the\n * exact same surface as `.on()` / `options.on` handlers.\n */\n private emit<K extends keyof SupervisorEventMap>(\n event: K,\n payload: WithoutIdentity<SupervisorEventMap[K]>,\n ): void {\n // Inject run identity once, here, so the three-tier emitter, the\n // structured log line, and the stream all see it. `rootRunId ===\n // runId` for a standalone run; nested propagation is a follow-up.\n const identity: EventIdentity = {\n runId: this.runId,\n rootRunId: this.runId,\n };\n\n const fullPayload = { ...payload, ...identity } as SupervisorEventMap[K];\n\n this.emitter.emit(event, fullPayload, this.options?.on);\n this.logEvent(event, fullPayload);\n\n if (this.streamController) {\n this.streamController.push({\n type: event,\n ...(fullPayload as object),\n } as SupervisorStreamEvent);\n }\n }\n\n private logEvent<K extends keyof import(\"../contracts/events/event-map.type\").SupervisorEventMap>(\n event: K,\n payload: import(\"../contracts/events/event-map.type\").SupervisorEventMap[K],\n ): void {\n const action = event.replace(/^supervisor\\./, \"\");\n\n switch (event) {\n case \"supervisor.starting\":\n this.logger.info(this.logModule, action, \"supervisor starting\", {\n runId: this.runId,\n });\n return;\n\n case \"supervisor.iteration.starting\":\n this.logger.debug(this.logModule, action, \"iteration starting\", {\n iteration: (payload as { iteration: number }).iteration,\n });\n return;\n\n case \"supervisor.router.decided\":\n this.logger.debug(this.logModule, action, \"router decided\", {\n iteration: (payload as { iteration: number }).iteration,\n next: (payload as { next: unknown }).next,\n });\n return;\n\n case \"supervisor.agent.completed\": {\n const typed = payload as {\n intent: string;\n duration: number;\n usage: Usage;\n };\n this.logger.success(this.logModule, action, `branch \"${typed.intent}\" done`, {\n duration: typed.duration,\n usage: typed.usage,\n });\n return;\n }\n\n case \"supervisor.agent.failed\": {\n const typed = payload as { intent: string; error: AIError };\n this.logger.warn(this.logModule, action, `branch \"${typed.intent}\" failed`, {\n code: typed.error.code,\n message: typed.error.message,\n });\n return;\n }\n\n case \"supervisor.error\": {\n const { error } = payload as { error: AIError };\n this.logger.error(this.logModule, action, error.message, {\n code: error.code,\n });\n return;\n }\n\n case \"supervisor.cancelled\": {\n const typed = payload as { cancelledAt: string; reason?: string };\n this.logger.warn(this.logModule, action, \"supervisor cancelled\", {\n cancelledAt: typed.cancelledAt,\n reason: typed.reason,\n });\n return;\n }\n\n case \"supervisor.iteration.completed\":\n this.logger.debug(this.logModule, action, \"iteration completed\", {\n iteration: (payload as { iteration: number }).iteration,\n });\n return;\n\n default:\n // Streaming / per-branch starting events are high-volume — no\n // dedicated log line.\n return;\n }\n }\n}\n\nfunction indexByIntent(branches: AgentBranchSnapshot[]): Record<string, AgentBranchSnapshot> {\n const indexed: Record<string, AgentBranchSnapshot> = {};\n\n for (const branch of branches) {\n indexed[branch.intent] = branch;\n }\n\n return indexed;\n}\n\nfunction indexBranchesForEvaluate(\n branches: AgentBranchSnapshot[],\n): Record<string, EvaluateBranchResult> {\n const indexed: Record<string, EvaluateBranchResult> = {};\n\n for (const branch of branches) {\n indexed[branch.intent] = {\n output: branch.output,\n input: branch.input,\n usage: branch.usage,\n durationMs: branch.duration,\n error: branch.error,\n };\n }\n\n return indexed;\n}\n\nfunction normalizeReassign(reassignTo: string | string[] | undefined): string[] {\n if (!reassignTo) {\n return [];\n }\n\n if (Array.isArray(reassignTo)) {\n return reassignTo;\n }\n\n return [reassignTo];\n}\n\nfunction toAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new SupervisorFailedError(message, { cause: thrown });\n}\n\n/**\n * Sum a list of child `BaseReport.usage` values. Callbacks\n * themselves contribute zero own-cost (they're dev code, not LLM\n * calls); their report's `usage` equals the sum of whatever\n * agents / workflows / nested callbacks they dispatched via\n * `ctx.intents.X.execute()`. Mirrors `compositeAsTool` semantics.\n */\nfunction aggregateChildUsage(children: BaseReport[]): Usage {\n return children.reduce<Usage>(\n (acc, child) => ({\n input: acc.input + child.usage.input,\n output: acc.output + child.usage.output,\n total: acc.total + child.usage.total,\n }),\n { input: 0, output: 0, total: 0 },\n );\n}\n\n/**\n * Best-effort stringification for the snapshot's `input` field when\n * a callback intent's resolved input is a non-string value. Falls\n * back to a typed placeholder if `JSON.stringify` throws (circular\n * refs, BigInt, etc.) so a snapshot write never fails on its own.\n */\nfunction safeStringify(value: unknown): string {\n if (value === undefined) {\n return \"undefined\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return `[unserializable: ${typeof value}]`;\n }\n}\n\nasync function validateOutput<TOutput>(\n schema: StandardSchemaV1<TOutput>,\n value: unknown,\n): Promise<TOutput> {\n const validation = await schema[\"~standard\"].validate(value);\n\n if (validation.issues) {\n throw new SchemaValidationError(validation.issues.map((issue) => issue.message).join(\"; \"), {\n issues: validation.issues,\n });\n }\n\n return validation.value;\n}\n","import { ClassifierAgentEntry, ClassifierRunEntry } from \"../contracts\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { ResolvedIntentEntry } from \"./entries\";\n\n/**\n * Deterministic structural fingerprint of a supervisor definition.\n * Persisted on every snapshot so `resume()` can detect drift between\n * the saved run and the current definition. Covers:\n *\n * - Supervisor name.\n * - Every intent key + its resolved description + the underlying\n * unit's stable identity (agent name, workflow name + signature,\n * or `\"callback\"` marker for dev-callback intents).\n * - Router agent's name (if the supervisor uses LLM routing).\n * - Whether a deterministic `route` callback is configured (but not\n * its contents — route callbacks are code, not data).\n * - Whether an `evaluate` callback is configured.\n * - `initialAgent` when set.\n * - `maxIterations` (a semantic shape change, not a cosmetic one).\n *\n * Does NOT cover: system prompt text, logger, store identity, per-\n * event handlers — all runtime knobs that don't change the shape of\n * a resumable run.\n */\nexport function computeSignature(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): string {\n const intentsFingerprint = [...entries.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([intent, entry]) => ({\n k: intent,\n d: entry.description,\n u: fingerprintUnit(entry),\n }));\n\n const fingerprint = {\n n: config.name,\n a: intentsFingerprint,\n r: resolveRouterName(config.router),\n rc: config.route ? 1 : 0,\n e: config.evaluate ? 1 : 0,\n i: config.initialAgent ?? null,\n m: config.maxIterations ?? null,\n // Phase 7 / decisions §37 — classifier is part of structural identity.\n // Resume drift detection notices when the classifier swap changes\n // routing semantics. Same fingerprint shape as router (agent name\n // when applicable; \"callback\" marker for callback form).\n c: resolveClassifierFingerprint(config.classifier),\n };\n\n return hash(JSON.stringify(fingerprint));\n}\n\nfunction resolveRouterName(router: SupervisorConfig<unknown>[\"router\"]): string | null {\n if (!router) {\n return null;\n }\n\n if (typeof (router as { execute?: unknown }).execute === \"function\") {\n return (router as { name?: string }).name ?? null;\n }\n\n return (router as { agent?: { name?: string } }).agent?.name ?? null;\n}\n\nfunction resolveClassifierFingerprint(\n classifier: SupervisorConfig<unknown>[\"classifier\"],\n): unknown {\n if (!classifier) {\n return null;\n }\n\n if (typeof classifier === \"function\") {\n return { t: \"callback\" };\n }\n\n if (typeof (classifier as { execute?: unknown }).execute === \"function\") {\n return { t: \"agent\", n: (classifier as { name?: string }).name ?? null };\n }\n\n if (typeof (classifier as ClassifierRunEntry).run === \"function\") {\n return { t: \"callback\" };\n }\n\n if (typeof (classifier as ClassifierAgentEntry).agent?.execute === \"function\") {\n return {\n t: \"agent\",\n n: (classifier as ClassifierAgentEntry).agent?.name ?? null,\n };\n }\n\n return { t: \"unknown\" };\n}\n\nfunction fingerprintUnit(entry: ResolvedIntentEntry): unknown {\n if (entry.type === \"callback\") {\n // Callbacks are dev code — fingerprint the type + intent name\n // only (the closure itself can't be hashed deterministically).\n // Drift detection covers add/remove/rename of callback intents,\n // not edits to the function body. Same trade-off as `route`.\n return { t: \"callback\" };\n }\n\n if (entry.type === \"workflow\") {\n const workflow = entry.unit;\n return { t: \"workflow\", n: workflow.name, s: workflow.signature };\n }\n\n return { t: \"agent\", n: entry.unit.name };\n}\n\n/**\n * FNV-1a 32-bit — same hash `workflow/signature.ts` uses. Deterministic,\n * no crypto dependency, cheap; signatures are 8-char hex.\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","import type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type { SupervisorStreamEvent } from \"../contracts/supervisor/supervisor-stream-event.type\";\n\n// Re-export so internal callers that already imported from this file\n// keep working unchanged. Canonical home is the contracts barrel.\nexport type { SupervisorStreamEvent };\n\n/**\n * Internal async-queue controller driving `supervisor.stream()`.\n * Mirrors `StreamController` from `agent-stream.ts` — same\n * producer/consumer pipe, same semantics, parameterized by the\n * supervisor event union and terminal result type.\n */\nexport type SupervisorStreamController<TResult> = {\n push(event: SupervisorStreamEvent): void;\n end(result: TResult): void;\n fail(error: Error): void;\n};\n\ntype PendingRead = {\n resolve(value: IteratorResult<SupervisorStreamEvent>): void;\n reject(error: Error): void;\n};\n\n/**\n * Factory mirroring `createAgentStream`. Returns a paired\n * `{ controller, stream }` — the `SupervisorExecution` pushes events\n * into the controller while the caller iterates (or awaits `.result`)\n * on the stream side. See `agent-stream.ts` for the full role\n * description.\n */\nexport function createSupervisorStream<TResult>(): {\n controller: SupervisorStreamController<TResult>;\n stream: StreamContract<TResult, SupervisorStreamEvent>;\n} {\n const queue: SupervisorStreamEvent[] = [];\n const pending: PendingRead[] = [];\n const handlers = new Map<string, (event: SupervisorStreamEvent) => void>();\n\n let closed = false;\n let failure: Error | undefined;\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const controller: SupervisorStreamController<TResult> = {\n push(event) {\n const handler = handlers.get(event.type);\n\n if (handler) {\n try {\n handler(event);\n } catch {\n // Stream handlers must never crash the supervisor.\n }\n }\n\n const reader = pending.shift();\n\n if (reader) {\n reader.resolve({ value: event, done: false });\n return;\n }\n\n queue.push(event);\n },\n\n end(finalResult) {\n closed = true;\n resolveResult(finalResult);\n\n while (pending.length > 0) {\n pending.shift()?.resolve({ value: undefined, done: true });\n }\n },\n\n fail(error) {\n closed = true;\n failure = error;\n rejectResult(error);\n\n while (pending.length > 0) {\n pending.shift()?.reject(error);\n }\n },\n };\n\n const iterator: AsyncIterator<SupervisorStreamEvent> = {\n next() {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (closed) {\n if (failure) {\n return Promise.reject(failure);\n }\n\n return Promise.resolve({ value: undefined, done: true });\n }\n\n return new Promise<IteratorResult<SupervisorStreamEvent>>(\n (resolve, reject) => {\n pending.push({ resolve, reject });\n },\n );\n },\n };\n\n // The `StreamContract<TResult>` shape is shared across primitives —\n // it types `on()` over the generic `StreamEvent` union (agent\n // events). Supervisor events are a distinct discriminated union\n // with the same `type`-keyed shape, so we satisfy the contract via\n // a structural cast — handlers see the supervisor events at their\n // correct narrowed types.\n const stream = {\n result,\n on(handlerMap) {\n for (const [key, handler] of Object.entries(handlerMap)) {\n if (handler) {\n handlers.set(key, handler as (event: SupervisorStreamEvent) => void);\n }\n }\n\n return stream;\n },\n [Symbol.asyncIterator]() {\n return iterator;\n },\n } as StreamContract<TResult, SupervisorStreamEvent>;\n\n return { controller, stream };\n}\n","import type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type { SupervisorResult } from \"../contracts/result/supervisor-result.type\";\nimport type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type { SupervisorIntentValue } from \"../contracts/supervisor/intent-entry.type\";\nimport type {\n SupervisorConfig,\n SupervisorEventHandler,\n} from \"../contracts/supervisor/supervisor-config.type\";\nimport type {\n SupervisorExecuteOptions,\n SupervisorResumeOptions,\n} from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type { SupervisorStreamEvent } from \"../contracts/supervisor/supervisor-stream-event.type\";\nimport type {\n SupervisorAsToolOptions,\n SupervisorContract,\n} from \"../contracts/supervisor/supervisor.contract\";\nimport { SupervisorFailedError } from \"../errors\";\nimport type { ToolContract } from \"../tool/tool\";\nimport { asTool } from \"./as-tool\";\nimport { SupervisorEmitter } from \"./emitter\";\nimport { assertRouterDescriptions, resolveIntentEntries } from \"./entries\";\nimport { SupervisorExecution } from \"./execution\";\nimport { computeSignature } from \"./signature\";\nimport { loadSnapshotForResume } from \"./snapshot\";\nimport { createSupervisorStream } from \"./supervisor-stream\";\n\n/**\n * `ai.supervisor(config)` — construct a `SupervisorContract`. Validates\n * the config at author time (throws `SupervisorFailedError` on bad\n * shape), resolves agent entries, computes a stable structural\n * signature, wires the three-tier event emitter, and returns an\n * instance that satisfies `ExecutableContract` so it can compose into\n * tools, outer agents, and (future) orchestrators uniformly.\n *\n * @example\n * const support = ai.supervisor({\n * name: \"customer-support\",\n * router: routerAgent,\n * intents: { triage, orderLookup, billingLookup, resolver },\n * evaluate: (ctx) => ctx.result.resolver?.output ? { satisfied: true } : undefined,\n * output: z.object({ response: z.string(), refund: z.boolean() }),\n * maxIterations: 6,\n * });\n */\nexport function supervisor<\n TOutput = unknown,\n TState = TOutput,\n TIntents extends Record<string, SupervisorIntentValue> = Record<string, SupervisorIntentValue>,\n TArtifacts = Record<string, unknown>,\n>(config: SupervisorConfig<TOutput, TState, TIntents, TArtifacts>): SupervisorContract<TOutput> {\n validateFactoryConfig(config as unknown as SupervisorConfig<TOutput>);\n\n const entries = resolveIntentEntries(config.intents, config.name);\n\n assertRouterDescriptions(config as SupervisorConfig<unknown>, entries);\n\n if (config.initialAgent && !entries.has(config.initialAgent)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`initialAgent\\` \"${config.initialAgent}\" is not a key in \\`intents\\``,\n { context: { authoring: true } },\n );\n }\n\n const signature = computeSignature(config as SupervisorConfig<unknown>, entries);\n const emitter = new SupervisorEmitter(config.on);\n\n async function execute(\n input: SupervisorInput,\n options?: SupervisorExecuteOptions,\n ): Promise<SupervisorResult<TOutput>> {\n const runId = options?.runId ?? generateRunId();\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input,\n runId,\n options,\n });\n\n return execution.run();\n }\n\n function stream(\n input: SupervisorInput,\n options?: SupervisorExecuteOptions,\n ): StreamContract<SupervisorResult<TOutput>, SupervisorStreamEvent> {\n const runId = options?.runId ?? generateRunId();\n const { controller, stream: contract } = createSupervisorStream<SupervisorResult<TOutput>>();\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input,\n runId,\n options,\n streamController: controller,\n });\n\n void execution.run();\n\n return contract;\n }\n\n async function resume(\n runId: string,\n options?: SupervisorResumeOptions,\n ): Promise<SupervisorResult<TOutput>> {\n const snapshot = await loadSnapshotForResume({\n config: config as SupervisorConfig<unknown>,\n signature,\n runId,\n options,\n });\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input: snapshot.input,\n runId,\n options,\n resumeFrom: snapshot,\n });\n\n return execution.run();\n }\n\n const instance: SupervisorContract<TOutput> = {\n name: config.name,\n signature,\n execute,\n stream,\n resume,\n on<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): () => void {\n return emitter.on(event, handler);\n },\n off<K extends keyof SupervisorEventMap>(event: K, handler: SupervisorEventHandler<K>): void {\n emitter.off(event, handler);\n },\n asTool<TToolInput = string>(\n options: SupervisorAsToolOptions<TToolInput>,\n ): ToolContract<TToolInput, TOutput> {\n return asTool<TOutput, TToolInput>(instance, options);\n },\n };\n\n return instance;\n}\n\n/**\n * Factory-time validation. Enforces the XOR + pairing rules the design\n * locked in §2 and surfaces any violation as a typed\n * `SupervisorFailedError` tagged `authoring: true`.\n */\nfunction validateFactoryConfig<T>(config: SupervisorConfig<T>): void {\n if (!config.name || typeof config.name !== \"string\") {\n throw new SupervisorFailedError(\"ai.supervisor: `name` is required and must be a string\", {\n context: { authoring: true },\n });\n }\n\n if (!config.intents || typeof config.intents !== \"object\") {\n throw new SupervisorFailedError(`ai.supervisor(\"${config.name}\"): \\`intents\\` is required`, {\n context: { authoring: true },\n });\n }\n\n const hasRoute = typeof config.route === \"function\";\n const hasRouter = !!config.router;\n\n if (hasRouter) {\n const router = config.router as { execute?: unknown } | { agent?: { execute?: unknown } };\n const isBareAgent = typeof (router as { execute?: unknown }).execute === \"function\";\n const isEntryForm =\n !isBareAgent &&\n typeof (router as { agent?: { execute?: unknown } }).agent === \"object\" &&\n typeof (router as { agent?: { execute?: unknown } }).agent?.execute === \"function\";\n\n if (!isBareAgent && !isEntryForm) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`router\\` must be an agent contract or a \\`{ agent, placeholders?, input? }\\` entry`,\n { context: { authoring: true } },\n );\n }\n }\n\n if (hasRoute && hasRouter) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`route\\` and \\`router\\` are mutually exclusive — configure exactly one`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 7 / decisions §37 — `classifier` is the iter-0 prelude;\n // satisfies the \"must have a dispatch source\" rule on its own.\n // Composes with router/route (classifier drives iter 0; router/route\n // takes iter 1+). When configured alone, supervisor terminates after\n // iter 0's branch settles.\n const hasClassifier = config.classifier !== undefined;\n\n if (!hasRoute && !hasRouter && !hasClassifier) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): one of \\`route\\`, \\`router\\`, or \\`classifier\\` is required`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 7 — classifier and initialAgent both decide what runs first.\n // Coexistence is meaningless; throw loudly.\n if (hasClassifier && config.initialAgent) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`classifier\\` and \\`initialAgent\\` are mutually exclusive — both decide which intent runs first. Pick one.`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 3.4 (Q9) — evaluate now pairs with both `route` and\n // `router`. State-driven termination is useful in either dispatch\n // mode; the historical router-only restriction was incidental,\n // not principled.\n\n if (config.ack !== undefined) {\n const ack = config.ack;\n const isCallback = typeof ack === \"function\";\n const isAgentEntry =\n typeof ack === \"object\" &&\n ack !== null &&\n typeof (ack as { agent?: { execute?: unknown } }).agent?.execute === \"function\";\n const isRunEntry =\n typeof ack === \"object\" &&\n ack !== null &&\n typeof (ack as { run?: unknown }).run === \"function\";\n\n if (!isCallback && !isAgentEntry && !isRunEntry) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`ack\\` must be an \\`{ agent, ... }\\` entry, an \\`{ run, ... }\\` entry, or a bare callback function`,\n { context: { authoring: true } },\n );\n }\n\n if (isAgentEntry && isRunEntry) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`ack\\` cannot declare both \\`agent\\` and \\`run\\` — pick one`,\n { context: { authoring: true } },\n );\n }\n }\n\n if (config.maxIterations !== undefined && config.maxIterations < 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`maxIterations\\` must be >= 1`,\n { context: { authoring: true, maxIterations: config.maxIterations } },\n );\n }\n}\n\nfunction generateRunId(): string {\n return `sup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * Render a template string against a placeholders map, supporting dot-path\n * lookups and inline fallback values.\n *\n * Supported syntax:\n * - `{{key}}` — replaced by `placeholders.key`, left untouched if missing.\n * - `{{a.b.c}}` — dot-path lookup into nested objects.\n * - `{{key|default}}` — substitutes `default` when the key resolves to\n * `undefined`, `null`, or empty string.\n *\n * Whitespace inside the braces is ignored (`{{ key }}` == `{{key}}`).\n * Values are coerced to strings via `String(value)`.\n *\n * @example\n * renderPlaceholders(\n * \"Hello {{user.name|friend}}, your role is {{role}}\",\n * { user: { name: \"Hasan\" }, role: \"admin\" },\n * );\n * // \"Hello Hasan, your role is admin\"\n *\n * @example\n * renderPlaceholders(\"Hello {{user.name|friend}}\", {});\n * // \"Hello friend\"\n */\nexport function renderPlaceholders(\n template: string,\n placeholders: Placeholders = {},\n): string {\n return template.replace(\n PLACEHOLDER_PATTERN,\n (match, rawExpression: string) => {\n const [rawPath, rawFallback] = rawExpression.split(\"|\");\n const path = rawPath.trim();\n const fallback = rawFallback?.trim();\n\n const value = lookupPath(placeholders, path);\n\n if (value === undefined || value === null || value === \"\") {\n if (fallback !== undefined) {\n return fallback;\n }\n\n return match;\n }\n\n return String(value);\n },\n );\n}\n\n/**\n * Walk a dot-path (`\"a.b.c\"`) through an arbitrary record, returning the\n * leaf value or `undefined` when any segment is missing or blocks traversal\n * (non-object). Never throws.\n */\nfunction lookupPath(source: Placeholders, path: string): unknown {\n const segments = path.split(\".\");\n let current: unknown = source;\n\n for (const segment of segments) {\n if (current === null || current === undefined) {\n return undefined;\n }\n\n if (typeof current !== \"object\") {\n return undefined;\n }\n\n current = (current as Record<string, unknown>)[segment];\n }\n\n return current;\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type { InstructionContract } from \"../contracts/system-prompt.contract\";\nimport { renderPlaceholders } from \"./render-placeholders\";\n\n/**\n * Concrete `InstructionContract` — a reusable directive block.\n *\n * **Role.** A single addressable prompt block representing one rule the\n * agent must follow (`\"Always respond in {{language|English}}.\"`). Exists\n * as its own type so the same instruction can be shared across many\n * prompts and agents, each render supplying its own placeholder map.\n *\n * **Responsibility.**\n * - Owns: the `type: \"instruction\"` discriminator, the raw template text,\n * and the placeholder-rendering step.\n * - Does NOT own: ordering relative to other instructions, joining with a\n * persona, or any surrounding prompt composition — those concerns live\n * in `SystemPrompt`.\n *\n * Users construct via the `ai.instruction()` factory — `new Instruction()`\n * is not the public API (see §4.2 of code-style.md).\n *\n * @example\n * const replyInLanguage = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt()\n * .persona(\"You are Alex.\")\n * .instruction(replyInLanguage)\n * .instruction(\"Always include code examples.\");\n */\nexport class Instruction implements InstructionContract {\n public readonly type = \"instruction\" as const;\n\n public constructor(public readonly text: string) {\n //\n }\n\n /**\n * Substitute `{{mustache}}` placeholders in the instruction text against\n * the supplied map. Delegates to the shared `renderPlaceholders` helper\n * so persona / instruction / system-prompt rendering stays identical.\n */\n public resolve(placeholders?: Placeholders): string {\n return renderPlaceholders(this.text, placeholders);\n }\n}\n\n/**\n * Create an `Instruction` from raw template text.\n *\n * @example\n * const replyIn = instruction(\"Respond in {{language|English}}.\");\n * const cite = instruction(\"Always cite sources inline.\");\n */\nexport function instruction(text: string): Instruction {\n return new Instruction(text);\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type { PersonaContract } from \"../contracts/system-prompt.contract\";\nimport { renderPlaceholders } from \"./render-placeholders\";\n\n/**\n * Concrete `PersonaContract` — a reusable \"who the agent is\" block.\n *\n * **Role.** A single addressable prompt block representing the agent's\n * identity (`\"You are Alex, a senior TypeScript engineer.\"`). Exists as\n * its own type so personas can be defined once and reused across many\n * `SystemPrompt` compositions, agents, and sessions — each render can\n * supply a different placeholder map.\n *\n * **Responsibility.**\n * - Owns: the `type: \"persona\"` discriminator, the raw template text, and\n * the placeholder-rendering step.\n * - Does NOT own: composition with instructions, ordering, joining, or\n * any knowledge of the surrounding `SystemPrompt`. Those concerns live\n * in `SystemPrompt`.\n *\n * Users construct via the `ai.persona()` factory — `new Persona()` is not\n * the public API (see §4.2 of code-style.md).\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n *\n * const prompt = ai.systemPrompt()\n * .persona(alex)\n * .instruction(\"Always cite sources.\");\n */\nexport class Persona implements PersonaContract {\n public readonly type = \"persona\" as const;\n\n public constructor(public readonly text: string) {\n //\n }\n\n /**\n * Substitute `{{mustache}}` placeholders in the persona text against the\n * supplied map. Delegates to the shared `renderPlaceholders` helper so\n * persona / instruction / system-prompt rendering stays identical.\n */\n public resolve(placeholders?: Placeholders): string {\n return renderPlaceholders(this.text, placeholders);\n }\n}\n\n/**\n * Create a `Persona` from raw template text.\n *\n * @example\n * const alex = persona(\"You are Alex, a TypeScript expert.\");\n * const greeter = persona(\"You are a greeter in {{language|English}}.\");\n */\nexport function persona(text: string): Persona {\n return new Persona(text);\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type {\n InstructionContract,\n PersonaContract,\n SystemPromptBlockContract,\n SystemPromptContract,\n} from \"../contracts/system-prompt.contract\";\nimport { Instruction } from \"./instruction\";\nimport { Persona } from \"./persona\";\n\n/**\n * Concrete `SystemPromptContract` — an immutable layered prompt builder.\n *\n * **Role.** The top-level composer for a system prompt: it holds an ordered\n * list of typed blocks (persona + instructions) and resolves the whole\n * stack into one final string when the agent is about to call the model.\n *\n * **Responsibility.**\n * - Owns: the ordered `blocks` list and the block-join rules (insertion\n * order, blank-line separator, trim).\n * - Does NOT own: how any individual block is rendered (delegated to each\n * block's `resolve()`), the placeholder syntax (delegated to\n * `renderPlaceholders`), or any knowledge of the agent, model, or\n * session consuming the resolved text.\n *\n * Blocks are discriminated by a string `type` tag (`\"persona\"` /\n * `\"instruction\"`) rather than `instanceof`, so user-supplied blocks that\n * implement `SystemPromptBlockContract` interoperate seamlessly with blocks\n * built via `ai.persona()` / `ai.instruction()` — even across duplicate\n * package copies or bundler scope boundaries.\n *\n * The builder is **immutable** — every `.persona()` / `.instruction()`\n * call returns a fresh `SystemPrompt` instance sharing nothing mutable\n * with its parent. This makes forking a base prompt into specialized\n * variants a safe, side-effect-free operation.\n *\n * Users construct via the `ai.systemPrompt()` factory — `new SystemPrompt()`\n * is not the public API (see §4.2 of code-style.md). Modeled as a class so\n * that methods live on the prototype (one copy shared across every forked\n * instance) and downstream code can branch via `instanceof SystemPrompt`.\n *\n * @example\n * // Chainable form\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const base = ai.systemPrompt().persona(alex).instruction(replyIn);\n * const arabicVariant = base.instruction(\"Prefer Arabic comments.\");\n *\n * base.resolve({ language: \"English\" });\n * arabicVariant.resolve({ language: \"Arabic\" });\n *\n * @example\n * // Array form — insertion order is preserved exactly\n * const prompt = ai.systemPrompt([\n * ai.persona(\"You are Alex, a TypeScript expert.\"),\n * ai.instruction(\"Respond in {{language|English}}.\"),\n * ]);\n */\nexport class SystemPrompt implements SystemPromptContract {\n public constructor(\n public readonly blocks: readonly SystemPromptBlockContract[] = [],\n ) {}\n\n /**\n * Return a new builder with the persona block set. If a persona already\n * exists it's replaced in place (preserving its position in `blocks`);\n * otherwise the new persona is prepended so persona-first remains the\n * default for chain-built prompts. Accepts either raw text (auto-wrapped\n * via `new Persona`) or an existing `PersonaContract` instance for reuse\n * across prompts.\n */\n public persona(value: PersonaContract | string): SystemPromptContract {\n const block = typeof value === \"string\" ? new Persona(value) : value;\n const existingIndex = this.blocks.findIndex(\n candidate => candidate.type === \"persona\",\n );\n\n if (existingIndex >= 0) {\n const next = [...this.blocks];\n next[existingIndex] = block;\n\n return new SystemPrompt(next) as this;\n }\n\n return new SystemPrompt([block, ...this.blocks]);\n }\n\n /**\n * Return a new builder with the given instruction appended. Instructions\n * render in insertion order. Accepts either raw text (auto-wrapped via\n * `new Instruction`) or an existing `InstructionContract` instance for\n * cross-prompt reuse.\n */\n public instruction(\n value: InstructionContract | string,\n ): SystemPromptContract {\n const block = typeof value === \"string\" ? new Instruction(value) : value;\n\n return new SystemPrompt([...this.blocks, block]);\n }\n\n /**\n * Resolve every block against the placeholder map, join the results with\n * blank-line separators (in insertion order), and trim. Returns an empty\n * string when no blocks are present — callers treat that as \"no system\n * message\".\n */\n public resolve(placeholders?: Placeholders): string {\n return this.blocks\n .map(block => block.resolve(placeholders))\n .join(\"\\n\\n\")\n .trim();\n }\n}\n\n/**\n * Create a new immutable system-prompt builder.\n *\n * **Role.** Public factory for `SystemPrompt` — keeps user-facing code\n * free of `new` and consistent with `ai.tool()`, `ai.agent()`,\n * `ai.persona()`, `ai.instruction()`.\n *\n * Three input forms:\n * - No argument → empty builder, chain `.persona()` / `.instruction()`\n * - Single string → seeded with one instruction for quick one-shot prompts\n * - Array of blocks → used verbatim, preserving insertion order\n *\n * @example\n * // Composed builder\n * const prompt = systemPrompt()\n * .persona(\"You are Alex, a senior TypeScript engineer.\")\n * .instruction(\"Always include working code examples.\")\n * .instruction(\"Respond in {{language|English}}.\");\n *\n * prompt.resolve({ language: \"Arabic\" });\n *\n * @example\n * // One-shot seed\n * const prompt = systemPrompt(\"Answer only with JSON matching the schema.\");\n *\n * @example\n * // Array form — fully declarative\n * const prompt = systemPrompt([\n * ai.persona(\"You are Alex.\"),\n * ai.instruction(\"Always cite sources.\"),\n * ai.instruction(\"Respond in {{language|English}}.\"),\n * ]);\n */\nexport function systemPrompt(\n input?: string | ReadonlyArray<SystemPromptBlockContract>,\n): SystemPrompt {\n if (input === undefined) {\n return new SystemPrompt();\n }\n\n if (typeof input === \"string\") {\n return new SystemPrompt([new Instruction(input)]);\n }\n\n return new SystemPrompt([...input]);\n}\n","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","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"../tool/tool\";\n\n/**\n * Wrap a `WorkflowInstance` as a `ToolContract` so an agent can invoke\n * it inside its tool-call loop. Closes the agent-calls-workflow\n * composition gap.\n *\n * Behavior:\n * - Tool `name` mirrors `workflow.name` — workflows without a name throw\n * `WorkflowError` at wrap time (the agent surface needs a stable id).\n * - Tool `input` is the supplied `inputSchema`; the validated value is\n * forwarded straight to `workflow.execute(input)`.\n * - On `result.error`, the workflow error is wrapped in\n * `ToolExecutionError` with `cause` set to the original\n * `WorkflowError` subclass — the agent's tool-call loop sees a\n * uniform error class regardless of which primitive failed.\n *\n * **Usage caveat (deferred to Phase 2):** the parent agent's\n * `result.usage` does NOT roll up tokens consumed inside the wrapped\n * workflow today. Nested-usage standardization lands with the\n * supervisor work; until then, sum workflow + agent usage manually if\n * you need a combined cost figure.\n *\n * @example\n * const wf = workflow({ name: \"triage\", steps: [...] });\n * const triageTool = asTool(wf, {\n * description: \"Run the support-ticket triage flow\",\n * inputSchema: ticketSchema,\n * });\n * const a = ai.agent({ model, tools: [triageTool] });\n */\nexport function asTool<TInput, TOutput, TToolInput = TInput>(\n workflowInstance: WorkflowInstance<TInput, TOutput>,\n options: {\n description?: string;\n inputSchema: StandardSchemaV1<TToolInput>;\n },\n): ToolContract<TToolInput, TOutput> {\n if (!workflowInstance.name || typeof workflowInstance.name !== \"string\") {\n throw new WorkflowError(\n \"workflow.asTool(): workflow must have a `name` to be wrapped as a tool\",\n );\n }\n\n return compositeAsTool<TToolInput, TOutput>({\n name: workflowInstance.name,\n description: options.description ?? `Invoke workflow \"${workflowInstance.name}\" as a tool.`,\n input: options.inputSchema,\n execute: async (input) => {\n const result = await workflowInstance.execute(input as unknown as TInput);\n\n if (result.error) {\n // Throw the workflow error so the surrounding wrapper catches\n // it and produces a `ToolExecutionError` with `cause` pointing\n // back at the original `WorkflowError` subclass — keeps the\n // agent's tool-call loop seeing one uniform error class\n // regardless of which primitive failed.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage,\n report: result.report,\n };\n },\n });\n}\n","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","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","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","import type { EventIdentity } from \"../contracts/events/event-identity.type\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type { WorkflowEventHandlers } from \"../contracts/workflow/workflow.contract\";\nimport type { WorkflowEmitter, WorkflowEventSink } from \"./emitter\";\n\n/**\n * Bind a factory-scoped `WorkflowEmitter` to one run's identity.\n *\n * The engine and step-runner emit bare payloads through this sink;\n * it injects `runId` / `rootRunId` once and delegates to the real\n * three-tier emitter. This is the single place workflow run identity\n * is stamped — the alternative (editing every `emitter.emit` call\n * site) would be ~15 scattered edits and easy to miss one.\n *\n * `rootRunId === runId` for a standalone run; nested propagation\n * (a child workflow inheriting an outer run's root) lands in a\n * follow-up.\n *\n * @example\n * // Inside runWorkflow(), once per execution:\n * const emitter = runScopedEmitter(params.emitter, { runId, rootRunId: runId });\n * emitter.emit(\"workflow.starting\", { workflowName, input }, executionHandlers);\n */\nexport function runScopedEmitter(\n emitter: WorkflowEmitter,\n identity: EventIdentity,\n): WorkflowEventSink {\n return {\n emit(event, payload, executionHandlers?: WorkflowEventHandlers) {\n const fullPayload = {\n ...payload,\n ...identity,\n } as WorkflowEventMap[typeof event];\n\n emitter.emit(event, fullPayload, executionHandlers);\n },\n };\n}\n","import { resolveDefaultStore } from \"../config\";\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 snapshot store: the workflow's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultStore })`.\n */\nfunction resolveSnapshotStore<T>(definition: WorkflowDefinition<any, T, any, any>) {\n return definition.snapshotStore ?? resolveDefaultStore();\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.set(params.runId, 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({ defaultStore })\\` at boot before calling resume()`,\n );\n }\n\n const snap = (await store.get<WorkflowSnapshot>(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","import { WorkflowError } from \"../errors\";\n\n/**\n * Deep-clone workflow state. Uses `structuredClone` — handles Date,\n * Map, Set, ArrayBuffer, nested objects, arrays, primitives. Throws\n * a typed `WorkflowError` on older runtimes (pre-Node-17) rather\n * than silently falling back to a JSON round-trip that would drop\n * non-serializable values like Dates without warning.\n *\n * Workflow state should stay serializable anyway (it round-trips\n * through `KVStore` on every checkpoint). If `structuredClone` chokes\n * on a value, that's a bug in the user's state — surface it.\n */\nexport function cloneState<T>(value: T): T {\n if (typeof structuredClone !== \"function\") {\n throw new WorkflowError(\n \"workflow state cloning requires `structuredClone` (Node 17+ or a modern browser)\",\n );\n }\n\n return structuredClone(value);\n}\n\n/**\n * Recursively freeze `value` and every nested plain object / array so\n * consumers of `ctx.steps[x].state` or `report.state` can't mutate\n * historical snapshots. Already-frozen values are skipped.\n */\nexport function deepFreeze<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n if (Object.isFrozen(value)) return value;\n\n for (const key of Object.keys(value as Record<string, unknown>)) {\n const child = (value as Record<string, unknown>)[key];\n if (child && typeof child === \"object\") deepFreeze(child);\n }\n\n return Object.freeze(value);\n}\n","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","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 { 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 {\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 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\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\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 agentInput = step.input\n ? await step.input(params.buildContext({ state: attemptState }))\n : { prompt: \"\" };\n\n const { prompt, ...agentOpts } = agentInput;\n\n const result = await step.agent.execute(prompt, {\n ...agentOpts,\n signal,\n });\n\n executionResult = result;\n\n if (result.usage) {\n params.usage.input += result.usage.input ?? 0;\n params.usage.output += result.usage.output ?? 0;\n params.usage.total += result.usage.total ?? 0;\n }\n\n if (result.error) throw result.error;\n } else if (step.run) {\n executionResult = await step.run(params.buildContext({ state: attemptState }));\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 };\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 };\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 });\n\n Object.assign(sharedState, snap.state);\n return { child, snap };\n }),\n );\n\n for (const { child, snap } of results) {\n childSnapshots[child.name] = finalizeSnapshot(snap);\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 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","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 });\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 ran one.\n // Today the step runner surfaces agent reports (the only executable\n // kind steps can invoke natively via `step.agent`); custom `run`\n // callbacks that call tools/workflows/supervisors can't be observed\n // here without a richer step-runner API — that's a v1.x follow-up\n // (see backlog: \"step.run executables surface in workflow tree\").\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 }\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 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","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","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.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 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 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 return 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\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 return 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\n const instance: WorkflowInstance<TInput, TOutput, TState, TContext> = {\n name: definition.name,\n description: definition.description,\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","import { agent } from \"./agent/agent\";\nimport { setAIConfig } from \"./config\";\nimport { budget } from \"./middleware/builtins/budget\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n },\n};\n","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 { MockModelResponse } from \"./mock-config.type\";\n\ntype RecordedCall = {\n messages: Message[];\n options?: ModelCallOptions;\n};\n\n/**\n * Deterministic in-memory `ModelContract` implementation for tests.\n *\n * **Role.** Stands in for a real provider model so agent/workflow/supervisor\n * tests can assert behavior without hitting the network, spending tokens, or\n * depending on non-deterministic LLM output.\n *\n * **Responsibility.**\n * - Owns: a scripted queue of `MockModelResponse` entries, a call-history\n * log for assertions, and the index pointer that advances through the\n * queue on each `complete()` / `stream()` call.\n * - Does NOT own: any real inference, tokenization, or network I/O — when\n * the queue is exhausted, the final entry is reused so tests never crash\n * on accidental over-consumption.\n *\n * Every AI-related test in this repo uses `MockSDK` / `MockModel` — real\n * provider APIs are never hit from the test suite (see §6 of code-style.md).\n *\n * @example\n * const model = new MockModel(\"mock-gpt\", [\n * { content: \"Hello!\", finishReason: \"stop\" },\n * { content: \"Second turn.\", finishReason: \"stop\" },\n * ]);\n *\n * const first = await model.complete([{ role: \"user\", content: \"hi\" }]);\n * expect(first.content).toBe(\"Hello!\");\n * expect(model.callCount).toBe(1);\n */\nexport class MockModel implements ModelContract {\n public readonly provider = \"mock\";\n public readonly capabilities?: ModelCapabilities;\n\n private responseIndex = 0;\n private calls: RecordedCall[] = [];\n\n public constructor(\n public readonly name: string,\n private readonly responses: MockModelResponse[],\n capabilities?: ModelCapabilities,\n ) {\n this.capabilities = capabilities;\n }\n\n /**\n * Full history of calls made to this model. Each entry is the exact\n * `{ messages, options }` pair that was passed — useful for asserting\n * that an agent built the right prompt or forwarded the right tool list.\n */\n public get callHistory(): RecordedCall[] {\n return this.calls;\n }\n\n /**\n * Number of times `complete()` or `stream()` has been invoked. Convenient\n * shorthand for `callHistory.length` in assertions.\n */\n public get callCount(): number {\n return this.calls.length;\n }\n\n /**\n * Advance the scripted response queue by one and return the entry at the\n * current pointer. If the queue is exhausted, the final scripted entry is\n * returned repeatedly so over-consumption in tests produces predictable\n * output instead of `undefined`.\n */\n private nextResponse(): MockModelResponse {\n const response = this.responses[Math.min(this.responseIndex, this.responses.length - 1)];\n\n this.responseIndex++;\n\n return response ?? { content: \"Mock response\", finishReason: \"stop\" };\n }\n\n /**\n * Convert a scripted `MockModelResponse` into a full `ModelResponse` with\n * synthesized usage numbers when the script didn't supply them. Input\n * usage is a fixed estimate; output usage is derived from content length.\n */\n private buildResponse(mock: MockModelResponse): ModelResponse {\n const estimatedInput = 10;\n const estimatedOutput = Math.ceil(mock.content.length / 4);\n\n return {\n content: mock.content,\n finishReason: mock.finishReason ?? \"stop\",\n usage: {\n input: mock.usage?.input ?? estimatedInput,\n output: mock.usage?.output ?? estimatedOutput,\n total: (mock.usage?.input ?? estimatedInput) + (mock.usage?.output ?? estimatedOutput),\n ...(mock.usage?.cachedTokens !== undefined ? { cachedTokens: mock.usage.cachedTokens } : {}),\n },\n toolCalls: mock.toolCalls,\n };\n }\n\n /**\n * Record the call, optionally delay (to simulate latency), and either\n * throw the scripted error or return the scripted response. Mirrors the\n * real provider's `complete()` contract so agents cannot tell the\n * difference at runtime.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.calls.push({ messages, options });\n\n const mock = this.nextResponse();\n\n if (mock.delay) {\n await new Promise((resolve) => setTimeout(resolve, mock.delay));\n }\n\n if (mock.error) {\n throw mock.error;\n }\n\n return this.buildResponse(mock);\n }\n\n /**\n * Record the call, optionally delay, then emit the scripted response as a\n * sequence of stream chunks: content split word-by-word as `delta`\n * chunks, each scripted tool call as a `tool-call` chunk, and finally a\n * `done` chunk with finish reason + usage. Throws eagerly if the scripted\n * entry carries an `error`.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.calls.push({ messages, options });\n\n const mock = this.nextResponse();\n\n if (mock.delay) {\n await new Promise((resolve) => setTimeout(resolve, mock.delay));\n }\n\n if (mock.error) {\n throw mock.error;\n }\n\n const words = mock.content.split(\" \");\n\n for (const word of words) {\n yield { type: \"delta\", content: word + \" \" };\n }\n\n if (mock.toolCalls) {\n for (const toolCall of mock.toolCalls) {\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n };\n }\n }\n\n const response = this.buildResponse(mock);\n\n yield {\n type: \"done\",\n finishReason: response.finishReason,\n usage: response.usage,\n };\n }\n\n /**\n * Reset call history and response pointer back to their initial state.\n * Intended for test-suite `beforeEach` hooks so a single `MockModel`\n * instance can be reused across cases without cross-test leakage.\n */\n public reset(): void {\n this.calls = [];\n this.responseIndex = 0;\n }\n}\n","import type {\n ModelConfig,\n SDKAdapterContract,\n} from \"../contracts/sdk-adapter.contract\";\nimport { approximateTokenCount } from \"../utils/token-count\";\nimport type { MockSDKConfig } from \"./mock-config.type\";\nimport { MockModel } from \"./mock-model\";\n\n/**\n * Creates a mock SDK adapter for testing — no HTTP calls, fully configurable.\n *\n * @example\n * const mock = MockSDK({\n * responses: [\n * { content: \"Hello from mock!\" },\n * { content: \"Second response\" },\n * ],\n * });\n * const model = mock.model({ name: \"gpt-4o\" });\n * const result = await model.complete([{ role: \"user\", content: \"Hi\" }]);\n * console.log(result.content); // \"Hello from mock!\"\n */\nexport function MockSDK(config: MockSDKConfig = {}): SDKAdapterContract & {\n /** All model instances created by this SDK — for inspecting calls in tests */\n models: MockModel[];\n} {\n const models: MockModel[] = [];\n const responses = config.responses ?? [{ content: \"Mock response\" }];\n\n return {\n models,\n model(modelConfig: ModelConfig) {\n const model = new MockModel(\n modelConfig.name ?? config.defaultModelName ?? \"mock-model\",\n responses,\n config.capabilities,\n );\n models.push(model);\n return model;\n },\n async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n },\n };\n}\n","import { agent } from \"../agent/agent\";\nimport type { AgentConfig } from \"../agent/agent-config.type\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ToolContract } from \"../tool/tool\";\nimport type { MockModelResponse } from \"./mock-config.type\";\nimport { MockSDK } from \"./mock-sdk\";\n\n/**\n * Test helper that wires `MockSDK` → mock model → `agent()` in one call.\n *\n * Replaces the 4-line ritual specs typically write:\n * ```ts\n * const mock = MockSDK({ responses: [...] });\n * const myAgent = agent({ name: \"x\", model: mock.model({ name: \"m\" }) });\n * ```\n *\n * Defaults to a single empty `\"stop\"` response — enough to exercise an\n * agent that doesn't need a scripted reply (composition wiring,\n * anonymous-name tests, etc.). Pass `responses` to script outputs.\n *\n * `name` is optional — when omitted the resulting agent runs through\n * the normal anonymous-name fingerprint\n * (`anon_<provider>_<model>[_<tool1>+<tool2>...]`), which is the\n * default for `agent({ model })`.\n *\n * @example\n * const a = mockAgent({ name: \"writer\", responses: [{ content: \"hi\", finishReason: \"stop\" }] });\n * const result = await a.execute(\"anything\");\n */\nexport function mockAgent<TOutput = unknown>(\n options: {\n name?: string;\n responses?: MockModelResponse[];\n tools?: ToolContract<unknown, unknown>[];\n /**\n * Override the model name reported by the mock model. Defaults to\n * `\"mock-model\"` (the MockSDK default). Useful when a test needs\n * deterministic provider/model fingerprinting.\n */\n modelName?: string;\n } = {},\n): AgentContract<TOutput> {\n const responses = options.responses ?? [{ content: \"\", finishReason: \"stop\" as const }];\n const sdk = MockSDK({ responses });\n const model = sdk.model({ name: options.modelName ?? \"mock-model\" });\n\n const config: AgentConfig<TOutput> = { model };\n\n if (options.name !== undefined) {\n config.name = options.name;\n }\n\n if (options.tools !== undefined) {\n config.tools = options.tools;\n }\n\n return agent<TOutput>(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,IAAa,UAAb,cAA6B,MAAM;;yBASuB;;CAMxD,AAAO,YACL,MACA,SACA,SACA,UACA;EACA,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU,SAAS;EACxB,KAAK,WAAW,YAAa,KAAK,YAA+B;EAEjE,IAAI,SAAS,UAAU,QACrB,AAAC,KAA6B,QAAQ,QAAQ;CAElD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;ACnFA,IAAa,sBAAb,cAAyC,QAAQ;CAC/C,AAAO,YACL,SACA,SACA,OAAoB,qBACpB;EACA,MAAM,MAAM,SAAS,OAAO;EAC5B,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,IAAa,sBAAb,cAAyC,oBAAoB;;yBACH;;CAKxD,AAAO,YAAY,SAAiB,SAAsC;EACxE,MAAM,SAAS,SAAS,iBAAiB;EACzC,KAAK,OAAO;EACZ,KAAK,cAAc,SAAS;EAC5B,KAAK,SAAS,SAAS;CACzB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACfA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A0B;GAC9B,MAAM,QAAQ,IAAI,UAChB,YAAY,QAAQ,OAAO,oBAAoB,cAC/C,WACA,OAAO,YACT;GACA,OAAO,KAAK,KAAK;GACjB,OAAO;EACT;EACA,MAAM,MAAM,MAAc,QAAkC;GAC1D,OAAO,sBAAsB,IAAI;EACnC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;ACfA,SAAgB,UACd,UAUI,CAAC,GACmB;CAKxB,MAAM,SAA+B,EAAE,OAH3B,QAAQ,EAAE,WADJ,QAAQ,aAAa,CAAC;EAAE,SAAS;EAAI,cAAc;CAAgB,CAAC,EACtD,CAChB,EAAE,MAAM,EAAE,MAAM,QAAQ,aAAa,aAAa,CAEvB,EAAE;CAE7C,IAAI,QAAQ,SAAS,QACnB,OAAO,OAAO,QAAQ;CAGxB,IAAI,QAAQ,UAAU,QACpB,OAAO,QAAQ,QAAQ;CAGzB,OAAO,MAAe,MAAM;AAC9B"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["LOG_MODULE","called","log","invoke","safeStringify","resolveSnapshotStore","LOG_MODULE_BASE","log","toAIError","computeSignature","hash","computeSignature","generateRunId","validate","asTool","createCancelledError","loadSnapshotForResume","createCancelledError","log","createCancelledError","generateRunId","loadSnapshotForResume","asTool","combined"],"sources":["../../../../../../@warlock.js/ai/src/errors/ai-error.ts","../../../../../../@warlock.js/ai/src/errors/agent-execution-error.ts","../../../../../../@warlock.js/ai/src/errors/agent-cancelled-error.ts","../../../../../../@warlock.js/ai/src/errors/agent-max-trips-error.ts","../../../../../../@warlock.js/ai/src/errors/budget-exceeded-error.ts","../../../../../../@warlock.js/ai/src/errors/provider-error.ts","../../../../../../@warlock.js/ai/src/errors/content-filter-error.ts","../../../../../../@warlock.js/ai/src/errors/context-length-exceeded-error.ts","../../../../../../@warlock.js/ai/src/errors/guardrail-violation-error.ts","../../../../../../@warlock.js/ai/src/errors/invalid-request-error.ts","../../../../../../@warlock.js/ai/src/errors/supervisor-failed-error.ts","../../../../../../@warlock.js/ai/src/errors/max-iterations-error.ts","../../../../../../@warlock.js/ai/src/errors/workflow-error.ts","../../../../../../@warlock.js/ai/src/errors/max-steps-exceeded-error.ts","../../../../../../@warlock.js/ai/src/errors/provider-auth-error.ts","../../../../../../@warlock.js/ai/src/errors/provider-rate-limit-error.ts","../../../../../../@warlock.js/ai/src/errors/provider-timeout-error.ts","../../../../../../@warlock.js/ai/src/errors/quota-exceeded-error.ts","../../../../../../@warlock.js/ai/src/errors/routing-error.ts","../../../../../../@warlock.js/ai/src/errors/schema-validation-error.ts","../../../../../../@warlock.js/ai/src/errors/step-failed-error.ts","../../../../../../@warlock.js/ai/src/errors/supervisor-cancelled-error.ts","../../../../../../@warlock.js/ai/src/errors/supervisor-drift-error.ts","../../../../../../@warlock.js/ai/src/errors/supervisor-routing-error.ts","../../../../../../@warlock.js/ai/src/errors/tool-execution-error.ts","../../../../../../@warlock.js/ai/src/errors/workflow-cancelled-error.ts","../../../../../../@warlock.js/ai/src/errors/workflow-drift-error.ts","../../../../../../@warlock.js/ai/src/middleware/utils/extract-user-text.ts","../../../../../../@warlock.js/ai/src/middleware/utils/namespaced-state.ts","../../../../../../@warlock.js/ai/src/middleware/builtins/budget.ts","../../../../../../@warlock.js/ai/src/middleware/builtins/guardrail.ts","../../../../../../@warlock.js/ai/src/config.ts","../../../../../../@warlock.js/ai/src/middleware/builtins/semantic-cache.ts","../../../../../../@warlock.js/ai/src/middleware/helpers/compose.ts","../../../../../../@warlock.js/ai/src/middleware/helpers/for-tool.ts","../../../../../../@warlock.js/ai/src/middleware/pipeline.ts","../../../../../../@warlock.js/ai/src/utils/compute-cost.ts","../../../../../../@warlock.js/ai/src/utils/extract-json-payload.ts","../../../../../../@warlock.js/ai/src/utils/generate-run-id.ts","../../../../../../@warlock.js/ai/src/utils/json-schema.ts","../../../../../../@warlock.js/ai/src/utils/resolve-attachment.ts","../../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts","../../../../../../@warlock.js/ai/src/utils/safe-json-parse.ts","../../../../../../@warlock.js/ai/src/contracts/result/base-report.type.ts","../../../../../../@warlock.js/ai/src/utils/stamp-report-lineage.ts","../../../../../../@warlock.js/ai/src/utils/token-count.ts","../../../../../../@warlock.js/ai/src/agent/agent-input-builder.ts","../../../../../../@warlock.js/ai/src/agent/agent-log-event.ts","../../../../../../@warlock.js/ai/src/agent/agent-stream.ts","../../../../../../@warlock.js/ai/src/agent/agent-to-stream-event.ts","../../../../../../@warlock.js/ai/src/agent/json-stream-guard.ts","../../../../../../@warlock.js/ai/src/agent/agent.ts","../../../../../../@warlock.js/ai/src/tool/tool.ts","../../../../../../@warlock.js/ai/src/supervisor/as-tool.ts","../../../../../../@warlock.js/ai/src/supervisor/emitter.ts","../../../../../../@warlock.js/ai/src/supervisor/entries.ts","../../../../../../@warlock.js/ai/src/contracts/end.type.ts","../../../../../../@warlock.js/ai/src/supervisor/cancellation.ts","../../../../../../@warlock.js/ai/src/supervisor/router-prompt.ts","../../../../../../@warlock.js/ai/src/supervisor/decide.ts","../../../../../../@warlock.js/ai/src/supervisor/snapshot.ts","../../../../../../@warlock.js/ai/src/supervisor/execution.ts","../../../../../../@warlock.js/ai/src/supervisor/signature.ts","../../../../../../@warlock.js/ai/src/supervisor/supervisor-stream.ts","../../../../../../@warlock.js/ai/src/supervisor/supervisor.ts","../../../../../../@warlock.js/ai/src/system-prompt/render-placeholders.ts","../../../../../../@warlock.js/ai/src/system-prompt/instruction.ts","../../../../../../@warlock.js/ai/src/system-prompt/persona.ts","../../../../../../@warlock.js/ai/src/system-prompt/system-prompt.ts","../../../../../../@warlock.js/ai/src/workflow/step.ts","../../../../../../@warlock.js/ai/src/workflow/as-tool.ts","../../../../../../@warlock.js/ai/src/workflow/emitter.ts","../../../../../../@warlock.js/ai/src/workflow/cancellation.ts","../../../../../../@warlock.js/ai/src/workflow/router.ts","../../../../../../@warlock.js/ai/src/workflow/run-scoped-emitter.ts","../../../../../../@warlock.js/ai/src/workflow/snapshot.ts","../../../../../../@warlock.js/ai/src/workflow/state.ts","../../../../../../@warlock.js/ai/src/workflow/retry.ts","../../../../../../@warlock.js/ai/src/workflow/step-runner.ts","../../../../../../@warlock.js/ai/src/workflow/engine.ts","../../../../../../@warlock.js/ai/src/workflow/signature.ts","../../../../../../@warlock.js/ai/src/workflow/workflow.ts","../../../../../../@warlock.js/ai/src/ai.ts","../../../../../../@warlock.js/ai/src/mock/mock-model.ts","../../../../../../@warlock.js/ai/src/mock/mock-sdk.ts","../../../../../../@warlock.js/ai/src/mock/mock-agent.ts"],"sourcesContent":["import type { ErrorCategory } from \"./error-category.type\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Optional constructor payload shared by every `AIError` subclass.\n *\n * `cause` carries the original thrown value (SDK error, runtime crash,\n * validation failure) so downstream logging and debuggers can still\n * reach it. `context` is a free-form diagnostic bag for provider-raw\n * metadata (status codes, request ids, response headers) that shouldn't\n * be promoted to typed fields but is useful in logs and telemetry.\n *\n * **No `category` here.** Category is fixed per subclass via the\n * class-level `static defaultCategory`. Subclasses ARE their\n * category — `RateLimitError` is always `\"rate-limit\"`, never\n * something else at runtime. Direct `new AIError(...)` callers (the\n * one legitimate override case, since the base catch-all has no\n * specific class) receive a separate 4th constructor argument\n * instead, so the override is structurally unreachable from subclass\n * call sites.\n */\nexport type AIErrorOptions = {\n cause?: unknown;\n context?: Record<string, unknown>;\n};\n\n/**\n * Base class for every error thrown (or surfaced via `result.error`) by\n * `@warlock.js/ai` and its provider adapter packages.\n *\n * **Role.** The single typed error contract across the AI framework.\n * Every thrown error anywhere in `@warlock.js/ai*` is either an\n * `AIError` itself or one of its subclasses — plain `Error` must never\n * leak out. Consumers branch either on the narrow `error.code` (stable\n * string), on `error.category` (coarse dashboard grouping), or on\n * `instanceof` a specific subclass.\n *\n * **Independence.** Deliberately extends the platform `Error` directly\n * — never `HttpError` from `@warlock.js/core`. The AI framework is a\n * standalone product; coupling its error base to a web framework would\n * force every consumer to pull in the HTTP layer even when they only\n * use AI in a CLI, worker, or test.\n *\n * **Fields.**\n * - `code` — stable machine-readable identifier (see `AIErrorCode`).\n * - `category` — coarse `ErrorCategory` for dashboards / retry policy.\n * Resolved at construction from the subclass's `static defaultCategory`\n * (or, for direct `new AIError(...)` calls, from the explicit 4th\n * constructor argument).\n * - `cause` — optional original thrown value (SDK error, nested error,\n * raw value). Preserves root cause through re-wrapping.\n * - `context` — optional free-form diagnostic bag (status, requestId,\n * headers). Consumers treat it as opaque; logs and telemetry read it.\n *\n * **Category override — direct AIError usage only.** Subclasses ARE\n * their category by type; there's no legitimate runtime override at\n * the subclass level. The 4th constructor argument exists ONLY for\n * direct `new AIError(...)` callers, who would otherwise be stuck with\n * the `\"unknown\"` default. Subclasses construct via `super(code,\n * message, options)` and physically cannot reach the override slot\n * through their own typed signatures.\n *\n * @example\n * try {\n * await agent.execute(\"hello\");\n * } catch (error) {\n * if (error instanceof AIError) {\n * console.error(`[${error.code}] (${error.category}) ${error.message}`);\n * }\n * }\n *\n * @example\n * // Direct AIError construction with explicit category — escape hatch\n * // for call sites that lack a specific subclass.\n * throw new AIError(\"UNEXPECTED\", \"transient glitch\", undefined, \"provider\");\n */\nexport class AIError extends Error {\n /**\n * Class-level category for every instance of this error type.\n * Subclasses redeclare with their own concrete `ErrorCategory` so\n * `error.category` is correct without per-call wiring. The base\n * class keeps `\"unknown\"` so untyped direct throws of `AIError`\n * itself remain honest about their lack of dispatch information\n * (and can override via the 4th constructor argument).\n */\n public static readonly defaultCategory: ErrorCategory = \"unknown\";\n\n public readonly code: AIErrorCode;\n public readonly category: ErrorCategory;\n public readonly context?: Record<string, unknown>;\n\n public constructor(\n code: AIErrorCode,\n message: string,\n options?: AIErrorOptions,\n category?: ErrorCategory,\n ) {\n super(message);\n\n this.name = \"AIError\";\n this.code = code;\n this.context = options?.context;\n this.category = category ?? (this.constructor as typeof AIError).defaultCategory;\n\n if (options?.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base for agent runtime failures that aren't schema / tool / provider\n * problems — runtime-structural issues inside the trip loop or\n * authoring-time middleware misconfiguration. Two specialized\n * subclasses cover the two non-generic cases:\n *\n * - {@link AgentCancelledError} (`AGENT_CANCELLED`) — caller-driven\n * abort via `AbortSignal`.\n * - {@link AgentMaxTripsError} (`AGENT_MAX_TRIPS`) — trip loop hit\n * the `maxTrips` cap without a natural stop.\n *\n * Use the base class directly for anything else (unregistered tool\n * dispatch, authoring-time middleware validation, surprise\n * exceptions). The subclasses exist so consumers can branch on a\n * dedicated `instanceof` / category without inferring from `context`\n * flags or parsing the message.\n *\n * @example\n * if (result.error?.code === \"AGENT_EXEC_FAILED\") {\n * logger.warn(\"unexpected agent failure\", result.error.context);\n * }\n */\nexport class AgentExecutionError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"AGENT_EXEC_FAILED\",\n ) {\n super(code, message, options);\n this.name = \"AgentExecutionError\";\n }\n}\n","import { AgentExecutionError } from \"./agent-execution-error\";\nimport type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload for {@link AgentCancelledError}. `cancelledAt` is the\n * ISO-8601 timestamp at which the abort was observed; `reason`\n * carries the value the caller supplied to `controller.abort(reason)`\n * when present.\n */\nexport type AgentCancelledErrorOptions = AIErrorOptions & {\n cancelledAt?: string;\n reason?: string;\n};\n\n/**\n * Agent run was cancelled via `AbortSignal` before it could finish.\n * Between-trip cancellation is guaranteed; mid-trip cancellation is\n * best-effort (the signal is threaded into the provider adapter's\n * HTTP client when supported).\n *\n * Surfaced on `result.error` rather than thrown — `agent.execute()`\n * still returns with `report.status = \"cancelled\"` and partial trip\n * history intact. Consumers branch on the class (not the message) to\n * distinguish caller-initiated stops from other failures.\n *\n * **Why split from `AgentExecutionError`.** Cancellation is a\n * different operational signal from \"the agent crashed\" — retry\n * policy and dashboards typically want different behavior for each.\n * Keeping cancellation in its own class lets the category\n * (`\"cancelled\"`) be set declaratively per type instead of inferred\n * from a `context.cancelled === true` flag.\n *\n * @example\n * const result = await agent.execute(input, { signal });\n * if (result.error instanceof AgentCancelledError) {\n * // caller pulled the plug — don't retry, surface a \"stopped\" UI\n * return { status: \"cancelled\" };\n * }\n */\nexport class AgentCancelledError extends AgentExecutionError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt?: string;\n public readonly reason?: string;\n\n public constructor(message: string, options?: AgentCancelledErrorOptions) {\n super(message, options, \"AGENT_CANCELLED\");\n this.name = \"AgentCancelledError\";\n this.cancelledAt = options?.cancelledAt;\n this.reason = options?.reason;\n }\n}\n","import { AgentExecutionError } from \"./agent-execution-error\";\nimport type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload for {@link AgentMaxTripsError}. `maxTrips` is the cap the\n * agent hit — useful for log/metric attribution and for retry-with-\n * higher-cap recovery strategies.\n */\nexport type AgentMaxTripsErrorOptions = AIErrorOptions & {\n maxTrips: number;\n};\n\n/**\n * Runaway-loop hard guard: the agent's trip loop ran `maxTrips` round\n * trips to the model without the model issuing a natural stop. The\n * loop terminates with this typed error on `result.error` and the\n * full trip history preserved in `result.report.trips` so consumers\n * can see where the loop got stuck.\n *\n * **Not retryable by default.** A run that hit the cap usually\n * indicates either a tool the agent can't satisfy (causing infinite\n * re-asks) or a model that won't commit to an answer. Bumping\n * `maxTrips` and retrying without root-causing the underlying issue\n * just burns more tokens.\n *\n * **Why split from `AgentExecutionError`.** The catch-all base wears\n * too many hats — cancellation vs. max-trips vs. generic crashes had\n * to be disambiguated from `context` flags or message regex. Split\n * subclasses let category dispatch (`\"max-trips\"`) and consumer\n * branching (`instanceof`) work without inference.\n *\n * @example\n * if (result.error instanceof AgentMaxTripsError) {\n * logger.warn(\"agent hit trip cap\", { max: result.error.maxTrips });\n * }\n */\nexport class AgentMaxTripsError extends AgentExecutionError {\n public static readonly defaultCategory: ErrorCategory = \"max-trips\";\n\n public readonly maxTrips: number;\n\n public constructor(message: string, options: AgentMaxTripsErrorOptions) {\n super(message, options, \"AGENT_MAX_TRIPS\");\n this.name = \"AgentMaxTripsError\";\n this.maxTrips = options.maxTrips;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Unit of the budget being enforced. `tokens` for context/output\n * caps, `usd` for monetary caps, `requests` for call-count caps.\n */\nexport type BudgetUnit = \"tokens\" | \"usd\" | \"requests\";\n\n/**\n * Payload for `BudgetExceededError`. All three fields are required so\n * consumers can present the breach numerically without having to\n * reparse the message.\n */\nexport type BudgetExceededErrorOptions = AIErrorOptions & {\n limit: number;\n actual: number;\n unit: BudgetUnit;\n};\n\n/**\n * A user- or framework-configured budget was exceeded mid-execution.\n *\n * **Not thrown yet.** The class is defined here so v2's budget\n * middleware can throw it without a breaking release of the error\n * hierarchy. Shape is locked: `{ limit, actual, unit }`.\n *\n * @example\n * if (error instanceof BudgetExceededError && error.unit === \"usd\") {\n * alertFinance(error.actual, error.limit);\n * }\n */\nexport class BudgetExceededError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"budget\";\n\n public readonly limit: number;\n public readonly actual: number;\n public readonly unit: BudgetUnit;\n\n public constructor(message: string, options: BudgetExceededErrorOptions) {\n super(\"BUDGET_EXCEEDED\", message, options);\n this.name = \"BudgetExceededError\";\n this.limit = options.limit;\n this.actual = options.actual;\n this.unit = options.unit;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Any failure that originated from the model provider (OpenAI, Azure,\n * OpenRouter, local gateway). Base class for the provider subclasses\n * below — raw provider errors caught in an adapter are always wrapped\n * into *some* `ProviderError` so downstream code can branch on\n * `instanceof ProviderError` when any provider-side failure will do.\n *\n * **Subclasses (more specific first).**\n * - `ProviderRateLimitError` — 429 / rate-limit / quota exhaustion.\n * - `ProviderTimeoutError` — connection or request timeout.\n * - `ContextLengthExceededError` — prompt exceeded the model window.\n * - `ContentFilterError` — response blocked by provider safety policy.\n * - `ProviderAuthError` — bad / expired API key.\n * - `InvalidRequestError` — catch-all 4xx not covered above.\n *\n * When no subclass fits (e.g. 5xx server error, unknown network\n * failure), adapters throw plain `ProviderError` with the raw payload\n * captured in `context`.\n *\n * @example\n * if (result.error instanceof ProviderError) {\n * if (result.error instanceof ProviderRateLimitError) {\n * return retryAfter(result.error.retryAfter ?? 1000);\n * }\n * }\n */\nexport class ProviderError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"provider\";\n\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"PROVIDER_ERROR\",\n ) {\n super(code, message, options);\n this.name = \"ProviderError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ContentFilterError`. Both fields optional — providers\n * don't consistently disclose the specific filter reason or\n * categories, especially when the block is pre-generation.\n */\nexport type ContentFilterErrorOptions = AIErrorOptions & {\n reason?: string;\n categories?: string[];\n};\n\n/**\n * Response (or request) was blocked by the provider's safety filter.\n * Not retryable with the same input — reshape the prompt or lean on\n * a less-restrictive model.\n *\n * @example\n * if (result.error instanceof ContentFilterError) {\n * return respondWithPolicyMessage(result.error.reason);\n * }\n */\nexport class ContentFilterError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"content-filter\";\n\n public readonly reason?: string;\n public readonly categories?: string[];\n\n public constructor(message: string, options?: ContentFilterErrorOptions) {\n super(message, options, \"CONTENT_FILTER\");\n this.name = \"ContentFilterError\";\n this.reason = options?.reason;\n this.categories = options?.categories;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ContextLengthExceededError`. All fields are optional —\n * providers inconsistently surface exact token counts and the\n * model's limit. When present, they let callers compute a trim\n * target; when absent, the error still categorizes the failure.\n */\nexport type ContextLengthExceededErrorOptions = AIErrorOptions & {\n limit?: number;\n actual?: number;\n modelName?: string;\n};\n\n/**\n * The request's prompt (messages + tools + schema) exceeded the\n * model's context window. Not retryable without shortening the input.\n *\n * Typically surfaced as OpenAI 400 with `code: \"context_length_exceeded\"`.\n *\n * @example\n * if (result.error instanceof ContextLengthExceededError) {\n * messages = truncateOldestTurns(messages);\n * return agent.execute(input, { history: messages });\n * }\n */\nexport class ContextLengthExceededError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"context-length\";\n\n public readonly limit?: number;\n public readonly actual?: number;\n public readonly modelName?: string;\n\n public constructor(\n message: string,\n options?: ContextLengthExceededErrorOptions,\n ) {\n super(message, options, \"CONTEXT_LENGTH_EXCEEDED\");\n this.name = \"ContextLengthExceededError\";\n this.limit = options?.limit;\n this.actual = options?.actual;\n this.modelName = options?.modelName;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Phase at which a guardrail rejected the content — `\"input\"` when the\n * violation was detected on the outbound prompt (before the model saw\n * it), `\"output\"` when it was detected on the model's response (before\n * the caller saw it).\n */\nexport type GuardrailPhase = \"input\" | \"output\";\n\n/**\n * Payload for `GuardrailViolationError`. `phase` tells the caller\n * whether the prompt or the response tripped the check; `reason` is\n * the free-form explanation the guardrail middleware produced;\n * `guardrail` names the offending middleware so operators can tune a\n * specific rule without hunting through logs.\n */\nexport type GuardrailViolationErrorOptions = AIErrorOptions & {\n phase: GuardrailPhase;\n reason: string;\n guardrail?: string;\n};\n\n/**\n * A guardrail middleware rejected the prompt or response mid-execution.\n *\n * **Role.** The typed abort surface for `ai.middleware.guardrail`.\n * Consumers branch on `error.phase` to distinguish \"the user asked\n * something disallowed\" (`\"input\"`) from \"the model produced something\n * disallowed\" (`\"output\"`) — the two failure modes have very different\n * product responses (block vs. retry, or surface a policy message vs.\n * re-prompt the model).\n *\n * Thrown from inside the middleware pipeline's `trip.before` / `trip.after`\n * hooks; surfaced to the caller via `result.error` like every other\n * `AIError`.\n *\n * @example\n * if (result.error instanceof GuardrailViolationError) {\n * if (result.error.phase === \"input\") {\n * return respondWithPolicyMessage(result.error.reason);\n * }\n * return retryWithSanitizedPrompt();\n * }\n */\nexport class GuardrailViolationError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"guardrail\";\n\n public readonly phase: GuardrailPhase;\n public readonly reason: string;\n public readonly guardrail?: string;\n\n public constructor(message: string, options: GuardrailViolationErrorOptions) {\n super(\"GUARDRAIL_VIOLATION\", message, options);\n\n this.name = \"GuardrailViolationError\";\n this.phase = options.phase;\n this.reason = options.reason;\n this.guardrail = options.guardrail;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider rejected the request as malformed — bad model name,\n * unsupported feature, missing required field, image attached to a\n * non-vision model, etc. The catch-all for 4xx responses that aren't\n * auth, rate-limit, context-length, or content-filter.\n *\n * Also thrown from the agent when user-side validation fails at the\n * boundary (e.g. vision gate, malformed attachment shape) — the\n * category is \"you sent something the provider / agent cannot use\".\n *\n * @example\n * if (result.error instanceof InvalidRequestError) {\n * logger.error(\"bad agent input\", { context: result.error.context });\n * }\n */\nexport class InvalidRequestError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"validation\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_INVALID_REQUEST\");\n this.name = \"InvalidRequestError\";\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base class for every supervisor-specific failure surfaced from\n * `supervisor.execute()` / `supervisor.resume()` / authoring-time\n * `ai.supervisor()` validation.\n *\n * **Role.** Anchor for the `SUPERVISOR_*` code family. Subclasses\n * carry precise codes (`SUPERVISOR_MAX_ITERATIONS`,\n * `SUPERVISOR_INVALID_ROUTE`, …); this base catches everything a\n * supervisor run can produce that isn't already an agent / tool /\n * provider / workflow error bubbling up from a child execution.\n *\n * Child-execution errors (agent, tool, provider, workflow) flow\n * through the supervisor unchanged — they are captured on the\n * relevant branch snapshot and, if fatal, wrapped as the `cause` of a\n * `SupervisorFailedError` only when the supervisor itself has no\n * narrower subclass to throw.\n *\n * @example\n * try {\n * ai.supervisor({\n * route: () => \"triage\",\n * router: routerAgent,\n * intents: { triage },\n * });\n * } catch (error) {\n * if (error instanceof SupervisorFailedError) {\n * console.error(error.code, error.message);\n * }\n * }\n */\nexport class SupervisorFailedError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"SUPERVISOR_FAILED\",\n ) {\n super(code, message, options);\n this.name = \"SupervisorFailedError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type MaxIterationsErrorOptions = AIErrorOptions & {\n maxIterations: number;\n};\n\n/**\n * Hard-cap guard: the supervisor ran `maxIterations` loop turns\n * without reaching a terminal decision (`END`, `satisfied: true`, or\n * cancellation). Terminates the run immediately with a typed error on\n * `result.error` — partial per-iteration snapshots are still\n * available on `result.report.snapshots`.\n *\n * @example\n * const { error, report } = await supervisor.execute(input);\n * if (error?.code === \"SUPERVISOR_MAX_ITERATIONS\") {\n * logger.warn(\"supervisor did not converge\", {\n * iterations: report.iterations,\n * });\n * }\n */\nexport class MaxIterationsError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"max-iterations\";\n\n public readonly maxIterations: number;\n\n public constructor(message: string, options: MaxIterationsErrorOptions) {\n super(message, options, \"SUPERVISOR_MAX_ITERATIONS\");\n this.name = \"MaxIterationsError\";\n this.maxIterations = options.maxIterations;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { AIErrorCode } from \"./error-code.type\";\n\n/**\n * Base class for all workflow-specific failures. Subclasses carry\n * precise codes; this base catches everything `workflow.execute()`\n * can produce beyond agent/tool/provider errors.\n */\nexport class WorkflowError extends AIError {\n public constructor(\n message: string,\n options?: AIErrorOptions,\n code: AIErrorCode = \"WORKFLOW_ERROR\",\n ) {\n super(code, message, options);\n this.name = \"WorkflowError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type MaxStepsExceededErrorOptions = AIErrorOptions & {\n maxSteps: number;\n};\n\n/**\n * Runaway-loop hard guard: workflow executed more step transitions\n * than `maxSteps` allows. Terminates the workflow immediately.\n */\nexport class MaxStepsExceededError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"max-steps\";\n\n public readonly maxSteps: number;\n\n public constructor(message: string, options: MaxStepsExceededErrorOptions) {\n super(message, options, \"WORKFLOW_MAX_STEPS\");\n this.name = \"MaxStepsExceededError\";\n this.maxSteps = options.maxSteps;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider rejected the credential — missing / invalid / expired API\n * key or insufficient permissions on the underlying account. Not\n * retryable; fix the credential and retry.\n *\n * @example\n * if (result.error instanceof ProviderAuthError) {\n * notifyOps(\"rotate API key\", result.error.context);\n * }\n */\nexport class ProviderAuthError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"auth\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_AUTH\");\n this.name = \"ProviderAuthError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Payload for `ProviderRateLimitError`. `retryAfter` is the server's\n * hint (typically parsed from the `Retry-After` header) in milliseconds.\n */\nexport type ProviderRateLimitErrorOptions = AIErrorOptions & {\n retryAfter?: number;\n};\n\n/**\n * Provider refused the call because the account (or key, or window)\n * is over its rate-limit or quota. Retryable after `retryAfter`\n * milliseconds — consumers are expected to back off before retrying.\n *\n * Covers both transient `429 Too Many Requests` and the billing-level\n * `insufficient_quota` case; the adapter decides which provider\n * signals map here.\n *\n * @example\n * if (result.error instanceof ProviderRateLimitError) {\n * await sleep(result.error.retryAfter ?? 1000);\n * }\n */\nexport class ProviderRateLimitError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"rate-limit\";\n\n public readonly retryAfter?: number;\n\n public constructor(message: string, options?: ProviderRateLimitErrorOptions) {\n super(message, options, \"PROVIDER_RATE_LIMIT\");\n this.name = \"ProviderRateLimitError\";\n this.retryAfter = options?.retryAfter;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider call timed out — either at the transport layer (socket\n * connection) or on the server side (request exceeded the provider's\n * processing deadline). Idempotent retries are usually safe.\n *\n * @example\n * if (result.error instanceof ProviderTimeoutError) {\n * return retry();\n * }\n */\nexport class ProviderTimeoutError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"timeout\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_TIMEOUT\");\n this.name = \"ProviderTimeoutError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { ProviderError } from \"./provider-error\";\n\n/**\n * Provider refused the call because the account has exhausted its\n * paid quota (monthly credit, billing cap, subscription tier limit).\n *\n * **Not retryable.** Unlike `ProviderRateLimitError` — where the\n * bucket refills after `retryAfter` milliseconds — this one needs\n * human intervention: top up the account, upgrade the plan, or\n * switch to a different key. Consumers who blindly back-off-and-retry\n * on rate-limit errors would loop forever here, which is why the two\n * are split.\n *\n * Typically surfaced as OpenAI `code: \"insufficient_quota\"`.\n *\n * **Distinct from `BudgetExceededError`.** `QuotaExceededError` is\n * the *provider* telling us their billing cap is hit.\n * `BudgetExceededError` is our *own* middleware enforcing a\n * user-configured ceiling client-side.\n *\n * @example\n * if (result.error instanceof QuotaExceededError) {\n * await pagerDuty.trigger(\"openai quota exhausted\");\n * return fallbackResponse();\n * }\n */\nexport class QuotaExceededError extends ProviderError {\n public static readonly defaultCategory: ErrorCategory = \"quota\";\n\n public constructor(message: string, options?: AIErrorOptions) {\n super(message, options, \"PROVIDER_QUOTA_EXCEEDED\");\n this.name = \"QuotaExceededError\";\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type RoutingErrorOptions = AIErrorOptions & {\n stepName: string;\n targetName?: string;\n};\n\n/**\n * `nextStep` returned an invalid `goto`, or the `nextStep` callback\n * itself threw. Routing is authoritative and has no recovery path —\n * the workflow terminates immediately.\n */\nexport class RoutingError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"routing\";\n\n public readonly stepName: string;\n public readonly targetName?: string;\n\n public constructor(message: string, options: RoutingErrorOptions) {\n super(message, options, \"WORKFLOW_INVALID_GOTO\");\n this.name = \"RoutingError\";\n this.stepName = options.stepName;\n this.targetName = options.targetName;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload passed to `SchemaValidationError`. Subset of\n * `AIErrorOptions` plus the machine-readable validation issues list.\n */\nexport type SchemaValidationErrorOptions = AIErrorOptions & {\n issues?: readonly StandardSchemaV1.Issue[];\n};\n\n/**\n * A `StandardSchemaV1` validation call returned issues, or the input\n * was not valid JSON before validation could even run.\n *\n * Produced in two places today:\n * - Agent output parsing — the final trip text failed `JSON.parse` or\n * the parsed value failed `~standard.validate`.\n * - Tool input validation — the model's raw arguments for a tool call\n * didn't match the tool's `input` schema.\n *\n * `issues` carries the structured validation result when available so\n * consumers can present per-field feedback.\n *\n * @example\n * if (result.error instanceof SchemaValidationError) {\n * for (const issue of result.error.issues ?? []) {\n * console.warn(issue.path, issue.message);\n * }\n * }\n */\nexport class SchemaValidationError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"schema\";\n\n public readonly issues?: readonly StandardSchemaV1.Issue[];\n\n public constructor(message: string, options?: SchemaValidationErrorOptions) {\n super(\"SCHEMA_VALIDATION_FAILED\", message, options);\n this.name = \"SchemaValidationError\";\n this.issues = options?.issues;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type StepFailedErrorOptions = AIErrorOptions & {\n stepName: string;\n attempts: number;\n};\n\n/**\n * A workflow step exhausted its retries (or was not retried) and\n * terminated with an error. `cause` carries the last underlying error.\n */\nexport class StepFailedError extends WorkflowError {\n public readonly stepName: string;\n public readonly attempts: number;\n\n public constructor(message: string, options: StepFailedErrorOptions) {\n super(message, options, \"STEP_FAILED\");\n this.name = \"StepFailedError\";\n this.stepName = options.stepName;\n this.attempts = options.attempts;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorCancelledErrorOptions = AIErrorOptions & {\n /** ISO-8601 timestamp at which the abort was observed by the supervisor. */\n cancelledAt: string;\n /** `controller.abort(reason)` payload when the caller supplied one. */\n reason?: string;\n};\n\n/**\n * Supervisor run was cancelled via `AbortSignal` before it could\n * finish. Between-iteration cancellation is guaranteed; mid-iteration\n * cancellation is best-effort (the signal is also threaded into every\n * in-flight child `execute()` call, but effectiveness depends on the\n * child primitive respecting it).\n *\n * On cancellation the supervisor returns normally with `status:\n * \"cancelled\"` and partial `report.snapshots` — the error is placed\n * on `result.error` rather than thrown.\n */\nexport class SupervisorCancelledError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt: string;\n public readonly reason?: string;\n\n public constructor(\n message: string,\n options: SupervisorCancelledErrorOptions,\n ) {\n super(message, options, \"SUPERVISOR_CANCELLED\");\n this.name = \"SupervisorCancelledError\";\n this.cancelledAt = options.cancelledAt;\n this.reason = options.reason;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorDriftErrorOptions = AIErrorOptions & {\n /** Signature recorded on the snapshot being resumed. */\n savedSignature: string;\n /** Signature computed from the current supervisor definition. */\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `supervisor.resume(runId)` loaded a snapshot whose structural\n * fingerprint does not match the current supervisor definition\n * (agent keys + descriptions + router identity + route presence).\n * The resume is refused — no iteration runs — and the user decides\n * how to recover: discard the snapshot, migrate manually, or call\n * `resume(runId, { force: true })` to bypass the check.\n *\n * Mirrors `WorkflowDriftError` for workflow resume — same rationale,\n * different primitive.\n */\nexport class SupervisorDriftError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: SupervisorDriftErrorOptions) {\n super(message, options, \"SUPERVISOR_DRIFT\");\n this.name = \"SupervisorDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { SupervisorFailedError } from \"./supervisor-failed-error\";\n\nexport type SupervisorRoutingErrorOptions = AIErrorOptions & {\n /**\n * The raw value the `route` callback or router agent returned. Keyed\n * `unknown` because a misbehaving router can emit any JSON value —\n * consumers should format it for display, not trust its shape.\n */\n returned: unknown;\n /** Every legal intent key configured on the supervisor at run time. */\n availableKeys: string[];\n};\n\n/**\n * A `route` callback or router agent returned a value that doesn't\n * resolve to a configured agent key, a `string[]` of configured keys,\n * or the `END` sentinel. Routing is authoritative — there is no\n * recovery path, so the supervisor terminates the run immediately.\n *\n * Named `SupervisorRoutingError` (not `RoutingError`) to avoid\n * colliding with `@warlock.js/ai`'s existing workflow `RoutingError`\n * (`WORKFLOW_INVALID_GOTO`). Both carry the same semantic weight —\n * \"routing asked for something I can't dispatch\" — in their\n * respective primitives.\n *\n * @example\n * const { error } = await supervisor.execute(input);\n * if (error?.code === \"SUPERVISOR_INVALID_ROUTE\") {\n * logger.error(\"bad router decision\", {\n * returned: (error as SupervisorRoutingError).returned,\n * available: (error as SupervisorRoutingError).availableKeys,\n * });\n * }\n */\nexport class SupervisorRoutingError extends SupervisorFailedError {\n public static readonly defaultCategory: ErrorCategory = \"routing\";\n\n public readonly returned: unknown;\n public readonly availableKeys: string[];\n\n public constructor(message: string, options: SupervisorRoutingErrorOptions) {\n super(message, options, \"SUPERVISOR_INVALID_ROUTE\");\n this.name = \"SupervisorRoutingError\";\n this.returned = options.returned;\n this.availableKeys = options.availableKeys;\n }\n}\n","import { AIError, type AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Payload passed to `ToolExecutionError` — identifies which tool\n * failed and, when applicable, which trip it was dispatched from.\n */\nexport type ToolExecutionErrorOptions = AIErrorOptions & {\n toolName: string;\n tripIndex?: number;\n};\n\n/**\n * A registered tool's `execute()` threw during dispatch — the tool\n * code itself failed (not its input schema). The model's request was\n * valid; the implementation crashed.\n *\n * Carries `toolName` so consumers can branch on which tool failed\n * without regex-parsing the message, and `tripIndex` to correlate\n * with the `LLMTrip` entry in `result.report.trips`.\n *\n * @example\n * if (result.error instanceof ToolExecutionError) {\n * metrics.increment(\"tool.failure\", { tool: result.error.toolName });\n * }\n */\nexport class ToolExecutionError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"tool\";\n\n public readonly toolName: string;\n public readonly tripIndex?: number;\n\n public constructor(message: string, options: ToolExecutionErrorOptions) {\n super(\"TOOL_EXEC_FAILED\", message, options);\n this.name = \"ToolExecutionError\";\n this.toolName = options.toolName;\n this.tripIndex = options.tripIndex;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type WorkflowCancelledErrorOptions = AIErrorOptions & {\n cancelledAt: string;\n reason?: string;\n};\n\n/**\n * Workflow was cancelled via `AbortSignal` before it could finish.\n * `cancelledAt` is ISO timestamp at abort; `reason` carries the\n * `controller.abort(reason)` payload when provided.\n */\nexport class WorkflowCancelledError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"cancelled\";\n\n public readonly cancelledAt: string;\n public readonly reason?: string;\n\n public constructor(message: string, options: WorkflowCancelledErrorOptions) {\n super(message, options, \"WORKFLOW_CANCELLED\");\n this.name = \"WorkflowCancelledError\";\n this.cancelledAt = options.cancelledAt;\n this.reason = options.reason;\n }\n}\n","import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { WorkflowError } from \"./workflow-error\";\n\nexport type WorkflowDriftErrorOptions = AIErrorOptions & {\n savedSignature: string;\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `workflow.resume(runId)` found a snapshot whose structural signature\n * doesn't match the current workflow definition. Thrown without\n * executing anything. User must discard, force, or migrate manually.\n */\nexport class WorkflowDriftError extends WorkflowError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: WorkflowDriftErrorOptions) {\n super(message, options, \"WORKFLOW_DRIFT\");\n this.name = \"WorkflowDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n","import type { Message } from \"../../contracts/conversation-message.type\";\n\n/**\n * Pull the text a content-inspection middleware should care about\n * from the outbound message list.\n *\n * **Role.** Built-ins that inspect \"what the user just said\" — the\n * guardrail on `trip.before`, the semantic cache on `trip.before`,\n * future consumers like PII redactors — all need the same string:\n * the most recent `user`-role message's text content. This helper\n * is the single authority on how that string is resolved.\n *\n * **Behavior.**\n * - Walks `messages` from the end backwards so the LAST user turn\n * wins (correct when the agent has history + a fresh prompt).\n * - Returns a plain string directly when `content` is a string.\n * - Joins `text` parts with `\"\\n\"` when `content` is a multipart\n * `ContentPart[]`. Non-text parts (images, audio) are skipped —\n * callers concerned with multimodal content inspect `request`\n * / attachments separately.\n * - Returns `\"\"` when there is no user message at all (e.g. a trip\n * composed entirely of tool results).\n *\n * @example\n * const prompt = extractUserText(context.messages);\n * if (!prompt) return;\n * const verdict = await inputCheck(prompt);\n */\nexport function extractUserText(messages: ReadonlyArray<Message>): string {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n\n if (message.role !== \"user\") {\n continue;\n }\n\n if (typeof message.content === \"string\") {\n return message.content;\n }\n\n if (Array.isArray(message.content)) {\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"\\n\");\n }\n }\n\n return \"\";\n}\n","import type { MiddlewareState } from \"../../contracts/middleware\";\n\n/**\n * Typed accessor over `ctx.state` for a single namespace key. Wraps\n * the raw `Map<string, unknown>` so middleware authors stop typing\n * `as Counters | undefined` on every read.\n *\n * **Role.** Every built-in middleware reads and writes one or two\n * entries in `ctx.state` under its own name. Without a helper,\n * every call-site looks like:\n *\n * ```ts\n * const counters = context.state.get(\"budget.counters\") as Counters | undefined;\n * if (!counters) { ... }\n * counters.tokens += n;\n * ```\n *\n * — cast noise, no type narrowing on `set`, no protection against\n * key typos. `namespacedState<T>` eliminates all three.\n *\n * **Scope.** Deliberately narrow: one key, typed value, four methods\n * (`get` / `set` / `delete` / `has`). Does NOT try to model compound\n * or nested keys — if you need those, use the raw `ctx.state` Map\n * directly, or create a second namespaced accessor for the second key.\n *\n * **Namespace convention.** Use the middleware's `name` as the key\n * (or a `name.<field>` prefix when a middleware needs multiple\n * entries). The pipeline does not enforce this — it is a convention\n * the built-ins follow to avoid collisions between middlewares.\n *\n * @example\n * // Inside a budget middleware:\n * const counters = namespacedState<Counters>(ctx, \"budget\");\n *\n * if (!counters.has()) {\n * counters.set({ tokens: 0, costUSD: 0 });\n * }\n *\n * const current = counters.get()!;\n * current.tokens += response.usage.total;\n */\nexport function namespacedState<T>(\n ctx: { readonly state: MiddlewareState },\n namespace: string,\n): NamespacedStateAccessor<T> {\n return {\n get(): T | undefined {\n return ctx.state.get(namespace) as T | undefined;\n },\n set(value: T): void {\n ctx.state.set(namespace, value);\n },\n delete(): void {\n ctx.state.delete(namespace);\n },\n has(): boolean {\n return ctx.state.has(namespace);\n },\n };\n}\n\n/**\n * Four-method accessor returned by `namespacedState`. Callers hold\n * it for the lifetime of a hook body — it is a thin typed view over\n * `ctx.state`, not a detached snapshot. Reads are live; writes hit\n * the underlying Map immediately and are visible to every other\n * hook that uses the same namespace.\n */\nexport type NamespacedStateAccessor<T> = {\n get(): T | undefined;\n set(value: T): void;\n delete(): void;\n has(): boolean;\n};\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\nimport { BudgetExceededError, type BudgetUnit } from \"../../errors\";\nimport { namespacedState } from \"../utils\";\n\n/**\n * Per-model pricing used to compute USD cost from token counts.\n * Caller-supplied — no bundled table. Keys are model names (the\n * `ModelContract.name` value); values are input / output token\n * prices expressed as **USD per 1K tokens** to match every major\n * provider's published pricing sheet.\n */\nexport type BudgetPricing = Record<\n string,\n {\n /** USD per 1,000 input tokens. */\n inputPer1K: number;\n /** USD per 1,000 output tokens. */\n outputPer1K: number;\n }\n>;\n\n/**\n * Configuration for `budget()`. At least one of `maxTokens` or\n * `maxCostUSD` must be supplied — a budget with no cap is a no-op.\n */\nexport type BudgetOptions = {\n /**\n * Hard cap on cumulative total tokens (input + output, summed\n * across every trip of the run). Inclusive — exceeding triggers\n * the configured `onExceeded`.\n */\n maxTokens?: number;\n /**\n * Hard cap on cumulative USD cost. Requires `pricing` for the\n * agent's configured model — without a pricing entry the USD check\n * silently skips (tokens-only enforcement still applies).\n */\n maxCostUSD?: number;\n /**\n * Per-model pricing table used to compute USD cost. Only consulted\n * when `maxCostUSD` is set. Model names must match the running\n * agent's `ModelContract.name` exactly.\n */\n pricing?: BudgetPricing;\n /**\n * Behavior when a cap is breached. `\"abort\"` throws\n * `BudgetExceededError` — surfaces on `result.error`, stops the\n * run at the next trip boundary. `\"warn\"` logs a warning and\n * lets the run continue (useful for observability-first rollouts\n * before flipping the switch to abort). Default `\"abort\"`.\n */\n onExceeded?: \"abort\" | \"warn\";\n /**\n * Override the middleware name. Useful when two budgets coexist\n * (e.g. a per-request cap plus a session-wide cap via different\n * instances). Default `\"budget\"`.\n */\n name?: string;\n};\n\ntype BudgetCounters = {\n tokens: number;\n costUSD: number;\n warned: boolean;\n};\n\nfunction breach(\n limit: number,\n actual: number,\n unit: BudgetUnit,\n name: string,\n): never {\n throw new BudgetExceededError(\n `budget \"${name}\" exceeded — ${actual} ${unit} (cap: ${limit})`,\n { limit, actual, unit },\n );\n}\n\n/**\n * Enforced token and / or USD budget for an agent run.\n *\n * **Role.** Guards against runaway tool loops, misconfigured\n * prompts, and unexpected provider price swings by capping\n * cumulative usage across every LLM trip of a single execution.\n * Aborts the run with a typed `BudgetExceededError` the moment a cap\n * is breached, rather than letting the damage grow trip by trip.\n *\n * **Scope.** Per-execution. A fresh counter is created at\n * `execute.before` and lives in the middleware state bag until the\n * run ends. Two concurrent `agent.execute()` calls on the same\n * agent therefore enforce the cap independently.\n *\n * **Token accounting.** After each successful trip, the middleware\n * adds `response.usage.total` to its running total and checks\n * against `maxTokens`. Synthetic trips (cache hits) contribute\n * `usage.total` as returned by the cache — cache middleware is\n * expected to surface zero usage on a hit, which naturally excludes\n * those trips from the budget.\n *\n * **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are\n * both present, the middleware converts per-trip input / output\n * tokens to USD and accumulates. Missing pricing silently degrades\n * to tokens-only — explicit rather than guessing.\n *\n * **Warn mode.** `onExceeded: \"warn\"` logs a single warning the first\n * time a cap is breached and lets the run continue. Useful for\n * measuring real-world traffic against a proposed cap before flipping\n * to `\"abort\"` in production.\n *\n * @example\n * const budgetMiddleware = budget({ maxTokens: 50_000 });\n *\n * const myAgent = agent({\n * model,\n * middleware: [budgetMiddleware],\n * });\n *\n * @example\n * // With USD cap and custom pricing\n * const guard = budget({\n * maxCostUSD: 0.5,\n * pricing: {\n * \"gpt-4o\": { inputPer1K: 0.005, outputPer1K: 0.015 },\n * },\n * });\n */\nexport function budget(options: BudgetOptions): AgentMiddleware {\n const name = options.name ?? \"budget\";\n const onExceeded = options.onExceeded ?? \"abort\";\n const hasTokenCap = typeof options.maxTokens === \"number\";\n const hasCostCap = typeof options.maxCostUSD === \"number\";\n\n return {\n name,\n execute: {\n before(context) {\n const counters = namespacedState<BudgetCounters>(context, name);\n counters.set({ tokens: 0, costUSD: 0, warned: false });\n },\n },\n trip: {\n after(context, response) {\n const counters = namespacedState<BudgetCounters>(context, name).get();\n\n if (!counters) {\n return;\n }\n\n counters.tokens += response.usage.total;\n\n if (hasCostCap && options.pricing) {\n const pricing = options.pricing[context.model.name];\n\n if (pricing) {\n const tripCost =\n (response.usage.input / 1000) * pricing.inputPer1K +\n (response.usage.output / 1000) * pricing.outputPer1K;\n counters.costUSD += tripCost;\n }\n }\n\n if (hasTokenCap && counters.tokens > options.maxTokens!) {\n if (onExceeded === \"abort\") {\n breach(options.maxTokens!, counters.tokens, \"tokens\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n\n if (hasCostCap && counters.costUSD > options.maxCostUSD!) {\n if (onExceeded === \"abort\") {\n breach(options.maxCostUSD!, counters.costUSD, \"usd\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n },\n },\n };\n}\n","import type {\n AgentMiddleware,\n MiddlewareTripContext,\n} from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { GuardrailViolationError } from \"../../errors\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Decision returned by a guardrail check function. `ok: true`\n * permits the call; `ok: false` rejects with a human-readable\n * `reason` surfaced on `GuardrailViolationError`.\n */\nexport type GuardrailCheckResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Synchronous or asynchronous check invoked against the outbound\n * prompt (`inputCheck`) or the inbound response (`outputCheck`).\n * Receives the raw text and the surrounding trip context so\n * consumers can classify, route to an external moderation API, or\n * branch on tripIndex / messages history.\n */\nexport type GuardrailCheck = (\n text: string,\n context: MiddlewareTripContext,\n) => GuardrailCheckResult | Promise<GuardrailCheckResult>;\n\n/**\n * Configuration for `guardrail()`. At least one of `inputCheck` or\n * `outputCheck` must be supplied — a guardrail with no checks is a\n * no-op.\n */\nexport type GuardrailOptions = {\n /**\n * Run against the outbound prompt just before the model sees it.\n * Fires every trip with the concatenated last user-message text.\n * Rejection aborts the trip with a `GuardrailViolationError` whose\n * `phase === \"input\"`.\n */\n inputCheck?: GuardrailCheck;\n /**\n * Run against the model's response text after the trip completes.\n * Fires every trip with `response.content`. Rejection aborts with\n * a `GuardrailViolationError` whose `phase === \"output\"`.\n *\n * Output checks run BEFORE any tool dispatch — a rejected response\n * means the tool calls it requested are never invoked.\n */\n outputCheck?: GuardrailCheck;\n /**\n * Override the middleware name — surfaces on\n * `GuardrailViolationError.guardrail` so operators can tell two\n * guardrails apart in logs. Default `\"guardrail\"`.\n */\n name?: string;\n};\n\n/**\n * Pre/post content guardrail for an agent run.\n *\n * **Role.** Inspects outbound prompts and inbound responses against\n * caller-supplied policies, aborting the trip with a typed\n * `GuardrailViolationError` when either trips a check. Consumers\n * distinguish `\"input\"` vs `\"output\"` violations off `error.phase`\n * — the two failure modes have very different product responses\n * (block the user vs re-prompt the model).\n *\n * **Scope.** Per-trip. Fires on every round-trip the agent makes,\n * including repair attempts and tool-follow-up trips. Input checks\n * evaluate the last user-role message; output checks evaluate the\n * raw model response text before any tool call is dispatched.\n *\n * **Composition.** A single middleware instance can carry both\n * `inputCheck` and `outputCheck`, or two separate instances can be\n * registered (useful when input and output policies come from\n * different teams / services). Registration order determines which\n * guardrail's violation surfaces first — the short-circuit throws\n * from the innermost offending hook, and outer guardrails never run\n * after an abort.\n *\n * **Not a sanitizer.** The guardrail either passes a trip unchanged\n * or aborts it. Mutating the prompt / response in-place is out of\n * scope — use a bespoke middleware for content rewriting.\n *\n * @example\n * const policy = guardrail({\n * inputCheck: async (text) =>\n * text.includes(\"SSN\") ? { ok: false, reason: \"pii\" } : { ok: true },\n * outputCheck: async (text) =>\n * text.length > 10_000 ? { ok: false, reason: \"too-long\" } : { ok: true },\n * });\n *\n * const myAgent = agent({ model, middleware: [policy] });\n */\nexport function guardrail(options: GuardrailOptions): AgentMiddleware {\n const name = options.name ?? \"guardrail\";\n const { inputCheck, outputCheck } = options;\n\n return {\n name,\n trip: {\n async before(context) {\n if (!inputCheck) {\n return;\n }\n\n const prompt = extractUserText(context.messages);\n\n if (!prompt) {\n return;\n }\n\n const verdict = await inputCheck(prompt, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected input — ${verdict.reason}`,\n { phase: \"input\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n async after(context, response: ModelResponse) {\n if (!outputCheck) {\n return;\n }\n\n if (!response.content) {\n return;\n }\n\n const verdict = await outputCheck(response.content, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected output — ${verdict.reason}`,\n { phase: \"output\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n },\n };\n}\n","import type { CacheDriver } from \"@warlock.js/cache\";\n\n/**\n * Process-wide `@warlock.js/ai` configuration. **Intentionally tiny.**\n * Lives here only for genuinely cross-cutting defaults that would\n * otherwise force users to wire the same value into every consumer.\n *\n * **What lives here.** A field earns a slot only when it satisfies\n * all three:\n * 1. Multiple unrelated consumers need the same value.\n * 2. The value is infrastructure (drivers, clients, pools), not\n * behavior (kill-switches, mode flags).\n * 3. Per-call override doesn't make sense for the use case.\n *\n * **What does NOT live here.** Logger config (use\n * `@warlock.js/logger` directly). Per-primitive feature flags\n * (live on the relevant config type). Anything that's really one\n * consumer's concern (lives on that consumer).\n *\n * Phase 3.2 deliberately removed the previous `configureAI()` bag\n * because it was growing unbounded. Treat new fields here with the\n * same suspicion.\n */\nexport type AIConfig = {\n /**\n * Default store used by every consumer that supports persistence\n * but didn't supply its own `store` / `snapshotStore`. Most\n * realistic deployments back resume snapshots, semantic cache, and\n * future memory primitives with the same driver — declaring it\n * once here removes the repetition.\n *\n * Per-declaration overrides (`SupervisorConfig.snapshotStore`,\n * `semanticCache({ store })`) win when supplied. Set this once at\n * app boot, *after* you've constructed your driver.\n *\n * @example\n * import { cache } from \"@warlock.js/cache\";\n * import { ai } from \"@warlock.js/ai\";\n *\n * ai.config({\n * defaultStore: cache.driver(\"redis\", { client: redisClient }),\n * });\n */\n defaultStore?: CacheDriver<any, any>;\n};\n\nconst aiConfig: AIConfig = {};\n\n/**\n * Set or extend process-wide AI configuration. Merges over existing\n * values — fields not present in `partial` keep whatever was set\n * before (or stay unset). Call once at app boot, before constructing\n * any agent / supervisor / middleware that should pick up the\n * defaults.\n *\n * Returns the merged config so callers can verify what landed.\n *\n * @example\n * import { cache } from \"@warlock.js/cache\";\n * import { ai } from \"@warlock.js/ai\";\n *\n * ai.config({ defaultStore: cache.driver(\"redis\", { client }) });\n */\nexport function setAIConfig(partial: Partial<AIConfig>): AIConfig {\n Object.assign(aiConfig, partial);\n return { ...aiConfig };\n}\n\n/**\n * Read the current AI config snapshot. Returns a shallow copy so\n * callers can't accidentally mutate the source of truth. Used\n * internally by consumers to resolve their `defaultStore` fallback.\n */\nexport function getAIConfig(): AIConfig {\n return { ...aiConfig };\n}\n\n/**\n * Resolve the effective store for a consumer that didn't receive an\n * explicit one. Returns the global `defaultStore` if set, otherwise\n * `undefined`. Consumers decide whether `undefined` is fatal (semantic\n * cache: yes, throws) or a no-op (snapshot persistence: yes, just\n * skips).\n */\nexport function resolveDefaultStore(): CacheDriver<any, any> | undefined {\n return aiConfig.defaultStore;\n}\n","import type { CacheDriver } from \"@warlock.js/cache\";\nimport { resolveDefaultStore } from \"../../config\";\nimport type { Message } from \"../../contracts/conversation-message.type\";\nimport type { EmbedderContract } from \"../../contracts/embedder.contract\";\nimport type { AgentMiddleware } from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Configuration for `semanticCache()`.\n */\nexport type SemanticCacheOptions = {\n /** Embedder used to produce the query vector from the prompt text. */\n embedder: EmbedderContract;\n /**\n * Vector-capable cache driver from `@warlock.js/cache`. Production\n * deployments pick a driver with a real ANN index (`pg` with\n * pgvector, `redis` with RediSearch). Dev / test environments use\n * `new MemoryCacheDriver()` — zero config, correct, but O(N) per\n * query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * Falls back to `ai.config({ defaultStore })` when omitted. When\n * neither is set, the factory throws at construction time —\n * semantic cache cannot operate without a store.\n */\n store?: CacheDriver<any, any>;\n /**\n * Minimum cosine similarity for a vector hit. Between 0 and 1 —\n * 0.95 is a solid default for question-answering caches.\n */\n threshold: number;\n /**\n * Optional TTL in milliseconds. Entries whose `storedAt` is older\n * than this are treated as misses on read and overwritten on the\n * next write. Default: no expiry — entries live until the store\n * evicts them (per its own TTL/eviction policy).\n */\n ttlMs?: number;\n /**\n * Namespace prefix applied to every key the cache writes. Lets\n * multiple agents share one driver without collision. Default\n * `\"ai.cache\"`.\n */\n namespace?: string;\n /**\n * Middleware name — also the state-bag key prefix inside a single\n * execution. Default `\"semantic-cache\"`.\n */\n name?: string;\n};\n\ntype CachedEntry = {\n response: ModelResponse;\n storedAt: number;\n};\n\ntype PendingWrite = {\n promptKey: string;\n vector: number[];\n};\n\nconst DEFAULT_NAMESPACE = \"ai.cache\";\n\n/**\n * Build a stable fingerprint for a prompt covering the full message\n * list (system + history + user turn). Ensures two prompts sharing\n * the user text but differing in prior context do not collide on\n * the exact-match fast path.\n *\n * FNV-1a variant — cheap, collision-resistant enough for a cache,\n * dependency-free. NOT a cryptographic hash: collisions would\n * surface as wrong cache hits, not a security issue in the current\n * trust model.\n */\nfunction hashPrompt(messages: ReadonlyArray<Message>): string {\n const serialized = messages\n .map((message) => {\n const role = message.role;\n const content = Array.isArray(message.content)\n ? message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"|\")\n : message.content;\n\n return `${role}:${content}`;\n })\n .join(\"||\");\n\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < serialized.length; index++) {\n hash ^= serialized.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return (hash >>> 0).toString(16);\n}\n\nfunction isFresh(entry: CachedEntry, ttlMs: number | undefined): boolean {\n if (ttlMs === undefined) {\n return true;\n }\n\n return Date.now() - entry.storedAt <= ttlMs;\n}\n\n/**\n * Semantic-similarity response cache for an agent run.\n *\n * **Role.** Skips LLM round-trips when the current prompt is\n * semantically close to one the agent has already answered. For\n * FAQ / support-style traffic this often eliminates 60–80% of\n * model calls — the production win is massive for cost and\n * latency.\n *\n * **Delegation to `@warlock.js/cache`.** This middleware does NOT\n * implement similarity search itself. It delegates to the supplied\n * `CacheDriver`. Production deployments pick a driver with an ANN\n * index (`pg` + pgvector, `redis` + RediSearch). Dev / test\n * environments pass `new MemoryCacheDriver()` — zero config, correct,\n * but O(N) per query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * **Two-tier lookup.**\n * 1. *Exact-match key* — a cheap FNV hash over the entire message\n * list. `store.get(hash)` returns the entry without an embedding\n * round trip when the prompt hasn't changed at all.\n * 2. *Vector-match* — on exact-match miss, embed the prompt and\n * call `store.similar(vector, { topK: 1, threshold })`. The\n * driver uses its native similarity index; anything clearing\n * `threshold` is returned as a hit.\n *\n * **Write-on-miss.** When both tiers miss, `trip.before` stashes\n * the prompt hash + vector in `ctx.state`; `trip.after` reads back\n * the pending entry and calls\n * `store.set(hash, entry, { vector })`. If an outer middleware\n * (guardrail) throws in `trip.after` before the cache's `trip.after`\n * runs, the pending entry is never written — bad responses stay out\n * of the cache **as long as the canonical install order is followed**\n * (cache outermost).\n *\n * **Synthetic-response on hit.** Returns a `ModelResponse` with\n * `usage: { input: 0, output: 0, total: 0 }` so budget /\n * observability correctly exclude the saved trip.\n *\n * @example\n * import { semanticCache } from \"@warlock.js/ai\";\n * import { MemoryCacheDriver } from \"@warlock.js/cache\";\n *\n * const store = new MemoryCacheDriver();\n * store.setOptions({});\n *\n * const cache = semanticCache({\n * embedder: openai.embedder({ name: \"text-embedding-3-small\" }),\n * store,\n * threshold: 0.95,\n * ttlMs: 60 * 60 * 1000,\n * });\n *\n * const myAgent = agent({ model, middleware: [cache] });\n */\nexport function semanticCache(options: SemanticCacheOptions): AgentMiddleware {\n const name = options.name ?? \"semantic-cache\";\n const namespace = options.namespace ?? DEFAULT_NAMESPACE;\n const pendingKey = `${name}.pending`;\n\n // Resolve the effective store at factory time, not per-call. Every\n // subsequent hook closes over `store` so the resolution happens once.\n // Throws now (loud, at construction) instead of later during the\n // first trip (silent until the agent actually runs).\n const store = options.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `semanticCache: no store supplied — pass \\`store\\` in options or call \\`ai.config({ defaultStore })\\` at app boot before constructing the middleware`,\n );\n }\n\n // Cache's parseKey replaces \":\" with \".\" so the namespace boundary\n // matches what `similar()` actually returns in `hit.key`. Using a\n // dot here keeps prefix checks aligned with stored keys.\n const keyFor = (hash: string): string => `${namespace}.${hash}`;\n\n return {\n name,\n log: true,\n trip: {\n async before(context) {\n // Only cache the first trip's response. Subsequent trips\n // happen because the previous trip requested tool calls — the\n // message list now carries tool results the original prompt\n // never saw, so a semantic match on the unchanged user text\n // would serve back the prior `tool_calls` response and loop\n // the agent forever. The first turn is also the only one\n // where a \"same question → same final answer\" caching story\n // is sound.\n if (context.tripIndex !== 0) {\n return;\n }\n\n const promptText = extractUserText(context.messages);\n\n if (!promptText) {\n return;\n }\n\n const promptKey = hashPrompt(context.messages);\n const scopedKey = keyFor(promptKey);\n\n const exact = await store.get<CachedEntry>(scopedKey);\n\n if (exact && isFresh(exact, options.ttlMs)) {\n return toSyntheticResponse(exact.response);\n }\n\n const query = await options.embedder.embed(promptText);\n\n const [hit] = await store.similar<CachedEntry>(query.vector, {\n topK: 1,\n threshold: options.threshold,\n });\n\n if (hit && isFresh(hit.value, options.ttlMs)) {\n // Only return hits whose stored key is within this cache's\n // namespace. Drivers shared across namespaces would otherwise\n // leak foreign entries into queries.\n if (hit.key.startsWith(`${namespace}.`)) {\n return toSyntheticResponse(hit.value.response);\n }\n }\n\n const pending: PendingWrite = { promptKey, vector: query.vector };\n context.state.set(pendingKey, pending);\n\n return;\n },\n async after(context, response) {\n const pending = context.state.get(pendingKey) as PendingWrite | undefined;\n\n if (!pending) {\n return;\n }\n\n // Mid-stream tool-call responses must not be cached — the\n // useful answer comes from the trip *after* the tool returns.\n // Crucially, leave the pending entry in place so a later trip\n // (the one that actually finishes with `stop`) can read it\n // and write the final response under the *original* trip-0\n // prompt key. Deleting here would orphan the pending and the\n // post-tool answer would never make it into the store.\n if (response.finishReason === \"tool_calls\") {\n return;\n }\n\n context.state.delete(pendingKey);\n\n const entry: CachedEntry = { response, storedAt: Date.now() };\n\n await store.set(keyFor(pending.promptKey), entry, {\n vector: pending.vector,\n });\n\n return;\n },\n },\n };\n}\n\nfunction toSyntheticResponse(response: ModelResponse): ModelResponse {\n return {\n content: response.content,\n finishReason: response.finishReason,\n usage: { input: 0, output: 0, total: 0 },\n toolCalls: response.toolCalls,\n };\n}\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\n\n/**\n * Flatten one or more middleware sources into a single ordered\n * array suitable for `agent({ middleware: [...] })`.\n *\n * **Role.** As middleware catalogs grow, agent configs accumulate\n * long arrays that mix \"always-on\" stacks (cache + budget + guardrail)\n * with per-concern extras (per-tool rate-limits, audit hooks). A\n * single `compose` call lets callers keep those sources as named\n * variables and flatten at the registration site.\n *\n * **Semantics.** Registration order is preserved across sources —\n * `compose(a, b, c)` produces `[...a, ...b, ...c]`. Because the\n * pipeline's onion is strictly registration-ordered, the flattened\n * order is the execution order. No de-duplication, no sorting, no\n * priority logic — that would hide bugs, not fix them.\n *\n * **Accepts arrays OR individual middlewares.** Both forms are\n * common in callsite code; the helper flattens either.\n *\n * @example\n * const standardStack = [\n * ai.middleware.semanticCache({ ... }),\n * ai.middleware.budget({ maxTokens: 20_000 }),\n * ai.middleware.guardrail({ ... }),\n * ];\n *\n * const toolRateLimits = [\n * toolRateLimit({ tool: \"search_web\", maxCalls: 3 }),\n * toolRateLimit({ tool: \"expensive_api\", maxCalls: 1 }),\n * ];\n *\n * const myAgent = ai.agent({\n * model,\n * middleware: ai.middleware.compose(standardStack, toolRateLimits, auditMiddleware),\n * });\n */\nexport function composeMiddleware(\n ...sources: ReadonlyArray<AgentMiddleware | ReadonlyArray<AgentMiddleware>>\n): AgentMiddleware[] {\n const out: AgentMiddleware[] = [];\n\n for (const source of sources) {\n if (Array.isArray(source)) {\n out.push(...source);\n continue;\n }\n\n out.push(source as AgentMiddleware);\n }\n\n return out;\n}\n","import type { AgentMiddleware } from \"../../contracts/middleware\";\n\n/**\n * Scope a middleware's `tool`-level hooks to only fire for a\n * specific tool name (or a set of names). `execute` and `trip`\n * hooks pass through unchanged.\n *\n * **Role.** Tool-specific concerns — \"rate-limit `search_web`\",\n * \"cache results for `fetch_faq`\" — are common. Rather than adding\n * a `middleware` field to `ai.tool()` (see decisions §27), the\n * framework keeps one contract (`AgentMiddleware`) and offers this\n * helper for the locality problem. The middleware body stays agnostic\n * of the tool name; `forTool` handles the filtering.\n *\n * **What gets filtered.** Only `tool.before` / `tool.after` /\n * `tool.onError`. Each hook is wrapped so that `ctx.tool.name`\n * must be in the allowed set or the wrapped hook is a no-op.\n * `execute` and `trip` hooks are NOT touched — they run normally.\n *\n * **Why not filter execute/trip too?** Because a middleware that\n * reaches across levels (a tool-specific budget that initializes a\n * counter in `execute.before` and checks it in `tool.before`) still\n * needs `execute.before` to fire unconditionally. Scoping all hooks\n * would break cross-level middleware; scoping only `tool` hooks\n * matches the mental model of \"this middleware cares about these\n * tools.\"\n *\n * **Single-name vs multi-name.** A string matches one tool; a string\n * array matches any of the listed tools. No wildcards, no regex —\n * keep it boring.\n *\n * @example\n * // Single tool\n * const scoped = ai.middleware.forTool(\n * \"search_web\",\n * toolRateLimit({ maxCalls: 3 }),\n * );\n *\n * @example\n * // Multiple tools sharing a rule\n * const scoped = ai.middleware.forTool(\n * [\"paid_api\", \"expensive_db\"],\n * toolRateLimit({ maxCalls: 5 }),\n * );\n *\n * ai.agent({\n * model,\n * tools: [webTool, paidApiTool, expensiveDbTool],\n * middleware: [scoped],\n * });\n */\nexport function forTool(\n toolNames: string | ReadonlyArray<string>,\n middleware: AgentMiddleware,\n): AgentMiddleware {\n const allowed = new Set(\n typeof toolNames === \"string\" ? [toolNames] : toolNames,\n );\n const scope =\n allowed.size === 1 ? Array.from(allowed)[0] : Array.from(allowed).join(\"+\");\n\n if (!middleware.tool) {\n return middleware;\n }\n\n const innerBefore = middleware.tool.before;\n const innerAfter = middleware.tool.after;\n const innerOnError = middleware.tool.onError;\n\n return {\n ...middleware,\n name: `${middleware.name}[for:${scope}]`,\n tool: {\n before: innerBefore\n ? async ctx => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerBefore(ctx);\n }\n : undefined,\n after: innerAfter\n ? async (ctx, result) => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerAfter(ctx, result);\n }\n : undefined,\n onError: innerOnError\n ? async (ctx, error) => {\n if (!allowed.has(ctx.tool.name)) {\n return;\n }\n\n return innerOnError(ctx, error);\n }\n : undefined,\n },\n };\n}\n","import type { Logger } from \"@warlock.js/logger\";\nimport type {\n AgentMiddleware,\n MiddlewareExecuteContext,\n MiddlewareToolContext,\n MiddlewareTripContext,\n} from \"../contracts/middleware\";\n\nconst LOG_MODULE = \"ai.middleware\";\n\n/**\n * The three levels at which agent middleware can hook — mirrors\n * `AgentMiddleware`'s optional `execute` / `trip` / `tool` keys.\n * Kept as a single named union so callers can pass it around without\n * inline-duplicating the literals.\n */\nexport type MiddlewareLevel = \"execute\" | \"trip\" | \"tool\";\n\n/**\n * Shape of the context object for each level. The pipeline is\n * level-parameterized on the ctx type via this mapping so callers\n * get compile-time narrowing when they instantiate `runPipeline`.\n */\nexport type MiddlewareContextByLevel = {\n execute: MiddlewareExecuteContext;\n trip: MiddlewareTripContext;\n tool: MiddlewareToolContext;\n};\n\n/**\n * Run an inner async operation through a stack of agent middlewares\n * at a single level, applying the onion-model before/after/onError\n * semantics documented on `AgentMiddleware`.\n *\n * **Semantics.**\n * - `before` hooks run in registration order (top-down).\n * Returning a defined value from a `before` hook short-circuits the\n * pipeline with that value as the result, skipping `inner()` and\n * all deeper `before` / `after` hooks — but outer middleware\n * `after` hooks (registered earlier) still run on the synthetic\n * value.\n * - `after` hooks run in reverse registration order (bottom-up).\n * Returning a defined value replaces the result before it\n * propagates further out. Returning `void` / `undefined` keeps the\n * existing result.\n * - `onError` hooks also run in reverse (bottom-up) — any error\n * thrown by `inner()`, by a `before` hook, or by an `after` hook\n * unwinds through each frame's `onError` in turn. Returning a\n * defined value from `onError` recovers: the error is cleared and\n * the returned value becomes the new result (which then flows\n * through outer `after` hooks). Returning `void` propagates the\n * error to the next outer frame.\n *\n * **Implementation.** Built by folding the middleware array from the\n * end inward: each middleware produces a closure that wraps the\n * previous closure (the deeper pipeline). The outermost wrap is\n * middleware index 0 — so registration order matches onion order\n * without any reverse iteration at call time.\n *\n * **No magic.** The pipeline does not swallow, retry, or translate\n * errors. Hooks that throw propagate unchanged (subject to `onError`\n * recovery). Pipeline-level logging is debug-only and respects each\n * middleware's `log: false` kill-switch.\n *\n * @example\n * const response = await runPipeline(\n * middlewares,\n * \"trip\",\n * tripContext,\n * () => model.complete(messages, callOptions),\n * logger,\n * );\n */\nexport async function runPipeline<Level extends MiddlewareLevel, TResult>(\n middlewares: ReadonlyArray<AgentMiddleware>,\n level: Level,\n context: MiddlewareContextByLevel[Level],\n inner: () => Promise<TResult>,\n logger?: Logger,\n): Promise<TResult> {\n if (middlewares.length === 0) {\n return inner();\n }\n\n let next: () => Promise<TResult> = inner;\n\n for (let index = middlewares.length - 1; index >= 0; index--) {\n const middleware = middlewares[index];\n const hooks = middleware[level];\n\n if (!hooks) {\n continue;\n }\n\n const previous = next;\n\n next = async () => {\n const logEnabled = middleware.log !== false && logger !== undefined;\n\n if (hooks.before) {\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.before`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n\n const shortCircuit = await (\n hooks.before as (ctx: unknown) => Promise<unknown> | unknown\n )(context);\n\n if (shortCircuit !== undefined) {\n if (logEnabled) {\n logger!.debug(\n LOG_MODULE,\n `${level}.short-circuit`,\n middleware.name,\n {\n middleware: middleware.name,\n level,\n },\n );\n }\n\n return shortCircuit as TResult;\n }\n }\n\n let result: TResult;\n\n try {\n result = await previous();\n } catch (thrown) {\n if (!hooks.onError) {\n throw thrown;\n }\n\n const recovered = await (\n hooks.onError as (\n ctx: unknown,\n error: unknown,\n ) => Promise<unknown> | unknown\n )(context, thrown);\n\n if (recovered === undefined) {\n throw thrown;\n }\n\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.recovered`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n\n result = recovered as TResult;\n }\n\n if (hooks.after) {\n const replacement = await (\n hooks.after as (\n ctx: unknown,\n value: unknown,\n ) => Promise<unknown> | unknown\n )(context, result);\n\n if (replacement !== undefined) {\n result = replacement as TResult;\n }\n\n if (logEnabled) {\n logger!.debug(LOG_MODULE, `${level}.after`, middleware.name, {\n middleware: middleware.name,\n level,\n });\n }\n }\n\n return result;\n };\n }\n\n return next();\n}\n","import type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Compute a per-channel USD cost breakdown for a single `Usage` against\n * a model's pricing table. Returns `undefined` when no pricing is\n * configured — the framework treats unpriced runs as \"cost unknown,\"\n * not \"cost zero,\" so dashboards can distinguish free-tier from\n * un-instrumented.\n *\n * **Shape mirrors `ModelPricing`** — `input`, `output`, optional\n * `cachedInput` / `cachedOutput`. Consumers needing a scalar total\n * sum the populated fields. The breakdown is the value-add: it tells\n * downstream tooling HOW the total was reached (input-vs-output\n * share, cache savings) without re-deriving against pricing tables\n * that may have shifted since the report was written.\n *\n * **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`\n * served from the provider's prompt cache and bills at\n * `pricing.cachedInput` (falls back to full `pricing.input` when the\n * provider doesn't publish a cache rate). The remaining `input -\n * cachedTokens` bills at full rate and shows up in `cost.input`. The\n * `cachedOutput` channel is reserved for Anthropic-style cache writes;\n * until an adapter populates `usage.cacheWriteTokens`, the framework\n * leaves it undefined.\n *\n * Pricing values are USD-per-million-tokens. The function divides\n * once at the end to avoid floating-point accumulation error on\n * per-token math.\n *\n * @example\n * const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };\n * const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });\n * // cost = {\n * // input: (60_000 * 0.15) / 1e6 = 0.009,\n * // output: (30_000 * 0.6) / 1e6 = 0.018,\n * // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,\n * // }\n */\nexport function computeCost(usage: Usage, pricing: ModelPricing | undefined): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cachedInput = usage.cachedTokens ?? 0;\n const uncachedInput = Math.max(0, usage.input - cachedInput);\n\n const cost: ModelPricing = {\n input: (uncachedInput * pricing.input) / 1_000_000,\n output: (usage.output * pricing.output) / 1_000_000,\n };\n\n if (cachedInput > 0) {\n const cachedInputRate = pricing.cachedInput ?? pricing.input;\n cost.cachedInput = (cachedInput * cachedInputRate) / 1_000_000;\n }\n\n return cost;\n}\n\n/**\n * Merge a child's cost breakdown into a running parent total. Each\n * channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums\n * independently — an undefined channel on either side is treated as\n * zero contribution rather than dropping the other side's value. A\n * single unpriced child should never erase the cost of its priced\n * siblings.\n *\n * Returns the new parent breakdown, or `undefined` when neither parent\n * nor child carried any cost data (preserves the \"no priced\n * contributor has appeared yet\" signal that distinguishes \"missing\n * pricing\" from \"genuinely zero\").\n */\nexport function accumulateCost(\n parent: ModelPricing | undefined,\n child: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!child) {\n return parent;\n }\n\n if (!parent) {\n return { ...child };\n }\n\n const merged: ModelPricing = {\n input: parent.input + child.input,\n output: parent.output + child.output,\n };\n\n const cachedInput = sumOptional(parent.cachedInput, child.cachedInput);\n if (cachedInput !== undefined) {\n merged.cachedInput = cachedInput;\n }\n\n const cachedOutput = sumOptional(parent.cachedOutput, child.cachedOutput);\n if (cachedOutput !== undefined) {\n merged.cachedOutput = cachedOutput;\n }\n\n return merged;\n}\n\n/**\n * Add two optional numbers, treating either side's `undefined` as\n * zero — but return `undefined` when both are absent. Keeps \"this\n * channel was never reported anywhere\" distinguishable from \"this\n * channel was reported as 0.\"\n */\nfunction sumOptional(parent: number | undefined, child: number | undefined): number | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n return (parent ?? 0) + (child ?? 0);\n}\n","/**\n * Strip markdown code fences from an LLM response before JSON parsing.\n *\n * Models — especially Claude, smaller models, and local models — routinely\n * wrap JSON output in fenced code blocks (` ```json\\n{...}\\n``` `) even when\n * instructed otherwise. Sometimes they also precede the fence with prose\n * (\"Here you go:\\n```json\\n...\\n```\"). This helper finds the first fenced\n * block regardless of language tag and returns its trimmed contents.\n *\n * Returns the trimmed original text unchanged when no fence is present, so\n * clean JSON passes through as a no-op.\n *\n * Deliberately does NOT fall back to \"find first `{` and last `}` and slice\n * between them\" — that heuristic silently corrupts data when prose contains\n * stray braces. Failing loudly at `JSON.parse` is safer.\n *\n * @example\n * extractJsonPayload('```json\\n{\"a\":1}\\n```');\n * // => '{\"a\":1}'\n *\n * @example\n * extractJsonPayload('Here you go:\\n```\\n{\"a\":1}\\n```\\nHope this helps.');\n * // => '{\"a\":1}'\n *\n * @example\n * extractJsonPayload('{\"a\":1}');\n * // => '{\"a\":1}' (no fence → unchanged)\n */\nexport function extractJsonPayload(text: string): string {\n const trimmed = text.trim();\n\n const fenceMatch = trimmed.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n\n if (fenceMatch) {\n return fenceMatch[1].trim();\n }\n\n return trimmed;\n}\n","/**\n * Generates a stable, human-readable run id for any execution node\n * (tool invocation, agent run, workflow run, supervisor run). Format:\n * `${prefix}_${timestamp36}_${random36}` — compact, sortable by\n * prefix, collision-resistant within a run.\n *\n * Shared helper so every primitive emits the same id shape. The\n * prefix is conventionally the primitive kind (`\"tool\"`, `\"agent\"`,\n * `\"workflow\"`, `\"sup\"`) but callers can pass anything; the id is\n * purely for correlation, never parsed.\n *\n * @example\n * const runId = generateRunId(\"tool\");\n * // → \"tool_ld8x3m_7fq2j1kp\"\n */\nexport function generateRunId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${Math.random()\n .toString(36)\n .slice(2, 10)}`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Supported JSON Schema output targets per the Standard JSON Schema V1\n * spec. `openai-strict` is the richest for OpenAI structured outputs —\n * every property listed in `required`, optionals expressed as\n * `[\"T\", \"null\"]`, `additionalProperties: false` everywhere. Other\n * targets produce standards-compliant but looser output.\n */\nexport type JsonSchemaTarget = \"draft-2020-12\" | \"draft-07\" | \"openapi-3.0\" | \"openai-strict\";\n\n/**\n * Options for `extractJsonSchema`. `target` is forwarded to libraries that\n * implement the Standard JSON Schema V1 spec (Seal, and any future lib\n * that follows the spec). Libraries using their own top-level `.jsonSchema`\n * / `._jsonSchema` property ignore the target.\n */\nexport type ExtractJsonSchemaOptions = {\n target?: JsonSchemaTarget | (string & {});\n};\n\n/**\n * Best-effort JSON Schema extraction from a Standard Schema instance.\n *\n * Different libraries expose their JSON representation through different\n * paths:\n * - **Seal / Standard JSON Schema V1**: `[\"~standard\"].jsonSchema.input({ target })`\n * — nested under the spec object, takes a target switch. Default target\n * is `\"openai-strict\"` since the primary consumer is OpenAI's native\n * structured-output mechanism; pass `options.target` to override.\n * - **Zod / similar**: top-level `.jsonSchema` property. Zod v4 actually\n * ships `toJSONSchema` as a module function, not a method, so it does\n * NOT hit this probe — Zod users pass their converted schema via the\n * `AgentExecuteOptions.responseSchema` escape hatch.\n *\n * Deliberately does NOT probe `toJSON` — that's a generic JavaScript\n * serialization hook (Seal's schemas have one that dumps internal rule\n * state) and matching it would return garbage disguised as a JSON Schema.\n *\n * Returns `undefined` when no path matches. The caller then either skips\n * native structured-output wiring or falls back to a schema-less\n * instruction.\n *\n * Shared across every SDK adapter package (OpenAI, Anthropic, Bedrock…)\n * so each provider converts schemas identically.\n *\n * @example\n * const schema = extractJsonSchema(mySealSchema);\n * // { type: \"object\", properties: { ... }, required: [ ... ], additionalProperties: false }\n *\n * @example\n * // Ask for a different target explicitly\n * const draft = extractJsonSchema(mySealSchema, { target: \"draft-2020-12\" });\n */\nexport function extractJsonSchema(\n schema: StandardSchemaV1<unknown> | undefined,\n options: ExtractJsonSchemaOptions = {},\n): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n\n const target = options.target ?? \"openai-strict\";\n\n // 1. Seal / Standard JSON Schema V1 pattern: [\"~standard\"].jsonSchema.input({ target })\n const sealJsonSchema = extractFromSealPath(schema, target);\n\n if (sealJsonSchema) {\n return sealJsonSchema;\n }\n\n // 2. Top-level jsonSchema / _jsonSchema (Zod-like, property or method form)\n const topLevel = extractFromCandidateKeys(schema as unknown as Record<string, unknown>);\n\n if (topLevel) {\n return topLevel;\n }\n\n return undefined;\n}\n\n/**\n * Probe the Standard JSON Schema V1 extension path on `schema[\"~standard\"]`.\n * The spec defines `jsonSchema.input({ target, libraryOptions? })` as a\n * function returning a JSON Schema tailored to the requested target. We\n * pass the caller's target (default `\"openai-strict\"`) so the library\n * produces output ready for OpenAI's native structured-output mode\n * without additional post-processing.\n *\n * Calling `.input()` without a target would throw (or return garbage) per\n * the spec — a failure here returns `undefined` so the fallback probe\n * runs.\n */\nfunction extractFromSealPath(\n schema: StandardSchemaV1<unknown>,\n target: string,\n): Record<string, unknown> | undefined {\n const standardSlot = (schema as unknown as Record<string, unknown>)[\"~standard\"];\n\n if (!standardSlot || typeof standardSlot !== \"object\") {\n return undefined;\n }\n\n const jsonSchemaSlot = (standardSlot as Record<string, unknown>)[\"jsonSchema\"];\n\n if (!jsonSchemaSlot || typeof jsonSchemaSlot !== \"object\") {\n return undefined;\n }\n\n const inputFn = (jsonSchemaSlot as Record<string, unknown>)[\"input\"];\n\n if (typeof inputFn !== \"function\") {\n return undefined;\n }\n\n try {\n const result = (inputFn as (options: { target: string }) => unknown).call(jsonSchemaSlot, {\n target,\n });\n\n if (result && typeof result === \"object\") {\n return result as Record<string, unknown>;\n }\n } catch {\n // fall through — library didn't support the target or threw otherwise\n }\n\n return undefined;\n}\n\n/**\n * Probe well-known top-level keys libraries use to expose their JSON\n * Schema. Supports both method form (rare) and property form (common).\n * Deliberately narrow — `toJSON` is NOT probed here because it's a\n * generic serialization hook that returns library-internal state for\n * many validators (Seal included), not a JSON Schema.\n */\nfunction extractFromCandidateKeys(\n schemaRecord: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const candidateKeys = [\"jsonSchema\", \"_jsonSchema\"] as const;\n\n for (const key of candidateKeys) {\n const value = schemaRecord[key];\n\n if (typeof value === \"function\") {\n try {\n const result = (value as () => unknown).call(schemaRecord);\n\n if (result && typeof result === \"object\") {\n return result as Record<string, unknown>;\n }\n } catch {\n // try next candidate\n }\n\n continue;\n }\n\n if (value && typeof value === \"object\") {\n return value as Record<string, unknown>;\n }\n }\n\n return undefined;\n}\n","import type {\n Attachment,\n AttachmentSource,\n ResolvedAttachment,\n} from \"../contracts/attachment.type\";\nimport { InvalidRequestError } from \"../errors\";\n\nconst REMOTE_URL_PATTERN = /^https?:\\/\\//i;\n\n/**\n * Normalize a user-supplied `Attachment` (or bare `AttachmentSource`)\n * into a `ResolvedAttachment` the agent can hand to file-reading code\n * without re-discriminating the input variant.\n *\n * Resolution rules:\n * - `{ base64, mediaType }` → `{ type: \"base64\", value, mediaType }`.\n * - `StorageFileShape` (`{ url?, absolutePath? }`) → URL wins over\n * absolute path. URL becomes `{ type: \"url\" }`; absolute path\n * becomes `{ type: \"path\" }`.\n * - String starting with `http://` / `https://` → `{ type: \"url\" }`.\n * - Any other string → `{ type: \"path\" }`.\n * - Tagged `{ type: \"image\" | \"text\", source }` → recurses into `source`.\n *\n * Throws `InvalidRequestError` on obviously invalid input (empty\n * string, storage object with neither url nor absolutePath, missing\n * source field).\n *\n * @example\n * resolveAttachment(\"https://cdn.example.com/doc.pdf\");\n * // → { type: \"url\", value: \"https://cdn.example.com/doc.pdf\" }\n *\n * @example\n * resolveAttachment({ type: \"image\", source: \"/tmp/x.png\" });\n * // → { type: \"path\", value: \"/tmp/x.png\" }\n */\nexport function resolveAttachment(attachment: Attachment): ResolvedAttachment {\n if (\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"type\" in attachment\n ) {\n return resolveSource(attachment.source);\n }\n\n return resolveSource(attachment);\n}\n\nfunction resolveSource(source: AttachmentSource): ResolvedAttachment {\n if (typeof source === \"string\") {\n if (!source) {\n throw new InvalidRequestError(\"Cannot resolve empty attachment string\");\n }\n\n if (REMOTE_URL_PATTERN.test(source)) {\n return { type: \"url\", value: source };\n }\n\n return { type: \"path\", value: source };\n }\n\n // StorageFile objects (from @warlock.js/core) can expose a `base64`\n // property alongside `url` / `absolutePath`. Check storage shape\n // first so we don't treat a StorageFile as an inline-bytes payload.\n if (\"url\" in source || \"absolutePath\" in source) {\n const storage = source as { url?: string; absolutePath?: string };\n\n if (storage.absolutePath) {\n return { type: \"path\", value: storage.absolutePath };\n }\n\n if (storage.url) {\n return { type: \"url\", value: storage.url };\n }\n\n throw new InvalidRequestError(\n \"Storage attachment has neither url nor absolutePath\",\n );\n }\n\n if (\"base64\" in source) {\n if (!source.base64 || !source.mediaType) {\n throw new InvalidRequestError(\n \"Inline attachment requires both `base64` and `mediaType`\",\n );\n }\n\n return {\n type: \"base64\",\n value: source.base64,\n mediaType: source.mediaType,\n };\n }\n\n throw new InvalidRequestError(\n \"Unrecognized attachment source — expected a string path/URL, a StorageFile, or `{ base64, mediaType }`\",\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { resolveAttachment } from \"./resolve-attachment\";\n\nconst IMAGE_EXTENSIONS_TO_MEDIA_TYPE: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n};\n\nconst TEXT_EXTENSIONS = new Set([\".txt\"]);\n\ntype AttachmentKind = \"image\" | \"text\";\n\n/**\n * Convert a user-supplied `Attachment` into a provider-ready\n * `ContentPart` the model adapter can consume without doing any I/O of\n * its own.\n *\n * Kind resolution:\n * - Tagged `{ type: \"image\", source }` / `{ type: \"text\", source }`\n * trusts the caller's intent.\n * - Shorthand (raw string / `StorageFileShape`) infers from the file\n * extension. Image extensions (`.png`/`.jpg`/`.jpeg`/`.webp`/`.gif`)\n * map to `\"image\"`. `.txt` maps to `\"text\"`. Anything else throws\n * `InvalidRequestError` — silent inference on ambiguous inputs\n * causes silent bugs.\n *\n * Local paths are read from disk; images are base64-encoded inline,\n * text files are read as UTF-8 strings and returned as a `text`\n * `ContentPart`. Remote URLs for image attachments are passed through\n * unchanged; remote URLs for text attachments are fetched so the\n * adapter never needs network access.\n *\n * @example\n * await prepareAttachmentPart(\"./photo.png\");\n * // → { type: \"image\", source: { base64: \"...\", mediaType: \"image/png\" } }\n *\n * @example\n * await prepareAttachmentPart({ type: \"text\", source: \"./notes.txt\" });\n * // → { type: \"text\", text: \"<file contents>\" }\n */\nexport async function prepareAttachmentPart(\n attachment: Attachment,\n): Promise<ContentPart> {\n const kind = resolveKind(attachment);\n\n if (kind === \"text\") {\n return prepareTextPart(attachment);\n }\n\n return prepareImagePart(attachment);\n}\n\n/**\n * Decide whether the attachment is text or image. Tagged forms win\n * immediately; for shorthand we inspect the extension. Throws if the\n * shorthand doesn't look like anything we recognize.\n */\nfunction resolveKind(attachment: Attachment): AttachmentKind {\n if (isTaggedAttachment(attachment)) {\n return attachment.type;\n }\n\n const path = extractPath(attachment);\n const extension = path ? extname(stripQuery(path)).toLowerCase() : \"\";\n\n if (IMAGE_EXTENSIONS_TO_MEDIA_TYPE[extension]) {\n return \"image\";\n }\n\n if (TEXT_EXTENSIONS.has(extension)) {\n return \"text\";\n }\n\n throw new InvalidRequestError(\n \"Cannot infer attachment type from input — pass an explicit `{ type: 'image' | 'text', source: ... }` or use a recognized extension (.png, .jpg, .jpeg, .webp, .gif, .txt)\",\n );\n}\n\n/**\n * Produce an `image` ContentPart. URLs pass through; paths are\n * read from disk and base64-encoded with an inferred media type.\n * Inline base64 attachments pass through unchanged.\n */\nasync function prepareImagePart(attachment: Attachment): Promise<ContentPart> {\n const inferredMediaType = isTaggedAttachment(attachment)\n ? undefined\n : inferImageMediaType(attachment);\n\n const resolved = resolveAttachment(attachment);\n\n if (resolved.type === \"url\") {\n return { type: \"image\", source: { url: resolved.value } };\n }\n\n if (resolved.type === \"base64\") {\n return {\n type: \"image\",\n source: { base64: resolved.value, mediaType: resolved.mediaType },\n };\n }\n\n const mediaType = inferredMediaType ?? inferImageMediaType(resolved.value);\n\n if (!mediaType) {\n throw new InvalidRequestError(\n `Cannot infer media type for path \"${resolved.value}\" — use a recognized image extension or pass ` +\n \"`{ type: 'image', source: { base64, mediaType } }`\",\n { context: { path: resolved.value } },\n );\n }\n\n const bytes = await readFile(resolved.value);\n\n return {\n type: \"image\",\n source: { base64: bytes.toString(\"base64\"), mediaType },\n };\n}\n\n/**\n * Produce a `text` ContentPart. URLs are fetched as UTF-8, paths are\n * read from disk as UTF-8, inline base64 is decoded to UTF-8. The\n * result joins the conversation as an additional text part the model\n * sees before responding.\n */\nasync function prepareTextPart(attachment: Attachment): Promise<ContentPart> {\n const resolved = resolveAttachment(attachment);\n\n if (resolved.type === \"url\") {\n const response = await fetch(resolved.value);\n\n if (!response.ok) {\n throw new InvalidRequestError(\n `Failed to fetch text attachment \"${resolved.value}\" — status ${response.status}`,\n { context: { url: resolved.value, status: response.status } },\n );\n }\n\n return { type: \"text\", text: await response.text() };\n }\n\n if (resolved.type === \"base64\") {\n const decoded = Buffer.from(resolved.value, \"base64\").toString(\"utf8\");\n\n return { type: \"text\", text: decoded };\n }\n\n const bytes = await readFile(resolved.value, \"utf8\");\n\n return { type: \"text\", text: bytes };\n}\n\nfunction isTaggedAttachment(\n attachment: Attachment,\n): attachment is Extract<Attachment, { type: string }> {\n return (\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"type\" in attachment\n );\n}\n\nfunction inferImageMediaType(input: unknown): string | undefined {\n const path = extractPath(input);\n\n if (!path) {\n return undefined;\n }\n\n const extension = extname(stripQuery(path)).toLowerCase();\n\n return IMAGE_EXTENSIONS_TO_MEDIA_TYPE[extension];\n}\n\nfunction extractPath(input: unknown): string | undefined {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const storage = input as { url?: string; absolutePath?: string };\n return storage.url ?? storage.absolutePath;\n }\n\n return undefined;\n}\n\nfunction stripQuery(path: string): string {\n const queryIndex = path.indexOf(\"?\");\n\n return queryIndex === -1 ? path : path.slice(0, queryIndex);\n}\n","/**\n * Parse a JSON string, returning a caller-supplied fallback when the input\n * is empty or malformed instead of throwing. Useful at provider boundaries\n * where tool-call arguments may arrive as `null`, `\"\"`, or partial JSON\n * during streaming — callers want a safe default, not an exception.\n *\n * @example\n * const args = safeJsonParse<Record<string, unknown>>(toolCall.function.arguments, {});\n */\nexport function safeJsonParse<TValue>(\n data: string | null | undefined,\n defaultValue: TValue,\n): TValue {\n if (!data) {\n return defaultValue;\n }\n\n try {\n return JSON.parse(data) as TValue;\n } catch {\n return defaultValue;\n }\n}\n","import type { AttemptEntry } from \"./attempt-entry.type\";\nimport type { Usage } from \"./usage.type\";\n\n/**\n * Wire-format version stamped on every root `BaseReport`. Bumped only\n * when we make a BREAKING change to the report shape (field removed,\n * required-ness flipped, semantics changed). Additive changes (new\n * optional fields) do not bump.\n *\n * Panoptic and other downstream consumers branch on this to parse\n * old stored reports with their original-shape rules.\n *\n * Current: **1** — initial Panoptic-readiness shape.\n */\nexport const REPORT_SCHEMA_VERSION = 1;\n\n/**\n * Discriminator for the kind of executable that produced a given\n * {@link BaseReport}. Forms a closed union so consumers can narrow on\n * the tree without string-matching on `name`.\n */\nexport type ReportType =\n | \"tool\"\n | \"callback\"\n | \"agent\"\n | \"workflow\"\n | \"supervisor\";\n\n/**\n * Terminal status every executable primitive reports. Unified across\n * tools, agents, workflows, and supervisors so dashboards and\n * generic traversal helpers don't special-case per primitive.\n *\n * - `\"completed\"` — ran to natural end with a usable result.\n * - `\"failed\"` — aborted mid-run or finished without a usable result\n * (crash, schema failure, max-trips, etc.). The\n * accompanying `error` on the envelope carries the typed cause.\n * - `\"cancelled\"` — caller aborted before completion via `AbortSignal`.\n * - `\"max-iterations\"` — supervisor-specific termination when the\n * iteration cap was hit without an explicit `END` / `satisfied`.\n * Harmless on non-supervisor reports; keeping it on the shared\n * union lets consumers write one `switch` for every status.\n */\nexport type ReportStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"max-iterations\";\n\n/**\n * Universal execution report shared by every primitive. Per-primitive\n * report types extend this with their own domain-specific fields\n * (agent trips, workflow steps, supervisor iteration snapshots) while\n * keeping the root fields identical. Recursion happens through\n * {@link BaseReport.children} — any executable this node invoked\n * contributes its own full report here, producing a walkable tree of\n * the entire run.\n *\n * **Usage rollup.** `usage` at every node equals this node's own cost\n * plus the sum of each child's `usage`. Leaves (tools) contribute\n * zero own-cost; composites contribute their direct LLM spend only,\n * with children covering everything delegated.\n *\n * @example\n * function totalCost(report: BaseReport): number {\n * return report.usage.total;\n * }\n *\n * function walk(report: BaseReport, depth = 0): void {\n * console.log(`${\" \".repeat(depth)}${report.type} \"${report.name}\" — ${report.status}`);\n * for (const child of report.children) walk(child, depth + 1);\n * }\n */\nexport type BaseReport = {\n /** Stable id for this execution node. Generated per `execute()`/`invoke()` call. */\n runId: string;\n /**\n * Run-id of the immediate parent execution node, when this node was\n * invoked as part of a larger run (e.g. a tool dispatched by an\n * agent; an agent dispatched by a supervisor; an inner primitive\n * wrapped via `asTool()`). Absent on root nodes.\n *\n * Lets Panoptic and other flat-row consumers reconstruct the tree\n * without traversing `children[]` in memory.\n */\n parentRunId?: string;\n /**\n * Run-id of the top-level execution this node belongs to. Equals\n * `runId` on the root node, and is propagated downward to every\n * descendant. Used to slice flat report tables back into per-run\n * groupings.\n */\n rootRunId: string;\n /** Executable identity — the tool/agent/workflow/supervisor name. */\n name: string;\n /**\n * Dev-curated version string mirrored from the primitive's config\n * (`AgentConfig.version`, `ToolConfig.version`, etc.). Free-form —\n * the framework neither parses nor compares it. Stored verbatim on\n * every report so trip-archive queries can distinguish runs of\n * \"agent X v2.1\" from \"agent X v2.2\" even when name + signature\n * are identical.\n *\n * Stays `undefined` when the dev didn't declare one — never\n * auto-defaulted.\n */\n version?: string;\n /**\n * Caller-supplied identifier that groups multiple `.execute()` calls\n * into one conceptual user session / request. Propagated to every\n * descendant report node so flat queries (\"total spend for session\n * X today\") work without joining the tree.\n *\n * Threaded from `execute()` options on every primitive. Optional —\n * absent when the caller didn't supply one.\n */\n sessionId?: string;\n /** Discriminator for the kind of executable that produced this report. */\n type: ReportType;\n /** Terminal status of this execution. */\n status: ReportStatus;\n /** ISO-8601 wall-clock timestamp when execution began. */\n startedAt: string;\n /** ISO-8601 wall-clock timestamp when execution finished. */\n endedAt: string;\n /** Monotonic duration in milliseconds — `performance.now()` delta. */\n duration: number;\n /** Rolled-up usage: own cost + sum of `children[].usage`. */\n usage: Usage;\n /**\n * Reports of every executable invoked by this node, in invocation\n * order. Empty for leaves (pure tools) and for executables that\n * didn't delegate work.\n */\n children: BaseReport[];\n /**\n * Retry history when middleware (or, for workflow steps, the engine\n * itself) retried this node before it either succeeded or gave up.\n * Absent when zero retries happened — keeps the common-case payload\n * lean. The surviving (final) attempt is NOT duplicated here; its\n * outcome is the report's own `status` / timing.\n */\n attempts?: AttemptEntry[];\n /**\n * Wire-format version of this report shape. Only present on root\n * report nodes — implies the same version for the whole tree.\n * Panoptic / archive consumers branch on this to parse old reports\n * with their original-shape rules.\n *\n * Always equals {@link REPORT_SCHEMA_VERSION} at write time.\n */\n reportSchemaVersion?: number;\n};\n","import type { BaseReport } from \"../contracts/result/base-report.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\n\n/**\n * Options for {@link stampReportLineage}. Every field is optional —\n * the caller supplies whichever pieces it knows. Missing pieces are\n * left untouched (existing values on the report survive).\n */\nexport type LineageStamp = {\n /**\n * The outermost run-id this subtree belongs to. When set, EVERY\n * node in the subtree gets its `rootRunId` rewritten to this\n * value — overrides any inner self-roots produced by nested\n * `buildResult` calls.\n */\n rootRunId: string;\n /**\n * Run-id of the immediate parent of THIS subtree's top node. Each\n * descendant's `parentRunId` is then derived from its own walk\n * position (its parent's `runId`).\n */\n parentRunId?: string;\n /**\n * Caller-supplied session identifier — propagates to every node in\n * the subtree. Skipped when undefined.\n */\n sessionId?: string;\n};\n\n/**\n * Walk a freshly-built report tree and stamp lineage fields onto\n * every node:\n *\n * - `rootRunId` — rewritten to `stamp.rootRunId` everywhere. Composite\n * children built by inner primitives carry their own self-root; this\n * walk overrides it so the outer root wins (single coherent run id\n * across the whole tree).\n * - `parentRunId` — root node gets `stamp.parentRunId`; descendants\n * derive theirs from each parent's own `runId`.\n * - `sessionId` — propagated when provided.\n * - `reportSchemaVersion` — stamped only on the root (the value is the\n * same for the whole tree; storing it on every node would waste\n * space).\n *\n * Designed to run ONCE per top-level `buildResult` call. Each\n * primitive's executor invokes this on the assembled root report just\n * before returning; nested primitives produced their own subtree with\n * a self-root, and this pass relinks everything to the outer caller's\n * lineage.\n *\n * Mutates the report in place — internal use only, before the report\n * is exposed via `result.report`.\n *\n * @example\n * const root = this.buildBareReport();\n * stampReportLineage(root, { rootRunId: this.runId, sessionId: this.options?.sessionId });\n * return { ..., report: root };\n */\nexport function stampReportLineage(root: BaseReport, stamp: LineageStamp): void {\n root.reportSchemaVersion = REPORT_SCHEMA_VERSION;\n\n walk(root, stamp.rootRunId, stamp.parentRunId, stamp.sessionId);\n}\n\nfunction walk(node: BaseReport, rootRunId: string, parentRunId?: string, sessionId?: string): void {\n node.rootRunId = rootRunId;\n\n if (parentRunId !== undefined) {\n node.parentRunId = parentRunId;\n } else {\n delete node.parentRunId;\n }\n\n if (sessionId !== undefined) {\n node.sessionId = sessionId;\n }\n\n for (const child of node.children) {\n walk(child, rootRunId, node.runId, sessionId);\n }\n}\n","/**\n * Approximate the number of tokens in a string.\n *\n * Uses the ~4-characters-per-token heuristic, which is accurate enough for\n * GPT-4 family models and most English text. Use this when a real tokenizer\n * (tiktoken, etc.) isn't available or would add native dependencies.\n *\n * @example\n * const tokens = approximateTokenCount(\"Hello, world!\"); // 4\n */\nexport function approximateTokenCount(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { Placeholders } from \"../contracts/placeholders.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { extractJsonSchema, prepareAttachmentPart } from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\n\n/**\n * Outcome of `buildAgentInputMessages` — the seeded message list and\n * the JSON Schema cached for every trip's\n * `ModelCallOptions.responseSchema`. `responseSchema` is `undefined`\n * when the caller didn't ask for structured output.\n */\nexport type AgentInputBuildResult = {\n messages: Message[];\n responseSchema?: Record<string, unknown>;\n};\n\n/**\n * Assemble the seed conversation for an agent execution. Runs exactly\n * once per run — subsequent trips append to the same message list.\n *\n * Responsibilities (previously three methods on `Execution`):\n * 1. Merge factory + per-call placeholders.\n * 2. Resolve the system prompt (string, contract, or absent).\n * 3. When an output schema is supplied:\n * - cache its JSON Schema form for `ModelCallOptions.responseSchema`\n * so native-structured-output providers enforce it at the token\n * level;\n * - fall back to a soft system-prompt instruction for providers\n * that don't advertise `structuredOutput` capability.\n * 4. Append caller-supplied `history` (e.g. session-level prior turns).\n * 5. Shape the user message — plain string in the common case,\n * multipart `ContentPart[]` when `attachments` are present. Image\n * attachments require model vision capability; mismatch throws\n * `InvalidRequestError` here rather than failing opaquely at the\n * provider.\n *\n * Extracted from the `Execution` class to isolate the declarative\n * input-shaping phase from the stateful trip loop.\n */\nexport async function buildAgentInputMessages<TOutput>(params: {\n config: AgentConfig<TOutput>;\n input: string;\n options?: AgentExecuteOptions<TOutput>;\n}): Promise<AgentInputBuildResult> {\n const { config, input, options } = params;\n\n const placeholders: Placeholders = {\n ...config.placeholders,\n ...options?.placeholders,\n };\n\n const systemPrompt = options?.systemPrompt ?? config.systemPrompt;\n let systemContent = \"\";\n\n if (typeof systemPrompt === \"string\") {\n systemContent = systemPrompt;\n } else if (systemPrompt) {\n systemContent = systemPrompt.resolve(placeholders);\n }\n\n const { responseSchema, instruction } = resolveStructuredOutput({\n outputSchema: options?.output ?? config.output,\n overrideResponseSchema: options?.responseSchema,\n modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput),\n });\n\n if (instruction) {\n systemContent = systemContent ? `${systemContent}\\n\\n${instruction}` : instruction;\n }\n\n const messages: Message[] = [];\n\n if (systemContent) {\n messages.push({ role: \"system\", content: systemContent });\n }\n\n if (options?.history) {\n messages.push(...options.history);\n }\n\n const userContent = await buildUserMessageContent({\n input,\n attachments: options?.attachments,\n modelName: config.model.name,\n modelSupportsVision: Boolean(config.model.capabilities?.vision),\n });\n\n messages.push({ role: \"user\", content: userContent });\n\n return { messages, responseSchema };\n}\n\n/**\n * Build the user message `content` field. Plain string when no\n * attachments (the hot path) — keeps wire payloads small. Multipart\n * `ContentPart[]` when attachments exist: input text first, resolved\n * parts in declaration order.\n */\nasync function buildUserMessageContent(params: {\n input: string;\n attachments?: Attachment[];\n modelName: string;\n modelSupportsVision: boolean;\n}): Promise<string | ContentPart[]> {\n const { input, attachments, modelName, modelSupportsVision } = params;\n\n if (!attachments || attachments.length === 0) {\n return input;\n }\n\n const parts: ContentPart[] = await Promise.all(\n attachments.map((attachment) => prepareAttachmentPart(attachment)),\n );\n\n const hasImage = parts.some((part) => part.type === \"image\");\n\n if (hasImage && !modelSupportsVision) {\n throw new InvalidRequestError(\n `Model \"${modelName}\" does not declare vision capability — image attachments are not supported`,\n { context: { modelName } },\n );\n }\n\n return [{ type: \"text\", text: input }, ...parts];\n}\n\n/**\n * When the caller supplied an `output` schema, resolve two artifacts:\n *\n * - `responseSchema` — extracted JSON Schema to attach on every trip.\n * Adapters that natively support structured output (OpenAI's\n * `response_format: json_schema`) consume it; others ignore it.\n * - `instruction` — a soft fallback appended to the system prompt\n * **only** for models without native structured-output capability.\n * Capable adapters skip it to save tokens and avoid redundancy.\n */\nfunction resolveStructuredOutput(params: {\n outputSchema?: StandardSchemaV1<unknown>;\n overrideResponseSchema?: Record<string, unknown>;\n modelSupportsStructuredOutput: boolean;\n}): {\n responseSchema?: Record<string, unknown>;\n instruction?: string;\n} {\n const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;\n\n if (!outputSchema) {\n return {};\n }\n\n const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);\n\n if (modelSupportsStructuredOutput) {\n return { responseSchema };\n }\n\n const schemaHint = responseSchema\n ? `\\n\\nThe response MUST match this JSON Schema:\\n${JSON.stringify(responseSchema, null, 2)}`\n : \"\";\n\n const instruction = [\n \"You MUST respond with a single valid JSON value only.\",\n \"Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.\",\n schemaHint,\n ]\n .join(\"\")\n .trim();\n\n return { responseSchema, instruction };\n}\n","import type { Logger } from \"@warlock.js/logger\";\nimport type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { LLMTrip } from \"../contracts/result/llm-trip.type\";\nimport type { ToolCall } from \"../contracts/result/tool-call.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Aggregate snapshot the agent-level log entries need at emission time\n * (agent completion + model name + running totals). Passed instead of\n * storing a back-reference to the Execution class — keeps this helper\n * a pure function.\n */\nexport type AgentLogContext = {\n /** Dotted logger module, e.g. `\"ai.agent.my-writer\"`. */\n module: string;\n /** Maximum trips configured for this run — logged once on `agent.starting`. */\n maxTrips: number;\n /** Model identifier — logged once on `agent.starting`. */\n modelName: string;\n /** Final running usage totals at the moment `agent.completed` fires. */\n totalUsage: Usage;\n /** Monotonic duration (ms) since start at the moment `agent.completed` fires. */\n totalDurationMs: number;\n /** All trips recorded so far — logged count on `agent.completed`. */\n trips: LLMTrip[];\n /** All tool calls recorded so far — logged count on `agent.completed`. */\n toolCalls: ToolCall[];\n};\n\n/**\n * Structured logging for agent lifecycle events. Mirrors\n * `Execution.emit`'s call sites without touching class state — the\n * caller passes the ambient snapshot in `ctx`, we route each event to\n * the right logger level and enrich with the per-event forensic\n * detail.\n *\n * Log-level convention:\n * - `info` — lifecycle boundaries (agent starting / completed) users\n * want to see at default verbosity\n * - `debug` — per-trip + per-tool progress (hot-path, opt-in)\n * - `success` — trip completion + tool success (terminal per-step state)\n * - `warn` — tool failures (recoverable, agent loop continues)\n * - `error` — agent-level terminal errors\n *\n * Streaming deltas (`agent.trip.streaming`) are intentionally skipped\n * to avoid token-granularity log spam.\n */\nexport function logAgentEvent<K extends keyof AgentEventMap>(\n logger: Logger,\n ctx: AgentLogContext,\n event: K,\n payload: AgentEventMap[K],\n): void {\n const action = event.replace(/^agent\\./, \"\");\n\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n logger.info(ctx.module, action, \"agent starting\", {\n maxTrips: ctx.maxTrips,\n model: ctx.modelName,\n inputLength: input.length,\n });\n return;\n }\n\n case \"agent.trip.started\": {\n const { tripIndex } = payload as AgentEventMap[\"agent.trip.started\"];\n logger.debug(ctx.module, action, \"trip started\", { tripIndex });\n return;\n }\n\n case \"agent.trip.streaming\": {\n // Deltas are too high-volume to log at token granularity.\n // Skipped on purpose; debug level still fires on trip boundaries.\n return;\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n logger.success(ctx.module, action, \"trip completed\", {\n tripIndex: trip.index,\n duration: trip.duration,\n usage: trip.usage,\n finishReason: trip.finishReason,\n });\n return;\n }\n\n case \"agent.tool.calling\": {\n const { tool, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n logger.debug(ctx.module, action, `calling tool \"${tool.name}\"`, {\n tool: tool.name,\n action: tool.action,\n tripIndex,\n });\n return;\n }\n\n case \"agent.tool.called\": {\n const toolCall = payload as AgentEventMap[\"agent.tool.called\"];\n logger.success(ctx.module, action, `tool \"${toolCall.name}\" finished`, {\n tool: toolCall.name,\n duration: toolCall.duration,\n tripIndex: toolCall.tripIndex,\n });\n return;\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n\n logger.warn(ctx.module, action, `tool \"${tool.name}\" failed`, {\n tool: tool.name,\n tripIndex,\n error: {\n code: error.code,\n message: error.message,\n name: error.name,\n stack: error.stack,\n },\n });\n return;\n }\n\n case \"agent.completed\": {\n logger.info(ctx.module, action, \"agent completed\", {\n duration: ctx.totalDurationMs,\n usage: ctx.totalUsage,\n trips: ctx.trips.length,\n tools: ctx.toolCalls.length,\n });\n return;\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n logger.error(ctx.module, action, error.message, {\n code: error.code,\n context: error.context,\n });\n return;\n }\n }\n}\n","import type { StreamContract, StreamEvent } from \"../contracts\";\n\n/**\n * Internal async-queue `StreamContract` used by `agent().stream()`.\n *\n * **Role.** The bridge between a streaming `Execution` (which runs in the\n * background, pushing events as they happen) and a consumer that reads\n * those events with `for await` or an `on(...)` handler map.\n *\n * **Responsibility.**\n * - Owns: the event queue, the pending-read promise chain, the terminal\n * `result` promise, and any user-registered event handlers.\n * - Does NOT own: any knowledge of agents, models, or tool calls — it is a\n * generic producer/consumer pipe parameterized by `TResult`. The streaming\n * execution writes via `push()` / `end()` / `fail()`; the consumer reads\n * via the AsyncIterable surface.\n *\n * Events are coalesced into a queue so that a consumer that starts\n * iterating late still sees every event in order — nothing is dropped. The\n * `on()` handlers fire the moment an event is pushed, independent of\n * whether anyone is iterating.\n *\n * @example\n * // Inside agent.stream():\n * const { controller, stream } = createAgentStream<AgentResult<TOutput>>();\n * new Execution(config, input, options, controller).run();\n * return stream;\n *\n * // Consumer:\n * for await (const event of stream) {\n * if (event.type === \"streaming\") process.stdout.write(event.delta);\n * }\n * const result = await stream.result;\n */\nexport type StreamController<TResult> = {\n push(event: StreamEvent): void;\n end(result: TResult): void;\n fail(error: Error): void;\n};\n\ntype PendingRead = {\n resolve(value: IteratorResult<StreamEvent>): void;\n reject(error: Error): void;\n};\n\nexport function createAgentStream<TResult>(): {\n controller: StreamController<TResult>;\n stream: StreamContract<TResult>;\n} {\n const queue: StreamEvent[] = [];\n const pending: PendingRead[] = [];\n const handlers = new Map<StreamEvent[\"type\"], (event: StreamEvent) => void>();\n\n let closed = false;\n let failure: Error | undefined;\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const controller: StreamController<TResult> = {\n push(event) {\n const handler = handlers.get(event.type);\n\n if (handler) {\n try {\n handler(event);\n } catch {\n // User-provided stream handlers must never crash the agent.\n // Swallow — structured logging attaches here in Phase 0.5.\n }\n }\n\n const reader = pending.shift();\n\n if (reader) {\n reader.resolve({ value: event, done: false });\n return;\n }\n\n queue.push(event);\n },\n\n end(finalResult) {\n closed = true;\n resolveResult(finalResult);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.resolve({ value: undefined, done: true });\n }\n },\n\n fail(error) {\n closed = true;\n failure = error;\n rejectResult(error);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.reject(error);\n }\n },\n };\n\n const iterator: AsyncIterator<StreamEvent> = {\n next() {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (closed) {\n if (failure) {\n return Promise.reject(failure);\n }\n\n return Promise.resolve({ value: undefined, done: true });\n }\n\n return new Promise<IteratorResult<StreamEvent>>((resolve, reject) => {\n pending.push({ resolve, reject });\n });\n },\n };\n\n const stream: StreamContract<TResult> = {\n result,\n on(handlerMap) {\n for (const [key, handler] of Object.entries(handlerMap)) {\n if (handler) {\n handlers.set(\n key as StreamEvent[\"type\"],\n handler as (event: StreamEvent) => void,\n );\n }\n }\n\n return stream;\n },\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n\n return { controller, stream };\n}\n","import type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { StreamEventBody } from \"../contracts/stream/stream-event.type\";\n\n/**\n * Map an internal `AgentEventMap` entry into the public `StreamEvent`\n * shape. Event names are the same dot-notation strings on both sides;\n * only the payload shape needs per-event translation — the notable\n * case is `agent.tool.called`, whose event-map payload is a bare\n * `ToolCall` but whose stream wrapper is `{ toolCall }`.\n *\n * Extracted from the `Execution` class in `agent.ts` because it's\n * fully stateless (pure function of event name + payload) and used\n * only from the stream-forwarding path. Keeps the class focused on\n * stateful orchestration.\n */\nexport function agentEventToStreamEvent<K extends keyof AgentEventMap>(\n event: K,\n payload: AgentEventMap[K],\n): StreamEventBody | undefined {\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n return { type: \"agent.starting\", input };\n }\n\n case \"agent.trip.started\": {\n const { tripIndex, input } =\n payload as AgentEventMap[\"agent.trip.started\"];\n return { type: \"agent.trip.started\", tripIndex, input };\n }\n\n case \"agent.trip.streaming\": {\n const { delta, tripIndex } =\n payload as AgentEventMap[\"agent.trip.streaming\"];\n return { type: \"agent.trip.streaming\", delta, tripIndex };\n }\n\n case \"agent.tool.calling\": {\n const { tool, input, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n return { type: \"agent.tool.calling\", tool, input, tripIndex };\n }\n\n case \"agent.tool.called\": {\n const called = payload as AgentEventMap[\"agent.tool.called\"];\n // Split off the agent's enriched ToolCall record from the tool meta\n // so the stream event surface mirrors the bus payload shape.\n const { tool, ...toolCall } = called;\n return { type: \"agent.tool.called\", toolCall, tool };\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n return { type: \"agent.tool.failed\", tool, error, tripIndex };\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n return { type: \"agent.trip.completed\", trip };\n }\n\n case \"agent.completed\": {\n return { type: \"agent.completed\" };\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n return { type: \"agent.error\", error };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ModelToolCallRequest } from \"../contracts/model-tool-call-request.type\";\nimport type { ToolContract } from \"../tool/tool\";\n\n/**\n * Default cap on bytes accumulated in a single suspect buffer before\n * the guard gives up, flushes as text, and resets to pass-through.\n * Real envelope payloads observed in production leaks are well under\n * 1 KB; this is a safety valve against runaway / adversarial input.\n */\nconst DEFAULT_MAX_BUFFER_BYTES = 4096;\n\n/**\n * Fence opener the guard recognizes in pass-through mode. Targets the\n * lowercase form ```` ```json ```` only — that is the form models\n * actually emit in the wild when they fence-wrap a JSON tool envelope.\n * Other languages / casings flush as plain text.\n */\nconst FENCE_OPENER = \"```json\";\n\n/**\n * Closing fence sequence inside `bufferingFence` mode. Three backticks,\n * no language tag.\n */\nconst FENCE_CLOSER = \"```\";\n\n/**\n * Options passed when constructing a `JsonStreamGuard`.\n *\n * The guard is deliberately framework-agnostic of *how* deltas are\n * emitted or how recovered calls are dispatched — callers wire those\n * via `onSafeDelta` / `onRecoveredCall`. This keeps the unit-testable\n * surface tiny and lets the agent loop own all event-emission policy.\n */\nexport type JsonStreamGuardOptions = {\n /** Tools the agent has registered for this trip. Envelope lookups use `.name`. */\n tools: ReadonlyArray<ToolContract<unknown, unknown>>;\n /**\n * Hard cap on a single suspect buffer's size. When exceeded, the\n * buffer is flushed verbatim as text and the guard returns to\n * pass-through. Defaults to {@link DEFAULT_MAX_BUFFER_BYTES}.\n */\n maxBufferBytes?: number;\n /**\n * Called for every chunk of text that survived the guard — exactly\n * what the consumer should treat as the visible delta. May be\n * called many times per `feed()` call, possibly with a single\n * character or with a multi-character flush.\n */\n onSafeDelta: (delta: string) => void;\n /**\n * Called once per envelope the guard successfully classifies as a\n * tool-call recovery. The request carries `recoveredFrom:\n * \"stream-text\"` so downstream consumers can distinguish synthesized\n * calls from real ones.\n */\n onRecoveredCall: (request: ModelToolCallRequest) => void;\n};\n\n/**\n * Per-trip state machine that intercepts streamed text deltas, detects\n * JSON envelopes the model has emitted as plain text (the\n * tool-call-leakage symptom), and synthesizes real `ModelToolCallRequest`\n * entries for them while suppressing the JSON from visible output.\n *\n * **Role.** A `JsonStreamGuard` is the per-trip implementation of the\n * opt-in `streamingToolGuard` config. It sits between the model\n * adapter's `delta` chunks and the agent's `agent.trip.streaming`\n * emit + `content` accumulator — text that survives the guard is what\n * the consumer sees and what the trip records as `output`.\n *\n * **Responsibility.**\n * - Owns: a small character-level state machine (pass-through,\n * brace-buffering, fence-buffering), string-literal-aware brace\n * tracking, fence-opener / fence-closer detection, named-envelope\n * matching against registered tool schemas, buffer-cap enforcement.\n * - Does NOT own: event emission (delegated via callbacks), tool\n * dispatch, `finishReason` normalization, dedupe vs. real tool\n * calls — the agent loop handles all four.\n *\n * **Matcher tier — named envelope only (v1).** A buffer matches when\n * it parses as a JSON object containing both:\n * - a `name` or `tool` key resolving to a registered tool name, AND\n * - an `arguments` or `input` key whose value validates against the\n * resolved tool's `~standard` schema.\n * Bare-object matching (where any registered tool's schema is the\n * sole signal) is deferred until tool input schemas are tight enough\n * to distinguish — `v.record(v.any())` would match everything.\n *\n * **Per-trip lifecycle.** One instance per trip. The agent loop calls\n * `feed(chunk)` for every `delta` chunk and `finalize()` exactly once\n * after the stream's `done` chunk. Mid-stream cancellation: the loop\n * simply stops calling `feed`; any open buffer is discarded with the\n * guard instance.\n *\n * Modeled as a class (see §4.2 of code-style.md — per-call execution\n * state across phases): the machine has 3 states, accumulators for\n * brace depth, string-literal escape tracking, and a synthesized-call\n * counter for stable ids across the trip.\n *\n * @example\n * // Inside the agent's streaming trip body:\n * const guard = new JsonStreamGuard({\n * tools: this.config.tools ?? [],\n * maxBufferBytes: guardConfig.maxBufferBytes,\n * onSafeDelta: (delta) => {\n * content += delta;\n * this.emit(\"agent.trip.streaming\", { delta, tripIndex });\n * },\n * onRecoveredCall: (request) => recoveredCalls.push(request),\n * });\n *\n * for await (const chunk of model.stream(messages, callOptions)) {\n * if (chunk.type === \"delta\") await guard.feed(chunk.content);\n * // ... other chunk types\n * }\n *\n * await guard.finalize();\n */\nexport class JsonStreamGuard {\n private readonly tools: ReadonlyArray<ToolContract<unknown, unknown>>;\n private readonly maxBufferBytes: number;\n private readonly onSafeDelta: (delta: string) => void;\n private readonly onRecoveredCall: (request: ModelToolCallRequest) => void;\n\n private mode: \"passThrough\" | \"bufferingBrace\" | \"bufferingFence\" = \"passThrough\";\n\n /**\n * Characters held back in pass-through mode while we resolve whether\n * a partial fence opener (`` ` ``, `` `` ``, `` ``` ``, `` ```j ``, …)\n * will complete or break. Always a strict prefix of {@link FENCE_OPENER};\n * emptied (and emitted verbatim) the moment a non-matching character\n * arrives.\n */\n private holdback = \"\";\n\n /**\n * Accumulator while `mode === \"bufferingBrace\"` or `\"bufferingFence\"`.\n * In brace mode it carries the JSON including the outermost `{`/`}`.\n * In fence mode it carries everything between the opener and the\n * closer (the opener and closer themselves are NOT in the buffer —\n * they are reconstructed only on a flush-as-text fallback).\n */\n private buffer = \"\";\n\n /**\n * Brace-depth counter for `bufferingBrace` mode. Increments on `{`,\n * decrements on `}` — but only when {@link inString} is false, so a\n * `{` inside a JSON string literal does not skew the depth. Buffer\n * closes when depth returns to zero.\n */\n private braceDepth = 0;\n\n /** True while the scanner is inside a `\"...\"` JSON string literal. */\n private inString = false;\n\n /**\n * True when the previous character inside a string literal was a\n * backslash, so the current character is escaped (`\\\"` does not end\n * the string; `\\\\` resets the flag without escaping anything else).\n */\n private escapeNext = false;\n\n /**\n * Trailing tail of the fence buffer used to detect the closing\n * ```` ``` ```` sequence. Length capped at the closer length; rotated\n * forward as new characters arrive.\n */\n private fenceCloseTail = \"\";\n\n /**\n * Count of envelopes the guard has successfully synthesized this\n * trip. Used to assign deterministic, collision-free ids on\n * recovered `ModelToolCallRequest` entries.\n */\n private recoveredCount = 0;\n\n public constructor(options: JsonStreamGuardOptions) {\n this.tools = options.tools;\n this.maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n this.onSafeDelta = options.onSafeDelta;\n this.onRecoveredCall = options.onRecoveredCall;\n }\n\n /**\n * Feed the next raw delta from the model. Splits the chunk into\n * characters and runs each through the state machine, awaiting\n * envelope classification whenever a buffer closes mid-chunk.\n *\n * The hot path (pass-through prose with no `{` / `` ` ``) is fully\n * synchronous — `await` here only blocks at buffer-close points,\n * which are rare in normal traffic.\n */\n public async feed(chunk: string): Promise<void> {\n for (let i = 0; i < chunk.length; i++) {\n await this.processChar(chunk[i]);\n }\n }\n\n /**\n * Stream ended. Anything still in the holdback was prose\n * misclassified as a partial fence opener — emit it. Anything still\n * in an open buffer never closed — emit it as text too (a leak\n * truncated mid-flight is still text the user partially saw).\n */\n public async finalize(): Promise<void> {\n if (this.holdback.length > 0) {\n this.onSafeDelta(this.holdback);\n this.holdback = \"\";\n }\n\n if (this.mode === \"bufferingBrace\") {\n this.flushBraceBufferAsText();\n return;\n }\n\n if (this.mode === \"bufferingFence\") {\n this.flushFenceBufferAsText();\n }\n }\n\n /**\n * True when at least one envelope was recovered this trip. The\n * agent loop reads this to override `finishReason` from `\"stop\"` to\n * `\"tool_calls\"` when the model reported a natural stop but the\n * guard found tool calls hiding in the text channel.\n */\n public hasRecoveredCalls(): boolean {\n return this.recoveredCount > 0;\n }\n\n /**\n * Route a single character based on the current mode. The\n * `passThrough` branch handles holdback expansion / flushing\n * iteratively (no recursion) so a character that \"breaks\" a fence\n * opener can be re-evaluated as a fresh pass-through input in the\n * same call.\n */\n private async processChar(char: string): Promise<void> {\n if (this.mode === \"bufferingBrace\") {\n await this.processBraceChar(char);\n return;\n }\n\n if (this.mode === \"bufferingFence\") {\n await this.processFenceChar(char);\n return;\n }\n\n let current = char;\n\n while (true) {\n if (this.holdback.length === 0 && current === \"{\") {\n this.openBraceBuffer(current);\n return;\n }\n\n const extended = this.holdback + current;\n\n if (this.isFenceOpenerPrefix(extended)) {\n this.holdback = extended;\n\n if (extended === FENCE_OPENER) {\n this.openFenceBuffer();\n }\n\n return;\n }\n\n if (this.holdback.length === 0) {\n this.onSafeDelta(current);\n return;\n }\n\n this.onSafeDelta(this.holdback);\n this.holdback = \"\";\n }\n }\n\n /**\n * Recognize any strict prefix of {@link FENCE_OPENER} including the\n * full string. Used to decide whether to keep extending the holdback\n * or flush it as plain text.\n */\n private isFenceOpenerPrefix(candidate: string): boolean {\n return candidate.length <= FENCE_OPENER.length && FENCE_OPENER.startsWith(candidate);\n }\n\n /**\n * Enter `bufferingBrace` mode with the seed `{` as the first buffer\n * character and the initial brace depth set to one. Any holdback at\n * this point was already a non-fence sequence so it stays empty.\n */\n private openBraceBuffer(seed: string): void {\n this.mode = \"bufferingBrace\";\n this.buffer = seed;\n this.braceDepth = 1;\n this.inString = false;\n this.escapeNext = false;\n }\n\n /**\n * Enter `bufferingFence` mode immediately after the opener\n * ```` ```json ```` matched in the holdback. Holdback resets;\n * subsequent characters accumulate into the buffer until the\n * closing fence is seen.\n */\n private openFenceBuffer(): void {\n this.mode = \"bufferingFence\";\n this.buffer = \"\";\n this.fenceCloseTail = \"\";\n this.holdback = \"\";\n }\n\n /**\n * Process one character while accumulating a brace-delimited JSON\n * object. Tracks string-literal context so `{` / `}` inside `\"...\"`\n * do not skew brace depth. Closes (and classifies) on balanced\n * braces; flushes-as-text on cap overflow.\n */\n private async processBraceChar(char: string): Promise<void> {\n this.buffer += char;\n\n if (this.inString) {\n if (this.escapeNext) {\n this.escapeNext = false;\n return;\n }\n\n if (char === \"\\\\\") {\n this.escapeNext = true;\n return;\n }\n\n if (char === '\"') {\n this.inString = false;\n }\n\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === '\"') {\n this.inString = true;\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === \"{\") {\n this.braceDepth++;\n this.guardBufferCap(\"brace\");\n return;\n }\n\n if (char === \"}\") {\n this.braceDepth--;\n\n if (this.braceDepth === 0) {\n await this.closeBraceBuffer();\n return;\n }\n\n this.guardBufferCap(\"brace\");\n return;\n }\n\n this.guardBufferCap(\"brace\");\n }\n\n /**\n * Process one character while accumulating a fence-delimited JSON\n * block. The closing fence ```` ``` ```` ends the block; the closing\n * characters are NOT included in the classified buffer (they are\n * re-emitted only when the block flushes back to text).\n */\n private async processFenceChar(char: string): Promise<void> {\n this.fenceCloseTail += char;\n\n if (this.fenceCloseTail.length > FENCE_CLOSER.length) {\n this.fenceCloseTail = this.fenceCloseTail.slice(-FENCE_CLOSER.length);\n }\n\n if (this.fenceCloseTail === FENCE_CLOSER) {\n const innerLength = this.buffer.length - (FENCE_CLOSER.length - 1);\n this.buffer = this.buffer.slice(0, Math.max(0, innerLength));\n\n await this.closeFenceBuffer();\n return;\n }\n\n this.buffer += char;\n this.guardBufferCap(\"fence\");\n }\n\n /**\n * Enforce the buffer-byte cap. When the current buffer exceeds the\n * cap, flush it back to the consumer as plain text and reset to\n * pass-through. Acts as a runaway / adversarial-input safety valve.\n */\n private guardBufferCap(source: \"brace\" | \"fence\"): void {\n if (this.buffer.length <= this.maxBufferBytes) {\n return;\n }\n\n if (source === \"brace\") {\n this.flushBraceBufferAsText();\n return;\n }\n\n this.flushFenceBufferAsText();\n }\n\n /**\n * Run the envelope matcher against the closed brace buffer. On a\n * match, synthesize a recovered `ModelToolCallRequest`; on no\n * match, flush the buffer back as plain text. Resets state to\n * pass-through either way.\n */\n private async closeBraceBuffer(): Promise<void> {\n const closed = this.buffer;\n\n this.resetToPassThrough();\n\n const matched = await this.tryMatchEnvelope(closed);\n\n if (matched) {\n return;\n }\n\n this.onSafeDelta(closed);\n }\n\n /**\n * Run the envelope matcher against the closed fence buffer. On a\n * match, synthesize a recovered call; on no match, flush as text\n * **with** the original opener and closer reconstructed so the\n * customer sees exactly the markdown the model emitted.\n */\n private async closeFenceBuffer(): Promise<void> {\n const closed = this.buffer;\n\n this.resetToPassThrough();\n\n const matched = await this.tryMatchEnvelope(closed);\n\n if (matched) {\n return;\n }\n\n this.onSafeDelta(`${FENCE_OPENER}${closed}${FENCE_CLOSER}`);\n }\n\n /**\n * Emit the brace-buffer verbatim as text and reset to pass-through.\n * Used on cap overflow and on `finalize()` for an unclosed buffer.\n */\n private flushBraceBufferAsText(): void {\n const closed = this.buffer;\n this.resetToPassThrough();\n this.onSafeDelta(closed);\n }\n\n /**\n * Emit the fence-buffer verbatim as text, reconstructing the\n * opener and closer so the original markdown structure is\n * preserved for the consumer.\n */\n private flushFenceBufferAsText(): void {\n const closed = this.buffer;\n this.resetToPassThrough();\n this.onSafeDelta(`${FENCE_OPENER}${closed}`);\n }\n\n /**\n * Reset all per-buffer state back to the pass-through baseline.\n * Called whenever a buffer closes — by recovery, by flush, or by\n * cap overflow — so the next character starts a fresh scan.\n */\n private resetToPassThrough(): void {\n this.mode = \"passThrough\";\n this.buffer = \"\";\n this.braceDepth = 0;\n this.inString = false;\n this.escapeNext = false;\n this.fenceCloseTail = \"\";\n }\n\n /**\n * Attempt to classify a closed buffer as a tool-call envelope. On\n * success, invoke `onRecoveredCall` with a synthesized request and\n * return `true`; on failure return `false` so the caller can flush\n * the buffer back as text.\n */\n private async tryMatchEnvelope(raw: string): Promise<boolean> {\n const parsed = safeParseJson(raw);\n\n if (parsed === undefined || typeof parsed !== \"object\" || parsed === null) {\n return false;\n }\n\n const envelope = parsed as Record<string, unknown>;\n const candidateName = readString(envelope, \"name\") ?? readString(envelope, \"tool\");\n const candidateInput = readObject(envelope, \"arguments\") ?? readObject(envelope, \"input\");\n\n if (!candidateName || !candidateInput) {\n return false;\n }\n\n const tool = this.tools.find((entry) => entry.name === candidateName);\n\n if (!tool || !tool.input) {\n return false;\n }\n\n const schema = tool.input as StandardSchemaV1<unknown>;\n\n let validationResult: StandardSchemaV1.Result<unknown>;\n\n try {\n validationResult = await schema[\"~standard\"].validate(candidateInput);\n } catch {\n return false;\n }\n\n if (validationResult.issues) {\n return false;\n }\n\n this.recoveredCount++;\n\n this.onRecoveredCall({\n id: `synth_${candidateName}_${this.recoveredCount}`,\n name: candidateName,\n input: validationResult.value,\n recoveredFrom: \"stream-text\",\n });\n\n return true;\n }\n}\n\n/**\n * Parse a JSON string returning `undefined` on any failure. Local to\n * the guard so it can distinguish \"not JSON\" from a parsed `null`\n * value, which `safeJsonParse` cannot — a parsed `null` is a valid\n * JSON value but not a valid envelope, and we want the difference.\n */\nfunction safeParseJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a string-typed field from an envelope candidate. Returns\n * `undefined` when the key is missing or the value is non-string —\n * the matcher rejects either case.\n */\nfunction readString(envelope: Record<string, unknown>, key: string): string | undefined {\n const value = envelope[key];\n\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Read an object-typed field from an envelope candidate. Returns\n * `undefined` when the key is missing or the value is not a\n * plain object (rejects arrays, primitives, null) — tool input\n * schemas always validate against an object root.\n */\nfunction readObject(\n envelope: Record<string, unknown>,\n key: string,\n): Record<string, unknown> | undefined {\n const value = envelope[key];\n\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n return value as Record<string, unknown>;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n AgentContract,\n AgentEventHandler,\n AgentEventMap,\n AgentExecuteOptions,\n AgentResult,\n BaseReport,\n CompleteEvent,\n FinishReason,\n LLMTrip,\n Message,\n MiddlewareExecuteContext,\n MiddlewareState,\n MiddlewareToolContext,\n MiddlewareTripContext,\n ModelResponse,\n ModelToolCallRequest,\n StreamContract,\n StreamEventBody,\n StreamingToolGuardConfig,\n ToolCall,\n ToolEventMeta,\n Usage,\n UsageEvent,\n WithoutIdentity,\n} from \"../contracts\";\nimport {\n AgentCancelledError,\n AgentExecutionError,\n AgentMaxTripsError,\n AIError,\n SchemaValidationError,\n} from \"../errors\";\nimport { runPipeline } from \"../middleware\";\nimport type { ToolContract, ToolInvokeResult } from \"../tool/tool\";\nimport {\n accumulateCost,\n computeCost,\n extractJsonPayload,\n generateRunId,\n safeJsonParse,\n stampReportLineage,\n} from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\nimport { buildAgentInputMessages } from \"./agent-input-builder\";\nimport { logAgentEvent } from \"./agent-log-event\";\nimport { createAgentStream, type StreamController } from \"./agent-stream\";\nimport { agentEventToStreamEvent } from \"./agent-to-stream-event\";\nimport { JsonStreamGuard } from \"./json-stream-guard\";\n\nconst LOG_MODULE = \"ai.agent\";\n\n/**\n * Detect abort-flavored errors surfaced by SDK HTTP layers — the\n * DOM `AbortError`, axios `ERR_CANCELED`, node-fetch's own\n * `AbortError`. Used to classify them as cancellation rather than\n * generic agent-execution failures.\n */\nfunction isAbortLike(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n\n const e = err as { name?: unknown; code?: unknown };\n\n return e.name === \"AbortError\" || e.code === \"ERR_CANCELED\" || e.code === \"ABORT_ERR\";\n}\n\n/**\n * Readable synthetic name for agents constructed without an explicit\n * `name`. Format: `anon_<provider>_<model>[_<tool1>+<tool2>+...]` —\n * deterministic (same config → same name across restarts) and\n * human-readable in logs / workflow snapshots.\n *\n * Keeps drift detection honest for the `ai.agent({ model })`\n * one-liner without punishing it with a hashed id nobody can read.\n */\nfunction synthesizeAgentName<T>(config: AgentConfig<T>): string {\n const provider = (config.model as unknown as { provider?: string })?.provider ?? \"unknown\";\n const model = config.model?.name ?? \"unknown\";\n const tools = (config.tools ?? [])\n .map((tool) => tool.name)\n .sort()\n .join(\"+\");\n\n const base = `anon_${sanitize(provider)}_${sanitize(model)}`;\n return tools ? `${base}_${sanitize(tools, { keepPlus: true })}` : base;\n}\n\nfunction sanitize(value: string, opts: { keepPlus?: boolean } = {}): string {\n const allowed = opts.keepPlus ? /[^a-zA-Z0-9._+-]/g : /[^a-zA-Z0-9._-]/g;\n return value.replace(allowed, \"-\");\n}\n\n/**\n * Authoring-time check on the middleware array. Throws an\n * `AgentExecutionError` with `context: { authoring: true }` the\n * moment an invalid entry is found — the agent factory surface is\n * where config bugs should surface, not ten trips into a run.\n *\n * Validates:\n * - Every entry is a non-null object with a non-empty string `name`.\n * - No two entries share the same `name` (would silently collide on\n * `ctx.state` keys and produce impossible-to-debug behavior).\n *\n * Does NOT validate that hook maps contain callable functions —\n * that would catch late-binding bugs but also reject legitimate\n * patterns like `before` being conditionally `undefined`. Runtime\n * dispatch handles missing hooks safely.\n */\nfunction validateMiddleware(middleware: ReadonlyArray<unknown> | undefined): void {\n if (!middleware || middleware.length === 0) {\n return;\n }\n\n const seen = new Set<string>();\n\n for (let index = 0; index < middleware.length; index++) {\n const entry = middleware[index];\n\n if (!entry || typeof entry !== \"object\") {\n throw new AgentExecutionError(\n `middleware[${index}] must be an object; received ${entry === null ? \"null\" : typeof entry}`,\n { context: { authoring: true, index } },\n );\n }\n\n const name = (entry as { name?: unknown }).name;\n\n if (typeof name !== \"string\" || name.length === 0) {\n throw new AgentExecutionError(`middleware[${index}] must have a non-empty string \"name\"`, {\n context: { authoring: true, index },\n });\n }\n\n if (seen.has(name)) {\n throw new AgentExecutionError(\n `duplicate middleware name \"${name}\" — each middleware needs a unique name so ctx.state keys do not collide`,\n { context: { authoring: true, index, name } },\n );\n }\n\n seen.add(name);\n }\n}\n\n/**\n * Creates an executable AI agent from the given configuration.\n *\n * The agent runs a bounded trip loop: each trip calls the model, dispatches\n * any requested tool calls, then loops until the model stops or `maxTrips`\n * is reached. Each `execute()` / `stream()` call spawns a fresh internal\n * `Execution` instance — the factory itself holds no state across calls.\n *\n * `execute()` never throws — any error is attached to the returned result\n * under `result.error`. `stream()` surfaces errors both on the terminal\n * `error` stream event and via the `stream.result` promise.\n *\n * @example\n * const myAgent = agent({\n * model: openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the capital of Egypt?\");\n *\n * @example\n * const stream = myAgent.stream(\"Write a haiku about Cairo.\");\n *\n * for await (const event of stream) {\n * if (event.type === \"streaming\") process.stdout.write(event.delta);\n * }\n *\n * const result = await stream.result;\n */\nexport function agent<TOutput = unknown>(config: AgentConfig<TOutput>): AgentContract<TOutput> {\n // Authoring-time validation of the middleware array. Rejects two\n // classes of bug that would otherwise surface as opaque failures\n // mid-execution: (a) entries that aren't proper middleware\n // objects (null, undefined, missing `name`), and (b) two\n // middlewares sharing the same `name`, which would silently\n // collide on `ctx.state` keys. Fail fast, fail loud — per the\n // authoring-time rules in `domains/ai/conventions/errors.md`.\n validateMiddleware(config.middleware);\n\n // Resolve the agent's identity. Explicit `name` wins; otherwise we\n // synthesize a DETERMINISTIC fingerprint from the config's\n // identity-defining fields (model + provider + tool names). Same\n // config across process restarts produces the same synthetic name,\n // so workflow signature drift detection stays honest for agents\n // composed into workflows without explicit names.\n const isAnonymous = !config.name || typeof config.name !== \"string\";\n const name = isAnonymous ? synthesizeAgentName(config) : (config.name as string);\n const resolvedConfig: AgentConfig<TOutput> = { ...config, name };\n\n // Instance-level handlers registered via `.on()`. Stored here\n // (factory-scope) so every `execute()` / `stream()` call on this\n // agent sees the same set. Each event name gets its own Set so\n // `off()` can remove a specific handler without disturbing others.\n const instanceHandlers = new Map<\n keyof AgentEventMap,\n Set<AgentEventHandler<keyof AgentEventMap>>\n >();\n\n function on<K extends keyof AgentEventMap>(event: K, handler: AgentEventHandler<K>): () => void {\n const existing = instanceHandlers.get(event);\n const bucket = existing ?? new Set<AgentEventHandler<keyof AgentEventMap>>();\n\n if (!existing) {\n instanceHandlers.set(event, bucket);\n }\n\n bucket.add(handler as AgentEventHandler<keyof AgentEventMap>);\n\n return () => off(event, handler);\n }\n\n function off<K extends keyof AgentEventMap>(event: K, handler: AgentEventHandler<K>): void {\n const bucket = instanceHandlers.get(event);\n\n if (!bucket) {\n return;\n }\n\n bucket.delete(handler as AgentEventHandler<keyof AgentEventMap>);\n\n if (bucket.size === 0) {\n instanceHandlers.delete(event);\n }\n }\n\n return {\n name,\n isAnonymous,\n description: config.description,\n async execute(\n input: string,\n options?: AgentExecuteOptions<TOutput>,\n ): Promise<AgentResult<TOutput>> {\n return new Execution<TOutput>(\n resolvedConfig,\n input,\n options,\n undefined,\n instanceHandlers,\n ).run();\n },\n\n stream(\n input: string,\n options?: AgentExecuteOptions<TOutput>,\n ): StreamContract<AgentResult<TOutput>> {\n const { controller, stream } = createAgentStream<AgentResult<TOutput>>();\n\n const execution = new Execution<TOutput>(\n resolvedConfig,\n input,\n options,\n controller,\n instanceHandlers,\n );\n\n void execution.run();\n\n return stream;\n },\n\n on,\n off,\n };\n}\n\n/**\n * Name → handler-set map shared between the `agent()` factory and its\n * per-call `Execution`. Each `.on()` registration mutates this map;\n * every `Execution` reads from the same reference so additions and\n * removals take effect mid-flight.\n */\ntype InstanceHandlerMap = Map<keyof AgentEventMap, Set<AgentEventHandler<keyof AgentEventMap>>>;\n\n/**\n * Per-call driver that owns the full lifecycle of a single\n * `agent.execute()` or `agent.stream()` invocation.\n *\n * **Role.** An `Execution` is the short-lived state container and phase\n * orchestrator for one agent run. The public `agent()` factory stays purely\n * functional — all mutable bookkeeping (trips, tool calls, usage totals,\n * message history, terminal error, parsed output) lives here so each call\n * gets a fresh, isolated instance.\n *\n * **Responsibility.**\n * - Owns: building the initial message list, driving the bounded trip loop,\n * dispatching tool calls safely, parsing the final output against the\n * caller's schema, emitting lifecycle events (to both the user handler\n * and, in stream mode, the `StreamController`), and producing the\n * `AgentResult`.\n * - Does NOT own: how the model produces responses (delegated to\n * `ModelContract.complete` / `ModelContract.stream`), how tools execute\n * (delegated to `ToolContract.invoke`), the async-queue plumbing for\n * streaming (delegated to `createAgentStream`), or any cross-call state\n * (factory-level concerns live in `agent()`).\n *\n * Streaming mode is opt-in via the fourth constructor argument: pass a\n * `StreamController` and every event is mirrored into it while model calls\n * are driven via `model.stream()` instead of `model.complete()`. The public\n * contract of `execute()` says it never throws — `Execution` enforces that\n * by funneling every unexpected error into `this.error` and returning a\n * well-formed result regardless of what went wrong.\n *\n * Not exported — consumers interact only with the `agent()` factory (see\n * §4.2 of code-style.md — \"per-call execution state across phases\").\n *\n * @example\n * // Non-streaming — inside agent.execute():\n * const result = await new Execution(config, input, options).run();\n *\n * @example\n * // Streaming — inside agent.stream():\n * const { controller, stream } = createAgentStream();\n * void new Execution(config, input, options, controller).run();\n * return stream;\n */\nclass Execution<TOutput> {\n private readonly trips: LLMTrip[] = [];\n private readonly toolCalls: ToolCall[] = [];\n private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n private readonly messages: Message[] = [];\n private readonly maxTrips: number;\n private readonly startedAt = new Date();\n private readonly start = performance.now();\n private readonly runId = generateRunId(\"agent\");\n private readonly logger: Logger = log;\n private readonly middleware: ReadonlyArray<\n NonNullable<AgentConfig<TOutput>[\"middleware\"]>[number]\n >;\n private readonly middlewareState: MiddlewareState = new Map();\n\n private error?: AIError;\n private data?: TOutput;\n private responseSchema?: Record<string, unknown>;\n\n public constructor(\n private readonly config: AgentConfig<TOutput>,\n private readonly input: string,\n private readonly options?: AgentExecuteOptions<TOutput>,\n private readonly streamController?: StreamController<AgentResult<TOutput>>,\n private readonly instanceHandlers?: InstanceHandlerMap,\n ) {\n this.maxTrips = config.maxTrips ?? 10;\n this.middleware = config.middleware ?? [];\n }\n\n /**\n * Base middleware context shared by every level. `state` is the\n * single mutable bag threaded through `execute`, `trip`, and `tool`\n * hooks for the lifetime of this execution — fresh per `execute()`\n * call, never reused across runs.\n */\n private buildExecuteContext(): MiddlewareExecuteContext {\n return {\n agent: {\n name: this.config.name ?? this.config.model.name,\n isAnonymous: !this.config.name,\n },\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n input: this.input,\n options: this.options as AgentExecuteOptions<unknown> | undefined,\n state: this.middlewareState,\n signal: this.options?.signal,\n };\n }\n\n /**\n * Entry point for a single agent execution. Wraps the real work\n * (`runCore`) in the `execute`-level middleware pipeline, then\n * emits the terminal `agent.completed` / `agent.error` events and\n * closes the stream (if any) with the post-pipeline result — so\n * middleware that short-circuits or transforms the final result\n * still produces a well-formed public outcome.\n *\n * Must never throw: any error that escapes the pipeline is\n * converted into an `AgentResult` with `error` populated before\n * returning, preserving the `agent.execute()` public contract.\n */\n public async run(): Promise<AgentResult<TOutput>> {\n const context = this.buildExecuteContext();\n\n let result: AgentResult<TOutput>;\n\n try {\n result = (await runPipeline(\n this.middleware,\n \"execute\",\n context,\n () => this.runCore(),\n this.logger,\n )) as AgentResult<TOutput>;\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n result = this.buildResult();\n }\n\n if (result.error) {\n this.emit(\"agent.error\", { error: result.error });\n }\n\n this.emit(\"agent.completed\", { result });\n\n // Fire the `onComplete` hook with a flat payload (runId +\n // durationMs pre-extracted) for audit-log consumers. Awaited but\n // errors swallowed so consumer bugs cannot crash the agent or\n // interfere with the result returned to the caller.\n await this.fireCompleteHook(result);\n\n this.streamController?.end(result);\n\n return result;\n }\n\n /**\n * Inner body wrapped by the `execute`-level pipeline. Drives the\n * full lifecycle — build messages → emit starting → run trip loop\n * → parse output → build result. Catches any unexpected throw and\n * funnels it into `this.error` so the returned result is always\n * well-formed; `execute`-level `after` hooks receive the result,\n * with `error` populated when things went wrong.\n */\n private async runCore(): Promise<AgentResult<TOutput>> {\n try {\n await this.buildInitialMessages();\n\n this.emit(\"agent.starting\", { input: this.input });\n\n await this.runTripLoop();\n\n const parseOutcome = await this.parseOutput();\n\n if (parseOutcome === \"failed\" && this.options?.repair) {\n await this.runRepairLoop();\n }\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n }\n\n return this.buildResult();\n }\n\n /**\n * Resolve the system prompt (string or `SystemPromptContract`), merge\n * placeholders from config + execute options, inject a structured-output\n * instruction when the caller wants typed output but the model can't\n * enforce it natively, prepend any conversation history, and append the\n * user input. Produces the initial `messages` array the first trip sends\n * to the model. Runs exactly once per execution.\n */\n private async buildInitialMessages(): Promise<void> {\n const { messages, responseSchema } = await buildAgentInputMessages({\n config: this.config,\n input: this.input,\n options: this.options,\n });\n this.messages.push(...messages);\n this.responseSchema = responseSchema;\n }\n\n /**\n * Drive sequential trips up to `maxTrips`. Each trip may stop the loop\n * naturally (model returned a non-tool-call finish), abort it (model\n * threw), or continue it (model requested tools). When the loop exits\n * after the cap without a natural stop, records a \"Max trips exceeded\"\n * error so the caller can distinguish runaway tool loops from a real result.\n */\n private async runTripLoop(): Promise<void> {\n for (let tripIndex = 0; tripIndex < this.maxTrips; tripIndex++) {\n if (this.options?.signal?.aborted) {\n this.error = this.makeCancelledError();\n return;\n }\n\n const tripInput = tripIndex === 0 ? this.input : \"[tool results]\";\n const outcome = await this.runTrip(tripIndex, tripInput);\n\n if (outcome === \"error\" || outcome === \"stop\") {\n return;\n }\n }\n\n const lastTrip = this.trips[this.trips.length - 1];\n\n if (lastTrip?.finishReason === \"tool_calls\") {\n this.error = new AgentMaxTripsError(\"Max trips exceeded\", {\n maxTrips: this.maxTrips,\n });\n }\n }\n\n /**\n * Execute one round-trip to the model. Aggregates usage into the running\n * total, dispatches any requested tool calls, appends the assistant +\n * tool-result messages for the next trip, and records an `LLMTrip`.\n * Returns an outcome that tells `runTripLoop` whether to continue, stop,\n * or abort.\n */\n private async runTrip(\n tripIndex: number,\n tripInput: string,\n ): Promise<\"continue\" | \"stop\" | \"error\"> {\n this.emit(\"agent.trip.started\", { tripIndex, input: tripInput });\n\n const tripStartedAt = new Date();\n const tripStart = performance.now();\n\n let response: ModelResponse;\n\n try {\n response = await this.runTripThroughPipeline(tripIndex);\n } catch (thrown) {\n this.error = this.toAIError(thrown);\n\n const failedTrip: LLMTrip = {\n index: tripIndex,\n input: tripInput,\n output: \"\",\n finishReason: \"error\",\n startedAt: tripStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - tripStart,\n usage: { input: 0, output: 0, total: 0 },\n error: this.error,\n };\n\n this.trips.push(failedTrip);\n\n this.emit(\"agent.trip.completed\", { trip: failedTrip });\n this.emit(\"agent.error\", { error: this.error });\n\n return \"error\";\n }\n\n // Attach per-trip cost breakdown using the model's pricing table\n // (when configured). Done at the framework boundary so stored trip\n // records carry historical cost — Panoptic and other archive\n // consumers never re-derive against today's pricing, and the\n // input/output/cached split stays queryable without joining to a\n // pricing table at all.\n if (response.usage.cost === undefined) {\n response.usage.cost = computeCost(response.usage, this.config.model.pricing);\n }\n\n this.usage.input += response.usage.input;\n this.usage.output += response.usage.output;\n this.usage.total += response.usage.total;\n if (response.usage.cachedTokens !== undefined) {\n this.usage.cachedTokens = (this.usage.cachedTokens ?? 0) + response.usage.cachedTokens;\n }\n this.usage.cost = accumulateCost(this.usage.cost, response.usage.cost);\n\n // Fire the `onUsage` hook with a flat, pre-packaged payload so\n // cost-ledger code receives stable identity (runId, model+provider)\n // without joining from elsewhere. Awaited but errors swallowed.\n await this.fireUsageHook(tripIndex, response.usage);\n\n const isToolCallTrip =\n response.finishReason === \"tool_calls\" &&\n response.toolCalls !== undefined &&\n response.toolCalls.length > 0;\n\n const tripToolCalls: ToolCall[] = [];\n\n if (isToolCallTrip) {\n this.messages.push({\n role: \"assistant\",\n content: response.content,\n toolCalls: response.toolCalls,\n });\n\n for (const toolCallRequest of response.toolCalls!) {\n const record = await this.dispatchToolCall(toolCallRequest, tripIndex);\n\n tripToolCalls.push(record);\n }\n }\n\n const trip: LLMTrip = {\n index: tripIndex,\n input: tripInput,\n output: response.content,\n finishReason: response.finishReason,\n startedAt: tripStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - tripStart,\n usage: response.usage,\n toolCalls: tripToolCalls.length > 0 ? tripToolCalls : undefined,\n };\n\n this.trips.push(trip);\n\n this.emit(\"agent.trip.completed\", { trip });\n\n if (!isToolCallTrip) {\n return \"stop\";\n }\n\n // Terminate the trip loop when EVERY tool call this trip is\n // `mode: \"silent\"`. Silent tools don't feed their result back\n // to the model — the prose the model streamed alongside the\n // tool call IS the final reply. The \"all\" rule is load-bearing:\n // if any feedback tool was called too, its result still needs\n // to round-trip, so we must continue.\n //\n // Composite (`asTool`-wrapped) tools never set `mode: \"silent\"`\n // in v1 — silent-composite mechanics are deferred per plan\n // 2026-05-07-silent-tools.md (Q4). They behave as feedback.\n const allSilent = response.toolCalls!.every((request) => {\n const registered = this.config.tools?.find((tool) => tool.name === request.name);\n return registered?.mode === \"silent\";\n });\n\n return allSilent ? \"stop\" : \"continue\";\n }\n\n /**\n * Route `getModelResponse` through the `trip`-level middleware\n * pipeline. `trip.before` hooks can short-circuit the trip by\n * returning a synthetic `ModelResponse` (semantic cache hit).\n * `trip.after` hooks can transform the response before the trip\n * record is built or any tool calls are dispatched. `trip.onError`\n * hooks can recover from provider failures (fallback chain).\n */\n private async runTripThroughPipeline(tripIndex: number): Promise<ModelResponse> {\n const context: MiddlewareTripContext = {\n ...this.buildExecuteContext(),\n tripIndex,\n messages: this.messages,\n };\n\n return (await runPipeline(\n this.middleware,\n \"trip\",\n context,\n () => this.getModelResponse(tripIndex),\n this.logger,\n )) as ModelResponse;\n }\n\n /**\n * Produce the `ModelResponse` for the current trip. In non-streaming\n * mode, delegates straight to `model.complete()`. In streaming mode,\n * drains `model.stream()` while emitting `streaming` events per delta\n * and accumulates the chunks into the same `ModelResponse` shape, so the\n * rest of the trip pipeline (tool dispatch, trip record, usage\n * aggregation) stays identical between the two modes.\n */\n private async getModelResponse(tripIndex: number): Promise<ModelResponse> {\n const callOptions = {\n ...this.config.modelOptions,\n tools: this.config.tools ?? [],\n ...(this.responseSchema ? { responseSchema: this.responseSchema } : {}),\n ...(this.options?.signal ? { signal: this.options.signal } : {}),\n };\n\n if (!this.streamController) {\n return this.config.model.complete(this.messages, callOptions);\n }\n\n let content = \"\";\n let finishReason: FinishReason = \"stop\";\n let usage: Usage = { input: 0, output: 0, total: 0 };\n const toolCalls: ModelToolCallRequest[] = [];\n const recoveredCalls: ModelToolCallRequest[] = [];\n\n const guardConfig = this.resolveStreamingToolGuard();\n const guard = guardConfig\n ? new JsonStreamGuard({\n tools: (this.config.tools ?? []) as ReadonlyArray<ToolContract<unknown, unknown>>,\n maxBufferBytes: guardConfig.maxBufferBytes,\n onSafeDelta: (delta) => {\n content += delta;\n\n this.emit(\"agent.trip.streaming\", { delta, tripIndex });\n },\n onRecoveredCall: (request) => {\n recoveredCalls.push(request);\n },\n })\n : undefined;\n\n for await (const chunk of this.config.model.stream(this.messages, callOptions)) {\n // Mid-stream abort — break out cleanly instead of continuing to\n // consume the iterator. The underlying fetch is already\n // cancelled via `signal` forwarded in callOptions; this covers\n // adapters that don't honor signal natively and keeps mock\n // models consistent under cancellation tests.\n if (this.options?.signal?.aborted) {\n throw this.makeCancelledError();\n }\n\n if (chunk.type === \"delta\") {\n if (guard) {\n await guard.feed(chunk.content);\n } else {\n content += chunk.content;\n\n this.emit(\"agent.trip.streaming\", { delta: chunk.content, tripIndex });\n }\n\n continue;\n }\n\n if (chunk.type === \"tool-call\") {\n toolCalls.push({\n id: chunk.id,\n name: chunk.name,\n input: chunk.input,\n ...(chunk.providerMetadata ? { providerMetadata: chunk.providerMetadata } : {}),\n });\n\n continue;\n }\n\n finishReason = chunk.finishReason;\n usage = chunk.usage;\n }\n\n if (guard) {\n await guard.finalize();\n }\n\n // Dedupe synthesized calls against real ones the provider streamed\n // structurally — the model occasionally emits BOTH channels for\n // the same call (real tool-call chunk + narrated JSON envelope).\n // Real wins; the synthesized duplicate is dropped so dispatch\n // doesn't run twice. See plan 2026-05-22 §Q5.\n const dedupedRecovered = recoveredCalls.filter(\n (recovered) => !isDuplicateToolCall(recovered, toolCalls),\n );\n\n const mergedToolCalls = [...toolCalls, ...dedupedRecovered];\n\n // When the guard recovered any calls but the model reported a\n // natural `\"stop\"`, override to `\"tool_calls\"` so the agent's\n // dispatch loop (`runTrip` → `isToolCallTrip`) actually fires.\n // Without this the guard silently suppresses the leaked JSON but\n // never dispatches the real action — chips never render.\n const resolvedFinishReason: FinishReason =\n dedupedRecovered.length > 0 && finishReason === \"stop\" ? \"tool_calls\" : finishReason;\n\n return {\n content,\n finishReason: resolvedFinishReason,\n usage,\n toolCalls: mergedToolCalls.length > 0 ? mergedToolCalls : undefined,\n };\n }\n\n /**\n * Resolve the effective `streamingToolGuard` for this trip.\n * Per-call options win over the agent-level config when the key is\n * explicitly present on options (including the explicit `undefined`\n * \"disable for this call\" form). Returns `undefined` when no guard\n * should run.\n */\n private resolveStreamingToolGuard(): StreamingToolGuardConfig | undefined {\n if (\n this.options !== undefined &&\n Object.prototype.hasOwnProperty.call(this.options, \"streamingToolGuard\")\n ) {\n return this.options.streamingToolGuard;\n }\n\n return this.config.streamingToolGuard;\n }\n\n /**\n * Dispatch a single tool call requested by the model. Looks up the tool\n * by name, invokes it via the safe `ToolContract.invoke` entry, pushes a\n * matching tool-result message into `this.messages` so the next trip can\n * see it, and emits the right lifecycle event (`tool-called` on success,\n * `tool-calling-failed` when the tool is unregistered or invoke returned\n * an error). Never throws — always returns a `ToolCall` record.\n */\n private async dispatchToolCall(\n toolCallRequest: ModelToolCallRequest,\n tripIndex: number,\n ): Promise<ToolCall> {\n const registeredTool = this.config.tools?.find((tool) => tool.name === toolCallRequest.name);\n\n if (!registeredTool) {\n const error = new AgentExecutionError(`Tool not registered: ${toolCallRequest.name}`, {\n context: { toolName: toolCallRequest.name, tripIndex },\n });\n\n const nowIso = new Date().toISOString();\n\n const record: ToolCall = {\n runId: generateRunId(\"tool\"),\n rootRunId: this.runId,\n name: toolCallRequest.name,\n type: \"tool\",\n status: \"failed\",\n startedAt: nowIso,\n endedAt: nowIso,\n duration: 0,\n usage: { input: 0, output: 0, total: 0 },\n children: [],\n tripIndex,\n input: toolCallRequest.input,\n error,\n ...(toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}),\n };\n\n this.toolCalls.push(record);\n\n this.messages.push({\n role: \"tool\",\n toolCallId: toolCallRequest.id,\n content: JSON.stringify({ error: error.message }),\n });\n\n // Stub meta — there's no real tool to describe. Carries the\n // requested name for log correlation and an explanatory\n // description so consumers don't see an empty string.\n this.emit(\"agent.tool.failed\", {\n tool: {\n name: toolCallRequest.name,\n description: \"(unregistered tool — no description available)\",\n },\n input: toolCallRequest.input,\n error,\n tripIndex,\n });\n\n return record;\n }\n\n // Build the lightweight event meta once. Resolves `action` to a\n // string here so consumers receive plain data rather than having\n // to re-evaluate a callback on every event.\n const toolMeta: ToolEventMeta = {\n name: registeredTool.name,\n description: registeredTool.description,\n action: resolveToolAction(registeredTool, toolCallRequest.input),\n };\n\n this.emit(\"agent.tool.calling\", {\n tool: toolMeta,\n input: toolCallRequest.input,\n tripIndex,\n });\n\n const toolContext: MiddlewareToolContext = {\n ...this.buildExecuteContext(),\n tripIndex,\n messages: this.messages,\n tool: {\n name: registeredTool.name,\n description: registeredTool.description,\n mode: registeredTool.mode,\n },\n request: toolCallRequest,\n };\n\n let invokeResult: ToolInvokeResult<unknown>;\n\n try {\n invokeResult = (await runPipeline(\n this.middleware,\n \"tool\",\n toolContext,\n () => registeredTool.invoke(toolCallRequest.input, this.options?.toolCtx),\n this.logger,\n )) as ToolInvokeResult<unknown>;\n } catch (thrown) {\n // A `tool`-level middleware hook threw. The real invoke never\n // throws (it funnels errors into `result.error`), so only a\n // middleware abort or a bug reaches this branch. Synthesize a\n // failed-invoke record so the tool-call trace stays consistent.\n const error = this.toAIError(thrown);\n const nowIso = new Date().toISOString();\n const emptyUsage: Usage = { input: 0, output: 0, total: 0 };\n\n const failedRunId = generateRunId(\"tool\");\n invokeResult = {\n error,\n usage: emptyUsage,\n report: {\n runId: failedRunId,\n rootRunId: failedRunId,\n name: registeredTool.name,\n version: registeredTool.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: nowIso,\n endedAt: nowIso,\n duration: 0,\n usage: emptyUsage,\n children: [],\n },\n };\n }\n\n // The agent-level ToolCall record merges the tool's own invocation\n // report with agent-side enrichments (tripIndex, input, output,\n // error). When the underlying tool was an `asTool`-wrapped\n // composite, its inner report becomes the sole child of this\n // ToolCall — preserving the full nested tree while keeping this\n // node's own `type` as `\"tool\"` (from the agent's POV it *was* a\n // tool dispatch).\n const innerReport = invokeResult.report;\n const isComposite = innerReport.type !== \"tool\";\n\n const record: ToolCall = {\n runId: innerReport.runId,\n rootRunId: this.runId,\n name: toolCallRequest.name,\n version: registeredTool.version,\n type: \"tool\",\n status: innerReport.status,\n startedAt: innerReport.startedAt,\n endedAt: innerReport.endedAt,\n duration: innerReport.duration,\n usage: invokeResult.usage,\n children: isComposite ? [innerReport] : innerReport.children,\n tripIndex,\n input: toolCallRequest.input,\n output: invokeResult.data,\n error: invokeResult.error,\n ...(toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}),\n };\n\n this.toolCalls.push(record);\n\n // Roll child usage into the agent's accumulator. Leaf tools\n // contribute zero; `asTool`-wrapped composites contribute the\n // full cost of the inner agent/workflow/supervisor run.\n this.usage.input += invokeResult.usage.input;\n this.usage.output += invokeResult.usage.output;\n this.usage.total += invokeResult.usage.total;\n this.usage.cost = accumulateCost(this.usage.cost, invokeResult.usage.cost);\n\n this.messages.push({\n role: \"tool\",\n toolCallId: toolCallRequest.id,\n content: invokeResult.error\n ? JSON.stringify({ error: invokeResult.error.message })\n : JSON.stringify(invokeResult.data ?? null),\n });\n\n if (invokeResult.error) {\n this.emit(\"agent.tool.failed\", {\n tool: toolMeta,\n input: toolCallRequest.input,\n error: invokeResult.error,\n tripIndex,\n });\n } else {\n this.emit(\"agent.tool.called\", { ...record, tool: toolMeta });\n }\n\n return record;\n }\n\n /**\n * Parse the final trip output against the user-supplied schema (if any).\n * Failures populate `this.error` but never throw. Returns an outcome the\n * caller uses to decide whether self-repair is worth attempting:\n *\n * - `\"skipped\"` — no schema, or a prior trip-level error already set\n * `this.error` (model crash, max trips). Not repairable; the failure\n * isn't a parse problem the model can fix by re-asking.\n * - `\"failed\"` — schema present, output text either failed JSON.parse\n * or failed `~standard.validate`. Repairable via `runRepairLoop`.\n * - `\"success\"` — parsed and validated; `this.data` populated.\n */\n private async parseOutput(): Promise<\"success\" | \"failed\" | \"skipped\"> {\n const schema = this.options?.output ?? this.config.output;\n\n if (!schema || this.error) {\n return \"skipped\";\n }\n\n const finalTrip = this.trips[this.trips.length - 1];\n const text = finalTrip?.output ?? \"\";\n\n if (!text) {\n return \"skipped\";\n }\n\n const payload = extractJsonPayload(text);\n const sentinel = Symbol(\"parse-failed\");\n const parsed = safeJsonParse<unknown>(payload, sentinel);\n\n if (parsed === sentinel) {\n this.error = new SchemaValidationError(\"Failed to parse model output as JSON\", {\n context: { text },\n });\n return \"failed\";\n }\n\n const validation = await (schema as StandardSchemaV1<TOutput>)[\"~standard\"].validate(parsed);\n\n if (validation.issues) {\n const summary = validation.issues.map((issue) => issue.message).join(\"; \");\n this.error = new SchemaValidationError(summary, {\n issues: validation.issues,\n });\n return \"failed\";\n }\n\n this.data = validation.value;\n return \"success\";\n }\n\n /**\n * Opt-in self-repair loop for `output` schema failures. Triggered only\n * when `options.repair` is set and `parseOutput()` returned `\"failed\"`.\n *\n * Each attempt:\n * 1. Pushes the bad assistant response into `this.messages` (so the\n * model can see what it just produced).\n * 2. Pushes a corrective user message naming the validation/parse error.\n * 3. Runs another trip — counted against the same `maxTrips` cap as\n * normal trips so a stuck model can't loop forever.\n * 4. Re-parses. Stops on success, on a trip-level error, or when\n * either `maxAttempts` or `maxTrips` is exhausted.\n *\n * Resets `this.error` and `this.data` before each attempt so the final\n * outcome (success or last failure) is what surfaces to the caller.\n */\n private async runRepairLoop(): Promise<void> {\n const maxAttempts = this.options?.repair?.maxAttempts ?? 1;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (this.trips.length >= this.maxTrips) {\n return;\n }\n\n const lastTrip = this.trips[this.trips.length - 1];\n const badResponse = lastTrip?.output ?? \"\";\n const failureReason = this.error?.message ?? \"unknown validation failure\";\n\n this.error = undefined;\n this.data = undefined;\n\n this.messages.push({ role: \"assistant\", content: badResponse });\n\n this.messages.push({\n role: \"user\",\n content: [\n `Your previous response failed validation: ${failureReason}.`,\n \"Respond again with valid JSON only — no prose, no markdown fences, no commentary.\",\n ].join(\" \"),\n });\n\n const tripIndex = this.trips.length;\n\n this.logger.warn(LOG_MODULE, \"repair.attempting\", \"retrying after validation failure\", {\n attempt: attempt + 1,\n maxAttempts,\n reason: failureReason,\n });\n\n const outcome = await this.runTrip(tripIndex, \"[repair attempt]\");\n\n if (outcome === \"error\") {\n return;\n }\n\n const parseOutcome = await this.parseOutput();\n\n if (parseOutcome === \"success\") {\n return;\n }\n }\n }\n\n /**\n * Build the final `AgentResult` snapshot from accumulated state\n * (trips, tool calls, data/error, usage, timing).\n *\n * Pure — no side effects. `run()` owns terminal event emission and\n * stream closure so the post-pipeline result (possibly transformed\n * or short-circuited by an `execute`-level middleware) is what\n * flows out to consumers and listeners.\n *\n * Trips, tool calls, status, and timing live under `report` so the\n * root stays focused on the four things callers reach for most:\n * `data`, `text`, `usage`, `error`.\n */\n private buildResult(): AgentResult<TOutput> {\n const finalTrip = this.trips[this.trips.length - 1];\n const endedAt = new Date();\n\n const agentName = this.config.name ?? this.config.model.name;\n const status: BaseReport[\"status\"] = this.error\n ? this.error instanceof AgentCancelledError\n ? \"cancelled\"\n : \"failed\"\n : \"completed\";\n\n const report = {\n runId: this.runId,\n rootRunId: this.runId,\n name: agentName,\n version: this.config.version,\n type: \"agent\" as const,\n status,\n startedAt: this.startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration: performance.now() - this.start,\n usage: this.usage,\n children: this.toolCalls,\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n trips: this.trips,\n };\n\n // Stamp lineage on the assembled tree exactly once per run.\n // Rewrites any inner self-roots from composite children to this\n // run's id, stamps `reportSchemaVersion` on the root, and\n // propagates `sessionId` to every node.\n stampReportLineage(report, {\n rootRunId: this.runId,\n sessionId: this.options?.sessionId,\n });\n\n return {\n type: \"agent\",\n data: this.data,\n text: finalTrip?.output,\n report,\n usage: this.usage,\n error: this.error,\n };\n }\n\n /**\n * Normalize any thrown value into an `AIError`. `AIError` instances\n * pass through untouched; provider-adapter SDK errors are caught by\n * the adapter and already arrive typed, so this branch mainly\n * handles runtime crashes (TypeError, ReferenceError) inside\n * model.complete / model.stream and non-Error values (`throw \"bad\"`).\n */\n private toAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n // Classify abort-flavored errors (DOMException \"AbortError\",\n // node-fetch's `FetchError` with name \"AbortError\", `ERR_CANCELED`\n // from the OpenAI SDK's axios-ish layer) as cancelled instead of\n // a generic exec failure so callers can route retries correctly.\n if (isAbortLike(thrown)) {\n return this.makeCancelledError();\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new AgentExecutionError(message, { cause: thrown });\n }\n\n /**\n * Build the typed cancelled error that both the trip-loop guard\n * and the mid-stream guard emit. Captures the abort reason when\n * one was supplied to `controller.abort(reason)` so logs and\n * telemetry can see what cancelled the run.\n */\n private makeCancelledError(): AgentCancelledError {\n const reason = this.options?.signal?.reason;\n const reasonText = reason === undefined ? \"\" : String(reason);\n\n return new AgentCancelledError(\"agent execution cancelled\", {\n cause: reason,\n cancelledAt: new Date().toISOString(),\n reason: reasonText,\n });\n }\n\n /**\n * Fire a single event through all three subscription tiers in order\n * — factory → instance → per-call — and mirror it into the\n * `StreamController` when streaming is active. A throwing user\n * handler must never crash the agent, so every dispatch is wrapped\n * in `safeCall`. Stream events are converted from the internal\n * `AgentEventMap` payload to the public `StreamEvent` shape because\n * some of them differ (e.g. the tool-called payload vs stream\n * event).\n */\n private emit<K extends keyof AgentEventMap>(\n event: K,\n payload: WithoutIdentity<AgentEventMap[K]>,\n ): void {\n // Inject run identity once, here, so every subscription tier and\n // the stream see it. `rootRunId === runId` for a standalone run;\n // nested propagation lands in a follow-up.\n const fullPayload = {\n ...payload,\n runId: this.runId,\n rootRunId: this.runId,\n } as AgentEventMap[K];\n\n this.logEvent(event, fullPayload);\n\n const factoryHandler = this.config.on?.[event] as AgentEventHandler<K> | undefined;\n\n if (factoryHandler) {\n safeCall(factoryHandler, fullPayload);\n }\n\n const bucket = this.instanceHandlers?.get(event);\n\n if (bucket) {\n for (const handler of bucket) {\n safeCall(handler as AgentEventHandler<K>, fullPayload);\n }\n }\n\n const perCallHandler = this.options?.on?.[event] as AgentEventHandler<K> | undefined;\n\n if (perCallHandler) {\n safeCall(perCallHandler, fullPayload);\n }\n\n if (this.streamController) {\n const body = this.toStreamEvent(event, fullPayload);\n\n if (body) {\n this.streamController.push({\n runId: this.runId,\n rootRunId: this.runId,\n ...body,\n });\n }\n }\n }\n\n /**\n * Emit a structured log line for a lifecycle event. The action\n * string mirrors the event name with the `agent.` prefix stripped\n * (`agent.trip.started` → `trip.started`) so log grep filters and\n * event handlers read the same vocabulary. Level mapping follows\n * the convention documented on `@warlock.js/logger`'s `Logger`.\n */\n private logEvent<K extends keyof AgentEventMap>(event: K, payload: AgentEventMap[K]): void {\n const agentName = this.config.name || this.config.model.name;\n logAgentEvent(\n this.logger,\n {\n module: `${LOG_MODULE}.${agentName}`,\n maxTrips: this.maxTrips,\n modelName: this.config.model.name,\n totalUsage: this.usage,\n totalDurationMs: performance.now() - this.start,\n trips: this.trips,\n toolCalls: this.toolCalls,\n },\n event,\n payload,\n );\n }\n\n private toStreamEvent<K extends keyof AgentEventMap>(\n event: K,\n payload: AgentEventMap[K],\n ): StreamEventBody | undefined {\n return agentEventToStreamEvent(event, payload);\n }\n\n /**\n * Invoke the `onUsage` hook (when configured) with a flat payload\n * carrying stable identity. Awaits the handler so async ledger\n * writes complete before the next trip starts; swallows any throw\n * so consumer bugs cannot crash the agent. Sync handlers wrapped\n * via `Promise.resolve()` so the await is safe in either case.\n */\n private async fireUsageHook(tripIndex: number, tripUsage: Usage): Promise<void> {\n const handler = this.config.onUsage;\n if (!handler) return;\n\n const event: UsageEvent = {\n runId: this.runId,\n tripIndex,\n model: {\n name: this.config.model.name,\n provider: this.config.model.provider,\n },\n usage: { ...tripUsage },\n timestamp: new Date().toISOString(),\n };\n\n try {\n await Promise.resolve(handler(event));\n } catch (err) {\n this.logger.warn(LOG_MODULE, \"onUsage.hook.error\", \"onUsage handler threw\", {\n runId: this.runId,\n tripIndex,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n /**\n * Invoke the `onComplete` hook (when configured) once at the end\n * of every run. Receives the full `AgentResult` plus pre-extracted\n * `runId` and `durationMs`. Same swallow-and-log error policy as\n * `fireUsageHook`.\n */\n private async fireCompleteHook(result: AgentResult<TOutput>): Promise<void> {\n const handler = this.config.onComplete;\n if (!handler) return;\n\n const event: CompleteEvent<TOutput> = {\n result,\n runId: this.runId,\n durationMs: performance.now() - this.start,\n };\n\n try {\n await Promise.resolve(handler(event));\n } catch (err) {\n this.logger.warn(LOG_MODULE, \"onComplete.hook.error\", \"onComplete handler threw\", {\n runId: this.runId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n}\n\n/**\n * Decide whether a guard-synthesized tool call duplicates a real one\n * the provider already streamed structurally. Match key is\n * `name + key-sorted JSON of input` so identical calls (regardless of\n * argument key order) collapse, but two legitimate calls to the same\n * tool with different inputs still both dispatch.\n */\nfunction isDuplicateToolCall(\n recovered: ModelToolCallRequest,\n realCalls: ReadonlyArray<ModelToolCallRequest>,\n): boolean {\n const recoveredKey = `${recovered.name}|${stableStringify(recovered.input)}`;\n\n for (const real of realCalls) {\n const realKey = `${real.name}|${stableStringify(real.input)}`;\n\n if (realKey === recoveredKey) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * `JSON.stringify` variant that sorts object keys at every nesting\n * level so structurally-equal inputs serialize to identical strings.\n * Used only for dedupe-key comparison; never surfaces to consumers.\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(value, (_key, val) => {\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n const source = val as Record<string, unknown>;\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(source).sort()) {\n sorted[key] = source[key];\n }\n\n return sorted;\n }\n\n return val;\n });\n}\n\n/**\n * Invoke a user-supplied event handler without letting exceptions\n * escape the agent. Thrown errors are swallowed — structured logging\n * attaches here in Phase 0.5 so operators still see the failure.\n */\nfunction safeCall<T>(handler: (payload: T) => void, payload: T): void {\n try {\n handler(payload);\n } catch {\n // Intentionally swallowed — user handlers never crash the agent.\n }\n}\n\n/**\n * Resolve a tool's `action` declaration into a plain string for\n * inclusion in `ToolEventMeta`. Static strings pass through;\n * function-shaped actions are invoked with the validated input.\n *\n * Defensive: if the user's callback throws, swallow and return\n * `undefined` rather than crashing the agent — UI strings are not\n * worth aborting an LLM dispatch over.\n */\nfunction resolveToolAction(\n tool: ToolContract<unknown, unknown>,\n input: unknown,\n): string | undefined {\n if (tool.action === undefined) return undefined;\n if (typeof tool.action === \"string\") return tool.action;\n try {\n return tool.action(input);\n } catch {\n return undefined;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { ToolConfig, ToolContext } from \"../contracts/tool.contract\";\nimport { AIError, SchemaValidationError, ToolExecutionError } from \"../errors\";\nimport { generateRunId } from \"../utils/generate-run-id\";\n\n/**\n * Degraded `ToolContext` supplied when no caller threads one through\n * (`tool.invoke(input)` standalone, batch scripts, tests). Per\n * decisions §35 — mutations on the empty bag are harmless no-ops;\n * production paths under a supervisor receive a real ctx with the\n * iteration's shared bag.\n */\nfunction defaultToolContext(): ToolContext {\n return { artifacts: {} };\n}\n\nconst EMPTY_USAGE: Usage = Object.freeze({ input: 0, output: 0, total: 0 });\n\n/**\n * Result returned by `ToolContract.invoke()`.\n *\n * **Canonical destructure:** `const { data, usage, report, error }` —\n * matches every other executable (`AgentResult`, `WorkflowResult`,\n * `SupervisorResult`) so parent agents can treat every tool dispatch\n * uniformly.\n *\n * **Shape.** `data` / `error` carry the outcome; `usage` and `report`\n * are always present. For leaf tools, `usage` is zero and `report`\n * is a framework-synthesized {@link BaseReport} (`type: \"tool\"`,\n * `children: []`, real timing) so parents never have to nil-check.\n * For composites wrapped via `asTool()`, `usage` and `report` mirror\n * the inner primitive's — the nested tree lives in `report.children`.\n *\n * @example\n * const result = await myTool.invoke({ city: \"Cairo\" });\n * if (result.error) console.error(result.error.message);\n * else console.log(result.data, result.report.duration);\n */\nexport type ToolInvokeResult<TOutput> = {\n /** Successfully-returned output. Undefined if execution or validation failed. */\n data?: TOutput;\n /** Typed AI error produced by validation or execute(), if any. */\n error?: AIError;\n /** Rolled-up usage (zero for leaf tools, populated for composites). */\n usage: Usage;\n /** Recursive execution report — `report.children` carries nested executables. */\n report: BaseReport;\n};\n\n/**\n * A `ToolConfig` augmented with a safe `invoke()` entry point for the agent runtime.\n *\n * @example\n * const wrapped: ToolContract<{ city: string }, { temp: number }> = tool(contract);\n * const result = await wrapped.invoke({ city: \"Cairo\" });\n */\nexport interface ToolContract<TInput = unknown, TOutput = unknown> extends ToolConfig<\n TInput,\n TOutput\n> {\n /**\n * Agent-runtime entry point. Validates raw input against the tool's schema,\n * calls execute(), catches errors, and reports duration.\n * Never throws — errors surface in the returned `error` field as\n * typed `AIError` subclasses.\n *\n * The optional second argument is a `ToolContext` (Phase 5 /\n * decisions §35) — when supplied, threaded into `execute(input, ctx)`\n * so tools can write system-only side data into `ctx.artifacts`.\n * Standalone callers may omit it; the framework supplies a\n * degraded `{ artifacts: {} }` so single-arg legacy handlers keep\n * working unchanged.\n *\n * @example\n * const result = await myTool.invoke(rawLLMArgs);\n * if (result.error) handleError(result.error);\n */\n invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>>;\n}\n\n/**\n * Wraps a raw `ToolConfig` and adds a safe `invoke()` method for the agent runtime.\n * The returned object preserves all original contract fields unchanged.\n *\n * Error categorization:\n * - Input schema rejects model args → `SchemaValidationError` (issues preserved).\n * - Schema's `validate()` itself throws → `SchemaValidationError` wrapping the cause.\n * - `execute()` throws → `ToolExecutionError` wrapping the cause.\n *\n * @example\n * const weatherTool = tool({\n * name: \"getWeather\",\n * description: \"Fetch current weather for a city\",\n * input: z.object({ city: z.string() }),\n * execute: async ({ city }) => ({ temp: 72 }),\n * });\n *\n * const result = await weatherTool.invoke({ city: \"Cairo\" });\n */\n/**\n * Internal factory for `asTool()` wrappers on composite primitives\n * (agent / workflow / supervisor). Unlike the public `tool()` factory\n * (which synthesizes a leaf `BaseReport` every time), this variant\n * lets the composite's own `ExecuteResult` flow through: the inner\n * primitive's `report` becomes the sole child of the outer tool-call\n * node, and the inner `usage` is surfaced so parents can roll it up.\n *\n * The caller supplies `execute()` returning `{ data, usage, report }`\n * from the composite's own `execute()` method. Validation failures\n * and thrown errors still produce a synthesized failed leaf report —\n * the inner-report propagation is strictly a success-path concern.\n *\n * Not exported from the package barrel — used by `agent.asTool()`,\n * `workflow.asTool()`, `supervisor.asTool()` only.\n */\nexport function compositeAsTool<TInput, TOutput>(contract: {\n name: string;\n description?: string;\n version?: string;\n meta?: ToolConfig[\"meta\"];\n input: StandardSchemaV1<TInput>;\n /** Runs the underlying composite and returns its full envelope. */\n execute: (input: TInput) => Promise<{\n data?: TOutput;\n error?: AIError;\n usage: Usage;\n report: BaseReport;\n }>;\n}): ToolContract<TInput, TOutput> {\n // The underlying `ToolConfig<TInput, TOutput>.execute` is typed as\n // `(input) => Promise<TOutput>`, but composite wrappers return an\n // envelope object instead. Surface a contract-shaped view that\n // extracts `.data` on demand for any code that still treats this\n // like a plain tool.\n const publicExecute = async (input: TInput): Promise<TOutput> => {\n const envelope = await contract.execute(input);\n if (envelope.error) throw envelope.error;\n return envelope.data as TOutput;\n };\n\n return {\n name: contract.name,\n description: contract.description ?? `Composite tool \"${contract.name}\".`,\n meta: contract.meta,\n input: contract.input,\n execute: publicExecute,\n\n async invoke(rawInput: unknown, _ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n // Composite tools (asTool-wrapped agent/workflow/supervisor) do\n // NOT relay the ctx into their inner execution — composites\n // have their own state/scope; an inner supervisor gets a fresh\n // artifacts bag. The parameter is accepted for signature parity\n // with `tool()` so callers can use both interchangeably.\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n\n const failLeaf = (error: AIError): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n return {\n error,\n usage: EMPTY_USAGE,\n report: {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n },\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n try {\n const schema = contract.input as StandardSchemaV1<TInput>;\n validationResult = await schema[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n );\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n return failLeaf(\n new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n );\n }\n\n try {\n const composite = await contract.execute(validationResult.value);\n // Surface the inner primitive's full envelope. The outer\n // ToolInvokeResult carries the composite's usage and report\n // verbatim; the agent runtime nests the report as a child of\n // the tool-dispatch node it records.\n return {\n data: composite.data,\n error: composite.error,\n usage: composite.usage,\n report: composite.report,\n };\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n );\n }\n },\n };\n}\n\nexport function tool<TInput, TOutput>(\n contract: ToolConfig<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n return {\n ...contract,\n\n async invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n const handlerCtx = ctx ?? defaultToolContext();\n\n const finish = (partial: { data?: TOutput; error?: AIError }): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n const status: BaseReport[\"status\"] = partial.error ? \"failed\" : \"completed\";\n const report: BaseReport = {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status,\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n };\n\n return {\n ...partial,\n usage: EMPTY_USAGE,\n report,\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n if (contract.input) {\n try {\n validationResult = await contract.input[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n });\n }\n } else {\n // `input` is optional on ToolConfig — this is a no-argument tool\n // (e.g. view_cart, checkout). With no schema there is nothing to\n // validate, so pass the raw model args straight to execute()\n // instead of dereferencing a missing schema's `~standard`.\n validationResult = { value: rawInput as TInput };\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n\n return finish({\n error: new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n });\n }\n\n try {\n const output = await contract.execute(validationResult.value, handlerCtx);\n return finish({ data: output });\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n });\n }\n },\n };\n}\n","import type {\n SupervisorAsToolOptions,\n SupervisorContract,\n} from \"../contracts/supervisor/supervisor.contract\";\nimport { SupervisorFailedError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"../tool/tool\";\n\n/**\n * Wrap a `SupervisorContract` as a `ToolContract` so an outer agent\n * can invoke it from its tool-call loop. Mirrors\n * `workflow.asTool()` / `agent.asTool()` — same composition pattern,\n * same error-normalization behavior.\n *\n * Behavior:\n * - The tool's `name` mirrors the supervisor's `name` unless the\n * caller overrides via `options.name`. Supervisors without a\n * meaningful name throw `SupervisorFailedError` — an outer agent\n * can't route to an anonymous tool.\n * - Tool `input` is the supplied schema; the validated value is\n * coerced to a string (via `String()` for non-string values, or\n * `JSON.stringify()` for objects) before being forwarded to\n * `supervisor.execute(input)`. Consumers whose inputs need\n * richer shaping should pre-format the string themselves.\n * - On `result.error`, the supervisor error is thrown so the tool\n * wrapper catches it and produces a `ToolExecutionError` with\n * `cause` set to the original typed supervisor error — the outer\n * agent sees one uniform error class regardless of which\n * primitive failed.\n *\n * **Usage caveat** (mirrors workflow-as-tool): nested usage is not\n * rolled into the outer agent's `result.usage` today — the\n * supervisor's tokens stay on the supervisor result. Sum manually\n * if you need a combined cost number until nested-usage\n * standardization lands.\n *\n * @example\n * const support = ai.supervisor({ ... });\n * const supportTool = support.asTool({\n * name: \"handle_support_ticket\",\n * description: \"Process a customer support ticket end-to-end.\",\n * inputSchema: z.object({ ticket: z.string() }),\n * });\n * const concierge = ai.agent({ model, tools: [supportTool] });\n */\nexport function asTool<TOutput, TToolInput>(\n supervisorInstance: SupervisorContract<TOutput>,\n options: SupervisorAsToolOptions<TToolInput>,\n): ToolContract<TToolInput, TOutput> {\n if (!supervisorInstance.name || typeof supervisorInstance.name !== \"string\") {\n throw new SupervisorFailedError(\n \"supervisor.asTool(): supervisor must have a `name` to be wrapped as a tool\",\n );\n }\n\n return compositeAsTool<TToolInput, TOutput>({\n name: options.name ?? supervisorInstance.name,\n description: options.description ?? `Invoke supervisor \"${supervisorInstance.name}\" as a tool.`,\n input: options.inputSchema,\n execute: async (input) => {\n const coerced = coerceInput(input);\n const result = await supervisorInstance.execute(coerced);\n\n if (result.error) {\n // Surface the typed supervisor error — the outer ToolContract\n // wraps it as a ToolExecutionError with `cause` preserved.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Coerce a tool-input value into the `string` shape supervisor\n * `execute()` expects. Strings pass through; everything else gets\n * JSON-stringified so supervisors invoked via tool wrappers receive a\n * predictable textual input regardless of how the outer agent shaped\n * its call.\n */\nfunction coerceInput(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value === undefined || value === null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","import type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type {\n SupervisorEventHandler,\n SupervisorEventHandlers,\n} from \"../contracts/supervisor/supervisor-config.type\";\n\ntype AnyHandler = SupervisorEventHandler<keyof SupervisorEventMap>;\n\n/**\n * Three-tier supervisor event emitter — factory (definition) → instance\n * → per-execution. Mirrors `WorkflowEmitter` structurally; the only\n * difference is the event map. All matching handlers fire in layer\n * order. Handler errors are swallowed so a listener bug can never\n * derail the run.\n *\n * @example\n * const emitter = new SupervisorEmitter(definition.on);\n * const unsubscribe = emitter.on(\"supervisor.completed\", (payload) => ...);\n * emitter.emit(\"supervisor.starting\", { runId, rootRunId, supervisorName, input }, perCallHandlers);\n */\nexport class SupervisorEmitter {\n private readonly factoryHandlers?: SupervisorEventHandlers;\n private readonly instanceHandlers = new Map<\n keyof SupervisorEventMap,\n Set<AnyHandler>\n >();\n\n public constructor(factoryHandlers?: SupervisorEventHandlers) {\n this.factoryHandlers = factoryHandlers;\n }\n\n public on<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): () => void {\n let bucket = this.instanceHandlers.get(event);\n\n if (!bucket) {\n bucket = new Set();\n this.instanceHandlers.set(event, bucket);\n }\n\n bucket.add(handler as AnyHandler);\n\n return () => this.off(event, handler);\n }\n\n public off<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): void {\n this.instanceHandlers.get(event)?.delete(handler as AnyHandler);\n }\n\n public emit<K extends keyof SupervisorEventMap>(\n event: K,\n payload: SupervisorEventMap[K],\n executionHandlers?: SupervisorEventHandlers,\n ): void {\n invoke(this.factoryHandlers?.[event], payload);\n\n const bucket = this.instanceHandlers.get(event);\n\n if (bucket) {\n for (const handler of bucket) {\n invoke(handler, payload);\n }\n }\n\n invoke(executionHandlers?.[event], payload);\n }\n}\n\nfunction invoke<K extends keyof SupervisorEventMap>(\n handler: ((payload: SupervisorEventMap[K]) => void) | undefined,\n payload: SupervisorEventMap[K],\n): void {\n if (typeof handler !== \"function\") {\n return;\n }\n\n try {\n handler(payload);\n } catch {\n // Listener bugs must not derail the supervisor.\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { EndSentinel } from \"../contracts/end.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { DispatchContext } from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n DispatchRawResult,\n IntentCallback,\n IntentEntry,\n IntentRunEntry,\n SupervisorIntentValue,\n} from \"../contracts/supervisor/intent-entry.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { SupervisorFailedError } from \"../errors\";\n\n/**\n * Normalized internal representation of one entry in a supervisor's\n * `intents` map — resolved at factory time from one of the accepted\n * value forms (bare agent / workflow / callback / object entry).\n *\n * Carrying the explicit `type` discriminator keeps downstream code\n * (execution, signature, router-prompt) from having to re-detect\n * shape on every dispatch. The discriminated union below replaces\n * the flat-shape used in Phase 3 so callbacks can carry their own\n * function reference + dispatch-context-shaped resolvers.\n *\n * Discriminator renamed `kind` → `type` (Q12) for codebase-wide\n * consistency — every other discriminated result/report shape uses\n * `type`.\n */\nexport type ResolvedIntentEntry =\n | ResolvedAgentEntry\n | ResolvedWorkflowEntry\n | ResolvedCallbackEntry;\n\n/**\n * Successor directive function type — the resolver-time projection of\n * `IntentEntry.next` / `IntentRunEntry.next`. Single source of truth\n * across the three resolved variants.\n */\nexport type IntentNext = (ctx: DispatchContext) => string | string[] | EndSentinel | undefined;\n\n/**\n * Resolver-time projection of `IntentEntry.history` /\n * `RouterEntry.history` / `AckEntry.history`. Custom slicer that\n * REPLACES the default `historyWindow.<role>` slice.\n */\nexport type EntryHistorySlicer = (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n\nexport type ResolvedAgentEntry = {\n intent: string;\n type: \"agent\";\n unit: AgentContract<unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n /**\n * Per-dispatch placeholder values for the agent's systemPrompt\n * template. Forwarded as `agent.execute(input, { placeholders })`.\n * Phase 3.4 (Stage 4b) — replaces the dropped `composeAgentInput`\n * mechanism for threading state into agents.\n */\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this intent's slice of supervisor state. Agent\n * output is strip-merged against it; only validated keys appear on\n * `IterationSnapshot.result[intent].output` AND merge into\n * supervisor `state`.\n */\n output?: StandardSchemaV1<unknown>;\n /**\n * Successor directive (Stage 4d / Q24). When present, runs after\n * this branch's slice merges into state to choose the next dispatch\n * (or terminate) without invoking the router.\n */\n next?: IntentNext;\n /**\n * Custom history slicer — replaces the default\n * `historyWindow.agents` slice when supplied. See `IntentEntry.history`.\n */\n history?: EntryHistorySlicer;\n /**\n * Phase 5 / decisions §34. `\"stream\"` runs the agent without\n * structured-output coercion and writes the assembled prose into\n * `state[streamTo]`; `\"structured\"` is the default. Resolved at\n * factory time — `undefined` here is treated as `\"structured\"`.\n */\n mode?: \"structured\" | \"stream\";\n /** State key the assembled stream-mode prose writes into. Set iff `mode === \"stream\"`. */\n streamTo?: string;\n};\n\nexport type ResolvedWorkflowEntry = {\n intent: string;\n type: \"workflow\";\n unit: WorkflowInstance<unknown, unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n history?: EntryHistorySlicer;\n};\n\nexport type ResolvedCallbackEntry = {\n intent: string;\n type: \"callback\";\n /**\n * The callback that actually runs at dispatch time. Always present\n * regardless of whether the user passed bare-function shorthand or\n * the `{ run, ... }` entry form.\n */\n callback: IntentCallback;\n /**\n * Description is required only when the supervisor uses a router.\n * Callback intents under a router are validated separately\n * (see {@link assertRouterDescriptions}); under deterministic\n * `route` mode this field is `undefined`.\n */\n description?: string;\n /**\n * Per-intent input resolver. Receives the upcoming\n * `DispatchContext` and returns the value forwarded as\n * `ctx.input` to the callback.\n */\n input?: (ctx: DispatchContext) => unknown;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this callback's slice of state. Without it, the\n * full return value shallow-merges; with it, return is strip-merged\n * to declared keys before merging.\n */\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n};\n\n/**\n * Validate and normalize the `intents` map into resolved entries.\n * Runs at factory time — throws `SupervisorFailedError` on the first\n * malformed entry so author-time bugs surface immediately rather\n * than mid-run.\n *\n * Validation rules:\n * - Every value must be an agent, a workflow, a callback function,\n * or an object entry with `agent` / `workflow` / `run`.\n * - Object entries with more than one of `{ agent, workflow, run }`\n * throw with code `SUPERVISOR_INTENT_MIXED_DISPATCH`.\n * - Agent / workflow / agent-shaped entries must resolve to a\n * non-empty description from the underlying unit or the entry's\n * `description` override. Bare callback shorthand has no\n * description source — that's enforced separately by\n * {@link assertRouterDescriptions} when a router is configured.\n */\nexport function resolveIntentEntries(\n rawIntents: Record<string, SupervisorIntentValue>,\n supervisorName: string,\n): Map<string, ResolvedIntentEntry> {\n const entries = Object.entries(rawIntents);\n\n if (entries.length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): \\`intents\\` must contain at least one entry`,\n { context: { authoring: true } },\n );\n }\n\n const resolved = new Map<string, ResolvedIntentEntry>();\n\n for (const [intent, value] of entries) {\n if (!intent || typeof intent !== \"string\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): every \\`intents\\` key must be a non-empty string`,\n { context: { authoring: true } },\n );\n }\n\n resolved.set(intent, resolveOne(intent, value, supervisorName));\n }\n\n return resolved;\n}\n\n/**\n * Construction-time guard: when the supervisor is configured with a\n * `router`, every intent must resolve to a non-empty description so\n * the router LLM has a signal for picking it. Bare callback\n * shorthand and `IntentRunEntry` without `description` fail this\n * check; agents and workflows whose underlying primitive lacks a\n * description fail too — same uniform error message.\n *\n * Deterministic `route` callers skip this check entirely.\n */\nexport function assertRouterDescriptions(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): void {\n if (!config.router) {\n return;\n }\n\n for (const [intent, entry] of entries) {\n const description = entry.type === \"callback\" ? entry.description : entry.description;\n\n if (description && description.trim().length > 0) {\n continue;\n }\n\n const fix =\n entry.type === \"callback\"\n ? \"upgrade the bare callback to `{ run, description }`\"\n : \"set `description` on the agent/workflow or via the `IntentEntry` `description` override\";\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): intents[\"${intent}\"] needs a description because a \\`router\\` is configured — ${fix}`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_DESCRIPTION_REQUIRED\",\n );\n }\n}\n\nfunction resolveOne(\n intent: string,\n value: SupervisorIntentValue,\n supervisorName: string,\n): ResolvedIntentEntry {\n // (c) Bare callback shorthand — typeof function. Highest priority\n // so a user passing `(ctx) => …` never accidentally matches the\n // object-shape branches below.\n if (typeof value === \"function\") {\n return {\n intent,\n type: \"callback\",\n callback: value as IntentCallback,\n description: undefined,\n };\n }\n\n if (!value || typeof value !== \"object\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] is not an agent, workflow, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n // Detect mixed-dispatch entries up front. Two of `{ agent, workflow,\n // run }` together is dev confusion, not a feature.\n assertSingleDispatchField(intent, value, supervisorName);\n\n // (d.run) Run-entry — `{ run, description?, input?, output? }`.\n if (\"run\" in value && typeof (value as IntentRunEntry).run === \"function\") {\n const entry = value as IntentRunEntry;\n\n return {\n intent,\n type: \"callback\",\n callback: entry.run,\n description: entry.description,\n input: entry.input,\n placeholders: entry.placeholders,\n output: entry.output,\n next: entry.next,\n };\n }\n\n // (d.agent / a / b) Agent-entry or bare unit. The existing\n // `IntentEntry` shape uses `agent: AgentContract | WorkflowInstance`\n // for both agent and workflow object entries; the resolver still\n // dispatches the underlying unit kind correctly.\n const entryForm = asAgentEntryForm(value);\n const unit = entryForm\n ? entryForm.agent\n : (value as AgentContract<unknown> | WorkflowInstance<unknown, unknown>);\n\n if (!isDispatchableUnit(unit)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] must be an AgentContract, WorkflowInstance, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n const detectedType = detectType(unit);\n const description = resolveAgentLikeDescription(intent, entryForm, unit, supervisorName);\n\n if (detectedType === \"workflow\") {\n if (entryForm?.mode === \"stream\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` on a workflow entry — stream mode is agent-only in v1. Wrap the workflow in an agent or remove the \\`mode\\` field.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_ON_WORKFLOW\",\n );\n }\n\n return {\n intent,\n type: \"workflow\",\n unit: unit as WorkflowInstance<unknown, unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n };\n }\n\n assertStreamModeShape(intent, entryForm, supervisorName);\n\n return {\n intent,\n type: \"agent\",\n unit: unit as AgentContract<unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n mode: entryForm?.mode,\n streamTo: entryForm?.streamTo,\n };\n}\n\n/**\n * Phase 5 / decisions §34 — enforce the two stream-mode invariants at\n * construction time:\n *\n * 1. `mode: \"stream\"` and per-intent `output` are mutually exclusive.\n * Stream agents declare their state contribution via `streamTo`,\n * not via a schema; allowing both would silently pick one and\n * surprise the author.\n * 2. `streamTo` is required when `mode === \"stream\"`. A stream agent\n * that doesn't write somewhere is a black box — fail loud at the\n * factory rather than at run-time when state validation surfaces a\n * missing key.\n */\nfunction assertStreamModeShape(\n intent: string,\n entryForm: IntentEntry | undefined,\n supervisorName: string,\n): void {\n if (!entryForm || entryForm.mode !== \"stream\") {\n return;\n }\n\n if (entryForm.output) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets both \\`mode: \"stream\"\\` and \\`output\\` — stream mode declares its slice via \\`streamTo\\`, not a schema. Drop one.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_AND_OUTPUT\",\n );\n }\n\n if (typeof entryForm.streamTo !== \"string\" || entryForm.streamTo.trim().length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` without a non-empty \\`streamTo\\` — a stream agent must name the state key its assembled prose writes into.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_TO_REQUIRED\",\n );\n }\n}\n\n/**\n * Reject entries that mix dispatch fields. `{ agent, run }` is a\n * common copy-paste bug; we surface it at construction with a clear\n * message rather than silently picking one based on resolution\n * order.\n */\nfunction assertSingleDispatchField(intent: string, value: object, supervisorName: string): void {\n const dispatchKeys = ([\"run\", \"agent\", \"workflow\"] as const).filter((key) => key in value);\n\n if (dispatchKeys.length > 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] has multiple dispatch fields (${dispatchKeys\n .map((key) => `\\`${key}\\``)\n .join(\n \", \",\n )}) — pick one. Two dispatch fields on the same entry is dev confusion, not a feature.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_MIXED_DISPATCH\",\n );\n }\n}\n\n/**\n * Coerce a `SupervisorIntentValue` into the agent-flavored\n * `IntentEntry` form when the caller passed the object form. Returns\n * `undefined` for bare shorthand. The shape check keys on the\n * presence of an `agent` property because both `AgentContract` and\n * `WorkflowInstance` have their own identifying fields\n * (`isAnonymous` for agents, `signature` for workflows) but neither\n * carries a top-level `agent`.\n */\nfunction asAgentEntryForm(value: object): IntentEntry | undefined {\n if (!(\"agent\" in value)) {\n return undefined;\n }\n\n const candidate = (value as { agent: unknown }).agent;\n\n if (!candidate || typeof candidate !== \"object\") {\n return undefined;\n }\n\n return value as IntentEntry;\n}\n\nfunction isDispatchableUnit(\n value: unknown,\n): value is AgentContract<unknown> | WorkflowInstance<unknown, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as { name?: unknown; execute?: unknown };\n\n return typeof candidate.name === \"string\" && typeof candidate.execute === \"function\";\n}\n\nfunction detectType(\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n): \"agent\" | \"workflow\" {\n // Workflows expose a structural `signature` field; agents don't.\n if (typeof (unit as WorkflowInstance<unknown, unknown>).signature === \"string\") {\n return \"workflow\";\n }\n\n return \"agent\";\n}\n\nfunction resolveAgentLikeDescription(\n intent: string,\n entryForm: IntentEntry | undefined,\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n supervisorName: string,\n): string {\n const entryOverride = entryForm?.description;\n\n if (entryOverride && entryOverride.trim().length > 0) {\n return entryOverride;\n }\n\n const unitDescription = (unit as { description?: unknown }).description;\n\n if (typeof unitDescription === \"string\" && unitDescription.trim().length > 0) {\n return unitDescription;\n }\n\n // Empty string sentinel — caller (assertRouterDescriptions) decides\n // whether a missing description is fatal. Under deterministic\n // `route` mode it isn't.\n return \"\";\n}\n\n/**\n * Type guard helper for downstream modules. Narrows a raw\n * `AgentResult | WorkflowResult` based on the resolved entry's kind,\n * so transformers and emitters can pull the right fields without\n * re-checking shape.\n */\nexport function isAgentResult(raw: DispatchRawResult): raw is AgentResult<unknown> {\n return raw.type === \"agent\";\n}\n\nexport function isWorkflowResult(raw: DispatchRawResult): raw is WorkflowResult<unknown> {\n return raw.type === \"workflow\";\n}\n","/**\n * Framework-global termination sentinel. Emitted by any primitive\n * whose control flow is routed through JSON-serializable strings —\n * supervisor (router agent's `next`, deterministic `route` callback),\n * future planner (plan steps), future orchestrator (session\n * directive), any future primitive that needs to say \"stop\" across a\n * wire that can't carry `null`.\n *\n * **Why one shared literal.** Consumers learn one word. Cross-\n * primitive pipes — a planner feeding a supervisor, a supervisor\n * nested as a tool inside an orchestrator — can pass the sentinel\n * through without translation.\n *\n * **Why this specific string.** Brand-prefixed (`__warlock:`) so it\n * can't collide with a realistic user-chosen intent / step / route\n * key (`\"end\"`, `\"done\"`, `\"stop\"` are all valid user keys).\n * Underscore-surrounded so it stands out in logs and snapshots.\n * JSON-safe so a router agent emits it verbatim.\n *\n * **Not used by every primitive.** Workflow's `nextStep` returns\n * `null` to end — a callback-level mechanism that predates this\n * sentinel. Workflows keep `null`; the sentinel is for primitives\n * whose \"end\" must survive a JSON boundary.\n *\n * @example\n * import { END } from \"@warlock.js/ai\";\n *\n * // Supervisor route callback\n * ai.supervisor({\n * intents: { writer, critic },\n * route: (ctx) => (ctx.iteration >= 5 ? END : \"writer\"),\n * });\n *\n * // Router agent output schema\n * const router = ai.agent({\n * model,\n * output: z.object({\n * next: z.union([z.string(), z.array(z.string()), z.literal(END)]),\n * }),\n * });\n */\nexport const END = \"__warlock:end__\" as const;\n\n/**\n * Value type of `END`. Exposed so consumers building Zod / Standard\n * Schema output schemas can write `z.literal(END)` without\n * hard-coding the string, and so generic helpers that accept \"the\n * end sentinel\" can type-narrow correctly.\n */\nexport type EndSentinel = typeof END;\n","import { SupervisorCancelledError } from \"../errors\";\n\n/**\n * Build a `SupervisorCancelledError` from an `AbortSignal`. Extracts a\n * human-readable reason from `signal.reason` whether it was a string,\n * an `Error`, or some other value. Used at between-iteration boundaries\n * and on any mid-iteration cancellation path.\n */\nexport function createCancelledError(\n signal: AbortSignal | undefined,\n): SupervisorCancelledError {\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 SupervisorCancelledError(\n `supervisor cancelled${reasonText ? `: ${reasonText}` : \"\"}`,\n { cancelledAt: new Date().toISOString(), reason: reasonText },\n );\n}\n","import { END } from \"../contracts/end.type\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type { ResolvedIntentEntry } from \"./entries\";\n\n/**\n * Build the per-turn user message the supervisor feeds to the router\n * agent. Carries everything the LLM needs to make a routing decision:\n *\n * - Available intents with descriptions (so the router knows what\n * to pick from).\n * - The reserved `END` sentinel value it can emit to terminate.\n * - Iteration counter + ceiling so the router can pace itself.\n * - Compact history of prior iterations (intent + short output clip).\n * - The supervisor's original input so the router stays anchored.\n *\n * Note the router's own `systemPrompt` is kept persistent across\n * turns — this function produces only the per-turn USER message.\n */\nexport function buildRouterContextMessage(params: {\n entries: Map<string, ResolvedIntentEntry>;\n iteration: number;\n maxIterations: number;\n iterations: IterationSnapshot[];\n input: SupervisorInput;\n /**\n * Per-execute state at the START of this iteration (post-merge of\n * the previous iteration). Rendered as a JSON snippet so the\n * router can pick the next intent based on what's already filled\n * in (Q14).\n */\n state?: Record<string, unknown>;\n /**\n * Reviewer feedback string from the previous iteration's evaluate\n * verdict. Rendered as its own section so the router weighs it\n * alongside the intent list (Q18).\n */\n feedback?: string;\n /**\n * Supervisor-level system prompt text, when configured. Surfaced at\n * the TOP of the router's per-turn user message so the router reads\n * team/domain context before the routing mechanics block. Skipped\n * when the supervisor didn't configure `systemPrompt`.\n */\n supervisorPrompt?: string;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`.\n * Surfaced as its own labeled section near the top of the router's\n * user message so routing decisions are objective-aware. Skipped\n * when no goal was configured.\n */\n goal?: string;\n}): string {\n const {\n entries,\n iteration,\n maxIterations,\n iterations,\n input,\n state,\n feedback,\n supervisorPrompt,\n goal,\n } = params;\n\n const intentLines = [...entries.values()].map(\n entry => `- ${entry.intent}: ${entry.description}`,\n );\n\n const historyLines =\n iterations.length === 0\n ? [\"(none yet)\"]\n : iterations.map(snapshot => formatHistoryLine(snapshot));\n\n const sections: string[] = [];\n\n if (supervisorPrompt) {\n sections.push(supervisorPrompt.trim(), \"\");\n }\n\n if (goal) {\n sections.push(\"Goal:\", goal.trim(), \"\");\n }\n\n sections.push(\n \"Available intents:\",\n ...intentLines,\n \"\",\n \"Reserved values:\",\n `- ${END} = terminate the run`,\n \"\",\n `Iteration: ${iteration + 1} / ${maxIterations}`,\n \"\",\n \"History:\",\n ...historyLines,\n );\n\n if (state && Object.keys(state).length > 0) {\n sections.push(\"\", \"Current state:\", safeStringify(state));\n }\n\n if (feedback) {\n sections.push(\"\", `Reviewer feedback from last iteration: ${feedback}`);\n }\n\n const renderedInput =\n typeof input === \"string\" ? input : safeStringify(input);\n\n sections.push(\"\", `Original input: ${renderedInput}`);\n\n return sections.join(\"\\n\");\n}\n\nfunction formatHistoryLine(snapshot: IterationSnapshot): string {\n const branches = Object.entries(snapshot.result).map(\n ([intent, branch]) => `${intent} → ${clip(branch.output)}`,\n );\n\n return `[${snapshot.iteration}] ${branches.join(\" | \")}`;\n}\n\nfunction clip(value: unknown, maxLength = 160): string {\n if (value === undefined || value === null) {\n return String(value);\n }\n\n const raw = typeof value === \"string\" ? value : safeStringify(value);\n\n if (raw.length <= maxLength) {\n return raw;\n }\n\n return `${raw.slice(0, maxLength - 1)}…`;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return `[unserializable: ${typeof value}]`;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END, type EndSentinel } from \"../contracts/end.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { Next } from \"../contracts/supervisor/next.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { RouterEntry } from \"../contracts/supervisor/router-entry.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport { AIError, SupervisorFailedError, SupervisorRoutingError } from \"../errors\";\nimport type { ResolvedIntentEntry } from \"./entries\";\nimport { buildRouterContextMessage } from \"./router-prompt\";\n\n/**\n * Outcome of one dispatch decision — what the iteration loop needs to\n * act on. `kind: \"end\"` signals termination; `kind: \"dispatch\"` carries\n * the resolved intents (always an array; single-agent dispatch has\n * length 1). `source` records which path made the call so the\n * iteration snapshot can surface it to debuggers.\n */\nexport type DispatchDecision =\n | {\n kind: \"end\";\n source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n raw: Next;\n reasoning?: string;\n durationMs: number;\n usage?: { input: number; output: number; total: number };\n /** Full router-agent report when this decision came from a router. */\n routerReport?: BaseReport;\n }\n | {\n kind: \"dispatch\";\n intents: string[];\n source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n raw: Next;\n reasoning?: string;\n durationMs: number;\n usage?: { input: number; output: number; total: number };\n /** Full router-agent report when this decision came from a router. */\n routerReport?: BaseReport;\n };\n\nexport type DecideParams = {\n config: SupervisorConfig<unknown>;\n entries: Map<string, ResolvedIntentEntry>;\n iteration: number;\n maxIterations: number;\n iterations: IterationSnapshot[];\n input: SupervisorInput;\n /**\n * Per-execute state accumulator at the start of this iteration.\n * Threaded into `RouteContext` for the route callback and\n * rendered into the router prompt so routing decisions can be\n * state-aware (Q14).\n */\n state: Record<string, unknown>;\n /**\n * Frozen request-scoped bag from the `execute({ context })` call —\n * surfaced on `RouteContext.context` for both `route` callbacks\n * and `RouterEntry.placeholders` / `RouterEntry.input` resolvers.\n */\n context: Readonly<Record<string, unknown>>;\n /**\n * Frozen prior-conversation history from `execute({ history })` —\n * surfaced on `RouteContext.history` and forwarded to the router\n * agent as `agent.execute(input, { history })` so router decisions\n * are conversation-aware.\n */\n history: ReadonlyArray<Message>;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`\n * (materialized to plain text at supervisor construction). Surfaced\n * on `RouteContext.goal` for `route` / `RouterEntry` resolvers, and\n * injected into the router agent's per-turn user message via\n * `buildRouterContextMessage`. `undefined` when no goal was set.\n */\n goal: string | undefined;\n evaluateFeedback?: RouteContext[\"evaluateFeedback\"];\n /**\n * Forensic record of the iter-0 classifier (Phase 7). Threaded into\n * `RouteContext.classifier` so route callbacks and router-agent\n * input composers can read the classification trail without\n * re-parsing state.\n */\n classifier?: RouteContext[\"classifier\"];\n signal?: AbortSignal;\n /**\n * Override for the very first iteration — when `initialAgent` is\n * set, the first turn skips `route`/`router` and dispatches the\n * named intent directly. `runIteration` passes `true` only on turn\n * 0 when the config has `initialAgent`.\n */\n useInitialAgent?: boolean;\n};\n\n/**\n * Unified dispatch decision entry — calls either the `route` callback\n * or the `router` agent based on the supervisor's configured mode and\n * normalizes the result into a `DispatchDecision`. Runtime validates\n * every routing value against the configured agent keys; unknown keys\n * surface as `SupervisorRoutingError`.\n */\nexport async function decide(params: DecideParams): Promise<DispatchDecision> {\n if (params.useInitialAgent && params.config.initialAgent) {\n const intent = params.config.initialAgent;\n validateKey(intent, params.entries);\n\n return {\n kind: \"dispatch\",\n intents: [intent],\n source: \"initialAgent\",\n raw: intent,\n durationMs: 0,\n };\n }\n\n if (params.config.route) {\n return decideViaCallback(params);\n }\n\n if (params.config.router) {\n return decideViaRouter(params);\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${params.config.name}\"): neither \\`route\\` nor \\`router\\` is configured — factory validation should have prevented this`,\n { context: { authoring: true } },\n );\n}\n\nasync function decideViaCallback(params: DecideParams): Promise<DispatchDecision> {\n const started = performance.now();\n const ctx: RouteContext = {\n iteration: params.iteration,\n input: params.input,\n state: params.state,\n iterations: params.iterations,\n feedback:\n typeof params.evaluateFeedback?.feedback === \"string\"\n ? params.evaluateFeedback.feedback\n : undefined,\n evaluateFeedback: params.evaluateFeedback,\n context: params.context,\n history: params.history,\n goal: params.goal,\n classifier: params.classifier,\n };\n\n let raw: Next;\n\n try {\n raw = await params.config.route!(ctx);\n } catch (thrown) {\n throw wrapRouteError(params.config.name, thrown);\n }\n\n const durationMs = performance.now() - started;\n\n return normalize(raw, params.entries, \"route\", durationMs);\n}\n\nasync function decideViaRouter(params: DecideParams): Promise<DispatchDecision> {\n const { agent, placeholders, inputOverride, historySlicer } = resolveRouterEntry(\n params.config.router!,\n );\n const started = performance.now();\n\n const routeCtx: RouteContext = {\n iteration: params.iteration,\n input: params.input,\n state: params.state,\n iterations: params.iterations,\n feedback:\n typeof params.evaluateFeedback?.feedback === \"string\"\n ? params.evaluateFeedback.feedback\n : undefined,\n evaluateFeedback: params.evaluateFeedback,\n context: params.context,\n history: params.history,\n goal: params.goal,\n };\n\n const userMessage =\n inputOverride?.(routeCtx) ??\n buildRouterContextMessage({\n entries: params.entries,\n iteration: params.iteration,\n maxIterations: params.maxIterations,\n iterations: params.iterations,\n input: params.input,\n state: params.state,\n feedback: routeCtx.feedback,\n supervisorPrompt: resolveSupervisorPromptText(params.config),\n goal: params.goal,\n });\n\n const resolvedPlaceholders = placeholders?.(routeCtx);\n\n // Inject the canonical router output schema so the supervisor gets\n // a predictable `{ next, reasoning? }` shape regardless of what the\n // user scripted on the router agent. Lets the router stay a plain\n // agent — no supervisor-specific config needed at construction.\n const routerHistory = resolveRouterHistory(\n historySlicer,\n routeCtx,\n params.history,\n params.config.historyWindow?.router,\n );\n\n const routerResult = await agent.execute(userMessage, {\n signal: params.signal,\n output: ROUTER_OUTPUT_SCHEMA as unknown as StandardSchemaV1<{\n next: Next;\n reasoning?: string;\n }>,\n ...(resolvedPlaceholders ? { placeholders: resolvedPlaceholders } : {}),\n ...(routerHistory.length > 0 ? { history: routerHistory } : {}),\n });\n\n const durationMs = performance.now() - started;\n\n if (routerResult.error) {\n throw routerResult.error instanceof AIError\n ? routerResult.error\n : new SupervisorFailedError(`router agent failed`, {\n cause: routerResult.error,\n });\n }\n\n const data = routerResult.data;\n\n if (!data || typeof data !== \"object\") {\n throw new SupervisorRoutingError(\n `router agent returned no structured \\`next\\` — did its output schema include { next, reasoning? }?`,\n { returned: data, availableKeys: [...params.entries.keys()] },\n );\n }\n\n const rawNext = (data as { next?: unknown }).next;\n const reasoning = (data as { reasoning?: unknown }).reasoning;\n\n if (rawNext === undefined) {\n throw new SupervisorRoutingError(`router agent output missing \\`next\\` field`, {\n returned: data,\n availableKeys: [...params.entries.keys()],\n });\n }\n\n const decision = normalize(rawNext as Next, params.entries, \"router\", durationMs);\n\n return {\n ...decision,\n reasoning: typeof reasoning === \"string\" ? reasoning : undefined,\n usage: routerResult.usage,\n routerReport: routerResult.report,\n };\n}\n\n/**\n * Normalize the `router` config field — accepts either a bare\n * `AgentContract` (shorthand) or a full `RouterEntry` — into a\n * uniform `{ agent, placeholders?, inputOverride? }` triple. Centralized\n * so the dispatch path doesn't branch on shape.\n */\nfunction resolveRouterEntry(router: AgentContract<unknown> | RouterEntry): {\n agent: AgentContract<unknown>;\n placeholders?: RouterEntry[\"placeholders\"];\n inputOverride?: RouterEntry[\"input\"];\n historySlicer?: RouterEntry[\"history\"];\n} {\n if (typeof (router as { execute?: unknown }).execute === \"function\") {\n return { agent: router as AgentContract<unknown> };\n }\n\n const entry = router as RouterEntry;\n\n return {\n agent: entry.agent,\n placeholders: entry.placeholders,\n inputOverride: entry.input,\n historySlicer: entry.history,\n };\n}\n\n/**\n * Resolve the supervisor's own `systemPrompt` (string or contract)\n * into plain text. Returns `undefined` when the supervisor didn't\n * configure one. The resolved text is surfaced in the per-turn\n * router user message so the router sees team/domain context without\n * disturbing the router agent's own factory-level system prompt —\n * functionally equivalent to prepending, without requiring an API\n * expansion on `AgentContract` to read the router's system prompt.\n */\nfunction resolveSupervisorPromptText(config: SupervisorConfig<unknown>): string | undefined {\n if (!config.systemPrompt) {\n return undefined;\n }\n\n return typeof config.systemPrompt === \"string\"\n ? config.systemPrompt\n : config.systemPrompt.resolve();\n}\n\n/**\n * Convert the raw routing value (callback return OR router agent\n * `next` field) into a canonical `DispatchDecision`, validating every\n * named intent against the supervisor's `intents` map.\n */\nfunction normalize(\n raw: Next,\n entries: Map<string, ResolvedIntentEntry>,\n source: \"route\" | \"router\",\n durationMs: number,\n): DispatchDecision {\n if (isEnd(raw)) {\n return { kind: \"end\", source, raw, durationMs };\n }\n\n if (typeof raw === \"string\") {\n validateKey(raw, entries);\n\n return {\n kind: \"dispatch\",\n intents: [raw],\n source,\n raw,\n durationMs,\n };\n }\n\n if (Array.isArray(raw)) {\n if (raw.length === 0) {\n throw new SupervisorRoutingError(\n `router returned an empty array — must be a non-empty list of agent intents`,\n { returned: raw, availableKeys: [...entries.keys()] },\n );\n }\n\n for (const intent of raw) {\n if (typeof intent !== \"string\") {\n throw new SupervisorRoutingError(`router returned a non-string inside its fan-out array`, {\n returned: raw,\n availableKeys: [...entries.keys()],\n });\n }\n\n validateKey(intent, entries);\n }\n\n return {\n kind: \"dispatch\",\n intents: raw,\n source,\n raw,\n durationMs,\n };\n }\n\n throw new SupervisorRoutingError(\n `router returned an unsupported value — expected a string, string[], or END`,\n { returned: raw, availableKeys: [...entries.keys()] },\n );\n}\n\nfunction validateKey(intent: string, entries: Map<string, ResolvedIntentEntry>): void {\n if (!entries.has(intent)) {\n throw new SupervisorRoutingError(`router returned unknown agent key \"${intent}\"`, {\n returned: intent,\n availableKeys: [...entries.keys()],\n });\n }\n}\n\nfunction isEnd(value: unknown): value is EndSentinel {\n return value === END;\n}\n\n/**\n * Resolve the history slice forwarded to the router agent. Mirrors\n * `SupervisorExecution.resolveHistoryFor(\"router\", ...)` — duplicated\n * here so the standalone `decide()` function stays callable without\n * threading the execution instance through. Precedence is identical:\n * entry slicer > `historyWindow.router` > full history.\n */\nfunction resolveRouterHistory(\n slicer: RouterEntry[\"history\"] | undefined,\n routeCtx: RouteContext,\n full: ReadonlyArray<Message>,\n window: number | undefined,\n): Message[] {\n if (slicer) {\n const sliced = slicer(routeCtx);\n return sliced ? [...sliced] : [];\n }\n\n if (window === undefined || window < 0) {\n return [...full];\n }\n\n if (window === 0) {\n return [];\n }\n\n return full.slice(-window);\n}\n\n/**\n * JSON Schema form of the canonical router output shape. Surfaced via\n * the Standard JSON Schema V1 extension path (`[\"~standard\"].jsonSchema.input`)\n * so `extractJsonSchema()` can pull it for native structured-output\n * enforcement on capable providers (OpenAI strict json_schema mode,\n * Anthropic tool-use shape, etc.). Without this, the model is told to\n * emit JSON only via soft system-prompt instruction — fragile, and\n * skipped entirely when the model advertises `structuredOutput: true`.\n *\n * `next` is intentionally `string` (not a union with arrays) because\n * OpenAI strict mode rejects polymorphic root types — fan-out via\n * `string[]` is still validated at the framework layer; the model\n * just emits a single intent name (or the END sentinel) and the\n * supervisor's own normalizer handles the rest.\n */\nconst ROUTER_OUTPUT_JSON_SCHEMA = {\n type: \"object\",\n properties: {\n next: {\n type: \"string\",\n description: \"Name of the agent to dispatch next, or the END sentinel to terminate the run.\",\n },\n reasoning: {\n type: \"string\",\n description: \"One-sentence justification for the routing choice.\",\n },\n },\n required: [\"next\", \"reasoning\"],\n additionalProperties: false,\n};\n\n/**\n * Canonical Standard Schema the supervisor injects when calling the\n * router agent. Pragmatic — accepts any `next` shape the router can\n * plausibly emit (`string`, `string[]`, or the `END` literal) plus an\n * optional `reasoning` field. Rejects anything else so a broken\n * router output surfaces cleanly via the agent's own validation path.\n *\n * Exposes `[\"~standard\"].jsonSchema.input()` (Standard JSON Schema V1)\n * so capable providers enforce the shape natively rather than relying\n * on prompt-side coaching.\n */\nconst ROUTER_OUTPUT_SCHEMA: StandardSchemaV1<{\n next: Next;\n reasoning?: string;\n}> = {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-supervisor\",\n jsonSchema: {\n input: () => ROUTER_OUTPUT_JSON_SCHEMA,\n },\n validate(value: unknown): StandardSchemaV1.Result<{ next: Next; reasoning?: string }> {\n if (!value || typeof value !== \"object\") {\n return { issues: [{ message: \"router output must be an object\" }] };\n }\n\n const record = value as { next?: unknown; reasoning?: unknown };\n const rawNext = record.next;\n\n const nextIsValid =\n typeof rawNext === \"string\" ||\n (Array.isArray(rawNext) && rawNext.every((element) => typeof element === \"string\"));\n\n if (!nextIsValid) {\n return {\n issues: [\n {\n message: \"router output `next` must be a string, string[], or the END sentinel\",\n },\n ],\n };\n }\n\n const reasoning = typeof record.reasoning === \"string\" ? record.reasoning : undefined;\n\n return {\n value: { next: rawNext as Next, reasoning },\n };\n },\n } as StandardSchemaV1<{ next: Next; reasoning?: string }>[\"~standard\"] & {\n jsonSchema: { input: () => Record<string, unknown> };\n },\n};\n\nfunction wrapRouteError(supervisorName: string, thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new SupervisorFailedError(\n `\\`route\\` callback threw in supervisor \"${supervisorName}\": ${message}`,\n { cause: thrown },\n );\n}\n","import { resolveDefaultStore } from \"../config\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorResumeOptions } from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type {\n SupervisorSnapshot,\n SupervisorSnapshotStatus,\n} from \"../contracts/supervisor/supervisor-snapshot.type\";\nimport { SupervisorDriftError, SupervisorFailedError } from \"../errors\";\n\n/**\n * Resolve the effective snapshot store: the supervisor's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultStore })`.\n */\nfunction resolveSnapshotStore(config: SupervisorConfig<unknown>) {\n return config.snapshotStore ?? resolveDefaultStore();\n}\n\nexport type PersistParams = {\n config: SupervisorConfig<unknown>;\n signature: string;\n runId: string;\n input: SupervisorInput;\n startedAt: string;\n iteration: number;\n snapshots: IterationSnapshot[];\n status: SupervisorSnapshotStatus;\n};\n\nexport type PersistOutcome = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Write the current run state to the resolved snapshot store. No-op\n * (ok) when neither the supervisor's `snapshotStore` nor the global\n * `defaultStore` is configured. Failures are returned as\n * `{ ok: false }` rather than thrown so the engine can surface them\n * via events/logs without aborting the run — callers decide whether\n * a failed checkpoint is fatal.\n */\nexport async function persistSupervisorSnapshot(\n params: PersistParams,\n): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.config);\n\n if (!store) {\n return { ok: true };\n }\n\n const snapshot: SupervisorSnapshot = {\n runId: params.runId,\n supervisorName: params.config.name,\n signature: params.signature,\n input: params.input,\n iteration: params.iteration,\n snapshots: params.snapshots,\n status: params.status,\n startedAt: params.startedAt,\n savedAt: new Date().toISOString(),\n };\n\n try {\n await store.set(snapshotKey(params.runId), snapshot);\n\n return { ok: true };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * Load a persisted snapshot for `resume()` and run the drift check.\n * Throws `SupervisorFailedError` when no store is configured or when\n * the run is missing; throws `SupervisorDriftError` when the stored\n * signature doesn't match the current definition (unless `force` is\n * set).\n */\nexport async function loadSnapshotForResume(params: {\n config: SupervisorConfig<unknown>;\n signature: string;\n runId: string;\n options?: SupervisorResumeOptions;\n}): Promise<SupervisorSnapshot> {\n const store = resolveSnapshotStore(params.config);\n\n if (!store) {\n throw new SupervisorFailedError(\n `supervisor \"${params.config.name}\" has no store configured — set \\`snapshotStore\\` on the config or call \\`ai.config({ defaultStore })\\` at boot before calling resume()`,\n { context: { runId: params.runId } },\n );\n }\n\n const snapshot =\n (await store.get<SupervisorSnapshot>(snapshotKey(params.runId))) ?? null;\n\n if (!snapshot) {\n throw new SupervisorFailedError(\n `supervisor \"${params.config.name}\": no snapshot for runId \"${params.runId}\"`,\n { context: { runId: params.runId } },\n );\n }\n\n if (!params.options?.force && snapshot.signature !== params.signature) {\n throw new SupervisorDriftError(\n `supervisor \"${params.config.name}\" signature drift on resume`,\n {\n savedSignature: snapshot.signature,\n currentSignature: params.signature,\n runId: params.runId,\n },\n );\n }\n\n return snapshot;\n}\n\n/**\n * Canonical key shape used in the KVStore. Prefixed so supervisor\n * snapshots don't collide with workflow / session snapshots in a\n * shared store.\n */\nexport function snapshotKey(runId: string): string {\n return `supervisor:${runId}`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END } from \"../contracts/end.type\";\nimport type { EventIdentity, WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type {\n SupervisorReport,\n SupervisorResult,\n SupervisorTerminatedBy,\n} from \"../contracts/result/supervisor-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type {\n ClassifierConfig,\n ClassifierContext,\n ClassifierOutput,\n ClassifierRefineContext,\n ClassifierRefineResult,\n ClassifierSnapshot,\n} from \"../contracts/supervisor/classifier-context.type\";\nimport type {\n DispatchContext,\n StreamableExecutable,\n SupervisableExecutable,\n SupervisableExecuteOptions,\n SupervisableResult,\n} from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n EvaluateBranchResult,\n EvaluateContext,\n EvaluateResult,\n} from \"../contracts/supervisor/evaluate-context.type\";\nimport type {\n AckSnapshot,\n AgentBranchSnapshot,\n IterationSnapshot,\n} from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorExecuteOptions } from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type {\n SupervisorSnapshot,\n SupervisorSnapshotStatus,\n} from \"../contracts/supervisor/supervisor-snapshot.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport {\n AIError,\n MaxIterationsError,\n SchemaValidationError,\n SupervisorCancelledError,\n SupervisorFailedError,\n} from \"../errors\";\nimport { stampReportLineage } from \"../utils\";\nimport { createCancelledError } from \"./cancellation\";\nimport { decide, type DispatchDecision } from \"./decide\";\nimport type { SupervisorEmitter } from \"./emitter\";\nimport type { ResolvedCallbackEntry, ResolvedIntentEntry } from \"./entries\";\nimport { isAgentResult, isWorkflowResult } from \"./entries\";\nimport { persistSupervisorSnapshot } from \"./snapshot\";\nimport type { SupervisorStreamController, SupervisorStreamEvent } from \"./supervisor-stream\";\n\nconst DEFAULT_MAX_ITERATIONS = 10;\nconst LOG_MODULE_BASE = \"ai.supervisor\";\n\nexport type SupervisorExecutionParams<TOutput> = {\n config: SupervisorConfig<TOutput>;\n entries: Map<string, ResolvedIntentEntry>;\n signature: string;\n emitter: SupervisorEmitter;\n input: SupervisorInput;\n runId: string;\n options?: SupervisorExecuteOptions;\n streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n resumeFrom?: SupervisorSnapshot;\n};\n\n/**\n * Per-call driver that owns the full lifecycle of one supervisor run.\n *\n * **Role.** Short-lived state container and phase orchestrator —\n * mirrors `agent/Execution` and `workflow/runWorkflow`, one level up.\n *\n * **Responsibility.**\n * - Owns: the iteration loop, per-iteration dispatch (single or\n * fan-out), evaluate scheduling, usage aggregation across router +\n * every branch + evaluate, snapshot collection, event emission\n * through all three tiers, KV-store checkpointing, final result\n * assembly (state validation against the output schema → typed data).\n * - Does NOT own: how child agents produce responses (delegated via\n * `agent.execute` / `workflow.execute`), the routing decision\n * itself (delegated to `decide.ts`), snapshot persistence mechanics\n * (delegated to `snapshot.ts`), the stream queue plumbing\n * (delegated to `supervisor-stream.ts`).\n *\n * `execute()` never throws — every unexpected failure funnels into\n * `this.error` and is returned on `result.error` with an appropriate\n * `SupervisorFailedError` / `MaxIterationsError` / `SupervisorRoutingError`\n * / `SupervisorCancelledError`.\n *\n * @example\n * // Inside supervisor.execute() — never constructed by user code directly:\n * return new SupervisorExecution(params).run();\n */\nexport class SupervisorExecution<TOutput> {\n private readonly config: SupervisorConfig<TOutput>;\n private readonly entries: Map<string, ResolvedIntentEntry>;\n private readonly signature: string;\n private readonly emitter: SupervisorEmitter;\n private readonly input: SupervisorInput;\n private readonly runId: string;\n private readonly options?: SupervisorExecuteOptions;\n private readonly streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n private readonly resumeFrom?: SupervisorSnapshot;\n\n private readonly maxIterations: number;\n private readonly logger: Logger = log;\n private readonly logModule: string;\n\n private readonly snapshots: IterationSnapshot[] = [];\n private readonly childReports: BaseReport[] = [];\n private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n\n private readonly startedAtIso: string;\n private readonly startPerf = performance.now();\n\n private iteration = 0;\n private carriedFeedback?: EvaluateResult;\n /**\n * Per-intent `next` directive (Q24 / Stage 4d) collected at the\n * end of an iteration after evaluate hasn't already steered. When\n * set, `decideDispatch` consumes it on the next iteration's start —\n * skipping the router entirely. Cleared after consumption.\n *\n * Only the dispatch variant is stored; an `END` collection\n * terminates the iteration loop directly inside `runIteration`.\n */\n private carriedNextDispatch?: { intents: string[] };\n private terminatedBy: SupervisorTerminatedBy = \"error\";\n private status: SupervisorReport[\"status\"] = \"failed\";\n private cancelledAtIso?: string;\n private error?: AIError;\n private data?: TOutput;\n private lastDispatchIntents: string[] = [];\n /**\n * Per-execute typed accumulator. Initialized from `config.state`\n * (default `{}`) at construction; rehydrated from the last\n * snapshot's `state` on resume; mutated in-place as each iteration's\n * intents strip-merge their outputs into it.\n */\n private state: Record<string, unknown> = {};\n /**\n * Per-iteration artifacts bag (Phase 5 / decisions §35). Tools\n * dispatched within an iteration mutate `ctx.artifacts` — which\n * points at this object. After the iteration's branches settle and\n * their slices merge into state, this bag validates against\n * `config.artifactsSchema` (if set) and merges via\n * `config.finalizeArtifacts` or auto-spread, then resets to `{}`\n * for the next iteration. The reset is crucial — long runs and\n * orchestrator sessions never accumulate raw artifacts here.\n */\n private currentArtifacts: Record<string, unknown> = {};\n /**\n * Frozen copy of the iteration's `currentArtifacts` bag captured at\n * merge time — BEFORE `finalizeArtifacts` (or auto-spread) reshaped\n * it into state (Phase 8 / decisions §38). Surfaced on the iteration\n * snapshot's `artifacts` field for forensic / telemetry consumers\n * that want the raw tool contributions.\n *\n * Reset to `{}` at the start of every iteration so a snapshot built\n * for an iteration whose tools wrote nothing carries an empty bag,\n * not a stale carry-over.\n */\n private capturedIterationArtifacts: Readonly<Record<string, unknown>> = Object.freeze({});\n /**\n * Classifier (Phase 7 / decisions §37) forensic record. Set on iter\n * 0 when `SupervisorConfig.classifier` is configured AND the run\n * started fresh (resumes don't re-fire classifier — same as ack).\n * Surfaced on `SupervisorReport.classifier` and threaded into\n * `ctx.classifier` on RouteContext / DispatchContext /\n * EvaluateContext from iter 0 onward.\n */\n private classifierSnapshot?: ClassifierSnapshot;\n /**\n * Iter-0 dispatch decision pre-computed by the classifier (Phase 7).\n * When set, `decideDispatch` short-circuits and uses this directly\n * with `source: \"classifier\"`. Cleared after consumption.\n */\n private carriedClassifierDispatch?: { intent: string };\n /** Set true by classifier refine returning END to halt before any dispatch. */\n private classifierHalted = false;\n /**\n * Receptionist forensic record. Set when an `ackAgent` was\n * configured AND the run started fresh (resumes don't re-fire ack).\n * Surfaced on `SupervisorReport.ack`.\n */\n private ackSnapshot?: AckSnapshot;\n /**\n * Read-only request-scoped context surfaced on every `ctx.context`.\n * Shallow-copied + frozen at construction so callbacks see a stable\n * snapshot of the caller's bag and can't mutate the original.\n * Always present — defaults to a frozen `{}` when no context was\n * passed. NOT persisted in snapshots.\n */\n private readonly context: Readonly<Record<string, unknown>>;\n /**\n * Prior conversation messages threaded through every callback context\n * (`ctx.history`) and forwarded verbatim to dispatched agents (and the\n * receptionist `ack` agent) as `agent.execute(input, { history })`.\n * Frozen reference so callbacks see a stable view; not deep-cloned —\n * conversation messages are treated as immutable by convention. NOT\n * persisted in snapshots (re-supply on `resume()`).\n */\n private readonly history: ReadonlyArray<Message>;\n /**\n * Resolved natural-language objective from `SupervisorConfig.goal`.\n * Materialized to plain text at construction (string passes through;\n * `SystemPromptContract` is `.resolve()`-d). `undefined` when the\n * supervisor was configured without a goal.\n */\n private readonly goal: string | undefined;\n\n public constructor(params: SupervisorExecutionParams<TOutput>) {\n this.config = params.config;\n this.entries = params.entries;\n this.signature = params.signature;\n this.emitter = params.emitter;\n this.input = params.input;\n this.runId = params.runId;\n this.options = params.options;\n this.streamController = params.streamController;\n this.resumeFrom = params.resumeFrom;\n\n this.maxIterations = params.config.maxIterations ?? DEFAULT_MAX_ITERATIONS;\n this.logModule = `${LOG_MODULE_BASE}.${params.config.name}`;\n\n // Shallow-copy + freeze the caller's context. Shallow only —\n // freezing deeply would break valid use cases (mutable DB\n // clients, abort controllers) without delivering meaningful\n // safety beyond what TS `Readonly` already enforces.\n this.context = Object.freeze({ ...(params.options?.context ?? {}) });\n // Freeze the array reference so callbacks can't mutate the slot\n // (`history.push(...)`); messages themselves are passed by reference\n // — supervisors trust the agent layer's read-only convention.\n // Precedence: per-call `options.history` (most explicit) overrides\n // factory-level `config.history` (default for callers who don't\n // supply per-call history). Final fallback is an empty array.\n this.history = Object.freeze([...(params.options?.history ?? params.config.history ?? [])]);\n\n // Resolve `goal` to plain text once, at construction. `string`\n // passes through; `SystemPromptContract` is `.resolve()`-d (it owns\n // its own placeholder substitution). `undefined` when no goal was\n // configured — every `ctx.goal` consumer must guard for absence.\n if (typeof params.config.goal === \"string\") {\n this.goal = params.config.goal;\n } else if (params.config.goal) {\n this.goal = params.config.goal.resolve();\n } else {\n this.goal = undefined;\n }\n\n if (params.resumeFrom) {\n this.snapshots.push(...params.resumeFrom.snapshots);\n this.iteration = params.resumeFrom.iteration + 1;\n this.startedAtIso = params.resumeFrom.startedAt;\n // Resume rehydrates state from the last persisted iteration —\n // every iteration's snapshot carries the post-merge state, so\n // the resume point's state is the last snapshot's state.\n const lastSnapshot = params.resumeFrom.snapshots[params.resumeFrom.snapshots.length - 1];\n this.state = {\n ...(lastSnapshot?.state ??\n (params.config.state as Record<string, unknown> | undefined) ??\n {}),\n };\n } else {\n this.startedAtIso = new Date().toISOString();\n this.state = {\n ...((params.config.state as Record<string, unknown> | undefined) ?? {}),\n };\n }\n }\n\n /**\n * Resolve the history slice forwarded to a child execution (router /\n * dispatched agent / ack). Precedence:\n *\n * 1. Per-entry `history` callback — full override; whatever it\n * returns goes through (after defensive copy).\n * 2. `SupervisorConfig.historyWindow.<role>` — last-N slice of the\n * caller-supplied history.\n * 3. Default — full history for `router`/`agents`, empty for `ack`\n * (receptionists rarely benefit from scroll-back).\n *\n * Always returns a fresh `Message[]` (the agent layer\n * mutates by reference internally, e.g. via `messages.push(...)`).\n */\n private resolveHistoryFor(\n role: \"router\" | \"agents\" | \"ack\",\n routeContext: RouteContext,\n entrySlicer?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>,\n ): Message[] {\n if (entrySlicer) {\n const sliced = entrySlicer(routeContext);\n return sliced ? [...sliced] : [];\n }\n\n const window = this.config.historyWindow?.[role];\n\n if (role === \"ack\") {\n // Default for ack is empty — receptionists rarely need history.\n // Override is opt-in via `historyWindow.ack: N`.\n if (window === undefined || window <= 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n if (window === undefined || window < 0) {\n return [...this.history];\n }\n\n if (window === 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n /**\n * Apply only the global `historyWindow.agents` slice — used by the\n * recursive `ctx.intents.X.execute()` re-entry path where no\n * `RouteContext` is available to feed the per-entry slicer.\n */\n private applyAgentsWindow(): Message[] {\n const window = this.config.historyWindow?.agents;\n\n if (window === undefined || window < 0) {\n return [...this.history];\n }\n\n if (window === 0) {\n return [];\n }\n\n return this.history.slice(-window);\n }\n\n /**\n * Entry point. Drives the iteration loop, finalizes the result, and\n * emits terminal events. Returns the uniform\n * `{ data, report, usage, error }` shape and closes the stream if\n * one was attached. Never throws.\n */\n public async run(): Promise<SupervisorResult<TOutput>> {\n this.emit(\"supervisor.starting\", {\n supervisorName: this.config.name,\n input: this.input,\n });\n\n this.logger.info(this.logModule, \"starting\", \"supervisor starting\", {\n runId: this.runId,\n maxIterations: this.maxIterations,\n });\n\n try {\n await this.runIterationLoop();\n } catch (thrown) {\n this.error = toAIError(thrown);\n this.status = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"failed\";\n this.terminatedBy = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"error\";\n\n if (this.error instanceof SupervisorCancelledError) {\n this.cancelledAtIso = this.error.cancelledAt;\n }\n\n if (this.error instanceof MaxIterationsError) {\n this.status = \"max-iterations\";\n this.terminatedBy = \"max-iterations\";\n }\n }\n\n const result = await this.finalize();\n\n if (result.error) {\n if (this.status === \"cancelled\") {\n this.emit(\"supervisor.cancelled\", {\n cancelledAt: this.cancelledAtIso ?? new Date().toISOString(),\n reason: (result.error as SupervisorCancelledError).reason,\n });\n } else {\n this.emit(\"supervisor.error\", { error: result.error });\n }\n }\n\n this.emit(\"supervisor.completed\", { result });\n\n this.streamController?.end(result);\n\n this.logger.info(this.logModule, \"completed\", \"supervisor completed\", {\n runId: this.runId,\n status: this.status,\n iterations: this.snapshots.length,\n duration: performance.now() - this.startPerf,\n });\n\n return result;\n }\n\n /**\n * Drive the iteration loop until a terminal condition fires:\n * `END` / `satisfied:true` / `maxIterations` / signal abort /\n * routing error. Between-iteration cancellation is guaranteed —\n * the signal is checked before every iteration starts.\n */\n private async runIterationLoop(): Promise<void> {\n while (this.iteration < this.maxIterations) {\n this.throwIfCancelled();\n\n const continued = await this.runIteration();\n\n if (!continued) {\n return;\n }\n\n this.iteration += 1;\n }\n\n throw new MaxIterationsError(\n `supervisor \"${this.config.name}\" exceeded maxIterations=${this.maxIterations}`,\n { maxIterations: this.maxIterations },\n );\n }\n\n /**\n * Run one iteration end-to-end: decide → dispatch → evaluate →\n * snapshot. Returns `true` when the loop should continue to the\n * next iteration, `false` when this iteration terminated the run\n * (success or satisfied-verdict). Failures throw — the loop's\n * outer catch converts them into typed errors on the result.\n */\n private async runIteration(): Promise<boolean> {\n const iterationStartedAt = new Date();\n const iterationStart = performance.now();\n const iterationUsage: Usage = { input: 0, output: 0, total: 0 };\n\n // Phase 8 / decisions §38 — reset the captured-artifacts forensic\n // surface at iteration start so a snapshot built for an iteration\n // whose tools wrote nothing carries an empty bag, not a stale\n // carry-over from the prior iteration. `mergeArtifactsIntoState`\n // refreshes this with the live bag (frozen) before merge.\n this.capturedIterationArtifacts = Object.freeze({});\n\n this.emit(\"supervisor.iteration.starting\", { iteration: this.iteration });\n\n // Kick off the receptionist (`ack`) in parallel with phase A's\n // dispatch decision — fires on iter 0 only when the run is fresh\n // (resumes don't re-emit; user already saw the original ack). The\n // promise is NOT awaited inline — `settleAck` probes it\n // non-blockingly later so a slow ack never extends total wall-\n // clock time. If ack hasn't settled by the probe point, its slice\n // is abandoned with a warning + error on the report.\n const ackPromise =\n this.iteration === 0 && !this.resumeFrom && this.config.ack ? this.runAck() : undefined;\n\n // Phase 7 / decisions §37 — classifier prelude. Runs once on iter 0\n // for fresh runs only (resumes inherit the prior classifier output\n // via state + report.classifier). Awaited inline because its\n // output drives the iter-0 dispatch decision; ack remains\n // non-blocking parallel by design.\n if (this.iteration === 0 && !this.resumeFrom && this.config.classifier) {\n await this.runClassifier();\n\n if (this.classifierHalted) {\n // Refine returned END (or classifier-alone mode interpreted\n // an END signal). Settle ack, mark terminated, capture a\n // synthetic decision snapshot, and exit the loop. State may\n // already carry refine's slice — do not clobber.\n await this.settleAck(ackPromise, iterationUsage);\n this.terminatedBy = \"classifier\";\n this.status = \"completed\";\n\n await this.recordTerminalDecisionSnapshot(\n {\n kind: \"end\",\n source: \"classifier\",\n raw: END,\n durationMs: 0,\n },\n iterationStartedAt,\n iterationStart,\n iterationUsage,\n );\n\n return false;\n }\n }\n\n const decision = await this.decideDispatch();\n\n this.aggregateUsage(iterationUsage, decision.usage);\n\n if (decision.kind === \"end\") {\n await this.settleAck(ackPromise, iterationUsage);\n this.terminatedBy = decision.source === \"route\" ? \"route\" : \"router\";\n this.status = \"completed\";\n\n await this.recordTerminalDecisionSnapshot(\n decision,\n iterationStartedAt,\n iterationStart,\n iterationUsage,\n );\n\n return false;\n }\n\n const branchSnapshots = await this.dispatchBranches(decision);\n\n for (const snapshot of branchSnapshots) {\n this.aggregateUsage(iterationUsage, snapshot.usage);\n }\n\n // Settle ack (if kicked off) before phase C merge. Probe is\n // non-blocking — `setImmediate` yields one macrotask cycle so an\n // already-resolved ack wins via microtask priority; otherwise the\n // probe returns NOT_READY and ack is abandoned (slice dropped,\n // warning logged, error captured on `report.ack`). Specialist\n // branches override the receptionist on key collision either way.\n await this.settleAck(ackPromise, iterationUsage);\n\n // Merge branch outputs into supervisor state in decision.intents\n // order so fan-out conflict resolution is deterministic — last\n // intent in the array wins on key collisions (Q15). Errored\n // branches don't contribute. Entries without an `output` schema\n // (agent/workflow) are NOT auto-merged — declaring the slice is\n // opt-in. Callbacks always merge (their full return value when\n // no schema; strip-merged when schema is declared) — they had\n // their schema applied inside runCallback already.\n this.mergeBranchesIntoState(decision.intents, branchSnapshots);\n\n // Phase 5 / decisions §35 — merge tool-side artifacts into state\n // AFTER branch slices land but BEFORE evaluate runs, so the\n // evaluate verdict sees the post-merge state including blocks /\n // citations / soft signals contributed by tools. Resets the bag\n // for the next iteration; long runs and orchestrator sessions\n // never accumulate raw artifacts.\n await this.mergeArtifactsIntoState();\n\n this.lastDispatchIntents = decision.intents;\n\n const evaluateVerdict = await this.runEvaluate(branchSnapshots);\n\n if (evaluateVerdict !== undefined && evaluateVerdict !== null) {\n this.emit(\"supervisor.evaluate.verdict\", {\n iteration: this.iteration,\n verdict: evaluateVerdict,\n });\n }\n\n const iterationEndedAt = new Date();\n const duration = performance.now() - iterationStart;\n\n const snapshot: IterationSnapshot = Object.freeze({\n iteration: this.iteration,\n result: indexByIntent(branchSnapshots),\n decision: {\n source: decision.source,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n },\n evaluateVerdict,\n state: { ...this.state },\n artifacts: this.capturedIterationArtifacts,\n startedAt: iterationStartedAt.toISOString(),\n endedAt: iterationEndedAt.toISOString(),\n duration,\n usage: iterationUsage,\n });\n\n this.snapshots.push(snapshot);\n\n this.emit(\"supervisor.iteration.completed\", {\n iteration: this.iteration,\n snapshot,\n });\n\n await this.checkpoint(\"running\");\n\n if (evaluateVerdict?.satisfied) {\n this.terminatedBy = \"evaluate\";\n this.status = \"completed\";\n\n return false;\n }\n\n this.carriedFeedback = evaluateVerdict;\n\n // Stage 4d (Q24): when evaluate hasn't taken a stance via\n // `reassignTo`, collect each branch's `intent.next(ctx)` to drive\n // the next iteration without a router call. Evaluate's\n // `reassignTo` outranks `next` — if evaluate forced a target,\n // `next` doesn't get to vote.\n const evaluateForcedReassign =\n evaluateVerdict?.reassignTo !== undefined &&\n normalizeReassign(evaluateVerdict.reassignTo).length > 0;\n\n if (!evaluateForcedReassign) {\n const collected = this.collectIntentNext(decision.intents, branchSnapshots);\n\n if (collected?.kind === \"end\") {\n this.terminatedBy = \"route\";\n this.status = \"completed\";\n this.carriedNextDispatch = undefined;\n return false;\n }\n\n if (collected?.kind === \"dispatch\") {\n this.carriedNextDispatch = { intents: collected.intents };\n }\n }\n\n // Phase 7 / decisions §37 — classifier-alone supervisor auto-\n // terminates after iter 0's branch settles. Without router/route,\n // there's no decision source for iter 1; preempt the throw with\n // a clean termination. `intent.next` from iter 0's dispatched\n // intent still wins if it set a continuation (rare, but allowed).\n if (\n this.iteration === 0 &&\n this.config.classifier &&\n !this.config.router &&\n !this.config.route &&\n !this.carriedNextDispatch\n ) {\n this.terminatedBy = \"classifier\";\n this.status = \"completed\";\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Resolve the dispatch decision for this iteration — defers to\n * `decide.ts`. When `carriedFeedback.reassignTo` is set the\n * supervisor overrides the router/route decision with an\n * evaluator-forced dispatch (design §2 — \"Evaluate can override\n * router\").\n */\n private async decideDispatch(): Promise<DispatchDecision> {\n if (this.config.router) {\n this.emit(\"supervisor.router.deciding\", { iteration: this.iteration });\n }\n\n const reassignTo = normalizeReassign(this.carriedFeedback?.reassignTo);\n\n if (reassignTo.length > 0) {\n this.carriedNextDispatch = undefined;\n for (const intent of reassignTo) {\n if (!this.entries.has(intent)) {\n throw new SupervisorFailedError(\n `evaluate.reassignTo targeted unknown agent \"${intent}\"`,\n { context: { available: [...this.entries.keys()] } },\n );\n }\n }\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: reassignTo,\n source: \"route\",\n raw: reassignTo.length === 1 ? reassignTo[0] : reassignTo,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: this.carriedFeedback?.feedback,\n durationMs: 0,\n });\n\n return decision;\n }\n\n // Phase 7 / decisions §37 — classifier prelude (iter 0 only)\n // produced an intent dispatch decision. Skip router/route /\n // initialAgent entirely; classifier's pick wins. Cleared after\n // consumption — iter 1+ falls through to router/route as usual.\n if (this.carriedClassifierDispatch) {\n const carried = this.carriedClassifierDispatch;\n this.carriedClassifierDispatch = undefined;\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: [carried.intent],\n source: \"classifier\",\n raw: carried.intent,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: this.classifierSnapshot?.reasoning,\n durationMs: 0,\n });\n\n return decision;\n }\n\n // Stage 4d: per-intent `next` collected from the previous\n // iteration drives this dispatch — skip router/route entirely.\n if (this.carriedNextDispatch) {\n const carried = this.carriedNextDispatch;\n this.carriedNextDispatch = undefined;\n\n const decision: DispatchDecision = {\n kind: \"dispatch\",\n intents: carried.intents,\n source: \"route\",\n raw: carried.intents.length === 1 ? carried.intents[0] : carried.intents,\n durationMs: 0,\n };\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: undefined,\n durationMs: 0,\n });\n\n return decision;\n }\n\n const decision = await decide({\n config: this.config as SupervisorConfig<unknown>,\n entries: this.entries,\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n iterations: this.snapshots,\n input: this.input,\n state: this.state,\n context: this.context,\n history: this.history,\n goal: this.goal,\n evaluateFeedback: this.carriedFeedback,\n classifier: this.classifierSnapshot,\n signal: this.options?.signal,\n useInitialAgent: this.iteration === 0 && !this.resumeFrom,\n });\n\n // Capture the router agent's report into the supervisor's tree so\n // router cost + internals are observable alongside dispatched\n // branches. Only present when decide() went through a router agent.\n if (decision.routerReport) {\n this.childReports.push(decision.routerReport);\n }\n\n this.emit(\"supervisor.router.decided\", {\n iteration: this.iteration,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n });\n\n return decision;\n }\n\n /**\n * Dispatch every intent named by the decision in parallel. Per-\n * branch errors don't abort siblings — they're recorded on the\n * branch snapshot and let evaluate (or default termination logic)\n * decide the response.\n */\n private async dispatchBranches(\n decision: DispatchDecision & { kind: \"dispatch\" },\n ): Promise<AgentBranchSnapshot[]> {\n const branches = await Promise.all(decision.intents.map((intent) => this.dispatchOne(intent)));\n\n return branches;\n }\n\n /**\n * Execute a single branch — resolve the input, invoke the\n * agent / workflow / callback, apply the per-intent `output`\n * transformer, and produce an immutable `AgentBranchSnapshot`.\n */\n private async dispatchOne(intent: string): Promise<AgentBranchSnapshot> {\n const entry = this.entries.get(intent)!;\n\n if (entry.type === \"callback\") {\n return this.dispatchCallback(entry);\n }\n\n const routeContext: RouteContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n iterations: this.snapshots,\n feedback:\n typeof this.carriedFeedback?.feedback === \"string\"\n ? this.carriedFeedback.feedback\n : undefined,\n evaluateFeedback: this.carriedFeedback,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n const resolvedInput = this.resolveBranchInput(entry, routeContext);\n const dispatchCtxForPlaceholders = this.seedDispatchContext(\n intent,\n resolvedInput,\n new Set<string>([intent]),\n [],\n );\n const placeholders = entry.placeholders\n ? entry.placeholders(dispatchCtxForPlaceholders)\n : undefined;\n\n this.emit(\"supervisor.agent.starting\", {\n iteration: this.iteration,\n intent,\n input: resolvedInput,\n });\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n let rawResult: AgentResult<unknown> | WorkflowResult<unknown> | undefined;\n let branchError: AIError | undefined;\n let branchUsage: Usage = { input: 0, output: 0, total: 0 };\n\n try {\n rawResult = await this.invokeUnit(entry, resolvedInput, placeholders, routeContext);\n\n if (rawResult.error) {\n branchError = rawResult.error;\n }\n\n branchUsage = rawResult.usage;\n\n // Capture the child's execution report into the supervisor's\n // recursive tree. Each dispatched agent/workflow contributes\n // one BaseReport node; fan-out produces sibling children.\n if (rawResult.report) {\n this.childReports.push(rawResult.report);\n }\n } catch (thrown) {\n branchError = toAIError(thrown);\n }\n\n const sliceOutcome = await this.applyOutputSchema(entry, rawResult);\n const transformedOutput = sliceOutcome.value;\n if (sliceOutcome.error && !branchError) {\n branchError = sliceOutcome.error;\n }\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n const snapshot: AgentBranchSnapshot = Object.freeze({\n intent,\n input: resolvedInput,\n output: transformedOutput,\n usage: branchUsage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: branchError,\n });\n\n if (branchError) {\n this.emit(\"supervisor.agent.failed\", {\n iteration: this.iteration,\n intent,\n error: branchError,\n });\n } else {\n this.emit(\"supervisor.agent.completed\", {\n iteration: this.iteration,\n intent,\n output: transformedOutput,\n usage: branchUsage,\n duration,\n });\n }\n\n return snapshot;\n }\n\n /**\n * Dispatch a callback intent as a top-level branch — produces an\n * `AgentBranchSnapshot` and pushes the synthesized callback report\n * onto the supervisor's recursive children. Delegates the actual\n * callback invocation to {@link runCallback} so nested\n * `ctx.intents.X.execute()` calls can reuse the same machinery.\n *\n * Each branch dispatch starts with a fresh per-branch call stack —\n * sibling fan-out branches don't share cycle-detection state, so\n * branch A and branch B both invoking the same intent isn't a\n * cycle. The branch's own intent name is seeded onto the stack so\n * a callback that re-enters itself via `ctx.intents.X.execute()` trips\n * cycle detection on the first recursion.\n */\n private async dispatchCallback(entry: ResolvedCallbackEntry): Promise<AgentBranchSnapshot> {\n const intent = entry.intent;\n const callStack = new Set<string>([intent]);\n const callbackInput = entry.input\n ? entry.input(this.seedDispatchContext(intent, this.input, callStack, []))\n : this.input;\n const inputForSnapshot =\n typeof callbackInput === \"string\" ? callbackInput : safeStringify(callbackInput);\n\n this.emit(\"supervisor.agent.starting\", {\n iteration: this.iteration,\n intent,\n input: inputForSnapshot,\n });\n\n const outcome = await this.runCallback(entry, callbackInput, callStack, this.childReports);\n\n const snapshot: AgentBranchSnapshot = Object.freeze({\n intent,\n input: inputForSnapshot,\n output: outcome.output,\n usage: outcome.report.usage,\n startedAt: outcome.report.startedAt,\n endedAt: outcome.report.endedAt,\n duration: outcome.report.duration,\n error: outcome.error,\n });\n\n if (outcome.error) {\n this.emit(\"supervisor.agent.failed\", {\n iteration: this.iteration,\n intent,\n error: outcome.error,\n });\n } else {\n this.emit(\"supervisor.agent.completed\", {\n iteration: this.iteration,\n intent,\n output: outcome.output,\n usage: outcome.report.usage,\n duration: outcome.report.duration,\n });\n }\n\n return snapshot;\n }\n\n /**\n * Run a callback intent and produce its leaf report + final\n * output. Used both for top-level branch dispatch (via\n * {@link dispatchCallback}) and for nested `dispatch.byName`\n * recursion. The synthesized report is appended to `reportSink`,\n * which is either `this.childReports` (top-level) or the calling\n * callback's own `children[]` (nested) — that's what gives the\n * unified report tree its compositional shape.\n *\n * Usage on the report rolls up children's usage; the callback\n * itself contributes zero (it's dev code, no token spend).\n */\n private async runCallback(\n entry: ResolvedCallbackEntry,\n input: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<{ output: unknown; error?: AIError; report: BaseReport }> {\n const childReports: BaseReport[] = [];\n const dispatchCtx: DispatchContext = this.seedDispatchContext(\n entry.intent,\n input,\n callStack,\n childReports,\n );\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n let rawOutput: unknown;\n let error: AIError | undefined;\n\n try {\n rawOutput = await entry.callback(dispatchCtx);\n } catch (thrown) {\n error =\n thrown instanceof AIError\n ? thrown\n : new SupervisorFailedError(\n `callback intent \"${entry.intent}\" threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`,\n { cause: thrown },\n );\n }\n\n let transformedOutput: unknown = rawOutput;\n\n if (!error && entry.output) {\n const validation = await entry.output[\"~standard\"].validate(rawOutput);\n if (validation.issues) {\n error = new SchemaValidationError(\n `intent \"${entry.intent}\" output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n transformedOutput = undefined;\n } else {\n transformedOutput = validation.value;\n }\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n const rolledUsage = aggregateChildUsage(childReports);\n\n const report: BaseReport = {\n runId: `${this.runId}.${entry.intent}`,\n rootRunId: this.runId,\n name: entry.intent,\n type: \"callback\",\n status: error ? \"failed\" : \"completed\",\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n usage: rolledUsage,\n children: childReports,\n };\n\n reportSink.push(report);\n\n return { output: transformedOutput, error, report };\n }\n\n /**\n * Build a {@link DispatchContext} with a typed `intents` map of\n * `IntentRunner` closures, each closing over the supplied call\n * stack and report sink. Cycle detection uses the call stack —\n * re-entering an intent already on it throws\n * `SupervisorFailedError` with code `SUPERVISOR_DISPATCH_CYCLE`\n * and the offending chain in the message.\n *\n * Replaces the Phase-3.3 `ctx.dispatch.byName` plumbing with\n * property-access on a typed map (Q5/Q6) — autocomplete, no typo\n * crashes, `.execute()` matches every other primitive's verb.\n */\n private seedDispatchContext(\n intent: string,\n input: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): DispatchContext {\n type RunnerSlot = {\n execute: (input?: unknown) => Promise<unknown>;\n stream: (input?: unknown) => unknown;\n };\n const intentsMap: Record<string, RunnerSlot> = {};\n\n for (const target of this.entries.keys()) {\n intentsMap[target] = {\n execute: (override?: unknown) =>\n this.runIntent(target, override === undefined ? input : override, callStack, reportSink),\n stream: (override?: unknown) =>\n this.streamIntent(\n target,\n override === undefined ? input : override,\n callStack,\n reportSink,\n intent,\n ),\n };\n }\n\n return {\n iteration: this.iteration,\n intent,\n input,\n state: this.state,\n result: {},\n iterations: this.snapshots,\n signal: this.options?.signal ?? new AbortController().signal,\n intents: intentsMap as DispatchContext[\"intents\"],\n context: this.context,\n history: this.history,\n goal: this.goal,\n run: (executable, runInput, runOptions) =>\n this.runInline(executable, runInput, runOptions, callStack, reportSink),\n stream: (executable, runInput, runOptions) =>\n this.streamInline(executable, runInput, runOptions, callStack, reportSink, intent),\n classifier: this.classifierSnapshot,\n } as DispatchContext;\n }\n\n /**\n * Backing implementation for `ctx.intents.X.execute(input?)`.\n * Looks up the named intent in the supervisor's registry, asserts\n * the call wouldn't close a cycle, and runs the dispatchable\n * through the same machinery a top-level branch would — except\n * the resulting report nests under the calling callback's\n * `children[]` rather than the supervisor's top-level child list,\n * and only the final output is returned (no snapshot).\n */\n private async runIntent(\n target: string,\n callerInput: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<unknown> {\n if (callStack.has(target)) {\n const chain = [...callStack, target].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.intents.${target}.execute: cycle detected (${chain})`,\n { context: { intent: target } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n const entry = this.entries.get(target);\n\n if (!entry) {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.execute: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n { context: { intent: target } },\n );\n }\n\n callStack.add(target);\n\n try {\n if (entry.type === \"callback\") {\n const { output, error } = await this.runCallback(entry, callerInput, callStack, reportSink);\n\n if (error) {\n throw error;\n }\n\n return output;\n }\n\n // Agent / workflow path. The unified-report tree gets the\n // child's report under the calling callback's children — we\n // intentionally do NOT also push to `this.childReports` (that\n // would double-count). The agent/workflow's own usage flows\n // up through the callback's roll-up.\n const inputString =\n typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n if (entry.type === \"agent\") {\n // Recursive `ctx.intents.X.execute()` re-entry path — no\n // `RouteContext` constructed here, so the per-entry slicer is\n // skipped; only the global `historyWindow.agents` window\n // applies. The original outer dispatch already passed a sliced\n // view; this sub-call mirrors that behavior.\n const reentryHistory = this.applyAgentsWindow();\n const result = await entry.unit.execute(inputString, {\n signal: this.options?.signal,\n ...(reentryHistory.length > 0 ? { history: reentryHistory } : {}),\n });\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n return result.data ?? result.text ?? undefined;\n }\n\n // workflow\n const result = await entry.unit.execute(inputString as never, {\n signal: this.options?.signal,\n });\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n return result.data;\n } finally {\n callStack.delete(target);\n }\n }\n\n /**\n * Backing implementation for `ctx.intents.X.stream(input?)` (Phase 6\n * / decisions §36). Streaming sibling of {@link runIntent} — same\n * cycle protection, same auto-merge of supervisor-level concerns,\n * but routes through the unit's `.stream()` method when available\n * and bubbles deltas as `supervisor.agent.streaming` under the\n * **calling callback's** intent name (not the dispatched intent's).\n */\n private streamIntent(\n target: string,\n callerInput: unknown,\n callStack: Set<string>,\n reportSink: BaseReport[],\n callerIntent: string,\n ): StreamContract<SupervisableResult> {\n if (callStack.has(target)) {\n const chain = [...callStack, target].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: cycle detected (${chain})`,\n { context: { intent: target } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n const entry = this.entries.get(target);\n\n if (!entry) {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n { context: { intent: target } },\n );\n }\n\n if (entry.type === \"callback\") {\n throw new SupervisorFailedError(\n `ctx.intents.${target}.stream: callback intents are not streamable — use \\`.execute(input?)\\` instead`,\n { context: { intent: target } },\n );\n }\n\n callStack.add(target);\n\n const inputString = typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n return this.streamSupervisedExecutable(\n entry.unit as StreamableExecutable,\n inputString,\n undefined,\n callerIntent,\n reportSink,\n () => callStack.delete(target),\n );\n }\n\n /**\n * Backing implementation for `ctx.run(executable, input, options?)`\n * (Phase 6 / decisions §36). Runs an inline / un-registered\n * executable under supervision: auto-merges `signal`, `toolCtx`,\n * `history` defaults; nests the resulting report under the\n * calling callback's `children[]`. Per-call options REPLACE auto-\n * defaults — standard Warlock convention.\n *\n * Cycle protection by executable `name` matches the registered-\n * intent path so a callback that recurses on the same agent trips\n * the same error, regardless of whether the agent was looked up\n * via `ctx.intents.X.execute()` or passed inline.\n */\n private async runInline(\n executable: SupervisableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callStack: Set<string>,\n reportSink: BaseReport[],\n ): Promise<SupervisableResult> {\n const name = executable.name;\n\n if (callStack.has(name)) {\n const chain = [...callStack, name].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.run(\"${name}\"): cycle detected (${chain})`,\n { context: { intent: name } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n callStack.add(name);\n\n try {\n const merged = this.mergeInlineOptions(options);\n const inputForExecutable = this.coerceInlineInput(executable, input);\n const result = (await (\n executable as {\n execute: (input: unknown, options?: unknown) => Promise<SupervisableResult>;\n }\n ).execute(inputForExecutable, merged)) as SupervisableResult;\n\n if (result.report) {\n reportSink.push(result.report);\n }\n\n return result;\n } finally {\n callStack.delete(name);\n }\n }\n\n /**\n * Backing implementation for `ctx.stream(executable, input, options?)`\n * (Phase 6 / decisions §36). Streaming sibling of {@link runInline}.\n * Routes through the executable's native `.stream()` method,\n * subscribes to delta events, and bubbles them as\n * `supervisor.agent.streaming` under the calling callback's intent\n * name. The returned `StreamContract` is the executable's own —\n * iteration and `.result` work identically.\n *\n * Cycle protection on entry mirrors {@link runInline}; release runs\n * after `.result` settles so a same-callback recursion is caught\n * regardless of which path closed the cycle.\n */\n private streamInline(\n executable: StreamableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callStack: Set<string>,\n reportSink: BaseReport[],\n callerIntent: string,\n ): StreamContract<SupervisableResult> {\n const name = executable.name;\n\n if (callStack.has(name)) {\n const chain = [...callStack, name].join(\" → \");\n throw new SupervisorFailedError(\n `ctx.stream(\"${name}\"): cycle detected (${chain})`,\n { context: { intent: name } },\n \"SUPERVISOR_DISPATCH_CYCLE\",\n );\n }\n\n callStack.add(name);\n\n return this.streamSupervisedExecutable(\n executable,\n this.coerceInlineInput(executable, input),\n options,\n callerIntent,\n reportSink,\n () => callStack.delete(name),\n );\n }\n\n /**\n * Shared wiring for both `ctx.intents.X.stream()` and\n * `ctx.stream(...)`. Subscribes to the executable's stream, re-\n * emits deltas as `supervisor.agent.streaming` under the calling\n * callback's intent name, and pushes the inner report onto the\n * reportSink once `.result` settles. The returned StreamContract\n * is the executable's own — the framework attaches handlers\n * transparently via `.on(...)`.\n */\n private streamSupervisedExecutable(\n executable: StreamableExecutable,\n input: unknown,\n options: SupervisableExecuteOptions | undefined,\n callerIntent: string,\n reportSink: BaseReport[],\n release: () => void,\n ): StreamContract<SupervisableResult> {\n const merged = this.mergeInlineOptions(options);\n const stream = (\n executable as {\n stream: (input: unknown, options?: unknown) => StreamContract<SupervisableResult>;\n }\n ).stream(input, merged);\n\n // Bubble inner deltas under the CALLING callback's intent name.\n // Agents fire `agent.trip.streaming`; supervisors fire\n // `supervisor.agent.streaming` already — the inner intent name\n // there is the inner supervisor's specialist, which we replace\n // with the outer callback's name so attribution is consistent.\n const handlers: Record<string, (event: { delta: string }) => void> = {\n \"agent.trip.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: callerIntent,\n delta,\n });\n },\n \"supervisor.agent.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: callerIntent,\n delta,\n });\n },\n };\n\n stream.on(handlers);\n\n // Always release the cycle-protection slot after `.result` settles\n // (success OR failure) so subsequent calls in the same callback\n // see a clean stack. Push report on success.\n void stream.result.then(\n (result) => {\n if (result?.report) {\n reportSink.push(result.report);\n }\n\n release();\n },\n () => release(),\n );\n\n return stream;\n }\n\n /**\n * Build the options object passed into an inline `.execute()` /\n * `.stream()` call. Auto-merges supervisor-level defaults\n * (`signal`, `toolCtx`, `history` window) under the caller's\n * options. Per-call values REPLACE the auto-defaults — when the\n * dev passes `signal: undefined` they explicitly opt out.\n */\n private mergeInlineOptions(\n options: SupervisableExecuteOptions | undefined,\n ): SupervisableExecuteOptions {\n const supplied = (options ?? {}) as Record<string, unknown>;\n const merged: Record<string, unknown> = { ...supplied };\n\n if (!(\"signal\" in supplied)) {\n merged.signal = this.options?.signal;\n }\n\n if (!(\"toolCtx\" in supplied)) {\n merged.toolCtx = {\n artifacts: this.currentArtifacts,\n signal: this.options?.signal,\n };\n }\n\n if (!(\"history\" in supplied)) {\n const window = this.applyAgentsWindow();\n\n if (window.length > 0) {\n merged.history = window;\n }\n }\n\n return merged as SupervisableExecuteOptions;\n }\n\n /**\n * Coerce an arbitrary inline input into the shape the underlying\n * executable expects. Agents take `string`; workflows + supervisors\n * take whatever they declared. We safe-stringify objects only when\n * passing to an agent — workflow / supervisor calls hand the value\n * through unchanged so structured inputs work.\n */\n private coerceInlineInput(executable: SupervisableExecutable, input: unknown): unknown {\n // Agents are the only kind that strictly require string input.\n // Workflows / supervisors accept arbitrary shapes.\n const isAgent =\n !(\"signature\" in executable) &&\n typeof executable.execute === \"function\" &&\n !this.isSupervisor(executable);\n\n if (isAgent && typeof input !== \"string\") {\n return safeStringify(input);\n }\n\n return input;\n }\n\n /**\n * Heuristic detection of `SupervisorContract` — the contract carries\n * a `signature` getter same as workflows, but supervisors expose\n * `resume()` while workflows expose `resume(runId, options)` too.\n * Cleanest distinguisher in the public surface: supervisors carry\n * the `asTool` method name `as` … unfortunately so do workflows.\n * Use the `streamableType` brand if we add one in v2; for now lean\n * on a duck-typed check that's good enough for the ctx.run path\n * (incorrect routing for workflows would still produce a runnable\n * call — workflow.execute accepts the same args either way).\n */\n private isSupervisor(executable: SupervisableExecutable): boolean {\n return (\n typeof (executable as { resume?: unknown; signature?: unknown }).resume === \"function\" &&\n typeof (executable as { signature?: unknown }).signature === \"string\" &&\n typeof (executable as { stream?: unknown }).stream === \"function\"\n );\n }\n\n /**\n * Invoke the underlying dispatchable unit. Agents and workflows\n * both satisfy `ExecutableContract<string, …>` so the call shape\n * is uniform; the `type` discriminator picks which options get\n * threaded through (e.g. per-call stream event bubbling for\n * agents, which we wire inline so child agent tokens surface as\n * `supervisor.agent.streaming`).\n */\n private async invokeUnit(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n input: string,\n placeholders: Record<string, unknown> | undefined,\n routeContext: RouteContext,\n ): Promise<AgentResult<unknown> | WorkflowResult<unknown>> {\n // When the supervisor itself is being streamed by the caller, run\n // the child agent in streaming mode too — that's the only way\n // token deltas surface up the tree as `supervisor.agent.streaming`\n // events. `agent.execute()` always uses `model.complete()` which\n // never fires `agent.trip.streaming`, so wiring a callback there\n // is a silent no-op for tokens. Lifecycle events (trip.started /\n // tool.called / completed) still fire through `.on()` regardless\n // — they're driven by orchestration boundaries, not the wire mode.\n const isStreaming = this.streamController !== undefined;\n\n if (entry.type === \"agent\") {\n // `type` and `unit` aren't a discriminated union on the entry\n // type — narrow manually. `resolveIntentEntries` guarantees\n // `unit` matches `type` at runtime.\n const agent = entry.unit as AgentContract<unknown>;\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: entry.intent,\n delta,\n });\n },\n };\n\n // Phase 5 / decisions §34 — stream-mode intents drop the\n // structured-output schema (factory already rejects coexistence)\n // and always run via `agent.stream()` so token deltas surface as\n // `supervisor.agent.streaming` events regardless of whether the\n // top-level caller streamed the supervisor.\n const isStreamMode = entry.mode === \"stream\";\n\n // Stage 4b/4d: forward `intent.output` as the agent's per-call\n // output schema when declared. The agent then parses model\n // output as structured data; `applyOutputSchema` re-validates\n // (cheap) and strip-merges into supervisor state.\n const resolvedHistory = this.resolveHistoryFor(\"agents\", routeContext, entry.history);\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders } : {}),\n ...(entry.output && !isStreamMode ? { output: entry.output } : {}),\n ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n toolCtx: {\n artifacts: this.currentArtifacts,\n signal: this.options?.signal,\n },\n };\n\n if (isStreamMode || isStreaming) {\n const childStream = agent.stream(input, agentOptions);\n return childStream.result;\n }\n\n return agent.execute(input, agentOptions);\n }\n\n const workflow = entry.unit as WorkflowInstance<unknown, unknown>;\n\n return workflow.execute(input, {\n signal: this.options?.signal,\n on: {\n \"workflow.step.streaming\": ({ delta }) => {\n this.emit(\"supervisor.agent.streaming\", {\n iteration: this.iteration,\n intent: entry.intent,\n delta,\n });\n },\n },\n });\n }\n\n /**\n * Build the input string passed to a branch's child execution.\n * Default: pass the supervisor's original `ctx.input` through\n * unchanged. The per-intent `entry.input` override is the escape\n * hatch for the rare case where the agent's user message itself\n * must vary per intent.\n *\n * Q17 lock: dropped `composeAgentInput` + `defaultComposeAgentInput`.\n * Their three jobs (carry original / prior outputs / feedback) all\n * have cleaner homes in the new model — original is the input\n * itself, prior outputs are state (Stage 4b), feedback is a\n * router-only signal (Q18).\n */\n private resolveBranchInput(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n ctx: RouteContext,\n ): string {\n const override = entry.input?.(ctx);\n\n if (typeof override === \"string\") {\n return override;\n }\n\n // Q1: supervisor-level input may be an object payload. Agents\n // need a string — JSON-stringify when no per-intent override\n // converted it. Devs wanting a different shape supply\n // `entry.input(ctx)`.\n return typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input);\n }\n\n /**\n * Strip-merge the agent/workflow's raw output against the per-intent\n * `output` schema (Q11/Q13). Returns the validated slice that:\n *\n * 1. Lands on `IterationSnapshot.result[intent].output` (so\n * consumers see the same shape that hit state).\n * 2. Shallow-merges into `this.state` (handled by the caller).\n *\n * When `entry.output` is omitted the agent's full `data` (or `text`\n * fallback for unstructured agents) flows through unvalidated — but\n * is NOT auto-merged into state. State contribution is opt-in via\n * declaring the slice schema.\n *\n * Validation failure surfaces as a per-branch error on the\n * snapshot; sibling branches still run.\n */\n private async applyOutputSchema(\n entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n raw: AgentResult<unknown> | WorkflowResult<unknown> | undefined,\n ): Promise<{ value: unknown; error?: AIError }> {\n if (!raw) {\n return { value: undefined };\n }\n\n const sourceValue = isAgentResult(raw)\n ? (raw.data ?? raw.text ?? undefined)\n : isWorkflowResult(raw)\n ? raw.data\n : undefined;\n\n // Phase 5 / decisions §34 — stream-mode agents have no `output`\n // schema. The assembled prose comes back as `raw.text` (the agent\n // never produced structured `data` because we dropped the schema\n // in `invokeUnit`). Wrap it as `{ [streamTo]: text }` so the\n // existing strip-merge path lands the prose under the named state\n // key without further special-casing downstream.\n if (entry.type === \"agent\" && entry.mode === \"stream\") {\n const text = typeof sourceValue === \"string\" ? sourceValue : \"\";\n\n return { value: { [entry.streamTo as string]: text } };\n }\n\n if (!entry.output) {\n return { value: sourceValue };\n }\n\n const validation = await entry.output[\"~standard\"].validate(sourceValue);\n\n if (validation.issues) {\n return {\n value: undefined,\n error: new SchemaValidationError(\n `intent \"${entry.intent}\" output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n ),\n };\n }\n\n return { value: validation.value };\n }\n\n /**\n * Fire the receptionist (`ack`) — runs in parallel with phase A on\n * iteration 0 only. Accepts three shapes:\n *\n * - `AckEntry` — `{ agent, placeholders?, input?, output? }`. LLM\n * form. Streams tokens via `supervisor.ack.streaming`; report\n * node pushes onto `childReports[]`.\n * - `AckRunEntry` — `{ run, output? }`. Pure-code callback. Settles\n * without an LLM call. No streaming events; just `.completed`.\n * - `AckCallback` — bare `(ctx) => slice` shorthand for the\n * pure-code form when no schema is declared.\n *\n * Failures are recorded but never abort the run — the receptionist\n * tripping doesn't stop the specialist from doing the actual job.\n * The returned outcome is what `mergeAckIntoState` consumes.\n */\n private async runAck(): Promise<\n | {\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }\n | undefined\n > {\n const ack = this.config.ack;\n if (!ack) return undefined;\n\n const routeContext: RouteContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n iterations: this.snapshots,\n feedback:\n typeof this.carriedFeedback?.feedback === \"string\"\n ? this.carriedFeedback.feedback\n : undefined,\n evaluateFeedback: this.carriedFeedback,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n const startedAt = new Date();\n const startPerf = performance.now();\n\n // Bare-callback shorthand: `ack: (ctx) => slice`.\n if (typeof ack === \"function\") {\n return this.runAckCallback(\n ack as (ctx: RouteContext) => unknown | Promise<unknown>,\n undefined,\n routeContext,\n startedAt,\n startPerf,\n );\n }\n\n // Run-entry form: `ack: { run, output? }`.\n if (\"run\" in ack && typeof (ack as { run?: unknown }).run === \"function\") {\n const runEntry = ack as {\n run: (ctx: RouteContext) => unknown | Promise<unknown>;\n output?: StandardSchemaV1<unknown>;\n };\n return this.runAckCallback(runEntry.run, runEntry.output, routeContext, startedAt, startPerf);\n }\n\n // Agent-entry form: `ack: { agent, placeholders?, input?, output? }`.\n return this.runAckAgent(\n ack as {\n agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n input?: (ctx: RouteContext) => string;\n output?: StandardSchemaV1<unknown>;\n history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n },\n routeContext,\n startedAt,\n startPerf,\n );\n }\n\n /**\n * Pure-code receptionist path — invokes the callback, strip-validates\n * the return value (when an `output` schema is declared), records the\n * snapshot, emits `supervisor.ack.completed`, returns the outcome.\n * No streaming events fire (callbacks settle synchronously from the\n * supervisor's POV).\n */\n private async runAckCallback(\n run: (ctx: RouteContext) => unknown | Promise<unknown>,\n output: StandardSchemaV1<unknown> | undefined,\n routeContext: RouteContext,\n startedAt: Date,\n startPerf: number,\n ): Promise<{\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }> {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n let validatedOutput: unknown;\n let ackError: AIError | undefined;\n\n try {\n const raw = await run(routeContext);\n\n if (output) {\n const validation = await output[\"~standard\"].validate(raw);\n if (validation.issues) {\n ackError = new SchemaValidationError(\n `ack output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n } else {\n validatedOutput = validation.value;\n }\n } else {\n validatedOutput = raw;\n }\n } catch (thrown) {\n ackError = toAIError(thrown);\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n this.ackSnapshot = Object.freeze({\n input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n output: validatedOutput,\n usage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: ackError,\n });\n\n this.emit(\"supervisor.ack.completed\", {\n output: validatedOutput,\n usage,\n duration,\n error: ackError,\n });\n\n return { output: validatedOutput, usage, duration, error: ackError };\n }\n\n /**\n * Agent-driven receptionist path — invokes the agent, streams tokens\n * via `supervisor.ack.streaming`, captures the report node, strip-\n * validates against `output` (when declared), records the snapshot,\n * emits `supervisor.ack.completed`.\n */\n private async runAckAgent(\n ack: {\n agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n input?: (ctx: RouteContext) => string;\n output?: StandardSchemaV1<unknown>;\n history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n },\n routeContext: RouteContext,\n startedAt: Date,\n startPerf: number,\n ): Promise<{\n output: unknown;\n usage: Usage;\n duration: number;\n error?: AIError;\n }> {\n const placeholders = ack.placeholders?.(routeContext);\n const inputForAck =\n ack.input?.(routeContext) ??\n (typeof this.input === \"string\" ? this.input : safeStringify(this.input));\n\n const isStreaming = this.streamController !== undefined;\n\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.ack.streaming\", { delta });\n },\n };\n\n const resolvedHistory = this.resolveHistoryFor(\"ack\", routeContext, ack.history);\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders } : {}),\n ...(ack.output ? { output: ack.output } : {}),\n ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n };\n\n let rawResult: AgentResult<unknown> | undefined;\n let ackError: AIError | undefined;\n let usage: Usage = { input: 0, output: 0, total: 0 };\n\n try {\n if (isStreaming) {\n const childStream = ack.agent.stream(inputForAck, agentOptions);\n rawResult = await childStream.result;\n } else {\n rawResult = await ack.agent.execute(inputForAck, agentOptions);\n }\n\n if (rawResult.error) {\n ackError = rawResult.error;\n }\n\n usage = rawResult.usage ?? usage;\n\n // Ack agent's report node in the supervisor's recursive tree.\n if (rawResult.report) {\n this.childReports.push(rawResult.report);\n }\n } catch (thrown) {\n ackError = toAIError(thrown);\n }\n\n const endedAt = new Date();\n const duration = performance.now() - startPerf;\n\n // Strip-validate against `ack.output` (when declared) — same\n // contract as per-intent output schemas.\n let validatedOutput: unknown;\n if (rawResult && !ackError && ack.output) {\n const sourceValue = rawResult.data ?? rawResult.text ?? undefined;\n const validation = await ack.output[\"~standard\"].validate(sourceValue);\n if (validation.issues) {\n ackError = new SchemaValidationError(\n `ack output failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues },\n );\n } else {\n validatedOutput = validation.value;\n }\n } else if (rawResult && !ackError) {\n validatedOutput = rawResult.data ?? rawResult.text ?? undefined;\n }\n\n this.ackSnapshot = Object.freeze({\n input: inputForAck,\n output: validatedOutput,\n usage,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n duration,\n error: ackError,\n });\n\n this.emit(\"supervisor.ack.completed\", {\n output: validatedOutput,\n usage,\n duration,\n error: ackError,\n });\n\n return { output: validatedOutput, usage, duration, error: ackError };\n }\n\n /**\n * Probe the ack promise non-blockingly. Yields one macrotask cycle\n * (`setImmediate`) so an already-resolved ack wins via microtask\n * priority; if the probe returns first, the slice is abandoned —\n * warning logged, error captured on `report.ack`, run completes\n * regardless. Specialists own the actual answer; the receptionist\n * was just a reassuring preview.\n */\n private async settleAck(\n ackPromise:\n | Promise<{ output: unknown; usage: Usage; duration: number; error?: AIError } | undefined>\n | undefined,\n iterationUsage: Usage,\n ): Promise<void> {\n if (!ackPromise) return;\n\n const NOT_READY = Symbol(\"ack-not-ready\");\n const probe = await Promise.race([\n ackPromise,\n new Promise<typeof NOT_READY>((resolve) => setTimeout(() => resolve(NOT_READY), 0)),\n ]);\n\n if (probe === NOT_READY) {\n this.logger.warn(\n this.logModule,\n \"ack.abandoned\",\n \"ack receptionist did not settle before iteration completed; slice dropped\",\n );\n const abandonedAt = new Date();\n this.ackSnapshot = Object.freeze({\n input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n output: undefined,\n usage: { input: 0, output: 0, total: 0 },\n startedAt: abandonedAt.toISOString(),\n endedAt: abandonedAt.toISOString(),\n duration: 0,\n error: new SupervisorFailedError(\n \"ack receptionist did not settle before iteration completed\",\n { context: { ackAbandoned: true } },\n ),\n });\n return;\n }\n\n const ackOutcome = probe;\n if (ackOutcome) {\n this.aggregateUsage(iterationUsage, ackOutcome.usage);\n this.mergeAckIntoState(ackOutcome);\n }\n }\n\n /**\n * Merge the receptionist's strip-validated slice into state. Called\n * from `settleAck` BEFORE branch merges so specialists override the\n * receptionist on key collision — the receptionist hedges, the\n * specialist commits.\n */\n private mergeAckIntoState(ackOutcome: { output: unknown; error?: AIError }): void {\n if (ackOutcome.error || !ackOutcome.output) return;\n\n if (typeof ackOutcome.output !== \"object\" || ackOutcome.output === null) return;\n\n const slice = ackOutcome.output as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(slice)) {\n this.state[key] = value;\n }\n }\n\n /**\n * Run the iter-0 classifier prelude (Phase 7 / decisions §37).\n * Resolves the configured classifier (agent / callback / entry\n * form), invokes it, runs the optional `refine` post-process hook,\n * and either:\n *\n * - sets `carriedClassifierDispatch` so the upcoming\n * `decideDispatch` short-circuits to the chosen intent, OR\n * - sets `classifierHalted = true` so `runIteration` terminates\n * before any dispatch (refine returned `END`).\n *\n * Captures the full forensic record on `classifierSnapshot` —\n * surfaced on `SupervisorReport.classifier` and threaded into\n * `ctx.classifier` on every downstream context.\n *\n * Errors in the classifier OR the refine hook abort the run with\n * a `SupervisorFailedError` so issues surface loudly instead of\n * silently falling through to router/route.\n */\n private async runClassifier(): Promise<void> {\n const startedAt = new Date();\n const startPerf = performance.now();\n const startedAtIso = startedAt.toISOString();\n\n this.emit(\"supervisor.classifier.starting\", { iteration: 0 });\n\n const ctx = this.buildClassifierContext();\n const config = this.config.classifier as ClassifierConfig;\n\n let raw: ClassifierOutput | undefined;\n let usage: Usage = { input: 0, output: 0, total: 0 };\n let executionError: AIError | undefined;\n\n try {\n const outcome = await this.invokeClassifier(config, ctx);\n raw = outcome.output;\n usage = outcome.usage;\n } catch (thrown) {\n executionError = toAIError(thrown);\n }\n\n if (executionError || !raw) {\n const error =\n executionError ??\n new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier produced no output`,\n { context: { iteration: 0 } },\n );\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw: raw ?? { intent: \"\" },\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n // Classifier failure aborts the run — no fallback to router/route.\n // Phase 7 / decisions §37.\n throw error;\n }\n\n // Validate the classifier's chosen intent against the registry\n // before running refine — refine may override, but we still want\n // to fail fast on raw classifier output that targets nothing.\n if (!this.entries.has(raw.intent)) {\n const error = new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier picked unknown intent \"${raw.intent}\" — must be a key in \\`intents\\``,\n { context: { iteration: 0, available: [...this.entries.keys()] } },\n \"SUPERVISOR_INVALID_ROUTE\",\n );\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n // Refine pass — optional. Refine receives the classifier output\n // on `ctx.result.data` plus `run` / `stream` for inline secondary\n // classifiers. Returns: undefined (use as-is) | END (halt) |\n // { intent?, ...slice } (override + merge).\n const refineHook = this.resolveRefineHook(config);\n let final: ClassifierOutput = raw;\n let refined = false;\n let halted = false;\n\n if (refineHook) {\n let refineResult: ClassifierRefineResult;\n\n try {\n refineResult = await refineHook(this.buildClassifierRefineContext(ctx, raw));\n } catch (thrown) {\n const error = toAIError(thrown);\n\n this.classifierSnapshot = {\n intent: undefined,\n refined: false,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n const interpretation = this.interpretRefineResult(refineResult, raw);\n\n if (interpretation.error) {\n this.classifierSnapshot = {\n intent: undefined,\n refined: true,\n halted: true,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n error: interpretation.error,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.failed\", { error: interpretation.error });\n\n throw interpretation.error;\n }\n\n refined = interpretation.refined;\n halted = interpretation.halted;\n final = interpretation.final ?? raw;\n\n // Merge refine's slice into state BEFORE dispatching — refine\n // can augment state (e.g. detected language) regardless of\n // override-vs-keep decision.\n if (interpretation.sliceToMerge) {\n for (const [key, value] of Object.entries(interpretation.sliceToMerge)) {\n this.state[key] = value;\n }\n }\n }\n\n // Always merge the (possibly refined) classifier output's\n // remaining fields into state — universal locked fields (intent,\n // reasoning, confidence) plus any dev-extended fields. Subject\n // to the supervisor's `output` schema validation at finalize.\n for (const [key, value] of Object.entries(final)) {\n this.state[key] = value;\n }\n\n this.classifierSnapshot = {\n intent: halted ? undefined : final.intent,\n reasoning: final.reasoning,\n confidence: final.confidence,\n refined,\n halted,\n raw,\n startedAt: startedAtIso,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n };\n\n this.aggregateUsage(this.usage, usage);\n\n this.emit(\"supervisor.classifier.completed\", {\n output: {\n intent: this.classifierSnapshot.intent,\n reasoning: this.classifierSnapshot.reasoning,\n confidence: this.classifierSnapshot.confidence,\n },\n intent: this.classifierSnapshot.intent,\n refined,\n halted,\n duration: this.classifierSnapshot.duration,\n usage,\n });\n\n if (halted) {\n this.classifierHalted = true;\n\n return;\n }\n\n // Validate the FINAL intent against the registry — refine may\n // have overridden to an unknown name. Throw loudly.\n if (!this.entries.has(final.intent)) {\n const error = new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier.refine returned unknown intent \"${final.intent}\" — must be a key in \\`intents\\``,\n { context: { iteration: 0, available: [...this.entries.keys()] } },\n \"SUPERVISOR_INVALID_ROUTE\",\n );\n\n this.classifierSnapshot = { ...this.classifierSnapshot, halted: true, error };\n this.classifierHalted = true;\n\n this.emit(\"supervisor.classifier.failed\", { error });\n\n throw error;\n }\n\n this.carriedClassifierDispatch = { intent: final.intent };\n }\n\n /**\n * Resolve the configured classifier into a callable that returns\n * `{ output, usage }`. Handles the four accepted shapes — bare\n * agent / bare callback / agent-entry / run-entry. Pure shape\n * normalization; no side effects.\n */\n private async invokeClassifier(\n config: ClassifierConfig,\n ctx: ClassifierContext,\n ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n // (a) Bare callback shorthand.\n if (typeof config === \"function\") {\n const output = await (\n config as (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput\n )(ctx);\n\n return { output, usage: { input: 0, output: 0, total: 0 } };\n }\n\n // (b) Run-entry — `{ run, refine? }`.\n if (typeof (config as { run?: unknown }).run === \"function\") {\n const runFn = (\n config as { run: (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput }\n ).run;\n const output = await runFn(ctx);\n\n return { output, usage: { input: 0, output: 0, total: 0 } };\n }\n\n // (c) Agent-entry — `{ agent, placeholders?, input?, history?, refine? }`.\n if (typeof (config as { agent?: { execute?: unknown } }).agent?.execute === \"function\") {\n const entry = config as {\n agent: AgentContract<unknown>;\n placeholders?: (ctx: ClassifierContext) => Record<string, unknown>;\n input?: (ctx: ClassifierContext) => string;\n history?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>;\n };\n\n return this.invokeClassifierAgent(\n entry.agent,\n ctx,\n entry.placeholders,\n entry.input,\n entry.history,\n );\n }\n\n // (d) Bare agent shorthand.\n if (typeof (config as { execute?: unknown }).execute === \"function\") {\n return this.invokeClassifierAgent(config as AgentContract<unknown>, ctx);\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): \\`classifier\\` is not an agent, callback, or entry object`,\n { context: { authoring: true } },\n );\n }\n\n /**\n * Invoke a classifier agent with the supervisor's standard wiring\n * — placeholders, input override, history slicing, signal,\n * streaming bubble. Output schema validation belongs to the agent\n * itself; we just pull the typed `data` (or fall back to parsing\n * `text`) and assert the locked `intent` field.\n */\n private async invokeClassifierAgent(\n agent: AgentContract<unknown>,\n ctx: ClassifierContext,\n placeholders?: (ctx: ClassifierContext) => Record<string, unknown>,\n inputResolver?: (ctx: ClassifierContext) => string,\n historySlicer?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>,\n ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n const inputForAgent =\n inputResolver?.(ctx) ??\n (typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input));\n\n const history = historySlicer ? [...historySlicer(ctx)] : this.applyAgentsWindow();\n\n const isStreaming = this.streamController !== undefined;\n\n const handlers = {\n \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n this.emit(\"supervisor.classifier.streaming\", { delta });\n },\n };\n\n const agentOptions = {\n signal: this.options?.signal,\n on: handlers,\n ...(placeholders ? { placeholders: placeholders(ctx) } : {}),\n ...(history.length > 0 ? { history } : {}),\n };\n\n let result: AgentResult<unknown>;\n\n if (isStreaming) {\n result = await agent.stream(inputForAgent, agentOptions).result;\n } else {\n result = await agent.execute(inputForAgent, agentOptions);\n }\n\n if (result.error) {\n throw result.error;\n }\n\n if (result.report) {\n this.childReports.push(result.report);\n }\n\n const data = result.data ?? result.text ?? undefined;\n const output = this.coerceClassifierOutput(data);\n\n return { output, usage: result.usage };\n }\n\n /**\n * Coerce an agent's output into the locked classifier shape.\n * Accepts a typed object with `intent` (the canonical case) or a\n * plain string (interpreted as the intent name with no reasoning).\n * Throws `SupervisorFailedError` if neither shape matches.\n */\n private coerceClassifierOutput(data: unknown): ClassifierOutput {\n if (typeof data === \"string\") {\n return { intent: data };\n }\n\n if (\n data &&\n typeof data === \"object\" &&\n typeof (data as { intent?: unknown }).intent === \"string\"\n ) {\n const record = data as Record<string, unknown>;\n\n return {\n intent: record.intent as string,\n reasoning: typeof record.reasoning === \"string\" ? (record.reasoning as string) : undefined,\n confidence:\n typeof record.confidence === \"number\" ? (record.confidence as number) : undefined,\n };\n }\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier output missing required \\`intent\\` field — got ${JSON.stringify(data)?.slice(0, 200)}`,\n { context: { iteration: 0 } },\n );\n }\n\n /**\n * Build the read-only context passed to a classifier callback / agent\n * resolvers. No dispatch helpers — registered intents haven't fired\n * yet; pre-running them from the classifier would be confusing.\n */\n private buildClassifierContext(): ClassifierContext {\n return {\n iteration: 0,\n input: this.input,\n state: this.state,\n context: this.context,\n history: this.history,\n signal: this.options?.signal ?? new AbortController().signal,\n goal: this.goal,\n };\n }\n\n /**\n * Build the refine context — extends ClassifierContext with the\n * classifier's just-resolved output plus `run` / `stream` so the\n * refine hook can spin up secondary classifiers / validators\n * inline (Phase 6 features).\n */\n private buildClassifierRefineContext(\n base: ClassifierContext,\n raw: ClassifierOutput,\n ): ClassifierRefineContext {\n const callStack = new Set<string>();\n const reportSink = this.childReports;\n\n return {\n ...base,\n result: { data: raw },\n run: (executable, runInput, runOptions) =>\n this.runInline(executable, runInput, runOptions, callStack, reportSink),\n stream: (executable, runInput, runOptions) =>\n this.streamInline(executable, runInput, runOptions, callStack, reportSink, \"classifier\"),\n };\n }\n\n /**\n * Pull the optional `refine` hook off whichever classifier-config\n * shape was supplied. Bare-callback and bare-agent forms have no\n * refine; only entry forms do.\n */\n private resolveRefineHook(\n config: ClassifierConfig,\n ):\n | ((ctx: ClassifierRefineContext) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n | undefined {\n if (typeof config === \"function\") {\n return undefined;\n }\n\n const refine = (config as { refine?: unknown }).refine;\n\n return typeof refine === \"function\"\n ? (refine as (\n ctx: ClassifierRefineContext,\n ) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n : undefined;\n }\n\n /**\n * Interpret a refine return value into actionable bits — final\n * classifier output to dispatch, slice-to-merge, halted/refined\n * flags, or an error. See {@link ClassifierRefineResult} for the\n * accepted shapes.\n */\n private interpretRefineResult(\n refineResult: ClassifierRefineResult,\n raw: ClassifierOutput,\n ): {\n final?: ClassifierOutput;\n sliceToMerge?: Record<string, unknown>;\n refined: boolean;\n halted: boolean;\n error?: AIError;\n } {\n if (refineResult === undefined) {\n return { final: raw, refined: false, halted: false };\n }\n\n if (refineResult === END) {\n return { refined: true, halted: true };\n }\n\n if (typeof refineResult !== \"object\" || refineResult === null) {\n return {\n refined: false,\n halted: true,\n error: new SupervisorFailedError(\n `ai.supervisor(\"${this.config.name}\"): classifier.refine returned an unsupported value — expected undefined, END, or an object`,\n { context: { iteration: 0 } },\n ),\n };\n }\n\n const record = refineResult as Record<string, unknown>;\n const intentField = record.intent;\n const halted = intentField === END;\n const intentOverride = typeof intentField === \"string\" ? intentField : undefined;\n\n // Slice-to-merge is the refine return MINUS the `intent` field\n // (which is dispatch metadata, not state contribution).\n const slice: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n if (key === \"intent\") continue;\n\n slice[key] = value;\n }\n\n const final: ClassifierOutput = {\n ...raw,\n ...(intentOverride ? { intent: intentOverride } : {}),\n };\n\n return {\n final: halted ? undefined : final,\n sliceToMerge: Object.keys(slice).length > 0 ? slice : undefined,\n refined: true,\n halted,\n };\n }\n\n /**\n * Run the `evaluate` callback (when configured) after the\n * iteration's branches settle and outputs have merged into state.\n * Errors in the callback surface as `SupervisorFailedError` so a\n * buggy evaluate doesn't silently swallow the whole run.\n *\n * Phase 3.4 (Stage 4b) — `EvaluateContext.state` carries the\n * post-merge accumulator so verdicts can be state-aware. Q9\n * lifted the router-only restriction; evaluate now runs in both\n * router and route modes.\n */\n private async runEvaluate(branches: AgentBranchSnapshot[]): Promise<EvaluateResult> {\n if (!this.config.evaluate) {\n return undefined;\n }\n\n const evaluateContext: EvaluateContext = {\n iteration: this.iteration,\n input: this.input,\n state: this.state,\n result: indexBranchesForEvaluate(branches),\n iterations: this.snapshots,\n context: this.context,\n history: this.history,\n goal: this.goal,\n classifier: this.classifierSnapshot,\n };\n\n try {\n return await (\n this.config.evaluate as (ctx: EvaluateContext) => EvaluateResult | Promise<EvaluateResult>\n )(evaluateContext);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n throw new SupervisorFailedError(`evaluate callback threw: ${message}`, {\n cause: thrown,\n });\n }\n }\n\n /**\n * Merge each branch's output into supervisor `state` in\n * `decision.intents` order — Q15 conflict rule: last intent in\n * the array wins on key collisions. Errored branches don't\n * contribute. Non-object outputs (primitives, null) are skipped\n * with a warning log; they can't shallow-merge into an object.\n *\n * For agent/workflow intents: merging is opt-in via declaring an\n * `output` schema (the strip-merge gate). Without a schema, the\n * raw output stays on the branch snapshot but doesn't pollute\n * state. For callback intents: their return is already strip-merged\n * (or pass-through) inside `runCallback` — we just merge what's on\n * the branch snapshot.\n */\n private mergeBranchesIntoState(intentsOrder: string[], branches: AgentBranchSnapshot[]): void {\n const indexed = new Map<string, AgentBranchSnapshot>();\n for (const branch of branches) {\n indexed.set(branch.intent, branch);\n }\n\n const mergedKeys = new Map<string, string>();\n\n for (const intent of intentsOrder) {\n const branch = indexed.get(intent);\n if (!branch || branch.error) continue;\n\n const entry = this.entries.get(intent);\n\n // For agent/workflow intents, only merge when the slice schema\n // was declared (output present on the entry). For callbacks,\n // their output is always merged (the schema, if any, was\n // applied inside runCallback). Stream-mode agents (Phase 5 /\n // decisions §34) merge unconditionally — `applyOutputSchema`\n // already shaped their slice as `{ [streamTo]: text }`, and\n // they have no `output` schema by construction.\n const isStreamModeAgent = entry?.type === \"agent\" && entry.mode === \"stream\";\n const shouldMerge =\n entry?.type === \"callback\" || (entry && entry.output !== undefined) || isStreamModeAgent;\n\n if (!shouldMerge) continue;\n\n const slice = branch.output;\n\n if (!slice || typeof slice !== \"object\" || Array.isArray(slice)) {\n if (slice !== undefined) {\n this.logger.warn(\n this.logModule,\n \"state.merge.skip\",\n `intent \"${intent}\" output is not a mergeable object — skipping state merge`,\n { intent, type: typeof slice },\n );\n }\n continue;\n }\n\n for (const [key, value] of Object.entries(slice as Record<string, unknown>)) {\n const previousOwner = mergedKeys.get(key);\n if (previousOwner !== undefined && previousOwner !== intent) {\n this.logger.warn(\n this.logModule,\n \"state.merge.conflict\",\n `state key \"${key}\" written by both \"${previousOwner}\" and \"${intent}\" — last-in-decision-array wins (Q15)`,\n { key, previousOwner, currentIntent: intent },\n );\n }\n this.state[key] = value;\n mergedKeys.set(key, intent);\n }\n }\n }\n\n /**\n * Merge the iteration's accumulated `currentArtifacts` bag into\n * supervisor state (Phase 5 / decisions §35). Runs once per\n * iteration after branch slices land and before evaluate.\n *\n * Order of operations:\n *\n * 1. **Empty-bag fast path** — if no tool wrote anything, skip\n * validation and merge entirely; reset the bag for the next\n * iteration is also a no-op (already empty).\n * 2. **Schema validation** — when `config.artifactsSchema` is set,\n * validate the bag against it. Failure aborts the iteration via\n * a thrown `SchemaValidationError`; the iteration loop's outer\n * catch surfaces it on `result.error`. Validation is opt-in\n * (no schema → no validation cost).\n * 3. **Merge** — `config.finalizeArtifacts` when supplied, else\n * auto-spread `state = { ...state, ...artifacts }`. Replace\n * semantics under auto-spread; `finalizeArtifacts` carries\n * full responsibility for concat / dedupe / cross-iteration\n * accumulation when configured.\n * 4. **Reset** — `currentArtifacts = {}`. The next iteration's\n * tool calls start with a fresh empty bag; long runs never\n * accumulate raw artifacts here.\n */\n private async mergeArtifactsIntoState(): Promise<void> {\n const artifacts = this.currentArtifacts;\n const keys = Object.keys(artifacts);\n\n // Phase 8 / decisions §38 — capture the raw bag BEFORE validation\n // or merge so the iteration snapshot surfaces what the tools\n // actually wrote, regardless of what `finalizeArtifacts` did with\n // it. Frozen — consumers should never mutate forensic data.\n // Always run, even on empty bags — snapshot builder reads\n // `capturedIterationArtifacts` regardless.\n this.capturedIterationArtifacts = Object.freeze({ ...artifacts });\n\n if (keys.length === 0) {\n return;\n }\n\n const schema = this.config.artifactsSchema;\n\n if (schema) {\n const validation = await schema[\"~standard\"].validate(artifacts);\n\n if (validation.issues) {\n throw new SchemaValidationError(\n `supervisor \"${this.config.name}\": iteration ${this.iteration} artifacts failed validation: ${validation.issues\n .map((issue) => issue.message)\n .join(\"; \")}`,\n { issues: validation.issues, context: { iteration: this.iteration } },\n );\n }\n }\n\n const finalize = this.config.finalizeArtifacts as\n | ((\n state: Record<string, unknown>,\n artifacts: Record<string, unknown>,\n ) => Record<string, unknown>)\n | undefined;\n\n if (finalize) {\n const merged = finalize(this.state, artifacts);\n\n // Mutate in place so external references to `this.state`\n // (snapshot copies, evaluate ctx) stay coherent. Drop keys\n // the finalize callback removed; overwrite the rest.\n for (const key of Object.keys(this.state)) {\n if (!(key in merged)) {\n delete this.state[key];\n }\n }\n\n for (const [key, value] of Object.entries(merged)) {\n this.state[key] = value;\n }\n } else {\n for (const [key, value] of Object.entries(artifacts)) {\n this.state[key] = value;\n }\n }\n\n this.currentArtifacts = {};\n }\n\n /**\n * Collect each branch's `intent.next(ctx)` directive after state\n * merge (Stage 4d / Q24). Iterates `decision.intents` order so\n * union resolution is deterministic.\n *\n * Rules:\n * - Errored branch → silent (treated as if no `next` defined).\n * - Branch with no `next` → silent; abstains (does NOT drag the\n * iteration to the router).\n * - Branch returns `END` → supreme; terminates immediately and\n * discards other branches' opinions.\n * - Branch returns `string` or `string[]` → contributes to the\n * union of unique intent names. Validated against the\n * supervisor's registry; unknown keys throw `SupervisorFailedError`.\n * - All branches silent → returns `undefined`; caller falls back\n * to router/route.\n */\n private collectIntentNext(\n intentsOrder: string[],\n branches: AgentBranchSnapshot[],\n ): { kind: \"dispatch\"; intents: string[] } | { kind: \"end\" } | undefined {\n const indexed = new Map<string, AgentBranchSnapshot>();\n for (const branch of branches) {\n indexed.set(branch.intent, branch);\n }\n\n const collected: string[] = [];\n const seen = new Set<string>();\n let anySilent = false;\n\n for (const intent of intentsOrder) {\n const branch = indexed.get(intent);\n if (!branch || branch.error) {\n anySilent = true;\n continue;\n }\n\n const entry = this.entries.get(intent);\n if (!entry?.next) {\n anySilent = true;\n continue;\n }\n\n // Build a per-branch DispatchContext for the resolver. Cycle\n // stack is fresh-and-self-seeded so a `next` that calls\n // `ctx.intents.X.execute()` reuses the per-iteration cycle\n // detection mechanic.\n const dispatchCtx = this.seedDispatchContext(\n intent,\n branch.input,\n new Set<string>([intent]),\n [],\n );\n\n let raw: string | string[] | typeof END | undefined;\n try {\n raw = entry.next(dispatchCtx) as string | string[] | typeof END | undefined;\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n throw new SupervisorFailedError(`intent \"${intent}\" \\`next\\` resolver threw: ${message}`, {\n cause: thrown,\n context: { intent },\n });\n }\n\n if (raw === undefined) {\n anySilent = true;\n continue;\n }\n\n if (raw === END) {\n return { kind: \"end\" };\n }\n\n const proposed = Array.isArray(raw) ? raw : [raw];\n\n for (const target of proposed) {\n if (typeof target !== \"string\") {\n throw new SupervisorFailedError(\n `intent \"${intent}\" \\`next\\` returned a non-string value`,\n { context: { intent } },\n );\n }\n\n if (!this.entries.has(target)) {\n throw new SupervisorFailedError(\n `intent \"${intent}\" \\`next\\` returned unknown intent \"${target}\"`,\n {\n context: { intent, target, available: [...this.entries.keys()] },\n },\n );\n }\n\n if (!seen.has(target)) {\n seen.add(target);\n collected.push(target);\n }\n }\n }\n\n void anySilent;\n\n if (collected.length === 0) {\n // No branch directed the next iteration — fall back to router.\n return undefined;\n }\n\n return { kind: \"dispatch\", intents: collected };\n }\n\n /**\n * Finalize the supervisor result: validate accumulated state\n * against the output schema and build the public `SupervisorResult`.\n * Assemble-only — event emission and stream close happen in\n * `run()` around this call.\n */\n private async finalize(): Promise<SupervisorResult<TOutput>> {\n if (this.status === \"completed\" && !this.error) {\n try {\n this.data = await this.buildTypedData();\n } catch (thrown) {\n this.error = toAIError(thrown);\n this.status = \"failed\";\n this.terminatedBy = \"error\";\n }\n }\n\n const endedAt = new Date();\n\n const finalStatus: SupervisorSnapshotStatus =\n this.status === \"max-iterations\" ? \"failed\" : this.status;\n\n await this.checkpoint(finalStatus);\n\n const report: SupervisorReport = {\n runId: this.runId,\n rootRunId: this.runId,\n name: this.config.name,\n version: this.config.version,\n type: \"supervisor\",\n supervisorName: this.config.name,\n signature: this.signature,\n status: this.status,\n terminatedBy: this.terminatedBy,\n iterations: this.snapshots.length,\n startedAt: this.startedAtIso,\n endedAt: endedAt.toISOString(),\n duration: performance.now() - this.startPerf,\n cancelledAt: this.cancelledAtIso,\n usage: this.usage,\n children: this.childReports,\n snapshots: this.snapshots,\n ack: this.ackSnapshot,\n classifier: this.classifierSnapshot,\n };\n\n // Stamp lineage on the assembled tree exactly once per run.\n // Walker rewrites inner self-roots from every nested agent /\n // workflow / callback report the supervisor absorbed, propagates\n // sessionId, and writes `reportSchemaVersion` on the root.\n stampReportLineage(report, {\n rootRunId: this.runId,\n sessionId: this.options?.sessionId,\n });\n\n return {\n type: \"supervisor\",\n data: this.data,\n report,\n usage: this.usage,\n error: this.error,\n };\n }\n\n /**\n * Build the typed `data` at finalize. Stage 4c — single mode:\n *\n * - When `config.output` is declared, validate the accumulated\n * `state` against it and return the validated value (Q8).\n * `result.data` always matches the schema, or `result.error`\n * carries the validation issues.\n * - When `config.output` is omitted, return the raw state object.\n *\n * Validation failure surfaces as `SchemaValidationError` on\n * `result.error`; the run is still considered semantically\n * \"completed\" (intents ran, evaluate said done) but the typed\n * data slot is empty.\n */\n private async buildTypedData(): Promise<TOutput | undefined> {\n if (this.config.output) {\n return validateOutput<TOutput>(this.config.output, this.state as unknown);\n }\n\n return this.state as TOutput;\n }\n\n /**\n * Record a snapshot for an iteration whose first decision was\n * `END` — no dispatch, no evaluate, just the decision record. Keeps\n * the snapshot log uniform so a late-route-to-END still appears in\n * the forensic history rather than vanishing.\n */\n private async recordTerminalDecisionSnapshot(\n decision: DispatchDecision & { kind: \"end\" },\n iterationStartedAt: Date,\n iterationStart: number,\n iterationUsage: Usage,\n ): Promise<void> {\n const snapshot: IterationSnapshot = Object.freeze({\n iteration: this.iteration,\n result: {},\n decision: {\n source: decision.source,\n next: decision.raw,\n reasoning: decision.reasoning,\n durationMs: decision.durationMs,\n },\n state: { ...this.state },\n artifacts: this.capturedIterationArtifacts,\n startedAt: iterationStartedAt.toISOString(),\n endedAt: new Date().toISOString(),\n duration: performance.now() - iterationStart,\n usage: iterationUsage,\n });\n\n this.snapshots.push(snapshot);\n\n this.emit(\"supervisor.iteration.completed\", {\n iteration: this.iteration,\n snapshot,\n });\n\n await this.checkpoint(\"running\");\n }\n\n /**\n * Write the current run state to the configured KV store (if any).\n * Persistence failures surface as `supervisor.error` events and\n * logged warnings but never abort the run — checkpoint best-effort\n * by design, matching `workflow` semantics.\n */\n private async checkpoint(status: SupervisorSnapshotStatus): Promise<void> {\n const outcome = await persistSupervisorSnapshot({\n config: this.config as SupervisorConfig<unknown>,\n signature: this.signature,\n runId: this.runId,\n input: this.input,\n startedAt: this.startedAtIso,\n iteration: this.snapshots.length - 1,\n snapshots: this.snapshots,\n status,\n });\n\n if (!outcome.ok) {\n this.logger.warn(this.logModule, \"persist.failed\", \"snapshot persist failed\", {\n runId: this.runId,\n });\n }\n }\n\n /**\n * Between-iteration cancellation check. Called at the top of\n * every iteration; signal abort here means the loop exits before\n * any routing happens.\n */\n private throwIfCancelled(): void {\n if (this.options?.signal?.aborted) {\n throw createCancelledError(this.options.signal);\n }\n }\n\n /**\n * Aggregate one usage record (typically a branch or a router call)\n * into both the run-wide total and the iteration-local total.\n */\n private aggregateUsage(iterationUsage: Usage, partial?: Usage): void {\n if (!partial) {\n return;\n }\n\n this.usage.input += partial.input;\n this.usage.output += partial.output;\n this.usage.total += partial.total;\n\n iterationUsage.input += partial.input;\n iterationUsage.output += partial.output;\n iterationUsage.total += partial.total;\n }\n\n /**\n * Fan an event out through the three-tier emitter AND mirror it\n * into the stream controller when streaming. Event names map 1:1\n * to stream event types so consumers iterating the stream see the\n * exact same surface as `.on()` / `options.on` handlers.\n */\n private emit<K extends keyof SupervisorEventMap>(\n event: K,\n payload: WithoutIdentity<SupervisorEventMap[K]>,\n ): void {\n // Inject run identity once, here, so the three-tier emitter, the\n // structured log line, and the stream all see it. `rootRunId ===\n // runId` for a standalone run; nested propagation is a follow-up.\n const identity: EventIdentity = {\n runId: this.runId,\n rootRunId: this.runId,\n };\n\n const fullPayload = { ...payload, ...identity } as SupervisorEventMap[K];\n\n this.emitter.emit(event, fullPayload, this.options?.on);\n this.logEvent(event, fullPayload);\n\n if (this.streamController) {\n this.streamController.push({\n type: event,\n ...(fullPayload as object),\n } as SupervisorStreamEvent);\n }\n }\n\n private logEvent<K extends keyof import(\"../contracts/events/event-map.type\").SupervisorEventMap>(\n event: K,\n payload: import(\"../contracts/events/event-map.type\").SupervisorEventMap[K],\n ): void {\n const action = event.replace(/^supervisor\\./, \"\");\n\n switch (event) {\n case \"supervisor.starting\":\n this.logger.info(this.logModule, action, \"supervisor starting\", {\n runId: this.runId,\n });\n return;\n\n case \"supervisor.iteration.starting\":\n this.logger.debug(this.logModule, action, \"iteration starting\", {\n iteration: (payload as { iteration: number }).iteration,\n });\n return;\n\n case \"supervisor.router.decided\":\n this.logger.debug(this.logModule, action, \"router decided\", {\n iteration: (payload as { iteration: number }).iteration,\n next: (payload as { next: unknown }).next,\n });\n return;\n\n case \"supervisor.agent.completed\": {\n const typed = payload as {\n intent: string;\n duration: number;\n usage: Usage;\n };\n this.logger.success(this.logModule, action, `branch \"${typed.intent}\" done`, {\n duration: typed.duration,\n usage: typed.usage,\n });\n return;\n }\n\n case \"supervisor.agent.failed\": {\n const typed = payload as { intent: string; error: AIError };\n this.logger.warn(this.logModule, action, `branch \"${typed.intent}\" failed`, {\n code: typed.error.code,\n message: typed.error.message,\n });\n return;\n }\n\n case \"supervisor.error\": {\n const { error } = payload as { error: AIError };\n this.logger.error(this.logModule, action, error.message, {\n code: error.code,\n });\n return;\n }\n\n case \"supervisor.cancelled\": {\n const typed = payload as { cancelledAt: string; reason?: string };\n this.logger.warn(this.logModule, action, \"supervisor cancelled\", {\n cancelledAt: typed.cancelledAt,\n reason: typed.reason,\n });\n return;\n }\n\n case \"supervisor.iteration.completed\":\n this.logger.debug(this.logModule, action, \"iteration completed\", {\n iteration: (payload as { iteration: number }).iteration,\n });\n return;\n\n default:\n // Streaming / per-branch starting events are high-volume — no\n // dedicated log line.\n return;\n }\n }\n}\n\nfunction indexByIntent(branches: AgentBranchSnapshot[]): Record<string, AgentBranchSnapshot> {\n const indexed: Record<string, AgentBranchSnapshot> = {};\n\n for (const branch of branches) {\n indexed[branch.intent] = branch;\n }\n\n return indexed;\n}\n\nfunction indexBranchesForEvaluate(\n branches: AgentBranchSnapshot[],\n): Record<string, EvaluateBranchResult> {\n const indexed: Record<string, EvaluateBranchResult> = {};\n\n for (const branch of branches) {\n indexed[branch.intent] = {\n output: branch.output,\n input: branch.input,\n usage: branch.usage,\n durationMs: branch.duration,\n error: branch.error,\n };\n }\n\n return indexed;\n}\n\nfunction normalizeReassign(reassignTo: string | string[] | undefined): string[] {\n if (!reassignTo) {\n return [];\n }\n\n if (Array.isArray(reassignTo)) {\n return reassignTo;\n }\n\n return [reassignTo];\n}\n\nfunction toAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return new SupervisorFailedError(message, { cause: thrown });\n}\n\n/**\n * Sum a list of child `BaseReport.usage` values. Callbacks\n * themselves contribute zero own-cost (they're dev code, not LLM\n * calls); their report's `usage` equals the sum of whatever\n * agents / workflows / nested callbacks they dispatched via\n * `ctx.intents.X.execute()`. Mirrors `compositeAsTool` semantics.\n */\nfunction aggregateChildUsage(children: BaseReport[]): Usage {\n return children.reduce<Usage>(\n (acc, child) => ({\n input: acc.input + child.usage.input,\n output: acc.output + child.usage.output,\n total: acc.total + child.usage.total,\n }),\n { input: 0, output: 0, total: 0 },\n );\n}\n\n/**\n * Best-effort stringification for the snapshot's `input` field when\n * a callback intent's resolved input is a non-string value. Falls\n * back to a typed placeholder if `JSON.stringify` throws (circular\n * refs, BigInt, etc.) so a snapshot write never fails on its own.\n */\nfunction safeStringify(value: unknown): string {\n if (value === undefined) {\n return \"undefined\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return `[unserializable: ${typeof value}]`;\n }\n}\n\nasync function validateOutput<TOutput>(\n schema: StandardSchemaV1<TOutput>,\n value: unknown,\n): Promise<TOutput> {\n const validation = await schema[\"~standard\"].validate(value);\n\n if (validation.issues) {\n throw new SchemaValidationError(validation.issues.map((issue) => issue.message).join(\"; \"), {\n issues: validation.issues,\n });\n }\n\n return validation.value;\n}\n","import { ClassifierAgentEntry, ClassifierRunEntry } from \"../contracts\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { ResolvedIntentEntry } from \"./entries\";\n\n/**\n * Deterministic structural fingerprint of a supervisor definition.\n * Persisted on every snapshot so `resume()` can detect drift between\n * the saved run and the current definition. Covers:\n *\n * - Supervisor name.\n * - Every intent key + its resolved description + the underlying\n * unit's stable identity (agent name, workflow name + signature,\n * or `\"callback\"` marker for dev-callback intents).\n * - Router agent's name (if the supervisor uses LLM routing).\n * - Whether a deterministic `route` callback is configured (but not\n * its contents — route callbacks are code, not data).\n * - Whether an `evaluate` callback is configured.\n * - `initialAgent` when set.\n * - `maxIterations` (a semantic shape change, not a cosmetic one).\n *\n * Does NOT cover: system prompt text, logger, store identity, per-\n * event handlers — all runtime knobs that don't change the shape of\n * a resumable run.\n */\nexport function computeSignature(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): string {\n const intentsFingerprint = [...entries.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([intent, entry]) => ({\n k: intent,\n d: entry.description,\n u: fingerprintUnit(entry),\n }));\n\n const fingerprint = {\n n: config.name,\n a: intentsFingerprint,\n r: resolveRouterName(config.router),\n rc: config.route ? 1 : 0,\n e: config.evaluate ? 1 : 0,\n i: config.initialAgent ?? null,\n m: config.maxIterations ?? null,\n // Phase 7 / decisions §37 — classifier is part of structural identity.\n // Resume drift detection notices when the classifier swap changes\n // routing semantics. Same fingerprint shape as router (agent name\n // when applicable; \"callback\" marker for callback form).\n c: resolveClassifierFingerprint(config.classifier),\n };\n\n return hash(JSON.stringify(fingerprint));\n}\n\nfunction resolveRouterName(router: SupervisorConfig<unknown>[\"router\"]): string | null {\n if (!router) {\n return null;\n }\n\n if (typeof (router as { execute?: unknown }).execute === \"function\") {\n return (router as { name?: string }).name ?? null;\n }\n\n return (router as { agent?: { name?: string } }).agent?.name ?? null;\n}\n\nfunction resolveClassifierFingerprint(\n classifier: SupervisorConfig<unknown>[\"classifier\"],\n): unknown {\n if (!classifier) {\n return null;\n }\n\n if (typeof classifier === \"function\") {\n return { t: \"callback\" };\n }\n\n if (typeof (classifier as { execute?: unknown }).execute === \"function\") {\n return { t: \"agent\", n: (classifier as { name?: string }).name ?? null };\n }\n\n if (typeof (classifier as ClassifierRunEntry).run === \"function\") {\n return { t: \"callback\" };\n }\n\n if (typeof (classifier as ClassifierAgentEntry).agent?.execute === \"function\") {\n return {\n t: \"agent\",\n n: (classifier as ClassifierAgentEntry).agent?.name ?? null,\n };\n }\n\n return { t: \"unknown\" };\n}\n\nfunction fingerprintUnit(entry: ResolvedIntentEntry): unknown {\n if (entry.type === \"callback\") {\n // Callbacks are dev code — fingerprint the type + intent name\n // only (the closure itself can't be hashed deterministically).\n // Drift detection covers add/remove/rename of callback intents,\n // not edits to the function body. Same trade-off as `route`.\n return { t: \"callback\" };\n }\n\n if (entry.type === \"workflow\") {\n const workflow = entry.unit;\n return { t: \"workflow\", n: workflow.name, s: workflow.signature };\n }\n\n return { t: \"agent\", n: entry.unit.name };\n}\n\n/**\n * FNV-1a 32-bit — same hash `workflow/signature.ts` uses. Deterministic,\n * no crypto dependency, cheap; signatures are 8-char hex.\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","import type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type { SupervisorStreamEvent } from \"../contracts/supervisor/supervisor-stream-event.type\";\n\n// Re-export so internal callers that already imported from this file\n// keep working unchanged. Canonical home is the contracts barrel.\nexport type { SupervisorStreamEvent };\n\n/**\n * Internal async-queue controller driving `supervisor.stream()`.\n * Mirrors `StreamController` from `agent-stream.ts` — same\n * producer/consumer pipe, same semantics, parameterized by the\n * supervisor event union and terminal result type.\n */\nexport type SupervisorStreamController<TResult> = {\n push(event: SupervisorStreamEvent): void;\n end(result: TResult): void;\n fail(error: Error): void;\n};\n\ntype PendingRead = {\n resolve(value: IteratorResult<SupervisorStreamEvent>): void;\n reject(error: Error): void;\n};\n\n/**\n * Factory mirroring `createAgentStream`. Returns a paired\n * `{ controller, stream }` — the `SupervisorExecution` pushes events\n * into the controller while the caller iterates (or awaits `.result`)\n * on the stream side. See `agent-stream.ts` for the full role\n * description.\n */\nexport function createSupervisorStream<TResult>(): {\n controller: SupervisorStreamController<TResult>;\n stream: StreamContract<TResult, SupervisorStreamEvent>;\n} {\n const queue: SupervisorStreamEvent[] = [];\n const pending: PendingRead[] = [];\n const handlers = new Map<string, (event: SupervisorStreamEvent) => void>();\n\n let closed = false;\n let failure: Error | undefined;\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const controller: SupervisorStreamController<TResult> = {\n push(event) {\n const handler = handlers.get(event.type);\n\n if (handler) {\n try {\n handler(event);\n } catch {\n // Stream handlers must never crash the supervisor.\n }\n }\n\n const reader = pending.shift();\n\n if (reader) {\n reader.resolve({ value: event, done: false });\n return;\n }\n\n queue.push(event);\n },\n\n end(finalResult) {\n closed = true;\n resolveResult(finalResult);\n\n while (pending.length > 0) {\n pending.shift()?.resolve({ value: undefined, done: true });\n }\n },\n\n fail(error) {\n closed = true;\n failure = error;\n rejectResult(error);\n\n while (pending.length > 0) {\n pending.shift()?.reject(error);\n }\n },\n };\n\n const iterator: AsyncIterator<SupervisorStreamEvent> = {\n next() {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (closed) {\n if (failure) {\n return Promise.reject(failure);\n }\n\n return Promise.resolve({ value: undefined, done: true });\n }\n\n return new Promise<IteratorResult<SupervisorStreamEvent>>(\n (resolve, reject) => {\n pending.push({ resolve, reject });\n },\n );\n },\n };\n\n // The `StreamContract<TResult>` shape is shared across primitives —\n // it types `on()` over the generic `StreamEvent` union (agent\n // events). Supervisor events are a distinct discriminated union\n // with the same `type`-keyed shape, so we satisfy the contract via\n // a structural cast — handlers see the supervisor events at their\n // correct narrowed types.\n const stream = {\n result,\n on(handlerMap) {\n for (const [key, handler] of Object.entries(handlerMap)) {\n if (handler) {\n handlers.set(key, handler as (event: SupervisorStreamEvent) => void);\n }\n }\n\n return stream;\n },\n [Symbol.asyncIterator]() {\n return iterator;\n },\n } as StreamContract<TResult, SupervisorStreamEvent>;\n\n return { controller, stream };\n}\n","import type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type { SupervisorResult } from \"../contracts/result/supervisor-result.type\";\nimport type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type { SupervisorIntentValue } from \"../contracts/supervisor/intent-entry.type\";\nimport type {\n SupervisorConfig,\n SupervisorEventHandler,\n} from \"../contracts/supervisor/supervisor-config.type\";\nimport type {\n SupervisorExecuteOptions,\n SupervisorResumeOptions,\n} from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type { SupervisorStreamEvent } from \"../contracts/supervisor/supervisor-stream-event.type\";\nimport type {\n SupervisorAsToolOptions,\n SupervisorContract,\n} from \"../contracts/supervisor/supervisor.contract\";\nimport { SupervisorFailedError } from \"../errors\";\nimport type { ToolContract } from \"../tool/tool\";\nimport { asTool } from \"./as-tool\";\nimport { SupervisorEmitter } from \"./emitter\";\nimport { assertRouterDescriptions, resolveIntentEntries } from \"./entries\";\nimport { SupervisorExecution } from \"./execution\";\nimport { computeSignature } from \"./signature\";\nimport { loadSnapshotForResume } from \"./snapshot\";\nimport { createSupervisorStream } from \"./supervisor-stream\";\n\n/**\n * `ai.supervisor(config)` — construct a `SupervisorContract`. Validates\n * the config at author time (throws `SupervisorFailedError` on bad\n * shape), resolves agent entries, computes a stable structural\n * signature, wires the three-tier event emitter, and returns an\n * instance that satisfies `ExecutableContract` so it can compose into\n * tools, outer agents, and (future) orchestrators uniformly.\n *\n * @example\n * const support = ai.supervisor({\n * name: \"customer-support\",\n * router: routerAgent,\n * intents: { triage, orderLookup, billingLookup, resolver },\n * evaluate: (ctx) => ctx.result.resolver?.output ? { satisfied: true } : undefined,\n * output: z.object({ response: z.string(), refund: z.boolean() }),\n * maxIterations: 6,\n * });\n */\nexport function supervisor<\n TOutput = unknown,\n TState = TOutput,\n TIntents extends Record<string, SupervisorIntentValue> = Record<string, SupervisorIntentValue>,\n TArtifacts = Record<string, unknown>,\n>(config: SupervisorConfig<TOutput, TState, TIntents, TArtifacts>): SupervisorContract<TOutput> {\n validateFactoryConfig(config as unknown as SupervisorConfig<TOutput>);\n\n const entries = resolveIntentEntries(config.intents, config.name);\n\n assertRouterDescriptions(config as SupervisorConfig<unknown>, entries);\n\n if (config.initialAgent && !entries.has(config.initialAgent)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`initialAgent\\` \"${config.initialAgent}\" is not a key in \\`intents\\``,\n { context: { authoring: true } },\n );\n }\n\n const signature = computeSignature(config as SupervisorConfig<unknown>, entries);\n const emitter = new SupervisorEmitter(config.on);\n\n async function execute(\n input: SupervisorInput,\n options?: SupervisorExecuteOptions,\n ): Promise<SupervisorResult<TOutput>> {\n const runId = options?.runId ?? generateRunId();\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input,\n runId,\n options,\n });\n\n return execution.run();\n }\n\n function stream(\n input: SupervisorInput,\n options?: SupervisorExecuteOptions,\n ): StreamContract<SupervisorResult<TOutput>, SupervisorStreamEvent> {\n const runId = options?.runId ?? generateRunId();\n const { controller, stream: contract } = createSupervisorStream<SupervisorResult<TOutput>>();\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input,\n runId,\n options,\n streamController: controller,\n });\n\n void execution.run();\n\n return contract;\n }\n\n async function resume(\n runId: string,\n options?: SupervisorResumeOptions,\n ): Promise<SupervisorResult<TOutput>> {\n const snapshot = await loadSnapshotForResume({\n config: config as SupervisorConfig<unknown>,\n signature,\n runId,\n options,\n });\n\n const execution = new SupervisorExecution<TOutput>({\n config: config as unknown as SupervisorConfig<TOutput>,\n entries,\n signature,\n emitter,\n input: snapshot.input,\n runId,\n options,\n resumeFrom: snapshot,\n });\n\n return execution.run();\n }\n\n const instance: SupervisorContract<TOutput> = {\n name: config.name,\n signature,\n execute,\n stream,\n resume,\n on<K extends keyof SupervisorEventMap>(\n event: K,\n handler: SupervisorEventHandler<K>,\n ): () => void {\n return emitter.on(event, handler);\n },\n off<K extends keyof SupervisorEventMap>(event: K, handler: SupervisorEventHandler<K>): void {\n emitter.off(event, handler);\n },\n asTool<TToolInput = string>(\n options: SupervisorAsToolOptions<TToolInput>,\n ): ToolContract<TToolInput, TOutput> {\n return asTool<TOutput, TToolInput>(instance, options);\n },\n };\n\n return instance;\n}\n\n/**\n * Factory-time validation. Enforces the XOR + pairing rules the design\n * locked in §2 and surfaces any violation as a typed\n * `SupervisorFailedError` tagged `authoring: true`.\n */\nfunction validateFactoryConfig<T>(config: SupervisorConfig<T>): void {\n if (!config.name || typeof config.name !== \"string\") {\n throw new SupervisorFailedError(\"ai.supervisor: `name` is required and must be a string\", {\n context: { authoring: true },\n });\n }\n\n if (!config.intents || typeof config.intents !== \"object\") {\n throw new SupervisorFailedError(`ai.supervisor(\"${config.name}\"): \\`intents\\` is required`, {\n context: { authoring: true },\n });\n }\n\n const hasRoute = typeof config.route === \"function\";\n const hasRouter = !!config.router;\n\n if (hasRouter) {\n const router = config.router as { execute?: unknown } | { agent?: { execute?: unknown } };\n const isBareAgent = typeof (router as { execute?: unknown }).execute === \"function\";\n const isEntryForm =\n !isBareAgent &&\n typeof (router as { agent?: { execute?: unknown } }).agent === \"object\" &&\n typeof (router as { agent?: { execute?: unknown } }).agent?.execute === \"function\";\n\n if (!isBareAgent && !isEntryForm) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`router\\` must be an agent contract or a \\`{ agent, placeholders?, input? }\\` entry`,\n { context: { authoring: true } },\n );\n }\n }\n\n if (hasRoute && hasRouter) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`route\\` and \\`router\\` are mutually exclusive — configure exactly one`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 7 / decisions §37 — `classifier` is the iter-0 prelude;\n // satisfies the \"must have a dispatch source\" rule on its own.\n // Composes with router/route (classifier drives iter 0; router/route\n // takes iter 1+). When configured alone, supervisor terminates after\n // iter 0's branch settles.\n const hasClassifier = config.classifier !== undefined;\n\n if (!hasRoute && !hasRouter && !hasClassifier) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): one of \\`route\\`, \\`router\\`, or \\`classifier\\` is required`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 7 — classifier and initialAgent both decide what runs first.\n // Coexistence is meaningless; throw loudly.\n if (hasClassifier && config.initialAgent) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`classifier\\` and \\`initialAgent\\` are mutually exclusive — both decide which intent runs first. Pick one.`,\n { context: { authoring: true } },\n );\n }\n\n // Phase 3.4 (Q9) — evaluate now pairs with both `route` and\n // `router`. State-driven termination is useful in either dispatch\n // mode; the historical router-only restriction was incidental,\n // not principled.\n\n if (config.ack !== undefined) {\n const ack = config.ack;\n const isCallback = typeof ack === \"function\";\n const isAgentEntry =\n typeof ack === \"object\" &&\n ack !== null &&\n typeof (ack as { agent?: { execute?: unknown } }).agent?.execute === \"function\";\n const isRunEntry =\n typeof ack === \"object\" &&\n ack !== null &&\n typeof (ack as { run?: unknown }).run === \"function\";\n\n if (!isCallback && !isAgentEntry && !isRunEntry) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`ack\\` must be an \\`{ agent, ... }\\` entry, an \\`{ run, ... }\\` entry, or a bare callback function`,\n { context: { authoring: true } },\n );\n }\n\n if (isAgentEntry && isRunEntry) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`ack\\` cannot declare both \\`agent\\` and \\`run\\` — pick one`,\n { context: { authoring: true } },\n );\n }\n }\n\n if (config.maxIterations !== undefined && config.maxIterations < 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): \\`maxIterations\\` must be >= 1`,\n { context: { authoring: true, maxIterations: config.maxIterations } },\n );\n }\n}\n\nfunction generateRunId(): string {\n return `sup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * Render a template string against a placeholders map, supporting dot-path\n * lookups and inline fallback values.\n *\n * Supported syntax:\n * - `{{key}}` — replaced by `placeholders.key`, left untouched if missing.\n * - `{{a.b.c}}` — dot-path lookup into nested objects.\n * - `{{key|default}}` — substitutes `default` when the key resolves to\n * `undefined`, `null`, or empty string.\n *\n * Whitespace inside the braces is ignored (`{{ key }}` == `{{key}}`).\n * Values are coerced to strings via `String(value)`.\n *\n * @example\n * renderPlaceholders(\n * \"Hello {{user.name|friend}}, your role is {{role}}\",\n * { user: { name: \"Hasan\" }, role: \"admin\" },\n * );\n * // \"Hello Hasan, your role is admin\"\n *\n * @example\n * renderPlaceholders(\"Hello {{user.name|friend}}\", {});\n * // \"Hello friend\"\n */\nexport function renderPlaceholders(\n template: string,\n placeholders: Placeholders = {},\n): string {\n return template.replace(\n PLACEHOLDER_PATTERN,\n (match, rawExpression: string) => {\n const [rawPath, rawFallback] = rawExpression.split(\"|\");\n const path = rawPath.trim();\n const fallback = rawFallback?.trim();\n\n const value = lookupPath(placeholders, path);\n\n if (value === undefined || value === null || value === \"\") {\n if (fallback !== undefined) {\n return fallback;\n }\n\n return match;\n }\n\n return String(value);\n },\n );\n}\n\n/**\n * Walk a dot-path (`\"a.b.c\"`) through an arbitrary record, returning the\n * leaf value or `undefined` when any segment is missing or blocks traversal\n * (non-object). Never throws.\n */\nfunction lookupPath(source: Placeholders, path: string): unknown {\n const segments = path.split(\".\");\n let current: unknown = source;\n\n for (const segment of segments) {\n if (current === null || current === undefined) {\n return undefined;\n }\n\n if (typeof current !== \"object\") {\n return undefined;\n }\n\n current = (current as Record<string, unknown>)[segment];\n }\n\n return current;\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type { InstructionContract } from \"../contracts/system-prompt.contract\";\nimport { renderPlaceholders } from \"./render-placeholders\";\n\n/**\n * Concrete `InstructionContract` — a reusable directive block.\n *\n * **Role.** A single addressable prompt block representing one rule the\n * agent must follow (`\"Always respond in {{language|English}}.\"`). Exists\n * as its own type so the same instruction can be shared across many\n * prompts and agents, each render supplying its own placeholder map.\n *\n * **Responsibility.**\n * - Owns: the `type: \"instruction\"` discriminator, the raw template text,\n * and the placeholder-rendering step.\n * - Does NOT own: ordering relative to other instructions, joining with a\n * persona, or any surrounding prompt composition — those concerns live\n * in `SystemPrompt`.\n *\n * Users construct via the `ai.instruction()` factory — `new Instruction()`\n * is not the public API (see §4.2 of code-style.md).\n *\n * @example\n * const replyInLanguage = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt()\n * .persona(\"You are Alex.\")\n * .instruction(replyInLanguage)\n * .instruction(\"Always include code examples.\");\n */\nexport class Instruction implements InstructionContract {\n public readonly type = \"instruction\" as const;\n\n public constructor(public readonly text: string) {\n //\n }\n\n /**\n * Substitute `{{mustache}}` placeholders in the instruction text against\n * the supplied map. Delegates to the shared `renderPlaceholders` helper\n * so persona / instruction / system-prompt rendering stays identical.\n */\n public resolve(placeholders?: Placeholders): string {\n return renderPlaceholders(this.text, placeholders);\n }\n}\n\n/**\n * Create an `Instruction` from raw template text.\n *\n * @example\n * const replyIn = instruction(\"Respond in {{language|English}}.\");\n * const cite = instruction(\"Always cite sources inline.\");\n */\nexport function instruction(text: string): Instruction {\n return new Instruction(text);\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type { PersonaContract } from \"../contracts/system-prompt.contract\";\nimport { renderPlaceholders } from \"./render-placeholders\";\n\n/**\n * Concrete `PersonaContract` — a reusable \"who the agent is\" block.\n *\n * **Role.** A single addressable prompt block representing the agent's\n * identity (`\"You are Alex, a senior TypeScript engineer.\"`). Exists as\n * its own type so personas can be defined once and reused across many\n * `SystemPrompt` compositions, agents, and sessions — each render can\n * supply a different placeholder map.\n *\n * **Responsibility.**\n * - Owns: the `type: \"persona\"` discriminator, the raw template text, and\n * the placeholder-rendering step.\n * - Does NOT own: composition with instructions, ordering, joining, or\n * any knowledge of the surrounding `SystemPrompt`. Those concerns live\n * in `SystemPrompt`.\n *\n * Users construct via the `ai.persona()` factory — `new Persona()` is not\n * the public API (see §4.2 of code-style.md).\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n *\n * const prompt = ai.systemPrompt()\n * .persona(alex)\n * .instruction(\"Always cite sources.\");\n */\nexport class Persona implements PersonaContract {\n public readonly type = \"persona\" as const;\n\n public constructor(public readonly text: string) {\n //\n }\n\n /**\n * Substitute `{{mustache}}` placeholders in the persona text against the\n * supplied map. Delegates to the shared `renderPlaceholders` helper so\n * persona / instruction / system-prompt rendering stays identical.\n */\n public resolve(placeholders?: Placeholders): string {\n return renderPlaceholders(this.text, placeholders);\n }\n}\n\n/**\n * Create a `Persona` from raw template text.\n *\n * @example\n * const alex = persona(\"You are Alex, a TypeScript expert.\");\n * const greeter = persona(\"You are a greeter in {{language|English}}.\");\n */\nexport function persona(text: string): Persona {\n return new Persona(text);\n}\n","import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type {\n InstructionContract,\n PersonaContract,\n SystemPromptBlockContract,\n SystemPromptContract,\n} from \"../contracts/system-prompt.contract\";\nimport { Instruction } from \"./instruction\";\nimport { Persona } from \"./persona\";\n\n/**\n * Concrete `SystemPromptContract` — an immutable layered prompt builder.\n *\n * **Role.** The top-level composer for a system prompt: it holds an ordered\n * list of typed blocks (persona + instructions) and resolves the whole\n * stack into one final string when the agent is about to call the model.\n *\n * **Responsibility.**\n * - Owns: the ordered `blocks` list and the block-join rules (insertion\n * order, blank-line separator, trim).\n * - Does NOT own: how any individual block is rendered (delegated to each\n * block's `resolve()`), the placeholder syntax (delegated to\n * `renderPlaceholders`), or any knowledge of the agent, model, or\n * session consuming the resolved text.\n *\n * Blocks are discriminated by a string `type` tag (`\"persona\"` /\n * `\"instruction\"`) rather than `instanceof`, so user-supplied blocks that\n * implement `SystemPromptBlockContract` interoperate seamlessly with blocks\n * built via `ai.persona()` / `ai.instruction()` — even across duplicate\n * package copies or bundler scope boundaries.\n *\n * The builder is **immutable** — every `.persona()` / `.instruction()`\n * call returns a fresh `SystemPrompt` instance sharing nothing mutable\n * with its parent. This makes forking a base prompt into specialized\n * variants a safe, side-effect-free operation.\n *\n * Users construct via the `ai.systemPrompt()` factory — `new SystemPrompt()`\n * is not the public API (see §4.2 of code-style.md). Modeled as a class so\n * that methods live on the prototype (one copy shared across every forked\n * instance) and downstream code can branch via `instanceof SystemPrompt`.\n *\n * @example\n * // Chainable form\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const base = ai.systemPrompt().persona(alex).instruction(replyIn);\n * const arabicVariant = base.instruction(\"Prefer Arabic comments.\");\n *\n * base.resolve({ language: \"English\" });\n * arabicVariant.resolve({ language: \"Arabic\" });\n *\n * @example\n * // Array form — insertion order is preserved exactly\n * const prompt = ai.systemPrompt([\n * ai.persona(\"You are Alex, a TypeScript expert.\"),\n * ai.instruction(\"Respond in {{language|English}}.\"),\n * ]);\n */\nexport class SystemPrompt implements SystemPromptContract {\n public constructor(\n public readonly blocks: readonly SystemPromptBlockContract[] = [],\n ) {}\n\n /**\n * Return a new builder with the persona block set. If a persona already\n * exists it's replaced in place (preserving its position in `blocks`);\n * otherwise the new persona is prepended so persona-first remains the\n * default for chain-built prompts. Accepts either raw text (auto-wrapped\n * via `new Persona`) or an existing `PersonaContract` instance for reuse\n * across prompts.\n */\n public persona(value: PersonaContract | string): SystemPromptContract {\n const block = typeof value === \"string\" ? new Persona(value) : value;\n const existingIndex = this.blocks.findIndex(\n candidate => candidate.type === \"persona\",\n );\n\n if (existingIndex >= 0) {\n const next = [...this.blocks];\n next[existingIndex] = block;\n\n return new SystemPrompt(next) as this;\n }\n\n return new SystemPrompt([block, ...this.blocks]);\n }\n\n /**\n * Return a new builder with the given instruction appended. Instructions\n * render in insertion order. Accepts either raw text (auto-wrapped via\n * `new Instruction`) or an existing `InstructionContract` instance for\n * cross-prompt reuse.\n */\n public instruction(\n value: InstructionContract | string,\n ): SystemPromptContract {\n const block = typeof value === \"string\" ? new Instruction(value) : value;\n\n return new SystemPrompt([...this.blocks, block]);\n }\n\n /**\n * Resolve every block against the placeholder map, join the results with\n * blank-line separators (in insertion order), and trim. Returns an empty\n * string when no blocks are present — callers treat that as \"no system\n * message\".\n */\n public resolve(placeholders?: Placeholders): string {\n return this.blocks\n .map(block => block.resolve(placeholders))\n .join(\"\\n\\n\")\n .trim();\n }\n}\n\n/**\n * Create a new immutable system-prompt builder.\n *\n * **Role.** Public factory for `SystemPrompt` — keeps user-facing code\n * free of `new` and consistent with `ai.tool()`, `ai.agent()`,\n * `ai.persona()`, `ai.instruction()`.\n *\n * Three input forms:\n * - No argument → empty builder, chain `.persona()` / `.instruction()`\n * - Single string → seeded with one instruction for quick one-shot prompts\n * - Array of blocks → used verbatim, preserving insertion order\n *\n * @example\n * // Composed builder\n * const prompt = systemPrompt()\n * .persona(\"You are Alex, a senior TypeScript engineer.\")\n * .instruction(\"Always include working code examples.\")\n * .instruction(\"Respond in {{language|English}}.\");\n *\n * prompt.resolve({ language: \"Arabic\" });\n *\n * @example\n * // One-shot seed\n * const prompt = systemPrompt(\"Answer only with JSON matching the schema.\");\n *\n * @example\n * // Array form — fully declarative\n * const prompt = systemPrompt([\n * ai.persona(\"You are Alex.\"),\n * ai.instruction(\"Always cite sources.\"),\n * ai.instruction(\"Respond in {{language|English}}.\"),\n * ]);\n */\nexport function systemPrompt(\n input?: string | ReadonlyArray<SystemPromptBlockContract>,\n): SystemPrompt {\n if (input === undefined) {\n return new SystemPrompt();\n }\n\n if (typeof input === \"string\") {\n return new SystemPrompt([new Instruction(input)]);\n }\n\n return new SystemPrompt([...input]);\n}\n","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","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { WorkflowError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"../tool/tool\";\n\n/**\n * Wrap a `WorkflowInstance` as a `ToolContract` so an agent can invoke\n * it inside its tool-call loop. Closes the agent-calls-workflow\n * composition gap.\n *\n * Behavior:\n * - Tool `name` mirrors `workflow.name` — workflows without a name throw\n * `WorkflowError` at wrap time (the agent surface needs a stable id).\n * - Tool `input` is the supplied `inputSchema`; the validated value is\n * forwarded straight to `workflow.execute(input)`.\n * - On `result.error`, the workflow error is wrapped in\n * `ToolExecutionError` with `cause` set to the original\n * `WorkflowError` subclass — the agent's tool-call loop sees a\n * uniform error class regardless of which primitive failed.\n *\n * **Usage caveat (deferred to Phase 2):** the parent agent's\n * `result.usage` does NOT roll up tokens consumed inside the wrapped\n * workflow today. Nested-usage standardization lands with the\n * supervisor work; until then, sum workflow + agent usage manually if\n * you need a combined cost figure.\n *\n * @example\n * const wf = workflow({ name: \"triage\", steps: [...] });\n * const triageTool = asTool(wf, {\n * description: \"Run the support-ticket triage flow\",\n * inputSchema: ticketSchema,\n * });\n * const a = ai.agent({ model, tools: [triageTool] });\n */\nexport function asTool<TInput, TOutput, TToolInput = TInput>(\n workflowInstance: WorkflowInstance<TInput, TOutput>,\n options: {\n description?: string;\n inputSchema: StandardSchemaV1<TToolInput>;\n },\n): ToolContract<TToolInput, TOutput> {\n if (!workflowInstance.name || typeof workflowInstance.name !== \"string\") {\n throw new WorkflowError(\n \"workflow.asTool(): workflow must have a `name` to be wrapped as a tool\",\n );\n }\n\n return compositeAsTool<TToolInput, TOutput>({\n name: workflowInstance.name,\n description: options.description ?? `Invoke workflow \"${workflowInstance.name}\" as a tool.`,\n input: options.inputSchema,\n execute: async (input) => {\n const result = await workflowInstance.execute(input as unknown as TInput);\n\n if (result.error) {\n // Throw the workflow error so the surrounding wrapper catches\n // it and produces a `ToolExecutionError` with `cause` pointing\n // back at the original `WorkflowError` subclass — keeps the\n // agent's tool-call loop seeing one uniform error class\n // regardless of which primitive failed.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage,\n report: result.report,\n };\n },\n });\n}\n","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","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","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","import type { EventIdentity } from \"../contracts/events/event-identity.type\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type { WorkflowEventHandlers } from \"../contracts/workflow/workflow.contract\";\nimport type { WorkflowEmitter, WorkflowEventSink } from \"./emitter\";\n\n/**\n * Bind a factory-scoped `WorkflowEmitter` to one run's identity.\n *\n * The engine and step-runner emit bare payloads through this sink;\n * it injects `runId` / `rootRunId` once and delegates to the real\n * three-tier emitter. This is the single place workflow run identity\n * is stamped — the alternative (editing every `emitter.emit` call\n * site) would be ~15 scattered edits and easy to miss one.\n *\n * `rootRunId === runId` for a standalone run; nested propagation\n * (a child workflow inheriting an outer run's root) lands in a\n * follow-up.\n *\n * @example\n * // Inside runWorkflow(), once per execution:\n * const emitter = runScopedEmitter(params.emitter, { runId, rootRunId: runId });\n * emitter.emit(\"workflow.starting\", { workflowName, input }, executionHandlers);\n */\nexport function runScopedEmitter(\n emitter: WorkflowEmitter,\n identity: EventIdentity,\n): WorkflowEventSink {\n return {\n emit(event, payload, executionHandlers?: WorkflowEventHandlers) {\n const fullPayload = {\n ...payload,\n ...identity,\n } as WorkflowEventMap[typeof event];\n\n emitter.emit(event, fullPayload, executionHandlers);\n },\n };\n}\n","import { resolveDefaultStore } from \"../config\";\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 snapshot store: the workflow's own\n * `snapshotStore` field wins; absent that, fall back to the global\n * default set via `ai.config({ defaultStore })`.\n */\nfunction resolveSnapshotStore<T>(definition: WorkflowDefinition<any, T, any, any>) {\n return definition.snapshotStore ?? resolveDefaultStore();\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.set(params.runId, 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({ defaultStore })\\` at boot before calling resume()`,\n );\n }\n\n const snap = (await store.get<WorkflowSnapshot>(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","import { WorkflowError } from \"../errors\";\n\n/**\n * Deep-clone workflow state. Uses `structuredClone` — handles Date,\n * Map, Set, ArrayBuffer, nested objects, arrays, primitives. Throws\n * a typed `WorkflowError` on older runtimes (pre-Node-17) rather\n * than silently falling back to a JSON round-trip that would drop\n * non-serializable values like Dates without warning.\n *\n * Workflow state should stay serializable anyway (it round-trips\n * through `KVStore` on every checkpoint). If `structuredClone` chokes\n * on a value, that's a bug in the user's state — surface it.\n */\nexport function cloneState<T>(value: T): T {\n if (typeof structuredClone !== \"function\") {\n throw new WorkflowError(\n \"workflow state cloning requires `structuredClone` (Node 17+ or a modern browser)\",\n );\n }\n\n return structuredClone(value);\n}\n\n/**\n * Recursively freeze `value` and every nested plain object / array so\n * consumers of `ctx.steps[x].state` or `report.state` can't mutate\n * historical snapshots. Already-frozen values are skipped.\n */\nexport function deepFreeze<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n if (Object.isFrozen(value)) return value;\n\n for (const key of Object.keys(value as Record<string, unknown>)) {\n const child = (value as Record<string, unknown>)[key];\n if (child && typeof child === \"object\") deepFreeze(child);\n }\n\n return Object.freeze(value);\n}\n","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","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 { 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 {\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 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\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\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 agentInput = step.input\n ? await step.input(params.buildContext({ state: attemptState }))\n : { prompt: \"\" };\n\n const { prompt, ...agentOpts } = agentInput;\n\n const result = await step.agent.execute(prompt, {\n ...agentOpts,\n signal,\n });\n\n executionResult = result;\n\n if (result.usage) {\n params.usage.input += result.usage.input ?? 0;\n params.usage.output += result.usage.output ?? 0;\n params.usage.total += result.usage.total ?? 0;\n }\n\n if (result.error) throw result.error;\n } else if (step.run) {\n executionResult = await step.run(params.buildContext({ state: attemptState }));\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 };\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 };\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 });\n\n Object.assign(sharedState, snap.state);\n return { child, snap };\n }),\n );\n\n for (const { child, snap } of results) {\n childSnapshots[child.name] = finalizeSnapshot(snap);\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 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","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 });\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 ran one.\n // Today the step runner surfaces agent reports (the only executable\n // kind steps can invoke natively via `step.agent`); custom `run`\n // callbacks that call tools/workflows/supervisors can't be observed\n // here without a richer step-runner API — that's a v1.x follow-up\n // (see backlog: \"step.run executables surface in workflow tree\").\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 }\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 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","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","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.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 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 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 return 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\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 return 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\n const instance: WorkflowInstance<TInput, TOutput, TState, TContext> = {\n name: definition.name,\n description: definition.description,\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","import { agent } from \"./agent/agent\";\nimport { setAIConfig } from \"./config\";\nimport { budget } from \"./middleware/builtins/budget\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n },\n};\n","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 { MockModelResponse } from \"./mock-config.type\";\n\ntype RecordedCall = {\n messages: Message[];\n options?: ModelCallOptions;\n};\n\n/**\n * Deterministic in-memory `ModelContract` implementation for tests.\n *\n * **Role.** Stands in for a real provider model so agent/workflow/supervisor\n * tests can assert behavior without hitting the network, spending tokens, or\n * depending on non-deterministic LLM output.\n *\n * **Responsibility.**\n * - Owns: a scripted queue of `MockModelResponse` entries, a call-history\n * log for assertions, and the index pointer that advances through the\n * queue on each `complete()` / `stream()` call.\n * - Does NOT own: any real inference, tokenization, or network I/O — when\n * the queue is exhausted, the final entry is reused so tests never crash\n * on accidental over-consumption.\n *\n * Every AI-related test in this repo uses `MockSDK` / `MockModel` — real\n * provider APIs are never hit from the test suite (see §6 of code-style.md).\n *\n * @example\n * const model = new MockModel(\"mock-gpt\", [\n * { content: \"Hello!\", finishReason: \"stop\" },\n * { content: \"Second turn.\", finishReason: \"stop\" },\n * ]);\n *\n * const first = await model.complete([{ role: \"user\", content: \"hi\" }]);\n * expect(first.content).toBe(\"Hello!\");\n * expect(model.callCount).toBe(1);\n */\nexport class MockModel implements ModelContract {\n public readonly provider = \"mock\";\n public readonly capabilities?: ModelCapabilities;\n\n private responseIndex = 0;\n private calls: RecordedCall[] = [];\n\n public constructor(\n public readonly name: string,\n private readonly responses: MockModelResponse[],\n capabilities?: ModelCapabilities,\n ) {\n this.capabilities = capabilities;\n }\n\n /**\n * Full history of calls made to this model. Each entry is the exact\n * `{ messages, options }` pair that was passed — useful for asserting\n * that an agent built the right prompt or forwarded the right tool list.\n */\n public get callHistory(): RecordedCall[] {\n return this.calls;\n }\n\n /**\n * Number of times `complete()` or `stream()` has been invoked. Convenient\n * shorthand for `callHistory.length` in assertions.\n */\n public get callCount(): number {\n return this.calls.length;\n }\n\n /**\n * Advance the scripted response queue by one and return the entry at the\n * current pointer. If the queue is exhausted, the final scripted entry is\n * returned repeatedly so over-consumption in tests produces predictable\n * output instead of `undefined`.\n */\n private nextResponse(): MockModelResponse {\n const response = this.responses[Math.min(this.responseIndex, this.responses.length - 1)];\n\n this.responseIndex++;\n\n return response ?? { content: \"Mock response\", finishReason: \"stop\" };\n }\n\n /**\n * Convert a scripted `MockModelResponse` into a full `ModelResponse` with\n * synthesized usage numbers when the script didn't supply them. Input\n * usage is a fixed estimate; output usage is derived from content length.\n */\n private buildResponse(mock: MockModelResponse): ModelResponse {\n const estimatedInput = 10;\n const estimatedOutput = Math.ceil(mock.content.length / 4);\n\n return {\n content: mock.content,\n finishReason: mock.finishReason ?? \"stop\",\n usage: {\n input: mock.usage?.input ?? estimatedInput,\n output: mock.usage?.output ?? estimatedOutput,\n total: (mock.usage?.input ?? estimatedInput) + (mock.usage?.output ?? estimatedOutput),\n ...(mock.usage?.cachedTokens !== undefined ? { cachedTokens: mock.usage.cachedTokens } : {}),\n },\n toolCalls: mock.toolCalls,\n };\n }\n\n /**\n * Record the call, optionally delay (to simulate latency), and either\n * throw the scripted error or return the scripted response. Mirrors the\n * real provider's `complete()` contract so agents cannot tell the\n * difference at runtime.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.calls.push({ messages, options });\n\n const mock = this.nextResponse();\n\n if (mock.delay) {\n await new Promise((resolve) => setTimeout(resolve, mock.delay));\n }\n\n if (mock.error) {\n throw mock.error;\n }\n\n return this.buildResponse(mock);\n }\n\n /**\n * Record the call, optionally delay, then emit the scripted response as a\n * sequence of stream chunks: content split word-by-word as `delta`\n * chunks, each scripted tool call as a `tool-call` chunk, and finally a\n * `done` chunk with finish reason + usage. Throws eagerly if the scripted\n * entry carries an `error`.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.calls.push({ messages, options });\n\n const mock = this.nextResponse();\n\n if (mock.delay) {\n await new Promise((resolve) => setTimeout(resolve, mock.delay));\n }\n\n if (mock.error) {\n throw mock.error;\n }\n\n const words = mock.content.split(\" \");\n\n for (const word of words) {\n yield { type: \"delta\", content: word + \" \" };\n }\n\n if (mock.toolCalls) {\n for (const toolCall of mock.toolCalls) {\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n };\n }\n }\n\n const response = this.buildResponse(mock);\n\n yield {\n type: \"done\",\n finishReason: response.finishReason,\n usage: response.usage,\n };\n }\n\n /**\n * Reset call history and response pointer back to their initial state.\n * Intended for test-suite `beforeEach` hooks so a single `MockModel`\n * instance can be reused across cases without cross-test leakage.\n */\n public reset(): void {\n this.calls = [];\n this.responseIndex = 0;\n }\n}\n","import type {\n ModelConfig,\n SDKAdapterContract,\n} from \"../contracts/sdk-adapter.contract\";\nimport { approximateTokenCount } from \"../utils/token-count\";\nimport type { MockSDKConfig } from \"./mock-config.type\";\nimport { MockModel } from \"./mock-model\";\n\n/**\n * Creates a mock SDK adapter for testing — no HTTP calls, fully configurable.\n *\n * @example\n * const mock = MockSDK({\n * responses: [\n * { content: \"Hello from mock!\" },\n * { content: \"Second response\" },\n * ],\n * });\n * const model = mock.model({ name: \"gpt-4o\" });\n * const result = await model.complete([{ role: \"user\", content: \"Hi\" }]);\n * console.log(result.content); // \"Hello from mock!\"\n */\nexport function MockSDK(config: MockSDKConfig = {}): SDKAdapterContract & {\n /** All model instances created by this SDK — for inspecting calls in tests */\n models: MockModel[];\n} {\n const models: MockModel[] = [];\n const responses = config.responses ?? [{ content: \"Mock response\" }];\n\n return {\n models,\n model(modelConfig: ModelConfig) {\n const model = new MockModel(\n modelConfig.name ?? config.defaultModelName ?? \"mock-model\",\n responses,\n config.capabilities,\n );\n models.push(model);\n return model;\n },\n async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n },\n };\n}\n","import { agent } from \"../agent/agent\";\nimport type { AgentConfig } from \"../agent/agent-config.type\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ToolContract } from \"../tool/tool\";\nimport type { MockModelResponse } from \"./mock-config.type\";\nimport { MockSDK } from \"./mock-sdk\";\n\n/**\n * Test helper that wires `MockSDK` → mock model → `agent()` in one call.\n *\n * Replaces the 4-line ritual specs typically write:\n * ```ts\n * const mock = MockSDK({ responses: [...] });\n * const myAgent = agent({ name: \"x\", model: mock.model({ name: \"m\" }) });\n * ```\n *\n * Defaults to a single empty `\"stop\"` response — enough to exercise an\n * agent that doesn't need a scripted reply (composition wiring,\n * anonymous-name tests, etc.). Pass `responses` to script outputs.\n *\n * `name` is optional — when omitted the resulting agent runs through\n * the normal anonymous-name fingerprint\n * (`anon_<provider>_<model>[_<tool1>+<tool2>...]`), which is the\n * default for `agent({ model })`.\n *\n * @example\n * const a = mockAgent({ name: \"writer\", responses: [{ content: \"hi\", finishReason: \"stop\" }] });\n * const result = await a.execute(\"anything\");\n */\nexport function mockAgent<TOutput = unknown>(\n options: {\n name?: string;\n responses?: MockModelResponse[];\n tools?: ToolContract<unknown, unknown>[];\n /**\n * Override the model name reported by the mock model. Defaults to\n * `\"mock-model\"` (the MockSDK default). Useful when a test needs\n * deterministic provider/model fingerprinting.\n */\n modelName?: string;\n } = {},\n): AgentContract<TOutput> {\n const responses = options.responses ?? [{ content: \"\", finishReason: \"stop\" as const }];\n const sdk = MockSDK({ responses });\n const model = sdk.model({ name: options.modelName ?? \"mock-model\" });\n\n const config: AgentConfig<TOutput> = { model };\n\n if (options.name !== undefined) {\n config.name = options.name;\n }\n\n if (options.tools !== undefined) {\n config.tools = options.tools;\n }\n\n return agent<TOutput>(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,IAAa,UAAb,cAA6B,MAAM;;yBASuB;;CAMxD,AAAO,YACL,MACA,SACA,SACA,UACA;EACA,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU,SAAS;EACxB,KAAK,WAAW,YAAa,KAAK,YAA+B;EAEjE,IAAI,SAAS,UAAU,QACrB,AAAC,KAA6B,QAAQ,QAAQ;CAElD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;ACnFA,IAAa,sBAAb,cAAyC,QAAQ;CAC/C,AAAO,YACL,SACA,S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