@warlock.js/ai 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -0
- package/cjs/index.cjs +8625 -0
- package/cjs/index.cjs.map +1 -0
- package/esm/agent/agent-config.type.d.mts +160 -0
- package/esm/agent/agent-config.type.d.mts.map +1 -0
- package/esm/agent/agent-input-builder.mjs +111 -0
- package/esm/agent/agent-input-builder.mjs.map +1 -0
- package/esm/agent/agent-log-event.mjs +101 -0
- package/esm/agent/agent-log-event.mjs.map +1 -0
- package/esm/agent/agent-stream.d.mts +47 -0
- package/esm/agent/agent-stream.d.mts.map +1 -0
- package/esm/agent/agent-stream.mjs +82 -0
- package/esm/agent/agent-stream.mjs.map +1 -0
- package/esm/agent/agent-to-stream-event.mjs +86 -0
- package/esm/agent/agent-to-stream-event.mjs.map +1 -0
- package/esm/agent/agent.d.mts +38 -0
- package/esm/agent/agent.d.mts.map +1 -0
- package/esm/agent/agent.mjs +974 -0
- package/esm/agent/agent.mjs.map +1 -0
- package/esm/agent/index.d.mts +3 -0
- package/esm/agent/index.mjs +4 -0
- package/esm/agent/json-stream-guard.mjs +400 -0
- package/esm/agent/json-stream-guard.mjs.map +1 -0
- package/esm/ai.d.mts +64 -0
- package/esm/ai.d.mts.map +1 -0
- package/esm/ai.mjs +65 -0
- package/esm/ai.mjs.map +1 -0
- package/esm/config.d.mts +79 -0
- package/esm/config.d.mts.map +1 -0
- package/esm/config.mjs +43 -0
- package/esm/config.mjs.map +1 -0
- package/esm/contracts/agent/agent-options.type.d.mts +132 -0
- package/esm/contracts/agent/agent-options.type.d.mts.map +1 -0
- package/esm/contracts/agent/agent.contract.d.mts +92 -0
- package/esm/contracts/agent/agent.contract.d.mts.map +1 -0
- package/esm/contracts/agent/index.d.mts +2 -0
- package/esm/contracts/attachment.type.d.mts +100 -0
- package/esm/contracts/attachment.type.d.mts.map +1 -0
- package/esm/contracts/content-part.type.d.mts +55 -0
- package/esm/contracts/content-part.type.d.mts.map +1 -0
- package/esm/contracts/conversation-message.type.d.mts +51 -0
- package/esm/contracts/conversation-message.type.d.mts.map +1 -0
- package/esm/contracts/embedder.contract.d.mts +69 -0
- package/esm/contracts/embedder.contract.d.mts.map +1 -0
- package/esm/contracts/end.type.d.mts +53 -0
- package/esm/contracts/end.type.d.mts.map +1 -0
- package/esm/contracts/end.type.mjs +47 -0
- package/esm/contracts/end.type.mjs.map +1 -0
- package/esm/contracts/events/agent-events.type.d.mts +71 -0
- package/esm/contracts/events/agent-events.type.d.mts.map +1 -0
- package/esm/contracts/events/complete-event.type.d.mts +33 -0
- package/esm/contracts/events/complete-event.type.d.mts.map +1 -0
- package/esm/contracts/events/event-identity.type.d.mts +30 -0
- package/esm/contracts/events/event-identity.type.d.mts.map +1 -0
- package/esm/contracts/events/event-map.type.d.mts +80 -0
- package/esm/contracts/events/event-map.type.d.mts.map +1 -0
- package/esm/contracts/events/index.d.mts +7 -0
- package/esm/contracts/events/supervisor-events.type.d.mts +162 -0
- package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -0
- package/esm/contracts/events/usage-event.type.d.mts +39 -0
- package/esm/contracts/events/usage-event.type.d.mts.map +1 -0
- package/esm/contracts/events/workflow-events.type.d.mts +51 -0
- package/esm/contracts/events/workflow-events.type.d.mts.map +1 -0
- package/esm/contracts/executable.contract.d.mts +25 -0
- package/esm/contracts/executable.contract.d.mts.map +1 -0
- package/esm/contracts/finish-reason.type.d.mts +17 -0
- package/esm/contracts/finish-reason.type.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +63 -0
- package/esm/contracts/middleware/index.d.mts +3 -0
- package/esm/contracts/middleware/middleware-context.type.d.mts +99 -0
- package/esm/contracts/middleware/middleware-context.type.d.mts.map +1 -0
- package/esm/contracts/middleware/middleware-state.type.d.mts +34 -0
- package/esm/contracts/middleware/middleware-state.type.d.mts.map +1 -0
- package/esm/contracts/middleware/middleware.contract.d.mts +140 -0
- package/esm/contracts/middleware/middleware.contract.d.mts.map +1 -0
- package/esm/contracts/model-tool-call-request.type.d.mts +58 -0
- package/esm/contracts/model-tool-call-request.type.d.mts.map +1 -0
- package/esm/contracts/model.contract.d.mts +164 -0
- package/esm/contracts/model.contract.d.mts.map +1 -0
- package/esm/contracts/placeholders.type.d.mts +23 -0
- package/esm/contracts/placeholders.type.d.mts.map +1 -0
- package/esm/contracts/result/agent-result.type.d.mts +33 -0
- package/esm/contracts/result/agent-result.type.d.mts.map +1 -0
- package/esm/contracts/result/attempt-entry.type.d.mts +40 -0
- package/esm/contracts/result/attempt-entry.type.d.mts.map +1 -0
- package/esm/contracts/result/base-report.type.d.mts +137 -0
- package/esm/contracts/result/base-report.type.d.mts.map +1 -0
- package/esm/contracts/result/base-report.type.mjs +17 -0
- package/esm/contracts/result/base-report.type.mjs.map +1 -0
- package/esm/contracts/result/base-result.type.d.mts +26 -0
- package/esm/contracts/result/base-result.type.d.mts.map +1 -0
- package/esm/contracts/result/execute-result.type.d.mts +40 -0
- package/esm/contracts/result/execute-result.type.d.mts.map +1 -0
- package/esm/contracts/result/execution-report.type.d.mts +50 -0
- package/esm/contracts/result/execution-report.type.d.mts.map +1 -0
- package/esm/contracts/result/index.d.mts +14 -0
- package/esm/contracts/result/llm-trip.type.d.mts +36 -0
- package/esm/contracts/result/llm-trip.type.d.mts.map +1 -0
- package/esm/contracts/result/model-pricing.type.d.mts +51 -0
- package/esm/contracts/result/model-pricing.type.d.mts.map +1 -0
- package/esm/contracts/result/session-send-result.type.d.mts +29 -0
- package/esm/contracts/result/session-send-result.type.d.mts.map +1 -0
- package/esm/contracts/result/step-result.type.d.mts +43 -0
- package/esm/contracts/result/step-result.type.d.mts.map +1 -0
- package/esm/contracts/result/supervisor-result.type.d.mts +86 -0
- package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -0
- package/esm/contracts/result/tool-call.type.d.mts +44 -0
- package/esm/contracts/result/tool-call.type.d.mts.map +1 -0
- package/esm/contracts/result/usage.type.d.mts +57 -0
- package/esm/contracts/result/usage.type.d.mts.map +1 -0
- package/esm/contracts/result/workflow-result.type.d.mts +45 -0
- package/esm/contracts/result/workflow-result.type.d.mts.map +1 -0
- package/esm/contracts/sdk-adapter.contract.d.mts +77 -0
- package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -0
- package/esm/contracts/stream/stream-event.type.d.mts +68 -0
- package/esm/contracts/stream/stream-event.type.d.mts.map +1 -0
- package/esm/contracts/stream/stream.contract.d.mts +61 -0
- package/esm/contracts/stream/stream.contract.d.mts.map +1 -0
- package/esm/contracts/streaming-tool-guard-config.type.d.mts +78 -0
- package/esm/contracts/streaming-tool-guard-config.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/ack-entry.type.d.mts +97 -0
- package/esm/contracts/supervisor/ack-entry.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/classifier-context.type.d.mts +189 -0
- package/esm/contracts/supervisor/classifier-context.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/dispatch-context.type.d.mts +235 -0
- package/esm/contracts/supervisor/dispatch-context.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/evaluate-context.type.d.mts +124 -0
- package/esm/contracts/supervisor/evaluate-context.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/index.d.mts +16 -0
- package/esm/contracts/supervisor/intent-entry.type.d.mts +254 -0
- package/esm/contracts/supervisor/intent-entry.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/iteration-snapshot.type.d.mts +117 -0
- package/esm/contracts/supervisor/iteration-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/next.type.d.mts +25 -0
- package/esm/contracts/supervisor/next.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/route-context.type.d.mts +91 -0
- package/esm/contracts/supervisor/route-context.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/router-entry.type.d.mts +67 -0
- package/esm/contracts/supervisor/router-entry.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts +356 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts +90 -0
- package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-input.type.d.mts +24 -0
- package/esm/contracts/supervisor/supervisor-input.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts +49 -0
- package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts +16 -0
- package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor.contract.d.mts +126 -0
- package/esm/contracts/supervisor/supervisor.contract.d.mts.map +1 -0
- package/esm/contracts/system-prompt.contract.d.mts +118 -0
- package/esm/contracts/system-prompt.contract.d.mts.map +1 -0
- package/esm/contracts/tool.contract.d.mts +161 -0
- package/esm/contracts/tool.contract.d.mts.map +1 -0
- package/esm/contracts/workflow/index.d.mts +6 -0
- package/esm/contracts/workflow/next-step-result.type.d.mts +17 -0
- package/esm/contracts/workflow/next-step-result.type.d.mts.map +1 -0
- package/esm/contracts/workflow/retry-config.type.d.mts +19 -0
- package/esm/contracts/workflow/retry-config.type.d.mts.map +1 -0
- package/esm/contracts/workflow/step.contract.d.mts +189 -0
- package/esm/contracts/workflow/step.contract.d.mts.map +1 -0
- package/esm/contracts/workflow/workflow-context.type.d.mts +45 -0
- package/esm/contracts/workflow/workflow-context.type.d.mts.map +1 -0
- package/esm/contracts/workflow/workflow-snapshot.type.d.mts +24 -0
- package/esm/contracts/workflow/workflow-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/workflow/workflow.contract.d.mts +142 -0
- package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -0
- package/esm/errors/agent-cancelled-error.d.mts +49 -0
- package/esm/errors/agent-cancelled-error.d.mts.map +1 -0
- package/esm/errors/agent-cancelled-error.mjs +43 -0
- package/esm/errors/agent-cancelled-error.mjs.map +1 -0
- package/esm/errors/agent-execution-error.d.mts +32 -0
- package/esm/errors/agent-execution-error.d.mts.map +1 -0
- package/esm/errors/agent-execution-error.mjs +35 -0
- package/esm/errors/agent-execution-error.mjs.map +1 -0
- package/esm/errors/agent-max-trips-error.d.mts +45 -0
- package/esm/errors/agent-max-trips-error.d.mts.map +1 -0
- package/esm/errors/agent-max-trips-error.mjs +41 -0
- package/esm/errors/agent-max-trips-error.mjs.map +1 -0
- package/esm/errors/ai-error.d.mts +94 -0
- package/esm/errors/ai-error.d.mts.map +1 -0
- package/esm/errors/ai-error.mjs +68 -0
- package/esm/errors/ai-error.mjs.map +1 -0
- package/esm/errors/budget-exceeded-error.d.mts +41 -0
- package/esm/errors/budget-exceeded-error.d.mts.map +1 -0
- package/esm/errors/budget-exceeded-error.mjs +31 -0
- package/esm/errors/budget-exceeded-error.mjs.map +1 -0
- package/esm/errors/content-filter-error.d.mts +33 -0
- package/esm/errors/content-filter-error.d.mts.map +1 -0
- package/esm/errors/content-filter-error.mjs +28 -0
- package/esm/errors/content-filter-error.mjs.map +1 -0
- package/esm/errors/context-length-exceeded-error.d.mts +38 -0
- package/esm/errors/context-length-exceeded-error.d.mts.map +1 -0
- package/esm/errors/context-length-exceeded-error.mjs +31 -0
- package/esm/errors/context-length-exceeded-error.mjs.map +1 -0
- package/esm/errors/error-category.type.d.mts +30 -0
- package/esm/errors/error-category.type.d.mts.map +1 -0
- package/esm/errors/error-code.type.d.mts +19 -0
- package/esm/errors/error-code.type.d.mts.map +1 -0
- package/esm/errors/guardrail-violation-error.d.mts +55 -0
- package/esm/errors/guardrail-violation-error.d.mts.map +1 -0
- package/esm/errors/guardrail-violation-error.mjs +41 -0
- package/esm/errors/guardrail-violation-error.mjs.map +1 -0
- package/esm/errors/index.d.mts +29 -0
- package/esm/errors/index.mjs +29 -0
- package/esm/errors/invalid-request-error.d.mts +27 -0
- package/esm/errors/invalid-request-error.d.mts.map +1 -0
- package/esm/errors/invalid-request-error.mjs +31 -0
- package/esm/errors/invalid-request-error.mjs.map +1 -0
- package/esm/errors/max-iterations-error.d.mts +31 -0
- package/esm/errors/max-iterations-error.d.mts.map +1 -0
- package/esm/errors/max-iterations-error.mjs +32 -0
- package/esm/errors/max-iterations-error.mjs.map +1 -0
- package/esm/errors/max-steps-exceeded-error.d.mts +20 -0
- package/esm/errors/max-steps-exceeded-error.d.mts.map +1 -0
- package/esm/errors/max-steps-exceeded-error.mjs +21 -0
- package/esm/errors/max-steps-exceeded-error.mjs.map +1 -0
- package/esm/errors/provider-auth-error.d.mts +22 -0
- package/esm/errors/provider-auth-error.d.mts.map +1 -0
- package/esm/errors/provider-auth-error.mjs +26 -0
- package/esm/errors/provider-auth-error.mjs.map +1 -0
- package/esm/errors/provider-error.d.mts +38 -0
- package/esm/errors/provider-error.d.mts.map +1 -0
- package/esm/errors/provider-error.mjs +42 -0
- package/esm/errors/provider-error.mjs.map +1 -0
- package/esm/errors/provider-rate-limit-error.d.mts +34 -0
- package/esm/errors/provider-rate-limit-error.d.mts.map +1 -0
- package/esm/errors/provider-rate-limit-error.mjs +31 -0
- package/esm/errors/provider-rate-limit-error.mjs.map +1 -0
- package/esm/errors/provider-timeout-error.d.mts +22 -0
- package/esm/errors/provider-timeout-error.d.mts.map +1 -0
- package/esm/errors/provider-timeout-error.mjs +26 -0
- package/esm/errors/provider-timeout-error.mjs.map +1 -0
- package/esm/errors/quota-exceeded-error.d.mts +36 -0
- package/esm/errors/quota-exceeded-error.d.mts.map +1 -0
- package/esm/errors/quota-exceeded-error.mjs +40 -0
- package/esm/errors/quota-exceeded-error.mjs.map +1 -0
- package/esm/errors/routing-error.d.mts +23 -0
- package/esm/errors/routing-error.d.mts.map +1 -0
- package/esm/errors/routing-error.mjs +23 -0
- package/esm/errors/routing-error.mjs.map +1 -0
- package/esm/errors/schema-validation-error.d.mts +40 -0
- package/esm/errors/schema-validation-error.d.mts.map +1 -0
- package/esm/errors/schema-validation-error.mjs +37 -0
- package/esm/errors/schema-validation-error.mjs.map +1 -0
- package/esm/errors/step-failed-error.d.mts +20 -0
- package/esm/errors/step-failed-error.d.mts.map +1 -0
- package/esm/errors/step-failed-error.mjs +19 -0
- package/esm/errors/step-failed-error.mjs.map +1 -0
- package/esm/errors/supervisor-cancelled-error.d.mts +29 -0
- package/esm/errors/supervisor-cancelled-error.d.mts.map +1 -0
- package/esm/errors/supervisor-cancelled-error.mjs +29 -0
- package/esm/errors/supervisor-cancelled-error.mjs.map +1 -0
- package/esm/errors/supervisor-drift-error.d.mts +31 -0
- package/esm/errors/supervisor-drift-error.d.mts.map +1 -0
- package/esm/errors/supervisor-drift-error.mjs +30 -0
- package/esm/errors/supervisor-drift-error.mjs.map +1 -0
- package/esm/errors/supervisor-failed-error.d.mts +40 -0
- package/esm/errors/supervisor-failed-error.d.mts.map +1 -0
- package/esm/errors/supervisor-failed-error.mjs +43 -0
- package/esm/errors/supervisor-failed-error.mjs.map +1 -0
- package/esm/errors/supervisor-routing-error.d.mts +44 -0
- package/esm/errors/supervisor-routing-error.d.mts.map +1 -0
- package/esm/errors/supervisor-routing-error.mjs +39 -0
- package/esm/errors/supervisor-routing-error.mjs.map +1 -0
- package/esm/errors/tool-execution-error.d.mts +35 -0
- package/esm/errors/tool-execution-error.d.mts.map +1 -0
- package/esm/errors/tool-execution-error.mjs +32 -0
- package/esm/errors/tool-execution-error.mjs.map +1 -0
- package/esm/errors/workflow-cancelled-error.d.mts +23 -0
- package/esm/errors/workflow-cancelled-error.d.mts.map +1 -0
- package/esm/errors/workflow-cancelled-error.mjs +23 -0
- package/esm/errors/workflow-cancelled-error.mjs.map +1 -0
- package/esm/errors/workflow-drift-error.d.mts +25 -0
- package/esm/errors/workflow-drift-error.d.mts.map +1 -0
- package/esm/errors/workflow-drift-error.mjs +24 -0
- package/esm/errors/workflow-drift-error.mjs.map +1 -0
- package/esm/errors/workflow-error.d.mts +15 -0
- package/esm/errors/workflow-error.d.mts.map +1 -0
- package/esm/errors/workflow-error.mjs +18 -0
- package/esm/errors/workflow-error.mjs.map +1 -0
- package/esm/index.d.mts +137 -0
- package/esm/index.mjs +81 -0
- package/esm/middleware/builtins/budget.d.mts +103 -0
- package/esm/middleware/builtins/budget.d.mts.map +1 -0
- package/esm/middleware/builtins/budget.mjs +100 -0
- package/esm/middleware/builtins/budget.mjs.map +1 -0
- package/esm/middleware/builtins/guardrail.d.mts +92 -0
- package/esm/middleware/builtins/guardrail.d.mts.map +1 -0
- package/esm/middleware/builtins/guardrail.mjs +76 -0
- package/esm/middleware/builtins/guardrail.mjs.map +1 -0
- package/esm/middleware/builtins/semantic-cache.d.mts +106 -0
- package/esm/middleware/builtins/semantic-cache.d.mts.map +1 -0
- package/esm/middleware/builtins/semantic-cache.mjs +149 -0
- package/esm/middleware/builtins/semantic-cache.mjs.map +1 -0
- package/esm/middleware/helpers/compose.d.mts +42 -0
- package/esm/middleware/helpers/compose.d.mts.map +1 -0
- package/esm/middleware/helpers/compose.mjs +52 -0
- package/esm/middleware/helpers/compose.mjs.map +1 -0
- package/esm/middleware/helpers/for-tool.d.mts +55 -0
- package/esm/middleware/helpers/for-tool.d.mts.map +1 -0
- package/esm/middleware/helpers/for-tool.mjs +80 -0
- package/esm/middleware/helpers/for-tool.mjs.map +1 -0
- package/esm/middleware/helpers/index.d.mts +2 -0
- package/esm/middleware/index.d.mts +8 -0
- package/esm/middleware/index.mjs +10 -0
- package/esm/middleware/pipeline.d.mts +70 -0
- package/esm/middleware/pipeline.d.mts.map +1 -0
- package/esm/middleware/pipeline.mjs +100 -0
- package/esm/middleware/pipeline.mjs.map +1 -0
- package/esm/middleware/utils/extract-user-text.d.mts +33 -0
- package/esm/middleware/utils/extract-user-text.d.mts.map +1 -0
- package/esm/middleware/utils/extract-user-text.mjs +40 -0
- package/esm/middleware/utils/extract-user-text.mjs.map +1 -0
- package/esm/middleware/utils/index.d.mts +2 -0
- package/esm/middleware/utils/namespaced-state.d.mts +60 -0
- package/esm/middleware/utils/namespaced-state.d.mts.map +1 -0
- package/esm/middleware/utils/namespaced-state.mjs +60 -0
- package/esm/middleware/utils/namespaced-state.mjs.map +1 -0
- package/esm/mock/index.d.mts +4 -0
- package/esm/mock/index.mjs +5 -0
- package/esm/mock/mock-agent.d.mts +41 -0
- package/esm/mock/mock-agent.d.mts.map +1 -0
- package/esm/mock/mock-agent.mjs +39 -0
- package/esm/mock/mock-agent.mjs.map +1 -0
- package/esm/mock/mock-config.type.d.mts +31 -0
- package/esm/mock/mock-config.type.d.mts.map +1 -0
- package/esm/mock/mock-model.d.mts +94 -0
- package/esm/mock/mock-model.d.mts.map +1 -0
- package/esm/mock/mock-model.mjs +150 -0
- package/esm/mock/mock-model.mjs.map +1 -0
- package/esm/mock/mock-sdk.d.mts +25 -0
- package/esm/mock/mock-sdk.d.mts.map +1 -0
- package/esm/mock/mock-sdk.mjs +37 -0
- package/esm/mock/mock-sdk.mjs.map +1 -0
- package/esm/supervisor/as-tool.d.mts +45 -0
- package/esm/supervisor/as-tool.d.mts.map +1 -0
- package/esm/supervisor/as-tool.mjs +80 -0
- package/esm/supervisor/as-tool.mjs.map +1 -0
- package/esm/supervisor/cancellation.d.mts +12 -0
- package/esm/supervisor/cancellation.d.mts.map +1 -0
- package/esm/supervisor/cancellation.mjs +22 -0
- package/esm/supervisor/cancellation.mjs.map +1 -0
- package/esm/supervisor/decide.mjs +272 -0
- package/esm/supervisor/decide.mjs.map +1 -0
- package/esm/supervisor/emitter.d.mts +27 -0
- package/esm/supervisor/emitter.d.mts.map +1 -0
- package/esm/supervisor/emitter.mjs +47 -0
- package/esm/supervisor/emitter.mjs.map +1 -0
- package/esm/supervisor/entries.d.mts +141 -0
- package/esm/supervisor/entries.d.mts.map +1 -0
- package/esm/supervisor/entries.mjs +206 -0
- package/esm/supervisor/entries.mjs.map +1 -0
- package/esm/supervisor/execution.d.mts +637 -0
- package/esm/supervisor/execution.d.mts.map +1 -0
- package/esm/supervisor/execution.mjs +1868 -0
- package/esm/supervisor/execution.mjs.map +1 -0
- package/esm/supervisor/index.d.mts +11 -0
- package/esm/supervisor/index.mjs +12 -0
- package/esm/supervisor/router-prompt.d.mts +56 -0
- package/esm/supervisor/router-prompt.d.mts.map +1 -0
- package/esm/supervisor/router-prompt.mjs +52 -0
- package/esm/supervisor/router-prompt.mjs.map +1 -0
- package/esm/supervisor/signature.d.mts +28 -0
- package/esm/supervisor/signature.d.mts.map +1 -0
- package/esm/supervisor/signature.mjs +89 -0
- package/esm/supervisor/signature.mjs.map +1 -0
- package/esm/supervisor/snapshot.d.mts +54 -0
- package/esm/supervisor/snapshot.d.mts.map +1 -0
- package/esm/supervisor/snapshot.mjs +77 -0
- package/esm/supervisor/snapshot.mjs.map +1 -0
- package/esm/supervisor/supervisor-stream.d.mts +29 -0
- package/esm/supervisor/supervisor-stream.d.mts.map +1 -0
- package/esm/supervisor/supervisor-stream.mjs +89 -0
- package/esm/supervisor/supervisor-stream.mjs.map +1 -0
- package/esm/supervisor/supervisor.d.mts +27 -0
- package/esm/supervisor/supervisor.d.mts.map +1 -0
- package/esm/supervisor/supervisor.mjs +138 -0
- package/esm/supervisor/supervisor.mjs.map +1 -0
- package/esm/system-prompt/instruction.d.mts +52 -0
- package/esm/system-prompt/instruction.d.mts.map +1 -0
- package/esm/system-prompt/instruction.mjs +57 -0
- package/esm/system-prompt/instruction.mjs.map +1 -0
- package/esm/system-prompt/persona.d.mts +52 -0
- package/esm/system-prompt/persona.d.mts.map +1 -0
- package/esm/system-prompt/persona.mjs +57 -0
- package/esm/system-prompt/persona.mjs.map +1 -0
- package/esm/system-prompt/render-placeholders.d.mts +31 -0
- package/esm/system-prompt/render-placeholders.d.mts.map +1 -0
- package/esm/system-prompt/render-placeholders.mjs +58 -0
- package/esm/system-prompt/render-placeholders.mjs.map +1 -0
- package/esm/system-prompt/system-prompt.d.mts +117 -0
- package/esm/system-prompt/system-prompt.d.mts.map +1 -0
- package/esm/system-prompt/system-prompt.mjs +137 -0
- package/esm/system-prompt/system-prompt.mjs.map +1 -0
- package/esm/tool/index.d.mts +1 -0
- package/esm/tool/index.mjs +3 -0
- package/esm/tool/tool.d.mts +64 -0
- package/esm/tool/tool.d.mts.map +1 -0
- package/esm/tool/tool.mjs +184 -0
- package/esm/tool/tool.mjs.map +1 -0
- package/esm/utils/compute-cost.d.mts +58 -0
- package/esm/utils/compute-cost.d.mts.map +1 -0
- package/esm/utils/compute-cost.mjs +87 -0
- package/esm/utils/compute-cost.mjs.map +1 -0
- package/esm/utils/extract-json-payload.d.mts +33 -0
- package/esm/utils/extract-json-payload.d.mts.map +1 -0
- package/esm/utils/extract-json-payload.mjs +39 -0
- package/esm/utils/extract-json-payload.mjs.map +1 -0
- package/esm/utils/generate-run-id.d.mts +20 -0
- package/esm/utils/generate-run-id.d.mts.map +1 -0
- package/esm/utils/generate-run-id.mjs +23 -0
- package/esm/utils/generate-run-id.mjs.map +1 -0
- package/esm/utils/index.d.mts +9 -0
- package/esm/utils/index.mjs +11 -0
- package/esm/utils/json-schema.d.mts +57 -0
- package/esm/utils/json-schema.d.mts.map +1 -0
- package/esm/utils/json-schema.mjs +89 -0
- package/esm/utils/json-schema.mjs.map +1 -0
- package/esm/utils/prepare-attachment-part.d.mts +36 -0
- package/esm/utils/prepare-attachment-part.d.mts.map +1 -0
- package/esm/utils/prepare-attachment-part.mjs +140 -0
- package/esm/utils/prepare-attachment-part.mjs.map +1 -0
- package/esm/utils/resolve-attachment.d.mts +33 -0
- package/esm/utils/resolve-attachment.d.mts.map +1 -0
- package/esm/utils/resolve-attachment.mjs +73 -0
- package/esm/utils/resolve-attachment.mjs.map +1 -0
- package/esm/utils/safe-json-parse.d.mts +14 -0
- package/esm/utils/safe-json-parse.d.mts.map +1 -0
- package/esm/utils/safe-json-parse.mjs +22 -0
- package/esm/utils/safe-json-parse.mjs.map +1 -0
- package/esm/utils/stamp-report-lineage.d.mts +61 -0
- package/esm/utils/stamp-report-lineage.d.mts.map +1 -0
- package/esm/utils/stamp-report-lineage.mjs +47 -0
- package/esm/utils/stamp-report-lineage.mjs.map +1 -0
- package/esm/utils/token-count.d.mts +15 -0
- package/esm/utils/token-count.d.mts.map +1 -0
- package/esm/utils/token-count.mjs +18 -0
- package/esm/utils/token-count.mjs.map +1 -0
- package/esm/workflow/as-tool.mjs +55 -0
- package/esm/workflow/as-tool.mjs.map +1 -0
- package/esm/workflow/cancellation.mjs +44 -0
- package/esm/workflow/cancellation.mjs.map +1 -0
- package/esm/workflow/emitter.mjs +40 -0
- package/esm/workflow/emitter.mjs.map +1 -0
- package/esm/workflow/engine.mjs +362 -0
- package/esm/workflow/engine.mjs.map +1 -0
- package/esm/workflow/index.d.mts +3 -0
- package/esm/workflow/index.mjs +5 -0
- package/esm/workflow/retry.mjs +32 -0
- package/esm/workflow/retry.mjs.map +1 -0
- package/esm/workflow/router.mjs +56 -0
- package/esm/workflow/router.mjs.map +1 -0
- package/esm/workflow/run-scoped-emitter.mjs +32 -0
- package/esm/workflow/run-scoped-emitter.mjs.map +1 -0
- package/esm/workflow/signature.d.mts +7 -0
- package/esm/workflow/signature.d.mts.map +1 -0
- package/esm/workflow/signature.mjs +34 -0
- package/esm/workflow/signature.mjs.map +1 -0
- package/esm/workflow/snapshot.mjs +71 -0
- package/esm/workflow/snapshot.mjs.map +1 -0
- package/esm/workflow/state.mjs +37 -0
- package/esm/workflow/state.mjs.map +1 -0
- package/esm/workflow/step-runner.mjs +371 -0
- package/esm/workflow/step-runner.mjs.map +1 -0
- package/esm/workflow/step.d.mts +19 -0
- package/esm/workflow/step.d.mts.map +1 -0
- package/esm/workflow/step.mjs +37 -0
- package/esm/workflow/step.mjs.map +1 -0
- package/esm/workflow/workflow.d.mts +12 -0
- package/esm/workflow/workflow.d.mts.map +1 -0
- package/esm/workflow/workflow.mjs +116 -0
- package/esm/workflow/workflow.mjs.map +1 -0
- package/llms-full.txt +2293 -0
- package/llms.txt +20 -0
- package/package.json +37 -0
- package/skills/README.md +53 -0
- package/skills/ai-basics/SKILL.md +95 -0
- package/skills/attach-ai-middleware/SKILL.md +184 -0
- package/skills/define-ai-tool/SKILL.md +186 -0
- package/skills/embed-text/SKILL.md +105 -0
- package/skills/handle-ai-errors/SKILL.md +194 -0
- package/skills/log-ai-calls/SKILL.md +141 -0
- package/skills/persist-ai-data/SKILL.md +207 -0
- package/skills/pick-ai-provider/SKILL.md +164 -0
- package/skills/run-ai-agent/SKILL.md +267 -0
- package/skills/run-ai-workflow/SKILL.md +258 -0
- package/skills/run-supervisor/SKILL.md +309 -0
- package/skills/write-system-prompt/SKILL.md +129 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { SchemaValidationError } from "../errors/schema-validation-error.mjs";
|
|
2
|
+
import { ToolExecutionError } from "../errors/tool-execution-error.mjs";
|
|
3
|
+
import "../errors/index.mjs";
|
|
4
|
+
import { generateRunId } from "../utils/generate-run-id.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../../@warlock.js/ai/src/tool/tool.ts
|
|
7
|
+
/**
|
|
8
|
+
* Degraded `ToolContext` supplied when no caller threads one through
|
|
9
|
+
* (`tool.invoke(input)` standalone, batch scripts, tests). Per
|
|
10
|
+
* decisions §35 — mutations on the empty bag are harmless no-ops;
|
|
11
|
+
* production paths under a supervisor receive a real ctx with the
|
|
12
|
+
* iteration's shared bag.
|
|
13
|
+
*/
|
|
14
|
+
function defaultToolContext() {
|
|
15
|
+
return { artifacts: {} };
|
|
16
|
+
}
|
|
17
|
+
const EMPTY_USAGE = Object.freeze({
|
|
18
|
+
input: 0,
|
|
19
|
+
output: 0,
|
|
20
|
+
total: 0
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Wraps a raw `ToolConfig` and adds a safe `invoke()` method for the agent runtime.
|
|
24
|
+
* The returned object preserves all original contract fields unchanged.
|
|
25
|
+
*
|
|
26
|
+
* Error categorization:
|
|
27
|
+
* - Input schema rejects model args → `SchemaValidationError` (issues preserved).
|
|
28
|
+
* - Schema's `validate()` itself throws → `SchemaValidationError` wrapping the cause.
|
|
29
|
+
* - `execute()` throws → `ToolExecutionError` wrapping the cause.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* const weatherTool = tool({
|
|
33
|
+
* name: "getWeather",
|
|
34
|
+
* description: "Fetch current weather for a city",
|
|
35
|
+
* input: z.object({ city: z.string() }),
|
|
36
|
+
* execute: async ({ city }) => ({ temp: 72 }),
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* const result = await weatherTool.invoke({ city: "Cairo" });
|
|
40
|
+
*/
|
|
41
|
+
/**
|
|
42
|
+
* Internal factory for `asTool()` wrappers on composite primitives
|
|
43
|
+
* (agent / workflow / supervisor). Unlike the public `tool()` factory
|
|
44
|
+
* (which synthesizes a leaf `BaseReport` every time), this variant
|
|
45
|
+
* lets the composite's own `ExecuteResult` flow through: the inner
|
|
46
|
+
* primitive's `report` becomes the sole child of the outer tool-call
|
|
47
|
+
* node, and the inner `usage` is surfaced so parents can roll it up.
|
|
48
|
+
*
|
|
49
|
+
* The caller supplies `execute()` returning `{ data, usage, report }`
|
|
50
|
+
* from the composite's own `execute()` method. Validation failures
|
|
51
|
+
* and thrown errors still produce a synthesized failed leaf report —
|
|
52
|
+
* the inner-report propagation is strictly a success-path concern.
|
|
53
|
+
*
|
|
54
|
+
* Not exported from the package barrel — used by `agent.asTool()`,
|
|
55
|
+
* `workflow.asTool()`, `supervisor.asTool()` only.
|
|
56
|
+
*/
|
|
57
|
+
function compositeAsTool(contract) {
|
|
58
|
+
const publicExecute = async (input) => {
|
|
59
|
+
const envelope = await contract.execute(input);
|
|
60
|
+
if (envelope.error) throw envelope.error;
|
|
61
|
+
return envelope.data;
|
|
62
|
+
};
|
|
63
|
+
return {
|
|
64
|
+
name: contract.name,
|
|
65
|
+
description: contract.description ?? `Composite tool "${contract.name}".`,
|
|
66
|
+
meta: contract.meta,
|
|
67
|
+
input: contract.input,
|
|
68
|
+
execute: publicExecute,
|
|
69
|
+
async invoke(rawInput, _ctx) {
|
|
70
|
+
const startedAtDate = /* @__PURE__ */ new Date();
|
|
71
|
+
const start = performance.now();
|
|
72
|
+
const runId = generateRunId("tool");
|
|
73
|
+
const failLeaf = (error) => {
|
|
74
|
+
const endedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
75
|
+
const duration = performance.now() - start;
|
|
76
|
+
return {
|
|
77
|
+
error,
|
|
78
|
+
usage: EMPTY_USAGE,
|
|
79
|
+
report: {
|
|
80
|
+
runId,
|
|
81
|
+
rootRunId: runId,
|
|
82
|
+
name: contract.name,
|
|
83
|
+
version: contract.version,
|
|
84
|
+
type: "tool",
|
|
85
|
+
status: "failed",
|
|
86
|
+
startedAt: startedAtDate.toISOString(),
|
|
87
|
+
endedAt,
|
|
88
|
+
duration,
|
|
89
|
+
usage: EMPTY_USAGE,
|
|
90
|
+
children: []
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
let validationResult;
|
|
95
|
+
try {
|
|
96
|
+
validationResult = await contract.input["~standard"].validate(rawInput);
|
|
97
|
+
} catch (thrown) {
|
|
98
|
+
const message = thrown instanceof Error ? thrown.message : String(thrown);
|
|
99
|
+
return failLeaf(new SchemaValidationError(`Schema validation threw for tool "${contract.name}": ${message}`, {
|
|
100
|
+
cause: thrown,
|
|
101
|
+
context: { toolName: contract.name }
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
if (validationResult.issues) return failLeaf(new SchemaValidationError(`Validation failed: ${validationResult.issues.map((issue) => issue.message).join("; ")}`, {
|
|
105
|
+
issues: validationResult.issues,
|
|
106
|
+
context: { toolName: contract.name }
|
|
107
|
+
}));
|
|
108
|
+
try {
|
|
109
|
+
const composite = await contract.execute(validationResult.value);
|
|
110
|
+
return {
|
|
111
|
+
data: composite.data,
|
|
112
|
+
error: composite.error,
|
|
113
|
+
usage: composite.usage,
|
|
114
|
+
report: composite.report
|
|
115
|
+
};
|
|
116
|
+
} catch (thrown) {
|
|
117
|
+
return failLeaf(new ToolExecutionError(thrown instanceof Error ? thrown.message : String(thrown), {
|
|
118
|
+
cause: thrown,
|
|
119
|
+
toolName: contract.name
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function tool(contract) {
|
|
126
|
+
return {
|
|
127
|
+
...contract,
|
|
128
|
+
async invoke(rawInput, ctx) {
|
|
129
|
+
const startedAtDate = /* @__PURE__ */ new Date();
|
|
130
|
+
const start = performance.now();
|
|
131
|
+
const runId = generateRunId("tool");
|
|
132
|
+
const handlerCtx = ctx ?? defaultToolContext();
|
|
133
|
+
const finish = (partial) => {
|
|
134
|
+
const endedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
135
|
+
const duration = performance.now() - start;
|
|
136
|
+
const status = partial.error ? "failed" : "completed";
|
|
137
|
+
const report = {
|
|
138
|
+
runId,
|
|
139
|
+
rootRunId: runId,
|
|
140
|
+
name: contract.name,
|
|
141
|
+
version: contract.version,
|
|
142
|
+
type: "tool",
|
|
143
|
+
status,
|
|
144
|
+
startedAt: startedAtDate.toISOString(),
|
|
145
|
+
endedAt,
|
|
146
|
+
duration,
|
|
147
|
+
usage: EMPTY_USAGE,
|
|
148
|
+
children: []
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
...partial,
|
|
152
|
+
usage: EMPTY_USAGE,
|
|
153
|
+
report
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
let validationResult;
|
|
157
|
+
try {
|
|
158
|
+
validationResult = await contract.input["~standard"].validate(rawInput);
|
|
159
|
+
} catch (thrown) {
|
|
160
|
+
const message = thrown instanceof Error ? thrown.message : String(thrown);
|
|
161
|
+
return finish({ error: new SchemaValidationError(`Schema validation threw for tool "${contract.name}": ${message}`, {
|
|
162
|
+
cause: thrown,
|
|
163
|
+
context: { toolName: contract.name }
|
|
164
|
+
}) });
|
|
165
|
+
}
|
|
166
|
+
if (validationResult.issues) return finish({ error: new SchemaValidationError(`Validation failed: ${validationResult.issues.map((issue) => issue.message).join("; ")}`, {
|
|
167
|
+
issues: validationResult.issues,
|
|
168
|
+
context: { toolName: contract.name }
|
|
169
|
+
}) });
|
|
170
|
+
try {
|
|
171
|
+
return finish({ data: await contract.execute(validationResult.value, handlerCtx) });
|
|
172
|
+
} catch (thrown) {
|
|
173
|
+
return finish({ error: new ToolExecutionError(thrown instanceof Error ? thrown.message : String(thrown), {
|
|
174
|
+
cause: thrown,
|
|
175
|
+
toolName: contract.name
|
|
176
|
+
}) });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
//#endregion
|
|
183
|
+
export { compositeAsTool, tool };
|
|
184
|
+
//# sourceMappingURL=tool.mjs.map
|
|
@@ -0,0 +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":";;;;;;;;;;;;;AAcA,SAAS,qBAAkC;CACzC,OAAO,EAAE,WAAW,CAAC,EAAE;AACzB;AAEA,MAAM,cAAqB,OAAO,OAAO;CAAE,OAAO;CAAG,QAAQ;CAAG,OAAO;AAAE,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmG1E,SAAgB,gBAAiC,UAaf;CAMhC,MAAM,gBAAgB,OAAO,UAAoC;EAC/D,MAAM,WAAW,MAAM,SAAS,QAAQ,KAAK;EAC7C,IAAI,SAAS,OAAO,MAAM,SAAS;EACnC,OAAO,SAAS;CAClB;CAEA,OAAO;EACL,MAAM,SAAS;EACf,aAAa,SAAS,eAAe,mBAAmB,SAAS,KAAK;EACtE,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,SAAS;EAET,MAAM,OAAO,UAAmB,MAAwD;GAMtF,MAAM,gCAAgB,IAAI,KAAK;GAC/B,MAAM,QAAQ,YAAY,IAAI;GAC9B,MAAM,QAAQ,cAAc,MAAM;GAElC,MAAM,YAAY,UAA8C;IAC9D,MAAM,2BAAU,IAAI,KAAK,GAAE,YAAY;IACvC,MAAM,WAAW,YAAY,IAAI,IAAI;IACrC,OAAO;KACL;KACA,OAAO;KACP,QAAQ;MACN;MACA,WAAW;MACX,MAAM,SAAS;MACf,SAAS,SAAS;MAClB,MAAM;MACN,QAAQ;MACR,WAAW,cAAc,YAAY;MACrC;MACA;MACA,OAAO;MACP,UAAU,CAAC;KACb;IACF;GACF;GAEA,IAAI;GACJ,IAAI;IAEF,mBAAmB,MADJ,SAAS,MACQ,aAAa,SAAS,QAAQ;GAChE,SAAS,QAAQ;IACf,MAAM,UAAU,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;IACxE,OAAO,SACL,IAAI,sBACF,qCAAqC,SAAS,KAAK,KAAK,WACxD;KAAE,OAAO;KAAQ,SAAS,EAAE,UAAU,SAAS,KAAK;IAAE,CACxD,CACF;GACF;GAEA,IAAI,iBAAiB,QAEnB,OAAO,SACL,IAAI,sBAAsB,sBAFZ,iBAAiB,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,KAAK,IAEnB,KAAK;IACzD,QAAQ,iBAAiB;IACzB,SAAS,EAAE,UAAU,SAAS,KAAK;GACrC,CAAC,CACH;GAGF,IAAI;IACF,MAAM,YAAY,MAAM,SAAS,QAAQ,iBAAiB,KAAK;IAK/D,OAAO;KACL,MAAM,UAAU;KAChB,OAAO,UAAU;KACjB,OAAO,UAAU;KACjB,QAAQ,UAAU;IACpB;GACF,SAAS,QAAQ;IAEf,OAAO,SACL,IAAI,mBAFU,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM,GAEtC;KAC9B,OAAO;KACP,UAAU,SAAS;IACrB,CAAC,CACH;GACF;EACF;CACF;AACF;AAEA,SAAgB,KACd,UAC+B;CAC/B,OAAO;EACL,GAAG;EAEH,MAAM,OAAO,UAAmB,KAAuD;GACrF,MAAM,gCAAgB,IAAI,KAAK;GAC/B,MAAM,QAAQ,YAAY,IAAI;GAC9B,MAAM,QAAQ,cAAc,MAAM;GAClC,MAAM,aAAa,OAAO,mBAAmB;GAE7C,MAAM,UAAU,YAA4E;IAC1F,MAAM,2BAAU,IAAI,KAAK,GAAE,YAAY;IACvC,MAAM,WAAW,YAAY,IAAI,IAAI;IACrC,MAAM,SAA+B,QAAQ,QAAQ,WAAW;IAChE,MAAM,SAAqB;KACzB;KACA,WAAW;KACX,MAAM,SAAS;KACf,SAAS,SAAS;KAClB,MAAM;KACN;KACA,WAAW,cAAc,YAAY;KACrC;KACA;KACA,OAAO;KACP,UAAU,CAAC;IACb;IAEA,OAAO;KACL,GAAG;KACH,OAAO;KACP;IACF;GACF;GAEA,IAAI;GACJ,IAAI;IAEF,mBAAmB,MADJ,SAAS,MACQ,aAAa,SAAS,QAAQ;GAChE,SAAS,QAAQ;IACf,MAAM,UAAU,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;IAExE,OAAO,OAAO,EACZ,OAAO,IAAI,sBACT,qCAAqC,SAAS,KAAK,KAAK,WACxD;KAAE,OAAO;KAAQ,SAAS,EAAE,UAAU,SAAS,KAAK;IAAE,CACxD,EACF,CAAC;GACH;GAEA,IAAI,iBAAiB,QAGnB,OAAO,OAAO,EACZ,OAAO,IAAI,sBAAsB,sBAHnB,iBAAiB,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,KAAK,IAGZ,KAAK;IAChE,QAAQ,iBAAiB;IACzB,SAAS,EAAE,UAAU,SAAS,KAAK;GACrC,CAAC,EACH,CAAC;GAGH,IAAI;IAEF,OAAO,OAAO,EAAE,MAAM,MADD,SAAS,QAAQ,iBAAiB,OAAO,UAAU,EAC3C,CAAC;GAChC,SAAS,QAAQ;IAGf,OAAO,OAAO,EACZ,OAAO,IAAI,mBAHG,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM,GAG/B;KACrC,OAAO;KACP,UAAU,SAAS;IACrB,CAAC,EACH,CAAC;GACH;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ModelPricing } from "../contracts/result/model-pricing.type.mjs";
|
|
2
|
+
import { Usage } from "../contracts/result/usage.type.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../@warlock.js/ai/src/utils/compute-cost.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Compute a per-channel USD cost breakdown for a single `Usage` against
|
|
7
|
+
* a model's pricing table. Returns `undefined` when no pricing is
|
|
8
|
+
* configured — the framework treats unpriced runs as "cost unknown,"
|
|
9
|
+
* not "cost zero," so dashboards can distinguish free-tier from
|
|
10
|
+
* un-instrumented.
|
|
11
|
+
*
|
|
12
|
+
* **Shape mirrors `ModelPricing`** — `input`, `output`, optional
|
|
13
|
+
* `cachedInput` / `cachedOutput`. Consumers needing a scalar total
|
|
14
|
+
* sum the populated fields. The breakdown is the value-add: it tells
|
|
15
|
+
* downstream tooling HOW the total was reached (input-vs-output
|
|
16
|
+
* share, cache savings) without re-deriving against pricing tables
|
|
17
|
+
* that may have shifted since the report was written.
|
|
18
|
+
*
|
|
19
|
+
* **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`
|
|
20
|
+
* served from the provider's prompt cache and bills at
|
|
21
|
+
* `pricing.cachedInput` (falls back to full `pricing.input` when the
|
|
22
|
+
* provider doesn't publish a cache rate). The remaining `input -
|
|
23
|
+
* cachedTokens` bills at full rate and shows up in `cost.input`. The
|
|
24
|
+
* `cachedOutput` channel is reserved for Anthropic-style cache writes;
|
|
25
|
+
* until an adapter populates `usage.cacheWriteTokens`, the framework
|
|
26
|
+
* leaves it undefined.
|
|
27
|
+
*
|
|
28
|
+
* Pricing values are USD-per-million-tokens. The function divides
|
|
29
|
+
* once at the end to avoid floating-point accumulation error on
|
|
30
|
+
* per-token math.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };
|
|
34
|
+
* const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });
|
|
35
|
+
* // cost = {
|
|
36
|
+
* // input: (60_000 * 0.15) / 1e6 = 0.009,
|
|
37
|
+
* // output: (30_000 * 0.6) / 1e6 = 0.018,
|
|
38
|
+
* // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,
|
|
39
|
+
* // }
|
|
40
|
+
*/
|
|
41
|
+
declare function computeCost(usage: Usage, pricing: ModelPricing | undefined): ModelPricing | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Merge a child's cost breakdown into a running parent total. Each
|
|
44
|
+
* channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums
|
|
45
|
+
* independently — an undefined channel on either side is treated as
|
|
46
|
+
* zero contribution rather than dropping the other side's value. A
|
|
47
|
+
* single unpriced child should never erase the cost of its priced
|
|
48
|
+
* siblings.
|
|
49
|
+
*
|
|
50
|
+
* Returns the new parent breakdown, or `undefined` when neither parent
|
|
51
|
+
* nor child carried any cost data (preserves the "no priced
|
|
52
|
+
* contributor has appeared yet" signal that distinguishes "missing
|
|
53
|
+
* pricing" from "genuinely zero").
|
|
54
|
+
*/
|
|
55
|
+
declare function accumulateCost(parent: ModelPricing | undefined, child: ModelPricing | undefined): ModelPricing | undefined;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { accumulateCost, computeCost };
|
|
58
|
+
//# sourceMappingURL=compute-cost.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
//#region ../../@warlock.js/ai/src/utils/compute-cost.ts
|
|
2
|
+
/**
|
|
3
|
+
* Compute a per-channel USD cost breakdown for a single `Usage` against
|
|
4
|
+
* a model's pricing table. Returns `undefined` when no pricing is
|
|
5
|
+
* configured — the framework treats unpriced runs as "cost unknown,"
|
|
6
|
+
* not "cost zero," so dashboards can distinguish free-tier from
|
|
7
|
+
* un-instrumented.
|
|
8
|
+
*
|
|
9
|
+
* **Shape mirrors `ModelPricing`** — `input`, `output`, optional
|
|
10
|
+
* `cachedInput` / `cachedOutput`. Consumers needing a scalar total
|
|
11
|
+
* sum the populated fields. The breakdown is the value-add: it tells
|
|
12
|
+
* downstream tooling HOW the total was reached (input-vs-output
|
|
13
|
+
* share, cache savings) without re-deriving against pricing tables
|
|
14
|
+
* that may have shifted since the report was written.
|
|
15
|
+
*
|
|
16
|
+
* **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`
|
|
17
|
+
* served from the provider's prompt cache and bills at
|
|
18
|
+
* `pricing.cachedInput` (falls back to full `pricing.input` when the
|
|
19
|
+
* provider doesn't publish a cache rate). The remaining `input -
|
|
20
|
+
* cachedTokens` bills at full rate and shows up in `cost.input`. The
|
|
21
|
+
* `cachedOutput` channel is reserved for Anthropic-style cache writes;
|
|
22
|
+
* until an adapter populates `usage.cacheWriteTokens`, the framework
|
|
23
|
+
* leaves it undefined.
|
|
24
|
+
*
|
|
25
|
+
* Pricing values are USD-per-million-tokens. The function divides
|
|
26
|
+
* once at the end to avoid floating-point accumulation error on
|
|
27
|
+
* per-token math.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };
|
|
31
|
+
* const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });
|
|
32
|
+
* // cost = {
|
|
33
|
+
* // input: (60_000 * 0.15) / 1e6 = 0.009,
|
|
34
|
+
* // output: (30_000 * 0.6) / 1e6 = 0.018,
|
|
35
|
+
* // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,
|
|
36
|
+
* // }
|
|
37
|
+
*/
|
|
38
|
+
function computeCost(usage, pricing) {
|
|
39
|
+
if (!pricing) return;
|
|
40
|
+
const cachedInput = usage.cachedTokens ?? 0;
|
|
41
|
+
const cost = {
|
|
42
|
+
input: Math.max(0, usage.input - cachedInput) * pricing.input / 1e6,
|
|
43
|
+
output: usage.output * pricing.output / 1e6
|
|
44
|
+
};
|
|
45
|
+
if (cachedInput > 0) cost.cachedInput = cachedInput * (pricing.cachedInput ?? pricing.input) / 1e6;
|
|
46
|
+
return cost;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Merge a child's cost breakdown into a running parent total. Each
|
|
50
|
+
* channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums
|
|
51
|
+
* independently — an undefined channel on either side is treated as
|
|
52
|
+
* zero contribution rather than dropping the other side's value. A
|
|
53
|
+
* single unpriced child should never erase the cost of its priced
|
|
54
|
+
* siblings.
|
|
55
|
+
*
|
|
56
|
+
* Returns the new parent breakdown, or `undefined` when neither parent
|
|
57
|
+
* nor child carried any cost data (preserves the "no priced
|
|
58
|
+
* contributor has appeared yet" signal that distinguishes "missing
|
|
59
|
+
* pricing" from "genuinely zero").
|
|
60
|
+
*/
|
|
61
|
+
function accumulateCost(parent, child) {
|
|
62
|
+
if (!child) return parent;
|
|
63
|
+
if (!parent) return { ...child };
|
|
64
|
+
const merged = {
|
|
65
|
+
input: parent.input + child.input,
|
|
66
|
+
output: parent.output + child.output
|
|
67
|
+
};
|
|
68
|
+
const cachedInput = sumOptional(parent.cachedInput, child.cachedInput);
|
|
69
|
+
if (cachedInput !== void 0) merged.cachedInput = cachedInput;
|
|
70
|
+
const cachedOutput = sumOptional(parent.cachedOutput, child.cachedOutput);
|
|
71
|
+
if (cachedOutput !== void 0) merged.cachedOutput = cachedOutput;
|
|
72
|
+
return merged;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Add two optional numbers, treating either side's `undefined` as
|
|
76
|
+
* zero — but return `undefined` when both are absent. Keeps "this
|
|
77
|
+
* channel was never reported anywhere" distinguishable from "this
|
|
78
|
+
* channel was reported as 0."
|
|
79
|
+
*/
|
|
80
|
+
function sumOptional(parent, child) {
|
|
81
|
+
if (parent === void 0 && child === void 0) return;
|
|
82
|
+
return (parent ?? 0) + (child ?? 0);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
//#endregion
|
|
86
|
+
export { accumulateCost, computeCost };
|
|
87
|
+
//# sourceMappingURL=compute-cost.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
//#region ../../@warlock.js/ai/src/utils/extract-json-payload.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Strip markdown code fences from an LLM response before JSON parsing.
|
|
4
|
+
*
|
|
5
|
+
* Models — especially Claude, smaller models, and local models — routinely
|
|
6
|
+
* wrap JSON output in fenced code blocks (` ```json\n{...}\n``` `) even when
|
|
7
|
+
* instructed otherwise. Sometimes they also precede the fence with prose
|
|
8
|
+
* ("Here you go:\n```json\n...\n```"). This helper finds the first fenced
|
|
9
|
+
* block regardless of language tag and returns its trimmed contents.
|
|
10
|
+
*
|
|
11
|
+
* Returns the trimmed original text unchanged when no fence is present, so
|
|
12
|
+
* clean JSON passes through as a no-op.
|
|
13
|
+
*
|
|
14
|
+
* Deliberately does NOT fall back to "find first `{` and last `}` and slice
|
|
15
|
+
* between them" — that heuristic silently corrupts data when prose contains
|
|
16
|
+
* stray braces. Failing loudly at `JSON.parse` is safer.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* extractJsonPayload('```json\n{"a":1}\n```');
|
|
20
|
+
* // => '{"a":1}'
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* extractJsonPayload('Here you go:\n```\n{"a":1}\n```\nHope this helps.');
|
|
24
|
+
* // => '{"a":1}'
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* extractJsonPayload('{"a":1}');
|
|
28
|
+
* // => '{"a":1}' (no fence → unchanged)
|
|
29
|
+
*/
|
|
30
|
+
declare function extractJsonPayload(text: string): string;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { extractJsonPayload };
|
|
33
|
+
//# sourceMappingURL=extract-json-payload.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
//#region ../../@warlock.js/ai/src/utils/extract-json-payload.ts
|
|
2
|
+
/**
|
|
3
|
+
* Strip markdown code fences from an LLM response before JSON parsing.
|
|
4
|
+
*
|
|
5
|
+
* Models — especially Claude, smaller models, and local models — routinely
|
|
6
|
+
* wrap JSON output in fenced code blocks (` ```json\n{...}\n``` `) even when
|
|
7
|
+
* instructed otherwise. Sometimes they also precede the fence with prose
|
|
8
|
+
* ("Here you go:\n```json\n...\n```"). This helper finds the first fenced
|
|
9
|
+
* block regardless of language tag and returns its trimmed contents.
|
|
10
|
+
*
|
|
11
|
+
* Returns the trimmed original text unchanged when no fence is present, so
|
|
12
|
+
* clean JSON passes through as a no-op.
|
|
13
|
+
*
|
|
14
|
+
* Deliberately does NOT fall back to "find first `{` and last `}` and slice
|
|
15
|
+
* between them" — that heuristic silently corrupts data when prose contains
|
|
16
|
+
* stray braces. Failing loudly at `JSON.parse` is safer.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* extractJsonPayload('```json\n{"a":1}\n```');
|
|
20
|
+
* // => '{"a":1}'
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* extractJsonPayload('Here you go:\n```\n{"a":1}\n```\nHope this helps.');
|
|
24
|
+
* // => '{"a":1}'
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* extractJsonPayload('{"a":1}');
|
|
28
|
+
* // => '{"a":1}' (no fence → unchanged)
|
|
29
|
+
*/
|
|
30
|
+
function extractJsonPayload(text) {
|
|
31
|
+
const trimmed = text.trim();
|
|
32
|
+
const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
|
|
33
|
+
if (fenceMatch) return fenceMatch[1].trim();
|
|
34
|
+
return trimmed;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
export { extractJsonPayload };
|
|
39
|
+
//# sourceMappingURL=extract-json-payload.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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,GAAG,KAAK;CAG5B,OAAO;AACT"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region ../../@warlock.js/ai/src/utils/generate-run-id.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Generates a stable, human-readable run id for any execution node
|
|
4
|
+
* (tool invocation, agent run, workflow run, supervisor run). Format:
|
|
5
|
+
* `${prefix}_${timestamp36}_${random36}` — compact, sortable by
|
|
6
|
+
* prefix, collision-resistant within a run.
|
|
7
|
+
*
|
|
8
|
+
* Shared helper so every primitive emits the same id shape. The
|
|
9
|
+
* prefix is conventionally the primitive kind (`"tool"`, `"agent"`,
|
|
10
|
+
* `"workflow"`, `"sup"`) but callers can pass anything; the id is
|
|
11
|
+
* purely for correlation, never parsed.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const runId = generateRunId("tool");
|
|
15
|
+
* // → "tool_ld8x3m_7fq2j1kp"
|
|
16
|
+
*/
|
|
17
|
+
declare function generateRunId(prefix: string): string;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { generateRunId };
|
|
20
|
+
//# sourceMappingURL=generate-run-id.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region ../../@warlock.js/ai/src/utils/generate-run-id.ts
|
|
2
|
+
/**
|
|
3
|
+
* Generates a stable, human-readable run id for any execution node
|
|
4
|
+
* (tool invocation, agent run, workflow run, supervisor run). Format:
|
|
5
|
+
* `${prefix}_${timestamp36}_${random36}` — compact, sortable by
|
|
6
|
+
* prefix, collision-resistant within a run.
|
|
7
|
+
*
|
|
8
|
+
* Shared helper so every primitive emits the same id shape. The
|
|
9
|
+
* prefix is conventionally the primitive kind (`"tool"`, `"agent"`,
|
|
10
|
+
* `"workflow"`, `"sup"`) but callers can pass anything; the id is
|
|
11
|
+
* purely for correlation, never parsed.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const runId = generateRunId("tool");
|
|
15
|
+
* // → "tool_ld8x3m_7fq2j1kp"
|
|
16
|
+
*/
|
|
17
|
+
function generateRunId(prefix) {
|
|
18
|
+
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//#endregion
|
|
22
|
+
export { generateRunId };
|
|
23
|
+
//# sourceMappingURL=generate-run-id.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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,EAAE,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,EACxD,SAAS,EAAE,EACX,MAAM,GAAG,EAAE;AAChB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { accumulateCost, computeCost } from "./compute-cost.mjs";
|
|
2
|
+
import { extractJsonPayload } from "./extract-json-payload.mjs";
|
|
3
|
+
import { generateRunId } from "./generate-run-id.mjs";
|
|
4
|
+
import { extractJsonSchema } from "./json-schema.mjs";
|
|
5
|
+
import { prepareAttachmentPart } from "./prepare-attachment-part.mjs";
|
|
6
|
+
import { resolveAttachment } from "./resolve-attachment.mjs";
|
|
7
|
+
import { safeJsonParse } from "./safe-json-parse.mjs";
|
|
8
|
+
import { LineageStamp, stampReportLineage } from "./stamp-report-lineage.mjs";
|
|
9
|
+
import { approximateTokenCount } from "./token-count.mjs";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { accumulateCost, computeCost } from "./compute-cost.mjs";
|
|
2
|
+
import { extractJsonPayload } from "./extract-json-payload.mjs";
|
|
3
|
+
import { generateRunId } from "./generate-run-id.mjs";
|
|
4
|
+
import { extractJsonSchema } from "./json-schema.mjs";
|
|
5
|
+
import { resolveAttachment } from "./resolve-attachment.mjs";
|
|
6
|
+
import { prepareAttachmentPart } from "./prepare-attachment-part.mjs";
|
|
7
|
+
import { safeJsonParse } from "./safe-json-parse.mjs";
|
|
8
|
+
import { stampReportLineage } from "./stamp-report-lineage.mjs";
|
|
9
|
+
import { approximateTokenCount } from "./token-count.mjs";
|
|
10
|
+
|
|
11
|
+
export { };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
|
|
3
|
+
//#region ../../@warlock.js/ai/src/utils/json-schema.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Supported JSON Schema output targets per the Standard JSON Schema V1
|
|
6
|
+
* spec. `openai-strict` is the richest for OpenAI structured outputs —
|
|
7
|
+
* every property listed in `required`, optionals expressed as
|
|
8
|
+
* `["T", "null"]`, `additionalProperties: false` everywhere. Other
|
|
9
|
+
* targets produce standards-compliant but looser output.
|
|
10
|
+
*/
|
|
11
|
+
type JsonSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | "openai-strict";
|
|
12
|
+
/**
|
|
13
|
+
* Options for `extractJsonSchema`. `target` is forwarded to libraries that
|
|
14
|
+
* implement the Standard JSON Schema V1 spec (Seal, and any future lib
|
|
15
|
+
* that follows the spec). Libraries using their own top-level `.jsonSchema`
|
|
16
|
+
* / `._jsonSchema` property ignore the target.
|
|
17
|
+
*/
|
|
18
|
+
type ExtractJsonSchemaOptions = {
|
|
19
|
+
target?: JsonSchemaTarget | (string & {});
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Best-effort JSON Schema extraction from a Standard Schema instance.
|
|
23
|
+
*
|
|
24
|
+
* Different libraries expose their JSON representation through different
|
|
25
|
+
* paths:
|
|
26
|
+
* - **Seal / Standard JSON Schema V1**: `["~standard"].jsonSchema.input({ target })`
|
|
27
|
+
* — nested under the spec object, takes a target switch. Default target
|
|
28
|
+
* is `"openai-strict"` since the primary consumer is OpenAI's native
|
|
29
|
+
* structured-output mechanism; pass `options.target` to override.
|
|
30
|
+
* - **Zod / similar**: top-level `.jsonSchema` property. Zod v4 actually
|
|
31
|
+
* ships `toJSONSchema` as a module function, not a method, so it does
|
|
32
|
+
* NOT hit this probe — Zod users pass their converted schema via the
|
|
33
|
+
* `AgentExecuteOptions.responseSchema` escape hatch.
|
|
34
|
+
*
|
|
35
|
+
* Deliberately does NOT probe `toJSON` — that's a generic JavaScript
|
|
36
|
+
* serialization hook (Seal's schemas have one that dumps internal rule
|
|
37
|
+
* state) and matching it would return garbage disguised as a JSON Schema.
|
|
38
|
+
*
|
|
39
|
+
* Returns `undefined` when no path matches. The caller then either skips
|
|
40
|
+
* native structured-output wiring or falls back to a schema-less
|
|
41
|
+
* instruction.
|
|
42
|
+
*
|
|
43
|
+
* Shared across every SDK adapter package (OpenAI, Anthropic, Bedrock…)
|
|
44
|
+
* so each provider converts schemas identically.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* const schema = extractJsonSchema(mySealSchema);
|
|
48
|
+
* // { type: "object", properties: { ... }, required: [ ... ], additionalProperties: false }
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* // Ask for a different target explicitly
|
|
52
|
+
* const draft = extractJsonSchema(mySealSchema, { target: "draft-2020-12" });
|
|
53
|
+
*/
|
|
54
|
+
declare function extractJsonSchema(schema: StandardSchemaV1<unknown> | undefined, options?: ExtractJsonSchemaOptions): Record<string, unknown> | undefined;
|
|
55
|
+
//#endregion
|
|
56
|
+
export { extractJsonSchema };
|
|
57
|
+
//# sourceMappingURL=json-schema.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|