@warlock.js/core 4.8.0 → 4.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/esm/connectors/ai-connector.mjs +1 -1
- package/package.json +12 -9
- package/esm/ai/src/agent/agent-input-builder.mjs +0 -133
- package/esm/ai/src/agent/agent-input-builder.mjs.map +0 -1
- package/esm/ai/src/agent/agent-log-event.mjs +0 -101
- package/esm/ai/src/agent/agent-log-event.mjs.map +0 -1
- package/esm/ai/src/agent/agent-stream.mjs +0 -82
- package/esm/ai/src/agent/agent-stream.mjs.map +0 -1
- package/esm/ai/src/agent/agent-to-stream-event.mjs +0 -86
- package/esm/ai/src/agent/agent-to-stream-event.mjs.map +0 -1
- package/esm/ai/src/agent/agent.mjs +0 -1276
- package/esm/ai/src/agent/agent.mjs.map +0 -1
- package/esm/ai/src/agent/index.mjs +0 -5
- package/esm/ai/src/agent/json-stream-guard.mjs +0 -400
- package/esm/ai/src/agent/json-stream-guard.mjs.map +0 -1
- package/esm/ai/src/agent/signature.mjs +0 -57
- package/esm/ai/src/agent/signature.mjs.map +0 -1
- package/esm/ai/src/agent/snapshot.mjs +0 -101
- package/esm/ai/src/agent/snapshot.mjs.map +0 -1
- package/esm/ai/src/agent/spawn-sub-agent.mjs +0 -68
- package/esm/ai/src/agent/spawn-sub-agent.mjs.map +0 -1
- package/esm/ai/src/ai.mjs +0 -191
- package/esm/ai/src/ai.mjs.map +0 -1
- package/esm/ai/src/batch/batch.mjs +0 -198
- package/esm/ai/src/batch/batch.mjs.map +0 -1
- package/esm/ai/src/batch/index.mjs +0 -3
- package/esm/ai/src/batch/run-batch-item.mjs +0 -100
- package/esm/ai/src/batch/run-batch-item.mjs.map +0 -1
- package/esm/ai/src/batch/run-with-concurrency.mjs +0 -39
- package/esm/ai/src/batch/run-with-concurrency.mjs.map +0 -1
- package/esm/ai/src/checkpoint/memory.mjs +0 -0
- package/esm/ai/src/checkpoint/memory.mjs.map +0 -1
- package/esm/ai/src/checkpoint/pg.mjs +0 -265
- package/esm/ai/src/checkpoint/pg.mjs.map +0 -1
- package/esm/ai/src/checkpoint/redis.mjs +0 -200
- package/esm/ai/src/checkpoint/redis.mjs.map +0 -1
- package/esm/ai/src/config.mjs +0 -59
- package/esm/ai/src/config.mjs.map +0 -1
- package/esm/ai/src/contracts/end.type.mjs +0 -47
- package/esm/ai/src/contracts/end.type.mjs.map +0 -1
- package/esm/ai/src/errors/agent-cancelled-error.mjs +0 -43
- package/esm/ai/src/errors/agent-cancelled-error.mjs.map +0 -1
- package/esm/ai/src/errors/agent-drift-error.mjs +0 -31
- package/esm/ai/src/errors/agent-drift-error.mjs.map +0 -1
- package/esm/ai/src/errors/agent-execution-error.mjs +0 -35
- package/esm/ai/src/errors/agent-execution-error.mjs.map +0 -1
- package/esm/ai/src/errors/agent-max-trips-error.mjs +0 -41
- package/esm/ai/src/errors/agent-max-trips-error.mjs.map +0 -1
- package/esm/ai/src/errors/ai-error.mjs +0 -68
- package/esm/ai/src/errors/ai-error.mjs.map +0 -1
- package/esm/ai/src/errors/budget-exceeded-error.mjs +0 -31
- package/esm/ai/src/errors/budget-exceeded-error.mjs.map +0 -1
- package/esm/ai/src/errors/content-filter-error.mjs +0 -28
- package/esm/ai/src/errors/content-filter-error.mjs.map +0 -1
- package/esm/ai/src/errors/context-length-exceeded-error.mjs +0 -31
- package/esm/ai/src/errors/context-length-exceeded-error.mjs.map +0 -1
- package/esm/ai/src/errors/guardrail-violation-error.mjs +0 -41
- package/esm/ai/src/errors/guardrail-violation-error.mjs.map +0 -1
- package/esm/ai/src/errors/index.mjs +0 -40
- package/esm/ai/src/errors/invalid-request-error.mjs +0 -31
- package/esm/ai/src/errors/invalid-request-error.mjs.map +0 -1
- package/esm/ai/src/errors/max-iterations-error.mjs +0 -32
- package/esm/ai/src/errors/max-iterations-error.mjs.map +0 -1
- package/esm/ai/src/errors/max-steps-exceeded-error.mjs +0 -21
- package/esm/ai/src/errors/max-steps-exceeded-error.mjs.map +0 -1
- package/esm/ai/src/errors/orchestrator-cancelled-error.mjs +0 -31
- package/esm/ai/src/errors/orchestrator-cancelled-error.mjs.map +0 -1
- package/esm/ai/src/errors/orchestrator-config-error.mjs +0 -30
- package/esm/ai/src/errors/orchestrator-config-error.mjs.map +0 -1
- package/esm/ai/src/errors/orchestrator-drift-error.mjs +0 -37
- package/esm/ai/src/errors/orchestrator-drift-error.mjs.map +0 -1
- package/esm/ai/src/errors/orchestrator-failed-error.mjs +0 -36
- package/esm/ai/src/errors/orchestrator-failed-error.mjs.map +0 -1
- package/esm/ai/src/errors/outbound-policy-error.mjs +0 -32
- package/esm/ai/src/errors/outbound-policy-error.mjs.map +0 -1
- package/esm/ai/src/errors/planner-cancelled-error.mjs +0 -29
- package/esm/ai/src/errors/planner-cancelled-error.mjs.map +0 -1
- package/esm/ai/src/errors/planner-drift-error.mjs +0 -33
- package/esm/ai/src/errors/planner-drift-error.mjs.map +0 -1
- package/esm/ai/src/errors/planner-failed-error.mjs +0 -37
- package/esm/ai/src/errors/planner-failed-error.mjs.map +0 -1
- package/esm/ai/src/errors/planner-plan-invalid-error.mjs +0 -25
- package/esm/ai/src/errors/planner-plan-invalid-error.mjs.map +0 -1
- package/esm/ai/src/errors/prompt-refinement-error.mjs +0 -27
- package/esm/ai/src/errors/prompt-refinement-error.mjs.map +0 -1
- package/esm/ai/src/errors/provider-auth-error.mjs +0 -26
- package/esm/ai/src/errors/provider-auth-error.mjs.map +0 -1
- package/esm/ai/src/errors/provider-error.mjs +0 -42
- package/esm/ai/src/errors/provider-error.mjs.map +0 -1
- package/esm/ai/src/errors/provider-rate-limit-error.mjs +0 -31
- package/esm/ai/src/errors/provider-rate-limit-error.mjs.map +0 -1
- package/esm/ai/src/errors/provider-timeout-error.mjs +0 -26
- package/esm/ai/src/errors/provider-timeout-error.mjs.map +0 -1
- package/esm/ai/src/errors/quota-exceeded-error.mjs +0 -40
- package/esm/ai/src/errors/quota-exceeded-error.mjs.map +0 -1
- package/esm/ai/src/errors/routing-error.mjs +0 -23
- package/esm/ai/src/errors/routing-error.mjs.map +0 -1
- package/esm/ai/src/errors/schema-validation-error.mjs +0 -37
- package/esm/ai/src/errors/schema-validation-error.mjs.map +0 -1
- package/esm/ai/src/errors/step-failed-error.mjs +0 -19
- package/esm/ai/src/errors/step-failed-error.mjs.map +0 -1
- package/esm/ai/src/errors/supervisor-cancelled-error.mjs +0 -29
- package/esm/ai/src/errors/supervisor-cancelled-error.mjs.map +0 -1
- package/esm/ai/src/errors/supervisor-drift-error.mjs +0 -30
- package/esm/ai/src/errors/supervisor-drift-error.mjs.map +0 -1
- package/esm/ai/src/errors/supervisor-failed-error.mjs +0 -43
- package/esm/ai/src/errors/supervisor-failed-error.mjs.map +0 -1
- package/esm/ai/src/errors/supervisor-routing-error.mjs +0 -39
- package/esm/ai/src/errors/supervisor-routing-error.mjs.map +0 -1
- package/esm/ai/src/errors/tool-execution-error.mjs +0 -32
- package/esm/ai/src/errors/tool-execution-error.mjs.map +0 -1
- package/esm/ai/src/errors/workflow-cancelled-error.mjs +0 -23
- package/esm/ai/src/errors/workflow-cancelled-error.mjs.map +0 -1
- package/esm/ai/src/errors/workflow-drift-error.mjs +0 -24
- package/esm/ai/src/errors/workflow-drift-error.mjs.map +0 -1
- package/esm/ai/src/errors/workflow-error.mjs +0 -18
- package/esm/ai/src/errors/workflow-error.mjs.map +0 -1
- package/esm/ai/src/eval/dataset.mjs +0 -112
- package/esm/ai/src/eval/dataset.mjs.map +0 -1
- package/esm/ai/src/eval/eval-runner.mjs +0 -135
- package/esm/ai/src/eval/eval-runner.mjs.map +0 -1
- package/esm/ai/src/eval/index.mjs +0 -48
- package/esm/ai/src/eval/index.mjs.map +0 -1
- package/esm/ai/src/eval/judge-scorer.mjs +0 -87
- package/esm/ai/src/eval/judge-scorer.mjs.map +0 -1
- package/esm/ai/src/eval/regression.mjs +0 -51
- package/esm/ai/src/eval/regression.mjs.map +0 -1
- package/esm/ai/src/eval/report-json.mjs +0 -33
- package/esm/ai/src/eval/report-json.mjs.map +0 -1
- package/esm/ai/src/eval/report-junit.mjs +0 -60
- package/esm/ai/src/eval/report-junit.mjs.map +0 -1
- package/esm/ai/src/eval/scorers.mjs +0 -101
- package/esm/ai/src/eval/scorers.mjs.map +0 -1
- package/esm/ai/src/guard/detectors/index.mjs +0 -6
- package/esm/ai/src/guard/detectors/injection.mjs +0 -254
- package/esm/ai/src/guard/detectors/injection.mjs.map +0 -1
- package/esm/ai/src/guard/detectors/moderation.mjs +0 -134
- package/esm/ai/src/guard/detectors/moderation.mjs.map +0 -1
- package/esm/ai/src/guard/detectors/pii.mjs +0 -199
- package/esm/ai/src/guard/detectors/pii.mjs.map +0 -1
- package/esm/ai/src/guard/detectors/topic.mjs +0 -99
- package/esm/ai/src/guard/detectors/topic.mjs.map +0 -1
- package/esm/ai/src/guard/errors.mjs +0 -18
- package/esm/ai/src/guard/errors.mjs.map +0 -1
- package/esm/ai/src/guard/guard.mjs +0 -209
- package/esm/ai/src/guard/guard.mjs.map +0 -1
- package/esm/ai/src/guard/guardrail.mjs +0 -22
- package/esm/ai/src/guard/guardrail.mjs.map +0 -1
- package/esm/ai/src/human/errors.mjs +0 -60
- package/esm/ai/src/human/errors.mjs.map +0 -1
- package/esm/ai/src/human/human-approval.mjs +0 -170
- package/esm/ai/src/human/human-approval.mjs.map +0 -1
- package/esm/ai/src/human/policy.mjs +0 -67
- package/esm/ai/src/human/policy.mjs.map +0 -1
- package/esm/ai/src/human/register.mjs +0 -37
- package/esm/ai/src/human/register.mjs.map +0 -1
- package/esm/ai/src/human/resume-seed.mjs +0 -53
- package/esm/ai/src/human/resume-seed.mjs.map +0 -1
- package/esm/ai/src/human/resume.mjs +0 -121
- package/esm/ai/src/human/resume.mjs.map +0 -1
- package/esm/ai/src/human/stores/index.mjs +0 -5
- package/esm/ai/src/human/stores/memory.mjs +0 -91
- package/esm/ai/src/human/stores/memory.mjs.map +0 -1
- package/esm/ai/src/human/stores/pg.mjs +0 -220
- package/esm/ai/src/human/stores/pg.mjs.map +0 -1
- package/esm/ai/src/human/stores/redis.mjs +0 -201
- package/esm/ai/src/human/stores/redis.mjs.map +0 -1
- package/esm/ai/src/image/image-cost.mjs +0 -55
- package/esm/ai/src/image/image-cost.mjs.map +0 -1
- package/esm/ai/src/image/image.mjs +0 -112
- package/esm/ai/src/image/image.mjs.map +0 -1
- package/esm/ai/src/image/index.mjs +0 -4
- package/esm/ai/src/index.mjs +0 -196
- package/esm/ai/src/memory/derive-id.mjs +0 -24
- package/esm/ai/src/memory/derive-id.mjs.map +0 -1
- package/esm/ai/src/memory/episodic-memory.mjs +0 -106
- package/esm/ai/src/memory/episodic-memory.mjs.map +0 -1
- package/esm/ai/src/memory/memory.mjs +0 -166
- package/esm/ai/src/memory/memory.mjs.map +0 -1
- package/esm/ai/src/memory/procedural-memory.mjs +0 -103
- package/esm/ai/src/memory/procedural-memory.mjs.map +0 -1
- package/esm/ai/src/memory/semantic-memory.mjs +0 -80
- package/esm/ai/src/memory/semantic-memory.mjs.map +0 -1
- package/esm/ai/src/memory/working-memory.mjs +0 -62
- package/esm/ai/src/memory/working-memory.mjs.map +0 -1
- package/esm/ai/src/middleware/builtins/budget.mjs +0 -219
- package/esm/ai/src/middleware/builtins/budget.mjs.map +0 -1
- package/esm/ai/src/middleware/builtins/guardrail.mjs +0 -76
- package/esm/ai/src/middleware/builtins/guardrail.mjs.map +0 -1
- package/esm/ai/src/middleware/builtins/semantic-cache.mjs +0 -149
- package/esm/ai/src/middleware/builtins/semantic-cache.mjs.map +0 -1
- package/esm/ai/src/middleware/helpers/compose.mjs +0 -52
- package/esm/ai/src/middleware/helpers/compose.mjs.map +0 -1
- package/esm/ai/src/middleware/helpers/for-tool.mjs +0 -80
- package/esm/ai/src/middleware/helpers/for-tool.mjs.map +0 -1
- package/esm/ai/src/middleware/index.mjs +0 -10
- package/esm/ai/src/middleware/pipeline.mjs +0 -100
- package/esm/ai/src/middleware/pipeline.mjs.map +0 -1
- package/esm/ai/src/middleware/utils/extract-user-text.mjs +0 -47
- package/esm/ai/src/middleware/utils/extract-user-text.mjs.map +0 -1
- package/esm/ai/src/middleware/utils/namespaced-state.mjs +0 -60
- package/esm/ai/src/middleware/utils/namespaced-state.mjs.map +0 -1
- package/esm/ai/src/mock/index.mjs +0 -4
- package/esm/ai/src/mock/mock-agent.mjs +0 -3
- package/esm/ai/src/mock/mock-router.mjs +0 -58
- package/esm/ai/src/mock/mock-router.mjs.map +0 -1
- package/esm/ai/src/model/fallback-model.mjs +0 -218
- package/esm/ai/src/model/fallback-model.mjs.map +0 -1
- package/esm/ai/src/model/index.mjs +0 -3
- package/esm/ai/src/object-stream/index.mjs +0 -4
- package/esm/ai/src/object-stream/parse-partial-json.mjs +0 -78
- package/esm/ai/src/object-stream/parse-partial-json.mjs.map +0 -1
- package/esm/ai/src/object-stream/stream-object.mjs +0 -97
- package/esm/ai/src/object-stream/stream-object.mjs.map +0 -1
- package/esm/ai/src/observe/index.mjs +0 -4
- package/esm/ai/src/observe/observer-registry.mjs +0 -35
- package/esm/ai/src/observe/observer-registry.mjs.map +0 -1
- package/esm/ai/src/observe/resolve-observers.mjs +0 -73
- package/esm/ai/src/observe/resolve-observers.mjs.map +0 -1
- package/esm/ai/src/orchestrator/as-tool.mjs +0 -98
- package/esm/ai/src/orchestrator/as-tool.mjs.map +0 -1
- package/esm/ai/src/orchestrator/checkpoint.mjs +0 -75
- package/esm/ai/src/orchestrator/checkpoint.mjs.map +0 -1
- package/esm/ai/src/orchestrator/commands.mjs +0 -34
- package/esm/ai/src/orchestrator/commands.mjs.map +0 -1
- package/esm/ai/src/orchestrator/compaction.mjs +0 -206
- package/esm/ai/src/orchestrator/compaction.mjs.map +0 -1
- package/esm/ai/src/orchestrator/dispatch.mjs +0 -171
- package/esm/ai/src/orchestrator/dispatch.mjs.map +0 -1
- package/esm/ai/src/orchestrator/emitter.mjs +0 -85
- package/esm/ai/src/orchestrator/emitter.mjs.map +0 -1
- package/esm/ai/src/orchestrator/execution.mjs +0 -395
- package/esm/ai/src/orchestrator/execution.mjs.map +0 -1
- package/esm/ai/src/orchestrator/index.mjs +0 -11
- package/esm/ai/src/orchestrator/load.mjs +0 -49
- package/esm/ai/src/orchestrator/load.mjs.map +0 -1
- package/esm/ai/src/orchestrator/lock.mjs +0 -75
- package/esm/ai/src/orchestrator/lock.mjs.map +0 -1
- package/esm/ai/src/orchestrator/memory.mjs +0 -141
- package/esm/ai/src/orchestrator/memory.mjs.map +0 -1
- package/esm/ai/src/orchestrator/orchestrator-stream.mjs +0 -98
- package/esm/ai/src/orchestrator/orchestrator-stream.mjs.map +0 -1
- package/esm/ai/src/orchestrator/orchestrator.mjs +0 -206
- package/esm/ai/src/orchestrator/orchestrator.mjs.map +0 -1
- package/esm/ai/src/orchestrator/resume.mjs +0 -74
- package/esm/ai/src/orchestrator/resume.mjs.map +0 -1
- package/esm/ai/src/orchestrator/session-lock.mjs +0 -83
- package/esm/ai/src/orchestrator/session-lock.mjs.map +0 -1
- package/esm/ai/src/orchestrator/signature.mjs +0 -120
- package/esm/ai/src/orchestrator/signature.mjs.map +0 -1
- package/esm/ai/src/orchestrator/window.mjs +0 -56
- package/esm/ai/src/orchestrator/window.mjs.map +0 -1
- package/esm/ai/src/planner/dag-scheduler.mjs +0 -97
- package/esm/ai/src/planner/dag-scheduler.mjs.map +0 -1
- package/esm/ai/src/planner/index.mjs +0 -6
- package/esm/ai/src/planner/plan-prompt.mjs +0 -31
- package/esm/ai/src/planner/plan-prompt.mjs.map +0 -1
- package/esm/ai/src/planner/plan-schema.mjs +0 -120
- package/esm/ai/src/planner/plan-schema.mjs.map +0 -1
- package/esm/ai/src/planner/planner-run.mjs +0 -769
- package/esm/ai/src/planner/planner-run.mjs.map +0 -1
- package/esm/ai/src/planner/planner.mjs +0 -144
- package/esm/ai/src/planner/planner.mjs.map +0 -1
- package/esm/ai/src/planner/signature.mjs +0 -27
- package/esm/ai/src/planner/signature.mjs.map +0 -1
- package/esm/ai/src/planner/snapshot.mjs +0 -95
- package/esm/ai/src/planner/snapshot.mjs.map +0 -1
- package/esm/ai/src/prompt/errors.mjs +0 -73
- package/esm/ai/src/prompt/errors.mjs.map +0 -1
- package/esm/ai/src/prompt/index.mjs +0 -4
- package/esm/ai/src/prompt/prompt-langfuse-sync.mjs +0 -104
- package/esm/ai/src/prompt/prompt-langfuse-sync.mjs.map +0 -1
- package/esm/ai/src/prompt/prompt-validate.mjs +0 -170
- package/esm/ai/src/prompt/prompt-validate.mjs.map +0 -1
- package/esm/ai/src/prompt/prompt.mjs +0 -218
- package/esm/ai/src/prompt/prompt.mjs.map +0 -1
- package/esm/ai/src/prompts/index.mjs +0 -3
- package/esm/ai/src/prompts/prompts-manager.mjs +0 -410
- package/esm/ai/src/prompts/prompts-manager.mjs.map +0 -1
- package/esm/ai/src/prompts/prompts-validate.mjs +0 -0
- package/esm/ai/src/prompts/prompts-validate.mjs.map +0 -1
- package/esm/ai/src/rag/as-tool.mjs +0 -48
- package/esm/ai/src/rag/as-tool.mjs.map +0 -1
- package/esm/ai/src/rag/chunk/chunk.mjs +0 -44
- package/esm/ai/src/rag/chunk/chunk.mjs.map +0 -1
- package/esm/ai/src/rag/chunk/fixed.mjs +0 -32
- package/esm/ai/src/rag/chunk/fixed.mjs.map +0 -1
- package/esm/ai/src/rag/chunk/markdown.mjs +0 -75
- package/esm/ai/src/rag/chunk/markdown.mjs.map +0 -1
- package/esm/ai/src/rag/chunk/recursive.mjs +0 -132
- package/esm/ai/src/rag/chunk/recursive.mjs.map +0 -1
- package/esm/ai/src/rag/chunk/sentence.mjs +0 -73
- package/esm/ai/src/rag/chunk/sentence.mjs.map +0 -1
- package/esm/ai/src/rag/hybrid/bm25.mjs +0 -51
- package/esm/ai/src/rag/hybrid/bm25.mjs.map +0 -1
- package/esm/ai/src/rag/hybrid/hybrid-rank.mjs +0 -29
- package/esm/ai/src/rag/hybrid/hybrid-rank.mjs.map +0 -1
- package/esm/ai/src/rag/hybrid/rrf.mjs +0 -30
- package/esm/ai/src/rag/hybrid/rrf.mjs.map +0 -1
- package/esm/ai/src/rag/index.mjs +0 -18
- package/esm/ai/src/rag/loaders/errors.mjs +0 -25
- package/esm/ai/src/rag/loaders/errors.mjs.map +0 -1
- package/esm/ai/src/rag/loaders/index.mjs +0 -7
- package/esm/ai/src/rag/loaders/load-html.mjs +0 -138
- package/esm/ai/src/rag/loaders/load-html.mjs.map +0 -1
- package/esm/ai/src/rag/loaders/load-pdf.mjs +0 -150
- package/esm/ai/src/rag/loaders/load-pdf.mjs.map +0 -1
- package/esm/ai/src/rag/loaders/load-text.mjs +0 -60
- package/esm/ai/src/rag/loaders/load-text.mjs.map +0 -1
- package/esm/ai/src/rag/loaders/load-web.mjs +0 -89
- package/esm/ai/src/rag/loaders/load-web.mjs.map +0 -1
- package/esm/ai/src/rag/rag.mjs +0 -126
- package/esm/ai/src/rag/rag.mjs.map +0 -1
- package/esm/ai/src/rag/rerank/keyword-reranker.mjs +0 -58
- package/esm/ai/src/rag/rerank/keyword-reranker.mjs.map +0 -1
- package/esm/ai/src/rag/rerank/llm-reranker.mjs +0 -85
- package/esm/ai/src/rag/rerank/llm-reranker.mjs.map +0 -1
- package/esm/ai/src/rag/retrieve.mjs +0 -68
- package/esm/ai/src/rag/retrieve.mjs.map +0 -1
- package/esm/ai/src/rag/store/cache-vector-store.mjs +0 -48
- package/esm/ai/src/rag/store/cache-vector-store.mjs.map +0 -1
- package/esm/ai/src/rag/store/pg-vector-store.mjs +0 -328
- package/esm/ai/src/rag/store/pg-vector-store.mjs.map +0 -1
- package/esm/ai/src/rag/transforms/multi-query.mjs +0 -41
- package/esm/ai/src/rag/transforms/multi-query.mjs.map +0 -1
- package/esm/ai/src/security/index.mjs +0 -5
- package/esm/ai/src/security/outbound-policy.mjs +0 -187
- package/esm/ai/src/security/outbound-policy.mjs.map +0 -1
- package/esm/ai/src/security/private-ip.mjs +0 -48
- package/esm/ai/src/security/private-ip.mjs.map +0 -1
- package/esm/ai/src/security/redact.mjs +0 -60
- package/esm/ai/src/security/redact.mjs.map +0 -1
- package/esm/ai/src/serve/serve.mjs +0 -90
- package/esm/ai/src/serve/serve.mjs.map +0 -1
- package/esm/ai/src/serve/sse.mjs +0 -25
- package/esm/ai/src/serve/sse.mjs.map +0 -1
- package/esm/ai/src/serve/stream-to-sse.mjs +0 -37
- package/esm/ai/src/serve/stream-to-sse.mjs.map +0 -1
- package/esm/ai/src/skills/catalog.mjs +0 -140
- package/esm/ai/src/skills/catalog.mjs.map +0 -1
- package/esm/ai/src/skills/index.mjs +0 -11
- package/esm/ai/src/skills/load-skill-tool.mjs +0 -65
- package/esm/ai/src/skills/load-skill-tool.mjs.map +0 -1
- package/esm/ai/src/skills/save-skill-tool.mjs +0 -65
- package/esm/ai/src/skills/save-skill-tool.mjs.map +0 -1
- package/esm/ai/src/skills/skills.mjs +0 -109
- package/esm/ai/src/skills/skills.mjs.map +0 -1
- package/esm/ai/src/skills/sources/directory-source.mjs +0 -108
- package/esm/ai/src/skills/sources/directory-source.mjs.map +0 -1
- package/esm/ai/src/skills/sources/index.mjs +0 -27
- package/esm/ai/src/skills/sources/index.mjs.map +0 -1
- package/esm/ai/src/skills/sources/parse-frontmatter.mjs +0 -46
- package/esm/ai/src/skills/sources/parse-frontmatter.mjs.map +0 -1
- package/esm/ai/src/skills/sources/store-source.mjs +0 -15
- package/esm/ai/src/skills/sources/store-source.mjs.map +0 -1
- package/esm/ai/src/skills/sources/url-source.mjs +0 -117
- package/esm/ai/src/skills/sources/url-source.mjs.map +0 -1
- package/esm/ai/src/snapshot/memory.mjs +0 -81
- package/esm/ai/src/snapshot/memory.mjs.map +0 -1
- package/esm/ai/src/snapshot/pg.mjs +0 -146
- package/esm/ai/src/snapshot/pg.mjs.map +0 -1
- package/esm/ai/src/snapshot/redis.mjs +0 -101
- package/esm/ai/src/snapshot/redis.mjs.map +0 -1
- package/esm/ai/src/speech/index.mjs +0 -3
- package/esm/ai/src/speech/speech.mjs +0 -122
- package/esm/ai/src/speech/speech.mjs.map +0 -1
- package/esm/ai/src/supervisor/as-tool.mjs +0 -74
- package/esm/ai/src/supervisor/as-tool.mjs.map +0 -1
- package/esm/ai/src/supervisor/cancellation.mjs +0 -22
- package/esm/ai/src/supervisor/cancellation.mjs.map +0 -1
- package/esm/ai/src/supervisor/decide.mjs +0 -272
- package/esm/ai/src/supervisor/decide.mjs.map +0 -1
- package/esm/ai/src/supervisor/emitter.mjs +0 -47
- package/esm/ai/src/supervisor/emitter.mjs.map +0 -1
- package/esm/ai/src/supervisor/entries.mjs +0 -206
- package/esm/ai/src/supervisor/entries.mjs.map +0 -1
- package/esm/ai/src/supervisor/execution.mjs +0 -1921
- package/esm/ai/src/supervisor/execution.mjs.map +0 -1
- package/esm/ai/src/supervisor/fan-out.mjs +0 -65
- package/esm/ai/src/supervisor/fan-out.mjs.map +0 -1
- package/esm/ai/src/supervisor/index.mjs +0 -14
- package/esm/ai/src/supervisor/router-factory.mjs +0 -141
- package/esm/ai/src/supervisor/router-factory.mjs.map +0 -1
- package/esm/ai/src/supervisor/router-prompt.mjs +0 -52
- package/esm/ai/src/supervisor/router-prompt.mjs.map +0 -1
- package/esm/ai/src/supervisor/signature.mjs +0 -89
- package/esm/ai/src/supervisor/signature.mjs.map +0 -1
- package/esm/ai/src/supervisor/snapshot.mjs +0 -69
- package/esm/ai/src/supervisor/snapshot.mjs.map +0 -1
- package/esm/ai/src/supervisor/supervisor-stream.mjs +0 -89
- package/esm/ai/src/supervisor/supervisor-stream.mjs.map +0 -1
- package/esm/ai/src/supervisor/supervisor.mjs +0 -144
- package/esm/ai/src/supervisor/supervisor.mjs.map +0 -1
- package/esm/ai/src/system-prompt/index.mjs +0 -7
- package/esm/ai/src/system-prompt/instruction.mjs +0 -57
- package/esm/ai/src/system-prompt/instruction.mjs.map +0 -1
- package/esm/ai/src/system-prompt/persona.mjs +0 -57
- package/esm/ai/src/system-prompt/persona.mjs.map +0 -1
- package/esm/ai/src/system-prompt/refined-system-prompt.mjs +0 -461
- package/esm/ai/src/system-prompt/refined-system-prompt.mjs.map +0 -1
- package/esm/ai/src/system-prompt/render-placeholders.mjs +0 -58
- package/esm/ai/src/system-prompt/render-placeholders.mjs.map +0 -1
- package/esm/ai/src/system-prompt/system-prompt.mjs +0 -286
- package/esm/ai/src/system-prompt/system-prompt.mjs.map +0 -1
- package/esm/ai/src/team/gates.mjs +0 -48
- package/esm/ai/src/team/gates.mjs.map +0 -1
- package/esm/ai/src/team/index.mjs +0 -3
- package/esm/ai/src/team/team.mjs +0 -94
- package/esm/ai/src/team/team.mjs.map +0 -1
- package/esm/ai/src/tool/executable-as-tool.mjs +0 -81
- package/esm/ai/src/tool/executable-as-tool.mjs.map +0 -1
- package/esm/ai/src/tool/index.mjs +0 -4
- package/esm/ai/src/tool/tool.mjs +0 -185
- package/esm/ai/src/tool/tool.mjs.map +0 -1
- package/esm/ai/src/transcribe/audio-input.mjs +0 -84
- package/esm/ai/src/transcribe/audio-input.mjs.map +0 -1
- package/esm/ai/src/transcribe/index.mjs +0 -4
- package/esm/ai/src/transcribe/transcribe.mjs +0 -127
- package/esm/ai/src/transcribe/transcribe.mjs.map +0 -1
- package/esm/ai/src/utils/compute-cost.mjs +0 -112
- package/esm/ai/src/utils/compute-cost.mjs.map +0 -1
- package/esm/ai/src/utils/extract-json-lenient.mjs +0 -97
- package/esm/ai/src/utils/extract-json-lenient.mjs.map +0 -1
- package/esm/ai/src/utils/extract-json-payload.mjs +0 -39
- package/esm/ai/src/utils/extract-json-payload.mjs.map +0 -1
- package/esm/ai/src/utils/generate-run-id.mjs +0 -23
- package/esm/ai/src/utils/generate-run-id.mjs.map +0 -1
- package/esm/ai/src/utils/index.mjs +0 -12
- package/esm/ai/src/utils/json-schema.mjs +0 -89
- package/esm/ai/src/utils/json-schema.mjs.map +0 -1
- package/esm/ai/src/utils/prepare-attachment-part.mjs +0 -232
- package/esm/ai/src/utils/prepare-attachment-part.mjs.map +0 -1
- package/esm/ai/src/utils/resolve-attachment.mjs +0 -74
- package/esm/ai/src/utils/resolve-attachment.mjs.map +0 -1
- package/esm/ai/src/utils/run-context.mjs +0 -89
- package/esm/ai/src/utils/run-context.mjs.map +0 -1
- package/esm/ai/src/utils/safe-json-parse.mjs +0 -22
- package/esm/ai/src/utils/safe-json-parse.mjs.map +0 -1
- package/esm/ai/src/utils/stamp-report-lineage.mjs +0 -45
- package/esm/ai/src/utils/stamp-report-lineage.mjs.map +0 -1
- package/esm/ai/src/vcr/cassette-io.mjs +0 -57
- package/esm/ai/src/vcr/cassette-io.mjs.map +0 -1
- package/esm/ai/src/vcr/errors.mjs +0 -37
- package/esm/ai/src/vcr/errors.mjs.map +0 -1
- package/esm/ai/src/vcr/hash-request.mjs +0 -118
- package/esm/ai/src/vcr/hash-request.mjs.map +0 -1
- package/esm/ai/src/vcr/index.mjs +0 -5
- package/esm/ai/src/vcr/vcr.mjs +0 -248
- package/esm/ai/src/vcr/vcr.mjs.map +0 -1
- package/esm/ai/src/workflow/as-tool.mjs +0 -49
- package/esm/ai/src/workflow/as-tool.mjs.map +0 -1
- package/esm/ai/src/workflow/cancellation.mjs +0 -44
- package/esm/ai/src/workflow/cancellation.mjs.map +0 -1
- package/esm/ai/src/workflow/emitter.mjs +0 -40
- package/esm/ai/src/workflow/emitter.mjs.map +0 -1
- package/esm/ai/src/workflow/engine.mjs +0 -363
- package/esm/ai/src/workflow/engine.mjs.map +0 -1
- package/esm/ai/src/workflow/index.mjs +0 -5
- package/esm/ai/src/workflow/retry.mjs +0 -32
- package/esm/ai/src/workflow/retry.mjs.map +0 -1
- package/esm/ai/src/workflow/router.mjs +0 -56
- package/esm/ai/src/workflow/router.mjs.map +0 -1
- package/esm/ai/src/workflow/run-scoped-emitter.mjs +0 -32
- package/esm/ai/src/workflow/run-scoped-emitter.mjs.map +0 -1
- package/esm/ai/src/workflow/signature.mjs +0 -34
- package/esm/ai/src/workflow/signature.mjs.map +0 -1
- package/esm/ai/src/workflow/snapshot.mjs +0 -77
- package/esm/ai/src/workflow/snapshot.mjs.map +0 -1
- package/esm/ai/src/workflow/state.mjs +0 -37
- package/esm/ai/src/workflow/state.mjs.map +0 -1
- package/esm/ai/src/workflow/step-runner.mjs +0 -370
- package/esm/ai/src/workflow/step-runner.mjs.map +0 -1
- package/esm/ai/src/workflow/step.mjs +0 -37
- package/esm/ai/src/workflow/step.mjs.map +0 -1
- package/esm/ai/src/workflow/workflow.mjs +0 -122
- package/esm/ai/src/workflow/workflow.mjs.map +0 -1
- package/esm/ai-openai/src/embedder.mjs +0 -4
- package/esm/ai-openai/src/image.mjs +0 -5
- package/esm/ai-openai/src/index.mjs +0 -7
- package/esm/ai-openai/src/model.mjs +0 -5
- package/esm/ai-openai/src/sdk.mjs +0 -9
- package/esm/ai-openai/src/speech.mjs +0 -5
- package/esm/ai-openai/src/transcription.mjs +0 -6
- package/esm/ai-openai/src/utils/index.mjs +0 -5
- package/esm/ai-openai/src/utils/to-openai-messages.mjs +0 -3
- package/esm/ai-openai/src/utils/to-openai-tools.mjs +0 -3
- package/esm/ai-openai/src/utils/wrap-openai-error.mjs +0 -4
- package/esm/node_modules/langfuse/lib/index.mjs +0 -1827
- package/esm/node_modules/langfuse/lib/index.mjs.map +0 -1
- package/esm/node_modules/langfuse-core/lib/index.mjs +0 -1770
- package/esm/node_modules/langfuse-core/lib/index.mjs.map +0 -1
- package/esm/node_modules/mustache/mustache.mjs +0 -587
- package/esm/node_modules/mustache/mustache.mjs.map +0 -1
- package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs +0 -180
- package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map +0 -1
- package/esm/node_modules/openai/auth/workload-identity-auth.mjs +0 -80
- package/esm/node_modules/openai/auth/workload-identity-auth.mjs.map +0 -1
- package/esm/node_modules/openai/azure.mjs +0 -82
- package/esm/node_modules/openai/azure.mjs.map +0 -1
- package/esm/node_modules/openai/client.mjs +0 -638
- package/esm/node_modules/openai/client.mjs.map +0 -1
- package/esm/node_modules/openai/core/api-promise.mjs +0 -75
- package/esm/node_modules/openai/core/api-promise.mjs.map +0 -1
- package/esm/node_modules/openai/core/error.mjs +0 -110
- package/esm/node_modules/openai/core/error.mjs.map +0 -1
- package/esm/node_modules/openai/core/pagination.mjs +0 -160
- package/esm/node_modules/openai/core/pagination.mjs.map +0 -1
- package/esm/node_modules/openai/core/resource.mjs +0 -10
- package/esm/node_modules/openai/core/resource.mjs.map +0 -1
- package/esm/node_modules/openai/core/streaming.mjs +0 -238
- package/esm/node_modules/openai/core/streaming.mjs.map +0 -1
- package/esm/node_modules/openai/index.mjs +0 -8
- package/esm/node_modules/openai/internal/decoders/line.mjs +0 -91
- package/esm/node_modules/openai/internal/decoders/line.mjs.map +0 -1
- package/esm/node_modules/openai/internal/detect-platform.mjs +0 -123
- package/esm/node_modules/openai/internal/detect-platform.mjs.map +0 -1
- package/esm/node_modules/openai/internal/errors.mjs +0 -26
- package/esm/node_modules/openai/internal/errors.mjs.map +0 -1
- package/esm/node_modules/openai/internal/headers.mjs +0 -65
- package/esm/node_modules/openai/internal/headers.mjs.map +0 -1
- package/esm/node_modules/openai/internal/parse.mjs +0 -41
- package/esm/node_modules/openai/internal/parse.mjs.map +0 -1
- package/esm/node_modules/openai/internal/qs/formats.mjs +0 -12
- package/esm/node_modules/openai/internal/qs/formats.mjs.map +0 -1
- package/esm/node_modules/openai/internal/qs/stringify.mjs +0 -179
- package/esm/node_modules/openai/internal/qs/stringify.mjs.map +0 -1
- package/esm/node_modules/openai/internal/qs/utils.mjs +0 -65
- package/esm/node_modules/openai/internal/qs/utils.mjs.map +0 -1
- package/esm/node_modules/openai/internal/request-options.mjs +0 -11
- package/esm/node_modules/openai/internal/request-options.mjs.map +0 -1
- package/esm/node_modules/openai/internal/shims.mjs +0 -77
- package/esm/node_modules/openai/internal/shims.mjs.map +0 -1
- package/esm/node_modules/openai/internal/to-file.mjs +0 -63
- package/esm/node_modules/openai/internal/to-file.mjs.map +0 -1
- package/esm/node_modules/openai/internal/tslib.mjs +0 -16
- package/esm/node_modules/openai/internal/tslib.mjs.map +0 -1
- package/esm/node_modules/openai/internal/uploads.mjs +0 -94
- package/esm/node_modules/openai/internal/uploads.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/base64.mjs +0 -22
- package/esm/node_modules/openai/internal/utils/base64.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/bytes.mjs +0 -26
- package/esm/node_modules/openai/internal/utils/bytes.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/env.mjs +0 -16
- package/esm/node_modules/openai/internal/utils/env.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/log.mjs +0 -58
- package/esm/node_modules/openai/internal/utils/log.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/path.mjs +0 -62
- package/esm/node_modules/openai/internal/utils/path.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/query.mjs +0 -10
- package/esm/node_modules/openai/internal/utils/query.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/sleep.mjs +0 -6
- package/esm/node_modules/openai/internal/utils/sleep.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/uuid.mjs +0 -18
- package/esm/node_modules/openai/internal/utils/uuid.mjs.map +0 -1
- package/esm/node_modules/openai/internal/utils/values.mjs +0 -41
- package/esm/node_modules/openai/internal/utils/values.mjs.map +0 -1
- package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +0 -247
- package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map +0 -1
- package/esm/node_modules/openai/lib/AssistantStream.mjs +0 -472
- package/esm/node_modules/openai/lib/AssistantStream.mjs.map +0 -1
- package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs +0 -26
- package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs.map +0 -1
- package/esm/node_modules/openai/lib/ChatCompletionStream.mjs +0 -423
- package/esm/node_modules/openai/lib/ChatCompletionStream.mjs.map +0 -1
- package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +0 -26
- package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map +0 -1
- package/esm/node_modules/openai/lib/EventStream.mjs +0 -163
- package/esm/node_modules/openai/lib/EventStream.mjs.map +0 -1
- package/esm/node_modules/openai/lib/ResponsesParser.mjs +0 -94
- package/esm/node_modules/openai/lib/ResponsesParser.mjs.map +0 -1
- package/esm/node_modules/openai/lib/RunnableFunction.mjs +0 -8
- package/esm/node_modules/openai/lib/RunnableFunction.mjs.map +0 -1
- package/esm/node_modules/openai/lib/Util.mjs +0 -19
- package/esm/node_modules/openai/lib/Util.mjs.map +0 -1
- package/esm/node_modules/openai/lib/chatCompletionUtils.mjs +0 -11
- package/esm/node_modules/openai/lib/chatCompletionUtils.mjs.map +0 -1
- package/esm/node_modules/openai/lib/parser.mjs +0 -88
- package/esm/node_modules/openai/lib/parser.mjs.map +0 -1
- package/esm/node_modules/openai/lib/responses/ResponseStream.mjs +0 -231
- package/esm/node_modules/openai/lib/responses/ResponseStream.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/admin.mjs +0 -15
- package/esm/node_modules/openai/resources/admin/admin.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs +0 -81
- package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs +0 -31
- package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/certificates.mjs +0 -153
- package/esm/node_modules/openai/resources/admin/organization/certificates.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs +0 -42
- package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs +0 -106
- package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs +0 -88
- package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs +0 -88
- package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/invites.mjs +0 -83
- package/esm/node_modules/openai/resources/admin/organization/invites.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/organization.mjs +0 -45
- package/esm/node_modules/openai/resources/admin/organization/organization.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs +0 -72
- package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs +0 -78
- package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs +0 -46
- package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +0 -95
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +0 -91
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +0 -45
- package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +0 -63
- package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs +0 -137
- package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +0 -51
- package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs +0 -108
- package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs +0 -112
- package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +0 -106
- package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs +0 -91
- package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs +0 -118
- package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/roles.mjs +0 -96
- package/esm/node_modules/openai/resources/admin/organization/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs +0 -97
- package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/usage.mjs +0 -207
- package/esm/node_modules/openai/resources/admin/organization/usage.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs +0 -88
- package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs.map +0 -1
- package/esm/node_modules/openai/resources/admin/organization/users/users.mjs +0 -82
- package/esm/node_modules/openai/resources/admin/organization/users/users.mjs.map +0 -1
- package/esm/node_modules/openai/resources/audio/audio.mjs +0 -21
- package/esm/node_modules/openai/resources/audio/audio.mjs.map +0 -1
- package/esm/node_modules/openai/resources/audio/speech.mjs +0 -39
- package/esm/node_modules/openai/resources/audio/speech.mjs.map +0 -1
- package/esm/node_modules/openai/resources/audio/transcriptions.mjs +0 -22
- package/esm/node_modules/openai/resources/audio/transcriptions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/audio/translations.mjs +0 -21
- package/esm/node_modules/openai/resources/audio/translations.mjs.map +0 -1
- package/esm/node_modules/openai/resources/batches.mjs +0 -54
- package/esm/node_modules/openai/resources/batches.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/assistants.mjs +0 -78
- package/esm/node_modules/openai/resources/beta/assistants.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/beta.mjs +0 -24
- package/esm/node_modules/openai/resources/beta/beta.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs +0 -18
- package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs +0 -49
- package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs +0 -85
- package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs +0 -21
- package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs +0 -33
- package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +0 -33
- package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/threads/messages.mjs +0 -83
- package/esm/node_modules/openai/resources/beta/threads/messages.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs +0 -183
- package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs +0 -45
- package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs.map +0 -1
- package/esm/node_modules/openai/resources/beta/threads/threads.mjs +0 -101
- package/esm/node_modules/openai/resources/beta/threads/threads.mjs.map +0 -1
- package/esm/node_modules/openai/resources/chat/chat.mjs +0 -15
- package/esm/node_modules/openai/resources/chat/chat.mjs.map +0 -1
- package/esm/node_modules/openai/resources/chat/completions/completions.mjs +0 -123
- package/esm/node_modules/openai/resources/chat/completions/completions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/chat/completions/index.mjs +0 -7
- package/esm/node_modules/openai/resources/chat/completions/messages.mjs +0 -35
- package/esm/node_modules/openai/resources/chat/completions/messages.mjs.map +0 -1
- package/esm/node_modules/openai/resources/chat/index.mjs +0 -5
- package/esm/node_modules/openai/resources/completions.mjs +0 -20
- package/esm/node_modules/openai/resources/completions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/containers/containers.mjs +0 -57
- package/esm/node_modules/openai/resources/containers/containers.mjs.map +0 -1
- package/esm/node_modules/openai/resources/containers/files/content.mjs +0 -23
- package/esm/node_modules/openai/resources/containers/files/content.mjs.map +0 -1
- package/esm/node_modules/openai/resources/containers/files/files.mjs +0 -63
- package/esm/node_modules/openai/resources/containers/files/files.mjs.map +0 -1
- package/esm/node_modules/openai/resources/conversations/conversations.mjs +0 -57
- package/esm/node_modules/openai/resources/conversations/conversations.mjs.map +0 -1
- package/esm/node_modules/openai/resources/conversations/items.mjs +0 -57
- package/esm/node_modules/openai/resources/conversations/items.mjs.map +0 -1
- package/esm/node_modules/openai/resources/embeddings.mjs +0 -48
- package/esm/node_modules/openai/resources/embeddings.mjs.map +0 -1
- package/esm/node_modules/openai/resources/evals/evals.mjs +0 -73
- package/esm/node_modules/openai/resources/evals/evals.mjs.map +0 -1
- package/esm/node_modules/openai/resources/evals/runs/output-items.mjs +0 -35
- package/esm/node_modules/openai/resources/evals/runs/output-items.mjs.map +0 -1
- package/esm/node_modules/openai/resources/evals/runs/runs.mjs +0 -72
- package/esm/node_modules/openai/resources/evals/runs/runs.mjs.map +0 -1
- package/esm/node_modules/openai/resources/files.mjs +0 -111
- package/esm/node_modules/openai/resources/files.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +0 -15
- package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +0 -60
- package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +0 -15
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +0 -102
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +0 -24
- package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +0 -34
- package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +0 -148
- package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map +0 -1
- package/esm/node_modules/openai/resources/fine-tuning/methods.mjs +0 -8
- package/esm/node_modules/openai/resources/fine-tuning/methods.mjs.map +0 -1
- package/esm/node_modules/openai/resources/graders/grader-models.mjs +0 -8
- package/esm/node_modules/openai/resources/graders/grader-models.mjs.map +0 -1
- package/esm/node_modules/openai/resources/graders/graders.mjs +0 -15
- package/esm/node_modules/openai/resources/graders/graders.mjs.map +0 -1
- package/esm/node_modules/openai/resources/images.mjs +0 -46
- package/esm/node_modules/openai/resources/images.mjs.map +0 -1
- package/esm/node_modules/openai/resources/index.mjs +0 -27
- package/esm/node_modules/openai/resources/models.mjs +0 -44
- package/esm/node_modules/openai/resources/models.mjs.map +0 -1
- package/esm/node_modules/openai/resources/moderations.mjs +0 -23
- package/esm/node_modules/openai/resources/moderations.mjs.map +0 -1
- package/esm/node_modules/openai/resources/realtime/calls.mjs +0 -79
- package/esm/node_modules/openai/resources/realtime/calls.mjs.map +0 -1
- package/esm/node_modules/openai/resources/realtime/client-secrets.mjs +0 -39
- package/esm/node_modules/openai/resources/realtime/client-secrets.mjs.map +0 -1
- package/esm/node_modules/openai/resources/realtime/realtime.mjs +0 -18
- package/esm/node_modules/openai/resources/realtime/realtime.mjs.map +0 -1
- package/esm/node_modules/openai/resources/responses/input-items.mjs +0 -31
- package/esm/node_modules/openai/resources/responses/input-items.mjs.map +0 -1
- package/esm/node_modules/openai/resources/responses/input-tokens.mjs +0 -27
- package/esm/node_modules/openai/resources/responses/input-tokens.mjs.map +0 -1
- package/esm/node_modules/openai/resources/responses/responses.mjs +0 -110
- package/esm/node_modules/openai/resources/responses/responses.mjs.map +0 -1
- package/esm/node_modules/openai/resources/skills/content.mjs +0 -22
- package/esm/node_modules/openai/resources/skills/content.mjs.map +0 -1
- package/esm/node_modules/openai/resources/skills/skills.mjs +0 -69
- package/esm/node_modules/openai/resources/skills/skills.mjs.map +0 -1
- package/esm/node_modules/openai/resources/skills/versions/content.mjs +0 -23
- package/esm/node_modules/openai/resources/skills/versions/content.mjs.map +0 -1
- package/esm/node_modules/openai/resources/skills/versions/versions.mjs +0 -58
- package/esm/node_modules/openai/resources/skills/versions/versions.mjs.map +0 -1
- package/esm/node_modules/openai/resources/uploads/parts.mjs +0 -34
- package/esm/node_modules/openai/resources/uploads/parts.mjs.map +0 -1
- package/esm/node_modules/openai/resources/uploads/uploads.mjs +0 -84
- package/esm/node_modules/openai/resources/uploads/uploads.mjs.map +0 -1
- package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs +0 -126
- package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs.map +0 -1
- package/esm/node_modules/openai/resources/vector-stores/files.mjs +0 -147
- package/esm/node_modules/openai/resources/vector-stores/files.mjs.map +0 -1
- package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs +0 -87
- package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs.map +0 -1
- package/esm/node_modules/openai/resources/videos.mjs +0 -115
- package/esm/node_modules/openai/resources/videos.mjs.map +0 -1
- package/esm/node_modules/openai/resources/webhooks/index.mjs +0 -3
- package/esm/node_modules/openai/resources/webhooks/webhooks.mjs +0 -69
- package/esm/node_modules/openai/resources/webhooks/webhooks.mjs.map +0 -1
- package/esm/node_modules/openai/resources/webhooks.mjs +0 -4
- package/esm/node_modules/openai/streaming.mjs +0 -3
- package/esm/node_modules/openai/version.mjs +0 -6
- package/esm/node_modules/openai/version.mjs.map +0 -1
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import { deriveMemoryId } from "./derive-id.mjs";
|
|
2
|
-
|
|
3
|
-
//#region ../@warlock.js/ai/src/memory/procedural-memory.ts
|
|
4
|
-
/**
|
|
5
|
-
* Extra candidates pulled from `similar()` before re-ranking by the
|
|
6
|
-
* reinforcement-blended score and slicing to `k` — reinforcement can
|
|
7
|
-
* promote a well-worn procedure past a slightly-closer one-off, which the
|
|
8
|
-
* raw top-`k` by similarity would miss.
|
|
9
|
-
*/
|
|
10
|
-
const RECALL_OVERSCAN = 5;
|
|
11
|
-
/**
|
|
12
|
-
* Procedural recall tier (memory core M2).
|
|
13
|
-
*
|
|
14
|
-
* Holds durable *how-to* knowledge — learned procedures, policies, and
|
|
15
|
-
* playbooks — and retrieves the ones relevant to a query, **blended with
|
|
16
|
-
* reinforcement** so procedures that have proven themselves (remembered /
|
|
17
|
-
* re-affirmed more often) outrank one-offs at equal similarity. That
|
|
18
|
-
* reinforcement weighting is the difference from the semantic tier (which
|
|
19
|
-
* treats every fact equally): procedural memory gets *stronger with use*.
|
|
20
|
-
*
|
|
21
|
-
* Reinforcement is explicit and side-effect-free on read: re-remembering
|
|
22
|
-
* a procedure (same id, or same text → same derived id) increments its
|
|
23
|
-
* `uses`, so a caller strengthens a procedure by remembering it again
|
|
24
|
-
* after a successful application. Recall never mutates.
|
|
25
|
-
*
|
|
26
|
-
* Like the other vector tiers it delegates similarity to the
|
|
27
|
-
* `@warlock.js/cache` driver's `similar()`. The blended `score` stays in
|
|
28
|
-
* `[0, 1]` so procedural hits merge and sort alongside the other tiers.
|
|
29
|
-
*
|
|
30
|
-
* Internal to the `memory()` factory — never exported on the package
|
|
31
|
-
* surface.
|
|
32
|
-
*/
|
|
33
|
-
var ProceduralMemory = class {
|
|
34
|
-
constructor(embedder, store, namespace, reinforcementWeight) {
|
|
35
|
-
this.embedder = embedder;
|
|
36
|
-
this.store = store;
|
|
37
|
-
this.namespace = namespace;
|
|
38
|
-
this.reinforcementWeight = reinforcementWeight;
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Embed the procedure text and index it, incrementing its `uses` when
|
|
42
|
-
* it already exists (reinforcement) or seeding it at `1` when new.
|
|
43
|
-
* Metadata on a reinforcing write wins; an omitted metadata keeps the
|
|
44
|
-
* prior value rather than wiping it.
|
|
45
|
-
*/
|
|
46
|
-
async remember(item) {
|
|
47
|
-
const id = item.id ?? deriveMemoryId(item.text);
|
|
48
|
-
const { vector } = await this.embedder.embed(item.text);
|
|
49
|
-
const existing = await this.store.get(this.keyFor(id));
|
|
50
|
-
const uses = (existing?.uses ?? 0) + 1;
|
|
51
|
-
const value = {
|
|
52
|
-
id,
|
|
53
|
-
text: item.text,
|
|
54
|
-
uses,
|
|
55
|
-
metadata: item.metadata ?? existing?.metadata
|
|
56
|
-
};
|
|
57
|
-
await this.store.set(this.keyFor(id), value, { vector });
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Embed `query`, pull the nearest procedures clearing the similarity
|
|
61
|
-
* `threshold`, then re-rank each by a reinforcement-blended score and
|
|
62
|
-
* return the top `k`. The similarity floor still gates relevance;
|
|
63
|
-
* reinforcement only reorders procedures that already cleared it.
|
|
64
|
-
*/
|
|
65
|
-
async recall(query, k, threshold) {
|
|
66
|
-
const { vector } = await this.embedder.embed(query);
|
|
67
|
-
const hits = await this.store.similar(vector, {
|
|
68
|
-
topK: Math.max(k * RECALL_OVERSCAN, k),
|
|
69
|
-
threshold
|
|
70
|
-
});
|
|
71
|
-
const prefix = `${this.namespace}.`;
|
|
72
|
-
return hits.filter((hit) => hit.key.startsWith(prefix)).map((hit) => ({
|
|
73
|
-
id: hit.value.id,
|
|
74
|
-
text: hit.value.text,
|
|
75
|
-
tier: "procedural",
|
|
76
|
-
score: this.blend(hit.score, hit.value.uses),
|
|
77
|
-
metadata: hit.value.metadata
|
|
78
|
-
})).sort((first, second) => second.score - first.score).slice(0, k);
|
|
79
|
-
}
|
|
80
|
-
/** Drop every procedure written under this instance's namespace. */
|
|
81
|
-
async clear() {
|
|
82
|
-
await this.store.removeNamespace(this.namespace);
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Combine raw similarity with a saturating reinforcement proxy:
|
|
86
|
-
* `(1 - w)·similarity + w·(uses / (uses + 1))`. A first-time procedure
|
|
87
|
-
* contributes `0.5`; each reinforcement nudges it toward `1` with
|
|
88
|
-
* diminishing returns. With `reinforcementWeight` 0 the score is pure
|
|
89
|
-
* similarity.
|
|
90
|
-
*/
|
|
91
|
-
blend(similarity, uses) {
|
|
92
|
-
const reinforcement = uses / (uses + 1);
|
|
93
|
-
return (1 - this.reinforcementWeight) * similarity + this.reinforcementWeight * reinforcement;
|
|
94
|
-
}
|
|
95
|
-
/** Namespaced key for an entry — dot separator, matching `similar()` keys. */
|
|
96
|
-
keyFor(id) {
|
|
97
|
-
return `${this.namespace}.${id}`;
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
//#endregion
|
|
102
|
-
export { ProceduralMemory };
|
|
103
|
-
//# sourceMappingURL=procedural-memory.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"procedural-memory.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/memory/procedural-memory.ts"],"sourcesContent":["import type { CacheDriver, CacheSimilarHit } from \"@warlock.js/cache\";\nimport type { EmbedderContract } from \"../contracts/embedder.contract\";\nimport type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * Shape persisted per procedure. `uses` is the reinforcement counter —\n * how many times the procedure has been remembered/re-affirmed — and\n * feeds the reinforcement half of the blended recall score. The vector\n * lives in the driver's index, so it is not duplicated here.\n */\ntype StoredProcedure = {\n id: string;\n text: string;\n uses: number;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Extra candidates pulled from `similar()` before re-ranking by the\n * reinforcement-blended score and slicing to `k` — reinforcement can\n * promote a well-worn procedure past a slightly-closer one-off, which the\n * raw top-`k` by similarity would miss.\n */\nconst RECALL_OVERSCAN = 5;\n\n/**\n * Procedural recall tier (memory core M2).\n *\n * Holds durable *how-to* knowledge — learned procedures, policies, and\n * playbooks — and retrieves the ones relevant to a query, **blended with\n * reinforcement** so procedures that have proven themselves (remembered /\n * re-affirmed more often) outrank one-offs at equal similarity. That\n * reinforcement weighting is the difference from the semantic tier (which\n * treats every fact equally): procedural memory gets *stronger with use*.\n *\n * Reinforcement is explicit and side-effect-free on read: re-remembering\n * a procedure (same id, or same text → same derived id) increments its\n * `uses`, so a caller strengthens a procedure by remembering it again\n * after a successful application. Recall never mutates.\n *\n * Like the other vector tiers it delegates similarity to the\n * `@warlock.js/cache` driver's `similar()`. The blended `score` stays in\n * `[0, 1]` so procedural hits merge and sort alongside the other tiers.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class ProceduralMemory {\n public constructor(\n private readonly embedder: EmbedderContract,\n private readonly store: CacheDriver<any, any>,\n private readonly namespace: string,\n private readonly reinforcementWeight: number,\n ) {}\n\n /**\n * Embed the procedure text and index it, incrementing its `uses` when\n * it already exists (reinforcement) or seeding it at `1` when new.\n * Metadata on a reinforcing write wins; an omitted metadata keeps the\n * prior value rather than wiping it.\n */\n public async remember(item: MemoryItem): Promise<void> {\n const id = item.id ?? deriveMemoryId(item.text);\n const { vector } = await this.embedder.embed(item.text);\n\n const existing = await this.store.get<StoredProcedure>(this.keyFor(id));\n const uses = (existing?.uses ?? 0) + 1;\n\n const value: StoredProcedure = {\n id,\n text: item.text,\n uses,\n metadata: item.metadata ?? existing?.metadata,\n };\n\n await this.store.set(this.keyFor(id), value, { vector });\n }\n\n /**\n * Embed `query`, pull the nearest procedures clearing the similarity\n * `threshold`, then re-rank each by a reinforcement-blended score and\n * return the top `k`. The similarity floor still gates relevance;\n * reinforcement only reorders procedures that already cleared it.\n */\n public async recall(\n query: string,\n k: number,\n threshold: number,\n ): Promise<RecalledMemory[]> {\n const { vector } = await this.embedder.embed(query);\n\n const hits = await this.store.similar<StoredProcedure>(vector, {\n topK: Math.max(k * RECALL_OVERSCAN, k),\n threshold,\n });\n\n const prefix = `${this.namespace}.`;\n\n return hits\n .filter((hit: CacheSimilarHit<StoredProcedure>) =>\n hit.key.startsWith(prefix),\n )\n .map((hit: CacheSimilarHit<StoredProcedure>) => ({\n id: hit.value.id,\n text: hit.value.text,\n tier: \"procedural\" as const,\n score: this.blend(hit.score, hit.value.uses),\n metadata: hit.value.metadata,\n }))\n .sort((first, second) => second.score - first.score)\n .slice(0, k);\n }\n\n /** Drop every procedure written under this instance's namespace. */\n public async clear(): Promise<void> {\n await this.store.removeNamespace(this.namespace);\n }\n\n /**\n * Combine raw similarity with a saturating reinforcement proxy:\n * `(1 - w)·similarity + w·(uses / (uses + 1))`. A first-time procedure\n * contributes `0.5`; each reinforcement nudges it toward `1` with\n * diminishing returns. With `reinforcementWeight` 0 the score is pure\n * similarity.\n */\n private blend(similarity: number, uses: number): number {\n const reinforcement = uses / (uses + 1);\n\n return (\n (1 - this.reinforcementWeight) * similarity +\n this.reinforcementWeight * reinforcement\n );\n }\n\n /** Namespaced key for an entry — dot separator, matching `similar()` keys. */\n private keyFor(id: string): string {\n return `${this.namespace}.${id}`;\n }\n}\n"],"mappings":";;;;;;;;;AA2BA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;AAwBxB,IAAa,mBAAb,MAA8B;CAC5B,AAAO,YACL,AAAiB,UACjB,AAAiB,OACjB,AAAiB,WACjB,AAAiB,qBACjB;EAJiB;EACA;EACA;EACA;CAChB;;;;;;;CAQH,MAAa,SAAS,MAAiC;EACrD,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAC9C,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK,IAAI;EAEtD,MAAM,WAAW,MAAM,KAAK,MAAM,IAAqB,KAAK,OAAO,EAAE,CAAC;EACtE,MAAM,QAAQ,UAAU,QAAQ,KAAK;EAErC,MAAM,QAAyB;GAC7B;GACA,MAAM,KAAK;GACX;GACA,UAAU,KAAK,YAAY,UAAU;EACvC;EAEA,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,CAAC;CACzD;;;;;;;CAQA,MAAa,OACX,OACA,GACA,WAC2B;EAC3B,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK;EAElD,MAAM,OAAO,MAAM,KAAK,MAAM,QAAyB,QAAQ;GAC7D,MAAM,KAAK,IAAI,IAAI,iBAAiB,CAAC;GACrC;EACF,CAAC;EAED,MAAM,SAAS,GAAG,KAAK,UAAU;EAEjC,OAAO,KACJ,QAAQ,QACP,IAAI,IAAI,WAAW,MAAM,CAC3B,CAAC,CACA,KAAK,SAA2C;GAC/C,IAAI,IAAI,MAAM;GACd,MAAM,IAAI,MAAM;GAChB,MAAM;GACN,OAAO,KAAK,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI;GAC3C,UAAU,IAAI,MAAM;EACtB,EAAE,CAAC,CACF,MAAM,OAAO,WAAW,OAAO,QAAQ,MAAM,KAAK,CAAC,CACnD,MAAM,GAAG,CAAC;CACf;;CAGA,MAAa,QAAuB;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,SAAS;CACjD;;;;;;;;CASA,AAAQ,MAAM,YAAoB,MAAsB;EACtD,MAAM,gBAAgB,QAAQ,OAAO;EAErC,QACG,IAAI,KAAK,uBAAuB,aACjC,KAAK,sBAAsB;CAE/B;;CAGA,AAAQ,OAAO,IAAoB;EACjC,OAAO,GAAG,KAAK,UAAU,GAAG;CAC9B;AACF"}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import { deriveMemoryId } from "./derive-id.mjs";
|
|
2
|
-
|
|
3
|
-
//#region ../@warlock.js/ai/src/memory/semantic-memory.ts
|
|
4
|
-
/**
|
|
5
|
-
* Semantic recall tier (memory core M1).
|
|
6
|
-
*
|
|
7
|
-
* Owns: embedding remembered text, writing it to a `@warlock.js/cache`
|
|
8
|
-
* driver with `set({ vector })`, and retrieving by cosine similarity via
|
|
9
|
-
* the driver's `similar()`. Does NOT own: the similarity algorithm or
|
|
10
|
-
* the ANN index — those belong to the cache driver. This mirrors the
|
|
11
|
-
* delegation model of `middleware/builtins/semantic-cache.ts`: memory is
|
|
12
|
-
* embedding-agnostic and store-agnostic, gluing an {@link EmbedderContract}
|
|
13
|
-
* to a {@link CacheDriver}.
|
|
14
|
-
*
|
|
15
|
-
* The driver may be shared across memory instances, so every key carries
|
|
16
|
-
* the configured `namespace` and recall filters hits to that prefix —
|
|
17
|
-
* foreign entries indexed by another instance never leak into a query.
|
|
18
|
-
*
|
|
19
|
-
* Internal to the `memory()` factory — never exported on the package
|
|
20
|
-
* surface.
|
|
21
|
-
*/
|
|
22
|
-
var SemanticMemory = class {
|
|
23
|
-
constructor(embedder, store, namespace) {
|
|
24
|
-
this.embedder = embedder;
|
|
25
|
-
this.store = store;
|
|
26
|
-
this.namespace = namespace;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Embed the item's text and index it under a namespaced, id-derived
|
|
30
|
-
* key. Re-remembering the same id overwrites the prior vector +
|
|
31
|
-
* value (the driver upserts by key).
|
|
32
|
-
*/
|
|
33
|
-
async remember(item) {
|
|
34
|
-
const id = item.id ?? deriveMemoryId(item.text);
|
|
35
|
-
const { vector } = await this.embedder.embed(item.text);
|
|
36
|
-
const value = {
|
|
37
|
-
id,
|
|
38
|
-
text: item.text,
|
|
39
|
-
metadata: item.metadata
|
|
40
|
-
};
|
|
41
|
-
await this.store.set(this.keyFor(id), value, { vector });
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Embed `query`, ask the driver for the `k` nearest entries clearing
|
|
45
|
-
* `threshold`, and return those within this instance's namespace as
|
|
46
|
-
* scored {@link RecalledMemory}. Hits indexed under a different
|
|
47
|
-
* namespace (a shared driver) are filtered out.
|
|
48
|
-
*/
|
|
49
|
-
async recall(query, k, threshold) {
|
|
50
|
-
const { vector } = await this.embedder.embed(query);
|
|
51
|
-
const hits = await this.store.similar(vector, {
|
|
52
|
-
topK: k,
|
|
53
|
-
threshold
|
|
54
|
-
});
|
|
55
|
-
const prefix = `${this.namespace}.`;
|
|
56
|
-
return hits.filter((hit) => hit.key.startsWith(prefix)).map((hit) => ({
|
|
57
|
-
id: hit.value.id,
|
|
58
|
-
text: hit.value.text,
|
|
59
|
-
tier: "semantic",
|
|
60
|
-
score: hit.score,
|
|
61
|
-
metadata: hit.value.metadata
|
|
62
|
-
}));
|
|
63
|
-
}
|
|
64
|
-
/** Drop every semantic entry written under this instance's namespace. */
|
|
65
|
-
async clear() {
|
|
66
|
-
await this.store.removeNamespace(this.namespace);
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Namespaced key for an entry. The cache's `parseKey` normalizes `:`
|
|
70
|
-
* to `.`, so a dot separator keeps the prefix used here aligned with
|
|
71
|
-
* the `hit.key` the driver returns from `similar()`.
|
|
72
|
-
*/
|
|
73
|
-
keyFor(id) {
|
|
74
|
-
return `${this.namespace}.${id}`;
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
//#endregion
|
|
79
|
-
export { SemanticMemory };
|
|
80
|
-
//# sourceMappingURL=semantic-memory.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"semantic-memory.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/memory/semantic-memory.ts"],"sourcesContent":["import type { CacheDriver, CacheSimilarHit } from \"@warlock.js/cache\";\nimport type { EmbedderContract } from \"../contracts/embedder.contract\";\nimport type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * Shape persisted per semantic memory in the cache driver. The vector\n * itself is stored by the driver's own index (passed via\n * `set({ vector })`), so it is not duplicated in the value.\n */\ntype StoredMemory = {\n id: string;\n text: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Semantic recall tier (memory core M1).\n *\n * Owns: embedding remembered text, writing it to a `@warlock.js/cache`\n * driver with `set({ vector })`, and retrieving by cosine similarity via\n * the driver's `similar()`. Does NOT own: the similarity algorithm or\n * the ANN index — those belong to the cache driver. This mirrors the\n * delegation model of `middleware/builtins/semantic-cache.ts`: memory is\n * embedding-agnostic and store-agnostic, gluing an {@link EmbedderContract}\n * to a {@link CacheDriver}.\n *\n * The driver may be shared across memory instances, so every key carries\n * the configured `namespace` and recall filters hits to that prefix —\n * foreign entries indexed by another instance never leak into a query.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class SemanticMemory {\n public constructor(\n private readonly embedder: EmbedderContract,\n private readonly store: CacheDriver<any, any>,\n private readonly namespace: string,\n ) {}\n\n /**\n * Embed the item's text and index it under a namespaced, id-derived\n * key. Re-remembering the same id overwrites the prior vector +\n * value (the driver upserts by key).\n */\n public async remember(item: MemoryItem): Promise<void> {\n const id = item.id ?? deriveMemoryId(item.text);\n const { vector } = await this.embedder.embed(item.text);\n\n const value: StoredMemory = {\n id,\n text: item.text,\n metadata: item.metadata,\n };\n\n await this.store.set(this.keyFor(id), value, { vector });\n }\n\n /**\n * Embed `query`, ask the driver for the `k` nearest entries clearing\n * `threshold`, and return those within this instance's namespace as\n * scored {@link RecalledMemory}. Hits indexed under a different\n * namespace (a shared driver) are filtered out.\n */\n public async recall(\n query: string,\n k: number,\n threshold: number,\n ): Promise<RecalledMemory[]> {\n const { vector } = await this.embedder.embed(query);\n\n const hits = await this.store.similar<StoredMemory>(vector, {\n topK: k,\n threshold,\n });\n\n const prefix = `${this.namespace}.`;\n\n return hits\n .filter((hit: CacheSimilarHit<StoredMemory>) =>\n hit.key.startsWith(prefix),\n )\n .map((hit: CacheSimilarHit<StoredMemory>) => ({\n id: hit.value.id,\n text: hit.value.text,\n tier: \"semantic\" as const,\n score: hit.score,\n metadata: hit.value.metadata,\n }));\n }\n\n /** Drop every semantic entry written under this instance's namespace. */\n public async clear(): Promise<void> {\n await this.store.removeNamespace(this.namespace);\n }\n\n /**\n * Namespaced key for an entry. The cache's `parseKey` normalizes `:`\n * to `.`, so a dot separator keeps the prefix used here aligned with\n * the `hit.key` the driver returns from `similar()`.\n */\n private keyFor(id: string): string {\n return `${this.namespace}.${id}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,iBAAb,MAA4B;CAC1B,AAAO,YACL,AAAiB,UACjB,AAAiB,OACjB,AAAiB,WACjB;EAHiB;EACA;EACA;CAChB;;;;;;CAOH,MAAa,SAAS,MAAiC;EACrD,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAC9C,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK,IAAI;EAEtD,MAAM,QAAsB;GAC1B;GACA,MAAM,KAAK;GACX,UAAU,KAAK;EACjB;EAEA,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,CAAC;CACzD;;;;;;;CAQA,MAAa,OACX,OACA,GACA,WAC2B;EAC3B,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK;EAElD,MAAM,OAAO,MAAM,KAAK,MAAM,QAAsB,QAAQ;GAC1D,MAAM;GACN;EACF,CAAC;EAED,MAAM,SAAS,GAAG,KAAK,UAAU;EAEjC,OAAO,KACJ,QAAQ,QACP,IAAI,IAAI,WAAW,MAAM,CAC3B,CAAC,CACA,KAAK,SAAwC;GAC5C,IAAI,IAAI,MAAM;GACd,MAAM,IAAI,MAAM;GAChB,MAAM;GACN,OAAO,IAAI;GACX,UAAU,IAAI,MAAM;EACtB,EAAE;CACN;;CAGA,MAAa,QAAuB;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,SAAS;CACjD;;;;;;CAOA,AAAQ,OAAO,IAAoB;EACjC,OAAO,GAAG,KAAK,UAAU,GAAG;CAC9B;AACF"}
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { deriveMemoryId } from "./derive-id.mjs";
|
|
2
|
-
|
|
3
|
-
//#region ../@warlock.js/ai/src/memory/working-memory.ts
|
|
4
|
-
/**
|
|
5
|
-
* In-run working memory — the volatile scratch tier (memory core M1).
|
|
6
|
-
*
|
|
7
|
-
* Owns: an insertion-ordered buffer of remembered items keyed by id,
|
|
8
|
-
* with overwrite-in-place on a repeated id. Does NOT own: durability,
|
|
9
|
-
* cross-process sharing, embeddings, or similarity — working memory is
|
|
10
|
-
* a plain in-process buffer the orchestrator threads across the turns of
|
|
11
|
-
* a single run.
|
|
12
|
-
*
|
|
13
|
-
* Recall here is not semantic: with no vector index, "relevant" reduces
|
|
14
|
-
* to "recent." `recall()` returns the most-recently-remembered items
|
|
15
|
-
* first, each scored on a `[0, 1]` recency proxy so a caller can merge
|
|
16
|
-
* working hits with semantic hits and sort on one `score` field.
|
|
17
|
-
*
|
|
18
|
-
* Internal to the `memory()` factory — never exported on the package
|
|
19
|
-
* surface.
|
|
20
|
-
*/
|
|
21
|
-
var WorkingMemory = class {
|
|
22
|
-
constructor() {
|
|
23
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Append an item to the buffer (or overwrite the entry sharing its
|
|
27
|
-
* id). Re-inserting an existing id keeps its original position; delete
|
|
28
|
-
* + set would move it to the end and lie about recency, so the value
|
|
29
|
-
* is updated in place.
|
|
30
|
-
*/
|
|
31
|
-
remember(item) {
|
|
32
|
-
const id = item.id ?? deriveMemoryId(item.text);
|
|
33
|
-
this.entries.set(id, {
|
|
34
|
-
text: item.text,
|
|
35
|
-
metadata: item.metadata
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Return up to `k` most-recently-remembered items, newest first. The
|
|
40
|
-
* `score` is a linear recency proxy: the newest item scores `1`, the
|
|
41
|
-
* oldest of the returned slice trends toward `0`. Working memory
|
|
42
|
-
* ignores any similarity threshold — it has no vector to compare.
|
|
43
|
-
*/
|
|
44
|
-
recall(k) {
|
|
45
|
-
const slice = [...this.entries.entries()].reverse().slice(0, Math.max(0, k));
|
|
46
|
-
return slice.map(([id, entry], index) => ({
|
|
47
|
-
id,
|
|
48
|
-
text: entry.text,
|
|
49
|
-
tier: "working",
|
|
50
|
-
score: slice.length <= 1 ? 1 : 1 - index / slice.length,
|
|
51
|
-
metadata: entry.metadata
|
|
52
|
-
}));
|
|
53
|
-
}
|
|
54
|
-
/** Drop every working-tier entry. */
|
|
55
|
-
clear() {
|
|
56
|
-
this.entries.clear();
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
//#endregion
|
|
61
|
-
export { WorkingMemory };
|
|
62
|
-
//# sourceMappingURL=working-memory.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"working-memory.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/memory/working-memory.ts"],"sourcesContent":["import type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * In-run working memory — the volatile scratch tier (memory core M1).\n *\n * Owns: an insertion-ordered buffer of remembered items keyed by id,\n * with overwrite-in-place on a repeated id. Does NOT own: durability,\n * cross-process sharing, embeddings, or similarity — working memory is\n * a plain in-process buffer the orchestrator threads across the turns of\n * a single run.\n *\n * Recall here is not semantic: with no vector index, \"relevant\" reduces\n * to \"recent.\" `recall()` returns the most-recently-remembered items\n * first, each scored on a `[0, 1]` recency proxy so a caller can merge\n * working hits with semantic hits and sort on one `score` field.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class WorkingMemory {\n /**\n * Id → text/metadata. A `Map` preserves insertion order, so iteration\n * yields oldest-first; recall reverses it for most-recent-first.\n */\n private readonly entries = new Map<\n string,\n { text: string; metadata?: Record<string, unknown> }\n >();\n\n /**\n * Append an item to the buffer (or overwrite the entry sharing its\n * id). Re-inserting an existing id keeps its original position; delete\n * + set would move it to the end and lie about recency, so the value\n * is updated in place.\n */\n public remember(item: MemoryItem): void {\n const id = item.id ?? deriveMemoryId(item.text);\n\n this.entries.set(id, { text: item.text, metadata: item.metadata });\n }\n\n /**\n * Return up to `k` most-recently-remembered items, newest first. The\n * `score` is a linear recency proxy: the newest item scores `1`, the\n * oldest of the returned slice trends toward `0`. Working memory\n * ignores any similarity threshold — it has no vector to compare.\n */\n public recall(k: number): RecalledMemory[] {\n const ordered = [...this.entries.entries()].reverse();\n const slice = ordered.slice(0, Math.max(0, k));\n\n return slice.map(([id, entry], index) => ({\n id,\n text: entry.text,\n tier: \"working\" as const,\n score: slice.length <= 1 ? 1 : 1 - index / slice.length,\n metadata: entry.metadata,\n }));\n }\n\n /** Drop every working-tier entry. */\n public clear(): void {\n this.entries.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,gBAAb,MAA2B;;iCAKE,IAAI,IAG7B;;;;;;;;CAQF,AAAO,SAAS,MAAwB;EACtC,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAE9C,KAAK,QAAQ,IAAI,IAAI;GAAE,MAAM,KAAK;GAAM,UAAU,KAAK;EAAS,CAAC;CACnE;;;;;;;CAQA,AAAO,OAAO,GAA6B;EAEzC,MAAM,QADU,CAAC,GAAG,KAAK,QAAQ,QAAQ,CAAC,CAAC,CAAC,QACxB,CAAC,CAAC,MAAM,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;EAE7C,OAAO,MAAM,KAAK,CAAC,IAAI,QAAQ,WAAW;GACxC;GACA,MAAM,MAAM;GACZ,MAAM;GACN,OAAO,MAAM,UAAU,IAAI,IAAI,IAAI,QAAQ,MAAM;GACjD,UAAU,MAAM;EAClB,EAAE;CACJ;;CAGA,AAAO,QAAc;EACnB,KAAK,QAAQ,MAAM;CACrB;AACF"}
|
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
import { BudgetExceededError } from "../../errors/budget-exceeded-error.mjs";
|
|
2
|
-
import "../../errors/index.mjs";
|
|
3
|
-
import { namespacedState } from "../utils/namespaced-state.mjs";
|
|
4
|
-
|
|
5
|
-
//#region ../@warlock.js/ai/src/middleware/builtins/budget.ts
|
|
6
|
-
/**
|
|
7
|
-
* The `BudgetUnit` to stamp on the thrown error per contract dimension.
|
|
8
|
-
* Latency has no native unit — it borrows `"requests"` as the least-wrong
|
|
9
|
-
* operational measure, while the authoritative detail rides on the
|
|
10
|
-
* error's `context.dimension`.
|
|
11
|
-
*/
|
|
12
|
-
const DIMENSION_UNIT = {
|
|
13
|
-
tokens: "tokens",
|
|
14
|
-
cost: "usd",
|
|
15
|
-
latency: "requests"
|
|
16
|
-
};
|
|
17
|
-
function breach(limit, actual, unit, name) {
|
|
18
|
-
throw new BudgetExceededError(`budget "${name}" exceeded — ${actual} ${unit} (cap: ${limit})`, {
|
|
19
|
-
limit,
|
|
20
|
-
actual,
|
|
21
|
-
unit
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
function breachContract(name, dimension, limit, actual) {
|
|
25
|
-
throw new BudgetExceededError(`budget "${name}" contract exceeded — ${dimension} ${actual} (cap: ${limit})`, {
|
|
26
|
-
limit,
|
|
27
|
-
actual,
|
|
28
|
-
unit: DIMENSION_UNIT[dimension],
|
|
29
|
-
context: {
|
|
30
|
-
dimension,
|
|
31
|
-
limit,
|
|
32
|
-
actual,
|
|
33
|
-
source: "contract"
|
|
34
|
-
}
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Read the contract fallback signal recorded by a `budget()` middleware
|
|
39
|
-
* running under `contract.onViolation: "fallback"`. Returns `undefined`
|
|
40
|
-
* when no clause was breached.
|
|
41
|
-
*
|
|
42
|
-
* **Role.** The middleware cannot itself switch models on a soft breach,
|
|
43
|
-
* so it records a typed {@link BudgetFallbackSignal} in the shared state
|
|
44
|
-
* bag and lets the run continue. A fallback orchestrator (or the
|
|
45
|
-
* `execute.after` hook of an outer middleware) reads it back here and
|
|
46
|
-
* decides how to degrade the next run — cheaper model, cached answer,
|
|
47
|
-
* truncated context.
|
|
48
|
-
*
|
|
49
|
-
* @param state - The middleware state bag (`ctx.state`).
|
|
50
|
-
* @param name - The budget middleware's name. Default `"budget"`,
|
|
51
|
-
* matching `BudgetOptions.name`'s default.
|
|
52
|
-
*
|
|
53
|
-
* @example
|
|
54
|
-
* const guard = budget({ contract: { maxCostUSD: 0.05, onViolation: "fallback" } });
|
|
55
|
-
*
|
|
56
|
-
* // In an outer middleware's execute.after, after the run:
|
|
57
|
-
* const signal = readBudgetFallbackSignal(ctx.state);
|
|
58
|
-
* if (signal?.dimension === "cost") {
|
|
59
|
-
* await rerunOnCheaperModel();
|
|
60
|
-
* }
|
|
61
|
-
*/
|
|
62
|
-
function readBudgetFallbackSignal(state, name = "budget") {
|
|
63
|
-
return namespacedState({ state }, `${name}.fallback`).get();
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Enforced token and / or USD budget for an agent run.
|
|
67
|
-
*
|
|
68
|
-
* **Role.** Guards against runaway tool loops, misconfigured
|
|
69
|
-
* prompts, and unexpected provider price swings by capping
|
|
70
|
-
* cumulative usage across every LLM trip of a single execution.
|
|
71
|
-
* Aborts the run with a typed `BudgetExceededError` the moment a cap
|
|
72
|
-
* is breached, rather than letting the damage grow trip by trip.
|
|
73
|
-
*
|
|
74
|
-
* **Scope.** Per-execution. A fresh counter is created at
|
|
75
|
-
* `execute.before` and lives in the middleware state bag until the
|
|
76
|
-
* run ends. Two concurrent `agent.execute()` calls on the same
|
|
77
|
-
* agent therefore enforce the cap independently.
|
|
78
|
-
*
|
|
79
|
-
* **Token accounting.** After each successful trip, the middleware
|
|
80
|
-
* adds `response.usage.total` to its running total and checks
|
|
81
|
-
* against `maxTokens`. Synthetic trips (cache hits) contribute
|
|
82
|
-
* `usage.total` as returned by the cache — cache middleware is
|
|
83
|
-
* expected to surface zero usage on a hit, which naturally excludes
|
|
84
|
-
* those trips from the budget.
|
|
85
|
-
*
|
|
86
|
-
* **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are
|
|
87
|
-
* both present, the middleware converts per-trip input / output
|
|
88
|
-
* tokens to USD and accumulates. Missing pricing silently degrades
|
|
89
|
-
* to tokens-only — explicit rather than guessing.
|
|
90
|
-
*
|
|
91
|
-
* **Warn mode.** `onExceeded: "warn"` logs a single warning the first
|
|
92
|
-
* time a cap is breached and lets the run continue. Useful for
|
|
93
|
-
* measuring real-world traffic against a proposed cap before flipping
|
|
94
|
-
* to `"abort"` in production.
|
|
95
|
-
*
|
|
96
|
-
* **Contract / SLO mode.** Pass `contract` to enforce a declarative
|
|
97
|
-
* service-level objective — `maxCostUSD`, `maxLatencyMs`, `maxTokens` —
|
|
98
|
-
* on top of the legacy caps, with a single `onViolation` reaction:
|
|
99
|
-
* `"abort"` hard-stops with `BudgetExceededError`; `"fallback"` records
|
|
100
|
-
* a typed signal (read it via {@link readBudgetFallbackSignal}), fires
|
|
101
|
-
* the optional `fallback` callback, and lets the run continue so an
|
|
102
|
-
* outer layer can degrade gracefully. The contract's clauses are
|
|
103
|
-
* evaluated independently of — and after — the top-level caps; the
|
|
104
|
-
* top-level caps stay fully functional with or without a contract.
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* const budgetMiddleware = budget({ maxTokens: 50_000 });
|
|
108
|
-
*
|
|
109
|
-
* const myAgent = agent({
|
|
110
|
-
* model,
|
|
111
|
-
* middleware: [budgetMiddleware],
|
|
112
|
-
* });
|
|
113
|
-
*
|
|
114
|
-
* @example
|
|
115
|
-
* // With USD cap and custom pricing
|
|
116
|
-
* const guard = budget({
|
|
117
|
-
* maxCostUSD: 0.5,
|
|
118
|
-
* pricing: {
|
|
119
|
-
* "gpt-4o": { inputPer1K: 0.005, outputPer1K: 0.015 },
|
|
120
|
-
* },
|
|
121
|
-
* });
|
|
122
|
-
*
|
|
123
|
-
* @example
|
|
124
|
-
* // SLO contract — soft-fallback on any breach
|
|
125
|
-
* const sloGuard = budget({
|
|
126
|
-
* pricing: { "gpt-4o": { inputPer1K: 0.005, outputPer1K: 0.015 } },
|
|
127
|
-
* contract: {
|
|
128
|
-
* maxCostUSD: 0.05,
|
|
129
|
-
* maxLatencyMs: 8_000,
|
|
130
|
-
* maxTokens: 40_000,
|
|
131
|
-
* onViolation: "fallback",
|
|
132
|
-
* fallback: (violation) => routeToCheaperModel(violation.dimension),
|
|
133
|
-
* },
|
|
134
|
-
* });
|
|
135
|
-
*/
|
|
136
|
-
function budget(options) {
|
|
137
|
-
const name = options.name ?? "budget";
|
|
138
|
-
const onExceeded = options.onExceeded ?? "abort";
|
|
139
|
-
const hasTokenCap = typeof options.maxTokens === "number";
|
|
140
|
-
const hasCostCap = typeof options.maxCostUSD === "number";
|
|
141
|
-
const contract = options.contract;
|
|
142
|
-
const contractMode = contract?.onViolation ?? "abort";
|
|
143
|
-
const hasContractTokenCap = typeof contract?.maxTokens === "number";
|
|
144
|
-
const hasContractCostCap = typeof contract?.maxCostUSD === "number";
|
|
145
|
-
const hasContractLatencyCap = typeof contract?.maxLatencyMs === "number";
|
|
146
|
-
const contractNeedsCost = hasCostCap || hasContractCostCap;
|
|
147
|
-
const warnedUnpricedModels = /* @__PURE__ */ new Set();
|
|
148
|
-
return {
|
|
149
|
-
name,
|
|
150
|
-
execute: { before(context) {
|
|
151
|
-
namespacedState(context, name).set({
|
|
152
|
-
tokens: 0,
|
|
153
|
-
costUSD: 0,
|
|
154
|
-
warned: false,
|
|
155
|
-
startedAt: Date.now(),
|
|
156
|
-
fallbackFired: false
|
|
157
|
-
});
|
|
158
|
-
} },
|
|
159
|
-
trip: { async after(context, response) {
|
|
160
|
-
const counters = namespacedState(context, name).get();
|
|
161
|
-
if (!counters) return;
|
|
162
|
-
counters.tokens += response.usage.total;
|
|
163
|
-
if (contractNeedsCost) {
|
|
164
|
-
const pricing = options.pricing?.[context.model.name];
|
|
165
|
-
if (pricing) {
|
|
166
|
-
const tripCost = response.usage.input / 1e3 * pricing.inputPer1K + response.usage.output / 1e3 * pricing.outputPer1K;
|
|
167
|
-
counters.costUSD += tripCost;
|
|
168
|
-
} else if (!warnedUnpricedModels.has(context.model.name)) {
|
|
169
|
-
warnedUnpricedModels.add(context.model.name);
|
|
170
|
-
console.warn(`ai.middleware.budget("${name}"): a USD cost cap is set but no pricing entry matches the running model "${context.model.name}" — the cap cannot be enforced for it. Add a pricing entry for "${context.model.name}" to options.pricing.`);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
if (hasTokenCap && counters.tokens > options.maxTokens) {
|
|
174
|
-
if (onExceeded === "abort") breach(options.maxTokens, counters.tokens, "tokens", name);
|
|
175
|
-
if (!counters.warned) counters.warned = true;
|
|
176
|
-
}
|
|
177
|
-
if (hasCostCap && counters.costUSD > options.maxCostUSD) {
|
|
178
|
-
if (onExceeded === "abort") breach(options.maxCostUSD, counters.costUSD, "usd", name);
|
|
179
|
-
if (!counters.warned) counters.warned = true;
|
|
180
|
-
}
|
|
181
|
-
if (!contract) return;
|
|
182
|
-
if (hasContractTokenCap && counters.tokens > contract.maxTokens) await enforceContract(context, counters, name, contractMode, contract, "tokens", contract.maxTokens, counters.tokens);
|
|
183
|
-
if (hasContractCostCap && counters.costUSD > contract.maxCostUSD) await enforceContract(context, counters, name, contractMode, contract, "cost", contract.maxCostUSD, counters.costUSD);
|
|
184
|
-
if (hasContractLatencyCap) {
|
|
185
|
-
const elapsedMs = Date.now() - counters.startedAt;
|
|
186
|
-
if (elapsedMs > contract.maxLatencyMs) await enforceContract(context, counters, name, contractMode, contract, "latency", contract.maxLatencyMs, elapsedMs);
|
|
187
|
-
}
|
|
188
|
-
} }
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Apply the contract's reaction to a single breached clause. `"abort"`
|
|
193
|
-
* throws `BudgetExceededError` (stops the run); `"fallback"` records the
|
|
194
|
-
* signal once, fires the callback, and returns so the run continues.
|
|
195
|
-
*
|
|
196
|
-
* The callback is invoked at most once per run (guarded by
|
|
197
|
-
* `counters.fallbackFired`) and its rejections are swallowed — a buggy
|
|
198
|
-
* fallback hook must never crash the agent.
|
|
199
|
-
*/
|
|
200
|
-
async function enforceContract(context, counters, name, mode, contract, dimension, limit, actual) {
|
|
201
|
-
if (mode === "abort") breachContract(name, dimension, limit, actual);
|
|
202
|
-
if (counters.fallbackFired) return;
|
|
203
|
-
counters.fallbackFired = true;
|
|
204
|
-
const violation = {
|
|
205
|
-
dimension,
|
|
206
|
-
limit,
|
|
207
|
-
actual,
|
|
208
|
-
mode
|
|
209
|
-
};
|
|
210
|
-
namespacedState(context, `${name}.fallback`).set(violation);
|
|
211
|
-
if (!contract.fallback) return;
|
|
212
|
-
try {
|
|
213
|
-
await contract.fallback(violation, context);
|
|
214
|
-
} catch {}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
//#endregion
|
|
218
|
-
export { budget, readBudgetFallbackSignal };
|
|
219
|
-
//# sourceMappingURL=budget.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"budget.mjs","names":[],"sources":["../../../../../../../../../../@warlock.js/ai/src/middleware/builtins/budget.ts"],"sourcesContent":["import type {\n AgentMiddleware,\n MiddlewareExecuteContext,\n} from \"../../contracts/middleware\";\nimport { BudgetExceededError, type BudgetUnit } from \"../../errors\";\nimport { namespacedState } from \"../utils\";\nimport type {\n BudgetContract,\n BudgetContractDimension,\n BudgetContractViolation,\n} from \"./budget-contract.type\";\n\nexport type {\n BudgetContract,\n BudgetContractDimension,\n BudgetContractFallback,\n BudgetContractViolation,\n BudgetContractViolationMode,\n} from \"./budget-contract.type\";\n\n/**\n * Per-model pricing used to compute USD cost from token counts.\n * Caller-supplied — no bundled table. Keys are model names (the\n * `ModelContract.name` value); values are input / output token\n * prices expressed as **USD per 1K tokens** to match every major\n * provider's published pricing sheet.\n */\nexport type BudgetPricing = Record<\n string,\n {\n /** USD per 1,000 input tokens. */\n inputPer1K: number;\n /** USD per 1,000 output tokens. */\n outputPer1K: number;\n }\n>;\n\n/**\n * Configuration for `budget()`. At least one of `maxTokens` or\n * `maxCostUSD` must be supplied — a budget with no cap is a no-op.\n */\nexport type BudgetOptions = {\n /**\n * Hard cap on cumulative total tokens (input + output, summed\n * across every trip of the run). Inclusive — exceeding triggers\n * the configured `onExceeded`.\n */\n maxTokens?: number;\n /**\n * Hard cap on cumulative USD cost. Requires `pricing` for the\n * agent's configured model — without a pricing entry the USD check\n * silently skips (tokens-only enforcement still applies).\n */\n maxCostUSD?: number;\n /**\n * Per-model pricing table used to compute USD cost. Only consulted\n * when `maxCostUSD` is set. Model names must match the running\n * agent's `ModelContract.name` exactly.\n */\n pricing?: BudgetPricing;\n /**\n * Behavior when a cap is breached. `\"abort\"` throws\n * `BudgetExceededError` — surfaces on `result.error`, stops the\n * run at the next trip boundary. `\"warn\"` logs a warning and\n * lets the run continue (useful for observability-first rollouts\n * before flipping the switch to abort). Default `\"abort\"`.\n */\n onExceeded?: \"abort\" | \"warn\";\n /**\n * Override the middleware name. Useful when two budgets coexist\n * (e.g. a per-request cap plus a session-wide cap via different\n * instances). Default `\"budget\"`.\n */\n name?: string;\n /**\n * Declarative SLO / cost contract enforced on top of (and\n * independently of) the legacy `maxTokens` / `maxCostUSD` caps.\n * Adds a wall-clock `maxLatencyMs` dimension and a per-contract\n * `onViolation` reaction (`\"abort\"` hard-stops, `\"fallback\"` records\n * a signal + fires `fallback` and lets the run continue). Omit to\n * keep the classic budget behavior unchanged.\n *\n * Read a recorded fallback signal back with\n * {@link readBudgetFallbackSignal}.\n */\n contract?: BudgetContract;\n};\n\ntype BudgetCounters = {\n tokens: number;\n costUSD: number;\n warned: boolean;\n /**\n * Wall-clock epoch ms captured at `execute.before`. Used to derive\n * cumulative run latency for the contract's `maxLatencyMs` clause.\n */\n startedAt: number;\n /**\n * Set once a `\"fallback\"` contract clause has fired, so the signal +\n * callback are emitted at most once per run even if later trips keep\n * breaching.\n */\n fallbackFired: boolean;\n};\n\n/**\n * Recorded contract fallback signal, stashed under the `<name>.fallback`\n * state key when a `\"fallback\"` clause trips. A fallback orchestrator\n * reads it via {@link readBudgetFallbackSignal} to decide how to degrade.\n */\nexport type BudgetFallbackSignal = BudgetContractViolation;\n\n/**\n * The `BudgetUnit` to stamp on the thrown error per contract dimension.\n * Latency has no native unit — it borrows `\"requests\"` as the least-wrong\n * operational measure, while the authoritative detail rides on the\n * error's `context.dimension`.\n */\nconst DIMENSION_UNIT: Record<BudgetContractDimension, BudgetUnit> = {\n tokens: \"tokens\",\n cost: \"usd\",\n latency: \"requests\",\n};\n\nfunction breach(\n limit: number,\n actual: number,\n unit: BudgetUnit,\n name: string,\n): never {\n throw new BudgetExceededError(\n `budget \"${name}\" exceeded — ${actual} ${unit} (cap: ${limit})`,\n { limit, actual, unit },\n );\n}\n\nfunction breachContract(\n name: string,\n dimension: BudgetContractDimension,\n limit: number,\n actual: number,\n): never {\n throw new BudgetExceededError(\n `budget \"${name}\" contract exceeded — ${dimension} ${actual} (cap: ${limit})`,\n {\n limit,\n actual,\n unit: DIMENSION_UNIT[dimension],\n context: { dimension, limit, actual, source: \"contract\" },\n },\n );\n}\n\n/**\n * Read the contract fallback signal recorded by a `budget()` middleware\n * running under `contract.onViolation: \"fallback\"`. Returns `undefined`\n * when no clause was breached.\n *\n * **Role.** The middleware cannot itself switch models on a soft breach,\n * so it records a typed {@link BudgetFallbackSignal} in the shared state\n * bag and lets the run continue. A fallback orchestrator (or the\n * `execute.after` hook of an outer middleware) reads it back here and\n * decides how to degrade the next run — cheaper model, cached answer,\n * truncated context.\n *\n * @param state - The middleware state bag (`ctx.state`).\n * @param name - The budget middleware's name. Default `\"budget\"`,\n * matching `BudgetOptions.name`'s default.\n *\n * @example\n * const guard = budget({ contract: { maxCostUSD: 0.05, onViolation: \"fallback\" } });\n *\n * // In an outer middleware's execute.after, after the run:\n * const signal = readBudgetFallbackSignal(ctx.state);\n * if (signal?.dimension === \"cost\") {\n * await rerunOnCheaperModel();\n * }\n */\nexport function readBudgetFallbackSignal(\n state: MiddlewareExecuteContext[\"state\"],\n name = \"budget\",\n): BudgetFallbackSignal | undefined {\n return namespacedState<BudgetFallbackSignal>(\n { state },\n `${name}.fallback`,\n ).get();\n}\n\n/**\n * Enforced token and / or USD budget for an agent run.\n *\n * **Role.** Guards against runaway tool loops, misconfigured\n * prompts, and unexpected provider price swings by capping\n * cumulative usage across every LLM trip of a single execution.\n * Aborts the run with a typed `BudgetExceededError` the moment a cap\n * is breached, rather than letting the damage grow trip by trip.\n *\n * **Scope.** Per-execution. A fresh counter is created at\n * `execute.before` and lives in the middleware state bag until the\n * run ends. Two concurrent `agent.execute()` calls on the same\n * agent therefore enforce the cap independently.\n *\n * **Token accounting.** After each successful trip, the middleware\n * adds `response.usage.total` to its running total and checks\n * against `maxTokens`. Synthetic trips (cache hits) contribute\n * `usage.total` as returned by the cache — cache middleware is\n * expected to surface zero usage on a hit, which naturally excludes\n * those trips from the budget.\n *\n * **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are\n * both present, the middleware converts per-trip input / output\n * tokens to USD and accumulates. Missing pricing silently degrades\n * to tokens-only — explicit rather than guessing.\n *\n * **Warn mode.** `onExceeded: \"warn\"` logs a single warning the first\n * time a cap is breached and lets the run continue. Useful for\n * measuring real-world traffic against a proposed cap before flipping\n * to `\"abort\"` in production.\n *\n * **Contract / SLO mode.** Pass `contract` to enforce a declarative\n * service-level objective — `maxCostUSD`, `maxLatencyMs`, `maxTokens` —\n * on top of the legacy caps, with a single `onViolation` reaction:\n * `\"abort\"` hard-stops with `BudgetExceededError`; `\"fallback\"` records\n * a typed signal (read it via {@link readBudgetFallbackSignal}), fires\n * the optional `fallback` callback, and lets the run continue so an\n * outer layer can degrade gracefully. The contract's clauses are\n * evaluated independently of — and after — the top-level caps; the\n * top-level caps stay fully functional with or without a contract.\n *\n * @example\n * const budgetMiddleware = budget({ maxTokens: 50_000 });\n *\n * const myAgent = agent({\n * model,\n * middleware: [budgetMiddleware],\n * });\n *\n * @example\n * // With USD cap and custom pricing\n * const guard = budget({\n * maxCostUSD: 0.5,\n * pricing: {\n * \"gpt-4o\": { inputPer1K: 0.005, outputPer1K: 0.015 },\n * },\n * });\n *\n * @example\n * // SLO contract — soft-fallback on any breach\n * const sloGuard = budget({\n * pricing: { \"gpt-4o\": { inputPer1K: 0.005, outputPer1K: 0.015 } },\n * contract: {\n * maxCostUSD: 0.05,\n * maxLatencyMs: 8_000,\n * maxTokens: 40_000,\n * onViolation: \"fallback\",\n * fallback: (violation) => routeToCheaperModel(violation.dimension),\n * },\n * });\n */\nexport function budget(options: BudgetOptions): AgentMiddleware {\n const name = options.name ?? \"budget\";\n const onExceeded = options.onExceeded ?? \"abort\";\n const hasTokenCap = typeof options.maxTokens === \"number\";\n const hasCostCap = typeof options.maxCostUSD === \"number\";\n\n const contract = options.contract;\n const contractMode = contract?.onViolation ?? \"abort\";\n const hasContractTokenCap = typeof contract?.maxTokens === \"number\";\n const hasContractCostCap = typeof contract?.maxCostUSD === \"number\";\n const hasContractLatencyCap = typeof contract?.maxLatencyMs === \"number\";\n const contractNeedsCost = hasCostCap || hasContractCostCap;\n // Warn once per model when a cost cap is configured but the running model\n // has no pricing entry — without this the USD cap silently never enforces\n // (costUSD stays 0), a fail-open the JSDoc on `maxCostUSD` documents.\n const warnedUnpricedModels = new Set<string>();\n\n return {\n name,\n execute: {\n before(context) {\n const counters = namespacedState<BudgetCounters>(context, name);\n counters.set({\n tokens: 0,\n costUSD: 0,\n warned: false,\n startedAt: Date.now(),\n fallbackFired: false,\n });\n },\n },\n trip: {\n async after(context, response) {\n const counters = namespacedState<BudgetCounters>(context, name).get();\n\n if (!counters) {\n return;\n }\n\n counters.tokens += response.usage.total;\n\n if (contractNeedsCost) {\n const pricing = options.pricing?.[context.model.name];\n\n if (pricing) {\n const tripCost =\n (response.usage.input / 1000) * pricing.inputPer1K +\n (response.usage.output / 1000) * pricing.outputPer1K;\n counters.costUSD += tripCost;\n } else if (!warnedUnpricedModels.has(context.model.name)) {\n // A cost cap is set but no pricing matched the running model, so\n // costUSD can never grow and the USD cap silently never fires.\n // Surface the fail-open once per model instead of swallowing it.\n warnedUnpricedModels.add(context.model.name);\n console.warn(\n `ai.middleware.budget(\"${name}\"): a USD cost cap is set but no pricing entry ` +\n `matches the running model \"${context.model.name}\" — the cap cannot be enforced ` +\n `for it. Add a pricing entry for \"${context.model.name}\" to options.pricing.`,\n );\n }\n }\n\n if (hasTokenCap && counters.tokens > options.maxTokens!) {\n if (onExceeded === \"abort\") {\n breach(options.maxTokens!, counters.tokens, \"tokens\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n\n if (hasCostCap && counters.costUSD > options.maxCostUSD!) {\n if (onExceeded === \"abort\") {\n breach(options.maxCostUSD!, counters.costUSD, \"usd\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n\n if (!contract) {\n return;\n }\n\n if (hasContractTokenCap && counters.tokens > contract.maxTokens!) {\n await enforceContract(\n context,\n counters,\n name,\n contractMode,\n contract,\n \"tokens\",\n contract.maxTokens!,\n counters.tokens,\n );\n }\n\n if (hasContractCostCap && counters.costUSD > contract.maxCostUSD!) {\n await enforceContract(\n context,\n counters,\n name,\n contractMode,\n contract,\n \"cost\",\n contract.maxCostUSD!,\n counters.costUSD,\n );\n }\n\n if (hasContractLatencyCap) {\n const elapsedMs = Date.now() - counters.startedAt;\n\n if (elapsedMs > contract.maxLatencyMs!) {\n await enforceContract(\n context,\n counters,\n name,\n contractMode,\n contract,\n \"latency\",\n contract.maxLatencyMs!,\n elapsedMs,\n );\n }\n }\n },\n },\n };\n}\n\n/**\n * Apply the contract's reaction to a single breached clause. `\"abort\"`\n * throws `BudgetExceededError` (stops the run); `\"fallback\"` records the\n * signal once, fires the callback, and returns so the run continues.\n *\n * The callback is invoked at most once per run (guarded by\n * `counters.fallbackFired`) and its rejections are swallowed — a buggy\n * fallback hook must never crash the agent.\n */\nasync function enforceContract(\n context: MiddlewareExecuteContext,\n counters: BudgetCounters,\n name: string,\n mode: NonNullable<BudgetContract[\"onViolation\"]>,\n contract: BudgetContract,\n dimension: BudgetContractDimension,\n limit: number,\n actual: number,\n): Promise<void> {\n if (mode === \"abort\") {\n breachContract(name, dimension, limit, actual);\n }\n\n if (counters.fallbackFired) {\n return;\n }\n\n counters.fallbackFired = true;\n\n const violation: BudgetContractViolation = {\n dimension,\n limit,\n actual,\n mode,\n };\n\n namespacedState<BudgetContractViolation>(context, `${name}.fallback`).set(\n violation,\n );\n\n if (!contract.fallback) {\n return;\n }\n\n try {\n await contract.fallback(violation, context);\n } catch {\n // A fallback callback is a notification hook — its failure must\n // never crash the run. Swallow deliberately.\n }\n}\n"],"mappings":";;;;;;;;;;;AAsHA,MAAM,iBAA8D;CAClE,QAAQ;CACR,MAAM;CACN,SAAS;AACX;AAEA,SAAS,OACP,OACA,QACA,MACA,MACO;CACP,MAAM,IAAI,oBACR,WAAW,KAAK,eAAe,OAAO,GAAG,KAAK,SAAS,MAAM,IAC7D;EAAE;EAAO;EAAQ;CAAK,CACxB;AACF;AAEA,SAAS,eACP,MACA,WACA,OACA,QACO;CACP,MAAM,IAAI,oBACR,WAAW,KAAK,wBAAwB,UAAU,GAAG,OAAO,SAAS,MAAM,IAC3E;EACE;EACA;EACA,MAAM,eAAe;EACrB,SAAS;GAAE;GAAW;GAAO;GAAQ,QAAQ;EAAW;CAC1D,CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,yBACd,OACA,OAAO,UAC2B;CAClC,OAAO,gBACL,EAAE,MAAM,GACR,GAAG,KAAK,UACV,CAAC,CAAC,IAAI;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,OAAO,SAAyC;CAC9D,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,cAAc,OAAO,QAAQ,cAAc;CACjD,MAAM,aAAa,OAAO,QAAQ,eAAe;CAEjD,MAAM,WAAW,QAAQ;CACzB,MAAM,eAAe,UAAU,eAAe;CAC9C,MAAM,sBAAsB,OAAO,UAAU,cAAc;CAC3D,MAAM,qBAAqB,OAAO,UAAU,eAAe;CAC3D,MAAM,wBAAwB,OAAO,UAAU,iBAAiB;CAChE,MAAM,oBAAoB,cAAc;CAIxC,MAAM,uCAAuB,IAAI,IAAY;CAE7C,OAAO;EACL;EACA,SAAS,EACP,OAAO,SAAS;GAEd,AADiB,gBAAgC,SAAS,IACnD,CAAC,CAAC,IAAI;IACX,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW,KAAK,IAAI;IACpB,eAAe;GACjB,CAAC;EACH,EACF;EACA,MAAM,EACJ,MAAM,MAAM,SAAS,UAAU;GAC7B,MAAM,WAAW,gBAAgC,SAAS,IAAI,CAAC,CAAC,IAAI;GAEpE,IAAI,CAAC,UACH;GAGF,SAAS,UAAU,SAAS,MAAM;GAElC,IAAI,mBAAmB;IACrB,MAAM,UAAU,QAAQ,UAAU,QAAQ,MAAM;IAEhD,IAAI,SAAS;KACX,MAAM,WACH,SAAS,MAAM,QAAQ,MAAQ,QAAQ,aACvC,SAAS,MAAM,SAAS,MAAQ,QAAQ;KAC3C,SAAS,WAAW;IACtB,OAAO,IAAI,CAAC,qBAAqB,IAAI,QAAQ,MAAM,IAAI,GAAG;KAIxD,qBAAqB,IAAI,QAAQ,MAAM,IAAI;KAC3C,QAAQ,KACN,yBAAyB,KAAK,4EACE,QAAQ,MAAM,KAAK,kEACb,QAAQ,MAAM,KAAK,sBAC3D;IACF;GACF;GAEA,IAAI,eAAe,SAAS,SAAS,QAAQ,WAAY;IACvD,IAAI,eAAe,SACjB,OAAO,QAAQ,WAAY,SAAS,QAAQ,UAAU,IAAI;IAG5D,IAAI,CAAC,SAAS,QACZ,SAAS,SAAS;GAEtB;GAEA,IAAI,cAAc,SAAS,UAAU,QAAQ,YAAa;IACxD,IAAI,eAAe,SACjB,OAAO,QAAQ,YAAa,SAAS,SAAS,OAAO,IAAI;IAG3D,IAAI,CAAC,SAAS,QACZ,SAAS,SAAS;GAEtB;GAEA,IAAI,CAAC,UACH;GAGF,IAAI,uBAAuB,SAAS,SAAS,SAAS,WACpD,MAAM,gBACJ,SACA,UACA,MACA,cACA,UACA,UACA,SAAS,WACT,SAAS,MACX;GAGF,IAAI,sBAAsB,SAAS,UAAU,SAAS,YACpD,MAAM,gBACJ,SACA,UACA,MACA,cACA,UACA,QACA,SAAS,YACT,SAAS,OACX;GAGF,IAAI,uBAAuB;IACzB,MAAM,YAAY,KAAK,IAAI,IAAI,SAAS;IAExC,IAAI,YAAY,SAAS,cACvB,MAAM,gBACJ,SACA,UACA,MACA,cACA,UACA,WACA,SAAS,cACT,SACF;GAEJ;EACF,EACF;CACF;AACF;;;;;;;;;;AAWA,eAAe,gBACb,SACA,UACA,MACA,MACA,UACA,WACA,OACA,QACe;CACf,IAAI,SAAS,SACX,eAAe,MAAM,WAAW,OAAO,MAAM;CAG/C,IAAI,SAAS,eACX;CAGF,SAAS,gBAAgB;CAEzB,MAAM,YAAqC;EACzC;EACA;EACA;EACA;CACF;CAEA,gBAAyC,SAAS,GAAG,KAAK,UAAU,CAAC,CAAC,IACpE,SACF;CAEA,IAAI,CAAC,SAAS,UACZ;CAGF,IAAI;EACF,MAAM,SAAS,SAAS,WAAW,OAAO;CAC5C,QAAQ,CAGR;AACF"}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { GuardrailViolationError } from "../../errors/guardrail-violation-error.mjs";
|
|
2
|
-
import "../../errors/index.mjs";
|
|
3
|
-
import { extractUserText } from "../utils/extract-user-text.mjs";
|
|
4
|
-
|
|
5
|
-
//#region ../@warlock.js/ai/src/middleware/builtins/guardrail.ts
|
|
6
|
-
/**
|
|
7
|
-
* Pre/post content guardrail for an agent run.
|
|
8
|
-
*
|
|
9
|
-
* **Role.** Inspects outbound prompts and inbound responses against
|
|
10
|
-
* caller-supplied policies, aborting the trip with a typed
|
|
11
|
-
* `GuardrailViolationError` when either trips a check. Consumers
|
|
12
|
-
* distinguish `"input"` vs `"output"` violations off `error.phase`
|
|
13
|
-
* — the two failure modes have very different product responses
|
|
14
|
-
* (block the user vs re-prompt the model).
|
|
15
|
-
*
|
|
16
|
-
* **Scope.** Per-trip. Fires on every round-trip the agent makes,
|
|
17
|
-
* including repair attempts and tool-follow-up trips. Input checks
|
|
18
|
-
* evaluate the last user-role message; output checks evaluate the
|
|
19
|
-
* raw model response text before any tool call is dispatched.
|
|
20
|
-
*
|
|
21
|
-
* **Composition.** A single middleware instance can carry both
|
|
22
|
-
* `inputCheck` and `outputCheck`, or two separate instances can be
|
|
23
|
-
* registered (useful when input and output policies come from
|
|
24
|
-
* different teams / services). Registration order determines which
|
|
25
|
-
* guardrail's violation surfaces first — the short-circuit throws
|
|
26
|
-
* from the innermost offending hook, and outer guardrails never run
|
|
27
|
-
* after an abort.
|
|
28
|
-
*
|
|
29
|
-
* **Not a sanitizer.** The guardrail either passes a trip unchanged
|
|
30
|
-
* or aborts it. Mutating the prompt / response in-place is out of
|
|
31
|
-
* scope — use a bespoke middleware for content rewriting.
|
|
32
|
-
*
|
|
33
|
-
* @example
|
|
34
|
-
* const policy = guardrail({
|
|
35
|
-
* inputCheck: async (text) =>
|
|
36
|
-
* text.includes("SSN") ? { ok: false, reason: "pii" } : { ok: true },
|
|
37
|
-
* outputCheck: async (text) =>
|
|
38
|
-
* text.length > 10_000 ? { ok: false, reason: "too-long" } : { ok: true },
|
|
39
|
-
* });
|
|
40
|
-
*
|
|
41
|
-
* const myAgent = agent({ model, middleware: [policy] });
|
|
42
|
-
*/
|
|
43
|
-
function guardrail(options) {
|
|
44
|
-
const name = options.name ?? "guardrail";
|
|
45
|
-
const { inputCheck, outputCheck } = options;
|
|
46
|
-
return {
|
|
47
|
-
name,
|
|
48
|
-
trip: {
|
|
49
|
-
async before(context) {
|
|
50
|
-
if (!inputCheck) return;
|
|
51
|
-
const prompt = extractUserText(context.messages);
|
|
52
|
-
if (!prompt) return;
|
|
53
|
-
const verdict = await inputCheck(prompt, context);
|
|
54
|
-
if (!verdict.ok) throw new GuardrailViolationError(`guardrail "${name}" rejected input — ${verdict.reason}`, {
|
|
55
|
-
phase: "input",
|
|
56
|
-
reason: verdict.reason,
|
|
57
|
-
guardrail: name
|
|
58
|
-
});
|
|
59
|
-
},
|
|
60
|
-
async after(context, response) {
|
|
61
|
-
if (!outputCheck) return;
|
|
62
|
-
if (!response.content) return;
|
|
63
|
-
const verdict = await outputCheck(response.content, context);
|
|
64
|
-
if (!verdict.ok) throw new GuardrailViolationError(`guardrail "${name}" rejected output — ${verdict.reason}`, {
|
|
65
|
-
phase: "output",
|
|
66
|
-
reason: verdict.reason,
|
|
67
|
-
guardrail: name
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
//#endregion
|
|
75
|
-
export { guardrail };
|
|
76
|
-
//# sourceMappingURL=guardrail.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"guardrail.mjs","names":[],"sources":["../../../../../../../../../../@warlock.js/ai/src/middleware/builtins/guardrail.ts"],"sourcesContent":["import type {\n AgentMiddleware,\n MiddlewareTripContext,\n} from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { GuardrailViolationError } from \"../../errors\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Decision returned by a guardrail check function. `ok: true`\n * permits the call; `ok: false` rejects with a human-readable\n * `reason` surfaced on `GuardrailViolationError`.\n */\nexport type GuardrailCheckResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Synchronous or asynchronous check invoked against the outbound\n * prompt (`inputCheck`) or the inbound response (`outputCheck`).\n * Receives the raw text and the surrounding trip context so\n * consumers can classify, route to an external moderation API, or\n * branch on tripIndex / messages history.\n */\nexport type GuardrailCheck = (\n text: string,\n context: MiddlewareTripContext,\n) => GuardrailCheckResult | Promise<GuardrailCheckResult>;\n\n/**\n * Configuration for `guardrail()`. At least one of `inputCheck` or\n * `outputCheck` must be supplied — a guardrail with no checks is a\n * no-op.\n */\nexport type GuardrailOptions = {\n /**\n * Run against the outbound prompt just before the model sees it.\n * Fires every trip with the concatenated last user-message text.\n * Rejection aborts the trip with a `GuardrailViolationError` whose\n * `phase === \"input\"`.\n */\n inputCheck?: GuardrailCheck;\n /**\n * Run against the model's response text after the trip completes.\n * Fires every trip with `response.content`. Rejection aborts with\n * a `GuardrailViolationError` whose `phase === \"output\"`.\n *\n * Output checks run BEFORE any tool dispatch — a rejected response\n * means the tool calls it requested are never invoked.\n */\n outputCheck?: GuardrailCheck;\n /**\n * Override the middleware name — surfaces on\n * `GuardrailViolationError.guardrail` so operators can tell two\n * guardrails apart in logs. Default `\"guardrail\"`.\n */\n name?: string;\n};\n\n/**\n * Pre/post content guardrail for an agent run.\n *\n * **Role.** Inspects outbound prompts and inbound responses against\n * caller-supplied policies, aborting the trip with a typed\n * `GuardrailViolationError` when either trips a check. Consumers\n * distinguish `\"input\"` vs `\"output\"` violations off `error.phase`\n * — the two failure modes have very different product responses\n * (block the user vs re-prompt the model).\n *\n * **Scope.** Per-trip. Fires on every round-trip the agent makes,\n * including repair attempts and tool-follow-up trips. Input checks\n * evaluate the last user-role message; output checks evaluate the\n * raw model response text before any tool call is dispatched.\n *\n * **Composition.** A single middleware instance can carry both\n * `inputCheck` and `outputCheck`, or two separate instances can be\n * registered (useful when input and output policies come from\n * different teams / services). Registration order determines which\n * guardrail's violation surfaces first — the short-circuit throws\n * from the innermost offending hook, and outer guardrails never run\n * after an abort.\n *\n * **Not a sanitizer.** The guardrail either passes a trip unchanged\n * or aborts it. Mutating the prompt / response in-place is out of\n * scope — use a bespoke middleware for content rewriting.\n *\n * @example\n * const policy = guardrail({\n * inputCheck: async (text) =>\n * text.includes(\"SSN\") ? { ok: false, reason: \"pii\" } : { ok: true },\n * outputCheck: async (text) =>\n * text.length > 10_000 ? { ok: false, reason: \"too-long\" } : { ok: true },\n * });\n *\n * const myAgent = agent({ model, middleware: [policy] });\n */\nexport function guardrail(options: GuardrailOptions): AgentMiddleware {\n const name = options.name ?? \"guardrail\";\n const { inputCheck, outputCheck } = options;\n\n return {\n name,\n trip: {\n async before(context) {\n if (!inputCheck) {\n return;\n }\n\n const prompt = extractUserText(context.messages);\n\n if (!prompt) {\n return;\n }\n\n const verdict = await inputCheck(prompt, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected input — ${verdict.reason}`,\n { phase: \"input\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n async after(context, response: ModelResponse) {\n if (!outputCheck) {\n return;\n }\n\n if (!response.content) {\n return;\n }\n\n const verdict = await outputCheck(response.content, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected output — ${verdict.reason}`,\n { phase: \"output\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,UAAU,SAA4C;CACpE,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,EAAE,YAAY,gBAAgB;CAEpC,OAAO;EACL;EACA,MAAM;GACJ,MAAM,OAAO,SAAS;IACpB,IAAI,CAAC,YACH;IAGF,MAAM,SAAS,gBAAgB,QAAQ,QAAQ;IAE/C,IAAI,CAAC,QACH;IAGF,MAAM,UAAU,MAAM,WAAW,QAAQ,OAAO;IAEhD,IAAI,CAAC,QAAQ,IACX,MAAM,IAAI,wBACR,cAAc,KAAK,qBAAqB,QAAQ,UAChD;KAAE,OAAO;KAAS,QAAQ,QAAQ;KAAQ,WAAW;IAAK,CAC5D;GAEJ;GACA,MAAM,MAAM,SAAS,UAAyB;IAC5C,IAAI,CAAC,aACH;IAGF,IAAI,CAAC,SAAS,SACZ;IAGF,MAAM,UAAU,MAAM,YAAY,SAAS,SAAS,OAAO;IAE3D,IAAI,CAAC,QAAQ,IACX,MAAM,IAAI,wBACR,cAAc,KAAK,sBAAsB,QAAQ,UACjD;KAAE,OAAO;KAAU,QAAQ,QAAQ;KAAQ,WAAW;IAAK,CAC7D;GAEJ;EACF;CACF;AACF"}
|