@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/esm/tool/tool.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.mjs","names":[],"sources":["../../../../../../@warlock.js/ai/src/tool/tool.ts"],"sourcesContent":["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"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"sourcesContent":["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"],"mappings":"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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ModelPricing } from "../contracts/result/model-pricing.type.mjs";
|
|
2
2
|
import { Usage } from "../contracts/result/usage.type.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../@warlock.js/ai/src/utils/compute-cost.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Compute a per-channel USD cost breakdown for a single `Usage` against
|
|
7
7
|
* a model's pricing table. Returns `undefined` when no pricing is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compute-cost.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"compute-cost.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"mappings":";;;;;;AAuCA;;;;;;;;;;;;;;AAA0F;AAkC1F;;;;;;;;;;;;;;AAGe;;;;;iBArCC,WAAA,CAAY,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,YAAA,eAA2B,YAAA;;;;;;;;;;;;;;iBAkC9D,cAAA,CACd,MAAA,EAAQ,YAAA,cACR,KAAA,EAAO,YAAA,eACN,YAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compute-cost.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"compute-cost.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAc,SAA6D;CACrG,IAAI,CAAC,SACH;CAGF,MAAM,cAAc,MAAM,gBAAgB;CAG1C,MAAM,OAAqB;EACzB,OAHoB,KAAK,IAAI,GAAG,MAAM,QAAQ,WAG1B,IAAI,QAAQ,QAAS;EACzC,QAAS,MAAM,SAAS,QAAQ,SAAU;CAC5C;CAEA,IAAI,cAAc,GAEhB,KAAK,cAAe,eADI,QAAQ,eAAe,QAAQ,SACF;CAGvD,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,eACd,QACA,OAC0B;CAC1B,IAAI,CAAC,OACH,OAAO;CAGT,IAAI,CAAC,QACH,OAAO,EAAE,GAAG,MAAM;CAGpB,MAAM,SAAuB;EAC3B,OAAO,OAAO,QAAQ,MAAM;EAC5B,QAAQ,OAAO,SAAS,MAAM;CAChC;CAEA,MAAM,cAAc,YAAY,OAAO,aAAa,MAAM,WAAW;CACrE,IAAI,gBAAgB,QAClB,OAAO,cAAc;CAGvB,MAAM,eAAe,YAAY,OAAO,cAAc,MAAM,YAAY;CACxE,IAAI,iBAAiB,QACnB,OAAO,eAAe;CAGxB,OAAO;AACT;;;;;;;AAQA,SAAS,YAAY,QAA4B,OAA+C;CAC9F,IAAI,WAAW,UAAa,UAAU,QACpC;CAGF,QAAQ,UAAU,MAAM,SAAS;AACnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract-json-payload.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"extract-json-payload.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/extract-json-payload.ts"],"mappings":";;AA4BA;;;;AAA+C;;;;;;;;;;;;;;;;;;;;;;;iBAA/B,kBAAA,CAAmB,IAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract-json-payload.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"extract-json-payload.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/extract-json-payload.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,mBAAmB,MAAsB;CACvD,MAAM,UAAU,KAAK,KAAK;CAE1B,MAAM,aAAa,QAAQ,MAAM,oCAAoC;CAErE,IAAI,YACF,OAAO,WAAW,EAAE,CAAC,KAAK;CAG5B,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-run-id.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"generate-run-id.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/generate-run-id.ts"],"mappings":";;AAeA;;;;AAA4C;;;;;;;;;;iBAA5B,aAAA,CAAc,MAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-run-id.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"generate-run-id.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/generate-run-id.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,cAAc,QAAwB;CACpD,OAAO,GAAG,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CACzD,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,EAAE;AAChB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/ai/src/utils/json-schema.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Supported JSON Schema output targets per the Standard JSON Schema V1
|
|
6
6
|
* spec. `openai-strict` is the richest for OpenAI structured outputs —
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-schema.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"json-schema.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/json-schema.ts"],"mappings":";;;;;AASA;;;;AAA4B;KAAhB,gBAAA;;;;AASe;AAoC3B;;KArCY,wBAAA;EACV,MAAA,GAAS,gBAAgB;AAAA;;;;;;;;;;AAuClB;;;;;;;;;;;;;;;;;;;;;;;;iBAHO,iBAAA,CACd,MAAA,EAAQ,gBAAA,uBACR,OAAA,GAAS,wBAAA,GACR,MAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-schema.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"json-schema.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/json-schema.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,QACA,UAAoC,CAAC,GACA;CACrC,IAAI,CAAC,QAAQ,OAAO;CAKpB,MAAM,iBAAiB,oBAAoB,QAH5B,QAAQ,UAAU,eAGwB;CAEzD,IAAI,gBACF,OAAO;CAIT,MAAM,WAAW,yBAAyB,MAA4C;CAEtF,IAAI,UACF,OAAO;AAIX;;;;;;;;;;;;;AAcA,SAAS,oBACP,QACA,QACqC;CACrC,MAAM,eAAgB,OAA8C;CAEpE,IAAI,CAAC,gBAAgB,OAAO,iBAAiB,UAC3C;CAGF,MAAM,iBAAkB,aAAyC;CAEjE,IAAI,CAAC,kBAAkB,OAAO,mBAAmB,UAC/C;CAGF,MAAM,UAAW,eAA2C;CAE5D,IAAI,OAAO,YAAY,YACrB;CAGF,IAAI;EACF,MAAM,SAAU,QAAqD,KAAK,gBAAgB,EACxF,OACF,CAAC;EAED,IAAI,UAAU,OAAO,WAAW,UAC9B,OAAO;CAEX,QAAQ,CAER;AAGF;;;;;;;;AASA,SAAS,yBACP,cACqC;CAGrC,KAAK,MAAM,OAAO,CAFK,cAAc,aAEP,GAAG;EAC/B,MAAM,QAAQ,aAAa;EAE3B,IAAI,OAAO,UAAU,YAAY;GAC/B,IAAI;IACF,MAAM,SAAU,MAAwB,KAAK,YAAY;IAEzD,IAAI,UAAU,OAAO,WAAW,UAC9B,OAAO;GAEX,QAAQ,CAER;GAEA;EACF;EAEA,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO;CAEX;AAGF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Attachment } from "../contracts/attachment.type.mjs";
|
|
2
2
|
import { ContentPart } from "../contracts/content-part.type.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../@warlock.js/ai/src/utils/prepare-attachment-part.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Convert a user-supplied `Attachment` into a provider-ready
|
|
7
7
|
* `ContentPart` the model adapter can consume without doing any I/O of
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare-attachment-part.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"prepare-attachment-part.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts"],"mappings":";;;;;;AA+CA;;;;;;;;;;;;;AAEsB;;;;;;;;;;;;;iBAFA,qBAAA,CACpB,UAAA,EAAY,UAAA,GACX,OAAA,CAAQ,WAAA"}
|
|
@@ -4,7 +4,7 @@ import { resolveAttachment } from "./resolve-attachment.mjs";
|
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
5
|
import { extname } from "node:path";
|
|
6
6
|
|
|
7
|
-
//#region
|
|
7
|
+
//#region ../@warlock.js/ai/src/utils/prepare-attachment-part.ts
|
|
8
8
|
const IMAGE_EXTENSIONS_TO_MEDIA_TYPE = {
|
|
9
9
|
".png": "image/png",
|
|
10
10
|
".jpg": "image/jpeg",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare-attachment-part.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"prepare-attachment-part.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts"],"sourcesContent":["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"],"mappings":";;;;;;;AAOA,MAAM,iCAAyD;CAC7D,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;AACV;AAEA,MAAM,kBAAkB,IAAI,IAAI,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCxC,eAAsB,sBACpB,YACsB;CAGtB,IAFa,YAAY,UAElB,MAAM,QACX,OAAO,gBAAgB,UAAU;CAGnC,OAAO,iBAAiB,UAAU;AACpC;;;;;;AAOA,SAAS,YAAY,YAAwC;CAC3D,IAAI,mBAAmB,UAAU,GAC/B,OAAO,WAAW;CAGpB,MAAM,OAAO,YAAY,UAAU;CACnC,MAAM,YAAY,OAAO,QAAQ,WAAW,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI;CAEnE,IAAI,+BAA+B,YACjC,OAAO;CAGT,IAAI,gBAAgB,IAAI,SAAS,GAC/B,OAAO;CAGT,MAAM,IAAI,oBACR,2KACF;AACF;;;;;;AAOA,eAAe,iBAAiB,YAA8C;CAC5E,MAAM,oBAAoB,mBAAmB,UAAU,IACnD,SACA,oBAAoB,UAAU;CAElC,MAAM,WAAW,kBAAkB,UAAU;CAE7C,IAAI,SAAS,SAAS,OACpB,OAAO;EAAE,MAAM;EAAS,QAAQ,EAAE,KAAK,SAAS,MAAM;CAAE;CAG1D,IAAI,SAAS,SAAS,UACpB,OAAO;EACL,MAAM;EACN,QAAQ;GAAE,QAAQ,SAAS;GAAO,WAAW,SAAS;EAAU;CAClE;CAGF,MAAM,YAAY,qBAAqB,oBAAoB,SAAS,KAAK;CAEzE,IAAI,CAAC,WACH,MAAM,IAAI,oBACR,qCAAqC,SAAS,MAAM,oGAEpD,EAAE,SAAS,EAAE,MAAM,SAAS,MAAM,EAAE,CACtC;CAKF,OAAO;EACL,MAAM;EACN,QAAQ;GAAE,SAAQ,MAJA,SAAS,SAAS,KAAK,EAIlB,CAAC,SAAS,QAAQ;GAAG;EAAU;CACxD;AACF;;;;;;;AAQA,eAAe,gBAAgB,YAA8C;CAC3E,MAAM,WAAW,kBAAkB,UAAU;CAE7C,IAAI,SAAS,SAAS,OAAO;EAC3B,MAAM,WAAW,MAAM,MAAM,SAAS,KAAK;EAE3C,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,oBACR,oCAAoC,SAAS,MAAM,aAAa,SAAS,UACzE,EAAE,SAAS;GAAE,KAAK,SAAS;GAAO,QAAQ,SAAS;EAAO,EAAE,CAC9D;EAGF,OAAO;GAAE,MAAM;GAAQ,MAAM,MAAM,SAAS,KAAK;EAAE;CACrD;CAEA,IAAI,SAAS,SAAS,UAGpB,OAAO;EAAE,MAAM;EAAQ,MAFP,OAAO,KAAK,SAAS,OAAO,QAAQ,CAAC,CAAC,SAAS,MAE5B;CAAE;CAKvC,OAAO;EAAE,MAAM;EAAQ,MAAM,MAFT,SAAS,SAAS,OAAO,MAAM;CAEhB;AACrC;AAEA,SAAS,mBACP,YACqD;CACrD,OACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU;AAEd;AAEA,SAAS,oBAAoB,OAAoC;CAC/D,MAAM,OAAO,YAAY,KAAK;CAE9B,IAAI,CAAC,MACH;CAKF,OAAO,+BAFW,QAAQ,WAAW,IAAI,CAAC,CAAC,CAAC,YAEE;AAChD;AAEA,SAAS,YAAY,OAAoC;CACvD,IAAI,OAAO,UAAU,UACnB,OAAO;CAGT,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,MAAM,UAAU;EAChB,OAAO,QAAQ,OAAO,QAAQ;CAChC;AAGF;AAEA,SAAS,WAAW,MAAsB;CACxC,MAAM,aAAa,KAAK,QAAQ,GAAG;CAEnC,OAAO,eAAe,KAAK,OAAO,KAAK,MAAM,GAAG,UAAU;AAC5D"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Attachment, ResolvedAttachment } from "../contracts/attachment.type.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/ai/src/utils/resolve-attachment.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Normalize a user-supplied `Attachment` (or bare `AttachmentSource`)
|
|
6
6
|
* into a `ResolvedAttachment` the agent can hand to file-reading code
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-attachment.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"resolve-attachment.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/resolve-attachment.ts"],"mappings":";;;;;AAmCA;;;;;;;;AAA6E;;;;;;;;;;;;;;;;iBAA7D,iBAAA,CAAkB,UAAA,EAAY,UAAA,GAAa,kBAAkB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { InvalidRequestError } from "../errors/invalid-request-error.mjs";
|
|
2
2
|
import "../errors/index.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../@warlock.js/ai/src/utils/resolve-attachment.ts
|
|
5
5
|
const REMOTE_URL_PATTERN = /^https?:\/\//i;
|
|
6
6
|
/**
|
|
7
7
|
* Normalize a user-supplied `Attachment` (or bare `AttachmentSource`)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-attachment.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"resolve-attachment.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/resolve-attachment.ts"],"sourcesContent":["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"],"mappings":";;;;AAOA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B3B,SAAgB,kBAAkB,YAA4C;CAC5E,IACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,YAEV,OAAO,cAAc,WAAW,MAAM;CAGxC,OAAO,cAAc,UAAU;AACjC;AAEA,SAAS,cAAc,QAA8C;CACnE,IAAI,OAAO,WAAW,UAAU;EAC9B,IAAI,CAAC,QACH,MAAM,IAAI,oBAAoB,wCAAwC;EAGxE,IAAI,mBAAmB,KAAK,MAAM,GAChC,OAAO;GAAE,MAAM;GAAO,OAAO;EAAO;EAGtC,OAAO;GAAE,MAAM;GAAQ,OAAO;EAAO;CACvC;CAKA,IAAI,SAAS,UAAU,kBAAkB,QAAQ;EAC/C,MAAM,UAAU;EAEhB,IAAI,QAAQ,cACV,OAAO;GAAE,MAAM;GAAQ,OAAO,QAAQ;EAAa;EAGrD,IAAI,QAAQ,KACV,OAAO;GAAE,MAAM;GAAO,OAAO,QAAQ;EAAI;EAG3C,MAAM,IAAI,oBACR,qDACF;CACF;CAEA,IAAI,YAAY,QAAQ;EACtB,IAAI,CAAC,OAAO,UAAU,CAAC,OAAO,WAC5B,MAAM,IAAI,oBACR,0DACF;EAGF,OAAO;GACL,MAAM;GACN,OAAO,OAAO;GACd,WAAW,OAAO;EACpB;CACF;CAEA,MAAM,IAAI,oBACR,wGACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../@warlock.js/ai/src/utils/safe-json-parse.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* Parse a JSON string, returning a caller-supplied fallback when the input
|
|
4
4
|
* is empty or malformed instead of throwing. Useful at provider boundaries
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-json-parse.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"safe-json-parse.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/safe-json-parse.ts"],"mappings":";;AASA;;;;;;;;iBAAgB,aAAA,SACd,IAAA,6BACA,YAAA,EAAc,MAAA,GACb,MAAM"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../@warlock.js/ai/src/utils/safe-json-parse.ts
|
|
2
2
|
/**
|
|
3
3
|
* Parse a JSON string, returning a caller-supplied fallback when the input
|
|
4
4
|
* is empty or malformed instead of throwing. Useful at provider boundaries
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-json-parse.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"safe-json-parse.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/safe-json-parse.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;AASA,SAAgB,cACd,MACA,cACQ;CACR,IAAI,CAAC,MACH,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseReport } from "../contracts/result/base-report.type.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/ai/src/utils/stamp-report-lineage.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Options for {@link stampReportLineage}. Every field is optional —
|
|
6
6
|
* the caller supplies whichever pieces it knows. Missing pieces are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stamp-report-lineage.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"stamp-report-lineage.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/stamp-report-lineage.ts"],"mappings":";;;;;AAQA;;;KAAY,YAAA;EAOV;;;;AAWS;AAgCX;EA3CE,SAAA;;;;;;EAMA,WAAA;EAqCsE;AAAA;;;EAhCtE,SAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCc,kBAAA,CAAmB,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,YAAY"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { REPORT_SCHEMA_VERSION } from "../contracts/result/base-report.type.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/ai/src/utils/stamp-report-lineage.ts
|
|
4
4
|
/**
|
|
5
5
|
* Walk a freshly-built report tree and stamp lineage fields onto
|
|
6
6
|
* every node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stamp-report-lineage.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"stamp-report-lineage.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/stamp-report-lineage.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,mBAAmB,MAAkB,OAA2B;CAC9E,KAAK;CAEL,KAAK,MAAM,MAAM,WAAW,MAAM,aAAa,MAAM,SAAS;AAChE;AAEA,SAAS,KAAK,MAAkB,WAAmB,aAAsB,WAA0B;CACjG,KAAK,YAAY;CAEjB,IAAI,gBAAgB,QAClB,KAAK,cAAc;MAEnB,OAAO,KAAK;CAGd,IAAI,cAAc,QAChB,KAAK,YAAY;CAGnB,KAAK,MAAM,SAAS,KAAK,UACvB,KAAK,OAAO,WAAW,KAAK,OAAO,SAAS;AAEhD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-count.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"token-count.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/token-count.ts"],"mappings":";;AAUA;;;;AAAkD;;;;;iBAAlC,qBAAA,CAAsB,IAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-count.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"token-count.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/token-count.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;AAUA,SAAgB,sBAAsB,MAAsB;CAC1D,OAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC"}
|
package/esm/workflow/as-tool.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { WorkflowError } from "../errors/workflow-error.mjs";
|
|
|
2
2
|
import "../errors/index.mjs";
|
|
3
3
|
import { compositeAsTool } from "../tool/tool.mjs";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../@warlock.js/ai/src/workflow/as-tool.ts
|
|
6
6
|
/**
|
|
7
7
|
* Wrap a `WorkflowInstance` as a `ToolContract` so an agent can invoke
|
|
8
8
|
* it inside its tool-call loop. Closes the agent-calls-workflow
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"as-tool.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"as-tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/workflow/as-tool.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,OACd,kBACA,SAImC;CACnC,IAAI,CAAC,iBAAiB,QAAQ,OAAO,iBAAiB,SAAS,UAC7D,MAAM,IAAI,cACR,wEACF;CAGF,OAAO,gBAAqC;EAC1C,MAAM,iBAAiB;EACvB,aAAa,QAAQ,eAAe,oBAAoB,iBAAiB,KAAK;EAC9E,OAAO,QAAQ;EACf,SAAS,OAAO,UAAU;GACxB,MAAM,SAAS,MAAM,iBAAiB,QAAQ,KAA0B;GAExE,IAAI,OAAO,OAMT,MAAM,OAAO;GAGf,OAAO;IACL,MAAM,OAAO;IACb,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WorkflowCancelledError } from "../errors/workflow-cancelled-error.mjs";
|
|
2
2
|
import "../errors/index.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../@warlock.js/ai/src/workflow/cancellation.ts
|
|
5
5
|
/**
|
|
6
6
|
* Build a `WorkflowCancelledError` from an `AbortSignal`, extracting
|
|
7
7
|
* a human-readable reason from `signal.reason` (string | Error | any).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancellation.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"cancellation.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/workflow/cancellation.ts"],"sourcesContent":["import { WorkflowCancelledError } from \"../errors\";\n\n/**\n * Build a `WorkflowCancelledError` from an `AbortSignal`, extracting\n * a human-readable reason from `signal.reason` (string | Error | any).\n * Used both at between-step boundaries and inside the retry backoff\n * sleep.\n */\nexport function createCancelledError(\n signal: AbortSignal | undefined,\n): WorkflowCancelledError {\n const reason = signal?.reason;\n const reasonText =\n typeof reason === \"string\"\n ? reason\n : reason instanceof Error\n ? reason.message\n : reason === undefined\n ? \"\"\n : String(reason);\n\n return new WorkflowCancelledError(\n `workflow cancelled${reasonText ? `: ${reasonText}` : \"\"}`,\n { cancelledAt: new Date().toISOString(), reason: reasonText },\n );\n}\n\n/**\n * Promise-based sleep that resolves after `ms` milliseconds, or\n * rejects with `WorkflowCancelledError` if the signal fires. The\n * timer is cleared on abort so we never leak a pending setTimeout.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(createCancelledError(signal));\n return;\n }\n\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(createCancelledError(signal));\n };\n\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgB,qBACd,QACwB;CACxB,MAAM,SAAS,QAAQ;CACvB,MAAM,aACJ,OAAO,WAAW,WACd,SACA,kBAAkB,QAChB,OAAO,UACP,WAAW,SACT,KACA,OAAO,MAAM;CAEvB,OAAO,IAAI,uBACT,qBAAqB,aAAa,KAAK,eAAe,MACtD;EAAE,8BAAa,IAAI,KAAK,EAAC,CAAC,YAAY;EAAG,QAAQ;CAAW,CAC9D;AACF;;;;;;AAOA,SAAgB,MAAM,IAAY,QAAqC;CACrE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,QAAQ,SAAS;GACnB,OAAO,qBAAqB,MAAM,CAAC;GACnC;EACF;EAEA,MAAM,QAAQ,iBAAiB;GAC7B,QAAQ,oBAAoB,SAAS,OAAO;GAC5C,QAAQ;EACV,GAAG,EAAE;EAEL,MAAM,gBAAgB;GACpB,aAAa,KAAK;GAClB,OAAO,qBAAqB,MAAM,CAAC;EACrC;EAEA,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,CAAC;AACH"}
|
package/esm/workflow/emitter.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emitter.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"emitter.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/workflow/emitter.ts"],"sourcesContent":["import type { WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { WorkflowEventMap } from \"../contracts/events/event-map.type\";\nimport type {\n WorkflowEventHandler,\n WorkflowEventHandlers,\n} from \"../contracts/workflow/workflow.contract\";\n\ntype AnyHandler = WorkflowEventHandler<keyof WorkflowEventMap>;\n\n/**\n * The emit surface the workflow engine and step-runner depend on.\n * They never construct run identity themselves — they hand a bare\n * payload to a sink that injects `runId` / `rootRunId` before\n * delegating to the real three-tier `WorkflowEmitter`.\n *\n * `WorkflowEmitter` is factory-scoped (shared across every\n * `execute()`), so it cannot own per-run identity. A per-run sink\n * (see `runScopedEmitter`) closes that gap without touching the ~15\n * `emit` call sites in `engine.ts` / `step-runner.ts`.\n */\nexport interface WorkflowEventSink {\n emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WithoutIdentity<WorkflowEventMap[K]>,\n executionHandlers?: WorkflowEventHandlers,\n ): void;\n}\n\n/**\n * Three-tier workflow event emitter — factory (definition) → instance →\n * per-execution. All matching handlers fire, in layer order. Handler\n * errors are swallowed so listener bugs can never derail the workflow.\n */\nexport class WorkflowEmitter {\n private readonly factoryHandlers?: WorkflowEventHandlers;\n private readonly instanceHandlers = new Map<\n keyof WorkflowEventMap,\n Set<AnyHandler>\n >();\n\n public constructor(factoryHandlers?: WorkflowEventHandlers) {\n this.factoryHandlers = factoryHandlers;\n }\n\n public on<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): () => void {\n let bucket = this.instanceHandlers.get(event);\n if (!bucket) {\n bucket = new Set();\n this.instanceHandlers.set(event, bucket);\n }\n bucket.add(handler as AnyHandler);\n return () => this.off(event, handler);\n }\n\n public off<K extends keyof WorkflowEventMap>(\n event: K,\n handler: WorkflowEventHandler<K>,\n ): void {\n this.instanceHandlers.get(event)?.delete(handler as AnyHandler);\n }\n\n public emit<K extends keyof WorkflowEventMap>(\n event: K,\n payload: WorkflowEventMap[K],\n executionHandlers?: WorkflowEventHandlers,\n ): void {\n // Layer 1 — factory\n invoke(this.factoryHandlers?.[event], payload);\n\n // Layer 2 — instance (set-based, possibly many handlers)\n const bucket = this.instanceHandlers.get(event);\n if (bucket) {\n for (const handler of bucket) invoke(handler, payload);\n }\n\n // Layer 3 — per-execution\n invoke(executionHandlers?.[event], payload);\n }\n}\n\nfunction invoke<K extends keyof WorkflowEventMap>(\n handler: ((payload: WorkflowEventMap[K]) => void) | undefined,\n payload: WorkflowEventMap[K],\n): void {\n if (typeof handler !== \"function\") return;\n try {\n handler(payload);\n } catch {\n // Swallow — listener bugs must not derail workflow execution.\n }\n}\n"],"mappings":";;;;;;AAiCA,IAAa,kBAAb,MAA6B;CAO3B,AAAO,YAAY,iBAAyC;0CALxB,IAAI,IAGtC;EAGA,KAAK,kBAAkB;CACzB;CAEA,AAAO,GACL,OACA,SACY;EACZ,IAAI,SAAS,KAAK,iBAAiB,IAAI,KAAK;EAC5C,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,IAAI;GACjB,KAAK,iBAAiB,IAAI,OAAO,MAAM;EACzC;EACA,OAAO,IAAI,OAAqB;EAChC,aAAa,KAAK,IAAI,OAAO,OAAO;CACtC;CAEA,AAAO,IACL,OACA,SACM;EACN,KAAK,iBAAiB,IAAI,KAAK,CAAC,EAAE,OAAO,OAAqB;CAChE;CAEA,AAAO,KACL,OACA,SACA,mBACM;EAEN,OAAO,KAAK,kBAAkB,QAAQ,OAAO;EAG7C,MAAM,SAAS,KAAK,iBAAiB,IAAI,KAAK;EAC9C,IAAI,QACF,KAAK,MAAM,WAAW,QAAQ,OAAO,SAAS,OAAO;EAIvD,OAAO,oBAAoB,QAAQ,OAAO;CAC5C;AACF;AAEA,SAAS,OACP,SACA,SACM;CACN,IAAI,OAAO,YAAY,YAAY;CACnC,IAAI;EACF,QAAQ,OAAO;CACjB,QAAQ,CAER;AACF"}
|
package/esm/workflow/engine.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { cloneState, deepFreeze } from "./state.mjs";
|
|
|
15
15
|
import { executeStep, finalizeSnapshot, toAIError } from "./step-runner.mjs";
|
|
16
16
|
import { log } from "@warlock.js/logger";
|
|
17
17
|
|
|
18
|
-
//#region
|
|
18
|
+
//#region ../@warlock.js/ai/src/workflow/engine.ts
|
|
19
19
|
const DEFAULT_MAX_STEPS = 100;
|
|
20
20
|
const DEFAULT_LOOP_WARN = 5;
|
|
21
21
|
const LOG_MODULE_BASE = "ai.workflow";
|