@warlock.js/ai 4.4.0 → 4.6.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 +63 -52
- package/cjs/index.cjs +240 -14147
- package/cjs/src-Bmajk4Qg.cjs +30 -0
- package/cjs/src-OZyDYHxm.cjs +25089 -0
- package/cjs/src-OZyDYHxm.cjs.map +1 -0
- package/esm/agent/agent-config.type.d.mts +119 -1
- package/esm/agent/agent-config.type.d.mts.map +1 -1
- package/esm/agent/agent-input-builder.mjs +27 -6
- package/esm/agent/agent-input-builder.mjs.map +1 -1
- package/esm/agent/agent.d.mts +40 -1
- package/esm/agent/agent.d.mts.map +1 -1
- package/esm/agent/agent.mjs +328 -36
- package/esm/agent/agent.mjs.map +1 -1
- package/esm/agent/index.d.mts +2 -1
- package/esm/agent/index.mjs +1 -0
- package/esm/agent/judge-config.type.d.mts +33 -0
- package/esm/agent/judge-config.type.d.mts.map +1 -0
- package/esm/agent/judge-config.type.mjs +13 -0
- package/esm/agent/judge-config.type.mjs.map +1 -0
- package/esm/agent/signature.mjs +57 -0
- package/esm/agent/signature.mjs.map +1 -0
- package/esm/agent/snapshot.mjs +101 -0
- package/esm/agent/snapshot.mjs.map +1 -0
- package/esm/ai-openai/src/embedder.mjs +4 -0
- package/esm/ai-openai/src/image.mjs +5 -0
- package/esm/ai-openai/src/index.mjs +7 -0
- package/esm/ai-openai/src/model.mjs +5 -0
- package/esm/ai-openai/src/sdk.mjs +9 -0
- package/esm/ai-openai/src/speech.mjs +5 -0
- package/esm/ai-openai/src/transcription.mjs +6 -0
- package/esm/ai-openai/src/utils/index.mjs +5 -0
- package/esm/ai-openai/src/utils/to-openai-messages.mjs +3 -0
- package/esm/ai-openai/src/utils/to-openai-tools.mjs +3 -0
- package/esm/ai-openai/src/utils/wrap-openai-error.mjs +4 -0
- package/esm/ai.d.mts +164 -53
- package/esm/ai.d.mts.map +1 -1
- package/esm/ai.mjs +79 -8
- package/esm/ai.mjs.map +1 -1
- package/esm/batch/batch.d.mts.map +1 -1
- package/esm/batch/batch.mjs +21 -1
- package/esm/batch/batch.mjs.map +1 -1
- package/esm/batch/batch.type.d.mts +11 -4
- package/esm/batch/batch.type.d.mts.map +1 -1
- package/esm/config.d.mts +39 -3
- package/esm/config.d.mts.map +1 -1
- package/esm/config.mjs +26 -2
- package/esm/config.mjs.map +1 -1
- package/esm/contracts/agent/agent-options.type.d.mts +33 -5
- package/esm/contracts/agent/agent-options.type.d.mts.map +1 -1
- package/esm/contracts/agent/agent-snapshot.type.d.mts +90 -0
- package/esm/contracts/agent/agent-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/agent/agent.contract.d.mts +29 -1
- package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
- package/esm/contracts/agent/eval.type.d.mts +43 -2
- package/esm/contracts/agent/eval.type.d.mts.map +1 -1
- package/esm/contracts/agent/index.d.mts +2 -1
- package/esm/contracts/attachment-policy.type.d.mts +51 -0
- package/esm/contracts/attachment-policy.type.d.mts.map +1 -0
- package/esm/contracts/attachment.type.d.mts +16 -7
- package/esm/contracts/attachment.type.d.mts.map +1 -1
- package/esm/contracts/content-part.type.d.mts +14 -5
- package/esm/contracts/content-part.type.d.mts.map +1 -1
- package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -1
- package/esm/contracts/image-model.contract.d.mts +156 -0
- package/esm/contracts/image-model.contract.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +13 -6
- package/esm/contracts/model.contract.d.mts +11 -8
- package/esm/contracts/model.contract.d.mts.map +1 -1
- package/esm/contracts/orchestrator/index.d.mts +1 -0
- package/esm/contracts/orchestrator/orchestrator-config.type.d.mts +31 -2
- package/esm/contracts/orchestrator/orchestrator-config.type.d.mts.map +1 -1
- package/esm/contracts/orchestrator/session-lock.contract.d.mts +47 -0
- package/esm/contracts/orchestrator/session-lock.contract.d.mts.map +1 -0
- package/esm/contracts/planner/index.d.mts +3 -2
- package/esm/contracts/planner/planner-config.type.d.mts +61 -0
- package/esm/contracts/planner/planner-config.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts +60 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-result.type.d.mts +8 -0
- package/esm/contracts/planner/planner-result.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-snapshot.type.d.mts +77 -0
- package/esm/contracts/planner/planner-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/planner/planner.contract.d.mts +21 -1
- package/esm/contracts/planner/planner.contract.d.mts.map +1 -1
- package/esm/contracts/result/agent-result.type.d.mts +6 -4
- package/esm/contracts/result/agent-result.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.d.mts +21 -3
- package/esm/contracts/result/base-report.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.mjs.map +1 -1
- package/esm/contracts/result/execution-report.type.d.mts +53 -1
- package/esm/contracts/result/execution-report.type.d.mts.map +1 -1
- package/esm/contracts/result/supervisor-result.type.d.mts +14 -2
- package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
- package/esm/contracts/result/workflow-result.type.d.mts +2 -1
- package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
- package/esm/contracts/sdk-adapter.contract.d.mts +37 -0
- package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -1
- package/esm/contracts/speech-model.contract.d.mts +97 -0
- package/esm/contracts/speech-model.contract.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts +29 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
- package/esm/contracts/system-prompt.contract.d.mts +103 -1
- package/esm/contracts/system-prompt.contract.d.mts.map +1 -1
- package/esm/contracts/team/index.d.mts +1 -0
- package/esm/contracts/team/team-config.type.d.mts +127 -0
- package/esm/contracts/team/team-config.type.d.mts.map +1 -0
- package/esm/contracts/tool.contract.d.mts +4 -2
- package/esm/contracts/tool.contract.d.mts.map +1 -1
- package/esm/contracts/transcription-model.contract.d.mts +101 -0
- package/esm/contracts/transcription-model.contract.d.mts.map +1 -0
- package/esm/contracts/workflow/step.contract.d.mts +30 -5
- package/esm/contracts/workflow/step.contract.d.mts.map +1 -1
- package/esm/contracts/workflow/workflow.contract.d.mts +16 -0
- package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
- package/esm/errors/agent-drift-error.d.mts +32 -0
- package/esm/errors/agent-drift-error.d.mts.map +1 -0
- package/esm/errors/agent-drift-error.mjs +31 -0
- package/esm/errors/agent-drift-error.mjs.map +1 -0
- package/esm/errors/error-code.type.d.mts +1 -1
- package/esm/errors/index.d.mts +3 -0
- package/esm/errors/index.mjs +3 -0
- package/esm/errors/outbound-policy-error.d.mts +27 -0
- package/esm/errors/outbound-policy-error.d.mts.map +1 -0
- package/esm/errors/outbound-policy-error.mjs +32 -0
- package/esm/errors/outbound-policy-error.mjs.map +1 -0
- package/esm/errors/planner-drift-error.d.mts +34 -0
- package/esm/errors/planner-drift-error.d.mts.map +1 -0
- package/esm/errors/planner-drift-error.mjs +33 -0
- package/esm/errors/planner-drift-error.mjs.map +1 -0
- package/esm/eval/dataset.d.mts +28 -0
- package/esm/eval/dataset.d.mts.map +1 -0
- package/esm/eval/dataset.mjs +112 -0
- package/esm/eval/dataset.mjs.map +1 -0
- package/esm/eval/dataset.type.d.mts +53 -0
- package/esm/eval/dataset.type.d.mts.map +1 -0
- package/esm/eval/eval-runner.d.mts.map +1 -1
- package/esm/eval/eval-runner.mjs +16 -2
- package/esm/eval/eval-runner.mjs.map +1 -1
- package/esm/eval/index.d.mts +20 -1
- package/esm/eval/index.d.mts.map +1 -1
- package/esm/eval/index.mjs +20 -2
- package/esm/eval/index.mjs.map +1 -1
- package/esm/eval/regression.d.mts +30 -0
- package/esm/eval/regression.d.mts.map +1 -0
- package/esm/eval/regression.mjs +51 -0
- package/esm/eval/regression.mjs.map +1 -0
- package/esm/eval/report-json.d.mts +30 -0
- package/esm/eval/report-json.d.mts.map +1 -0
- package/esm/eval/report-json.mjs +33 -0
- package/esm/eval/report-json.mjs.map +1 -0
- package/esm/eval/report-junit.d.mts +22 -0
- package/esm/eval/report-junit.d.mts.map +1 -0
- package/esm/eval/report-junit.mjs +60 -0
- package/esm/eval/report-junit.mjs.map +1 -0
- package/esm/guard/contracts/guard-options.type.d.mts +165 -0
- package/esm/guard/contracts/guard-options.type.d.mts.map +1 -0
- package/esm/guard/contracts/guardrail.contract.d.mts +78 -0
- package/esm/guard/contracts/guardrail.contract.d.mts.map +1 -0
- package/esm/guard/contracts/index.d.mts +4 -0
- package/esm/guard/contracts/openai-client.contract.d.mts +51 -0
- package/esm/guard/contracts/openai-client.contract.d.mts.map +1 -0
- package/esm/guard/contracts/verdict.type.d.mts +76 -0
- package/esm/guard/contracts/verdict.type.d.mts.map +1 -0
- package/esm/guard/detectors/index.d.mts +4 -0
- package/esm/guard/detectors/index.mjs +6 -0
- package/esm/guard/detectors/injection.d.mts +34 -0
- package/esm/guard/detectors/injection.d.mts.map +1 -0
- package/esm/guard/detectors/injection.mjs +254 -0
- package/esm/guard/detectors/injection.mjs.map +1 -0
- package/esm/guard/detectors/moderation.d.mts +32 -0
- package/esm/guard/detectors/moderation.d.mts.map +1 -0
- package/esm/guard/detectors/moderation.mjs +134 -0
- package/esm/guard/detectors/moderation.mjs.map +1 -0
- package/esm/guard/detectors/pii.d.mts +41 -0
- package/esm/guard/detectors/pii.d.mts.map +1 -0
- package/esm/guard/detectors/pii.mjs +199 -0
- package/esm/guard/detectors/pii.mjs.map +1 -0
- package/esm/guard/detectors/topic.d.mts +29 -0
- package/esm/guard/detectors/topic.d.mts.map +1 -0
- package/esm/guard/detectors/topic.mjs +99 -0
- package/esm/guard/detectors/topic.mjs.map +1 -0
- package/esm/guard/errors.d.mts +12 -0
- package/esm/guard/errors.d.mts.map +1 -0
- package/esm/guard/errors.mjs +18 -0
- package/esm/guard/errors.mjs.map +1 -0
- package/esm/guard/guard.d.mts +67 -0
- package/esm/guard/guard.d.mts.map +1 -0
- package/esm/guard/guard.mjs +209 -0
- package/esm/guard/guard.mjs.map +1 -0
- package/esm/guard/guardrail.d.mts +39 -0
- package/esm/guard/guardrail.d.mts.map +1 -0
- package/esm/guard/guardrail.mjs +22 -0
- package/esm/guard/guardrail.mjs.map +1 -0
- package/esm/human/contracts/approval.type.d.mts +154 -0
- package/esm/human/contracts/approval.type.d.mts.map +1 -0
- package/esm/human/contracts/human-approval.type.d.mts +38 -0
- package/esm/human/contracts/human-approval.type.d.mts.map +1 -0
- package/esm/human/contracts/index.d.mts +4 -0
- package/esm/human/contracts/interrupt-store.contract.d.mts +112 -0
- package/esm/human/contracts/interrupt-store.contract.d.mts.map +1 -0
- package/esm/human/contracts/resume.type.d.mts +77 -0
- package/esm/human/contracts/resume.type.d.mts.map +1 -0
- package/esm/human/errors.d.mts +84 -0
- package/esm/human/errors.d.mts.map +1 -0
- package/esm/human/errors.mjs +60 -0
- package/esm/human/errors.mjs.map +1 -0
- package/esm/human/human-approval.d.mts +57 -0
- package/esm/human/human-approval.d.mts.map +1 -0
- package/esm/human/human-approval.mjs +170 -0
- package/esm/human/human-approval.mjs.map +1 -0
- package/esm/human/policy.d.mts +55 -0
- package/esm/human/policy.d.mts.map +1 -0
- package/esm/human/policy.mjs +67 -0
- package/esm/human/policy.mjs.map +1 -0
- package/esm/human/register.mjs +37 -0
- package/esm/human/register.mjs.map +1 -0
- package/esm/human/resume-seed.mjs +53 -0
- package/esm/human/resume-seed.mjs.map +1 -0
- package/esm/human/resume.d.mts +54 -0
- package/esm/human/resume.d.mts.map +1 -0
- package/esm/human/resume.mjs +121 -0
- package/esm/human/resume.mjs.map +1 -0
- package/esm/human/stores/index.mjs +5 -0
- package/esm/human/stores/memory.d.mts +30 -0
- package/esm/human/stores/memory.d.mts.map +1 -0
- package/esm/human/stores/memory.mjs +91 -0
- package/esm/human/stores/memory.mjs.map +1 -0
- package/esm/human/stores/pg.d.mts +59 -0
- package/esm/human/stores/pg.d.mts.map +1 -0
- package/esm/human/stores/pg.mjs +220 -0
- package/esm/human/stores/pg.mjs.map +1 -0
- package/esm/human/stores/redis.d.mts +56 -0
- package/esm/human/stores/redis.d.mts.map +1 -0
- package/esm/human/stores/redis.mjs +201 -0
- package/esm/human/stores/redis.mjs.map +1 -0
- package/esm/image/image-cost.d.mts +32 -0
- package/esm/image/image-cost.d.mts.map +1 -0
- package/esm/image/image-cost.mjs +55 -0
- package/esm/image/image-cost.mjs.map +1 -0
- package/esm/image/image.d.mts +92 -0
- package/esm/image/image.d.mts.map +1 -0
- package/esm/image/image.mjs +113 -0
- package/esm/image/image.mjs.map +1 -0
- package/esm/image/index.mjs +4 -0
- package/esm/index.d.mts +137 -24
- package/esm/index.mjs +101 -11
- package/esm/middleware/builtins/budget.mjs +6 -2
- package/esm/middleware/builtins/budget.mjs.map +1 -1
- package/esm/middleware/utils/extract-user-text.d.mts +8 -1
- package/esm/middleware/utils/extract-user-text.d.mts.map +1 -1
- package/esm/middleware/utils/extract-user-text.mjs +8 -1
- package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
- package/esm/mock/index.d.mts +3 -0
- package/esm/mock/index.mjs +3 -0
- package/esm/mock/mock-config.type.d.mts +22 -0
- package/esm/mock/mock-config.type.d.mts.map +1 -1
- package/esm/mock/mock-image-model.d.mts +41 -0
- package/esm/mock/mock-image-model.d.mts.map +1 -0
- package/esm/mock/mock-image-model.mjs +52 -0
- package/esm/mock/mock-image-model.mjs.map +1 -0
- package/esm/mock/mock-sdk.d.mts +7 -1
- package/esm/mock/mock-sdk.d.mts.map +1 -1
- package/esm/mock/mock-sdk.mjs +27 -0
- package/esm/mock/mock-sdk.mjs.map +1 -1
- package/esm/mock/mock-speech-model.d.mts +31 -0
- package/esm/mock/mock-speech-model.d.mts.map +1 -0
- package/esm/mock/mock-speech-model.mjs +39 -0
- package/esm/mock/mock-speech-model.mjs.map +1 -0
- package/esm/mock/mock-transcription-model.d.mts +32 -0
- package/esm/mock/mock-transcription-model.d.mts.map +1 -0
- package/esm/mock/mock-transcription-model.mjs +36 -0
- package/esm/mock/mock-transcription-model.mjs.map +1 -0
- package/esm/object-stream/index.d.mts +2 -0
- package/esm/object-stream/index.mjs +4 -0
- package/esm/object-stream/parse-partial-json.d.mts +22 -0
- package/esm/object-stream/parse-partial-json.d.mts.map +1 -0
- package/esm/object-stream/parse-partial-json.mjs +78 -0
- package/esm/object-stream/parse-partial-json.mjs.map +1 -0
- package/esm/object-stream/stream-object.d.mts +68 -0
- package/esm/object-stream/stream-object.d.mts.map +1 -0
- package/esm/object-stream/stream-object.mjs +104 -0
- package/esm/object-stream/stream-object.mjs.map +1 -0
- package/esm/observe/index.mjs +4 -0
- package/esm/observe/observer-registry.d.mts +30 -0
- package/esm/observe/observer-registry.d.mts.map +1 -0
- package/esm/observe/observer-registry.mjs +51 -0
- package/esm/observe/observer-registry.mjs.map +1 -0
- package/esm/observe/observer.contract.d.mts +40 -0
- package/esm/observe/observer.contract.d.mts.map +1 -0
- package/esm/observe/resolve-observers.d.mts +40 -0
- package/esm/observe/resolve-observers.d.mts.map +1 -0
- package/esm/observe/resolve-observers.mjs +73 -0
- package/esm/observe/resolve-observers.mjs.map +1 -0
- package/esm/orchestrator/execution.d.mts.map +1 -1
- package/esm/orchestrator/execution.mjs +5 -2
- package/esm/orchestrator/execution.mjs.map +1 -1
- package/esm/orchestrator/index.d.mts +1 -0
- package/esm/orchestrator/index.mjs +1 -0
- package/esm/orchestrator/orchestrator.d.mts.map +1 -1
- package/esm/orchestrator/orchestrator.mjs +39 -6
- package/esm/orchestrator/orchestrator.mjs.map +1 -1
- package/esm/orchestrator/session-lock.d.mts +25 -0
- package/esm/orchestrator/session-lock.d.mts.map +1 -0
- package/esm/orchestrator/session-lock.mjs +83 -0
- package/esm/orchestrator/session-lock.mjs.map +1 -0
- package/esm/planner/dag-scheduler.mjs +97 -0
- package/esm/planner/dag-scheduler.mjs.map +1 -0
- package/esm/planner/plan-prompt.d.mts +1 -1
- package/esm/planner/plan-prompt.d.mts.map +1 -1
- package/esm/planner/plan-prompt.mjs +2 -1
- package/esm/planner/plan-prompt.mjs.map +1 -1
- package/esm/planner/planner-run.d.mts +8 -0
- package/esm/planner/planner-run.d.mts.map +1 -1
- package/esm/planner/planner-run.mjs +457 -31
- package/esm/planner/planner-run.mjs.map +1 -1
- package/esm/planner/planner.d.mts.map +1 -1
- package/esm/planner/planner.mjs +26 -2
- package/esm/planner/planner.mjs.map +1 -1
- package/esm/planner/snapshot.mjs +95 -0
- package/esm/planner/snapshot.mjs.map +1 -0
- package/esm/prompt/errors.d.mts +57 -0
- package/esm/prompt/errors.d.mts.map +1 -0
- package/esm/prompt/errors.mjs +73 -0
- package/esm/prompt/errors.mjs.map +1 -0
- package/esm/prompt/index.d.mts +3 -0
- package/esm/prompt/index.mjs +4 -0
- package/esm/prompt/prompt-langfuse-sync.mjs +104 -0
- package/esm/prompt/prompt-langfuse-sync.mjs.map +1 -0
- package/esm/prompt/prompt-langfuse-sync.type.d.mts +32 -0
- package/esm/prompt/prompt-langfuse-sync.type.d.mts.map +1 -0
- package/esm/prompt/prompt-validate.mjs +170 -0
- package/esm/prompt/prompt-validate.mjs.map +1 -0
- package/esm/prompt/prompt.d.mts +54 -0
- package/esm/prompt/prompt.d.mts.map +1 -0
- package/esm/prompt/prompt.mjs +218 -0
- package/esm/prompt/prompt.mjs.map +1 -0
- package/esm/prompt/prompt.type.d.mts +174 -0
- package/esm/prompt/prompt.type.d.mts.map +1 -0
- package/esm/prompts/index.d.mts +3 -0
- package/esm/prompts/index.mjs +3 -0
- package/esm/prompts/prompts-manager.contract.d.mts +154 -0
- package/esm/prompts/prompts-manager.contract.d.mts.map +1 -0
- package/esm/prompts/prompts-manager.d.mts +38 -0
- package/esm/prompts/prompts-manager.d.mts.map +1 -0
- package/esm/prompts/prompts-manager.mjs +410 -0
- package/esm/prompts/prompts-manager.mjs.map +1 -0
- package/esm/prompts/prompts-manager.type.d.mts +172 -0
- package/esm/prompts/prompts-manager.type.d.mts.map +1 -0
- package/esm/prompts/prompts-validate.mjs +200 -0
- package/esm/prompts/prompts-validate.mjs.map +1 -0
- package/esm/rag/as-tool.mjs +48 -0
- package/esm/rag/as-tool.mjs.map +1 -0
- package/esm/rag/chunk/chunk.d.mts +24 -0
- package/esm/rag/chunk/chunk.d.mts.map +1 -0
- package/esm/rag/chunk/chunk.mjs +44 -0
- package/esm/rag/chunk/chunk.mjs.map +1 -0
- package/esm/rag/chunk/fixed.mjs +32 -0
- package/esm/rag/chunk/fixed.mjs.map +1 -0
- package/esm/rag/chunk/markdown.mjs +75 -0
- package/esm/rag/chunk/markdown.mjs.map +1 -0
- package/esm/rag/chunk/recursive.mjs +132 -0
- package/esm/rag/chunk/recursive.mjs.map +1 -0
- package/esm/rag/chunk/sentence.mjs +73 -0
- package/esm/rag/chunk/sentence.mjs.map +1 -0
- package/esm/rag/contracts/chunk-options.type.d.mts +35 -0
- package/esm/rag/contracts/chunk-options.type.d.mts.map +1 -0
- package/esm/rag/contracts/citation.type.d.mts +35 -0
- package/esm/rag/contracts/citation.type.d.mts.map +1 -0
- package/esm/rag/contracts/index.d.mts +4 -0
- package/esm/rag/contracts/rag-config.type.d.mts +68 -0
- package/esm/rag/contracts/rag-config.type.d.mts.map +1 -0
- package/esm/rag/contracts/rag-document.type.d.mts +21 -0
- package/esm/rag/contracts/rag-document.type.d.mts.map +1 -0
- package/esm/rag/hybrid/bm25.d.mts +23 -0
- package/esm/rag/hybrid/bm25.d.mts.map +1 -0
- package/esm/rag/hybrid/bm25.mjs +51 -0
- package/esm/rag/hybrid/bm25.mjs.map +1 -0
- package/esm/rag/hybrid/hybrid-rank.d.mts +33 -0
- package/esm/rag/hybrid/hybrid-rank.d.mts.map +1 -0
- package/esm/rag/hybrid/hybrid-rank.mjs +29 -0
- package/esm/rag/hybrid/hybrid-rank.mjs.map +1 -0
- package/esm/rag/hybrid/rrf.d.mts +25 -0
- package/esm/rag/hybrid/rrf.d.mts.map +1 -0
- package/esm/rag/hybrid/rrf.mjs +30 -0
- package/esm/rag/hybrid/rrf.mjs.map +1 -0
- package/esm/rag/index.d.mts +22 -0
- package/esm/rag/index.mjs +18 -0
- package/esm/rag/loaders/errors.d.mts +19 -0
- package/esm/rag/loaders/errors.d.mts.map +1 -0
- package/esm/rag/loaders/errors.mjs +25 -0
- package/esm/rag/loaders/errors.mjs.map +1 -0
- package/esm/rag/loaders/index.mjs +7 -0
- package/esm/rag/loaders/load-html.d.mts +26 -0
- package/esm/rag/loaders/load-html.d.mts.map +1 -0
- package/esm/rag/loaders/load-html.mjs +138 -0
- package/esm/rag/loaders/load-html.mjs.map +1 -0
- package/esm/rag/loaders/load-pdf.d.mts +38 -0
- package/esm/rag/loaders/load-pdf.d.mts.map +1 -0
- package/esm/rag/loaders/load-pdf.mjs +150 -0
- package/esm/rag/loaders/load-pdf.mjs.map +1 -0
- package/esm/rag/loaders/load-text.d.mts +47 -0
- package/esm/rag/loaders/load-text.d.mts.map +1 -0
- package/esm/rag/loaders/load-text.mjs +60 -0
- package/esm/rag/loaders/load-text.mjs.map +1 -0
- package/esm/rag/loaders/load-web.d.mts +42 -0
- package/esm/rag/loaders/load-web.d.mts.map +1 -0
- package/esm/rag/loaders/load-web.mjs +89 -0
- package/esm/rag/loaders/load-web.mjs.map +1 -0
- package/esm/rag/loaders/loader.type.d.mts +89 -0
- package/esm/rag/loaders/loader.type.d.mts.map +1 -0
- package/esm/rag/rag.d.mts +38 -0
- package/esm/rag/rag.d.mts.map +1 -0
- package/esm/rag/rag.mjs +126 -0
- package/esm/rag/rag.mjs.map +1 -0
- package/esm/rag/rerank/keyword-reranker.d.mts +32 -0
- package/esm/rag/rerank/keyword-reranker.d.mts.map +1 -0
- package/esm/rag/rerank/keyword-reranker.mjs +58 -0
- package/esm/rag/rerank/keyword-reranker.mjs.map +1 -0
- package/esm/rag/rerank/llm-reranker.d.mts +36 -0
- package/esm/rag/rerank/llm-reranker.d.mts.map +1 -0
- package/esm/rag/rerank/llm-reranker.mjs +85 -0
- package/esm/rag/rerank/llm-reranker.mjs.map +1 -0
- package/esm/rag/rerank/reranker.contract.d.mts +28 -0
- package/esm/rag/rerank/reranker.contract.d.mts.map +1 -0
- package/esm/rag/retrieve.mjs +68 -0
- package/esm/rag/retrieve.mjs.map +1 -0
- package/esm/rag/store/cache-vector-store.d.mts +27 -0
- package/esm/rag/store/cache-vector-store.d.mts.map +1 -0
- package/esm/rag/store/cache-vector-store.mjs +48 -0
- package/esm/rag/store/cache-vector-store.mjs.map +1 -0
- package/esm/rag/store/pg-vector-store.d.mts +139 -0
- package/esm/rag/store/pg-vector-store.d.mts.map +1 -0
- package/esm/rag/store/pg-vector-store.mjs +328 -0
- package/esm/rag/store/pg-vector-store.mjs.map +1 -0
- package/esm/rag/store/vector-store.contract.d.mts +38 -0
- package/esm/rag/store/vector-store.contract.d.mts.map +1 -0
- package/esm/rag/transforms/multi-query.d.mts +27 -0
- package/esm/rag/transforms/multi-query.d.mts.map +1 -0
- package/esm/rag/transforms/multi-query.mjs +41 -0
- package/esm/rag/transforms/multi-query.mjs.map +1 -0
- package/esm/security/index.mjs +5 -0
- package/esm/security/outbound-policy.d.mts +46 -0
- package/esm/security/outbound-policy.d.mts.map +1 -0
- package/esm/security/outbound-policy.mjs +187 -0
- package/esm/security/outbound-policy.mjs.map +1 -0
- package/esm/security/outbound-policy.type.d.mts +74 -0
- package/esm/security/outbound-policy.type.d.mts.map +1 -0
- package/esm/security/private-ip.d.mts +15 -0
- package/esm/security/private-ip.d.mts.map +1 -0
- package/esm/security/private-ip.mjs +48 -0
- package/esm/security/private-ip.mjs.map +1 -0
- package/esm/security/redact.d.mts +59 -0
- package/esm/security/redact.d.mts.map +1 -0
- package/esm/security/redact.mjs +122 -0
- package/esm/security/redact.mjs.map +1 -0
- package/esm/serve/serve.d.mts +50 -0
- package/esm/serve/serve.d.mts.map +1 -0
- package/esm/serve/serve.mjs +90 -0
- package/esm/serve/serve.mjs.map +1 -0
- package/esm/serve/sse.d.mts +20 -0
- package/esm/serve/sse.d.mts.map +1 -0
- package/esm/serve/sse.mjs +25 -0
- package/esm/serve/sse.mjs.map +1 -0
- package/esm/serve/stream-to-sse.d.mts +29 -0
- package/esm/serve/stream-to-sse.d.mts.map +1 -0
- package/esm/serve/stream-to-sse.mjs +37 -0
- package/esm/serve/stream-to-sse.mjs.map +1 -0
- package/esm/skills/catalog.d.mts +49 -0
- package/esm/skills/catalog.d.mts.map +1 -0
- package/esm/skills/catalog.mjs +140 -0
- package/esm/skills/catalog.mjs.map +1 -0
- package/esm/skills/contracts/skill-record.type.d.mts +37 -0
- package/esm/skills/contracts/skill-record.type.d.mts.map +1 -0
- package/esm/skills/contracts/skills-config.type.d.mts +108 -0
- package/esm/skills/contracts/skills-config.type.d.mts.map +1 -0
- package/esm/skills/contracts/skills-store.contract.d.mts +28 -0
- package/esm/skills/contracts/skills-store.contract.d.mts.map +1 -0
- package/esm/skills/contracts/skills.contract.d.mts +43 -0
- package/esm/skills/contracts/skills.contract.d.mts.map +1 -0
- package/esm/skills/index.d.mts +16 -0
- package/esm/skills/index.mjs +14 -0
- package/esm/skills/load-skill-tool.d.mts +38 -0
- package/esm/skills/load-skill-tool.d.mts.map +1 -0
- package/esm/skills/load-skill-tool.mjs +65 -0
- package/esm/skills/load-skill-tool.mjs.map +1 -0
- package/esm/skills/review-gate.d.mts +33 -0
- package/esm/skills/review-gate.d.mts.map +1 -0
- package/esm/skills/review-gate.mjs +60 -0
- package/esm/skills/review-gate.mjs.map +1 -0
- package/esm/skills/save-skill-tool.d.mts +39 -0
- package/esm/skills/save-skill-tool.d.mts.map +1 -0
- package/esm/skills/save-skill-tool.mjs +65 -0
- package/esm/skills/save-skill-tool.mjs.map +1 -0
- package/esm/skills/skills.d.mts +33 -0
- package/esm/skills/skills.d.mts.map +1 -0
- package/esm/skills/skills.mjs +109 -0
- package/esm/skills/skills.mjs.map +1 -0
- package/esm/skills/sources/directory-source.d.mts +19 -0
- package/esm/skills/sources/directory-source.d.mts.map +1 -0
- package/esm/skills/sources/directory-source.mjs +108 -0
- package/esm/skills/sources/directory-source.mjs.map +1 -0
- package/esm/skills/sources/index.d.mts +18 -0
- package/esm/skills/sources/index.d.mts.map +1 -0
- package/esm/skills/sources/index.mjs +27 -0
- package/esm/skills/sources/index.mjs.map +1 -0
- package/esm/skills/sources/parse-frontmatter.d.mts +27 -0
- package/esm/skills/sources/parse-frontmatter.d.mts.map +1 -0
- package/esm/skills/sources/parse-frontmatter.mjs +46 -0
- package/esm/skills/sources/parse-frontmatter.mjs.map +1 -0
- package/esm/skills/sources/store-source.d.mts +14 -0
- package/esm/skills/sources/store-source.d.mts.map +1 -0
- package/esm/skills/sources/store-source.mjs +15 -0
- package/esm/skills/sources/store-source.mjs.map +1 -0
- package/esm/skills/sources/url-source.d.mts +29 -0
- package/esm/skills/sources/url-source.d.mts.map +1 -0
- package/esm/skills/sources/url-source.mjs +117 -0
- package/esm/skills/sources/url-source.mjs.map +1 -0
- package/esm/skills/store/mock-skills-store.d.mts +57 -0
- package/esm/skills/store/mock-skills-store.d.mts.map +1 -0
- package/esm/skills/store/mock-skills-store.mjs +100 -0
- package/esm/skills/store/mock-skills-store.mjs.map +1 -0
- package/esm/skills/store/procedural-skill-store.d.mts +30 -0
- package/esm/skills/store/procedural-skill-store.d.mts.map +1 -0
- package/esm/skills/store/procedural-skill-store.mjs +125 -0
- package/esm/skills/store/procedural-skill-store.mjs.map +1 -0
- package/esm/speech/index.mjs +3 -0
- package/esm/speech/speech.d.mts +65 -0
- package/esm/speech/speech.d.mts.map +1 -0
- package/esm/speech/speech.mjs +123 -0
- package/esm/speech/speech.mjs.map +1 -0
- package/esm/supervisor/as-tool.mjs +2 -2
- package/esm/supervisor/as-tool.mjs.map +1 -1
- package/esm/supervisor/entries.mjs +2 -2
- package/esm/supervisor/entries.mjs.map +1 -1
- package/esm/supervisor/execution.d.mts.map +1 -1
- package/esm/supervisor/execution.mjs +31 -28
- package/esm/supervisor/execution.mjs.map +1 -1
- package/esm/supervisor/supervisor.d.mts.map +1 -1
- package/esm/supervisor/supervisor.mjs +8 -3
- package/esm/supervisor/supervisor.mjs.map +1 -1
- package/esm/system-prompt/index.d.mts +4 -0
- package/esm/system-prompt/system-prompt.d.mts +68 -4
- package/esm/system-prompt/system-prompt.d.mts.map +1 -1
- package/esm/system-prompt/system-prompt.mjs +89 -5
- package/esm/system-prompt/system-prompt.mjs.map +1 -1
- package/esm/team/gates.mjs +48 -0
- package/esm/team/gates.mjs.map +1 -0
- package/esm/team/index.d.mts +1 -0
- package/esm/team/index.mjs +3 -0
- package/esm/team/team.d.mts +42 -0
- package/esm/team/team.d.mts.map +1 -0
- package/esm/team/team.mjs +94 -0
- package/esm/team/team.mjs.map +1 -0
- package/esm/tool/executable-as-tool.d.mts.map +1 -1
- package/esm/tool/executable-as-tool.mjs +2 -2
- package/esm/tool/executable-as-tool.mjs.map +1 -1
- package/esm/tool/tool.d.mts.map +1 -1
- package/esm/tool/tool.mjs +2 -2
- package/esm/tool/tool.mjs.map +1 -1
- package/esm/transcribe/audio-input.d.mts +47 -0
- package/esm/transcribe/audio-input.d.mts.map +1 -0
- package/esm/transcribe/audio-input.mjs +84 -0
- package/esm/transcribe/audio-input.mjs.map +1 -0
- package/esm/transcribe/index.mjs +4 -0
- package/esm/transcribe/transcribe.d.mts +64 -0
- package/esm/transcribe/transcribe.d.mts.map +1 -0
- package/esm/transcribe/transcribe.mjs +128 -0
- package/esm/transcribe/transcribe.mjs.map +1 -0
- package/esm/utils/compute-cost.d.mts +17 -1
- package/esm/utils/compute-cost.d.mts.map +1 -1
- package/esm/utils/compute-cost.mjs +26 -1
- package/esm/utils/compute-cost.mjs.map +1 -1
- package/esm/utils/extract-json-lenient.d.mts +42 -0
- package/esm/utils/extract-json-lenient.d.mts.map +1 -0
- package/esm/utils/extract-json-lenient.mjs +97 -0
- package/esm/utils/extract-json-lenient.mjs.map +1 -0
- package/esm/utils/index.d.mts +4 -2
- package/esm/utils/index.mjs +3 -1
- package/esm/utils/json-schema.d.mts +1 -1
- package/esm/utils/prepare-attachment-part.d.mts +10 -1
- package/esm/utils/prepare-attachment-part.d.mts.map +1 -1
- package/esm/utils/prepare-attachment-part.mjs +103 -11
- package/esm/utils/prepare-attachment-part.mjs.map +1 -1
- package/esm/utils/resolve-attachment.d.mts +4 -3
- package/esm/utils/resolve-attachment.d.mts.map +1 -1
- package/esm/utils/resolve-attachment.mjs +4 -3
- package/esm/utils/resolve-attachment.mjs.map +1 -1
- package/esm/utils/run-context.d.mts +94 -0
- package/esm/utils/run-context.d.mts.map +1 -0
- package/esm/utils/run-context.mjs +98 -0
- package/esm/utils/run-context.mjs.map +1 -0
- package/esm/vcr/cassette-io.mjs +57 -0
- package/esm/vcr/cassette-io.mjs.map +1 -0
- package/esm/vcr/errors.d.mts +42 -0
- package/esm/vcr/errors.d.mts.map +1 -0
- package/esm/vcr/errors.mjs +37 -0
- package/esm/vcr/errors.mjs.map +1 -0
- package/esm/vcr/hash-request.d.mts +28 -0
- package/esm/vcr/hash-request.d.mts.map +1 -0
- package/esm/vcr/hash-request.mjs +118 -0
- package/esm/vcr/hash-request.mjs.map +1 -0
- package/esm/vcr/index.d.mts +4 -0
- package/esm/vcr/index.mjs +5 -0
- package/esm/vcr/vcr.d.mts +32 -0
- package/esm/vcr/vcr.d.mts.map +1 -0
- package/esm/vcr/vcr.mjs +248 -0
- package/esm/vcr/vcr.mjs.map +1 -0
- package/esm/vcr/vcr.type.d.mts +118 -0
- package/esm/vcr/vcr.type.d.mts.map +1 -0
- package/esm/workflow/as-tool.mjs +2 -2
- package/esm/workflow/as-tool.mjs.map +1 -1
- package/esm/workflow/engine.mjs +1 -0
- package/esm/workflow/engine.mjs.map +1 -1
- package/esm/workflow/step-runner.mjs +19 -20
- package/esm/workflow/step-runner.mjs.map +1 -1
- package/esm/workflow/workflow.d.mts.map +1 -1
- package/esm/workflow/workflow.mjs +8 -3
- package/esm/workflow/workflow.mjs.map +1 -1
- package/llms-full.txt +2572 -204
- package/llms.txt +21 -4
- package/package.json +7 -3
- package/skills/README.md +44 -4
- package/skills/ai-dx-helpers/SKILL.md +2 -2
- package/skills/approve-tool-calls/SKILL.md +134 -0
- package/skills/attach-ai-middleware/SKILL.md +1 -1
- package/skills/detect-and-redact-pii/SKILL.md +104 -0
- package/skills/durable-agent-runs/SKILL.md +135 -0
- package/skills/durable-resume/SKILL.md +128 -0
- package/skills/escalate-block-to-human/SKILL.md +85 -0
- package/skills/eval-datasets-and-ci/SKILL.md +117 -0
- package/skills/generate-images/SKILL.md +138 -0
- package/skills/generate-speech/SKILL.md +139 -0
- package/skills/guard-input-output/SKILL.md +117 -0
- package/skills/manage-prompts/SKILL.md +186 -0
- package/skills/observe-ai-flows/SKILL.md +94 -0
- package/skills/rag-loaders-and-stores/SKILL.md +164 -0
- package/skills/record-replay-llm/SKILL.md +92 -0
- package/skills/run-ai-agent/SKILL.md +26 -1
- package/skills/run-ai-rag/SKILL.md +139 -0
- package/skills/run-ai-team/SKILL.md +107 -0
- package/skills/run-orchestrator/SKILL.md +2 -0
- package/skills/run-planner/SKILL.md +73 -8
- package/skills/run-supervisor/SKILL.md +20 -1
- package/skills/transcribe-audio/SKILL.md +157 -0
- package/skills/use-runtime-skills/SKILL.md +106 -0
- package/skills/write-system-prompt/SKILL.md +30 -1
- package/cjs/index.cjs.map +0 -1
- package/esm/contracts/result/index.d.mts +0 -15
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { SupervisorFailedError } from "../errors/supervisor-failed-error.mjs";
|
|
2
|
+
import "../errors/index.mjs";
|
|
3
|
+
import { supervisor } from "../supervisor/supervisor.mjs";
|
|
4
|
+
import { buildQualityGate, buildVerifyGate } from "./gates.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/ai/src/team/team.ts
|
|
7
|
+
/**
|
|
8
|
+
* `ai.team(config)` — thin, transparent sugar over `ai.supervisor`.
|
|
9
|
+
*
|
|
10
|
+
* Builds a {@link SupervisorConfig} from the team-shaped config and
|
|
11
|
+
* calls `supervisor(...)`, returning the **unchanged**
|
|
12
|
+
* `SupervisorContract<TOutput>` — the same object `ai.supervisor`
|
|
13
|
+
* returns, so `ctx.intents.<member>.execute()`, `.asTool()`,
|
|
14
|
+
* `.resume()`, snapshots, and events all stay intact. `team()` owns no
|
|
15
|
+
* loop: the manager becomes `route`/`router`, the members become
|
|
16
|
+
* `intents`, and the `gate` becomes `evaluate`. Everything else passes
|
|
17
|
+
* through 1:1.
|
|
18
|
+
*
|
|
19
|
+
* A `gate: "quality" | "verify"` string selects a pre-built `evaluate`
|
|
20
|
+
* strategy ({@link buildQualityGate} / {@link buildVerifyGate}); a
|
|
21
|
+
* function forwards straight to `SupervisorConfig.evaluate` (full
|
|
22
|
+
* escape hatch). When the gate is a string, the resolved `fixer` (and,
|
|
23
|
+
* for `"quality"`, the `reviewer`) roles are validated against
|
|
24
|
+
* `members` at construction — a missing role throws an authoring-style
|
|
25
|
+
* {@link SupervisorFailedError} (`context: { authoring: true }`) rather
|
|
26
|
+
* than silently starving until `maxIterations`.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* const codeTeam = ai.team({
|
|
30
|
+
* name: "code-team",
|
|
31
|
+
* goal: "Ship a tested module that passes review.",
|
|
32
|
+
* manager: techLeadRouter,
|
|
33
|
+
* members: { builder, reviewer, fixer },
|
|
34
|
+
* gate: "quality",
|
|
35
|
+
* output: v.object({ code: v.string() }),
|
|
36
|
+
* maxIterations: 6,
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* const { data, report } = await codeTeam.execute("Build a debounce<T> utility.");
|
|
40
|
+
*/
|
|
41
|
+
function team(config) {
|
|
42
|
+
const supervisorConfig = {
|
|
43
|
+
name: config.name,
|
|
44
|
+
version: config.version,
|
|
45
|
+
reportType: "team",
|
|
46
|
+
intents: config.members,
|
|
47
|
+
evaluate: resolveGate(config),
|
|
48
|
+
goal: config.goal,
|
|
49
|
+
output: config.output,
|
|
50
|
+
state: config.state,
|
|
51
|
+
maxIterations: config.maxIterations,
|
|
52
|
+
snapshotStore: config.snapshotStore,
|
|
53
|
+
on: config.on,
|
|
54
|
+
observe: config.observe
|
|
55
|
+
};
|
|
56
|
+
if (isRouteManager(config.manager)) supervisorConfig.route = config.manager.route;
|
|
57
|
+
else supervisorConfig.router = config.manager;
|
|
58
|
+
return supervisor(supervisorConfig);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Resolve the team's `gate` into a concrete `evaluate` callback. A
|
|
62
|
+
* function forwards untouched; a {@link TeamGate} string is validated
|
|
63
|
+
* against `members` and desugared into the matching pre-built gate.
|
|
64
|
+
*/
|
|
65
|
+
function resolveGate(config) {
|
|
66
|
+
if (typeof config.gate === "function") return config.gate;
|
|
67
|
+
const gate = config.gate;
|
|
68
|
+
const fixerRole = config.roles?.fixer ?? "fixer";
|
|
69
|
+
assertMemberExists(config, fixerRole, "fixer");
|
|
70
|
+
if (gate === "quality") {
|
|
71
|
+
assertMemberExists(config, config.roles?.reviewer ?? "reviewer", "reviewer");
|
|
72
|
+
return buildQualityGate(config.gateKey ?? "approved", fixerRole);
|
|
73
|
+
}
|
|
74
|
+
return buildVerifyGate(config.gateKey ?? "passed", fixerRole);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Construction-time guard: assert the resolved role key exists in
|
|
78
|
+
* `members`, throwing an authoring-style {@link SupervisorFailedError}
|
|
79
|
+
* (tagged `authoring: true`) listing the missing role when it doesn't.
|
|
80
|
+
*/
|
|
81
|
+
function assertMemberExists(config, role, label) {
|
|
82
|
+
if (!Object.prototype.hasOwnProperty.call(config.members, role)) throw new SupervisorFailedError(`ai.team("${config.name}"): gate "${config.gate}" needs a "${label}" member but no \`members.${role}\` key exists`, { context: { authoring: true } });
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Discriminate the `manager` union: `true` when it is the deterministic
|
|
86
|
+
* `{ route }` form, `false` for a bare `AgentContract` / `RouterEntry`.
|
|
87
|
+
*/
|
|
88
|
+
function isRouteManager(manager) {
|
|
89
|
+
return typeof manager === "object" && manager !== null && "route" in manager && typeof manager.route === "function";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
//#endregion
|
|
93
|
+
export { team };
|
|
94
|
+
//# sourceMappingURL=team.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"team.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/team/team.ts"],"sourcesContent":["import type {\n EvaluateContext,\n EvaluateResult,\n} from \"../contracts/supervisor/evaluate-context.type\";\nimport type { SupervisorIntentValue } from \"../contracts/supervisor/intent-entry.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorContract } from \"../contracts/supervisor/supervisor.contract\";\nimport type {\n TeamConfig,\n TeamGate,\n TeamGateFn,\n TeamMemberValue,\n} from \"../contracts/team/team-config.type\";\nimport { SupervisorFailedError } from \"../errors\";\nimport { supervisor } from \"../supervisor/supervisor\";\nimport { buildQualityGate, buildVerifyGate } from \"./gates\";\n\n/**\n * `ai.team(config)` — thin, transparent sugar over `ai.supervisor`.\n *\n * Builds a {@link SupervisorConfig} from the team-shaped config and\n * calls `supervisor(...)`, returning the **unchanged**\n * `SupervisorContract<TOutput>` — the same object `ai.supervisor`\n * returns, so `ctx.intents.<member>.execute()`, `.asTool()`,\n * `.resume()`, snapshots, and events all stay intact. `team()` owns no\n * loop: the manager becomes `route`/`router`, the members become\n * `intents`, and the `gate` becomes `evaluate`. Everything else passes\n * through 1:1.\n *\n * A `gate: \"quality\" | \"verify\"` string selects a pre-built `evaluate`\n * strategy ({@link buildQualityGate} / {@link buildVerifyGate}); a\n * function forwards straight to `SupervisorConfig.evaluate` (full\n * escape hatch). When the gate is a string, the resolved `fixer` (and,\n * for `\"quality\"`, the `reviewer`) roles are validated against\n * `members` at construction — a missing role throws an authoring-style\n * {@link SupervisorFailedError} (`context: { authoring: true }`) rather\n * than silently starving until `maxIterations`.\n *\n * @example\n * const codeTeam = ai.team({\n * name: \"code-team\",\n * goal: \"Ship a tested module that passes review.\",\n * manager: techLeadRouter,\n * members: { builder, reviewer, fixer },\n * gate: \"quality\",\n * output: v.object({ code: v.string() }),\n * maxIterations: 6,\n * });\n *\n * const { data, report } = await codeTeam.execute(\"Build a debounce<T> utility.\");\n */\nexport function team<\n TOutput = unknown,\n TState = TOutput,\n TMembers extends Record<string, TeamMemberValue> = Record<string, TeamMemberValue>,\n>(config: TeamConfig<TOutput, TState, TMembers>): SupervisorContract<TOutput> {\n const supervisorConfig: SupervisorConfig<TOutput, TState> = {\n name: config.name,\n version: config.version,\n // Stamp the report/result discriminator as \"team\" so team runs are\n // distinguishable on the wire (Panoptic groups/filters them as their\n // own type) — the only behavioural difference from a plain supervisor.\n reportType: \"team\",\n intents: config.members as unknown as Record<string, SupervisorIntentValue>,\n evaluate: resolveGate<TOutput, TState, TMembers>(config),\n goal: config.goal,\n output: config.output,\n state: config.state,\n maxIterations: config.maxIterations,\n snapshotStore: config.snapshotStore,\n on: config.on,\n // Forward observability verbatim — the supervisor `team()` returns\n // routes its report through the generic Observer seam, so a team\n // inherits observation with no team-specific wiring (F1/F3).\n observe: config.observe,\n };\n\n // Manager → `route` XOR `router`. Reuse the supervisor's own XOR\n // validation; team() forwards exactly one of the two, so a malformed\n // manager surfaces the existing SupervisorFailedError downstream.\n if (isRouteManager(config.manager)) {\n supervisorConfig.route = config.manager.route;\n } else {\n supervisorConfig.router = config.manager;\n }\n\n return supervisor<TOutput, TState>(supervisorConfig);\n}\n\n/**\n * Resolve the team's `gate` into a concrete `evaluate` callback. A\n * function forwards untouched; a {@link TeamGate} string is validated\n * against `members` and desugared into the matching pre-built gate.\n */\nfunction resolveGate<\n TOutput,\n TState,\n TMembers extends Record<string, TeamMemberValue>,\n>(\n config: TeamConfig<TOutput, TState, TMembers>,\n): (ctx: EvaluateContext<TState>) => EvaluateResult | Promise<EvaluateResult> {\n if (typeof config.gate === \"function\") {\n return config.gate as TeamGateFn<TState>;\n }\n\n const gate: TeamGate = config.gate;\n const fixerRole = config.roles?.fixer ?? \"fixer\";\n\n assertMemberExists(config, fixerRole, \"fixer\");\n\n if (gate === \"quality\") {\n const reviewerRole = config.roles?.reviewer ?? \"reviewer\";\n\n assertMemberExists(config, reviewerRole, \"reviewer\");\n\n const gateKey = config.gateKey ?? \"approved\";\n\n return buildQualityGate<TState>(gateKey, fixerRole);\n }\n\n const gateKey = config.gateKey ?? \"passed\";\n\n return buildVerifyGate<TState>(gateKey, fixerRole);\n}\n\n/**\n * Construction-time guard: assert the resolved role key exists in\n * `members`, throwing an authoring-style {@link SupervisorFailedError}\n * (tagged `authoring: true`) listing the missing role when it doesn't.\n */\nfunction assertMemberExists<\n TOutput,\n TState,\n TMembers extends Record<string, TeamMemberValue>,\n>(\n config: TeamConfig<TOutput, TState, TMembers>,\n role: string,\n label: string,\n): void {\n if (!Object.prototype.hasOwnProperty.call(config.members, role)) {\n throw new SupervisorFailedError(\n `ai.team(\"${config.name}\"): gate \"${config.gate as string}\" needs a \"${label}\" member but no \\`members.${role}\\` key exists`,\n { context: { authoring: true } },\n );\n }\n}\n\n/**\n * Discriminate the `manager` union: `true` when it is the deterministic\n * `{ route }` form, `false` for a bare `AgentContract` / `RouterEntry`.\n */\nfunction isRouteManager<TOutput, TState>(\n manager: TeamConfig<TOutput, TState>[\"manager\"],\n): manager is { route: NonNullable<SupervisorConfig<TOutput, TState>[\"route\"]> } {\n return (\n typeof manager === \"object\" &&\n manager !== null &&\n \"route\" in manager &&\n typeof (manager as { route?: unknown }).route === \"function\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,KAId,QAA4E;CAC5E,MAAM,mBAAsD;EAC1D,MAAM,OAAO;EACb,SAAS,OAAO;EAIhB,YAAY;EACZ,SAAS,OAAO;EAChB,UAAU,YAAuC,MAAM;EACvD,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,OA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AnDU;AA0BlC;;;;;iBA0EgB,mBAAA,CACd,KAAA,EAAO,aAAA,CAAc,cAAA,gBACpB,YAAA"}
|
|
@@ -48,8 +48,8 @@ function executableToTool(executable) {
|
|
|
48
48
|
name: executable.name,
|
|
49
49
|
description: executable.description ?? `Invoke "${executable.name}" as a tool.`,
|
|
50
50
|
input: executable.inputSchema ?? passthroughSchema(),
|
|
51
|
-
execute: async (input) => {
|
|
52
|
-
const result = await executable.execute(input);
|
|
51
|
+
execute: async (input, ctx) => {
|
|
52
|
+
const result = await executable.execute(input, ctx?.signal ? { signal: ctx.signal } : void 0);
|
|
53
53
|
if (result.error) throw result.error;
|
|
54
54
|
return {
|
|
55
55
|
data: result.data,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executable-as-tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { BaseResult } from \"../contracts/result/base-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AgentExecutionError, type AIError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"./tool\";\n\n/**\n * Envelope every executable's `execute()` resolves to. Agent, workflow,\n * and supervisor results all satisfy this shape — `data` / `error`\n * carry the outcome while `usage` and `report` are always present —\n * which is exactly what {@link compositeAsTool} needs to nest the inner\n * run under the outer tool-call node.\n */\ntype ExecutableEnvelope<TOutput> = BaseResult & {\n data?: TOutput;\n error?: AIError;\n report: BaseReport;\n};\n\n/**\n * Structural view of an executable primitive (agent / workflow /\n * supervisor) when it is dropped straight into an agent's `tools: []`\n * array WITHOUT being wrapped via `.asTool()` first.\n *\n * Only the fields the auto-adapt path reads are declared:\n * - `name` — becomes the LLM tool name (required; anonymous executables\n * are rejected at author time, mirroring `.asTool()`).\n * - `description` — the \"when would the model pick this?\" line.\n * - `inputSchema` — opt-in Standard Schema typing the tool's arguments.\n * Surfaced on `WorkflowInstance` / `SupervisorContract` from the new\n * optional `inputSchema` config field. Absent for agents (which take\n * a plain string prompt).\n * - `execute` — the dispatch entry every `ExecutableContract` exposes.\n *\n * `invoke` is declared `never` so a `ToolContract` (which HAS `invoke`)\n * can never be mistaken for an executable by the {@link isExecutableTool}\n * guard.\n */\nexport type ExecutableTool<TInput = unknown, TOutput = unknown> = {\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: StandardSchemaV1<TInput>;\n execute(input: TInput, options?: unknown): Promise<ExecutableEnvelope<TOutput>>;\n invoke?: never;\n};\n\n/**\n * Entry accepted in an agent's `tools: []` array — either an already-\n * built `ToolContract` (the `.asTool()` / `ai.tool()` path) or a raw\n * executable primitive the framework auto-adapts on the caller's\n * behalf.\n */\nexport type AgentToolEntry<TInput = unknown, TOutput = unknown> =\n | ToolContract<TInput, TOutput>\n | ExecutableTool<TInput, TOutput>;\n\n/**\n * Identity passthrough schema used when an executable is registered as\n * a tool without declaring an `inputSchema`. The model's raw arguments\n * flow straight to `execute()` unchanged — the executable validates\n * internally (workflows via their steps, supervisors/agents via their\n * own input handling).\n */\nfunction passthroughSchema<TInput>(): StandardSchemaV1<TInput> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-ai\",\n validate: (value: unknown) => ({ value: value as TInput }),\n },\n };\n}\n\n/**\n * Type guard distinguishing a raw executable primitive from a built\n * `ToolContract`. An executable exposes `execute()` and no `invoke()`;\n * a `ToolContract` exposes `invoke()`. The `invoke` check is the\n * load-bearing discriminator — `.asTool()`-wrapped composites keep\n * their own `execute` too, so checking `execute` alone is insufficient.\n */\nexport function isExecutableTool(entry: unknown): entry is ExecutableTool {\n if (!entry || typeof entry !== \"object\") {\n return false;\n }\n\n const candidate = entry as { execute?: unknown; invoke?: unknown };\n\n return typeof candidate.execute === \"function\" && typeof candidate.invoke !== \"function\";\n}\n\n/**\n * Adapt a raw executable primitive (agent / workflow / supervisor) into\n * a `ToolContract` so an agent can dispatch it inside its tool-call\n * loop WITHOUT the caller writing `.asTool()`. Derives the LLM tool\n * manifest from the executable's own `name` + `description` +\n * (optional) `inputSchema`, then dispatches through the executable's\n * `execute()` — the inner report nests under the outer tool-call node\n * exactly like an explicit `.asTool()` wrapper.\n *\n * Throws `AgentExecutionError` at author time when the executable lacks\n * a usable `name` — the agent's tool surface needs a stable id, the\n * same constraint `.asTool()` enforces.\n */\nexport function executableToTool<TInput, TOutput>(\n executable: ExecutableTool<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n if (!executable.name || typeof executable.name !== \"string\") {\n throw new AgentExecutionError(\n \"tools[]: an executable (agent/workflow/supervisor) used as a tool must have a `name`\",\n { context: { authoring: true } },\n );\n }\n\n return compositeAsTool<TInput, TOutput>({\n name: executable.name,\n description: executable.description ?? `Invoke \"${executable.name}\" as a tool.`,\n input: executable.inputSchema ?? passthroughSchema<TInput>(),\n execute: async (input) => {\n const result = await executable.execute(input);\n\n if (result.error) {\n // Surface the inner typed error so the surrounding\n // `compositeAsTool` wrapper produces a `ToolExecutionError`\n // with `cause` pointing back at the original subclass — the\n // agent's tool-call loop sees 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 as Usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Normalize an agent's `tools: []` array into a uniform\n * `ToolContract[]` for the runtime. Already-built `ToolContract`s\n * (`.asTool()` / `ai.tool()`) pass through untouched; raw executable\n * primitives are auto-adapted via {@link executableToTool}.\n *\n * Returns `undefined` when no tools were supplied so the agent's\n * existing `config.tools ?? []` fallbacks stay byte-identical.\n */\nexport function normalizeAgentTools(\n tools: ReadonlyArray<AgentToolEntry> | undefined,\n): ToolContract<unknown, unknown>[] | undefined {\n if (!tools) {\n return undefined;\n }\n\n return tools.map((entry) => {\n if (isExecutableTool(entry)) {\n return executableToTool(entry) as ToolContract<unknown, unknown>;\n }\n\n return entry as ToolContract<unknown, unknown>;\n });\n}\n"],"mappings":";;;;;;;;;;;;AAgEA,SAAS,oBAAsD;CAC7D,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,WAAoB,EAAS,MAAgB;CAC1D,EACF;AACF;;;;;;;;AASA,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,YAAY,cAAc,OAAO,UAAU,WAAW;AAChF;;;;;;;;;;;;;;AAeA,SAAgB,iBACd,YAC+B;CAC/B,IAAI,CAAC,WAAW,QAAQ,OAAO,WAAW,SAAS,UACjD,MAAM,IAAI,oBACR,wFACA,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,OAAO,gBAAiC;EACtC,MAAM,WAAW;EACjB,aAAa,WAAW,eAAe,WAAW,WAAW,KAAK;EAClE,OAAO,WAAW,eAAe,kBAA0B;EAC3D,SAAS,OAAO,
|
|
1
|
+
{"version":3,"file":"executable-as-tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { BaseResult } from \"../contracts/result/base-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AgentExecutionError, type AIError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"./tool\";\n\n/**\n * Envelope every executable's `execute()` resolves to. Agent, workflow,\n * and supervisor results all satisfy this shape — `data` / `error`\n * carry the outcome while `usage` and `report` are always present —\n * which is exactly what {@link compositeAsTool} needs to nest the inner\n * run under the outer tool-call node.\n */\ntype ExecutableEnvelope<TOutput> = BaseResult & {\n data?: TOutput;\n error?: AIError;\n report: BaseReport;\n};\n\n/**\n * Structural view of an executable primitive (agent / workflow /\n * supervisor) when it is dropped straight into an agent's `tools: []`\n * array WITHOUT being wrapped via `.asTool()` first.\n *\n * Only the fields the auto-adapt path reads are declared:\n * - `name` — becomes the LLM tool name (required; anonymous executables\n * are rejected at author time, mirroring `.asTool()`).\n * - `description` — the \"when would the model pick this?\" line.\n * - `inputSchema` — opt-in Standard Schema typing the tool's arguments.\n * Surfaced on `WorkflowInstance` / `SupervisorContract` from the new\n * optional `inputSchema` config field. Absent for agents (which take\n * a plain string prompt).\n * - `execute` — the dispatch entry every `ExecutableContract` exposes.\n *\n * `invoke` is declared `never` so a `ToolContract` (which HAS `invoke`)\n * can never be mistaken for an executable by the {@link isExecutableTool}\n * guard.\n */\nexport type ExecutableTool<TInput = unknown, TOutput = unknown> = {\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: StandardSchemaV1<TInput>;\n execute(input: TInput, options?: unknown): Promise<ExecutableEnvelope<TOutput>>;\n invoke?: never;\n};\n\n/**\n * Entry accepted in an agent's `tools: []` array — either an already-\n * built `ToolContract` (the `.asTool()` / `ai.tool()` path) or a raw\n * executable primitive the framework auto-adapts on the caller's\n * behalf.\n */\nexport type AgentToolEntry<TInput = unknown, TOutput = unknown> =\n | ToolContract<TInput, TOutput>\n | ExecutableTool<TInput, TOutput>;\n\n/**\n * Identity passthrough schema used when an executable is registered as\n * a tool without declaring an `inputSchema`. The model's raw arguments\n * flow straight to `execute()` unchanged — the executable validates\n * internally (workflows via their steps, supervisors/agents via their\n * own input handling).\n */\nfunction passthroughSchema<TInput>(): StandardSchemaV1<TInput> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-ai\",\n validate: (value: unknown) => ({ value: value as TInput }),\n },\n };\n}\n\n/**\n * Type guard distinguishing a raw executable primitive from a built\n * `ToolContract`. An executable exposes `execute()` and no `invoke()`;\n * a `ToolContract` exposes `invoke()`. The `invoke` check is the\n * load-bearing discriminator — `.asTool()`-wrapped composites keep\n * their own `execute` too, so checking `execute` alone is insufficient.\n */\nexport function isExecutableTool(entry: unknown): entry is ExecutableTool {\n if (!entry || typeof entry !== \"object\") {\n return false;\n }\n\n const candidate = entry as { execute?: unknown; invoke?: unknown };\n\n return typeof candidate.execute === \"function\" && typeof candidate.invoke !== \"function\";\n}\n\n/**\n * Adapt a raw executable primitive (agent / workflow / supervisor) into\n * a `ToolContract` so an agent can dispatch it inside its tool-call\n * loop WITHOUT the caller writing `.asTool()`. Derives the LLM tool\n * manifest from the executable's own `name` + `description` +\n * (optional) `inputSchema`, then dispatches through the executable's\n * `execute()` — the inner report nests under the outer tool-call node\n * exactly like an explicit `.asTool()` wrapper.\n *\n * Throws `AgentExecutionError` at author time when the executable lacks\n * a usable `name` — the agent's tool surface needs a stable id, the\n * same constraint `.asTool()` enforces.\n */\nexport function executableToTool<TInput, TOutput>(\n executable: ExecutableTool<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n if (!executable.name || typeof executable.name !== \"string\") {\n throw new AgentExecutionError(\n \"tools[]: an executable (agent/workflow/supervisor) used as a tool must have a `name`\",\n { context: { authoring: true } },\n );\n }\n\n return compositeAsTool<TInput, TOutput>({\n name: executable.name,\n description: executable.description ?? `Invoke \"${executable.name}\" as a tool.`,\n input: executable.inputSchema ?? passthroughSchema<TInput>(),\n execute: async (input, ctx) => {\n // Relay the outer run's cancellation signal so a cancelled parent\n // aborts this nested agent/workflow/supervisor (C2). Omit the\n // options object entirely when there's no signal so primitives that\n // treat any second arg as meaningful stay byte-identical.\n const result = await executable.execute(\n input,\n ctx?.signal ? { signal: ctx.signal } : undefined,\n );\n\n if (result.error) {\n // Surface the inner typed error so the surrounding\n // `compositeAsTool` wrapper produces a `ToolExecutionError`\n // with `cause` pointing back at the original subclass — the\n // agent's tool-call loop sees 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 as Usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Normalize an agent's `tools: []` array into a uniform\n * `ToolContract[]` for the runtime. Already-built `ToolContract`s\n * (`.asTool()` / `ai.tool()`) pass through untouched; raw executable\n * primitives are auto-adapted via {@link executableToTool}.\n *\n * Returns `undefined` when no tools were supplied so the agent's\n * existing `config.tools ?? []` fallbacks stay byte-identical.\n */\nexport function normalizeAgentTools(\n tools: ReadonlyArray<AgentToolEntry> | undefined,\n): ToolContract<unknown, unknown>[] | undefined {\n if (!tools) {\n return undefined;\n }\n\n return tools.map((entry) => {\n if (isExecutableTool(entry)) {\n return executableToTool(entry) as ToolContract<unknown, unknown>;\n }\n\n return entry as ToolContract<unknown, unknown>;\n });\n}\n"],"mappings":";;;;;;;;;;;;AAgEA,SAAS,oBAAsD;CAC7D,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,WAAoB,EAAS,MAAgB;CAC1D,EACF;AACF;;;;;;;;AASA,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,YAAY,cAAc,OAAO,UAAU,WAAW;AAChF;;;;;;;;;;;;;;AAeA,SAAgB,iBACd,YAC+B;CAC/B,IAAI,CAAC,WAAW,QAAQ,OAAO,WAAW,SAAS,UACjD,MAAM,IAAI,oBACR,wFACA,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,OAAO,gBAAiC;EACtC,MAAM,WAAW;EACjB,aAAa,WAAW,eAAe,WAAW,WAAW,KAAK;EAClE,OAAO,WAAW,eAAe,kBAA0B;EAC3D,SAAS,OAAO,OAAO,QAAQ;GAK7B,MAAM,SAAS,MAAM,WAAW,QAC9B,OACA,KAAK,SAAS,EAAE,QAAQ,IAAI,OAAO,IAAI,MACzC;GAEA,IAAI,OAAO,OAMT,MAAM,OAAO;GAGf,OAAO;IACL,MAAM,OAAO;IACb,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF;CACF,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,oBACd,OAC8C;CAC9C,IAAI,CAAC,OACH;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAI,iBAAiB,KAAK,GACxB,OAAO,iBAAiB,KAAK;EAG/B,OAAO;CACT,CAAC;AACH"}
|
package/esm/tool/tool.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"mappings":";;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;KAAY,gBAAA;EAQQ,iFANlB,IAAA,GAAO,OAAA,EAgBQ;EAdf,KAAA,GAAQ,OAAA,EAcmB;EAZ3B,KAAA,EAAO,KAAA,EAcP;EAZA,MAAA,EAAQ,UAAA;AAAA;;;;;;;;UAUO,YAAA,8CAA0D,UAAA,CACzE,MAAA,EACA,OAAA;EADA;;;;;;;;;;AAoB8E;
|
|
1
|
+
{"version":3,"file":"tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"mappings":";;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;KAAY,gBAAA;EAQQ,iFANlB,IAAA,GAAO,OAAA,EAgBQ;EAdf,KAAA,GAAQ,OAAA,EAcmB;EAZ3B,KAAA,EAAO,KAAA,EAcP;EAZA,MAAA,EAAQ,UAAA;AAAA;;;;;;;;UAUO,YAAA,8CAA0D,UAAA,CACzE,MAAA,EACA,OAAA;EADA;;;;;;;;;;AAoB8E;AA6JhF;;;;;;EA7JE,MAAA,CAAO,QAAA,WAAmB,GAAA,GAAM,WAAA,GAAc,OAAA,CAAQ,gBAAA,CAAiB,OAAA;AAAA;AAAA,iBA6JzD,IAAA,kBACd,QAAA,EAAU,UAAA,CAAW,MAAA,EAAQ,OAAA,IAC5B,YAAA,CAAa,MAAA,EAAQ,OAAA"}
|
package/esm/tool/tool.mjs
CHANGED
|
@@ -66,7 +66,7 @@ function compositeAsTool(contract) {
|
|
|
66
66
|
meta: contract.meta,
|
|
67
67
|
input: contract.input,
|
|
68
68
|
execute: publicExecute,
|
|
69
|
-
async invoke(rawInput,
|
|
69
|
+
async invoke(rawInput, ctx) {
|
|
70
70
|
const startedAtDate = /* @__PURE__ */ new Date();
|
|
71
71
|
const start = performance.now();
|
|
72
72
|
const runId = generateRunId("tool");
|
|
@@ -106,7 +106,7 @@ function compositeAsTool(contract) {
|
|
|
106
106
|
context: { toolName: contract.name }
|
|
107
107
|
}));
|
|
108
108
|
try {
|
|
109
|
-
const composite = await contract.execute(validationResult.value);
|
|
109
|
+
const composite = await contract.execute(validationResult.value, ctx);
|
|
110
110
|
return {
|
|
111
111
|
data: composite.data,
|
|
112
112
|
error: composite.error,
|
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 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":";;;;;;;;;;;;;AAcA,SAAS,qBAAkC;CACzC,OAAO,EAAE,WAAW,CAAC,EAAE;AACzB;AAEA,MAAM,cAAqB,OAAO,OAAO;CAAE,OAAO;CAAG,QAAQ;CAAG,OAAO;AAAE,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;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mB;GAGjD,IAAI,iBAAiB,QAGnB,OAAO,OAAO,EACZ,OAAO,IAAI,sBAAsB,sBAHnB,iBAAiB,OAAO,KAAK,UAAU,MAAM,OAAO,CAAC,CAAC,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"}
|
|
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 /**\n * Runs the underlying composite and returns its full envelope. The\n * optional `ctx` relays the outer run's cancellation `signal` so a\n * cancelled parent aborts the nested primitive instead of letting it\n * outlive the cancellation (C2).\n */\n execute: (input: TInput, ctx?: ToolContext) => 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) run in\n // their own state/scope — the ctx's `artifacts` bag is NOT shared\n // into the inner primitive (an inner supervisor gets a fresh bag).\n // The cancellation `signal`, however, IS relayed (below, into\n // `contract.execute`) so a cancelled outer run aborts the nested\n // primitive instead of letting it outlive the cancellation (C2).\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, ctx);\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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,CAAC,SAAS,QAAQ;GACxE,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;QAMA,mBAAmB,EAAE,OAAO,SAAmB;GAGjD,IAAI,iBAAiB,QAGnB,OAAO,OAAO,EACZ,OAAO,IAAI,sBAAsB,sBAHnB,iBAAiB,OAAO,KAAK,UAAU,MAAM,OAAO,CAAC,CAAC,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,47 @@
|
|
|
1
|
+
import { AudioInput } from "../contracts/transcription-model.contract.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/transcribe/audio-input.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Resolve the audio media type from a filename's extension, or
|
|
6
|
+
* `undefined` when the extension is unknown. Case-insensitive.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* audioMediaTypeForFilename("voice-note.opus"); // "audio/ogg"
|
|
10
|
+
*/
|
|
11
|
+
declare function audioMediaTypeForFilename(filename: string): string | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.
|
|
14
|
+
* Pure plumbing — no AI, no I/O. Use when you already hold the bytes
|
|
15
|
+
* (an upload buffer, a downloaded blob).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const audio = audioFromBuffer(uploadBuffer, "audio/ogg", "note.ogg");
|
|
19
|
+
* const { data } = await ai.transcribe({ model: openai.transcribe({ name: "whisper-1" }), audio });
|
|
20
|
+
*/
|
|
21
|
+
declare function audioFromBuffer(data: Uint8Array, mediaType: string, filename?: string): AudioInput;
|
|
22
|
+
/**
|
|
23
|
+
* Read an audio file from disk and package it as an {@link AudioInput}
|
|
24
|
+
* for `ai.transcribe()` — the one-line bridge from a file on disk
|
|
25
|
+
* (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the
|
|
26
|
+
* transcription verb. **Pure utility — no AI here**; the actual text
|
|
27
|
+
* extraction is the AI step (`ai.transcribe`).
|
|
28
|
+
*
|
|
29
|
+
* The media type is inferred from the file extension (override via
|
|
30
|
+
* `options.mediaType` for extensionless or mislabeled files).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* // WhatsApp voice note → text, end to end:
|
|
34
|
+
* const audio = await audioFromFile("./voice-note.ogg");
|
|
35
|
+
* const { data, error } = await ai.transcribe({
|
|
36
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
37
|
+
* audio,
|
|
38
|
+
* language: "en",
|
|
39
|
+
* });
|
|
40
|
+
* if (!error) console.log(data.text);
|
|
41
|
+
*/
|
|
42
|
+
declare function audioFromFile(filePath: string, options?: {
|
|
43
|
+
mediaType?: string;
|
|
44
|
+
}): Promise<AudioInput>;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { audioFromBuffer, audioFromFile, audioMediaTypeForFilename };
|
|
47
|
+
//# sourceMappingURL=audio-input.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audio-input.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/audio-input.ts"],"mappings":";;;;;AAgCA;;;;AAA0D;iBAA1C,yBAAA,CAA0B,QAAgB;;;;;;;;;;iBAa1C,eAAA,CACd,IAAA,EAAM,UAAA,EACN,SAAA,UACA,QAAA,YACC,UAAU;AA4Bb;;;;;;;;;;AAGqB;;;;;;;;;;AAHrB,iBAAsB,aAAA,CACpB,QAAA,UACA,OAAA;EAAY,SAAA;AAAA,IACX,OAAO,CAAC,UAAA"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { basename, extname } from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/ai/src/transcribe/audio-input.ts
|
|
5
|
+
/**
|
|
6
|
+
* File-extension → IANA audio media type map covering the formats the
|
|
7
|
+
* common STT providers accept — including the **WhatsApp voice-note**
|
|
8
|
+
* formats (`.ogg` / `.opus`, Opus-in-Ogg on Android; `.m4a` on iOS).
|
|
9
|
+
*/
|
|
10
|
+
const AUDIO_MEDIA_TYPES = {
|
|
11
|
+
".mp3": "audio/mpeg",
|
|
12
|
+
".mpeg": "audio/mpeg",
|
|
13
|
+
".mpga": "audio/mpeg",
|
|
14
|
+
".m4a": "audio/mp4",
|
|
15
|
+
".mp4": "audio/mp4",
|
|
16
|
+
".wav": "audio/wav",
|
|
17
|
+
".webm": "audio/webm",
|
|
18
|
+
".weba": "audio/webm",
|
|
19
|
+
".ogg": "audio/ogg",
|
|
20
|
+
".oga": "audio/ogg",
|
|
21
|
+
".opus": "audio/ogg",
|
|
22
|
+
".flac": "audio/flac",
|
|
23
|
+
".aac": "audio/aac"
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the audio media type from a filename's extension, or
|
|
27
|
+
* `undefined` when the extension is unknown. Case-insensitive.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* audioMediaTypeForFilename("voice-note.opus"); // "audio/ogg"
|
|
31
|
+
*/
|
|
32
|
+
function audioMediaTypeForFilename(filename) {
|
|
33
|
+
return AUDIO_MEDIA_TYPES[extname(filename).toLowerCase()];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.
|
|
37
|
+
* Pure plumbing — no AI, no I/O. Use when you already hold the bytes
|
|
38
|
+
* (an upload buffer, a downloaded blob).
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const audio = audioFromBuffer(uploadBuffer, "audio/ogg", "note.ogg");
|
|
42
|
+
* const { data } = await ai.transcribe({ model: openai.transcribe({ name: "whisper-1" }), audio });
|
|
43
|
+
*/
|
|
44
|
+
function audioFromBuffer(data, mediaType, filename) {
|
|
45
|
+
return {
|
|
46
|
+
base64: Buffer.from(data).toString("base64"),
|
|
47
|
+
mediaType,
|
|
48
|
+
...filename ? { filename } : {}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Read an audio file from disk and package it as an {@link AudioInput}
|
|
53
|
+
* for `ai.transcribe()` — the one-line bridge from a file on disk
|
|
54
|
+
* (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the
|
|
55
|
+
* transcription verb. **Pure utility — no AI here**; the actual text
|
|
56
|
+
* extraction is the AI step (`ai.transcribe`).
|
|
57
|
+
*
|
|
58
|
+
* The media type is inferred from the file extension (override via
|
|
59
|
+
* `options.mediaType` for extensionless or mislabeled files).
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* // WhatsApp voice note → text, end to end:
|
|
63
|
+
* const audio = await audioFromFile("./voice-note.ogg");
|
|
64
|
+
* const { data, error } = await ai.transcribe({
|
|
65
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
66
|
+
* audio,
|
|
67
|
+
* language: "en",
|
|
68
|
+
* });
|
|
69
|
+
* if (!error) console.log(data.text);
|
|
70
|
+
*/
|
|
71
|
+
async function audioFromFile(filePath, options) {
|
|
72
|
+
const buffer = await readFile(filePath);
|
|
73
|
+
const filename = basename(filePath);
|
|
74
|
+
const mediaType = options?.mediaType ?? audioMediaTypeForFilename(filename) ?? "audio/mpeg";
|
|
75
|
+
return {
|
|
76
|
+
base64: buffer.toString("base64"),
|
|
77
|
+
mediaType,
|
|
78
|
+
filename
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
export { audioFromBuffer, audioFromFile, audioMediaTypeForFilename };
|
|
84
|
+
//# sourceMappingURL=audio-input.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audio-input.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/audio-input.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { basename, extname } from \"node:path\";\nimport type { AudioInput } from \"../contracts/transcription-model.contract\";\n\n/**\n * File-extension → IANA audio media type map covering the formats the\n * common STT providers accept — including the **WhatsApp voice-note**\n * formats (`.ogg` / `.opus`, Opus-in-Ogg on Android; `.m4a` on iOS).\n */\nconst AUDIO_MEDIA_TYPES: Record<string, string> = {\n \".mp3\": \"audio/mpeg\",\n \".mpeg\": \"audio/mpeg\",\n \".mpga\": \"audio/mpeg\",\n \".m4a\": \"audio/mp4\",\n \".mp4\": \"audio/mp4\",\n \".wav\": \"audio/wav\",\n \".webm\": \"audio/webm\",\n \".weba\": \"audio/webm\",\n \".ogg\": \"audio/ogg\",\n \".oga\": \"audio/ogg\",\n \".opus\": \"audio/ogg\",\n \".flac\": \"audio/flac\",\n \".aac\": \"audio/aac\",\n};\n\n/**\n * Resolve the audio media type from a filename's extension, or\n * `undefined` when the extension is unknown. Case-insensitive.\n *\n * @example\n * audioMediaTypeForFilename(\"voice-note.opus\"); // \"audio/ogg\"\n */\nexport function audioMediaTypeForFilename(filename: string): string | undefined {\n return AUDIO_MEDIA_TYPES[extname(filename).toLowerCase()];\n}\n\n/**\n * Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.\n * Pure plumbing — no AI, no I/O. Use when you already hold the bytes\n * (an upload buffer, a downloaded blob).\n *\n * @example\n * const audio = audioFromBuffer(uploadBuffer, \"audio/ogg\", \"note.ogg\");\n * const { data } = await ai.transcribe({ model: openai.transcribe({ name: \"whisper-1\" }), audio });\n */\nexport function audioFromBuffer(\n data: Uint8Array,\n mediaType: string,\n filename?: string,\n): AudioInput {\n return {\n base64: Buffer.from(data).toString(\"base64\"),\n mediaType,\n ...(filename ? { filename } : {}),\n };\n}\n\n/**\n * Read an audio file from disk and package it as an {@link AudioInput}\n * for `ai.transcribe()` — the one-line bridge from a file on disk\n * (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the\n * transcription verb. **Pure utility — no AI here**; the actual text\n * extraction is the AI step (`ai.transcribe`).\n *\n * The media type is inferred from the file extension (override via\n * `options.mediaType` for extensionless or mislabeled files).\n *\n * @example\n * // WhatsApp voice note → text, end to end:\n * const audio = await audioFromFile(\"./voice-note.ogg\");\n * const { data, error } = await ai.transcribe({\n * model: openai.transcribe({ name: \"whisper-1\" }),\n * audio,\n * language: \"en\",\n * });\n * if (!error) console.log(data.text);\n */\nexport async function audioFromFile(\n filePath: string,\n options?: { mediaType?: string },\n): Promise<AudioInput> {\n const buffer = await readFile(filePath);\n const filename = basename(filePath);\n const mediaType = options?.mediaType ?? audioMediaTypeForFilename(filename) ?? \"audio/mpeg\";\n\n return { base64: buffer.toString(\"base64\"), mediaType, filename };\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,oBAA4C;CAChD,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;AACV;;;;;;;;AASA,SAAgB,0BAA0B,UAAsC;CAC9E,OAAO,kBAAkB,QAAQ,QAAQ,CAAC,CAAC,YAAY;AACzD;;;;;;;;;;AAWA,SAAgB,gBACd,MACA,WACA,UACY;CACZ,OAAO;EACL,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;EAC3C;EACA,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CACjC;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,cACpB,UACA,SACqB;CACrB,MAAM,SAAS,MAAM,SAAS,QAAQ;CACtC,MAAM,WAAW,SAAS,QAAQ;CAClC,MAAM,YAAY,SAAS,aAAa,0BAA0B,QAAQ,KAAK;CAE/E,OAAO;EAAE,QAAQ,OAAO,SAAS,QAAQ;EAAG;EAAW;CAAS;AAClE"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { BaseReport } from "../contracts/result/base-report.type.mjs";
|
|
2
|
+
import { ExecuteResult } from "../contracts/result/execute-result.type.mjs";
|
|
3
|
+
import { FlowObserveOption } from "../observe/resolve-observers.mjs";
|
|
4
|
+
import { AudioInput, TranscriptionModelContract, TranscriptionSegment } from "../contracts/transcription-model.contract.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/ai/src/transcribe/transcribe.d.ts
|
|
7
|
+
/** Parameters for {@link transcribe}. `model` comes from `sdk.transcribe({ name })`. */
|
|
8
|
+
type TranscribeParams = {
|
|
9
|
+
/** The STT model to transcribe with. */model: TranscriptionModelContract; /** The audio to transcribe (inlined base64 bytes + media type). */
|
|
10
|
+
audio: AudioInput; /** BCP-47 language hint. */
|
|
11
|
+
language?: string; /** Optional priming prompt (spelling/style hints). */
|
|
12
|
+
prompt?: string; /** Provider response-format override (e.g. `"verbose_json"`). */
|
|
13
|
+
format?: string; /** Cancellation handle. */
|
|
14
|
+
signal?: AbortSignal; /** Observability routing — same `observe` seam as agents. */
|
|
15
|
+
observe?: FlowObserveOption; /** Groups this call into a session for flat cost/trace queries. */
|
|
16
|
+
sessionId?: string; /** Report node name (defaults to `"transcription"`). */
|
|
17
|
+
name?: string; /** Provider-specific options forwarded verbatim to the adapter. */
|
|
18
|
+
options?: Record<string, unknown>;
|
|
19
|
+
};
|
|
20
|
+
/** Success payload of a {@link transcribe} run. */
|
|
21
|
+
type TranscriptionData = {
|
|
22
|
+
/** The full transcript text. */text: string; /** Timestamped segments when the provider returned them. */
|
|
23
|
+
segments?: TranscriptionSegment[];
|
|
24
|
+
};
|
|
25
|
+
/** The report node a {@link transcribe} run produces (`type: "transcription"`). */
|
|
26
|
+
type TranscriptionReport = BaseReport & {
|
|
27
|
+
type: "transcription"; /** Identity of the STT model this run used. */
|
|
28
|
+
model: {
|
|
29
|
+
name: string;
|
|
30
|
+
provider: string;
|
|
31
|
+
}; /** Input audio duration in seconds, when the provider reported it. */
|
|
32
|
+
durationSeconds?: number;
|
|
33
|
+
};
|
|
34
|
+
/** Result envelope of {@link transcribe} — the uniform `{ data, error, usage, report }`. */
|
|
35
|
+
type TranscriptionResult = ExecuteResult<TranscriptionData> & {
|
|
36
|
+
type: "transcription";
|
|
37
|
+
report: TranscriptionReport;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Transcribe audio to text — the speech-to-text verb of the
|
|
41
|
+
* output-modality track (Theme I), inverse of `ai.speech()`. Wraps a
|
|
42
|
+
* {@link TranscriptionModelContract} (from `openai.transcribe(...)`) in
|
|
43
|
+
* the uniform result contract:
|
|
44
|
+
*
|
|
45
|
+
* - **Never throws.** Provider failures surface as a typed `AIError` on
|
|
46
|
+
* `result.error`.
|
|
47
|
+
* - **Cost-truth.** `result.usage.cost` is filled per-minute
|
|
48
|
+
* (`whisper-1`) or per-token (`gpt-4o-transcribe`).
|
|
49
|
+
* - **Observable.** The completed {@link TranscriptionReport} routes to
|
|
50
|
+
* any registered `Observer` via the `observe` seam.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* const openai = new OpenAISDK({ apiKey });
|
|
54
|
+
* const { data, error } = await ai.transcribe({
|
|
55
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
56
|
+
* audio: { base64, mediaType: "audio/mpeg", filename: "voicemail.mp3" },
|
|
57
|
+
* language: "en",
|
|
58
|
+
* });
|
|
59
|
+
* if (!error) console.log(data.text);
|
|
60
|
+
*/
|
|
61
|
+
declare function transcribe(params: TranscribeParams): Promise<TranscriptionResult>;
|
|
62
|
+
//#endregion
|
|
63
|
+
export { TranscribeParams, TranscriptionData, TranscriptionReport, TranscriptionResult, transcribe };
|
|
64
|
+
//# sourceMappingURL=transcribe.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcribe.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/transcribe.ts"],"mappings":";;;;;;;KAoBY,gBAAA;EAAA,wCAEV,KAAA,EAAO,0BAAA;EAEP,KAAA,EAAO,UAAA,EAAA;EAEP,QAAA,WAQU;EANV,MAAA,WAYgB;EAVhB,MAAA,WARA;EAUA,MAAA,GAAS,WAAA,EART;EAUA,OAAA,GAAU,iBAAA,EARV;EAUA,SAAA,WANA;EAQA,IAAA,WANS;EAQT,OAAA,GAAU,MAAA;AAAA;;KAIA,iBAAA;EAJV,gCAMA,IAAA,UANgB;EAQhB,QAAA,GAAW,oBAAoB;AAAA;;KAIrB,mBAAA,GAAsB,UAAU;EAC1C,IAAA,mBAPA;EASA,KAAA;IAAS,IAAA;IAAc,QAAA;EAAA,GAHb;EAKV,eAAA;AAAA;;KAIU,mBAAA,GAAsB,aAAA,CAAc,iBAAA;EAC9C,IAAA;EACA,MAAA,EAAQ,mBAAA;AAAA;;;;AANO;AAIjB;;;;;;;;;;;;;;AAE6B;AAyB7B;;;iBAAsB,UAAA,CAAW,MAAA,EAAQ,gBAAA,GAAmB,OAAA,CAAQ,mBAAA"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { AIError } from "../errors/ai-error.mjs";
|
|
2
|
+
import { ProviderError } from "../errors/provider-error.mjs";
|
|
3
|
+
import { computeCost } from "../utils/compute-cost.mjs";
|
|
4
|
+
import { generateRunId } from "../utils/generate-run-id.mjs";
|
|
5
|
+
import { REPORT_SCHEMA_VERSION } from "../contracts/result/base-report.type.mjs";
|
|
6
|
+
import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
|
|
7
|
+
import { notifyObservers } from "../observe/resolve-observers.mjs";
|
|
8
|
+
|
|
9
|
+
//#region ../@warlock.js/ai/src/transcribe/transcribe.ts
|
|
10
|
+
/**
|
|
11
|
+
* Transcribe audio to text — the speech-to-text verb of the
|
|
12
|
+
* output-modality track (Theme I), inverse of `ai.speech()`. Wraps a
|
|
13
|
+
* {@link TranscriptionModelContract} (from `openai.transcribe(...)`) in
|
|
14
|
+
* the uniform result contract:
|
|
15
|
+
*
|
|
16
|
+
* - **Never throws.** Provider failures surface as a typed `AIError` on
|
|
17
|
+
* `result.error`.
|
|
18
|
+
* - **Cost-truth.** `result.usage.cost` is filled per-minute
|
|
19
|
+
* (`whisper-1`) or per-token (`gpt-4o-transcribe`).
|
|
20
|
+
* - **Observable.** The completed {@link TranscriptionReport} routes to
|
|
21
|
+
* any registered `Observer` via the `observe` seam.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const openai = new OpenAISDK({ apiKey });
|
|
25
|
+
* const { data, error } = await ai.transcribe({
|
|
26
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
27
|
+
* audio: { base64, mediaType: "audio/mpeg", filename: "voicemail.mp3" },
|
|
28
|
+
* language: "en",
|
|
29
|
+
* });
|
|
30
|
+
* if (!error) console.log(data.text);
|
|
31
|
+
*/
|
|
32
|
+
async function transcribe(params) {
|
|
33
|
+
const { model, audio } = params;
|
|
34
|
+
const runId = generateRunId("transcription");
|
|
35
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
36
|
+
const startPerf = performance.now();
|
|
37
|
+
const usage = {
|
|
38
|
+
input: 0,
|
|
39
|
+
output: 0,
|
|
40
|
+
total: 0
|
|
41
|
+
};
|
|
42
|
+
let data;
|
|
43
|
+
let error;
|
|
44
|
+
let status = "completed";
|
|
45
|
+
let durationSeconds;
|
|
46
|
+
try {
|
|
47
|
+
const response = await model.transcribe(audio, {
|
|
48
|
+
language: params.language,
|
|
49
|
+
prompt: params.prompt,
|
|
50
|
+
format: params.format,
|
|
51
|
+
signal: params.signal,
|
|
52
|
+
...params.options
|
|
53
|
+
});
|
|
54
|
+
Object.assign(usage, response.usage);
|
|
55
|
+
durationSeconds = response.durationSeconds;
|
|
56
|
+
if (usage.cost === void 0) {
|
|
57
|
+
const cost = computeTranscriptionCost(usage, durationSeconds, model.pricing);
|
|
58
|
+
if (cost !== void 0) usage.cost = cost;
|
|
59
|
+
}
|
|
60
|
+
data = {
|
|
61
|
+
text: response.text,
|
|
62
|
+
...response.segments ? { segments: response.segments } : {}
|
|
63
|
+
};
|
|
64
|
+
} catch (thrown) {
|
|
65
|
+
error = thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });
|
|
66
|
+
status = params.signal?.aborted ? "cancelled" : "failed";
|
|
67
|
+
}
|
|
68
|
+
const report = {
|
|
69
|
+
runId,
|
|
70
|
+
rootRunId: runId,
|
|
71
|
+
name: params.name ?? "transcription",
|
|
72
|
+
type: "transcription",
|
|
73
|
+
status,
|
|
74
|
+
error,
|
|
75
|
+
startedAt,
|
|
76
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
77
|
+
duration: performance.now() - startPerf,
|
|
78
|
+
usage,
|
|
79
|
+
children: [],
|
|
80
|
+
model: {
|
|
81
|
+
name: model.name,
|
|
82
|
+
provider: model.provider
|
|
83
|
+
},
|
|
84
|
+
...durationSeconds !== void 0 ? { durationSeconds } : {},
|
|
85
|
+
reportSchemaVersion: 1
|
|
86
|
+
};
|
|
87
|
+
stampReportLineage(report, {
|
|
88
|
+
rootRunId: runId,
|
|
89
|
+
sessionId: params.sessionId
|
|
90
|
+
});
|
|
91
|
+
await notifyObservers(params.observe, report);
|
|
92
|
+
return {
|
|
93
|
+
type: "transcription",
|
|
94
|
+
data,
|
|
95
|
+
error,
|
|
96
|
+
usage,
|
|
97
|
+
report
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Price an STT run: `perMinute × (durationSeconds / 60)` (per-minute
|
|
102
|
+
* metering, attributed to `cost.input`) wins when configured, otherwise
|
|
103
|
+
* the standard token math. Returns `undefined` when no usable pricing
|
|
104
|
+
* is present (e.g. per-minute pricing but the provider didn't report a
|
|
105
|
+
* duration).
|
|
106
|
+
*/
|
|
107
|
+
function computeTranscriptionCost(usage, durationSeconds, pricing) {
|
|
108
|
+
if (!pricing) return;
|
|
109
|
+
if (pricing.perMinute !== void 0) {
|
|
110
|
+
if (durationSeconds === void 0) return;
|
|
111
|
+
return {
|
|
112
|
+
input: durationSeconds / 60 * pricing.perMinute,
|
|
113
|
+
output: 0
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (pricing.input !== void 0 && pricing.output !== void 0) return computeCost(usage, {
|
|
117
|
+
input: pricing.input,
|
|
118
|
+
output: pricing.output
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/** Best-effort message for a non-`AIError` thrown value. */
|
|
122
|
+
function toMessage(thrown) {
|
|
123
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//#endregion
|
|
127
|
+
export { transcribe };
|
|
128
|
+
//# sourceMappingURL=transcribe.mjs.map
|