@warlock.js/core 4.3.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -6
- package/README.md +47 -11
- package/esm/ai/src/agent/agent-input-builder.mjs +132 -0
- package/esm/ai/src/agent/agent-input-builder.mjs.map +1 -0
- package/esm/ai/src/agent/agent-log-event.mjs +101 -0
- package/esm/ai/src/agent/agent-log-event.mjs.map +1 -0
- package/esm/ai/src/agent/agent-stream.mjs +82 -0
- package/esm/ai/src/agent/agent-stream.mjs.map +1 -0
- package/esm/ai/src/agent/agent-to-stream-event.mjs +86 -0
- package/esm/ai/src/agent/agent-to-stream-event.mjs.map +1 -0
- package/esm/ai/src/agent/agent.mjs +1157 -0
- package/esm/ai/src/agent/agent.mjs.map +1 -0
- package/esm/ai/src/agent/index.mjs +5 -0
- package/esm/ai/src/agent/json-stream-guard.mjs +400 -0
- package/esm/ai/src/agent/json-stream-guard.mjs.map +1 -0
- package/esm/ai/src/agent/spawn-sub-agent.mjs +68 -0
- package/esm/ai/src/agent/spawn-sub-agent.mjs.map +1 -0
- package/esm/ai/src/ai.mjs +155 -0
- package/esm/ai/src/ai.mjs.map +1 -0
- package/esm/ai/src/batch/batch.mjs +198 -0
- package/esm/ai/src/batch/batch.mjs.map +1 -0
- package/esm/ai/src/batch/index.mjs +3 -0
- package/esm/ai/src/batch/run-batch-item.mjs +100 -0
- package/esm/ai/src/batch/run-batch-item.mjs.map +1 -0
- package/esm/ai/src/batch/run-with-concurrency.mjs +39 -0
- package/esm/ai/src/batch/run-with-concurrency.mjs.map +1 -0
- package/esm/ai/src/checkpoint/memory.mjs +0 -0
- package/esm/ai/src/checkpoint/memory.mjs.map +1 -0
- package/esm/ai/src/checkpoint/pg.mjs +265 -0
- package/esm/ai/src/checkpoint/pg.mjs.map +1 -0
- package/esm/ai/src/checkpoint/redis.mjs +200 -0
- package/esm/ai/src/checkpoint/redis.mjs.map +1 -0
- package/esm/ai/src/config.mjs +59 -0
- package/esm/ai/src/config.mjs.map +1 -0
- package/esm/ai/src/contracts/end.type.mjs +47 -0
- package/esm/ai/src/contracts/end.type.mjs.map +1 -0
- package/esm/ai/src/errors/agent-cancelled-error.mjs +43 -0
- package/esm/ai/src/errors/agent-cancelled-error.mjs.map +1 -0
- package/esm/ai/src/errors/agent-execution-error.mjs +35 -0
- package/esm/ai/src/errors/agent-execution-error.mjs.map +1 -0
- package/esm/ai/src/errors/agent-max-trips-error.mjs +41 -0
- package/esm/ai/src/errors/agent-max-trips-error.mjs.map +1 -0
- package/esm/ai/src/errors/ai-error.mjs +68 -0
- package/esm/ai/src/errors/ai-error.mjs.map +1 -0
- package/esm/ai/src/errors/budget-exceeded-error.mjs +31 -0
- package/esm/ai/src/errors/budget-exceeded-error.mjs.map +1 -0
- package/esm/ai/src/errors/content-filter-error.mjs +28 -0
- package/esm/ai/src/errors/content-filter-error.mjs.map +1 -0
- package/esm/ai/src/errors/context-length-exceeded-error.mjs +31 -0
- package/esm/ai/src/errors/context-length-exceeded-error.mjs.map +1 -0
- package/esm/ai/src/errors/guardrail-violation-error.mjs +41 -0
- package/esm/ai/src/errors/guardrail-violation-error.mjs.map +1 -0
- package/esm/ai/src/errors/index.mjs +37 -0
- package/esm/ai/src/errors/invalid-request-error.mjs +31 -0
- package/esm/ai/src/errors/invalid-request-error.mjs.map +1 -0
- package/esm/ai/src/errors/max-iterations-error.mjs +32 -0
- package/esm/ai/src/errors/max-iterations-error.mjs.map +1 -0
- package/esm/ai/src/errors/max-steps-exceeded-error.mjs +21 -0
- package/esm/ai/src/errors/max-steps-exceeded-error.mjs.map +1 -0
- package/esm/ai/src/errors/orchestrator-cancelled-error.mjs +31 -0
- package/esm/ai/src/errors/orchestrator-cancelled-error.mjs.map +1 -0
- package/esm/ai/src/errors/orchestrator-config-error.mjs +30 -0
- package/esm/ai/src/errors/orchestrator-config-error.mjs.map +1 -0
- package/esm/ai/src/errors/orchestrator-drift-error.mjs +37 -0
- package/esm/ai/src/errors/orchestrator-drift-error.mjs.map +1 -0
- package/esm/ai/src/errors/orchestrator-failed-error.mjs +36 -0
- package/esm/ai/src/errors/orchestrator-failed-error.mjs.map +1 -0
- package/esm/ai/src/errors/outbound-policy-error.mjs +32 -0
- package/esm/ai/src/errors/outbound-policy-error.mjs.map +1 -0
- package/esm/ai/src/errors/planner-cancelled-error.mjs +29 -0
- package/esm/ai/src/errors/planner-cancelled-error.mjs.map +1 -0
- package/esm/ai/src/errors/planner-failed-error.mjs +37 -0
- package/esm/ai/src/errors/planner-failed-error.mjs.map +1 -0
- package/esm/ai/src/errors/planner-plan-invalid-error.mjs +25 -0
- package/esm/ai/src/errors/planner-plan-invalid-error.mjs.map +1 -0
- package/esm/ai/src/errors/provider-auth-error.mjs +26 -0
- package/esm/ai/src/errors/provider-auth-error.mjs.map +1 -0
- package/esm/ai/src/errors/provider-error.mjs +42 -0
- package/esm/ai/src/errors/provider-error.mjs.map +1 -0
- package/esm/ai/src/errors/provider-rate-limit-error.mjs +31 -0
- package/esm/ai/src/errors/provider-rate-limit-error.mjs.map +1 -0
- package/esm/ai/src/errors/provider-timeout-error.mjs +26 -0
- package/esm/ai/src/errors/provider-timeout-error.mjs.map +1 -0
- package/esm/ai/src/errors/quota-exceeded-error.mjs +40 -0
- package/esm/ai/src/errors/quota-exceeded-error.mjs.map +1 -0
- package/esm/ai/src/errors/routing-error.mjs +23 -0
- package/esm/ai/src/errors/routing-error.mjs.map +1 -0
- package/esm/ai/src/errors/schema-validation-error.mjs +37 -0
- package/esm/ai/src/errors/schema-validation-error.mjs.map +1 -0
- package/esm/ai/src/errors/step-failed-error.mjs +19 -0
- package/esm/ai/src/errors/step-failed-error.mjs.map +1 -0
- package/esm/ai/src/errors/supervisor-cancelled-error.mjs +29 -0
- package/esm/ai/src/errors/supervisor-cancelled-error.mjs.map +1 -0
- package/esm/ai/src/errors/supervisor-drift-error.mjs +30 -0
- package/esm/ai/src/errors/supervisor-drift-error.mjs.map +1 -0
- package/esm/ai/src/errors/supervisor-failed-error.mjs +43 -0
- package/esm/ai/src/errors/supervisor-failed-error.mjs.map +1 -0
- package/esm/ai/src/errors/supervisor-routing-error.mjs +39 -0
- package/esm/ai/src/errors/supervisor-routing-error.mjs.map +1 -0
- package/esm/ai/src/errors/tool-execution-error.mjs +32 -0
- package/esm/ai/src/errors/tool-execution-error.mjs.map +1 -0
- package/esm/ai/src/errors/workflow-cancelled-error.mjs +23 -0
- package/esm/ai/src/errors/workflow-cancelled-error.mjs.map +1 -0
- package/esm/ai/src/errors/workflow-drift-error.mjs +24 -0
- package/esm/ai/src/errors/workflow-drift-error.mjs.map +1 -0
- package/esm/ai/src/errors/workflow-error.mjs +18 -0
- package/esm/ai/src/errors/workflow-error.mjs.map +1 -0
- package/esm/ai/src/eval/dataset.mjs +112 -0
- package/esm/ai/src/eval/dataset.mjs.map +1 -0
- package/esm/ai/src/eval/eval-runner.mjs +135 -0
- package/esm/ai/src/eval/eval-runner.mjs.map +1 -0
- package/esm/ai/src/eval/index.mjs +48 -0
- package/esm/ai/src/eval/index.mjs.map +1 -0
- package/esm/ai/src/eval/judge-scorer.mjs +87 -0
- package/esm/ai/src/eval/judge-scorer.mjs.map +1 -0
- package/esm/ai/src/eval/regression.mjs +51 -0
- package/esm/ai/src/eval/regression.mjs.map +1 -0
- package/esm/ai/src/eval/report-json.mjs +33 -0
- package/esm/ai/src/eval/report-json.mjs.map +1 -0
- package/esm/ai/src/eval/report-junit.mjs +60 -0
- package/esm/ai/src/eval/report-junit.mjs.map +1 -0
- package/esm/ai/src/eval/scorers.mjs +101 -0
- package/esm/ai/src/eval/scorers.mjs.map +1 -0
- package/esm/ai/src/guard/detectors/index.mjs +6 -0
- package/esm/ai/src/guard/detectors/injection.mjs +254 -0
- package/esm/ai/src/guard/detectors/injection.mjs.map +1 -0
- package/esm/ai/src/guard/detectors/moderation.mjs +134 -0
- package/esm/ai/src/guard/detectors/moderation.mjs.map +1 -0
- package/esm/ai/src/guard/detectors/pii.mjs +199 -0
- package/esm/ai/src/guard/detectors/pii.mjs.map +1 -0
- package/esm/ai/src/guard/detectors/topic.mjs +99 -0
- package/esm/ai/src/guard/detectors/topic.mjs.map +1 -0
- package/esm/ai/src/guard/errors.mjs +18 -0
- package/esm/ai/src/guard/errors.mjs.map +1 -0
- package/esm/ai/src/guard/guard.mjs +209 -0
- package/esm/ai/src/guard/guard.mjs.map +1 -0
- package/esm/ai/src/guard/guardrail.mjs +22 -0
- package/esm/ai/src/guard/guardrail.mjs.map +1 -0
- package/esm/ai/src/human/errors.mjs +60 -0
- package/esm/ai/src/human/errors.mjs.map +1 -0
- package/esm/ai/src/human/human-approval.mjs +170 -0
- package/esm/ai/src/human/human-approval.mjs.map +1 -0
- package/esm/ai/src/human/policy.mjs +67 -0
- package/esm/ai/src/human/policy.mjs.map +1 -0
- package/esm/ai/src/human/register.mjs +37 -0
- package/esm/ai/src/human/register.mjs.map +1 -0
- package/esm/ai/src/human/resume-seed.mjs +53 -0
- package/esm/ai/src/human/resume-seed.mjs.map +1 -0
- package/esm/ai/src/human/resume.mjs +121 -0
- package/esm/ai/src/human/resume.mjs.map +1 -0
- package/esm/ai/src/human/stores/index.mjs +5 -0
- package/esm/ai/src/human/stores/memory.mjs +91 -0
- package/esm/ai/src/human/stores/memory.mjs.map +1 -0
- package/esm/ai/src/human/stores/pg.mjs +220 -0
- package/esm/ai/src/human/stores/pg.mjs.map +1 -0
- package/esm/ai/src/human/stores/redis.mjs +201 -0
- package/esm/ai/src/human/stores/redis.mjs.map +1 -0
- package/esm/ai/src/index.mjs +174 -0
- package/esm/ai/src/memory/derive-id.mjs +24 -0
- package/esm/ai/src/memory/derive-id.mjs.map +1 -0
- package/esm/ai/src/memory/episodic-memory.mjs +106 -0
- package/esm/ai/src/memory/episodic-memory.mjs.map +1 -0
- package/esm/ai/src/memory/memory.mjs +166 -0
- package/esm/ai/src/memory/memory.mjs.map +1 -0
- package/esm/ai/src/memory/procedural-memory.mjs +103 -0
- package/esm/ai/src/memory/procedural-memory.mjs.map +1 -0
- package/esm/ai/src/memory/semantic-memory.mjs +80 -0
- package/esm/ai/src/memory/semantic-memory.mjs.map +1 -0
- package/esm/ai/src/memory/working-memory.mjs +62 -0
- package/esm/ai/src/memory/working-memory.mjs.map +1 -0
- package/esm/ai/src/middleware/builtins/budget.mjs +219 -0
- package/esm/ai/src/middleware/builtins/budget.mjs.map +1 -0
- package/esm/ai/src/middleware/builtins/guardrail.mjs +76 -0
- package/esm/ai/src/middleware/builtins/guardrail.mjs.map +1 -0
- package/esm/ai/src/middleware/builtins/semantic-cache.mjs +149 -0
- package/esm/ai/src/middleware/builtins/semantic-cache.mjs.map +1 -0
- package/esm/ai/src/middleware/helpers/compose.mjs +52 -0
- package/esm/ai/src/middleware/helpers/compose.mjs.map +1 -0
- package/esm/ai/src/middleware/helpers/for-tool.mjs +80 -0
- package/esm/ai/src/middleware/helpers/for-tool.mjs.map +1 -0
- package/esm/ai/src/middleware/index.mjs +10 -0
- package/esm/ai/src/middleware/pipeline.mjs +100 -0
- package/esm/ai/src/middleware/pipeline.mjs.map +1 -0
- package/esm/ai/src/middleware/utils/extract-user-text.mjs +47 -0
- package/esm/ai/src/middleware/utils/extract-user-text.mjs.map +1 -0
- package/esm/ai/src/middleware/utils/namespaced-state.mjs +60 -0
- package/esm/ai/src/middleware/utils/namespaced-state.mjs.map +1 -0
- package/esm/ai/src/mock/index.mjs +4 -0
- package/esm/ai/src/mock/mock-agent.mjs +3 -0
- package/esm/ai/src/mock/mock-router.mjs +58 -0
- package/esm/ai/src/mock/mock-router.mjs.map +1 -0
- package/esm/ai/src/model/fallback-model.mjs +218 -0
- package/esm/ai/src/model/fallback-model.mjs.map +1 -0
- package/esm/ai/src/model/index.mjs +3 -0
- package/esm/ai/src/object-stream/index.mjs +4 -0
- package/esm/ai/src/object-stream/parse-partial-json.mjs +78 -0
- package/esm/ai/src/object-stream/parse-partial-json.mjs.map +1 -0
- package/esm/ai/src/object-stream/stream-object.mjs +97 -0
- package/esm/ai/src/object-stream/stream-object.mjs.map +1 -0
- package/esm/ai/src/observe/index.mjs +4 -0
- package/esm/ai/src/observe/observer-registry.mjs +35 -0
- package/esm/ai/src/observe/observer-registry.mjs.map +1 -0
- package/esm/ai/src/observe/resolve-observers.mjs +73 -0
- package/esm/ai/src/observe/resolve-observers.mjs.map +1 -0
- package/esm/ai/src/orchestrator/as-tool.mjs +98 -0
- package/esm/ai/src/orchestrator/as-tool.mjs.map +1 -0
- package/esm/ai/src/orchestrator/checkpoint.mjs +75 -0
- package/esm/ai/src/orchestrator/checkpoint.mjs.map +1 -0
- package/esm/ai/src/orchestrator/commands.mjs +34 -0
- package/esm/ai/src/orchestrator/commands.mjs.map +1 -0
- package/esm/ai/src/orchestrator/compaction.mjs +206 -0
- package/esm/ai/src/orchestrator/compaction.mjs.map +1 -0
- package/esm/ai/src/orchestrator/dispatch.mjs +171 -0
- package/esm/ai/src/orchestrator/dispatch.mjs.map +1 -0
- package/esm/ai/src/orchestrator/emitter.mjs +85 -0
- package/esm/ai/src/orchestrator/emitter.mjs.map +1 -0
- package/esm/ai/src/orchestrator/execution.mjs +395 -0
- package/esm/ai/src/orchestrator/execution.mjs.map +1 -0
- package/esm/ai/src/orchestrator/index.mjs +11 -0
- package/esm/ai/src/orchestrator/load.mjs +49 -0
- package/esm/ai/src/orchestrator/load.mjs.map +1 -0
- package/esm/ai/src/orchestrator/lock.mjs +75 -0
- package/esm/ai/src/orchestrator/lock.mjs.map +1 -0
- package/esm/ai/src/orchestrator/memory.mjs +141 -0
- package/esm/ai/src/orchestrator/memory.mjs.map +1 -0
- package/esm/ai/src/orchestrator/orchestrator-stream.mjs +98 -0
- package/esm/ai/src/orchestrator/orchestrator-stream.mjs.map +1 -0
- package/esm/ai/src/orchestrator/orchestrator.mjs +206 -0
- package/esm/ai/src/orchestrator/orchestrator.mjs.map +1 -0
- package/esm/ai/src/orchestrator/resume.mjs +74 -0
- package/esm/ai/src/orchestrator/resume.mjs.map +1 -0
- package/esm/ai/src/orchestrator/session-lock.mjs +83 -0
- package/esm/ai/src/orchestrator/session-lock.mjs.map +1 -0
- package/esm/ai/src/orchestrator/signature.mjs +120 -0
- package/esm/ai/src/orchestrator/signature.mjs.map +1 -0
- package/esm/ai/src/orchestrator/window.mjs +56 -0
- package/esm/ai/src/orchestrator/window.mjs.map +1 -0
- package/esm/ai/src/planner/dag-scheduler.mjs +97 -0
- package/esm/ai/src/planner/dag-scheduler.mjs.map +1 -0
- package/esm/ai/src/planner/index.mjs +6 -0
- package/esm/ai/src/planner/plan-prompt.mjs +31 -0
- package/esm/ai/src/planner/plan-prompt.mjs.map +1 -0
- package/esm/ai/src/planner/plan-schema.mjs +120 -0
- package/esm/ai/src/planner/plan-schema.mjs.map +1 -0
- package/esm/ai/src/planner/planner-run.mjs +614 -0
- package/esm/ai/src/planner/planner-run.mjs.map +1 -0
- package/esm/ai/src/planner/planner.mjs +120 -0
- package/esm/ai/src/planner/planner.mjs.map +1 -0
- package/esm/ai/src/planner/signature.mjs +27 -0
- package/esm/ai/src/planner/signature.mjs.map +1 -0
- package/esm/ai/src/prompt/errors.mjs +73 -0
- package/esm/ai/src/prompt/errors.mjs.map +1 -0
- package/esm/ai/src/prompt/index.mjs +4 -0
- package/esm/ai/src/prompt/prompt-langfuse-sync.mjs +104 -0
- package/esm/ai/src/prompt/prompt-langfuse-sync.mjs.map +1 -0
- package/esm/ai/src/prompt/prompt-validate.mjs +170 -0
- package/esm/ai/src/prompt/prompt-validate.mjs.map +1 -0
- package/esm/ai/src/prompt/prompt.mjs +218 -0
- package/esm/ai/src/prompt/prompt.mjs.map +1 -0
- package/esm/ai/src/prompts/index.mjs +3 -0
- package/esm/ai/src/prompts/prompts-manager.mjs +410 -0
- package/esm/ai/src/prompts/prompts-manager.mjs.map +1 -0
- package/esm/ai/src/prompts/prompts-validate.mjs +200 -0
- package/esm/ai/src/prompts/prompts-validate.mjs.map +1 -0
- package/esm/ai/src/rag/as-tool.mjs +48 -0
- package/esm/ai/src/rag/as-tool.mjs.map +1 -0
- package/esm/ai/src/rag/chunk/chunk.mjs +44 -0
- package/esm/ai/src/rag/chunk/chunk.mjs.map +1 -0
- package/esm/ai/src/rag/chunk/fixed.mjs +32 -0
- package/esm/ai/src/rag/chunk/fixed.mjs.map +1 -0
- package/esm/ai/src/rag/chunk/markdown.mjs +75 -0
- package/esm/ai/src/rag/chunk/markdown.mjs.map +1 -0
- package/esm/ai/src/rag/chunk/recursive.mjs +132 -0
- package/esm/ai/src/rag/chunk/recursive.mjs.map +1 -0
- package/esm/ai/src/rag/chunk/sentence.mjs +73 -0
- package/esm/ai/src/rag/chunk/sentence.mjs.map +1 -0
- package/esm/ai/src/rag/index.mjs +7 -0
- package/esm/ai/src/rag/rag.mjs +126 -0
- package/esm/ai/src/rag/rag.mjs.map +1 -0
- package/esm/ai/src/rag/rerank/keyword-reranker.mjs +58 -0
- package/esm/ai/src/rag/rerank/keyword-reranker.mjs.map +1 -0
- package/esm/ai/src/rag/rerank/llm-reranker.mjs +85 -0
- package/esm/ai/src/rag/rerank/llm-reranker.mjs.map +1 -0
- package/esm/ai/src/rag/retrieve.mjs +68 -0
- package/esm/ai/src/rag/retrieve.mjs.map +1 -0
- package/esm/ai/src/rag/store/cache-vector-store.mjs +48 -0
- package/esm/ai/src/rag/store/cache-vector-store.mjs.map +1 -0
- package/esm/ai/src/security/index.mjs +5 -0
- package/esm/ai/src/security/outbound-policy.mjs +187 -0
- package/esm/ai/src/security/outbound-policy.mjs.map +1 -0
- package/esm/ai/src/security/private-ip.mjs +48 -0
- package/esm/ai/src/security/private-ip.mjs.map +1 -0
- package/esm/ai/src/security/redact.mjs +60 -0
- package/esm/ai/src/security/redact.mjs.map +1 -0
- package/esm/ai/src/serve/serve.mjs +90 -0
- package/esm/ai/src/serve/serve.mjs.map +1 -0
- package/esm/ai/src/serve/sse.mjs +25 -0
- package/esm/ai/src/serve/sse.mjs.map +1 -0
- package/esm/ai/src/serve/stream-to-sse.mjs +37 -0
- package/esm/ai/src/serve/stream-to-sse.mjs.map +1 -0
- package/esm/ai/src/skills/catalog.mjs +140 -0
- package/esm/ai/src/skills/catalog.mjs.map +1 -0
- package/esm/ai/src/skills/index.mjs +11 -0
- package/esm/ai/src/skills/load-skill-tool.mjs +65 -0
- package/esm/ai/src/skills/load-skill-tool.mjs.map +1 -0
- package/esm/ai/src/skills/save-skill-tool.mjs +65 -0
- package/esm/ai/src/skills/save-skill-tool.mjs.map +1 -0
- package/esm/ai/src/skills/skills.mjs +109 -0
- package/esm/ai/src/skills/skills.mjs.map +1 -0
- package/esm/ai/src/skills/sources/directory-source.mjs +108 -0
- package/esm/ai/src/skills/sources/directory-source.mjs.map +1 -0
- package/esm/ai/src/skills/sources/index.mjs +27 -0
- package/esm/ai/src/skills/sources/index.mjs.map +1 -0
- package/esm/ai/src/skills/sources/parse-frontmatter.mjs +46 -0
- package/esm/ai/src/skills/sources/parse-frontmatter.mjs.map +1 -0
- package/esm/ai/src/skills/sources/store-source.mjs +15 -0
- package/esm/ai/src/skills/sources/store-source.mjs.map +1 -0
- package/esm/ai/src/skills/sources/url-source.mjs +117 -0
- package/esm/ai/src/skills/sources/url-source.mjs.map +1 -0
- package/esm/ai/src/snapshot/memory.mjs +81 -0
- package/esm/ai/src/snapshot/memory.mjs.map +1 -0
- package/esm/ai/src/snapshot/pg.mjs +146 -0
- package/esm/ai/src/snapshot/pg.mjs.map +1 -0
- package/esm/ai/src/snapshot/redis.mjs +101 -0
- package/esm/ai/src/snapshot/redis.mjs.map +1 -0
- package/esm/ai/src/supervisor/as-tool.mjs +74 -0
- package/esm/ai/src/supervisor/as-tool.mjs.map +1 -0
- package/esm/ai/src/supervisor/cancellation.mjs +22 -0
- package/esm/ai/src/supervisor/cancellation.mjs.map +1 -0
- package/esm/ai/src/supervisor/decide.mjs +272 -0
- package/esm/ai/src/supervisor/decide.mjs.map +1 -0
- package/esm/ai/src/supervisor/emitter.mjs +47 -0
- package/esm/ai/src/supervisor/emitter.mjs.map +1 -0
- package/esm/ai/src/supervisor/entries.mjs +206 -0
- package/esm/ai/src/supervisor/entries.mjs.map +1 -0
- package/esm/ai/src/supervisor/execution.mjs +1921 -0
- package/esm/ai/src/supervisor/execution.mjs.map +1 -0
- package/esm/ai/src/supervisor/fan-out.mjs +65 -0
- package/esm/ai/src/supervisor/fan-out.mjs.map +1 -0
- package/esm/ai/src/supervisor/index.mjs +14 -0
- package/esm/ai/src/supervisor/router-factory.mjs +141 -0
- package/esm/ai/src/supervisor/router-factory.mjs.map +1 -0
- package/esm/ai/src/supervisor/router-prompt.mjs +52 -0
- package/esm/ai/src/supervisor/router-prompt.mjs.map +1 -0
- package/esm/ai/src/supervisor/signature.mjs +89 -0
- package/esm/ai/src/supervisor/signature.mjs.map +1 -0
- package/esm/ai/src/supervisor/snapshot.mjs +69 -0
- package/esm/ai/src/supervisor/snapshot.mjs.map +1 -0
- package/esm/ai/src/supervisor/supervisor-stream.mjs +89 -0
- package/esm/ai/src/supervisor/supervisor-stream.mjs.map +1 -0
- package/esm/ai/src/supervisor/supervisor.mjs +144 -0
- package/esm/ai/src/supervisor/supervisor.mjs.map +1 -0
- package/esm/ai/src/system-prompt/index.mjs +6 -0
- package/esm/ai/src/system-prompt/instruction.mjs +57 -0
- package/esm/ai/src/system-prompt/instruction.mjs.map +1 -0
- package/esm/ai/src/system-prompt/persona.mjs +57 -0
- package/esm/ai/src/system-prompt/persona.mjs.map +1 -0
- package/esm/ai/src/system-prompt/render-placeholders.mjs +58 -0
- package/esm/ai/src/system-prompt/render-placeholders.mjs.map +1 -0
- package/esm/ai/src/system-prompt/system-prompt.mjs +267 -0
- package/esm/ai/src/system-prompt/system-prompt.mjs.map +1 -0
- package/esm/ai/src/team/gates.mjs +48 -0
- package/esm/ai/src/team/gates.mjs.map +1 -0
- package/esm/ai/src/team/index.mjs +3 -0
- package/esm/ai/src/team/team.mjs +94 -0
- package/esm/ai/src/team/team.mjs.map +1 -0
- package/esm/ai/src/tool/executable-as-tool.mjs +81 -0
- package/esm/ai/src/tool/executable-as-tool.mjs.map +1 -0
- package/esm/ai/src/tool/index.mjs +4 -0
- package/esm/ai/src/tool/tool.mjs +185 -0
- package/esm/ai/src/tool/tool.mjs.map +1 -0
- package/esm/ai/src/utils/compute-cost.mjs +112 -0
- package/esm/ai/src/utils/compute-cost.mjs.map +1 -0
- package/esm/ai/src/utils/extract-json-lenient.mjs +97 -0
- package/esm/ai/src/utils/extract-json-lenient.mjs.map +1 -0
- package/esm/ai/src/utils/extract-json-payload.mjs +39 -0
- package/esm/ai/src/utils/extract-json-payload.mjs.map +1 -0
- package/esm/ai/src/utils/generate-run-id.mjs +23 -0
- package/esm/ai/src/utils/generate-run-id.mjs.map +1 -0
- package/esm/ai/src/utils/index.mjs +12 -0
- package/esm/ai/src/utils/json-schema.mjs +89 -0
- package/esm/ai/src/utils/json-schema.mjs.map +1 -0
- package/esm/ai/src/utils/prepare-attachment-part.mjs +232 -0
- package/esm/ai/src/utils/prepare-attachment-part.mjs.map +1 -0
- package/esm/ai/src/utils/resolve-attachment.mjs +74 -0
- package/esm/ai/src/utils/resolve-attachment.mjs.map +1 -0
- package/esm/ai/src/utils/run-context.mjs +89 -0
- package/esm/ai/src/utils/run-context.mjs.map +1 -0
- package/esm/ai/src/utils/safe-json-parse.mjs +22 -0
- package/esm/ai/src/utils/safe-json-parse.mjs.map +1 -0
- package/esm/ai/src/utils/stamp-report-lineage.mjs +45 -0
- package/esm/ai/src/utils/stamp-report-lineage.mjs.map +1 -0
- package/esm/ai/src/vcr/cassette-io.mjs +57 -0
- package/esm/ai/src/vcr/cassette-io.mjs.map +1 -0
- package/esm/ai/src/vcr/errors.mjs +37 -0
- package/esm/ai/src/vcr/errors.mjs.map +1 -0
- package/esm/ai/src/vcr/hash-request.mjs +118 -0
- package/esm/ai/src/vcr/hash-request.mjs.map +1 -0
- package/esm/ai/src/vcr/index.mjs +5 -0
- package/esm/ai/src/vcr/vcr.mjs +248 -0
- package/esm/ai/src/vcr/vcr.mjs.map +1 -0
- package/esm/ai/src/workflow/as-tool.mjs +49 -0
- package/esm/ai/src/workflow/as-tool.mjs.map +1 -0
- package/esm/ai/src/workflow/cancellation.mjs +44 -0
- package/esm/ai/src/workflow/cancellation.mjs.map +1 -0
- package/esm/ai/src/workflow/emitter.mjs +40 -0
- package/esm/ai/src/workflow/emitter.mjs.map +1 -0
- package/esm/ai/src/workflow/engine.mjs +363 -0
- package/esm/ai/src/workflow/engine.mjs.map +1 -0
- package/esm/ai/src/workflow/index.mjs +5 -0
- package/esm/ai/src/workflow/retry.mjs +32 -0
- package/esm/ai/src/workflow/retry.mjs.map +1 -0
- package/esm/ai/src/workflow/router.mjs +56 -0
- package/esm/ai/src/workflow/router.mjs.map +1 -0
- package/esm/ai/src/workflow/run-scoped-emitter.mjs +32 -0
- package/esm/ai/src/workflow/run-scoped-emitter.mjs.map +1 -0
- package/esm/ai/src/workflow/signature.mjs +34 -0
- package/esm/ai/src/workflow/signature.mjs.map +1 -0
- package/esm/ai/src/workflow/snapshot.mjs +77 -0
- package/esm/ai/src/workflow/snapshot.mjs.map +1 -0
- package/esm/ai/src/workflow/state.mjs +37 -0
- package/esm/ai/src/workflow/state.mjs.map +1 -0
- package/esm/ai/src/workflow/step-runner.mjs +370 -0
- package/esm/ai/src/workflow/step-runner.mjs.map +1 -0
- package/esm/ai/src/workflow/step.mjs +37 -0
- package/esm/ai/src/workflow/step.mjs.map +1 -0
- package/esm/ai/src/workflow/workflow.mjs +122 -0
- package/esm/ai/src/workflow/workflow.mjs.map +1 -0
- package/esm/ai-openai/src/embedder.mjs +4 -0
- package/esm/ai-openai/src/index.mjs +4 -0
- package/esm/ai-openai/src/model.mjs +5 -0
- package/esm/ai-openai/src/sdk.mjs +6 -0
- package/esm/ai-openai/src/utils/index.mjs +4 -0
- package/esm/ai-openai/src/utils/to-openai-tools.mjs +3 -0
- package/esm/ai-openai/src/utils/wrap-openai-error.mjs +4 -0
- package/esm/application/application.d.mts +126 -4
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs +133 -0
- package/esm/application/application.mjs.map +1 -1
- package/esm/application/index.d.mts +1 -1
- package/esm/cli/commands/dev-server.command.mjs +1 -1
- package/esm/cli/commands/dev-server.command.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs +3 -4
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/types.d.mts +2 -1
- package/esm/cli/types.d.mts.map +1 -1
- package/esm/config/config-getter.mjs +5 -5
- package/esm/config/config-getter.mjs.map +1 -1
- package/esm/config/config-loader.mjs +2 -2
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/connectors/access-connector.mjs +2 -2
- package/esm/connectors/access-connector.mjs.map +1 -1
- package/esm/connectors/ai-connector.d.mts +43 -0
- package/esm/connectors/ai-connector.d.mts.map +1 -0
- package/esm/connectors/ai-connector.mjs +56 -0
- package/esm/connectors/ai-connector.mjs.map +1 -0
- package/esm/connectors/cache-connector.d.mts +5 -0
- package/esm/connectors/cache-connector.d.mts.map +1 -1
- package/esm/connectors/cache-connector.mjs +9 -2
- package/esm/connectors/cache-connector.mjs.map +1 -1
- package/esm/connectors/connectors-manager.d.mts +6 -2
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs +12 -3
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.mjs +2 -2
- package/esm/connectors/database-connector.mjs.map +1 -1
- package/esm/connectors/herald-connector.mjs +2 -2
- package/esm/connectors/herald-connector.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts +8 -0
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +40 -7
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/index.d.mts +1 -0
- package/esm/connectors/index.mjs +1 -0
- package/esm/connectors/logger-connector.mjs +2 -2
- package/esm/connectors/logger-connector.mjs.map +1 -1
- package/esm/connectors/mail-connector.mjs +2 -2
- package/esm/connectors/mail-connector.mjs.map +1 -1
- package/esm/connectors/notifications-connector.mjs +2 -2
- package/esm/connectors/notifications-connector.mjs.map +1 -1
- package/esm/connectors/socket-connector.d.mts +16 -1
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs +31 -8
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/storage.connector.d.mts +7 -0
- package/esm/connectors/storage.connector.d.mts.map +1 -1
- package/esm/connectors/storage.connector.mjs +7 -0
- package/esm/connectors/storage.connector.mjs.map +1 -1
- package/esm/connectors/types.d.mts +3 -2
- package/esm/connectors/types.d.mts.map +1 -1
- package/esm/connectors/types.mjs +1 -0
- package/esm/connectors/types.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +9 -14
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs +15 -3
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs +1 -1
- package/esm/generations/add-command.action.mjs +61 -12
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/stubs.mjs +31 -1
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/config.mjs +2 -2
- package/esm/http/config.mjs.map +1 -1
- package/esm/http/createHttpApplication.mjs +2 -2
- package/esm/http/createHttpApplication.mjs.map +1 -1
- package/esm/http/health.d.mts +57 -0
- package/esm/http/health.d.mts.map +1 -0
- package/esm/http/health.mjs +75 -0
- package/esm/http/health.mjs.map +1 -0
- package/esm/http/index.d.mts +2 -1
- package/esm/http/index.mjs +2 -1
- package/esm/http/middleware/cache-response-middleware.d.mts +1 -1
- package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs +15 -6
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs +2 -0
- package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs +9 -6
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +2 -2
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +6 -5
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/plugins.mjs +9 -9
- package/esm/http/plugins.mjs.map +1 -1
- package/esm/http/request.d.mts +9 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +15 -3
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +12 -0
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +24 -7
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts +16 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs +24 -4
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/types.d.mts +45 -0
- package/esm/http/types.d.mts.map +1 -1
- package/esm/index.d.mts +10 -5
- package/esm/index.mjs +10 -5
- package/esm/node_modules/langfuse/lib/index.mjs +1827 -0
- package/esm/node_modules/langfuse/lib/index.mjs.map +1 -0
- package/esm/node_modules/langfuse-core/lib/index.mjs +1770 -0
- package/esm/node_modules/langfuse-core/lib/index.mjs.map +1 -0
- package/esm/node_modules/mustache/mustache.mjs +587 -0
- package/esm/node_modules/mustache/mustache.mjs.map +1 -0
- package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs +180 -0
- package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map +1 -0
- package/esm/node_modules/openai/auth/workload-identity-auth.mjs +80 -0
- package/esm/node_modules/openai/auth/workload-identity-auth.mjs.map +1 -0
- package/esm/node_modules/openai/azure.mjs +82 -0
- package/esm/node_modules/openai/azure.mjs.map +1 -0
- package/esm/node_modules/openai/client.mjs +638 -0
- package/esm/node_modules/openai/client.mjs.map +1 -0
- package/esm/node_modules/openai/core/api-promise.mjs +75 -0
- package/esm/node_modules/openai/core/api-promise.mjs.map +1 -0
- package/esm/node_modules/openai/core/error.mjs +110 -0
- package/esm/node_modules/openai/core/error.mjs.map +1 -0
- package/esm/node_modules/openai/core/pagination.mjs +160 -0
- package/esm/node_modules/openai/core/pagination.mjs.map +1 -0
- package/esm/node_modules/openai/core/resource.mjs +10 -0
- package/esm/node_modules/openai/core/resource.mjs.map +1 -0
- package/esm/node_modules/openai/core/streaming.mjs +238 -0
- package/esm/node_modules/openai/core/streaming.mjs.map +1 -0
- package/esm/node_modules/openai/index.mjs +8 -0
- package/esm/node_modules/openai/internal/decoders/line.mjs +91 -0
- package/esm/node_modules/openai/internal/decoders/line.mjs.map +1 -0
- package/esm/node_modules/openai/internal/detect-platform.mjs +123 -0
- package/esm/node_modules/openai/internal/detect-platform.mjs.map +1 -0
- package/esm/node_modules/openai/internal/errors.mjs +26 -0
- package/esm/node_modules/openai/internal/errors.mjs.map +1 -0
- package/esm/node_modules/openai/internal/headers.mjs +65 -0
- package/esm/node_modules/openai/internal/headers.mjs.map +1 -0
- package/esm/node_modules/openai/internal/parse.mjs +41 -0
- package/esm/node_modules/openai/internal/parse.mjs.map +1 -0
- package/esm/node_modules/openai/internal/qs/formats.mjs +12 -0
- package/esm/node_modules/openai/internal/qs/formats.mjs.map +1 -0
- package/esm/node_modules/openai/internal/qs/stringify.mjs +179 -0
- package/esm/node_modules/openai/internal/qs/stringify.mjs.map +1 -0
- package/esm/node_modules/openai/internal/qs/utils.mjs +65 -0
- package/esm/node_modules/openai/internal/qs/utils.mjs.map +1 -0
- package/esm/node_modules/openai/internal/request-options.mjs +11 -0
- package/esm/node_modules/openai/internal/request-options.mjs.map +1 -0
- package/esm/node_modules/openai/internal/shims.mjs +77 -0
- package/esm/node_modules/openai/internal/shims.mjs.map +1 -0
- package/esm/node_modules/openai/internal/to-file.mjs +63 -0
- package/esm/node_modules/openai/internal/to-file.mjs.map +1 -0
- package/esm/node_modules/openai/internal/tslib.mjs +16 -0
- package/esm/node_modules/openai/internal/tslib.mjs.map +1 -0
- package/esm/node_modules/openai/internal/uploads.mjs +94 -0
- package/esm/node_modules/openai/internal/uploads.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/base64.mjs +22 -0
- package/esm/node_modules/openai/internal/utils/base64.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/bytes.mjs +26 -0
- package/esm/node_modules/openai/internal/utils/bytes.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/env.mjs +16 -0
- package/esm/node_modules/openai/internal/utils/env.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/log.mjs +58 -0
- package/esm/node_modules/openai/internal/utils/log.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/path.mjs +62 -0
- package/esm/node_modules/openai/internal/utils/path.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/query.mjs +10 -0
- package/esm/node_modules/openai/internal/utils/query.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/sleep.mjs +6 -0
- package/esm/node_modules/openai/internal/utils/sleep.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/uuid.mjs +18 -0
- package/esm/node_modules/openai/internal/utils/uuid.mjs.map +1 -0
- package/esm/node_modules/openai/internal/utils/values.mjs +41 -0
- package/esm/node_modules/openai/internal/utils/values.mjs.map +1 -0
- package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +247 -0
- package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map +1 -0
- package/esm/node_modules/openai/lib/AssistantStream.mjs +472 -0
- package/esm/node_modules/openai/lib/AssistantStream.mjs.map +1 -0
- package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs +26 -0
- package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs.map +1 -0
- package/esm/node_modules/openai/lib/ChatCompletionStream.mjs +423 -0
- package/esm/node_modules/openai/lib/ChatCompletionStream.mjs.map +1 -0
- package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +26 -0
- package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map +1 -0
- package/esm/node_modules/openai/lib/EventStream.mjs +163 -0
- package/esm/node_modules/openai/lib/EventStream.mjs.map +1 -0
- package/esm/node_modules/openai/lib/ResponsesParser.mjs +94 -0
- package/esm/node_modules/openai/lib/ResponsesParser.mjs.map +1 -0
- package/esm/node_modules/openai/lib/RunnableFunction.mjs +8 -0
- package/esm/node_modules/openai/lib/RunnableFunction.mjs.map +1 -0
- package/esm/node_modules/openai/lib/Util.mjs +19 -0
- package/esm/node_modules/openai/lib/Util.mjs.map +1 -0
- package/esm/node_modules/openai/lib/chatCompletionUtils.mjs +11 -0
- package/esm/node_modules/openai/lib/chatCompletionUtils.mjs.map +1 -0
- package/esm/node_modules/openai/lib/parser.mjs +88 -0
- package/esm/node_modules/openai/lib/parser.mjs.map +1 -0
- package/esm/node_modules/openai/lib/responses/ResponseStream.mjs +231 -0
- package/esm/node_modules/openai/lib/responses/ResponseStream.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/admin.mjs +15 -0
- package/esm/node_modules/openai/resources/admin/admin.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs +81 -0
- package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs +31 -0
- package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/certificates.mjs +153 -0
- package/esm/node_modules/openai/resources/admin/organization/certificates.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs +42 -0
- package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs +106 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs +88 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs +88 -0
- package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/invites.mjs +83 -0
- package/esm/node_modules/openai/resources/admin/organization/invites.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/organization.mjs +45 -0
- package/esm/node_modules/openai/resources/admin/organization/organization.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs +72 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs +78 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs +46 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +95 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +91 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +45 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +63 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs +137 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +51 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs +108 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs +112 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +106 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs +91 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs +118 -0
- package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/roles.mjs +96 -0
- package/esm/node_modules/openai/resources/admin/organization/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs +97 -0
- package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/usage.mjs +207 -0
- package/esm/node_modules/openai/resources/admin/organization/usage.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs +88 -0
- package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs.map +1 -0
- package/esm/node_modules/openai/resources/admin/organization/users/users.mjs +82 -0
- package/esm/node_modules/openai/resources/admin/organization/users/users.mjs.map +1 -0
- package/esm/node_modules/openai/resources/audio/audio.mjs +21 -0
- package/esm/node_modules/openai/resources/audio/audio.mjs.map +1 -0
- package/esm/node_modules/openai/resources/audio/speech.mjs +39 -0
- package/esm/node_modules/openai/resources/audio/speech.mjs.map +1 -0
- package/esm/node_modules/openai/resources/audio/transcriptions.mjs +22 -0
- package/esm/node_modules/openai/resources/audio/transcriptions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/audio/translations.mjs +21 -0
- package/esm/node_modules/openai/resources/audio/translations.mjs.map +1 -0
- package/esm/node_modules/openai/resources/batches.mjs +54 -0
- package/esm/node_modules/openai/resources/batches.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/assistants.mjs +78 -0
- package/esm/node_modules/openai/resources/beta/assistants.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/beta.mjs +24 -0
- package/esm/node_modules/openai/resources/beta/beta.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs +18 -0
- package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs +49 -0
- package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs +85 -0
- package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs +21 -0
- package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs +33 -0
- package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +33 -0
- package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/threads/messages.mjs +83 -0
- package/esm/node_modules/openai/resources/beta/threads/messages.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs +183 -0
- package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs +45 -0
- package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs.map +1 -0
- package/esm/node_modules/openai/resources/beta/threads/threads.mjs +101 -0
- package/esm/node_modules/openai/resources/beta/threads/threads.mjs.map +1 -0
- package/esm/node_modules/openai/resources/chat/chat.mjs +15 -0
- package/esm/node_modules/openai/resources/chat/chat.mjs.map +1 -0
- package/esm/node_modules/openai/resources/chat/completions/completions.mjs +123 -0
- package/esm/node_modules/openai/resources/chat/completions/completions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/chat/completions/index.mjs +7 -0
- package/esm/node_modules/openai/resources/chat/completions/messages.mjs +35 -0
- package/esm/node_modules/openai/resources/chat/completions/messages.mjs.map +1 -0
- package/esm/node_modules/openai/resources/chat/index.mjs +5 -0
- package/esm/node_modules/openai/resources/completions.mjs +20 -0
- package/esm/node_modules/openai/resources/completions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/containers/containers.mjs +57 -0
- package/esm/node_modules/openai/resources/containers/containers.mjs.map +1 -0
- package/esm/node_modules/openai/resources/containers/files/content.mjs +23 -0
- package/esm/node_modules/openai/resources/containers/files/content.mjs.map +1 -0
- package/esm/node_modules/openai/resources/containers/files/files.mjs +63 -0
- package/esm/node_modules/openai/resources/containers/files/files.mjs.map +1 -0
- package/esm/node_modules/openai/resources/conversations/conversations.mjs +57 -0
- package/esm/node_modules/openai/resources/conversations/conversations.mjs.map +1 -0
- package/esm/node_modules/openai/resources/conversations/items.mjs +57 -0
- package/esm/node_modules/openai/resources/conversations/items.mjs.map +1 -0
- package/esm/node_modules/openai/resources/embeddings.mjs +48 -0
- package/esm/node_modules/openai/resources/embeddings.mjs.map +1 -0
- package/esm/node_modules/openai/resources/evals/evals.mjs +73 -0
- package/esm/node_modules/openai/resources/evals/evals.mjs.map +1 -0
- package/esm/node_modules/openai/resources/evals/runs/output-items.mjs +35 -0
- package/esm/node_modules/openai/resources/evals/runs/output-items.mjs.map +1 -0
- package/esm/node_modules/openai/resources/evals/runs/runs.mjs +72 -0
- package/esm/node_modules/openai/resources/evals/runs/runs.mjs.map +1 -0
- package/esm/node_modules/openai/resources/files.mjs +111 -0
- package/esm/node_modules/openai/resources/files.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +15 -0
- package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +60 -0
- package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +15 -0
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +102 -0
- package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +24 -0
- package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +34 -0
- package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +148 -0
- package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map +1 -0
- package/esm/node_modules/openai/resources/fine-tuning/methods.mjs +8 -0
- package/esm/node_modules/openai/resources/fine-tuning/methods.mjs.map +1 -0
- package/esm/node_modules/openai/resources/graders/grader-models.mjs +8 -0
- package/esm/node_modules/openai/resources/graders/grader-models.mjs.map +1 -0
- package/esm/node_modules/openai/resources/graders/graders.mjs +15 -0
- package/esm/node_modules/openai/resources/graders/graders.mjs.map +1 -0
- package/esm/node_modules/openai/resources/images.mjs +46 -0
- package/esm/node_modules/openai/resources/images.mjs.map +1 -0
- package/esm/node_modules/openai/resources/index.mjs +27 -0
- package/esm/node_modules/openai/resources/models.mjs +44 -0
- package/esm/node_modules/openai/resources/models.mjs.map +1 -0
- package/esm/node_modules/openai/resources/moderations.mjs +23 -0
- package/esm/node_modules/openai/resources/moderations.mjs.map +1 -0
- package/esm/node_modules/openai/resources/realtime/calls.mjs +79 -0
- package/esm/node_modules/openai/resources/realtime/calls.mjs.map +1 -0
- package/esm/node_modules/openai/resources/realtime/client-secrets.mjs +39 -0
- package/esm/node_modules/openai/resources/realtime/client-secrets.mjs.map +1 -0
- package/esm/node_modules/openai/resources/realtime/realtime.mjs +18 -0
- package/esm/node_modules/openai/resources/realtime/realtime.mjs.map +1 -0
- package/esm/node_modules/openai/resources/responses/input-items.mjs +31 -0
- package/esm/node_modules/openai/resources/responses/input-items.mjs.map +1 -0
- package/esm/node_modules/openai/resources/responses/input-tokens.mjs +27 -0
- package/esm/node_modules/openai/resources/responses/input-tokens.mjs.map +1 -0
- package/esm/node_modules/openai/resources/responses/responses.mjs +110 -0
- package/esm/node_modules/openai/resources/responses/responses.mjs.map +1 -0
- package/esm/node_modules/openai/resources/skills/content.mjs +22 -0
- package/esm/node_modules/openai/resources/skills/content.mjs.map +1 -0
- package/esm/node_modules/openai/resources/skills/skills.mjs +69 -0
- package/esm/node_modules/openai/resources/skills/skills.mjs.map +1 -0
- package/esm/node_modules/openai/resources/skills/versions/content.mjs +23 -0
- package/esm/node_modules/openai/resources/skills/versions/content.mjs.map +1 -0
- package/esm/node_modules/openai/resources/skills/versions/versions.mjs +58 -0
- package/esm/node_modules/openai/resources/skills/versions/versions.mjs.map +1 -0
- package/esm/node_modules/openai/resources/uploads/parts.mjs +34 -0
- package/esm/node_modules/openai/resources/uploads/parts.mjs.map +1 -0
- package/esm/node_modules/openai/resources/uploads/uploads.mjs +84 -0
- package/esm/node_modules/openai/resources/uploads/uploads.mjs.map +1 -0
- package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs +126 -0
- package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs.map +1 -0
- package/esm/node_modules/openai/resources/vector-stores/files.mjs +147 -0
- package/esm/node_modules/openai/resources/vector-stores/files.mjs.map +1 -0
- package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs +87 -0
- package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs.map +1 -0
- package/esm/node_modules/openai/resources/videos.mjs +115 -0
- package/esm/node_modules/openai/resources/videos.mjs.map +1 -0
- package/esm/node_modules/openai/resources/webhooks/index.mjs +3 -0
- package/esm/node_modules/openai/resources/webhooks/webhooks.mjs +69 -0
- package/esm/node_modules/openai/resources/webhooks/webhooks.mjs.map +1 -0
- package/esm/node_modules/openai/resources/webhooks.mjs +4 -0
- package/esm/node_modules/openai/streaming.mjs +3 -0
- package/esm/node_modules/openai/version.mjs +6 -0
- package/esm/node_modules/openai/version.mjs.map +1 -0
- package/esm/production/production-builder.mjs +2 -2
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +9 -0
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs +32 -5
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +17 -3
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/repository.manager.d.mts +11 -1
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs +79 -25
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/router/route-registry.mjs +19 -10
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +7 -4
- package/esm/router/router.mjs.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs +48 -12
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.mjs +1 -1
- package/esm/storage/drivers/do-spaces-driver.mjs.map +1 -1
- package/esm/storage/drivers/local-driver.d.mts +8 -0
- package/esm/storage/drivers/local-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.mjs +19 -4
- package/esm/storage/drivers/local-driver.mjs.map +1 -1
- package/esm/storage/drivers/r2-driver.mjs +1 -1
- package/esm/storage/drivers/r2-driver.mjs.map +1 -1
- package/esm/storage/drivers/s3-driver.mjs +1 -1
- package/esm/storage/drivers/s3-driver.mjs.map +1 -1
- package/esm/storage/index.d.mts +4 -1
- package/esm/storage/index.mjs +3 -0
- package/esm/storage/scoped-storage.d.mts +8 -4
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +21 -6
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts +12 -4
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +23 -9
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/types.d.mts +33 -5
- package/esm/storage/types.d.mts.map +1 -1
- package/esm/storage/utils/contain-path.d.mts +23 -0
- package/esm/storage/utils/contain-path.d.mts.map +1 -0
- package/esm/storage/utils/contain-path.mjs +35 -0
- package/esm/storage/utils/contain-path.mjs.map +1 -0
- package/esm/storage/utils/safe-fetch.d.mts +68 -0
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -0
- package/esm/storage/utils/safe-fetch.mjs +205 -0
- package/esm/storage/utils/safe-fetch.mjs.map +1 -0
- package/esm/storage/utils/storage-error.d.mts +35 -0
- package/esm/storage/utils/storage-error.d.mts.map +1 -0
- package/esm/storage/utils/storage-error.mjs +17 -0
- package/esm/storage/utils/storage-error.mjs.map +1 -0
- package/esm/use-cases/use-case-pipeline.mjs +4 -1
- package/esm/use-cases/use-case-pipeline.mjs.map +1 -1
- package/esm/use-cases/use-case.mjs +12 -4
- package/esm/use-cases/use-case.mjs.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts +12 -4
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs +13 -3
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/environment.d.mts +6 -1
- package/esm/utils/environment.d.mts.map +1 -1
- package/esm/utils/environment.mjs.map +1 -1
- package/esm/utils/index.d.mts +1 -1
- package/esm/utils/npm-registry.d.mts +1 -1
- package/esm/utils/npm-registry.mjs +2 -2
- package/esm/utils/npm-registry.mjs.map +1 -1
- package/esm/utils/paths.mjs +2 -2
- package/esm/utils/paths.mjs.map +1 -1
- package/esm/validation/validateAll.mjs +2 -2
- package/esm/validation/validateAll.mjs.map +1 -1
- package/llms-full.txt +193 -3
- package/llms.txt +2 -1
- package/package.json +9 -9
- package/skills/add-connector/SKILL.md +6 -1
- package/skills/configure-app/SKILL.md +23 -0
- package/skills/health-checks/SKILL.md +98 -0
- package/skills/use-app-context/SKILL.md +62 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fallback-model.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/model/fallback-model.ts"],"sourcesContent":["import type {\n FallbackAttempt,\n FallbackModelContract,\n FallbackModelOptions,\n FallbackRetryPredicate,\n} from \"../contracts/fallback-model.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type {\n ModelCallOptions,\n ModelCapabilities,\n ModelContract,\n ModelResponse,\n ModelStreamChunk,\n} from \"../contracts/model.contract\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AIError } from \"../errors/ai-error\";\nimport type { AIErrorCode } from \"../errors/error-code.type\";\nimport { accumulateCost } from \"../utils/compute-cost\";\n\n/**\n * Error codes treated as transient — and therefore worth falling over\n * to the next model — when the caller does not supply an explicit\n * `retryOn`. Covers provider rate-limits, timeouts, and the generic\n * `PROVIDER_ERROR` catch-all that adapters throw for 5xx / unknown\n * network failures. Deliberately omits auth, invalid-request,\n * context-length, and content-filter: those fail identically on every\n * downstream model, so retrying only burns budget.\n */\nconst DEFAULT_RETRYABLE_CODES: readonly AIErrorCode[] = [\n \"PROVIDER_RATE_LIMIT\",\n \"PROVIDER_TIMEOUT\",\n \"PROVIDER_ERROR\",\n];\n\n/**\n * A `ModelContract` that wraps an ordered list of models and tries each\n * in turn, advancing to the next only when the current one fails with a\n * matching (transient) provider error.\n *\n * **Role.** A drop-in `ModelContract` for resilience: hand it to any\n * agent / workflow / supervisor in place of a single model and provider\n * outages, rate-limits, and timeouts transparently fail over to a\n * backup. Non-transient failures (bad key, oversized prompt, blocked\n * content) re-throw immediately rather than wastefully retrying.\n *\n * **What it owns / doesn't own.** Owns the ordered model list, the\n * retry decision, and per-call usage aggregation across attempted\n * models. Does NOT own retry/backoff timing (it advances instantly to\n * the next model — pair it with a backoff middleware if you want delay)\n * nor any provider I/O of its own; every call is delegated to a wrapped\n * model.\n *\n * **Streaming fall-over caveat.** `stream()` can only fail over while no\n * chunk has been emitted yet. Once the first `delta` / `tool-call`\n * reaches the consumer, the partial output cannot be un-sent, so a\n * mid-stream failure propagates instead of restarting on the next\n * model.\n *\n * @example\n * const model = fallbackModel([\n * ai.openai.model({ name: \"gpt-4o\" }),\n * ai.anthropic.model({ name: \"claude-3-5-sonnet\" }),\n * ]);\n * const agent = ai.agent({ model });\n *\n * @example\n * // custom retry predicate\n * const model = fallbackModel([primary, backup], {\n * retryOn: (error) => error instanceof ProviderError,\n * });\n */\nexport function fallbackModel(\n models: ModelContract[],\n options?: FallbackModelOptions,\n): FallbackModelContract {\n if (models.length === 0) {\n throw new AIError(\n \"PROVIDER_INVALID_REQUEST\",\n \"fallbackModel() requires at least one model in the chain.\",\n undefined,\n \"validation\",\n );\n }\n\n return new FallbackModel(models, resolveShouldRetry(options?.retryOn));\n}\n\n/**\n * Build the chain-advancement predicate from the caller's `retryOn`.\n * An array becomes a code membership test against an `AIError.code`; a\n * function is used verbatim; absence falls back to the transient\n * default set.\n */\nfunction resolveShouldRetry(\n retryOn: FallbackModelOptions[\"retryOn\"],\n): FallbackRetryPredicate {\n if (typeof retryOn === \"function\") {\n return retryOn;\n }\n\n const codes: readonly AIErrorCode[] = retryOn ?? DEFAULT_RETRYABLE_CODES;\n\n return (error: unknown): boolean => {\n return error instanceof AIError && codes.includes(error.code);\n };\n}\n\n/**\n * Add a successful call's usage into a running aggregate, mirroring the\n * agent's trip accumulation: scalar token counts sum, optional channels\n * sum only when present, and cost merges via `accumulateCost` so an\n * unpriced model never erases a priced sibling's cost.\n */\nfunction aggregateUsage(total: Usage, next: Usage): void {\n total.input += next.input;\n total.output += next.output;\n total.total += next.total;\n\n if (next.cachedTokens !== undefined) {\n total.cachedTokens = (total.cachedTokens ?? 0) + next.cachedTokens;\n }\n\n if (next.reasoningTokens !== undefined) {\n total.reasoningTokens = (total.reasoningTokens ?? 0) + next.reasoningTokens;\n }\n\n if (next.cacheWriteTokens !== undefined) {\n total.cacheWriteTokens = (total.cacheWriteTokens ?? 0) + next.cacheWriteTokens;\n }\n\n total.cost = accumulateCost(total.cost, next.cost);\n}\n\n/**\n * Internal `ModelContract` implementation backing {@link fallbackModel}.\n *\n * Long-lived (its identity, capabilities, and pricing front the primary\n * model for the wrapper's whole lifetime) so it is a class rather than a\n * closure. Per-call mutable state (the usage aggregate, the attempt log)\n * lives in {@link FallbackRun}, instantiated fresh on every\n * `complete()` / `stream()` so concurrent calls never share bookkeeping.\n */\nclass FallbackModel implements FallbackModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities?: ModelCapabilities;\n public readonly pricing?: ModelContract[\"pricing\"];\n\n private latestAttempts: FallbackAttempt[] = [];\n\n public constructor(\n private readonly models: ModelContract[],\n private readonly shouldRetry: FallbackRetryPredicate,\n ) {\n const primary = models[0]!;\n\n this.name = primary.name;\n this.provider = primary.provider;\n this.capabilities = primary.capabilities;\n this.pricing = primary.pricing;\n }\n\n /**\n * Models that failed with a chain-advancing error during the most\n * recent `complete()` / `stream()` call, in attempt order. Empty when\n * the primary model succeeded outright. Overwritten on each call.\n */\n public get lastAttempts(): FallbackAttempt[] {\n return this.latestAttempts;\n }\n\n public async complete(\n messages: Message[],\n options?: ModelCallOptions,\n ): Promise<ModelResponse> {\n const run = new FallbackRun(this.models, this.shouldRetry);\n const response = await run.complete(messages, options);\n\n this.latestAttempts = run.attempts;\n\n return response;\n }\n\n public stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n const run = new FallbackRun(this.models, this.shouldRetry);\n\n return run.stream(messages, options, (attempts) => {\n this.latestAttempts = attempts;\n });\n }\n}\n\n/**\n * Per-call execution of the fallback chain. Holds the usage aggregate\n * and the attempt log for a single `complete()` / `stream()` invocation\n * so the long-lived {@link FallbackModel} stays free of shared mutable\n * state across concurrent calls.\n */\nclass FallbackRun {\n public readonly attempts: FallbackAttempt[] = [];\n\n private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n\n public constructor(\n private readonly models: ModelContract[],\n private readonly shouldRetry: FallbackRetryPredicate,\n ) {}\n\n /**\n * Try each model's `complete()` in order. On a chain-advancing error,\n * record the attempt and move to the next; on the last model (or a\n * non-retryable error) re-throw the underlying error verbatim so the\n * caller still sees a typed `AIError` with its original code.\n */\n public async complete(\n messages: Message[],\n options?: ModelCallOptions,\n ): Promise<ModelResponse> {\n for (let index = 0; index < this.models.length; index++) {\n const model = this.models[index]!;\n const isLast = index === this.models.length - 1;\n\n try {\n const response = await model.complete(messages, options);\n\n aggregateUsage(this.usage, response.usage);\n\n return { ...response, usage: this.usage };\n } catch (error) {\n if (isLast || !this.shouldRetry(error)) {\n throw error;\n }\n\n this.recordAttempt(model, error);\n }\n }\n\n throw new AIError(\n \"PROVIDER_ERROR\",\n \"fallbackModel() exhausted its chain without producing a response.\",\n undefined,\n \"provider\",\n );\n }\n\n /**\n * Try each model's `stream()` in order. Fall-over is only attempted\n * while no chunk has been emitted yet for the current model — once the\n * consumer has seen a `delta` / `tool-call`, a mid-stream failure\n * propagates instead of restarting (partial output cannot be un-sent).\n * The aggregated usage replaces the `done` chunk's usage so the caller\n * sees the chain total.\n */\n public async *stream(\n messages: Message[],\n options: ModelCallOptions | undefined,\n onSettle: (attempts: FallbackAttempt[]) => void,\n ): AsyncIterable<ModelStreamChunk> {\n try {\n for (let index = 0; index < this.models.length; index++) {\n const model = this.models[index]!;\n const isLast = index === this.models.length - 1;\n let emitted = false;\n\n try {\n for await (const chunk of model.stream(messages, options)) {\n if (chunk.type === \"done\") {\n aggregateUsage(this.usage, chunk.usage);\n\n yield { ...chunk, usage: this.usage };\n return;\n }\n\n emitted = true;\n\n yield chunk;\n }\n\n return;\n } catch (error) {\n if (emitted || isLast || !this.shouldRetry(error)) {\n throw error;\n }\n\n this.recordAttempt(model, error);\n }\n }\n\n throw new AIError(\n \"PROVIDER_ERROR\",\n \"fallbackModel() exhausted its chain without producing a response.\",\n undefined,\n \"provider\",\n );\n } finally {\n onSettle(this.attempts);\n }\n }\n\n private recordAttempt(model: ModelContract, error: unknown): void {\n this.attempts.push({\n modelName: model.name,\n provider: model.provider,\n error,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA4BA,MAAM,0BAAkD;CACtD;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,cACd,QACA,SACuB;CACvB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,QACR,4BACA,6DACA,QACA,YACF;CAGF,OAAO,IAAI,cAAc,QAAQ,mBAAmB,SAAS,OAAO,CAAC;AACvE;;;;;;;AAQA,SAAS,mBACP,SACwB;CACxB,IAAI,OAAO,YAAY,YACrB,OAAO;CAGT,MAAM,QAAgC,WAAW;CAEjD,QAAQ,UAA4B;EAClC,OAAO,iBAAiB,WAAW,MAAM,SAAS,MAAM,IAAI;CAC9D;AACF;;;;;;;AAQA,SAAS,eAAe,OAAc,MAAmB;CACvD,MAAM,SAAS,KAAK;CACpB,MAAM,UAAU,KAAK;CACrB,MAAM,SAAS,KAAK;CAEpB,IAAI,KAAK,iBAAiB,QACxB,MAAM,gBAAgB,MAAM,gBAAgB,KAAK,KAAK;CAGxD,IAAI,KAAK,oBAAoB,QAC3B,MAAM,mBAAmB,MAAM,mBAAmB,KAAK,KAAK;CAG9D,IAAI,KAAK,qBAAqB,QAC5B,MAAM,oBAAoB,MAAM,oBAAoB,KAAK,KAAK;CAGhE,MAAM,OAAO,eAAe,MAAM,MAAM,KAAK,IAAI;AACnD;;;;;;;;;;AAWA,IAAM,gBAAN,MAAqD;CAQnD,AAAO,YACL,AAAiB,QACjB,AAAiB,aACjB;EAFiB;EACA;wBAJyB,CAAC;EAM3C,MAAM,UAAU,OAAO;EAEvB,KAAK,OAAO,QAAQ;EACpB,KAAK,WAAW,QAAQ;EACxB,KAAK,eAAe,QAAQ;EAC5B,KAAK,UAAU,QAAQ;CACzB;;;;;;CAOA,IAAW,eAAkC;EAC3C,OAAO,KAAK;CACd;CAEA,MAAa,SACX,UACA,SACwB;EACxB,MAAM,MAAM,IAAI,YAAY,KAAK,QAAQ,KAAK,WAAW;EACzD,MAAM,WAAW,MAAM,IAAI,SAAS,UAAU,OAAO;EAErD,KAAK,iBAAiB,IAAI;EAE1B,OAAO;CACT;CAEA,AAAO,OACL,UACA,SACiC;EAGjC,OAAO,IAFS,YAAY,KAAK,QAAQ,KAAK,WAErC,CAAC,CAAC,OAAO,UAAU,UAAU,aAAa;GACjD,KAAK,iBAAiB;EACxB,CAAC;CACH;AACF;;;;;;;AAQA,IAAM,cAAN,MAAkB;CAKhB,AAAO,YACL,AAAiB,QACjB,AAAiB,aACjB;EAFiB;EACA;kBAN2B,CAAC;eAEf;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;CAK7D;;;;;;;CAQH,MAAa,SACX,UACA,SACwB;EACxB,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,OAAO,QAAQ,SAAS;GACvD,MAAM,QAAQ,KAAK,OAAO;GAC1B,MAAM,SAAS,UAAU,KAAK,OAAO,SAAS;GAE9C,IAAI;IACF,MAAM,WAAW,MAAM,MAAM,SAAS,UAAU,OAAO;IAEvD,eAAe,KAAK,OAAO,SAAS,KAAK;IAEzC,OAAO;KAAE,GAAG;KAAU,OAAO,KAAK;IAAM;GAC1C,SAAS,OAAO;IACd,IAAI,UAAU,CAAC,KAAK,YAAY,KAAK,GACnC,MAAM;IAGR,KAAK,cAAc,OAAO,KAAK;GACjC;EACF;EAEA,MAAM,IAAI,QACR,kBACA,qEACA,QACA,UACF;CACF;;;;;;;;;CAUA,OAAc,OACZ,UACA,SACA,UACiC;EACjC,IAAI;GACF,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,OAAO,QAAQ,SAAS;IACvD,MAAM,QAAQ,KAAK,OAAO;IAC1B,MAAM,SAAS,UAAU,KAAK,OAAO,SAAS;IAC9C,IAAI,UAAU;IAEd,IAAI;KACF,WAAW,MAAM,SAAS,MAAM,OAAO,UAAU,OAAO,GAAG;MACzD,IAAI,MAAM,SAAS,QAAQ;OACzB,eAAe,KAAK,OAAO,MAAM,KAAK;OAEtC,MAAM;QAAE,GAAG;QAAO,OAAO,KAAK;OAAM;OACpC;MACF;MAEA,UAAU;MAEV,MAAM;KACR;KAEA;IACF,SAAS,OAAO;KACd,IAAI,WAAW,UAAU,CAAC,KAAK,YAAY,KAAK,GAC9C,MAAM;KAGR,KAAK,cAAc,OAAO,KAAK;IACjC;GACF;GAEA,MAAM,IAAI,QACR,kBACA,qEACA,QACA,UACF;EACF,UAAU;GACR,SAAS,KAAK,QAAQ;EACxB;CACF;CAEA,AAAQ,cAAc,OAAsB,OAAsB;EAChE,KAAK,SAAS,KAAK;GACjB,WAAW,MAAM;GACjB,UAAU,MAAM;GAChB;EACF,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
//#region ../@warlock.js/ai/src/object-stream/parse-partial-json.ts
|
|
2
|
+
/**
|
|
3
|
+
* Best-effort parse of a possibly-truncated JSON string into the value it
|
|
4
|
+
* is "on its way to" becoming. Used by {@link streamObject} to emit a
|
|
5
|
+
* partial object snapshot from each streamed delta before the full reply
|
|
6
|
+
* has arrived.
|
|
7
|
+
*
|
|
8
|
+
* Returns `undefined` when the prefix can't yet be coerced into a value
|
|
9
|
+
* (so the caller simply waits for more text). The FINAL parse in
|
|
10
|
+
* `streamObject` is always strict `JSON.parse` — this tolerant parser only
|
|
11
|
+
* powers the in-flight snapshots, so a too-clever completion never affects
|
|
12
|
+
* the authoritative result.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* parsePartialJson('{"name":"Al'); // → { name: "Al" }
|
|
16
|
+
* parsePartialJson('{"items":[1,2,'); // → { items: [1, 2] }
|
|
17
|
+
* parsePartialJson('{"a":1,"b"'); // → { a: 1 } (drops the dangling key)
|
|
18
|
+
*/
|
|
19
|
+
function parsePartialJson(text) {
|
|
20
|
+
const trimmed = text.trim();
|
|
21
|
+
if (!trimmed) return void 0;
|
|
22
|
+
const direct = tryParse(trimmed);
|
|
23
|
+
if (direct.ok) return direct.value;
|
|
24
|
+
const completed = completePartialJson(trimmed);
|
|
25
|
+
if (completed === void 0) return void 0;
|
|
26
|
+
const parsed = tryParse(completed);
|
|
27
|
+
return parsed.ok ? parsed.value : void 0;
|
|
28
|
+
}
|
|
29
|
+
function tryParse(text) {
|
|
30
|
+
try {
|
|
31
|
+
return {
|
|
32
|
+
ok: true,
|
|
33
|
+
value: JSON.parse(text)
|
|
34
|
+
};
|
|
35
|
+
} catch {
|
|
36
|
+
return { ok: false };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Reconstruct a parseable JSON string from a truncated prefix by closing
|
|
41
|
+
* open strings/containers and trimming dangling separators, keys, and
|
|
42
|
+
* partial literals. Tries the most faithful completion first, then falls
|
|
43
|
+
* back to dropping the unfinished tail.
|
|
44
|
+
*/
|
|
45
|
+
function completePartialJson(text) {
|
|
46
|
+
const stack = [];
|
|
47
|
+
let inString = false;
|
|
48
|
+
let escaped = false;
|
|
49
|
+
for (const ch of text) {
|
|
50
|
+
if (inString) {
|
|
51
|
+
if (escaped) escaped = false;
|
|
52
|
+
else if (ch === "\\") escaped = true;
|
|
53
|
+
else if (ch === "\"") inString = false;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (ch === "\"") inString = true;
|
|
57
|
+
else if (ch === "{" || ch === "[") stack.push(ch);
|
|
58
|
+
else if (ch === "}" || ch === "]") stack.pop();
|
|
59
|
+
}
|
|
60
|
+
const closers = () => stack.map((c) => c === "{" ? "}" : "]").reverse().join("");
|
|
61
|
+
let core = text;
|
|
62
|
+
if (inString) core += "\"";
|
|
63
|
+
core = core.replace(/\s+$/, "");
|
|
64
|
+
if (core.endsWith(",")) core = core.slice(0, -1);
|
|
65
|
+
if (core.endsWith(":")) core += "null";
|
|
66
|
+
const attempts = [core + closers()];
|
|
67
|
+
if (stack[stack.length - 1] === "{") {
|
|
68
|
+
const droppedKey = core.replace(/,?\s*"(?:[^"\\]|\\.)*"\s*$/, "");
|
|
69
|
+
attempts.push(droppedKey.replace(/,\s*$/, "") + closers());
|
|
70
|
+
}
|
|
71
|
+
const droppedLiteral = core.replace(/[:,]?\s*[A-Za-z0-9.+\-eE]+$/, (match) => match.trimStart().startsWith(":") ? ":null" : "");
|
|
72
|
+
attempts.push(droppedLiteral.replace(/,\s*$/, "") + closers());
|
|
73
|
+
for (const candidate of attempts) if (tryParse(candidate).ok) return candidate;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
//#endregion
|
|
77
|
+
export { parsePartialJson };
|
|
78
|
+
//# sourceMappingURL=parse-partial-json.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse-partial-json.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/object-stream/parse-partial-json.ts"],"sourcesContent":["/**\n * Best-effort parse of a possibly-truncated JSON string into the value it\n * is \"on its way to\" becoming. Used by {@link streamObject} to emit a\n * partial object snapshot from each streamed delta before the full reply\n * has arrived.\n *\n * Returns `undefined` when the prefix can't yet be coerced into a value\n * (so the caller simply waits for more text). The FINAL parse in\n * `streamObject` is always strict `JSON.parse` — this tolerant parser only\n * powers the in-flight snapshots, so a too-clever completion never affects\n * the authoritative result.\n *\n * @example\n * parsePartialJson('{\"name\":\"Al'); // → { name: \"Al\" }\n * parsePartialJson('{\"items\":[1,2,'); // → { items: [1, 2] }\n * parsePartialJson('{\"a\":1,\"b\"'); // → { a: 1 } (drops the dangling key)\n */\nexport function parsePartialJson(text: string): unknown | undefined {\n const trimmed = text.trim();\n if (!trimmed) return undefined;\n\n // Fast path: already-valid JSON.\n const direct = tryParse(trimmed);\n if (direct.ok) return direct.value;\n\n const completed = completePartialJson(trimmed);\n if (completed === undefined) return undefined;\n\n const parsed = tryParse(completed);\n return parsed.ok ? parsed.value : undefined;\n}\n\nfunction tryParse(text: string): { ok: true; value: unknown } | { ok: false } {\n try {\n return { ok: true, value: JSON.parse(text) };\n } catch {\n return { ok: false };\n }\n}\n\n/**\n * Reconstruct a parseable JSON string from a truncated prefix by closing\n * open strings/containers and trimming dangling separators, keys, and\n * partial literals. Tries the most faithful completion first, then falls\n * back to dropping the unfinished tail.\n */\nfunction completePartialJson(text: string): string | undefined {\n const stack: Array<\"{\" | \"[\"> = [];\n let inString = false;\n let escaped = false;\n\n for (const ch of text) {\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === \"\\\\\") escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === \"{\" || ch === \"[\") stack.push(ch);\n else if (ch === \"}\" || ch === \"]\") stack.pop();\n }\n\n const closers = () =>\n stack\n .map(c => (c === \"{\" ? \"}\" : \"]\"))\n .reverse()\n .join(\"\");\n\n // Faithful completion: close an open string, drop a trailing comma,\n // fill a dangling `key:` with null, then close containers.\n let core = text;\n if (inString) core += '\"';\n core = core.replace(/\\s+$/, \"\");\n if (core.endsWith(\",\")) core = core.slice(0, -1);\n if (core.endsWith(\":\")) core += \"null\";\n\n const attempts: string[] = [core + closers()];\n\n // Fallback 1: drop a dangling object key (a `\"...\"` with no value yet).\n if (stack[stack.length - 1] === \"{\") {\n const droppedKey = core.replace(/,?\\s*\"(?:[^\"\\\\]|\\\\.)*\"\\s*$/, \"\");\n attempts.push(droppedKey.replace(/,\\s*$/, \"\") + closers());\n }\n\n // Fallback 2: drop a partial trailing literal / number (e.g. `tr`, `12.`).\n const droppedLiteral = core.replace(/[:,]?\\s*[A-Za-z0-9.+\\-eE]+$/, match =>\n match.trimStart().startsWith(\":\") ? \":null\" : \"\",\n );\n attempts.push(droppedLiteral.replace(/,\\s*$/, \"\") + closers());\n\n for (const candidate of attempts) {\n if (tryParse(candidate).ok) return candidate;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,MAAmC;CAClE,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,SAAS,OAAO;CAGrB,MAAM,SAAS,SAAS,OAAO;CAC/B,IAAI,OAAO,IAAI,OAAO,OAAO;CAE7B,MAAM,YAAY,oBAAoB,OAAO;CAC7C,IAAI,cAAc,QAAW,OAAO;CAEpC,MAAM,SAAS,SAAS,SAAS;CACjC,OAAO,OAAO,KAAK,OAAO,QAAQ;AACpC;AAEA,SAAS,SAAS,MAA4D;CAC5E,IAAI;EACF,OAAO;GAAE,IAAI;GAAM,OAAO,KAAK,MAAM,IAAI;EAAE;CAC7C,QAAQ;EACN,OAAO,EAAE,IAAI,MAAM;CACrB;AACF;;;;;;;AAQA,SAAS,oBAAoB,MAAkC;CAC7D,MAAM,QAA0B,CAAC;CACjC,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,MAAM,MAAM,MAAM;EACrB,IAAI,UAAU;GACZ,IAAI,SAAS,UAAU;QAClB,IAAI,OAAO,MAAM,UAAU;QAC3B,IAAI,OAAO,MAAK,WAAW;GAChC;EACF;EACA,IAAI,OAAO,MAAK,WAAW;OACtB,IAAI,OAAO,OAAO,OAAO,KAAK,MAAM,KAAK,EAAE;OAC3C,IAAI,OAAO,OAAO,OAAO,KAAK,MAAM,IAAI;CAC/C;CAEA,MAAM,gBACJ,MACG,KAAI,MAAM,MAAM,MAAM,MAAM,GAAI,CAAC,CACjC,QAAQ,CAAC,CACT,KAAK,EAAE;CAIZ,IAAI,OAAO;CACX,IAAI,UAAU,QAAQ;CACtB,OAAO,KAAK,QAAQ,QAAQ,EAAE;CAC9B,IAAI,KAAK,SAAS,GAAG,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE;CAC/C,IAAI,KAAK,SAAS,GAAG,GAAG,QAAQ;CAEhC,MAAM,WAAqB,CAAC,OAAO,QAAQ,CAAC;CAG5C,IAAI,MAAM,MAAM,SAAS,OAAO,KAAK;EACnC,MAAM,aAAa,KAAK,QAAQ,8BAA8B,EAAE;EAChE,SAAS,KAAK,WAAW,QAAQ,SAAS,EAAE,IAAI,QAAQ,CAAC;CAC3D;CAGA,MAAM,iBAAiB,KAAK,QAAQ,gCAA+B,UACjE,MAAM,UAAU,CAAC,CAAC,WAAW,GAAG,IAAI,UAAU,EAChD;CACA,SAAS,KAAK,eAAe,QAAQ,SAAS,EAAE,IAAI,QAAQ,CAAC;CAE7D,KAAK,MAAM,aAAa,UACtB,IAAI,SAAS,SAAS,CAAC,CAAC,IAAI,OAAO;AAIvC"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { SchemaValidationError } from "../errors/schema-validation-error.mjs";
|
|
2
|
+
import "../errors/index.mjs";
|
|
3
|
+
import { parsePartialJson } from "./parse-partial-json.mjs";
|
|
4
|
+
|
|
5
|
+
//#region ../@warlock.js/ai/src/object-stream/stream-object.ts
|
|
6
|
+
/**
|
|
7
|
+
* Stream a structured object: emit raw token deltas, progressively-parsed
|
|
8
|
+
* partial-object snapshots, and a final strictly-validated object — the
|
|
9
|
+
* first-class structured-output streaming primitive (A1). Reuses the
|
|
10
|
+
* model's existing `stream()` seam; the partial snapshots come from a
|
|
11
|
+
* tolerant {@link parsePartialJson}, while the terminal `done` event is a
|
|
12
|
+
* strict `JSON.parse` + schema validation, so an over-eager partial parse
|
|
13
|
+
* never affects the authoritative result.
|
|
14
|
+
*
|
|
15
|
+
* Pair it with a `structuredOutput`-capable model and a `responseSchema`
|
|
16
|
+
* (via `options`) for the cleanest JSON; otherwise prompt the model to
|
|
17
|
+
* reply with JSON only.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* for await (const event of streamObject({ model, messages, schema })) {
|
|
21
|
+
* if (event.type === "partial") render(event.value); // live UI
|
|
22
|
+
* if (event.type === "done" && event.valid) save(event.value); // final
|
|
23
|
+
* }
|
|
24
|
+
*/
|
|
25
|
+
async function* streamObject(params) {
|
|
26
|
+
const { model, messages, schema, options } = params;
|
|
27
|
+
let accumulated = "";
|
|
28
|
+
let lastPartialKey;
|
|
29
|
+
let usage = {
|
|
30
|
+
input: 0,
|
|
31
|
+
output: 0,
|
|
32
|
+
total: 0
|
|
33
|
+
};
|
|
34
|
+
for await (const chunk of model.stream(messages, options)) if (chunk.type === "delta") {
|
|
35
|
+
accumulated += chunk.content;
|
|
36
|
+
yield {
|
|
37
|
+
type: "text-delta",
|
|
38
|
+
delta: chunk.content
|
|
39
|
+
};
|
|
40
|
+
const partial = parsePartialJson(accumulated);
|
|
41
|
+
if (partial !== void 0) {
|
|
42
|
+
const key = safeStringify(partial);
|
|
43
|
+
if (key !== lastPartialKey) {
|
|
44
|
+
lastPartialKey = key;
|
|
45
|
+
yield {
|
|
46
|
+
type: "partial",
|
|
47
|
+
value: partial
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
} else if (chunk.type === "done") usage = chunk.usage;
|
|
52
|
+
yield await finalize(accumulated, schema, usage);
|
|
53
|
+
}
|
|
54
|
+
/** Strict parse + schema validation of the complete streamed text. */
|
|
55
|
+
async function finalize(text, schema, usage) {
|
|
56
|
+
const cleaned = stripJsonFences(text).trim();
|
|
57
|
+
let parsed;
|
|
58
|
+
try {
|
|
59
|
+
parsed = JSON.parse(cleaned);
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
return {
|
|
62
|
+
type: "done",
|
|
63
|
+
valid: false,
|
|
64
|
+
error: new SchemaValidationError("streamObject: the final streamed output was not valid JSON", { cause }),
|
|
65
|
+
usage
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const result = await schema["~standard"].validate(parsed);
|
|
69
|
+
if ("issues" in result && result.issues) return {
|
|
70
|
+
type: "done",
|
|
71
|
+
valid: false,
|
|
72
|
+
error: new SchemaValidationError("streamObject: the streamed object failed schema validation", { issues: result.issues }),
|
|
73
|
+
usage
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
type: "done",
|
|
77
|
+
valid: true,
|
|
78
|
+
value: result.value,
|
|
79
|
+
usage
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Strip a leading/trailing ```json fence the model may wrap output in. */
|
|
83
|
+
function stripJsonFences(text) {
|
|
84
|
+
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
|
|
85
|
+
return fenced ? fenced[1] : text;
|
|
86
|
+
}
|
|
87
|
+
function safeStringify(value) {
|
|
88
|
+
try {
|
|
89
|
+
return JSON.stringify(value);
|
|
90
|
+
} catch {
|
|
91
|
+
return String(value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
//#endregion
|
|
96
|
+
export { streamObject };
|
|
97
|
+
//# sourceMappingURL=stream-object.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-object.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/object-stream/stream-object.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { ModelCallOptions, ModelContract } from \"../contracts/model.contract\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AIError, SchemaValidationError } from \"../errors\";\nimport { parsePartialJson } from \"./parse-partial-json\";\n\n/**\n * One event in a {@link streamObject} run.\n *\n * - `text-delta` — the raw token text as it streams (for a \"typing\" view).\n * - `partial` — a best-effort snapshot of the object so far, re-parsed\n * from the accumulated text on each delta (only emitted when it changed).\n * - `done` — terminal: the final text is strictly parsed and validated\n * against the schema. `valid` + `value` on success; `valid: false` +\n * `error` when the output wasn't valid JSON or failed the schema.\n */\nexport type ObjectStreamEvent<T> =\n | { type: \"text-delta\"; delta: string }\n | { type: \"partial\"; value: unknown }\n | { type: \"done\"; valid: true; value: T; usage: Usage }\n | { type: \"done\"; valid: false; error: AIError; usage: Usage };\n\n/** Parameters for {@link streamObject}. */\nexport type StreamObjectParams<T> = {\n /** The model to stream from (e.g. `sdk.model({ name })`). */\n model: ModelContract;\n /** The prompt messages. */\n messages: Message[];\n /** Standard Schema the final object is validated against. */\n schema: StandardSchemaV1<T>;\n /** Extra model call options (e.g. `responseSchema`, `temperature`). */\n options?: ModelCallOptions;\n};\n\n/**\n * Stream a structured object: emit raw token deltas, progressively-parsed\n * partial-object snapshots, and a final strictly-validated object — the\n * first-class structured-output streaming primitive (A1). Reuses the\n * model's existing `stream()` seam; the partial snapshots come from a\n * tolerant {@link parsePartialJson}, while the terminal `done` event is a\n * strict `JSON.parse` + schema validation, so an over-eager partial parse\n * never affects the authoritative result.\n *\n * Pair it with a `structuredOutput`-capable model and a `responseSchema`\n * (via `options`) for the cleanest JSON; otherwise prompt the model to\n * reply with JSON only.\n *\n * @example\n * for await (const event of streamObject({ model, messages, schema })) {\n * if (event.type === \"partial\") render(event.value); // live UI\n * if (event.type === \"done\" && event.valid) save(event.value); // final\n * }\n */\nexport async function* streamObject<T>(\n params: StreamObjectParams<T>,\n): AsyncIterable<ObjectStreamEvent<T>> {\n const { model, messages, schema, options } = params;\n\n let accumulated = \"\";\n let lastPartialKey: string | undefined;\n let usage: Usage = { input: 0, output: 0, total: 0 };\n\n for await (const chunk of model.stream(messages, options)) {\n if (chunk.type === \"delta\") {\n accumulated += chunk.content;\n yield { type: \"text-delta\", delta: chunk.content };\n\n const partial = parsePartialJson(accumulated);\n if (partial !== undefined) {\n const key = safeStringify(partial);\n if (key !== lastPartialKey) {\n lastPartialKey = key;\n yield { type: \"partial\", value: partial };\n }\n }\n } else if (chunk.type === \"done\") {\n usage = chunk.usage;\n }\n }\n\n yield await finalize(accumulated, schema, usage);\n}\n\n/** Strict parse + schema validation of the complete streamed text. */\nasync function finalize<T>(\n text: string,\n schema: StandardSchemaV1<T>,\n usage: Usage,\n): Promise<ObjectStreamEvent<T>> {\n const cleaned = stripJsonFences(text).trim();\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(cleaned);\n } catch (cause) {\n return {\n type: \"done\",\n valid: false,\n error: new SchemaValidationError(\n \"streamObject: the final streamed output was not valid JSON\",\n { cause },\n ),\n usage,\n };\n }\n\n const result = await schema[\"~standard\"].validate(parsed);\n if (\"issues\" in result && result.issues) {\n return {\n type: \"done\",\n valid: false,\n error: new SchemaValidationError(\n \"streamObject: the streamed object failed schema validation\",\n { issues: result.issues },\n ),\n usage,\n };\n }\n\n return { type: \"done\", valid: true, value: (result as { value: T }).value, usage };\n}\n\n/** Collect a {@link streamObject} run down to just its terminal event. */\nexport async function collectStreamObject<T>(\n stream: AsyncIterable<ObjectStreamEvent<T>>,\n): Promise<Extract<ObjectStreamEvent<T>, { type: \"done\" }>> {\n let done: Extract<ObjectStreamEvent<T>, { type: \"done\" }> | undefined;\n for await (const event of stream) {\n if (event.type === \"done\") done = event;\n }\n if (!done) {\n throw new SchemaValidationError(\"streamObject: stream ended without a terminal event\");\n }\n return done;\n}\n\n/** Strip a leading/trailing ```json fence the model may wrap output in. */\nfunction stripJsonFences(text: string): string {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/i);\n return fenced ? fenced[1] : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsDA,gBAAuB,aACrB,QACqC;CACrC,MAAM,EAAE,OAAO,UAAU,QAAQ,YAAY;CAE7C,IAAI,cAAc;CAClB,IAAI;CACJ,IAAI,QAAe;EAAE,OAAO;EAAG,QAAQ;EAAG,OAAO;CAAE;CAEnD,WAAW,MAAM,SAAS,MAAM,OAAO,UAAU,OAAO,GACtD,IAAI,MAAM,SAAS,SAAS;EAC1B,eAAe,MAAM;EACrB,MAAM;GAAE,MAAM;GAAc,OAAO,MAAM;EAAQ;EAEjD,MAAM,UAAU,iBAAiB,WAAW;EAC5C,IAAI,YAAY,QAAW;GACzB,MAAM,MAAM,cAAc,OAAO;GACjC,IAAI,QAAQ,gBAAgB;IAC1B,iBAAiB;IACjB,MAAM;KAAE,MAAM;KAAW,OAAO;IAAQ;GAC1C;EACF;CACF,OAAO,IAAI,MAAM,SAAS,QACxB,QAAQ,MAAM;CAIlB,MAAM,MAAM,SAAS,aAAa,QAAQ,KAAK;AACjD;;AAGA,eAAe,SACb,MACA,QACA,OAC+B;CAC/B,MAAM,UAAU,gBAAgB,IAAI,CAAC,CAAC,KAAK;CAE3C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO;CAC7B,SAAS,OAAO;EACd,OAAO;GACL,MAAM;GACN,OAAO;GACP,OAAO,IAAI,sBACT,8DACA,EAAE,MAAM,CACV;GACA;EACF;CACF;CAEA,MAAM,SAAS,MAAM,OAAO,YAAY,CAAC,SAAS,MAAM;CACxD,IAAI,YAAY,UAAU,OAAO,QAC/B,OAAO;EACL,MAAM;EACN,OAAO;EACP,OAAO,IAAI,sBACT,8DACA,EAAE,QAAQ,OAAO,OAAO,CAC1B;EACA;CACF;CAGF,OAAO;EAAE,MAAM;EAAQ,OAAO;EAAM,OAAQ,OAAwB;EAAO;CAAM;AACnF;;AAiBA,SAAS,gBAAgB,MAAsB;CAC7C,MAAM,SAAS,KAAK,MAAM,kCAAkC;CAC5D,OAAO,SAAS,OAAO,KAAK;AAC9B;AAEA,SAAS,cAAc,OAAwB;CAC7C,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region ../@warlock.js/ai/src/observe/observer-registry.ts
|
|
2
|
+
/**
|
|
3
|
+
* Module-level list of globally registered {@link Observer}s. A flow
|
|
4
|
+
* that resolves to "observed" hands its finished report to every entry
|
|
5
|
+
* here. An observability tool (panoptic, …) registers exactly one
|
|
6
|
+
* collector when its config is applied.
|
|
7
|
+
*/
|
|
8
|
+
const observers = [];
|
|
9
|
+
/**
|
|
10
|
+
* Global "observe every flow by default" flag. When `true`, a flow that
|
|
11
|
+
* did not set its own `observe` option is observed (routed to the
|
|
12
|
+
* globally registered observers). Individual flows opt out with
|
|
13
|
+
* `observe: false`. Default `false` — opt-in observability.
|
|
14
|
+
*/
|
|
15
|
+
let observeAll = false;
|
|
16
|
+
/**
|
|
17
|
+
* The currently registered global observers. Returned as a read-only
|
|
18
|
+
* snapshot reference — callers must not mutate it; use
|
|
19
|
+
* {@link registerObserver} to add and {@link clearObservers} (test-only)
|
|
20
|
+
* to reset.
|
|
21
|
+
*/
|
|
22
|
+
function getObservers() {
|
|
23
|
+
return observers;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Read the global "observe every flow by default" flag. Consulted by the
|
|
27
|
+
* observe-resolution helper when a flow left `observe` undefined.
|
|
28
|
+
*/
|
|
29
|
+
function isObserveAll() {
|
|
30
|
+
return observeAll;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
export { getObservers, isObserveAll };
|
|
35
|
+
//# sourceMappingURL=observer-registry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observer-registry.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/observe/observer-registry.ts"],"sourcesContent":["import type { Observer } from \"./observer.contract\";\n\n/**\n * Module-level list of globally registered {@link Observer}s. A flow\n * that resolves to \"observed\" hands its finished report to every entry\n * here. An observability tool (panoptic, …) registers exactly one\n * collector when its config is applied.\n */\nconst observers: Observer[] = [];\n\n/**\n * Global \"observe every flow by default\" flag. When `true`, a flow that\n * did not set its own `observe` option is observed (routed to the\n * globally registered observers). Individual flows opt out with\n * `observe: false`. Default `false` — opt-in observability.\n */\nlet observeAll = false;\n\n/**\n * Register a global {@link Observer}. Every flow that resolves to\n * \"observed\" (via `observeAll` or `observe: true`) routes its completed\n * report to it. An observability tool registers its collector here once,\n * when its config is applied.\n */\nexport function registerObserver(observer: Observer): void {\n observers.push(observer);\n}\n\n/**\n * The currently registered global observers. Returned as a read-only\n * snapshot reference — callers must not mutate it; use\n * {@link registerObserver} to add and {@link clearObservers} (test-only)\n * to reset.\n */\nexport function getObservers(): readonly Observer[] {\n return observers;\n}\n\n/**\n * Set the global \"observe every flow by default\" flag. An observability\n * tool flips this on when configured with its own observe-all option.\n */\nexport function setObserveAll(value: boolean): void {\n observeAll = value;\n}\n\n/**\n * Read the global \"observe every flow by default\" flag. Consulted by the\n * observe-resolution helper when a flow left `observe` undefined.\n */\nexport function isObserveAll(): boolean {\n return observeAll;\n}\n\n/**\n * Reset the registry to its initial empty state — clears all registered\n * observers and turns off the observe-all flag. Internal: intended for\n * test isolation so one spec's registrations don't leak into the next.\n * Not part of the public surface.\n */\nexport function clearObservers(): void {\n observers.length = 0;\n observeAll = false;\n}\n"],"mappings":";;;;;;;AAQA,MAAM,YAAwB,CAAC;;;;;;;AAQ/B,IAAI,aAAa;;;;;;;AAkBjB,SAAgB,eAAoC;CAClD,OAAO;AACT;;;;;AAcA,SAAgB,eAAwB;CACtC,OAAO;AACT"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { isNestedRun } from "../utils/run-context.mjs";
|
|
2
|
+
import { getObservers, isObserveAll } from "./observer-registry.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/ai/src/observe/resolve-observers.ts
|
|
5
|
+
/**
|
|
6
|
+
* Resolve a flow's `observe` option into the concrete list of
|
|
7
|
+
* {@link Observer}s to notify with that flow's completed report:
|
|
8
|
+
*
|
|
9
|
+
* - `false` → `[]` (opted out).
|
|
10
|
+
* - `true` → the globally registered observers.
|
|
11
|
+
* - an `Observer` object → just that one (flow-local).
|
|
12
|
+
* - `undefined` → the globally registered observers when observe-all is
|
|
13
|
+
* on AND this is a ROOT run, otherwise `[]`.
|
|
14
|
+
*
|
|
15
|
+
* Reads the ambient {@link currentRunFrame} for the observe-all path:
|
|
16
|
+
* flows call it at completion, so a present frame means the run is nested
|
|
17
|
+
* inside an orchestration callback and is already attached to its parent's
|
|
18
|
+
* report tree — self-routing it again would double-count it as a separate
|
|
19
|
+
* top-level trace (and double its tokens/cost in the aggregate). Explicit
|
|
20
|
+
* `observe: true` / an `Observer` still route regardless of nesting.
|
|
21
|
+
*/
|
|
22
|
+
function resolveObservers(observe) {
|
|
23
|
+
if (observe === false) return [];
|
|
24
|
+
if (observe === true) return getObservers();
|
|
25
|
+
if (observe !== void 0) return [observe];
|
|
26
|
+
return isObserveAll() && !isNestedRun() ? getObservers() : [];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Observers whose `collect()` already threw once — so the isolate-but-
|
|
30
|
+
* surface warning fires at most once per observer object, never spamming
|
|
31
|
+
* the log when every flow report hits the same broken exporter. Keyed by
|
|
32
|
+
* object identity via a {@link WeakSet} so a discarded observer is GC'd
|
|
33
|
+
* without leaking. Mirrors panoptic's per-exporter `warnedExporters`.
|
|
34
|
+
*/
|
|
35
|
+
const warnedObservers = /* @__PURE__ */ new WeakSet();
|
|
36
|
+
/**
|
|
37
|
+
* Route a completed flow report to every observer the flow's `observe`
|
|
38
|
+
* option resolves to. Each `collect` is awaited so async exporters
|
|
39
|
+
* finish before the flow returns; a throw is **isolated** (never breaks
|
|
40
|
+
* the run) but no longer **silent** — it is surfaced via `onError` when
|
|
41
|
+
* supplied, otherwise a `console.warn` once per observer. A broken
|
|
42
|
+
* observer/exporter must not disappear from production with no signal
|
|
43
|
+
* (C5). Adopts the isolate-but-surface pattern panoptic's collector
|
|
44
|
+
* already uses for exporters.
|
|
45
|
+
*/
|
|
46
|
+
async function notifyObservers(observe, report, onError) {
|
|
47
|
+
for (const observer of resolveObservers(observe)) try {
|
|
48
|
+
await observer.collect(report);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
surfaceObserverError(observer, error, onError);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Surface an isolated observer failure without ever rethrowing into the
|
|
55
|
+
* flow. Prefers the caller-supplied `onError` (itself guarded so a
|
|
56
|
+
* throwing handler can't escape); otherwise warns once per observer.
|
|
57
|
+
*/
|
|
58
|
+
function surfaceObserverError(observer, error, onError) {
|
|
59
|
+
if (onError) {
|
|
60
|
+
try {
|
|
61
|
+
onError(error, observer);
|
|
62
|
+
} catch {}
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (warnedObservers.has(observer)) return;
|
|
66
|
+
warnedObservers.add(observer);
|
|
67
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
68
|
+
console.warn(`[warlock-ai] an observer's collect() threw and was isolated: ${message}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
export { notifyObservers, resolveObservers };
|
|
73
|
+
//# sourceMappingURL=resolve-observers.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-observers.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/observe/resolve-observers.ts"],"sourcesContent":["import { isNestedRun } from \"../utils/run-context\";\nimport { getObservers, isObserveAll } from \"./observer-registry\";\nimport type { Observer } from \"./observer.contract\";\n\n/**\n * The value a flow's `observe` config option may take. Additive and\n * gated — when `undefined` (the default), behavior follows the global\n * observe-all flag, so a flow that never sets `observe` behaves exactly\n * as before unless an observability tool turned observe-all on.\n *\n * - `true` → route this flow to the globally registered observers,\n * even when observe-all is off.\n * - `false` → opt this flow out entirely, even when observe-all is on.\n * - an {@link Observer} object → a flow-local collector; only this flow's\n * report is routed, and only to it (the global observers are skipped).\n * A panoptic flow-local collector implements `Observer`, so it can be\n * passed here directly — core stays panoptic-agnostic.\n * - `undefined` → follow the global observe-all flag.\n */\nexport type FlowObserveOption = boolean | Observer;\n\n/**\n * Resolve a flow's `observe` option into the concrete list of\n * {@link Observer}s to notify with that flow's completed report:\n *\n * - `false` → `[]` (opted out).\n * - `true` → the globally registered observers.\n * - an `Observer` object → just that one (flow-local).\n * - `undefined` → the globally registered observers when observe-all is\n * on AND this is a ROOT run, otherwise `[]`.\n *\n * Reads the ambient {@link currentRunFrame} for the observe-all path:\n * flows call it at completion, so a present frame means the run is nested\n * inside an orchestration callback and is already attached to its parent's\n * report tree — self-routing it again would double-count it as a separate\n * top-level trace (and double its tokens/cost in the aggregate). Explicit\n * `observe: true` / an `Observer` still route regardless of nesting.\n */\nexport function resolveObservers(observe: FlowObserveOption | undefined): readonly Observer[] {\n if (observe === false) {\n return [];\n }\n\n if (observe === true) {\n return getObservers();\n }\n\n if (observe !== undefined) {\n return [observe];\n }\n\n // Observe-all captures ROOT runs only. A run nested inside any parent\n // capture (orchestration callback, supervisor member dispatch, workflow\n // step) already nests in its parent's report, so routing it here too would\n // duplicate it as a standalone top-level trace.\n return isObserveAll() && !isNestedRun() ? getObservers() : [];\n}\n\n/**\n * Observers whose `collect()` already threw once — so the isolate-but-\n * surface warning fires at most once per observer object, never spamming\n * the log when every flow report hits the same broken exporter. Keyed by\n * object identity via a {@link WeakSet} so a discarded observer is GC'd\n * without leaking. Mirrors panoptic's per-exporter `warnedExporters`.\n */\nconst warnedObservers = new WeakSet<Observer>();\n\n/**\n * Route a completed flow report to every observer the flow's `observe`\n * option resolves to. Each `collect` is awaited so async exporters\n * finish before the flow returns; a throw is **isolated** (never breaks\n * the run) but no longer **silent** — it is surfaced via `onError` when\n * supplied, otherwise a `console.warn` once per observer. A broken\n * observer/exporter must not disappear from production with no signal\n * (C5). Adopts the isolate-but-surface pattern panoptic's collector\n * already uses for exporters.\n */\nexport async function notifyObservers(\n observe: FlowObserveOption | undefined,\n report: Parameters<Observer[\"collect\"]>[0],\n onError?: (error: unknown, observer: Observer) => void,\n): Promise<void> {\n for (const observer of resolveObservers(observe)) {\n try {\n await observer.collect(report);\n } catch (error) {\n surfaceObserverError(observer, error, onError);\n }\n }\n}\n\n/**\n * Surface an isolated observer failure without ever rethrowing into the\n * flow. Prefers the caller-supplied `onError` (itself guarded so a\n * throwing handler can't escape); otherwise warns once per observer.\n */\nfunction surfaceObserverError(\n observer: Observer,\n error: unknown,\n onError?: (error: unknown, observer: Observer) => void,\n): void {\n if (onError) {\n try {\n onError(error, observer);\n } catch {\n // Never let the error handler itself escape into the flow.\n }\n return;\n }\n\n if (warnedObservers.has(observer)) return;\n warnedObservers.add(observer);\n\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[warlock-ai] an observer's collect() threw and was isolated: ${message}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,iBAAiB,SAA6D;CAC5F,IAAI,YAAY,OACd,OAAO,CAAC;CAGV,IAAI,YAAY,MACd,OAAO,aAAa;CAGtB,IAAI,YAAY,QACd,OAAO,CAAC,OAAO;CAOjB,OAAO,aAAa,KAAK,CAAC,YAAY,IAAI,aAAa,IAAI,CAAC;AAC9D;;;;;;;;AASA,MAAM,kCAAkB,IAAI,QAAkB;;;;;;;;;;;AAY9C,eAAsB,gBACpB,SACA,QACA,SACe;CACf,KAAK,MAAM,YAAY,iBAAiB,OAAO,GAC7C,IAAI;EACF,MAAM,SAAS,QAAQ,MAAM;CAC/B,SAAS,OAAO;EACd,qBAAqB,UAAU,OAAO,OAAO;CAC/C;AAEJ;;;;;;AAOA,SAAS,qBACP,UACA,OACA,SACM;CACN,IAAI,SAAS;EACX,IAAI;GACF,QAAQ,OAAO,QAAQ;EACzB,QAAQ,CAER;EACA;CACF;CAEA,IAAI,gBAAgB,IAAI,QAAQ,GAAG;CACnC,gBAAgB,IAAI,QAAQ;CAE5B,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACrE,QAAQ,KAAK,gEAAgE,SAAS;AACxF"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { SupervisorFailedError } from "../errors/supervisor-failed-error.mjs";
|
|
2
|
+
import "../errors/index.mjs";
|
|
3
|
+
import { generateRunId } from "../utils/generate-run-id.mjs";
|
|
4
|
+
import { compositeAsTool } from "../tool/tool.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/ai/src/orchestrator/as-tool.ts
|
|
7
|
+
/**
|
|
8
|
+
* Wrap an {@link OrchestratorContract} as a {@link ToolContract} so an
|
|
9
|
+
* outer agent can invoke it from its tool-call loop (design §13).
|
|
10
|
+
* Mirrors `supervisor.asTool()` — same `compositeAsTool` composition and
|
|
11
|
+
* error normalization — and adds `sessionScope`.
|
|
12
|
+
*
|
|
13
|
+
* The boundary is OPAQUE (§13, §18.6): the parent's `signal` / `context`
|
|
14
|
+
* / events do NOT auto-forward. Anything the wrapped orchestrator needs
|
|
15
|
+
* per call must ride on the tool's `inputSchema` payload.
|
|
16
|
+
*
|
|
17
|
+
* Session continuity:
|
|
18
|
+
* - `"fresh"` (default) — each invocation gets a brand-new `sessionId`
|
|
19
|
+
* (a generated id) and empty history; the session lives only for this
|
|
20
|
+
* tool call. The whole validated payload is forwarded as the
|
|
21
|
+
* orchestrator's `execute(input)` argument.
|
|
22
|
+
* - `"shared"` — the parent supplies `sessionId` (and optionally
|
|
23
|
+
* `history`) inside the validated payload; the orchestrator
|
|
24
|
+
* participates in that session. The remaining payload fields are
|
|
25
|
+
* forwarded as `execute(input)`. A missing/blank `sessionId` throws
|
|
26
|
+
* {@link SupervisorFailedError}.
|
|
27
|
+
*
|
|
28
|
+
* On `result.error`, the typed orchestrator error is thrown so the tool
|
|
29
|
+
* wrapper produces a `ToolExecutionError` with `cause` preserved — the
|
|
30
|
+
* outer agent sees one uniform error class.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* const support = ai.orchestrator({ name: "refund-support", intents });
|
|
34
|
+
* const supportTool = support.asTool({
|
|
35
|
+
* name: "handle_refund",
|
|
36
|
+
* description: "Handle a refund conversation end-to-end.",
|
|
37
|
+
* inputSchema: v.object({ message: v.string() }),
|
|
38
|
+
* });
|
|
39
|
+
* const concierge = ai.agent({ model, tools: [supportTool] });
|
|
40
|
+
*/
|
|
41
|
+
function asTool(orchestrator, options) {
|
|
42
|
+
if (!orchestrator.name || typeof orchestrator.name !== "string") throw new SupervisorFailedError("orchestrator.asTool(): orchestrator must have a `name` to be wrapped as a tool");
|
|
43
|
+
const sessionScope = options.sessionScope ?? "fresh";
|
|
44
|
+
return compositeAsTool({
|
|
45
|
+
name: options.name ?? orchestrator.name,
|
|
46
|
+
description: options.description ?? `Invoke orchestrator "${orchestrator.name}" as a tool.`,
|
|
47
|
+
input: options.inputSchema,
|
|
48
|
+
execute: async (input) => {
|
|
49
|
+
const { sessionId, history, executeInput } = resolveSession(sessionScope, input);
|
|
50
|
+
const result = await orchestrator.execute(executeInput, {
|
|
51
|
+
sessionId,
|
|
52
|
+
history
|
|
53
|
+
});
|
|
54
|
+
if (result.error) throw result.error;
|
|
55
|
+
return {
|
|
56
|
+
data: result.data,
|
|
57
|
+
usage: result.usage,
|
|
58
|
+
report: result.report
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Resolve the per-call `sessionId`, `history`, and the `execute(input)`
|
|
65
|
+
* argument from the validated tool payload, according to `sessionScope`.
|
|
66
|
+
*/
|
|
67
|
+
function resolveSession(sessionScope, input) {
|
|
68
|
+
if (sessionScope === "fresh") return {
|
|
69
|
+
sessionId: generateRunId("session"),
|
|
70
|
+
history: [],
|
|
71
|
+
executeInput: coerceInput(input)
|
|
72
|
+
};
|
|
73
|
+
const payload = typeof input === "object" && input !== null ? input : {};
|
|
74
|
+
if (typeof payload.sessionId !== "string" || payload.sessionId.length === 0) throw new SupervisorFailedError("orchestrator.asTool(): sessionScope \"shared\" requires a `sessionId` string in the tool input payload");
|
|
75
|
+
const { sessionId, history, ...rest } = payload;
|
|
76
|
+
return {
|
|
77
|
+
sessionId,
|
|
78
|
+
history: Array.isArray(history) ? history : [],
|
|
79
|
+
executeInput: coerceInput(rest)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Coerce a tool-input value into the `SupervisorInput` shape the
|
|
84
|
+
* orchestrator's `execute()` accepts (`string | Record<string,
|
|
85
|
+
* unknown>`). Strings and plain objects pass through; everything else
|
|
86
|
+
* is JSON-stringified so the orchestrator receives a predictable input
|
|
87
|
+
* regardless of how the outer agent shaped its call.
|
|
88
|
+
*/
|
|
89
|
+
function coerceInput(value) {
|
|
90
|
+
if (typeof value === "string") return value;
|
|
91
|
+
if (typeof value === "object" && value !== null) return value;
|
|
92
|
+
if (value === void 0 || value === null) return "";
|
|
93
|
+
return String(value);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//#endregion
|
|
97
|
+
export { asTool };
|
|
98
|
+
//# sourceMappingURL=as-tool.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"as-tool.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/orchestrator/as-tool.ts"],"sourcesContent":["import type { Message } from \"../contracts/conversation-message.type\";\nimport type {\n OrchestratorAsToolOptions,\n OrchestratorContract,\n} from \"../contracts/orchestrator/orchestrator.contract\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport { SupervisorFailedError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"../tool/tool\";\nimport { generateRunId } from \"../utils/generate-run-id\";\n\n/**\n * Shape the orchestrator looks for inside the validated tool input when\n * `sessionScope: \"shared\"` — the parent must thread the session id (and\n * optionally the prior history) through the tool's `inputSchema`\n * payload, since the boundary is opaque (§13). Everything else on the\n * payload becomes the orchestrator's `execute(input)` argument.\n */\ntype SharedScopePayload = {\n sessionId?: unknown;\n history?: unknown;\n [key: string]: unknown;\n};\n\n/**\n * Wrap an {@link OrchestratorContract} as a {@link ToolContract} so an\n * outer agent can invoke it from its tool-call loop (design §13).\n * Mirrors `supervisor.asTool()` — same `compositeAsTool` composition and\n * error normalization — and adds `sessionScope`.\n *\n * The boundary is OPAQUE (§13, §18.6): the parent's `signal` / `context`\n * / events do NOT auto-forward. Anything the wrapped orchestrator needs\n * per call must ride on the tool's `inputSchema` payload.\n *\n * Session continuity:\n * - `\"fresh\"` (default) — each invocation gets a brand-new `sessionId`\n * (a generated id) and empty history; the session lives only for this\n * tool call. The whole validated payload is forwarded as the\n * orchestrator's `execute(input)` argument.\n * - `\"shared\"` — the parent supplies `sessionId` (and optionally\n * `history`) inside the validated payload; the orchestrator\n * participates in that session. The remaining payload fields are\n * forwarded as `execute(input)`. A missing/blank `sessionId` throws\n * {@link SupervisorFailedError}.\n *\n * On `result.error`, the typed orchestrator error is thrown so the tool\n * wrapper produces a `ToolExecutionError` with `cause` preserved — the\n * outer agent sees one uniform error class.\n *\n * @example\n * const support = ai.orchestrator({ name: \"refund-support\", intents });\n * const supportTool = support.asTool({\n * name: \"handle_refund\",\n * description: \"Handle a refund conversation end-to-end.\",\n * inputSchema: v.object({ message: v.string() }),\n * });\n * const concierge = ai.agent({ model, tools: [supportTool] });\n */\nexport function asTool<TOutput, TState, TToolInput>(\n orchestrator: OrchestratorContract<TOutput, TState>,\n options: OrchestratorAsToolOptions<TToolInput>,\n): ToolContract<TToolInput, TOutput> {\n if (!orchestrator.name || typeof orchestrator.name !== \"string\") {\n throw new SupervisorFailedError(\n \"orchestrator.asTool(): orchestrator must have a `name` to be wrapped as a tool\",\n );\n }\n\n const sessionScope = options.sessionScope ?? \"fresh\";\n\n return compositeAsTool<TToolInput, TOutput>({\n name: options.name ?? orchestrator.name,\n description:\n options.description ??\n `Invoke orchestrator \"${orchestrator.name}\" as a tool.`,\n input: options.inputSchema,\n execute: async (input) => {\n const { sessionId, history, executeInput } = resolveSession(\n sessionScope,\n input,\n );\n\n const result = await orchestrator.execute(executeInput, {\n sessionId,\n history,\n });\n\n if (result.error) {\n // Surface the typed orchestrator error — the outer ToolContract\n // wraps it as a ToolExecutionError with `cause` preserved.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Resolve the per-call `sessionId`, `history`, and the `execute(input)`\n * argument from the validated tool payload, according to `sessionScope`.\n */\nfunction resolveSession(\n sessionScope: \"fresh\" | \"shared\",\n input: unknown,\n): { sessionId: string; history: Message[]; executeInput: SupervisorInput } {\n if (sessionScope === \"fresh\") {\n return {\n sessionId: generateRunId(\"session\"),\n history: [],\n executeInput: coerceInput(input),\n };\n }\n\n const payload = (\n typeof input === \"object\" && input !== null ? input : {}\n ) as SharedScopePayload;\n\n if (typeof payload.sessionId !== \"string\" || payload.sessionId.length === 0) {\n throw new SupervisorFailedError(\n 'orchestrator.asTool(): sessionScope \"shared\" requires a `sessionId` string in the tool input payload',\n );\n }\n\n const { sessionId, history, ...rest } = payload;\n\n return {\n sessionId,\n history: Array.isArray(history) ? (history as Message[]) : [],\n executeInput: coerceInput(rest),\n };\n}\n\n/**\n * Coerce a tool-input value into the `SupervisorInput` shape the\n * orchestrator's `execute()` accepts (`string | Record<string,\n * unknown>`). Strings and plain objects pass through; everything else\n * is JSON-stringified so the orchestrator receives a predictable input\n * regardless of how the outer agent shaped its call.\n */\nfunction coerceInput(value: unknown): SupervisorInput {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"object\" && value !== null) {\n return value as Record<string, unknown>;\n }\n\n if (value === undefined || value === null) {\n return \"\";\n }\n\n return String(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,OACd,cACA,SACmC;CACnC,IAAI,CAAC,aAAa,QAAQ,OAAO,aAAa,SAAS,UACrD,MAAM,IAAI,sBACR,gFACF;CAGF,MAAM,eAAe,QAAQ,gBAAgB;CAE7C,OAAO,gBAAqC;EAC1C,MAAM,QAAQ,QAAQ,aAAa;EACnC,aACE,QAAQ,eACR,wBAAwB,aAAa,KAAK;EAC5C,OAAO,QAAQ;EACf,SAAS,OAAO,UAAU;GACxB,MAAM,EAAE,WAAW,SAAS,iBAAiB,eAC3C,cACA,KACF;GAEA,MAAM,SAAS,MAAM,aAAa,QAAQ,cAAc;IACtD;IACA;GACF,CAAC;GAED,IAAI,OAAO,OAGT,MAAM,OAAO;GAGf,OAAO;IACL,MAAM,OAAO;IACb,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF;CACF,CAAC;AACH;;;;;AAMA,SAAS,eACP,cACA,OAC0E;CAC1E,IAAI,iBAAiB,SACnB,OAAO;EACL,WAAW,cAAc,SAAS;EAClC,SAAS,CAAC;EACV,cAAc,YAAY,KAAK;CACjC;CAGF,MAAM,UACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,CAAC;CAGzD,IAAI,OAAO,QAAQ,cAAc,YAAY,QAAQ,UAAU,WAAW,GACxE,MAAM,IAAI,sBACR,wGACF;CAGF,MAAM,EAAE,WAAW,SAAS,GAAG,SAAS;CAExC,OAAO;EACL;EACA,SAAS,MAAM,QAAQ,OAAO,IAAK,UAAwB,CAAC;EAC5D,cAAc,YAAY,IAAI;CAChC;AACF;;;;;;;;AASA,SAAS,YAAY,OAAiC;CACpD,IAAI,OAAO,UAAU,UACnB,OAAO;CAGT,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAGT,IAAI,UAAU,UAAa,UAAU,MACnC,OAAO;CAGT,OAAO,OAAO,KAAK;AACrB"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
//#region ../@warlock.js/ai/src/orchestrator/checkpoint.ts
|
|
2
|
+
/** Framework default for snapshot retention per session (§4 Phase 6). */
|
|
3
|
+
const DEFAULT_KEEP_SNAPSHOTS = 100;
|
|
4
|
+
/**
|
|
5
|
+
* Summarize a supervisor dispatch decision into the `last_route`
|
|
6
|
+
* checkpoint column (§4 Phase 6). A bare string passes through; a
|
|
7
|
+
* fan-out array passes through; the `END` sentinel and anything else
|
|
8
|
+
* collapse to `null` (the turn routed nowhere worth recording).
|
|
9
|
+
*/
|
|
10
|
+
function summarizeRoute(next) {
|
|
11
|
+
if (typeof next === "string") return next === "__warlock:end__" ? null : next;
|
|
12
|
+
if (Array.isArray(next)) return next;
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Phase 6 — persist checkpoint (orchestrator.md §3 / §4 Phase 6).
|
|
17
|
+
* Writes a fresh append-only row at `turn_index = N` carrying the
|
|
18
|
+
* post-merge `state`, the current `signature` (read by the next call's
|
|
19
|
+
* Phase 2), the informational `version`, the dispatch `last_route`, and
|
|
20
|
+
* the carried-forward `summarized_through`. Lock columns are written
|
|
21
|
+
* `null` here — they are populated only by an in-flight Phase 7
|
|
22
|
+
* compaction.
|
|
23
|
+
*
|
|
24
|
+
* Emits `orchestrator.checkpoint.persisted` after the row lands, then
|
|
25
|
+
* prunes to `keepSnapshots` (default 100; `"all"` opts out) — §4 Phase
|
|
26
|
+
* 6 pruning (Q20). Pruning runs only when the store exposes the
|
|
27
|
+
* optional `prune` hook (memory/pg/redis own their own pruning); when
|
|
28
|
+
* absent the write still succeeds.
|
|
29
|
+
*
|
|
30
|
+
* Returns the persisted record so the engine can fold it into the
|
|
31
|
+
* turn's report.
|
|
32
|
+
*/
|
|
33
|
+
async function persistCheckpoint(params) {
|
|
34
|
+
const { ctx, sessionId, turnIndex, state, lastRoute, summarizedThrough } = params;
|
|
35
|
+
const record = {
|
|
36
|
+
orchestrator_name: ctx.config.name,
|
|
37
|
+
session_id: sessionId,
|
|
38
|
+
turn_index: turnIndex,
|
|
39
|
+
state,
|
|
40
|
+
last_route: lastRoute,
|
|
41
|
+
signature: ctx.signature,
|
|
42
|
+
version: ctx.config.version ?? null,
|
|
43
|
+
summarized_through: summarizedThrough,
|
|
44
|
+
lock_acquired_at: null,
|
|
45
|
+
lock_expires_at: null,
|
|
46
|
+
saved_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
47
|
+
};
|
|
48
|
+
await ctx.checkpointStore.save(record);
|
|
49
|
+
ctx.emitter.emit("orchestrator.checkpoint.persisted", {
|
|
50
|
+
sessionId,
|
|
51
|
+
turnIndex
|
|
52
|
+
});
|
|
53
|
+
await prune(ctx, sessionId, turnIndex);
|
|
54
|
+
return record;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Prune session rows older than `max_turn_index - keepSnapshots` (§4
|
|
58
|
+
* Phase 6). Synchronous-after-save; opted out with
|
|
59
|
+
* `keepSnapshots: "all"`. Delegated to an optional store-side `prune`
|
|
60
|
+
* hook so each driver implements deletion in its own dialect — the
|
|
61
|
+
* engine never reaches into store internals.
|
|
62
|
+
*/
|
|
63
|
+
async function prune(ctx, sessionId, latestTurnIndex) {
|
|
64
|
+
const keep = ctx.config.keepSnapshots ?? 100;
|
|
65
|
+
if (keep === "all") return;
|
|
66
|
+
const store = ctx.checkpointStore;
|
|
67
|
+
if (typeof store.prune !== "function") return;
|
|
68
|
+
const keepBeforeTurnIndex = latestTurnIndex - keep + 1;
|
|
69
|
+
if (keepBeforeTurnIndex <= 0) return;
|
|
70
|
+
await store.prune(ctx.config.name, sessionId, keepBeforeTurnIndex);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
//#endregion
|
|
74
|
+
export { persistCheckpoint, summarizeRoute };
|
|
75
|
+
//# sourceMappingURL=checkpoint.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkpoint.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/orchestrator/checkpoint.ts"],"sourcesContent":["import type { CheckpointRecord } from \"../contracts/orchestrator/checkpoint-store.contract\";\nimport type { Next } from \"../contracts/supervisor/next.type\";\nimport type { OrchestratorEngineContext } from \"./engine-context.type\";\n\n/** Framework default for snapshot retention per session (§4 Phase 6). */\nexport const DEFAULT_KEEP_SNAPSHOTS = 100;\n\n/** Fields the engine supplies to build a fresh checkpoint row. */\nexport type PersistParams<TState> = {\n ctx: OrchestratorEngineContext<unknown, TState>;\n sessionId: string;\n turnIndex: number;\n state: unknown;\n /** Dispatch decision summary — a single intent, fan-out list, or null. */\n lastRoute: string | string[] | null;\n /** Carried forward from the loaded checkpoint (compaction progress). */\n summarizedThrough: number | null;\n};\n\n/**\n * Summarize a supervisor dispatch decision into the `last_route`\n * checkpoint column (§4 Phase 6). A bare string passes through; a\n * fan-out array passes through; the `END` sentinel and anything else\n * collapse to `null` (the turn routed nowhere worth recording).\n */\nexport function summarizeRoute(next: Next | undefined): string | string[] | null {\n if (typeof next === \"string\") {\n return next === \"__warlock:end__\" ? null : next;\n }\n\n if (Array.isArray(next)) {\n return next;\n }\n\n return null;\n}\n\n/**\n * Phase 6 — persist checkpoint (orchestrator.md §3 / §4 Phase 6).\n * Writes a fresh append-only row at `turn_index = N` carrying the\n * post-merge `state`, the current `signature` (read by the next call's\n * Phase 2), the informational `version`, the dispatch `last_route`, and\n * the carried-forward `summarized_through`. Lock columns are written\n * `null` here — they are populated only by an in-flight Phase 7\n * compaction.\n *\n * Emits `orchestrator.checkpoint.persisted` after the row lands, then\n * prunes to `keepSnapshots` (default 100; `\"all\"` opts out) — §4 Phase\n * 6 pruning (Q20). Pruning runs only when the store exposes the\n * optional `prune` hook (memory/pg/redis own their own pruning); when\n * absent the write still succeeds.\n *\n * Returns the persisted record so the engine can fold it into the\n * turn's report.\n */\nexport async function persistCheckpoint<TState>(\n params: PersistParams<TState>,\n): Promise<CheckpointRecord> {\n const { ctx, sessionId, turnIndex, state, lastRoute, summarizedThrough } = params;\n\n const record: CheckpointRecord = {\n orchestrator_name: ctx.config.name,\n session_id: sessionId,\n turn_index: turnIndex,\n state,\n last_route: lastRoute,\n signature: ctx.signature,\n version: ctx.config.version ?? null,\n summarized_through: summarizedThrough,\n lock_acquired_at: null,\n lock_expires_at: null,\n saved_at: new Date().toISOString(),\n };\n\n await ctx.checkpointStore.save(record);\n\n ctx.emitter.emit(\"orchestrator.checkpoint.persisted\", {\n sessionId,\n turnIndex,\n });\n\n await prune(ctx, sessionId, turnIndex);\n\n return record;\n}\n\n/**\n * Prune session rows older than `max_turn_index - keepSnapshots` (§4\n * Phase 6). Synchronous-after-save; opted out with\n * `keepSnapshots: \"all\"`. Delegated to an optional store-side `prune`\n * hook so each driver implements deletion in its own dialect — the\n * engine never reaches into store internals.\n */\nasync function prune<TState>(\n ctx: OrchestratorEngineContext<unknown, TState>,\n sessionId: string,\n latestTurnIndex: number,\n): Promise<void> {\n const keep = ctx.config.keepSnapshots ?? DEFAULT_KEEP_SNAPSHOTS;\n\n if (keep === \"all\") {\n return;\n }\n\n const store = ctx.checkpointStore as {\n prune?: (\n orchestratorName: string,\n sessionId: string,\n keepBeforeTurnIndex: number,\n ) => Promise<void>;\n };\n\n if (typeof store.prune !== \"function\") {\n return;\n }\n\n const keepBeforeTurnIndex = latestTurnIndex - keep + 1;\n\n if (keepBeforeTurnIndex <= 0) {\n return;\n }\n\n await store.prune(ctx.config.name, sessionId, keepBeforeTurnIndex);\n}\n"],"mappings":";;AAKA,MAAa,yBAAyB;;;;;;;AAoBtC,SAAgB,eAAe,MAAkD;CAC/E,IAAI,OAAO,SAAS,UAClB,OAAO,SAAS,oBAAoB,OAAO;CAG7C,IAAI,MAAM,QAAQ,IAAI,GACpB,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,eAAsB,kBACpB,QAC2B;CAC3B,MAAM,EAAE,KAAK,WAAW,WAAW,OAAO,WAAW,sBAAsB;CAE3E,MAAM,SAA2B;EAC/B,mBAAmB,IAAI,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ;EACA,YAAY;EACZ,WAAW,IAAI;EACf,SAAS,IAAI,OAAO,WAAW;EAC/B,oBAAoB;EACpB,kBAAkB;EAClB,iBAAiB;EACjB,2BAAU,IAAI,KAAK,EAAC,CAAC,YAAY;CACnC;CAEA,MAAM,IAAI,gBAAgB,KAAK,MAAM;CAErC,IAAI,QAAQ,KAAK,qCAAqC;EACpD;EACA;CACF,CAAC;CAED,MAAM,MAAM,KAAK,WAAW,SAAS;CAErC,OAAO;AACT;;;;;;;;AASA,eAAe,MACb,KACA,WACA,iBACe;CACf,MAAM,OAAO,IAAI,OAAO;CAExB,IAAI,SAAS,OACX;CAGF,MAAM,QAAQ,IAAI;CAQlB,IAAI,OAAO,MAAM,UAAU,YACzB;CAGF,MAAM,sBAAsB,kBAAkB,OAAO;CAErD,IAAI,uBAAuB,GACzB;CAGF,MAAM,MAAM,MAAM,IAAI,OAAO,MAAM,WAAW,mBAAmB;AACnE"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { SupervisorFailedError } from "../errors/supervisor-failed-error.mjs";
|
|
2
|
+
import "../errors/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/ai/src/orchestrator/commands.ts
|
|
5
|
+
/**
|
|
6
|
+
* Build the typed `command(name, args)` dispatcher backing
|
|
7
|
+
* {@link import("../contracts/orchestrator/orchestrator.contract").OrchestratorContract.command}
|
|
8
|
+
* (design §11). Looks the command up in the supplied handler bag and
|
|
9
|
+
* forwards `args`, preserving the discriminated `OrchestratorCommands`
|
|
10
|
+
* typing end to end.
|
|
11
|
+
*
|
|
12
|
+
* v1 ships exactly one built-in command, `compact`. v2 user commands
|
|
13
|
+
* attach via module augmentation of `OrchestratorCommands`; the
|
|
14
|
+
* dispatcher widens with the map automatically, and an unregistered
|
|
15
|
+
* command throws {@link SupervisorFailedError} rather than silently
|
|
16
|
+
* resolving `undefined`.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* const command = createCommandDispatcher({
|
|
20
|
+
* compact: (args) => runCompaction(args),
|
|
21
|
+
* });
|
|
22
|
+
* const result = await command("compact", { sessionId, history });
|
|
23
|
+
*/
|
|
24
|
+
function createCommandDispatcher(handlers) {
|
|
25
|
+
return function command(name, args) {
|
|
26
|
+
const handler = handlers[name];
|
|
27
|
+
if (typeof handler !== "function") throw new SupervisorFailedError(`orchestrator.command(): unknown command "${String(name)}"`);
|
|
28
|
+
return handler(args);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
export { createCommandDispatcher };
|
|
34
|
+
//# sourceMappingURL=commands.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"commands.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/orchestrator/commands.ts"],"sourcesContent":["import type { OrchestratorCommands } from \"../contracts/orchestrator/orchestrator-commands.type\";\nimport { SupervisorFailedError } from \"../errors\";\n\n/**\n * Per-command handler bag — one async runner per key of\n * {@link OrchestratorCommands}. The orchestrator factory supplies the\n * `compact` runner (which delegates to the shared compaction code path,\n * §11) so this module owns command ROUTING only, never the compaction\n * logic itself.\n *\n * Typed against the same discriminated map the public `command<K>`\n * method uses, so a registered handler's `args` / result line up with\n * the contract with no casting at the call site.\n */\nexport type OrchestratorCommandHandlers = {\n [K in keyof OrchestratorCommands]: (\n args: OrchestratorCommands[K][\"args\"],\n ) => Promise<OrchestratorCommands[K][\"result\"]>;\n};\n\n/**\n * Build the typed `command(name, args)` dispatcher backing\n * {@link import(\"../contracts/orchestrator/orchestrator.contract\").OrchestratorContract.command}\n * (design §11). Looks the command up in the supplied handler bag and\n * forwards `args`, preserving the discriminated `OrchestratorCommands`\n * typing end to end.\n *\n * v1 ships exactly one built-in command, `compact`. v2 user commands\n * attach via module augmentation of `OrchestratorCommands`; the\n * dispatcher widens with the map automatically, and an unregistered\n * command throws {@link SupervisorFailedError} rather than silently\n * resolving `undefined`.\n *\n * @example\n * const command = createCommandDispatcher({\n * compact: (args) => runCompaction(args),\n * });\n * const result = await command(\"compact\", { sessionId, history });\n */\nexport function createCommandDispatcher(handlers: OrchestratorCommandHandlers) {\n return function command<K extends keyof OrchestratorCommands>(\n name: K,\n args: OrchestratorCommands[K][\"args\"],\n ): Promise<OrchestratorCommands[K][\"result\"]> {\n const handler = handlers[name];\n\n if (typeof handler !== \"function\") {\n throw new SupervisorFailedError(\n `orchestrator.command(): unknown command \"${String(name)}\"`,\n );\n }\n\n return handler(args);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,wBAAwB,UAAuC;CAC7E,OAAO,SAAS,QACd,MACA,MAC4C;EAC5C,MAAM,UAAU,SAAS;EAEzB,IAAI,OAAO,YAAY,YACrB,MAAM,IAAI,sBACR,4CAA4C,OAAO,IAAI,EAAE,EAC3D;EAGF,OAAO,QAAQ,IAAI;CACrB;AACF"}
|