@alvin0/ai-agent-sdk-core 0.1.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/LICENSE +21 -0
- package/README.md +52 -0
- package/dist/agent/accounting/common.js +2 -0
- package/dist/agent/accounting/common.js.map +1 -0
- package/dist/agent/accounting/config.js +2 -0
- package/dist/agent/accounting/config.js.map +1 -0
- package/dist/agent/accounting/contracts.d.ts +36 -0
- package/dist/agent/accounting/contracts.d.ts.map +1 -0
- package/dist/agent/accounting/delivery/accounting-data.js +2 -0
- package/dist/agent/accounting/delivery/accounting-data.js.map +1 -0
- package/dist/agent/accounting/delivery/config.js +2 -0
- package/dist/agent/accounting/delivery/config.js.map +1 -0
- package/dist/agent/accounting/delivery/data.js +2 -0
- package/dist/agent/accounting/delivery/data.js.map +1 -0
- package/dist/agent/accounting/delivery/support-errors.js +2 -0
- package/dist/agent/accounting/delivery/support-errors.js.map +1 -0
- package/dist/agent/accounting/delivery/terminal.js +2 -0
- package/dist/agent/accounting/delivery/terminal.js.map +1 -0
- package/dist/agent/accounting/delivery-types.d.ts +43 -0
- package/dist/agent/accounting/delivery-types.d.ts.map +1 -0
- package/dist/agent/accounting/error.d.ts +18 -0
- package/dist/agent/accounting/error.d.ts.map +1 -0
- package/dist/agent/accounting/error.js +2 -0
- package/dist/agent/accounting/error.js.map +1 -0
- package/dist/agent/accounting/estimate.js +2 -0
- package/dist/agent/accounting/estimate.js.map +1 -0
- package/dist/agent/accounting/event-buffer.js +2 -0
- package/dist/agent/accounting/event-buffer.js.map +1 -0
- package/dist/agent/accounting/ledger.js +2 -0
- package/dist/agent/accounting/ledger.js.map +1 -0
- package/dist/agent/accounting/report.d.ts +70 -0
- package/dist/agent/accounting/report.d.ts.map +1 -0
- package/dist/agent/accounting/usage.d.ts +13 -0
- package/dist/agent/accounting/usage.d.ts.map +1 -0
- package/dist/agent/accounting/usage.js +2 -0
- package/dist/agent/accounting/usage.js.map +1 -0
- package/dist/agent/context/section.d.ts +15 -0
- package/dist/agent/context/section.d.ts.map +1 -0
- package/dist/agent/context/section.js +2 -0
- package/dist/agent/context/section.js.map +1 -0
- package/dist/agent/context/types.d.ts +98 -0
- package/dist/agent/context/types.d.ts.map +1 -0
- package/dist/agent/define/definition.d.ts +110 -0
- package/dist/agent/define/definition.d.ts.map +1 -0
- package/dist/agent/define/definition.js +2 -0
- package/dist/agent/define/definition.js.map +1 -0
- package/dist/agent/define/instructions.js +2 -0
- package/dist/agent/define/instructions.js.map +1 -0
- package/dist/agent/define/output-format.js +2 -0
- package/dist/agent/define/output-format.js.map +1 -0
- package/dist/agent/define/session/accounting.js +2 -0
- package/dist/agent/define/session/accounting.js.map +1 -0
- package/dist/agent/define/session/common.js +2 -0
- package/dist/agent/define/session/common.js.map +1 -0
- package/dist/agent/define/session/config.js +2 -0
- package/dist/agent/define/session/config.js.map +1 -0
- package/dist/agent/define/session/model-config.js +2 -0
- package/dist/agent/define/session/model-config.js.map +1 -0
- package/dist/agent/define/session/observer.js +2 -0
- package/dist/agent/define/session/observer.js.map +1 -0
- package/dist/agent/define/session/run-seal.js +2 -0
- package/dist/agent/define/session/run-seal.js.map +1 -0
- package/dist/agent/define/session/runtime-binding.js +2 -0
- package/dist/agent/define/session/runtime-binding.js.map +1 -0
- package/dist/agent/define/session/runtime-compaction.js +2 -0
- package/dist/agent/define/session/runtime-compaction.js.map +1 -0
- package/dist/agent/define/session/runtime-memory.js +2 -0
- package/dist/agent/define/session/runtime-memory.js.map +1 -0
- package/dist/agent/define/session/skills.js +2 -0
- package/dist/agent/define/session/skills.js.map +1 -0
- package/dist/agent/define/session/trace-accounting.js +2 -0
- package/dist/agent/define/session/trace-accounting.js.map +1 -0
- package/dist/agent/define/session/types.d.ts +217 -0
- package/dist/agent/define/session/types.d.ts.map +1 -0
- package/dist/agent/define/session/validation.js +2 -0
- package/dist/agent/define/session/validation.js.map +1 -0
- package/dist/agent/define/session.d.ts +77 -0
- package/dist/agent/define/session.d.ts.map +1 -0
- package/dist/agent/define/session.js +2 -0
- package/dist/agent/define/session.js.map +1 -0
- package/dist/agent/history/config.js +2 -0
- package/dist/agent/history/config.js.map +1 -0
- package/dist/agent/history/history.d.ts +33 -0
- package/dist/agent/history/history.d.ts.map +1 -0
- package/dist/agent/history/history.js +2 -0
- package/dist/agent/history/history.js.map +1 -0
- package/dist/agent/history/normalize.d.ts +7 -0
- package/dist/agent/history/normalize.d.ts.map +1 -0
- package/dist/agent/history/normalize.js +2 -0
- package/dist/agent/history/normalize.js.map +1 -0
- package/dist/agent/history/project.d.ts +14 -0
- package/dist/agent/history/project.d.ts.map +1 -0
- package/dist/agent/history/project.js +2 -0
- package/dist/agent/history/project.js.map +1 -0
- package/dist/agent/history/types.d.ts +85 -0
- package/dist/agent/history/types.d.ts.map +1 -0
- package/dist/agent/history/validation.js +2 -0
- package/dist/agent/history/validation.js.map +1 -0
- package/dist/agent/loop/events.d.ts +213 -0
- package/dist/agent/loop/events.d.ts.map +1 -0
- package/dist/agent/loop/queue.js +2 -0
- package/dist/agent/loop/queue.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts +8 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -0
- package/dist/agent/loop/run-turn.js +2 -0
- package/dist/agent/loop/run-turn.js.map +1 -0
- package/dist/agent/loop/schedule.d.ts +62 -0
- package/dist/agent/loop/schedule.d.ts.map +1 -0
- package/dist/agent/loop/schedule.js +3 -0
- package/dist/agent/loop/schedule.js.map +1 -0
- package/dist/agent/loop/turn/cancellation.js +2 -0
- package/dist/agent/loop/turn/cancellation.js.map +1 -0
- package/dist/agent/loop/turn/common.js +2 -0
- package/dist/agent/loop/turn/common.js.map +1 -0
- package/dist/agent/loop/turn/config.js +2 -0
- package/dist/agent/loop/turn/config.js.map +1 -0
- package/dist/agent/loop/turn/content.js +4 -0
- package/dist/agent/loop/turn/content.js.map +1 -0
- package/dist/agent/loop/turn/hooks.js +2 -0
- package/dist/agent/loop/turn/hooks.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +2 -0
- package/dist/agent/loop/turn/model-round.js.map +1 -0
- package/dist/agent/loop/turn/repetition.js +2 -0
- package/dist/agent/loop/turn/repetition.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +82 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -0
- package/dist/agent/loop/turn/usage-stop.js +2 -0
- package/dist/agent/loop/turn/usage-stop.js.map +1 -0
- package/dist/agent/loop/turn/validation.js +2 -0
- package/dist/agent/loop/turn/validation.js.map +1 -0
- package/dist/agent/loop/types.d.ts +82 -0
- package/dist/agent/loop/types.d.ts.map +1 -0
- package/dist/agent/memory/accounting-binding.js +2 -0
- package/dist/agent/memory/accounting-binding.js.map +1 -0
- package/dist/agent/memory/compaction-config.d.ts +63 -0
- package/dist/agent/memory/compaction-config.d.ts.map +1 -0
- package/dist/agent/memory/compaction-config.js +2 -0
- package/dist/agent/memory/compaction-config.js.map +1 -0
- package/dist/agent/memory/compaction.d.ts +62 -0
- package/dist/agent/memory/compaction.d.ts.map +1 -0
- package/dist/agent/memory/compaction.js +6 -0
- package/dist/agent/memory/compaction.js.map +1 -0
- package/dist/agent/memory/memory.d.ts +61 -0
- package/dist/agent/memory/memory.d.ts.map +1 -0
- package/dist/agent/memory/memory.js +5 -0
- package/dist/agent/memory/memory.js.map +1 -0
- package/dist/agent/memory/persistence-types.d.ts +44 -0
- package/dist/agent/memory/persistence-types.d.ts.map +1 -0
- package/dist/agent/memory/surface-compaction.d.ts +6 -0
- package/dist/agent/memory/surface-compaction.d.ts.map +1 -0
- package/dist/agent/memory/surface-compaction.js +4 -0
- package/dist/agent/memory/surface-compaction.js.map +1 -0
- package/dist/agent/memory/token-estimator.d.ts +12 -0
- package/dist/agent/memory/token-estimator.d.ts.map +1 -0
- package/dist/agent/memory/token-estimator.js +2 -0
- package/dist/agent/memory/token-estimator.js.map +1 -0
- package/dist/agent/mode/run-agent.d.ts +79 -0
- package/dist/agent/mode/run-agent.d.ts.map +1 -0
- package/dist/agent/mode/run-agent.js +4 -0
- package/dist/agent/mode/run-agent.js.map +1 -0
- package/dist/agent/mode/user-input.d.ts +61 -0
- package/dist/agent/mode/user-input.d.ts.map +1 -0
- package/dist/agent/mode/user-input.js +2 -0
- package/dist/agent/mode/user-input.js.map +1 -0
- package/dist/agent/skill/catalog.d.ts +53 -0
- package/dist/agent/skill/catalog.d.ts.map +1 -0
- package/dist/agent/skill/catalog.js +2 -0
- package/dist/agent/skill/catalog.js.map +1 -0
- package/dist/agent/skill/definition.d.ts +106 -0
- package/dist/agent/skill/definition.d.ts.map +1 -0
- package/dist/agent/skill/definition.js +2 -0
- package/dist/agent/skill/definition.js.map +1 -0
- package/dist/agent/skill/provider/config.d.ts +11 -0
- package/dist/agent/skill/provider/config.d.ts.map +1 -0
- package/dist/agent/skill/provider/config.js +2 -0
- package/dist/agent/skill/provider/config.js.map +1 -0
- package/dist/agent/skill/provider/context.js +2 -0
- package/dist/agent/skill/provider/context.js.map +1 -0
- package/dist/agent/skill/provider/definition.d.ts +6 -0
- package/dist/agent/skill/provider/definition.d.ts.map +1 -0
- package/dist/agent/skill/provider/definition.js +2 -0
- package/dist/agent/skill/provider/definition.js.map +1 -0
- package/dist/agent/skill/provider/snapshot.js +2 -0
- package/dist/agent/skill/provider/snapshot.js.map +1 -0
- package/dist/agent/skill/provider/types.d.ts +49 -0
- package/dist/agent/skill/provider/types.d.ts.map +1 -0
- package/dist/agent/skill/tools.d.ts +45 -0
- package/dist/agent/skill/tools.d.ts.map +1 -0
- package/dist/agent/skill/tools.js +14 -0
- package/dist/agent/skill/tools.js.map +1 -0
- package/dist/agent/team/common.d.ts +26 -0
- package/dist/agent/team/common.d.ts.map +1 -0
- package/dist/agent/team/common.js +2 -0
- package/dist/agent/team/common.js.map +1 -0
- package/dist/agent/team/composed.d.ts +45 -0
- package/dist/agent/team/composed.d.ts.map +1 -0
- package/dist/agent/team/composed.js +2 -0
- package/dist/agent/team/composed.js.map +1 -0
- package/dist/agent/team/contracts.d.ts +54 -0
- package/dist/agent/team/contracts.d.ts.map +1 -0
- package/dist/agent/team/managed.d.ts +527 -0
- package/dist/agent/team/managed.d.ts.map +1 -0
- package/dist/agent/team/managed.js +4 -0
- package/dist/agent/team/managed.js.map +1 -0
- package/dist/agent/team/team.d.ts +142 -0
- package/dist/agent/team/team.d.ts.map +1 -0
- package/dist/agent/team/team.js +2 -0
- package/dist/agent/team/team.js.map +1 -0
- package/dist/agent/team/types.d.ts +170 -0
- package/dist/agent/team/types.d.ts.map +1 -0
- package/dist/agent/tool/approval.d.ts +106 -0
- package/dist/agent/tool/approval.d.ts.map +1 -0
- package/dist/agent/tool/approval.js +2 -0
- package/dist/agent/tool/approval.js.map +1 -0
- package/dist/agent/tool/capture.js +2 -0
- package/dist/agent/tool/capture.js.map +1 -0
- package/dist/agent/tool/config.js +2 -0
- package/dist/agent/tool/config.js.map +1 -0
- package/dist/agent/tool/definition.d.ts +227 -0
- package/dist/agent/tool/definition.d.ts.map +1 -0
- package/dist/agent/tool/definition.js +2 -0
- package/dist/agent/tool/definition.js.map +1 -0
- package/dist/agent/tool/errors.d.ts +82 -0
- package/dist/agent/tool/errors.d.ts.map +1 -0
- package/dist/agent/tool/errors.js +2 -0
- package/dist/agent/tool/errors.js.map +1 -0
- package/dist/agent/tool/execution.d.ts +60 -0
- package/dist/agent/tool/execution.d.ts.map +1 -0
- package/dist/agent/tool/execution.js +2 -0
- package/dist/agent/tool/execution.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts +159 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -0
- package/dist/agent/tool/output-budget.js +3 -0
- package/dist/agent/tool/output-budget.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +98 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -0
- package/dist/agent/tool/pipeline.js +4 -0
- package/dist/agent/tool/pipeline.js.map +1 -0
- package/dist/agent/tool/registry.d.ts +70 -0
- package/dist/agent/tool/registry.d.ts.map +1 -0
- package/dist/agent/tool/registry.js +2 -0
- package/dist/agent/tool/registry.js.map +1 -0
- package/dist/agent/tool/schema.d.ts +12 -0
- package/dist/agent/tool/schema.d.ts.map +1 -0
- package/dist/agent/tool/schema.js +2 -0
- package/dist/agent/tool/schema.js.map +1 -0
- package/dist/agent/tool/source-types.d.ts +25 -0
- package/dist/agent/tool/source-types.d.ts.map +1 -0
- package/dist/agent/trace/trace.d.ts +63 -0
- package/dist/agent/trace/trace.d.ts.map +1 -0
- package/dist/agent/trace/trace.js +2 -0
- package/dist/agent/trace/trace.js.map +1 -0
- package/dist/agent.d.ts +52 -0
- package/dist/agent.js +1 -0
- package/dist/async/settlement.d.ts +6 -0
- package/dist/async/settlement.d.ts.map +1 -0
- package/dist/async/settlement.js +2 -0
- package/dist/async/settlement.js.map +1 -0
- package/dist/capability/common/config.js +2 -0
- package/dist/capability/common/config.js.map +1 -0
- package/dist/capability/common/data.js +2 -0
- package/dist/capability/common/data.js.map +1 -0
- package/dist/composition/agent/author.d.ts +12 -0
- package/dist/composition/agent/author.d.ts.map +1 -0
- package/dist/composition/agent/author.js +2 -0
- package/dist/composition/agent/author.js.map +1 -0
- package/dist/composition/agent/definition.js +2 -0
- package/dist/composition/agent/definition.js.map +1 -0
- package/dist/composition/agent/native-event.js +2 -0
- package/dist/composition/agent/native-event.js.map +1 -0
- package/dist/composition/agent/native-tools.js +2 -0
- package/dist/composition/agent/native-tools.js.map +1 -0
- package/dist/composition/agent/options.js +2 -0
- package/dist/composition/agent/options.js.map +1 -0
- package/dist/composition/agent/policy.js +2 -0
- package/dist/composition/agent/policy.js.map +1 -0
- package/dist/composition/agent/public-message.js +2 -0
- package/dist/composition/agent/public-message.js.map +1 -0
- package/dist/composition/agent/session.js +2 -0
- package/dist/composition/agent/session.js.map +1 -0
- package/dist/composition/agent/types.d.ts +218 -0
- package/dist/composition/agent/types.d.ts.map +1 -0
- package/dist/composition/common/counter.js +2 -0
- package/dist/composition/common/counter.js.map +1 -0
- package/dist/composition/common/errors.d.ts +15 -0
- package/dist/composition/common/errors.d.ts.map +1 -0
- package/dist/composition/common/errors.js +2 -0
- package/dist/composition/common/errors.js.map +1 -0
- package/dist/composition/common/json-data.js +2 -0
- package/dist/composition/common/json-data.js.map +1 -0
- package/dist/composition/credential/config.d.ts +5 -0
- package/dist/composition/credential/config.d.ts.map +1 -0
- package/dist/composition/credential/config.js +2 -0
- package/dist/composition/credential/config.js.map +1 -0
- package/dist/composition/credential/definition.d.ts +9 -0
- package/dist/composition/credential/definition.d.ts.map +1 -0
- package/dist/composition/credential/definition.js +2 -0
- package/dist/composition/credential/definition.js.map +1 -0
- package/dist/composition/credential/types.d.ts +38 -0
- package/dist/composition/credential/types.d.ts.map +1 -0
- package/dist/composition/delivery/ack.js +2 -0
- package/dist/composition/delivery/ack.js.map +1 -0
- package/dist/composition/delivery/attempt.js +2 -0
- package/dist/composition/delivery/attempt.js.map +1 -0
- package/dist/composition/delivery/batch.js +2 -0
- package/dist/composition/delivery/batch.js.map +1 -0
- package/dist/composition/delivery/checkpoint.js +2 -0
- package/dist/composition/delivery/checkpoint.js.map +1 -0
- package/dist/composition/delivery/event.js +2 -0
- package/dist/composition/delivery/event.js.map +1 -0
- package/dist/composition/delivery/resource.d.ts +11 -0
- package/dist/composition/delivery/resource.d.ts.map +1 -0
- package/dist/composition/delivery/resource.js +2 -0
- package/dist/composition/delivery/resource.js.map +1 -0
- package/dist/composition/delivery/staging.js +2 -0
- package/dist/composition/delivery/staging.js.map +1 -0
- package/dist/composition/diagnostics/config.js +2 -0
- package/dist/composition/diagnostics/config.js.map +1 -0
- package/dist/composition/diagnostics/ring.d.ts +12 -0
- package/dist/composition/diagnostics/ring.d.ts.map +1 -0
- package/dist/composition/diagnostics/ring.js +2 -0
- package/dist/composition/diagnostics/ring.js.map +1 -0
- package/dist/composition/exporter/definition.d.ts +7 -0
- package/dist/composition/exporter/definition.d.ts.map +1 -0
- package/dist/composition/exporter/definition.js +2 -0
- package/dist/composition/exporter/definition.js.map +1 -0
- package/dist/composition/exporter/lifecycle.js +2 -0
- package/dist/composition/exporter/lifecycle.js.map +1 -0
- package/dist/composition/exporter/preflight.js +2 -0
- package/dist/composition/exporter/preflight.js.map +1 -0
- package/dist/composition/exporter/types.d.ts +25 -0
- package/dist/composition/exporter/types.d.ts.map +1 -0
- package/dist/composition/exporter/types.js +2 -0
- package/dist/composition/exporter/types.js.map +1 -0
- package/dist/composition/identity/agent.js +2 -0
- package/dist/composition/identity/agent.js.map +1 -0
- package/dist/composition/lifecycle/bounded.js +2 -0
- package/dist/composition/lifecycle/bounded.js.map +1 -0
- package/dist/composition/lifecycle/operations.js +2 -0
- package/dist/composition/lifecycle/operations.js.map +1 -0
- package/dist/composition/lifecycle/types.d.ts +13 -0
- package/dist/composition/lifecycle/types.d.ts.map +1 -0
- package/dist/composition/lifecycle/types.js +2 -0
- package/dist/composition/lifecycle/types.js.map +1 -0
- package/dist/composition/logging/config.js +2 -0
- package/dist/composition/logging/config.js.map +1 -0
- package/dist/composition/logging/integration.js +2 -0
- package/dist/composition/logging/integration.js.map +1 -0
- package/dist/composition/logging/logger.d.ts +9 -0
- package/dist/composition/logging/logger.d.ts.map +1 -0
- package/dist/composition/logging/logger.js +2 -0
- package/dist/composition/logging/logger.js.map +1 -0
- package/dist/composition/memory/config.d.ts +10 -0
- package/dist/composition/memory/config.d.ts.map +1 -0
- package/dist/composition/memory/config.js +2 -0
- package/dist/composition/memory/config.js.map +1 -0
- package/dist/composition/memory/definition.d.ts +7 -0
- package/dist/composition/memory/definition.d.ts.map +1 -0
- package/dist/composition/memory/definition.js +2 -0
- package/dist/composition/memory/definition.js.map +1 -0
- package/dist/composition/memory/key.js +2 -0
- package/dist/composition/memory/key.js.map +1 -0
- package/dist/composition/memory/resume.js +2 -0
- package/dist/composition/memory/resume.js.map +1 -0
- package/dist/composition/memory/run.js +2 -0
- package/dist/composition/memory/run.js.map +1 -0
- package/dist/composition/model-catalog/config.js +2 -0
- package/dist/composition/model-catalog/config.js.map +1 -0
- package/dist/composition/model-catalog/manager.js +2 -0
- package/dist/composition/model-catalog/manager.js.map +1 -0
- package/dist/composition/model-catalog/options.js +2 -0
- package/dist/composition/model-catalog/options.js.map +1 -0
- package/dist/composition/model-catalog/types.d.ts +9 -0
- package/dist/composition/model-catalog/types.d.ts.map +1 -0
- package/dist/composition/observation/config.js +2 -0
- package/dist/composition/observation/config.js.map +1 -0
- package/dist/composition/observation/extensions.js +2 -0
- package/dist/composition/observation/extensions.js.map +1 -0
- package/dist/composition/observation/final-report.d.ts +6 -0
- package/dist/composition/observation/final-report.d.ts.map +1 -0
- package/dist/composition/observation/final-report.js +2 -0
- package/dist/composition/observation/final-report.js.map +1 -0
- package/dist/composition/observation/health.d.ts +13 -0
- package/dist/composition/observation/health.d.ts.map +1 -0
- package/dist/composition/observation/port.d.ts +11 -0
- package/dist/composition/observation/port.d.ts.map +1 -0
- package/dist/composition/observation/port.js +2 -0
- package/dist/composition/observation/port.js.map +1 -0
- package/dist/composition/preflight.js +2 -0
- package/dist/composition/preflight.js.map +1 -0
- package/dist/composition/provider/activation.js +2 -0
- package/dist/composition/provider/activation.js.map +1 -0
- package/dist/composition/provider/definition.d.ts +7 -0
- package/dist/composition/provider/definition.d.ts.map +1 -0
- package/dist/composition/provider/definition.js +2 -0
- package/dist/composition/provider/definition.js.map +1 -0
- package/dist/composition/provider/model-selection.js +2 -0
- package/dist/composition/provider/model-selection.js.map +1 -0
- package/dist/composition/provider/preflight.js +2 -0
- package/dist/composition/provider/preflight.js.map +1 -0
- package/dist/composition/provider/types.d.ts +38 -0
- package/dist/composition/provider/types.d.ts.map +1 -0
- package/dist/composition/provider/types.js +2 -0
- package/dist/composition/provider/types.js.map +1 -0
- package/dist/composition/queue/config.js +2 -0
- package/dist/composition/queue/config.js.map +1 -0
- package/dist/composition/queue/scheduler.js +2 -0
- package/dist/composition/queue/scheduler.js.map +1 -0
- package/dist/composition/queue/store.js +2 -0
- package/dist/composition/queue/store.js.map +1 -0
- package/dist/composition/runtime/config.js +2 -0
- package/dist/composition/runtime/config.js.map +1 -0
- package/dist/composition/runtime/owner.js +2 -0
- package/dist/composition/runtime/owner.js.map +1 -0
- package/dist/composition/runtime/public.d.ts +7 -0
- package/dist/composition/runtime/public.d.ts.map +1 -0
- package/dist/composition/runtime/public.js +2 -0
- package/dist/composition/runtime/public.js.map +1 -0
- package/dist/composition/runtime/types.d.ts +76 -0
- package/dist/composition/runtime/types.d.ts.map +1 -0
- package/dist/composition/startup.js +2 -0
- package/dist/composition/startup.js.map +1 -0
- package/dist/composition/team/config.js +2 -0
- package/dist/composition/team/config.js.map +1 -0
- package/dist/composition/team/options.js +2 -0
- package/dist/composition/team/options.js.map +1 -0
- package/dist/composition/team/runtime.js +2 -0
- package/dist/composition/team/runtime.js.map +1 -0
- package/dist/composition/team/types.d.ts +63 -0
- package/dist/composition/team/types.d.ts.map +1 -0
- package/dist/composition/tool-source/config.d.ts +5 -0
- package/dist/composition/tool-source/config.d.ts.map +1 -0
- package/dist/composition/tool-source/config.js +2 -0
- package/dist/composition/tool-source/config.js.map +1 -0
- package/dist/composition/tool-source/definition.d.ts +7 -0
- package/dist/composition/tool-source/definition.d.ts.map +1 -0
- package/dist/composition/tool-source/definition.js +2 -0
- package/dist/composition/tool-source/definition.js.map +1 -0
- package/dist/composition/tool-source/snapshot.js +2 -0
- package/dist/composition/tool-source/snapshot.js.map +1 -0
- package/dist/contract/adapter.d.ts +91 -0
- package/dist/contract/adapter.d.ts.map +1 -0
- package/dist/contract/adapter.js +2 -0
- package/dist/contract/adapter.js.map +1 -0
- package/dist/contract/call-config.d.ts +36 -0
- package/dist/contract/call-config.d.ts.map +1 -0
- package/dist/contract/call-config.js +2 -0
- package/dist/contract/call-config.js.map +1 -0
- package/dist/contract/generate-options.d.ts +41 -0
- package/dist/contract/generate-options.d.ts.map +1 -0
- package/dist/contract/model-info.d.ts +99 -0
- package/dist/contract/model-info.d.ts.map +1 -0
- package/dist/contract/output-format.d.ts +18 -0
- package/dist/contract/output-format.d.ts.map +1 -0
- package/dist/contract/retry-policy.d.ts +104 -0
- package/dist/contract/retry-policy.d.ts.map +1 -0
- package/dist/contract/retry-policy.js +2 -0
- package/dist/contract/retry-policy.js.map +1 -0
- package/dist/contract/tool.d.ts +65 -0
- package/dist/contract/tool.d.ts.map +1 -0
- package/dist/contract/tool.js +2 -0
- package/dist/contract/tool.js.map +1 -0
- package/dist/errors/agent-sdk-error.d.ts +88 -0
- package/dist/errors/agent-sdk-error.d.ts.map +1 -0
- package/dist/errors/agent-sdk-error.js +2 -0
- package/dist/errors/agent-sdk-error.js.map +1 -0
- package/dist/errors/capability-identity.d.ts +10 -0
- package/dist/errors/capability-identity.d.ts.map +1 -0
- package/dist/errors/capability-identity.js +2 -0
- package/dist/errors/capability-identity.js.map +1 -0
- package/dist/errors/failure.d.ts +33 -0
- package/dist/errors/failure.d.ts.map +1 -0
- package/dist/errors/failure.js +2 -0
- package/dist/errors/failure.js.map +1 -0
- package/dist/errors/model-error.d.ts +83 -0
- package/dist/errors/model-error.d.ts.map +1 -0
- package/dist/errors/model-error.js +2 -0
- package/dist/errors/model-error.js.map +1 -0
- package/dist/http/api-key.d.ts +47 -0
- package/dist/http/api-key.d.ts.map +1 -0
- package/dist/http/api-key.js +2 -0
- package/dist/http/api-key.js.map +1 -0
- package/dist/http/attribution.d.ts +51 -0
- package/dist/http/attribution.d.ts.map +1 -0
- package/dist/http/attribution.js +2 -0
- package/dist/http/attribution.js.map +1 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +1 -0
- package/dist/logging/types.d.ts +53 -0
- package/dist/logging/types.d.ts.map +1 -0
- package/dist/logging/types.js +2 -0
- package/dist/logging/types.js.map +1 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +1 -0
- package/dist/message/content.d.ts +125 -0
- package/dist/message/content.d.ts.map +1 -0
- package/dist/message/message.d.ts +154 -0
- package/dist/message/message.d.ts.map +1 -0
- package/dist/message/message.js +2 -0
- package/dist/message/message.js.map +1 -0
- package/dist/message/projection.d.ts +34 -0
- package/dist/message/projection.d.ts.map +1 -0
- package/dist/message/projection.js +2 -0
- package/dist/message/projection.js.map +1 -0
- package/dist/observability/bus.d.ts +7 -0
- package/dist/observability/bus.d.ts.map +1 -0
- package/dist/observability/bus.js +2 -0
- package/dist/observability/bus.js.map +1 -0
- package/dist/observability/exporters.d.ts +39 -0
- package/dist/observability/exporters.d.ts.map +1 -0
- package/dist/observability/exporters.js +2 -0
- package/dist/observability/exporters.js.map +1 -0
- package/dist/observability/logger.js +2 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/projections.d.ts +12 -0
- package/dist/observability/projections.d.ts.map +1 -0
- package/dist/observability/projections.js +2 -0
- package/dist/observability/projections.js.map +1 -0
- package/dist/observability/types.d.ts +103 -0
- package/dist/observability/types.d.ts.map +1 -0
- package/dist/observability.d.ts +20 -0
- package/dist/observability.js +1 -0
- package/dist/observation/boundaries.js +2 -0
- package/dist/observation/boundaries.js.map +1 -0
- package/dist/observation/context.d.ts +39 -0
- package/dist/observation/context.d.ts.map +1 -0
- package/dist/observation/context.js +2 -0
- package/dist/observation/context.js.map +1 -0
- package/dist/observation/event.d.ts +50 -0
- package/dist/observation/event.d.ts.map +1 -0
- package/dist/observation/event.js +2 -0
- package/dist/observation/event.js.map +1 -0
- package/dist/observation/port.d.ts +56 -0
- package/dist/observation/port.d.ts.map +1 -0
- package/dist/observation/port.js +2 -0
- package/dist/observation/port.js.map +1 -0
- package/dist/observation/privacy.js +2 -0
- package/dist/observation/privacy.js.map +1 -0
- package/dist/observation/report.d.ts +117 -0
- package/dist/observation/report.d.ts.map +1 -0
- package/dist/observation/report.js +2 -0
- package/dist/observation/report.js.map +1 -0
- package/dist/observation/telemetry-types.d.ts +29 -0
- package/dist/observation/telemetry-types.d.ts.map +1 -0
- package/dist/observation/usage.d.ts +52 -0
- package/dist/observation/usage.d.ts.map +1 -0
- package/dist/observation/usage.js +2 -0
- package/dist/observation/usage.js.map +1 -0
- package/dist/platform/adapter.js +2 -0
- package/dist/platform/adapter.js.map +1 -0
- package/dist/platform/capability-operation.js +2 -0
- package/dist/platform/capability-operation.js.map +1 -0
- package/dist/platform/config.js +2 -0
- package/dist/platform/config.js.map +1 -0
- package/dist/platform/logger-platform.js +2 -0
- package/dist/platform/logger-platform.js.map +1 -0
- package/dist/platform/resources.js +2 -0
- package/dist/platform/resources.js.map +1 -0
- package/dist/plugin/provider-plugin.d.ts +37 -0
- package/dist/plugin/provider-plugin.d.ts.map +1 -0
- package/dist/plugin/provider-plugin.js +2 -0
- package/dist/plugin/provider-plugin.js.map +1 -0
- package/dist/primitives/brand.d.ts +61 -0
- package/dist/primitives/brand.d.ts.map +1 -0
- package/dist/primitives/brand.js +2 -0
- package/dist/primitives/brand.js.map +1 -0
- package/dist/primitives/freeze.d.ts +20 -0
- package/dist/primitives/freeze.d.ts.map +1 -0
- package/dist/primitives/freeze.js +2 -0
- package/dist/primitives/freeze.js.map +1 -0
- package/dist/primitives/json-snapshot.js +2 -0
- package/dist/primitives/json-snapshot.js.map +1 -0
- package/dist/primitives/json.d.ts +32 -0
- package/dist/primitives/json.d.ts.map +1 -0
- package/dist/primitives/json.js +2 -0
- package/dist/primitives/json.js.map +1 -0
- package/dist/primitives/never.d.ts +22 -0
- package/dist/primitives/never.d.ts.map +1 -0
- package/dist/primitives/never.js +2 -0
- package/dist/primitives/never.js.map +1 -0
- package/dist/primitives/snapshot.d.ts +10 -0
- package/dist/primitives/snapshot.d.ts.map +1 -0
- package/dist/primitives/snapshot.js +2 -0
- package/dist/primitives/snapshot.js.map +1 -0
- package/dist/primitives/version.d.ts +6 -0
- package/dist/primitives/version.d.ts.map +1 -0
- package/dist/primitives/version.js +2 -0
- package/dist/primitives/version.js.map +1 -0
- package/dist/provider.d.ts +19 -0
- package/dist/provider.js +1 -0
- package/dist/runtime/model-call-handle.js +2 -0
- package/dist/runtime/model-call-handle.js.map +1 -0
- package/dist/runtime/model-metadata.js +2 -0
- package/dist/runtime/model-metadata.js.map +1 -0
- package/dist/runtime/model-stream.js +2 -0
- package/dist/runtime/model-stream.js.map +1 -0
- package/dist/runtime/registry.d.ts +171 -0
- package/dist/runtime/registry.d.ts.map +1 -0
- package/dist/runtime/registry.js +2 -0
- package/dist/runtime/registry.js.map +1 -0
- package/dist/runtime/with-retry.d.ts +45 -0
- package/dist/runtime/with-retry.d.ts.map +1 -0
- package/dist/runtime/with-retry.js +2 -0
- package/dist/runtime/with-retry.js.map +1 -0
- package/dist/skills.d.ts +8 -0
- package/dist/skills.js +1 -0
- package/dist/stream/assembler.d.ts +86 -0
- package/dist/stream/assembler.d.ts.map +1 -0
- package/dist/stream/assembler.js +2 -0
- package/dist/stream/assembler.js.map +1 -0
- package/dist/stream/chunk.d.ts +135 -0
- package/dist/stream/chunk.d.ts.map +1 -0
- package/dist/stream/idle-timeout.d.ts +30 -0
- package/dist/stream/idle-timeout.d.ts.map +1 -0
- package/dist/stream/idle-timeout.js +2 -0
- package/dist/stream/idle-timeout.js.map +1 -0
- package/dist/support-safe/error.d.ts +29 -0
- package/dist/support-safe/error.d.ts.map +1 -0
- package/dist/support-safe/error.js +2 -0
- package/dist/support-safe/error.js.map +1 -0
- package/dist/tools.d.ts +15 -0
- package/dist/tools.js +1 -0
- package/package.json +96 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.js","names":[],"sources":["../../../src/agent/history/history.ts"],"sourcesContent":["import type { Message } from '../../message/index.ts'\nimport { deepFreeze } from '../../primitives/index.ts'\nimport { projectHistorySurface, projectMessages } from './project.ts'\nimport {\n type SurfaceOp, type HistoryEvent, type HistoryEntry, type HistorySnapshot, type HistoryLimits,\n type ResolvedHistoryLimits,\n} from './types.ts'\nimport { resolveHistoryLimits, serializedBytes } from './config.ts'\nimport {\n snapshotEntries, assertEntriesWithinLimits, emptyValidationState, cloneValidationState,\n validateEntries, type SnapshotValidationState, validateHistoryEvent, updateVisibleMessages,\n messageOfHistoryEvent, validateSurfaceOp,\n} from './validation.ts'\n\n/** Append-only conversation history with a replaceable model-facing projection. */\nexport class History {\n private readonly log: HistoryEntry[]\n private replacementGeneration: number\n private validationState: SnapshotValidationState\n private readonly limits: ResolvedHistoryLimits\n private storedBytes = 0\n\n constructor(limits: HistoryLimits = {}) {\n this.log = []\n this.replacementGeneration = 0\n this.validationState = emptyValidationState()\n this.limits = resolveHistoryLimits(limits)\n }\n\n private static hydrate(\n entries: HistoryEntry[],\n validationState: SnapshotValidationState,\n limits: ResolvedHistoryLimits,\n storedBytes: number,\n ): History {\n const history = new History(limits)\n history.log.push(...entries)\n history.replacementGeneration = entries.filter(entry => entry.surfaceOp !== 'append').length\n history.validationState = validationState\n history.storedBytes = storedBytes\n return history\n }\n\n static fromSnapshot(snapshot: HistorySnapshot, limits: HistoryLimits = {}): History {\n const resolved = resolveHistoryLimits(limits)\n const sourceEntries = snapshotEntries(snapshot)\n if (sourceEntries.length > resolved.maxEntries) {\n throw new RangeError(`history snapshot exceeds the ${resolved.maxEntries}-entry limit`)\n }\n // Reject oversized input before duplicating it with structuredClone. The\n // detached clone is measured again because accessors/toJSON on hostile\n // objects must not be able to make the preflight size authoritative.\n assertEntriesWithinLimits(sourceEntries, resolved)\n const clone = structuredClone(sourceEntries) as HistoryEntry[]\n const storedBytes = assertEntriesWithinLimits(clone, resolved)\n const validationState = validateEntries(clone)\n return History.hydrate(clone.map(entry => deepFreeze(entry)), validationState, resolved, storedBytes)\n }\n\n private static assertCandidateWithinLimits(entry: HistoryEntry, limits: ResolvedHistoryLimits): number {\n const bytes = serializedBytes(entry)\n if (bytes > limits.maxEntryBytes) {\n throw new RangeError(`history entry exceeds the ${limits.maxEntryBytes}-byte limit`)\n }\n return bytes\n }\n\n private static cloneCandidate(\n seq: number,\n event: HistoryEvent,\n surfaceOp: SurfaceOp,\n limits: ResolvedHistoryLimits,\n ): { readonly entry: HistoryEntry; readonly bytes: number } {\n const source = { seq, event, surfaceOp }\n // Preflight before cloning so a single oversized caller value cannot force\n // an equally large detached copy merely to discover that it exceeds policy.\n History.assertCandidateWithinLimits(source, limits)\n const entry = structuredClone(source) as HistoryEntry\n return { entry, bytes: History.assertCandidateWithinLimits(entry, limits) }\n }\n\n append(event: HistoryEvent, surfaceOp: SurfaceOp = 'append'): HistoryEntry {\n return this.appendOne(event, surfaceOp)\n }\n\n /** Validate and commit related history writes atomically. */\n appendBatch(\n writes: readonly { readonly event: HistoryEvent; readonly surfaceOp?: SurfaceOp }[],\n ): readonly HistoryEntry[] {\n if (writes.length === 0) return Object.freeze([])\n if (writes.length === 1) {\n const write = writes[0]!\n return Object.freeze([this.appendOne(write.event, write.surfaceOp ?? 'append')])\n }\n if (this.log.length + writes.length > this.limits.maxEntries) {\n throw new RangeError(`history reached its ${this.limits.maxEntries}-entry limit`)\n }\n const state = cloneValidationState(this.validationState)\n const candidates: HistoryEntry[] = []\n let totalBytes = this.storedBytes\n let replacements = 0\n for (let index = 0; index < writes.length; index++) {\n const write = writes[index]!\n const surfaceOp = write.surfaceOp ?? 'append'\n const { entry: candidate, bytes: entryBytes } = History.cloneCandidate(\n this.log.length + index + 1, write.event, surfaceOp, this.limits,\n )\n validateHistoryEvent(candidate.event, candidate.seq, state)\n validateSurfaceOp(\n candidate.surfaceOp,\n candidate.seq,\n state.visibleMessageSeqs,\n messageOfHistoryEvent(candidate.event),\n )\n updateVisibleMessages(candidate, state.visibleMessageSeqs)\n totalBytes += entryBytes\n if (totalBytes > this.limits.maxBytes) {\n throw new RangeError(`history reached its ${this.limits.maxBytes}-byte limit`)\n }\n candidates.push(deepFreeze(candidate))\n if (surfaceOp !== 'append') replacements++\n }\n this.log.push(...candidates)\n this.validationState = state\n this.storedBytes = totalBytes\n this.replacementGeneration += replacements\n return Object.freeze([...candidates])\n }\n\n private appendOne(event: HistoryEvent, surfaceOp: SurfaceOp): HistoryEntry {\n if (this.log.length >= this.limits.maxEntries) {\n throw new RangeError(`history reached its ${this.limits.maxEntries}-entry limit`)\n }\n const { entry: candidate, bytes: entryBytes } = History.cloneCandidate(\n this.log.length + 1, event, surfaceOp, this.limits,\n )\n try {\n validateHistoryEvent(candidate.event, candidate.seq, this.validationState)\n validateSurfaceOp(\n candidate.surfaceOp,\n candidate.seq,\n this.validationState.visibleMessageSeqs,\n messageOfHistoryEvent(candidate.event),\n )\n updateVisibleMessages(candidate, this.validationState.visibleMessageSeqs)\n if (this.storedBytes + entryBytes > this.limits.maxBytes) {\n throw new RangeError(`history reached its ${this.limits.maxBytes}-byte limit`)\n }\n const entry = deepFreeze(candidate)\n this.log.push(entry)\n this.storedBytes += entryBytes\n if (surfaceOp !== 'append') this.replacementGeneration++\n return entry\n } catch (error: unknown) {\n // Incremental validators mutate correlation sets. Rebuild only on the\n // exceptional path so normal append stays O(1) rather than O(history).\n this.validationState = validateEntries(this.log)\n throw error\n }\n }\n\n entries(): readonly HistoryEntry[] {\n return Object.freeze([...this.log])\n }\n\n messages(): readonly Message[] {\n return projectMessages(this.log)\n }\n\n /** Current model-visible nodes with durable seq identity, in surface order. */\n surface(): readonly import('./project.ts').HistorySurfaceNode[] {\n return projectHistorySurface(this.log)\n }\n\n generation(): number {\n return this.replacementGeneration\n }\n\n snapshot(): HistorySnapshot {\n return deepFreeze(structuredClone({ version: 1 as const, entries: this.log }))\n }\n}\n\nexport type {\n SurfaceOp, CompactionBackoffReason, HistoryEvent, HistoryEntry, HistorySnapshot, HistoryLimits,\n} from './types.ts'\n"],"mappings":"2cAeA,IAAa,EAAb,MAAa,CAAQ,CACnB,IACA,sBACA,gBACA,OACA,YAAsB,EAEtB,YAAY,EAAwB,CAAC,EAAG,CACtC,KAAK,IAAM,CAAC,EACZ,KAAK,sBAAwB,EAC7B,KAAK,gBAAkB,EAAqB,EAC5C,KAAK,OAAS,EAAqB,CAAM,CAC3C,CAEA,OAAe,QACb,EACA,EACA,EACA,EACS,CACT,IAAM,EAAU,IAAI,EAAQ,CAAM,EAKlC,OAJA,EAAQ,IAAI,KAAK,GAAG,CAAO,EAC3B,EAAQ,s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AAc,EAAa,KAAK,OAAO,SAC9C,MAAU,WAAW,uBAAuB,KAAK,OAAO,SAAS,YAAY,EAE/E,IAAM,EAAQ,EAAW,CAAS,EAIlC,OAHA,KAAK,IAAI,KAAK,CAAK,EACnB,KAAK,aAAe,EAChB,IAAc,UAAU,KAAK,wBAC1B,CACT,OAAS,EAAgB,CAIvB,KADA,MAAK,gBAAkB,EAAgB,KAAK,GAAG,EACzC,CACR,CACF,CAEA,SAAmC,CACjC,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,GAAG,CAAC,CACpC,CAEA,UAA+B,CAC7B,OAAO,EAAgB,KAAK,GAAG,CACjC,CAGA,SAAgE,CAC9D,OAAO,EAAsB,KAAK,GAAG,CACvC,CAEA,YAAqB,CACnB,OAAO,KAAK,qBACd,CAEA,UAA4B,CAC1B,OAAO,EAAW,gBAAgB,CAAE,QAAS,EAAY,QAAS,KAAK,GAAI,CAAC,CAAC,CAC/E,CACF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Message } from "../../message/message.js";
|
|
2
|
+
//#region src/agent/history/normalize.d.ts
|
|
3
|
+
/** Repair provider-invalid tool pairing without mutating persisted history. */
|
|
4
|
+
declare function normalizeToolPairing(messages: readonly Message[]): readonly Message[];
|
|
5
|
+
//#endregion
|
|
6
|
+
export { normalizeToolPairing };
|
|
7
|
+
//# sourceMappingURL=normalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize.d.ts","names":[],"sources":["../../../src/agent/history/normalize.ts"],"mappings":";;;iBAKgB,qBAAqB,mBAAmB,qBAAqB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{MessageId as e}from"../../primitives/brand.js";import{freezeMessage as t}from"../../message/message.js";function n(e){let t=new Map,n=new Set;for(let r of e)for(let e of r.content)e.type===`tool-call`&&t.set(e.id,{call:e,owner:r}),e.type===`tool-result`&&t.has(e.toolCallId)&&n.add(e.toolCallId);let i=[],a=new Set;for(let t of e)if(!(t.source.kind===`tool`&&!a.has(t.source.callId))&&(i.push(t),t.role===`assistant`))for(let e of t.content)e.type===`tool-call`&&(a.add(e.id),n.has(e.id)||i.push(r(t,e.id)));return Object.freeze(i)}function r(n,r){let i=[{type:`tool-result`,toolCallId:r,content:[{type:`text`,text:`Error: the previous tool call was interrupted before a result was recorded`}],isError:!0}];return t({id:e(`synthetic-tool-result:${n.id}:${r}`),role:`user`,source:{kind:`tool`,callId:r},content:i})}export{n as normalizeToolPairing};
|
|
2
|
+
//# sourceMappingURL=normalize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize.js","names":[],"sources":["../../../src/agent/history/normalize.ts"],"sourcesContent":["import type { ContentBlock, ToolCallBlock } from '../../message/index.ts'\nimport { freezeMessage, type Message } from '../../message/index.ts'\nimport { MessageId, type ToolCallId } from '../../primitives/index.ts'\n\n/** Repair provider-invalid tool pairing without mutating persisted history. */\nexport function normalizeToolPairing(messages: readonly Message[]): readonly Message[] {\n const calls = new Map<ToolCallId, { call: ToolCallBlock; owner: Message }>()\n const answered = new Set<ToolCallId>()\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type === 'tool-call') calls.set(block.id, { call: block, owner: message })\n if (block.type === 'tool-result' && calls.has(block.toolCallId)) answered.add(block.toolCallId)\n }\n }\n\n const result: Message[] = []\n const seenCalls = new Set<ToolCallId>()\n for (const message of messages) {\n if (message.source.kind === 'tool' && !seenCalls.has(message.source.callId)) continue\n result.push(message)\n if (message.role !== 'assistant') continue\n for (const block of message.content) {\n if (block.type !== 'tool-call') continue\n seenCalls.add(block.id)\n if (!answered.has(block.id)) result.push(syntheticInterruptedResult(message, block.id))\n }\n }\n return Object.freeze(result)\n}\n\nfunction syntheticInterruptedResult(owner: Message, callId: ToolCallId): Message {\n const content: ContentBlock[] = [{\n type: 'tool-result',\n toolCallId: callId,\n content: [{ type: 'text', text: 'Error: the previous tool call was interrupted before a result was recorded' }],\n isError: true,\n }]\n return freezeMessage({\n id: MessageId(`synthetic-tool-result:${owner.id}:${callId}`),\n role: 'user',\n source: { kind: 'tool', callId },\n content,\n })\n}\n"],"mappings":"+GAKA,SAAgB,EAAqB,EAAkD,CACrF,IAAM,EAAQ,IAAI,IACZ,EAAW,IAAI,IACrB,IAAK,IAAM,KAAW,EACpB,IAAK,IAAM,KAAS,EAAQ,QACtB,EAAM,OAAS,aAAa,EAAM,IAAI,EAAM,GAAI,CAAE,KAAM,EAAO,MAAO,CAAQ,CAAC,EAC/E,EAAM,OAAS,eAAiB,EAAM,IAAI,EAAM,UAAU,GAAG,EAAS,IAAI,EAAM,UAAU,EAIlG,IAAM,EAAoB,CAAC,EACrB,EAAY,IAAI,IACtB,IAAK,IAAM,KAAW,EAChB,OAAQ,OAAO,OAAS,QAAU,CAAC,EAAU,IAAI,EAAQ,OAAO,MAAM,KAC1E,EAAO,KAAK,CAAO,EACf,EAAQ,OAAS,aACrB,IAAK,IAAM,KAAS,EAAQ,QACtB,EAAM,OAAS,cACnB,EAAU,IAAI,EAAM,EAAE,EACjB,EAAS,IAAI,EAAM,EAAE,GAAG,EAAO,KAAK,EAA2B,EAAS,EAAM,EAAE,CAAC,GAG1F,OAAO,OAAO,OAAO,CAAM,CAC7B,CAEA,SAAS,EAA2B,EAAgB,EAA6B,CAC/E,IAAM,EAA0B,CAAC,CAC/B,KAAM,cACN,WAAY,EACZ,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,4EAA6E,CAAC,EAC9G,QAAS,EACX,CAAC,EACD,OAAO,EAAc,CACnB,GAAI,EAAU,yBAAyB,EAAM,GAAG,GAAG,GAAQ,EAC3D,KAAM,OACN,OAAQ,CAAE,KAAM,OAAQ,QAAO,EAC/B,SACF,CAAC,CACH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Message } from "../../message/message.js";
|
|
2
|
+
import { HistoryEntry } from "./types.js";
|
|
3
|
+
//#region src/agent/history/project.d.ts
|
|
4
|
+
interface HistorySurfaceNode {
|
|
5
|
+
readonly seq: number;
|
|
6
|
+
readonly message: Message;
|
|
7
|
+
}
|
|
8
|
+
/** Rebuild the model-visible surface from an append-only history prefix. */
|
|
9
|
+
declare function projectMessages(entries: readonly HistoryEntry[]): readonly Message[];
|
|
10
|
+
/** Rebuild the model-visible surface while retaining durable log identities. */
|
|
11
|
+
declare function projectHistorySurface(entries: readonly HistoryEntry[]): readonly HistorySurfaceNode[];
|
|
12
|
+
//#endregion
|
|
13
|
+
export { HistorySurfaceNode, projectHistorySurface, projectMessages };
|
|
14
|
+
//# sourceMappingURL=project.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project.d.ts","names":[],"sources":["../../../src/agent/history/project.ts"],"mappings":";;;UAGiB;WACN;WACA,SAAS;;;iBAIJ,gBAAgB,kBAAkB,0BAA0B;;iBAK5D,sBAAsB,kBAAkB,0BAA0B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return Object.freeze(t(e).map(e=>e.message))}function t(e){let t=[];for(let r of e){let e=t.length;if(r.surfaceOp!==`append`){let n=r.surfaceOp,i=n.targets===void 0?void 0:new Set(n.targets),a=t.flatMap((e,t)=>i?.has(e.seq)??(e.seq>=n.from&&e.seq<=n.to)?[t]:[]);a.length>0&&(e=a[0]??t.length);for(let e=t.length-1;e>=0;e--){let r=t[e];r!==void 0&&(i?.has(r.seq)??(r.seq>=n.from&&r.seq<=n.to))&&t.splice(e,1)}}let i=n(r);i!==void 0&&t.splice(e,0,{seq:r.seq,message:i})}return Object.freeze(t.map(e=>Object.freeze({...e})))}function n(e){switch(e.event.kind){case`user`:case`assistant`:return e.event.message;case`tool-result`:return e.event.message;case`tool-call`:case`compaction-start`:case`compaction-prune`:case`compaction-summary`:case`compaction-end`:return}}export{t as projectHistorySurface,e as projectMessages};
|
|
2
|
+
//# sourceMappingURL=project.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project.js","names":[],"sources":["../../../src/agent/history/project.ts"],"sourcesContent":["import type { Message } from '../../message/index.ts'\nimport type { HistoryEntry } from './history.ts'\n\nexport interface HistorySurfaceNode {\n readonly seq: number\n readonly message: Message\n}\n\n/** Rebuild the model-visible surface from an append-only history prefix. */\nexport function projectMessages(entries: readonly HistoryEntry[]): readonly Message[] {\n return Object.freeze(projectHistorySurface(entries).map(item => item.message))\n}\n\n/** Rebuild the model-visible surface while retaining durable log identities. */\nexport function projectHistorySurface(entries: readonly HistoryEntry[]): readonly HistorySurfaceNode[] {\n const visible: HistorySurfaceNode[] = []\n for (const entry of entries) {\n let insertionIndex = visible.length\n if (entry.surfaceOp !== 'append') {\n const operation = entry.surfaceOp\n const targets = operation.targets === undefined\n ? undefined\n : new Set(operation.targets)\n const replaced = visible.flatMap((current, index) => {\n const selected = targets?.has(current.seq)\n ?? (current.seq >= operation.from && current.seq <= operation.to)\n return selected ? [index] : []\n })\n if (replaced.length > 0) insertionIndex = replaced[0] ?? visible.length\n for (let index = visible.length - 1; index >= 0; index--) {\n const current = visible[index]\n if (current !== undefined && (targets?.has(current.seq)\n ?? (current.seq >= operation.from && current.seq <= operation.to))) {\n visible.splice(index, 1)\n }\n }\n }\n const message = messageOf(entry)\n if (message !== undefined) visible.splice(insertionIndex, 0, { seq: entry.seq, message })\n }\n return Object.freeze(visible.map(item => Object.freeze({ ...item })))\n}\n\nfunction messageOf(entry: HistoryEntry): Message | undefined {\n switch (entry.event.kind) {\n case 'user':\n case 'assistant':\n return entry.event.message\n case 'tool-result':\n return entry.event.message\n case 'tool-call':\n case 'compaction-start':\n case 'compaction-prune':\n case 'compaction-summary':\n case 'compaction-end':\n return undefined\n }\n}\n"],"mappings":"AASA,SAAgB,EAAgB,EAAsD,CACpF,OAAO,OAAO,OAAO,EAAsB,CAAO,CAAC,CAAC,IAAI,GAAQ,EAAK,OAAO,CAAC,CAC/E,CAGA,SAAgB,EAAsB,EAAiE,CACrG,IAAM,EAAgC,CAAC,EACvC,IAAK,IAAM,KAAS,EAAS,CAC3B,IAAI,EAAiB,EAAQ,OAC7B,GAAI,EAAM,YAAc,SAAU,CAChC,IAAM,EAAY,EAAM,UAClB,EAAU,EAAU,UAAY,IAAA,GAClC,IAAA,GACA,IAAI,IAAI,EAAU,OAAO,EACvB,EAAW,EAAQ,SAAS,EAAS,IACxB,GAAS,IAAI,EAAQ,GAAG,IACnC,EAAQ,KAAO,EAAU,MAAQ,EAAQ,KAAO,EAAU,IAC9C,CAAC,CAAK,EAAI,CAAC,CAC9B,EACG,EAAS,OAAS,IAAG,EAAiB,EAAS,IAAM,EAAQ,QACjE,IAAK,IAAI,EAAQ,EAAQ,OAAS,EAAG,GAAS,EAAG,IAAS,CACxD,IAAM,EAAU,EAAQ,GACpB,IAAY,IAAA,KAAc,GAAS,IAAI,EAAQ,GAAG,IAChD,EAAQ,KAAO,EAAU,MAAQ,EAAQ,KAAO,EAAU,MAC9D,EAAQ,OAAO,EAAO,CAAC,CAE3B,CACF,CACA,IAAM,EAAU,EAAU,CAAK,EAC3B,IAAY,IAAA,IAAW,EAAQ,OAAO,EAAgB,EAAG,CAAE,IAAK,EAAM,IAAK,SAAQ,CAAC,CAC1F,CACA,OAAO,OAAO,OAAO,EAAQ,IAAI,GAAQ,OAAO,OAAO,CAAE,GAAG,CAAK,CAAC,CAAC,CAAC,CACtE,CAEA,SAAS,EAAU,EAA0C,CAC3D,OAAQ,EAAM,MAAM,KAApB,CACE,IAAK,OACL,IAAK,YACH,OAAO,EAAM,MAAM,QACrB,IAAK,cACH,OAAO,EAAM,MAAM,QACrB,IAAK,YACL,IAAK,mBACL,IAAK,mBACL,IAAK,qBACL,IAAK,iBACH,MACJ,CACF"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { ToolCallId } from "../../primitives/brand.js";
|
|
2
|
+
import { TokenUsage } from "../../stream/chunk.js";
|
|
3
|
+
import { Message } from "../../message/message.js";
|
|
4
|
+
import { ToolExecutionResult } from "../tool/definition.js";
|
|
5
|
+
//#region src/agent/history/types.d.ts
|
|
6
|
+
type SurfaceOp = 'append' | {
|
|
7
|
+
readonly op: 'replace';
|
|
8
|
+
/** Backward-compatible inclusive log range for simple replacements. */
|
|
9
|
+
readonly from: number;
|
|
10
|
+
readonly to: number;
|
|
11
|
+
/** Exact current-surface nodes, required when prior replacements made seqs non-contiguous. */
|
|
12
|
+
readonly targets?: readonly number[];
|
|
13
|
+
};
|
|
14
|
+
/** Shared persisted/runtime compaction backoff vocabulary. */
|
|
15
|
+
type CompactionBackoffReason = 'low-savings' | 'unreachable-threshold';
|
|
16
|
+
type HistoryEvent = {
|
|
17
|
+
readonly kind: 'user';
|
|
18
|
+
readonly message: Message;
|
|
19
|
+
} | {
|
|
20
|
+
readonly kind: 'assistant';
|
|
21
|
+
readonly message: Message;
|
|
22
|
+
readonly interrupted?: true;
|
|
23
|
+
readonly usage?: TokenUsage;
|
|
24
|
+
} | {
|
|
25
|
+
readonly kind: 'tool-call';
|
|
26
|
+
readonly callId: ToolCallId;
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly rawArguments: string;
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: 'tool-result';
|
|
31
|
+
readonly callId: ToolCallId;
|
|
32
|
+
readonly message: Message;
|
|
33
|
+
readonly result: ToolExecutionResult;
|
|
34
|
+
} | {
|
|
35
|
+
readonly kind: 'compaction-start';
|
|
36
|
+
readonly compactionId: string;
|
|
37
|
+
readonly trigger: 'pressure' | 'context-overflow' | 'manual';
|
|
38
|
+
readonly at: string;
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: 'compaction-prune';
|
|
41
|
+
readonly callId: ToolCallId;
|
|
42
|
+
readonly originalSeq: number;
|
|
43
|
+
readonly charsBefore: number;
|
|
44
|
+
readonly charsAfter: number;
|
|
45
|
+
} | {
|
|
46
|
+
readonly kind: 'compaction-summary';
|
|
47
|
+
readonly compactionId: string;
|
|
48
|
+
readonly summary: string;
|
|
49
|
+
readonly shadowedSeqs: readonly number[];
|
|
50
|
+
readonly estimatedTokensBefore: number;
|
|
51
|
+
readonly estimatedTokensAfter: number;
|
|
52
|
+
readonly provider: string;
|
|
53
|
+
readonly model: string;
|
|
54
|
+
readonly usage?: TokenUsage;
|
|
55
|
+
} | {
|
|
56
|
+
readonly kind: 'compaction-end';
|
|
57
|
+
readonly compactionId: string;
|
|
58
|
+
readonly status: 'completed' | 'failed';
|
|
59
|
+
readonly at: string;
|
|
60
|
+
readonly thresholdTokens?: number;
|
|
61
|
+
readonly estimatedNonCompactableTokens?: number;
|
|
62
|
+
readonly backoffReason?: CompactionBackoffReason;
|
|
63
|
+
readonly cooldownSteps?: number;
|
|
64
|
+
readonly error?: string;
|
|
65
|
+
};
|
|
66
|
+
interface HistoryEntry {
|
|
67
|
+
readonly seq: number;
|
|
68
|
+
readonly event: HistoryEvent;
|
|
69
|
+
readonly surfaceOp: SurfaceOp;
|
|
70
|
+
}
|
|
71
|
+
interface HistorySnapshot {
|
|
72
|
+
readonly version: 1;
|
|
73
|
+
readonly entries: readonly HistoryEntry[];
|
|
74
|
+
}
|
|
75
|
+
interface HistoryLimits {
|
|
76
|
+
/** Maximum append-only entries retained by one in-memory history. Defaults to 100,000. */
|
|
77
|
+
readonly maxEntries?: number;
|
|
78
|
+
/** Maximum serialized bytes for one entry. Defaults to 16 MiB. */
|
|
79
|
+
readonly maxEntryBytes?: number;
|
|
80
|
+
/** Maximum cumulative serialized entry bytes. Defaults to 128 MiB. */
|
|
81
|
+
readonly maxBytes?: number;
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { CompactionBackoffReason, HistoryEntry, HistoryEvent, HistoryLimits, HistorySnapshot, SurfaceOp };
|
|
85
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/agent/history/types.ts"],"mappings":";;;;;KAKY;WACD;;WAEA;WACA;;WAEA;;;KAIC;KAEA;WACG;WAAuB,SAAS;;WAElC;WACA,SAAS;WACT;WACA,QAAQ;;WAGR;WACA,QAAQ;WACR;WACA;;WAGA;WACA,QAAQ;WACR,SAAS;WACT,QAAQ;;WAGR;WACA;WACA;WACA;;WAGA;WACA,QAAQ;WACR;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,QAAQ;;WAGR;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;WAChB;WACA;;UAGI;WACN;WACA,OAAO;WACP,WAAW;;UAGL;WACN;WACA,kBAAkB;;UAGZ;;WAEN;;WAEA;;WAEA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{serializedBytes as e}from"./config.js";function t(e){if(typeof e!=`object`||!e)throw TypeError(`history snapshot must be an object`);let t=e;if(t.version!==1)throw TypeError(`unsupported history snapshot version`);if(!Array.isArray(t.entries))throw TypeError(`history snapshot entries must be an array`);return t.entries}function n(t,n){let r=0;for(let i of t){let t=e(i);if(t>n.maxEntryBytes)throw RangeError(`history snapshot entry exceeds the ${n.maxEntryBytes}-byte limit`);if(r+=t,r>n.maxBytes)throw RangeError(`history snapshot exceeds the ${n.maxBytes}-byte limit`)}return r}function r(){return{messageIds:new Set,toolCallIds:new Set,nativeToolIds:new Set,toolCallEventIds:new Set,compactions:new Map,visibleMessageSeqs:new Set}}function i(e){return{messageIds:new Set(e.messageIds),toolCallIds:new Set(e.toolCallIds),nativeToolIds:new Set(e.nativeToolIds),toolCallEventIds:new Set(e.toolCallEventIds),compactions:new Map([...e.compactions].map(([e,t])=>[e,{...t}])),visibleMessageSeqs:new Set(e.visibleMessageSeqs)}}function a(e){let t=r();for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r.seq!==n+1||typeof r.event!=`object`||r.event===null||!(`kind`in r.event))throw TypeError(`invalid history entry at index ${n}`);if(![`user`,`assistant`,`tool-call`,`tool-result`,`compaction-start`,`compaction-prune`,`compaction-summary`,`compaction-end`].includes(String(r.event.kind)))throw TypeError(`unknown history event kind at index ${n}`);o(r.event,r.seq,t),T(r.surfaceOp,r.seq,t.visibleMessageSeqs,y(r.event)),v(r,t.visibleMessageSeqs)}return t}function o(e,t,n){let r=`history entry ${t} ${e.kind}`;switch(e.kind){case`user`:s(e.message,`${r}.message`,n);return;case`assistant`:if(s(e.message,`${r}.message`,n),e.interrupted!==void 0&&e.interrupted!==!0)throw TypeError(`${r}.interrupted must be true when present`);e.usage!==void 0&&g(e.usage,`${r}.usage`);return;case`tool-call`:{let t=x(e.callId,`${r}.callId`);if(n.toolCallEventIds.has(t))throw TypeError(`duplicate tool-call event id '${t}'`);if(n.toolCallEventIds.add(t),x(e.name,`${r}.name`),typeof e.rawArguments!=`string`)throw TypeError(`${r}.rawArguments must be a string`);return}case`tool-result`:{let t=x(e.callId,`${r}.callId`);s(e.message,`${r}.message`,n),p(e.message,t,`${r}.message`),m(e.result,`${r}.result`);return}case`compaction-start`:{let t=x(e.compactionId,`${r}.compactionId`);if(n.compactions.has(t))throw TypeError(`duplicate compaction id '${t}'`);if(![`pressure`,`context-overflow`,`manual`].includes(e.trigger))throw TypeError(`${r}.trigger is invalid`);w(e.at,`${r}.at`),n.compactions.set(t,{summary:!1,end:!1});return}case`compaction-prune`:if(x(e.callId,`${r}.callId`),S(e.originalSeq,`${r}.originalSeq`),e.originalSeq>=t)throw TypeError(`${r}.originalSeq must reference an earlier entry`);if(C(e.charsBefore,`${r}.charsBefore`),C(e.charsAfter,`${r}.charsAfter`),e.charsAfter>e.charsBefore)throw TypeError(`${r}.charsAfter cannot exceed charsBefore`);return;case`compaction-summary`:{let i=x(e.compactionId,`${r}.compactionId`),a=n.compactions.get(i);if(a===void 0)throw TypeError(`${r} has no matching compaction-start`);if(a.summary)throw TypeError(`duplicate compaction summary for '${i}'`);if(a.end)throw TypeError(`${r} appears after compaction-end`);x(e.summary,`${r}.summary`),_(e.shadowedSeqs,t,`${r}.shadowedSeqs`);for(let t of e.shadowedSeqs)if(!n.visibleMessageSeqs.has(t))throw TypeError(`${r}.shadowedSeqs references non-visible message ${t}`);if(C(e.estimatedTokensBefore,`${r}.estimatedTokensBefore`),C(e.estimatedTokensAfter,`${r}.estimatedTokensAfter`),e.estimatedTokensAfter>e.estimatedTokensBefore)throw TypeError(`${r}.estimatedTokensAfter cannot exceed estimatedTokensBefore`);x(e.provider,`${r}.provider`),x(e.model,`${r}.model`),e.usage!==void 0&&g(e.usage,`${r}.usage`),a.summary=!0;return}case`compaction-end`:{let t=x(e.compactionId,`${r}.compactionId`),i=n.compactions.get(t);if(i===void 0)throw TypeError(`${r} has no matching compaction-start`);if(i.end)throw TypeError(`duplicate compaction end for '${t}'`);if(![`completed`,`failed`].includes(e.status))throw TypeError(`${r}.status is invalid`);if(w(e.at,`${r}.at`),e.thresholdTokens!==void 0&&S(e.thresholdTokens,`${r}.thresholdTokens`),e.estimatedNonCompactableTokens!==void 0&&C(e.estimatedNonCompactableTokens,`${r}.estimatedNonCompactableTokens`),e.backoffReason!==void 0&&![`low-savings`,`unreachable-threshold`].includes(e.backoffReason))throw TypeError(`${r}.backoffReason is invalid`);if(e.cooldownSteps!==void 0&&S(e.cooldownSteps,`${r}.cooldownSteps`),e.backoffReason===void 0!=(e.cooldownSteps===void 0))throw TypeError(`${r}.backoffReason and cooldownSteps must be set together`);if(e.backoffReason!==void 0&&e.thresholdTokens===void 0)throw TypeError(`${r}.backoffReason requires thresholdTokens`);if(e.status===`completed`){if(!i.summary)throw TypeError(`${r} completed without a compaction-summary`);if(e.error!==void 0)throw TypeError(`${r}.error is only valid for failed compaction`)}else if(x(e.error,`${r}.error`),e.backoffReason!==void 0||e.thresholdTokens!==void 0||e.estimatedNonCompactableTokens!==void 0)throw TypeError(`${r} failed compaction cannot carry completed metrics`);i.end=!0;return}}}function s(e,t,n){if(!b(e))throw TypeError(`${t} must be an object`);let r=x(e.id,`${t}.id`);if(n.messageIds.has(r))throw TypeError(`duplicate message id '${r}'`);if(n.messageIds.add(r),![`system`,`user`,`assistant`].includes(String(e.role)))throw TypeError(`${t}.role is invalid`);if(!Array.isArray(e.content))throw TypeError(`${t}.content must be an array`);for(let r=0;r<e.content.length;r++)l(e.content[r],`${t}.content[${r}]`,n,new Set,0);c(e.source,`${t}.source`)}function c(e,t){if(!b(e))throw TypeError(`${t} must be an object`);switch(x(e.kind,`${t}.kind`)){case`user`:return;case`app`:x(e.producer,`${t}.producer`);return;case`model`:x(e.provider,`${t}.provider`),x(e.model,`${t}.model`);return;case`tool`:x(e.callId,`${t}.callId`);return;default:return}}function l(e,t,n,r,i){if(i>64)throw TypeError(`${t} exceeds the maximum content depth`);if(!b(e))throw TypeError(`${t} must be an object`);if(r.has(e))throw TypeError(`${t} must not contain a cycle`);let a=new Set(r).add(e);switch(x(e.type,`${t}.type`)){case`text`:if(typeof e.text!=`string`)throw TypeError(`${t}.text must be a string`);if(e.phase!==void 0&&![`commentary`,`final-answer`].includes(String(e.phase)))throw TypeError(`${t}.phase is invalid`);if(e.annotations!==void 0){if(!Array.isArray(e.annotations))throw TypeError(`${t}.annotations must be an array`);for(let n=0;n<e.annotations.length;n++)d(e.annotations[n],`${t}.annotations[${n}]`)}return;case`reasoning`:if(typeof e.text!=`string`)throw TypeError(`${t}.text must be a string`);return;case`image`:f(e.source,`${t}.source`);return;case`native-tool-call`:{let r=x(e.id,`${t}.id`);if(n.nativeToolIds.has(r))throw TypeError(`duplicate native tool id '${r}'`);n.nativeToolIds.add(r)}if(x(e.name,`${t}.name`),e.status!==void 0&&typeof e.status!=`string`)throw TypeError(`${t}.status must be a string`);u(e.content,`${t}.content`,n,a,i+1);return;case`tool-call`:{let r=x(e.id,`${t}.id`);if(n.toolCallIds.has(r))throw TypeError(`duplicate tool call id '${r}'`);if(n.toolCallIds.add(r),x(e.name,`${t}.name`),typeof e.arguments!=`string`)throw TypeError(`${t}.arguments must be a string`);return}case`tool-result`:if(x(e.toolCallId,`${t}.toolCallId`),e.isError!==void 0&&typeof e.isError!=`boolean`)throw TypeError(`${t}.isError must be a boolean`);u(e.content,`${t}.content`,n,a,i+1);return;default:return}}function u(e,t,n,r,i){if(!Array.isArray(e))throw TypeError(`${t} must be an array`);for(let a=0;a<e.length;a++)l(e[a],`${t}[${a}]`,n,r,i)}function d(e,t){if(!b(e))throw TypeError(`${t} must be an object`);if(x(e.type,`${t}.type`)===`url-citation`){if(x(e.url,`${t}.url`),e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`${t}.title must be a string`);for(let n of[`startIndex`,`endIndex`])e[n]!==void 0&&C(e[n],`${t}.${n}`)}}function f(e,t){if(!b(e))throw TypeError(`${t} must be an object`);let n=x(e.kind,`${t}.kind`);if(n===`base64`){if(![`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(String(e.mediaType)))throw TypeError(`${t}.mediaType is invalid`);if(typeof e.data!=`string`)throw TypeError(`${t}.data must be a string`)}else if(n===`url`)x(e.url,`${t}.url`);else if(n===`file`)x(e.fileId,`${t}.fileId`);else throw TypeError(`${t}.kind is invalid`)}function p(e,t,n){if(e.source.kind!==`tool`||e.source.callId!==t)throw TypeError(`${n}.source.callId must match its tool-result event`);if(e.role!==`user`||e.content.length!==1||e.content[0]?.type!==`tool-result`||e.content[0].toolCallId!==t)throw TypeError(`${n} must carry exactly one matching tool-result block`)}function m(e,t){if(!b(e)||typeof e.isError!=`boolean`)throw TypeError(`${t}.isError must be a boolean`);if(h(e.content,`${t}.content`),e.additionalContext!==void 0&&h(e.additionalContext,`${t}.additionalContext`),e.meta!==void 0&&!b(e.meta))throw TypeError(`${t}.meta must be an object`);if(e.isError){if(!b(e.error))throw TypeError(`${t}.error must be an object`);if(x(e.error.message,`${t}.error.message`),x(e.error.code,`${t}.error.code`),e.concludesTurn!==void 0)throw TypeError(`${t}.concludesTurn is invalid for a failure`)}else if(e.concludesTurn!==void 0&&e.concludesTurn!==!0)throw TypeError(`${t}.concludesTurn must be true when present`)}function h(e,t){u(e,t,{messageIds:new Set,toolCallIds:new Set,nativeToolIds:new Set,toolCallEventIds:new Set,compactions:new Map,visibleMessageSeqs:new Set},new Set,0)}function g(e,t){if(!b(e))throw TypeError(`${t} must be an object`);for(let n of[`inputTokens`,`outputTokens`,`totalTokens`,`cacheReadTokens`,`cacheWriteTokens`,`reasoningTokens`]){let r=e[n];(n===`inputTokens`||n===`outputTokens`||r!==void 0)&&C(r,`${t}.${n}`)}}function _(e,t,n){if(!Array.isArray(e)||e.length===0||new Set(e).size!==e.length||e.some(e=>!Number.isInteger(e)||e<1||e>=t))throw TypeError(`${n} must contain unique earlier sequence numbers`)}function v(e,t){if(e.surfaceOp!==`append`){let n=e.surfaceOp,r=n.targets===void 0?[...t].filter(e=>e>=n.from&&e<=n.to):[...n.targets];for(let e of r)t.delete(e)}y(e.event)&&t.add(e.seq)}function y(e){return e.kind===`user`||e.kind===`assistant`||e.kind===`tool-result`}function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e,t){if(typeof e!=`string`||e.trim().length===0)throw TypeError(`${t} must be a non-empty string`);return e}function S(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw TypeError(`${t} must be a positive integer`)}function C(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw TypeError(`${t} must be a non-negative integer`)}function w(e,t){let n=x(e,t),r=new Date(n);if(Number.isNaN(r.valueOf())||r.toISOString()!==n)throw TypeError(`${t} must be an ISO timestamp`)}function T(e,t,n,r=!0){if(e!==`append`){if(typeof e!=`object`||e.op!==`replace`||!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<1||e.to<e.from||e.to>=t)throw TypeError(`history replace span must reference an earlier inclusive sequence range`);if(e.targets!==void 0){if(e.targets.length===0||new Set(e.targets).size!==e.targets.length||e.targets.some(e=>!Number.isInteger(e)||e<1||e>=t))throw TypeError(`history replace targets must be unique earlier sequence numbers`);if(e.targets.some(t=>t<e.from||t>e.to))throw TypeError(`history replace targets must stay within its inclusive sequence range`)}if(n!==void 0){if(!r)throw TypeError(`history replacement entry must carry a message`);let t=e.targets??[...n].filter(t=>t>=e.from&&t<=e.to);if(t.length===0||t.some(e=>!n.has(e)))throw TypeError(`history replace targets must reference current visible messages`)}}}export{n as assertEntriesWithinLimits,i as cloneValidationState,r as emptyValidationState,b as isRecord,y as messageOfHistoryEvent,x as nonEmptyString,C as nonNegativeInteger,S as positiveInteger,t as snapshotEntries,v as updateVisibleMessages,u as validateContentArray,l as validateContentBlock,h as validateDetachedContent,a as validateEntries,o as validateHistoryEvent,f as validateImageSource,w as validateIsoTimestamp,s as validateMessage,c as validateMessageSource,_ as validateSeqTargets,T as validateSurfaceOp,d as validateTextAnnotation,m as validateToolExecutionResult,p as validateToolResultMessage,g as validateUsage};
|
|
2
|
+
//# sourceMappingURL=validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../../src/agent/history/validation.ts"],"sourcesContent":["import type { Message } from '../../message/index.ts'\nimport {\n type SurfaceOp, type HistoryEvent, type HistoryEntry, type HistorySnapshot,\n type ResolvedHistoryLimits,\n} from './types.ts'\nimport { MAX_CONTENT_DEPTH, serializedBytes } from './config.ts'\n\nexport function snapshotEntries(value: unknown): readonly HistoryEntry[] {\n if (typeof value !== 'object' || value === null) throw new TypeError('history snapshot must be an object')\n const snapshot = value as Partial<HistorySnapshot>\n if (snapshot.version !== 1) throw new TypeError('unsupported history snapshot version')\n if (!Array.isArray(snapshot.entries)) throw new TypeError('history snapshot entries must be an array')\n return snapshot.entries as readonly HistoryEntry[]\n}\n\nexport function assertEntriesWithinLimits(entries: readonly HistoryEntry[], limits: ResolvedHistoryLimits): number {\n let totalBytes = 0\n for (const entry of entries) {\n const bytes = serializedBytes(entry)\n if (bytes > limits.maxEntryBytes) {\n throw new RangeError(`history snapshot entry exceeds the ${limits.maxEntryBytes}-byte limit`)\n }\n totalBytes += bytes\n if (totalBytes > limits.maxBytes) {\n throw new RangeError(`history snapshot exceeds the ${limits.maxBytes}-byte limit`)\n }\n }\n return totalBytes\n}\n\nexport function emptyValidationState(): SnapshotValidationState {\n return {\n messageIds: new Set(),\n toolCallIds: new Set(),\n nativeToolIds: new Set(),\n toolCallEventIds: new Set(),\n compactions: new Map(),\n visibleMessageSeqs: new Set(),\n }\n}\n\nexport function cloneValidationState(state: SnapshotValidationState): SnapshotValidationState {\n return {\n messageIds: new Set(state.messageIds),\n toolCallIds: new Set(state.toolCallIds),\n nativeToolIds: new Set(state.nativeToolIds),\n toolCallEventIds: new Set(state.toolCallEventIds),\n compactions: new Map([...state.compactions].map(([id, lifecycle]) => [id, { ...lifecycle }])),\n visibleMessageSeqs: new Set(state.visibleMessageSeqs),\n }\n}\n\nexport function validateEntries(entries: readonly HistoryEntry[]): SnapshotValidationState {\n const state = emptyValidationState()\n for (let index = 0; index < entries.length; index++) {\n const entry = entries[index] as Partial<HistoryEntry> | undefined\n if (entry === undefined || entry.seq !== index + 1 || typeof entry.event !== 'object'\n || entry.event === null || !('kind' in entry.event)) {\n throw new TypeError(`invalid history entry at index ${index}`)\n }\n if (![\n 'user', 'assistant', 'tool-call', 'tool-result',\n 'compaction-start', 'compaction-prune', 'compaction-summary', 'compaction-end',\n ].includes(String(entry.event.kind))) {\n throw new TypeError(`unknown history event kind at index ${index}`)\n }\n validateHistoryEvent(entry.event, entry.seq, state)\n validateSurfaceOp(\n entry.surfaceOp as SurfaceOp,\n entry.seq,\n state.visibleMessageSeqs,\n messageOfHistoryEvent(entry.event),\n )\n updateVisibleMessages(entry as HistoryEntry, state.visibleMessageSeqs)\n }\n return state\n}\n\nexport interface SnapshotValidationState {\n readonly messageIds: Set<string>\n readonly toolCallIds: Set<string>\n readonly nativeToolIds: Set<string>\n readonly toolCallEventIds: Set<string>\n readonly compactions: Map<string, { summary: boolean; end: boolean }>\n readonly visibleMessageSeqs: Set<number>\n}\n\nexport function validateHistoryEvent(\n event: HistoryEvent,\n seq: number,\n state: SnapshotValidationState,\n): void {\n const path = `history entry ${seq} ${event.kind}`\n switch (event.kind) {\n case 'user':\n validateMessage(event.message, `${path}.message`, state)\n return\n case 'assistant':\n validateMessage(event.message, `${path}.message`, state)\n if (event.interrupted !== undefined && event.interrupted !== true) {\n throw new TypeError(`${path}.interrupted must be true when present`)\n }\n if (event.usage !== undefined) validateUsage(event.usage, `${path}.usage`)\n return\n case 'tool-call': {\n const callId = nonEmptyString(event.callId, `${path}.callId`)\n if (state.toolCallEventIds.has(callId)) throw new TypeError(`duplicate tool-call event id '${callId}'`)\n state.toolCallEventIds.add(callId)\n nonEmptyString(event.name, `${path}.name`)\n if (typeof event.rawArguments !== 'string') throw new TypeError(`${path}.rawArguments must be a string`)\n return\n }\n case 'tool-result': {\n const callId = nonEmptyString(event.callId, `${path}.callId`)\n validateMessage(event.message, `${path}.message`, state)\n validateToolResultMessage(event.message, callId, `${path}.message`)\n validateToolExecutionResult(event.result, `${path}.result`)\n return\n }\n case 'compaction-start': {\n const id = nonEmptyString(event.compactionId, `${path}.compactionId`)\n if (state.compactions.has(id)) throw new TypeError(`duplicate compaction id '${id}'`)\n if (!['pressure', 'context-overflow', 'manual'].includes(event.trigger)) {\n throw new TypeError(`${path}.trigger is invalid`)\n }\n validateIsoTimestamp(event.at, `${path}.at`)\n state.compactions.set(id, { summary: false, end: false })\n return\n }\n case 'compaction-prune':\n nonEmptyString(event.callId, `${path}.callId`)\n positiveInteger(event.originalSeq, `${path}.originalSeq`)\n if (event.originalSeq >= seq) throw new TypeError(`${path}.originalSeq must reference an earlier entry`)\n nonNegativeInteger(event.charsBefore, `${path}.charsBefore`)\n nonNegativeInteger(event.charsAfter, `${path}.charsAfter`)\n if (event.charsAfter > event.charsBefore) throw new TypeError(`${path}.charsAfter cannot exceed charsBefore`)\n return\n case 'compaction-summary': {\n const id = nonEmptyString(event.compactionId, `${path}.compactionId`)\n const lifecycle = state.compactions.get(id)\n if (lifecycle === undefined) throw new TypeError(`${path} has no matching compaction-start`)\n if (lifecycle.summary) throw new TypeError(`duplicate compaction summary for '${id}'`)\n if (lifecycle.end) throw new TypeError(`${path} appears after compaction-end`)\n nonEmptyString(event.summary, `${path}.summary`)\n validateSeqTargets(event.shadowedSeqs, seq, `${path}.shadowedSeqs`)\n for (const target of event.shadowedSeqs) {\n if (!state.visibleMessageSeqs.has(target)) {\n throw new TypeError(`${path}.shadowedSeqs references non-visible message ${target}`)\n }\n }\n nonNegativeInteger(event.estimatedTokensBefore, `${path}.estimatedTokensBefore`)\n nonNegativeInteger(event.estimatedTokensAfter, `${path}.estimatedTokensAfter`)\n if (event.estimatedTokensAfter > event.estimatedTokensBefore) {\n throw new TypeError(`${path}.estimatedTokensAfter cannot exceed estimatedTokensBefore`)\n }\n nonEmptyString(event.provider, `${path}.provider`)\n nonEmptyString(event.model, `${path}.model`)\n if (event.usage !== undefined) validateUsage(event.usage, `${path}.usage`)\n lifecycle.summary = true\n return\n }\n case 'compaction-end': {\n const id = nonEmptyString(event.compactionId, `${path}.compactionId`)\n const lifecycle = state.compactions.get(id)\n if (lifecycle === undefined) throw new TypeError(`${path} has no matching compaction-start`)\n if (lifecycle.end) throw new TypeError(`duplicate compaction end for '${id}'`)\n if (!['completed', 'failed'].includes(event.status)) throw new TypeError(`${path}.status is invalid`)\n validateIsoTimestamp(event.at, `${path}.at`)\n if (event.thresholdTokens !== undefined) positiveInteger(event.thresholdTokens, `${path}.thresholdTokens`)\n if (event.estimatedNonCompactableTokens !== undefined) {\n nonNegativeInteger(event.estimatedNonCompactableTokens, `${path}.estimatedNonCompactableTokens`)\n }\n if (event.backoffReason !== undefined\n && !['low-savings', 'unreachable-threshold'].includes(event.backoffReason)) {\n throw new TypeError(`${path}.backoffReason is invalid`)\n }\n if (event.cooldownSteps !== undefined) positiveInteger(event.cooldownSteps, `${path}.cooldownSteps`)\n if ((event.backoffReason === undefined) !== (event.cooldownSteps === undefined)) {\n throw new TypeError(`${path}.backoffReason and cooldownSteps must be set together`)\n }\n if (event.backoffReason !== undefined && event.thresholdTokens === undefined) {\n throw new TypeError(`${path}.backoffReason requires thresholdTokens`)\n }\n if (event.status === 'completed') {\n if (!lifecycle.summary) throw new TypeError(`${path} completed without a compaction-summary`)\n if (event.error !== undefined) throw new TypeError(`${path}.error is only valid for failed compaction`)\n } else {\n nonEmptyString(event.error, `${path}.error`)\n if (event.backoffReason !== undefined || event.thresholdTokens !== undefined\n || event.estimatedNonCompactableTokens !== undefined) {\n throw new TypeError(`${path} failed compaction cannot carry completed metrics`)\n }\n }\n lifecycle.end = true\n return\n }\n }\n}\n\nexport function validateMessage(value: unknown, path: string, state: SnapshotValidationState): asserts value is Message {\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n const id = nonEmptyString(value.id, `${path}.id`)\n if (state.messageIds.has(id)) throw new TypeError(`duplicate message id '${id}'`)\n state.messageIds.add(id)\n if (!['system', 'user', 'assistant'].includes(String(value.role))) {\n throw new TypeError(`${path}.role is invalid`)\n }\n if (!Array.isArray(value.content)) throw new TypeError(`${path}.content must be an array`)\n for (let index = 0; index < value.content.length; index++) {\n validateContentBlock(value.content[index], `${path}.content[${index}]`, state, new Set(), 0)\n }\n validateMessageSource(value.source, `${path}.source`)\n}\n\nexport function validateMessageSource(value: unknown, path: string): void {\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n const kind = nonEmptyString(value.kind, `${path}.kind`)\n switch (kind) {\n case 'user': return\n case 'app': nonEmptyString(value.producer, `${path}.producer`); return\n case 'model':\n nonEmptyString(value.provider, `${path}.provider`)\n nonEmptyString(value.model, `${path}.model`)\n return\n case 'tool': nonEmptyString(value.callId, `${path}.callId`); return\n default:\n // Message sources and content blocks are declaration-merge extensible.\n // Preserve third-party kinds while still requiring their discriminator.\n return\n }\n}\n\nexport function validateContentBlock(\n value: unknown,\n path: string,\n state: SnapshotValidationState,\n ancestors: Set<object>,\n depth: number,\n): void {\n if (depth > MAX_CONTENT_DEPTH) throw new TypeError(`${path} exceeds the maximum content depth`)\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n if (ancestors.has(value)) throw new TypeError(`${path} must not contain a cycle`)\n const nextAncestors = new Set(ancestors).add(value)\n const type = nonEmptyString(value.type, `${path}.type`)\n switch (type) {\n case 'text':\n if (typeof value.text !== 'string') throw new TypeError(`${path}.text must be a string`)\n if (value.phase !== undefined && !['commentary', 'final-answer'].includes(String(value.phase))) {\n throw new TypeError(`${path}.phase is invalid`)\n }\n if (value.annotations !== undefined) {\n if (!Array.isArray(value.annotations)) throw new TypeError(`${path}.annotations must be an array`)\n for (let index = 0; index < value.annotations.length; index++) {\n validateTextAnnotation(value.annotations[index], `${path}.annotations[${index}]`)\n }\n }\n return\n case 'reasoning':\n if (typeof value.text !== 'string') throw new TypeError(`${path}.text must be a string`)\n return\n case 'image': validateImageSource(value.source, `${path}.source`); return\n case 'native-tool-call':\n {\n const id = nonEmptyString(value.id, `${path}.id`)\n if (state.nativeToolIds.has(id)) throw new TypeError(`duplicate native tool id '${id}'`)\n state.nativeToolIds.add(id)\n }\n nonEmptyString(value.name, `${path}.name`)\n if (value.status !== undefined && typeof value.status !== 'string') {\n throw new TypeError(`${path}.status must be a string`)\n }\n validateContentArray(value.content, `${path}.content`, state, nextAncestors, depth + 1)\n return\n case 'tool-call': {\n const id = nonEmptyString(value.id, `${path}.id`)\n if (state.toolCallIds.has(id)) throw new TypeError(`duplicate tool call id '${id}'`)\n state.toolCallIds.add(id)\n nonEmptyString(value.name, `${path}.name`)\n if (typeof value.arguments !== 'string') throw new TypeError(`${path}.arguments must be a string`)\n return\n }\n case 'tool-result':\n nonEmptyString(value.toolCallId, `${path}.toolCallId`)\n if (value.isError !== undefined && typeof value.isError !== 'boolean') {\n throw new TypeError(`${path}.isError must be a boolean`)\n }\n validateContentArray(value.content, `${path}.content`, state, nextAncestors, depth + 1)\n return\n default:\n return\n }\n}\n\nexport function validateContentArray(\n value: unknown,\n path: string,\n state: SnapshotValidationState,\n ancestors: Set<object>,\n depth: number,\n): void {\n if (!Array.isArray(value)) throw new TypeError(`${path} must be an array`)\n for (let index = 0; index < value.length; index++) {\n validateContentBlock(value[index], `${path}[${index}]`, state, ancestors, depth)\n }\n}\n\nexport function validateTextAnnotation(value: unknown, path: string): void {\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n const type = nonEmptyString(value.type, `${path}.type`)\n if (type !== 'url-citation') return\n nonEmptyString(value.url, `${path}.url`)\n if (value.title !== undefined && typeof value.title !== 'string') throw new TypeError(`${path}.title must be a string`)\n for (const field of ['startIndex', 'endIndex'] as const) {\n if (value[field] !== undefined) nonNegativeInteger(value[field], `${path}.${field}`)\n }\n}\n\nexport function validateImageSource(value: unknown, path: string): void {\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n const kind = nonEmptyString(value.kind, `${path}.kind`)\n if (kind === 'base64') {\n if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(String(value.mediaType))) {\n throw new TypeError(`${path}.mediaType is invalid`)\n }\n if (typeof value.data !== 'string') throw new TypeError(`${path}.data must be a string`)\n } else if (kind === 'url') {\n nonEmptyString(value.url, `${path}.url`)\n } else if (kind === 'file') {\n nonEmptyString(value.fileId, `${path}.fileId`)\n } else {\n throw new TypeError(`${path}.kind is invalid`)\n }\n}\n\nexport function validateToolResultMessage(message: Message, callId: string, path: string): void {\n if (message.source.kind !== 'tool' || message.source.callId !== callId) {\n throw new TypeError(`${path}.source.callId must match its tool-result event`)\n }\n if (message.role !== 'user' || message.content.length !== 1\n || message.content[0]?.type !== 'tool-result'\n || message.content[0].toolCallId !== callId) {\n throw new TypeError(`${path} must carry exactly one matching tool-result block`)\n }\n}\n\nexport function validateToolExecutionResult(value: unknown, path: string): void {\n if (!isRecord(value) || typeof value.isError !== 'boolean') {\n throw new TypeError(`${path}.isError must be a boolean`)\n }\n validateDetachedContent(value.content, `${path}.content`)\n if (value.additionalContext !== undefined) {\n validateDetachedContent(value.additionalContext, `${path}.additionalContext`)\n }\n if (value.meta !== undefined && (!isRecord(value.meta))) throw new TypeError(`${path}.meta must be an object`)\n if (value.isError) {\n if (!isRecord(value.error)) throw new TypeError(`${path}.error must be an object`)\n nonEmptyString(value.error.message, `${path}.error.message`)\n nonEmptyString(value.error.code, `${path}.error.code`)\n if (value.concludesTurn !== undefined) throw new TypeError(`${path}.concludesTurn is invalid for a failure`)\n } else if (value.concludesTurn !== undefined && value.concludesTurn !== true) {\n throw new TypeError(`${path}.concludesTurn must be true when present`)\n }\n}\n\nexport function validateDetachedContent(value: unknown, path: string): void {\n const state: SnapshotValidationState = {\n messageIds: new Set(), toolCallIds: new Set(), nativeToolIds: new Set(), toolCallEventIds: new Set(),\n compactions: new Map(), visibleMessageSeqs: new Set(),\n }\n validateContentArray(value, path, state, new Set(), 0)\n}\n\nexport function validateUsage(value: unknown, path: string): void {\n if (!isRecord(value)) throw new TypeError(`${path} must be an object`)\n for (const field of [\n 'inputTokens', 'outputTokens', 'totalTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens',\n ] as const) {\n const tokenCount = value[field]\n if ((field === 'inputTokens' || field === 'outputTokens') || tokenCount !== undefined) {\n nonNegativeInteger(tokenCount, `${path}.${field}`)\n }\n }\n}\n\nexport function validateSeqTargets(value: unknown, nextSeq: number, path: string): asserts value is readonly number[] {\n if (!Array.isArray(value) || value.length === 0 || new Set(value).size !== value.length) {\n throw new TypeError(`${path} must contain unique earlier sequence numbers`)\n }\n if (value.some(seq => !Number.isInteger(seq) || seq < 1 || seq >= nextSeq)) {\n throw new TypeError(`${path} must contain unique earlier sequence numbers`)\n }\n}\n\nexport function updateVisibleMessages(entry: HistoryEntry, visible: Set<number>): void {\n if (entry.surfaceOp !== 'append') {\n const operation = entry.surfaceOp\n const targets = operation.targets === undefined\n ? [...visible].filter(seq => seq >= operation.from && seq <= operation.to)\n : [...operation.targets]\n for (const target of targets) visible.delete(target)\n }\n if (messageOfHistoryEvent(entry.event)) visible.add(entry.seq)\n}\n\nexport function messageOfHistoryEvent(event: HistoryEvent): boolean {\n return event.kind === 'user' || event.kind === 'assistant' || event.kind === 'tool-result'\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function nonEmptyString(value: unknown, path: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) throw new TypeError(`${path} must be a non-empty string`)\n return value\n}\n\nexport function positiveInteger(value: unknown, path: string): asserts value is number {\n if (!Number.isSafeInteger(value) || Number(value) < 1) throw new TypeError(`${path} must be a positive integer`)\n}\n\nexport function nonNegativeInteger(value: unknown, path: string): asserts value is number {\n if (!Number.isSafeInteger(value) || Number(value) < 0) throw new TypeError(`${path} must be a non-negative integer`)\n}\n\nexport function validateIsoTimestamp(value: unknown, path: string): void {\n const timestamp = nonEmptyString(value, path)\n const date = new Date(timestamp)\n if (Number.isNaN(date.valueOf()) || date.toISOString() !== timestamp) {\n throw new TypeError(`${path} must be an ISO timestamp`)\n }\n}\n\nexport function validateSurfaceOp(\n op: SurfaceOp,\n nextSeq: number,\n visible?: ReadonlySet<number>,\n replacementCarriesMessage = true,\n): void {\n if (op === 'append') return\n if (typeof op !== 'object' || op.op !== 'replace'\n || !Number.isInteger(op.from) || !Number.isInteger(op.to)\n || op.from < 1 || op.to < op.from || op.to >= nextSeq) {\n throw new TypeError('history replace span must reference an earlier inclusive sequence range')\n }\n if (op.targets !== undefined) {\n if (op.targets.length === 0 || new Set(op.targets).size !== op.targets.length\n || op.targets.some(seq => !Number.isInteger(seq) || seq < 1 || seq >= nextSeq)) {\n throw new TypeError('history replace targets must be unique earlier sequence numbers')\n }\n if (op.targets.some(seq => seq < op.from || seq > op.to)) {\n throw new TypeError('history replace targets must stay within its inclusive sequence range')\n }\n }\n if (visible !== undefined) {\n if (!replacementCarriesMessage) throw new TypeError('history replacement entry must carry a message')\n const targets = op.targets ?? [...visible].filter(seq => seq >= op.from && seq <= op.to)\n if (targets.length === 0 || targets.some(seq => !visible.has(seq))) {\n throw new TypeError('history replace targets must reference current visible messages')\n }\n }\n}\n"],"mappings":"8CAOA,SAAgB,EAAgB,EAAyC,CACvE,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAU,UAAU,oCAAoC,EACz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U,iEAAiE,CAEzF,CAjB+F,CAkBjG"}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { MessageId, ToolCallId } from "../../primitives/brand.js";
|
|
2
|
+
import { ModelFailure } from "../../errors/failure.js";
|
|
3
|
+
import { AssistantTextPhase, ImageMediaType, NativeToolCallBlock } from "../../message/content.js";
|
|
4
|
+
import { TokenUsage } from "../../stream/chunk.js";
|
|
5
|
+
import { SdkLogger } from "../../logging/types.js";
|
|
6
|
+
import { Message } from "../../message/message.js";
|
|
7
|
+
import { GenerateOptions } from "../../contract/generate-options.js";
|
|
8
|
+
import { ToolExecutionResult } from "../tool/definition.js";
|
|
9
|
+
import { CompactionBackoffReason, HistorySnapshot } from "../history/types.js";
|
|
10
|
+
import { ApprovalRequest } from "../tool/approval.js";
|
|
11
|
+
import { ToolCallRequest } from "../tool/pipeline.js";
|
|
12
|
+
import { TraceEvent, TraceRef } from "../trace/trace.js";
|
|
13
|
+
import { RunUsageReport } from "../accounting/report.js";
|
|
14
|
+
//#region src/agent/loop/events.d.ts
|
|
15
|
+
type ExhaustedBudget = 'steps' | 'tool-calls' | 'consecutive-tool-errors' | 'repeated-tool-call' | 'tool-call-cycle' | 'tokens';
|
|
16
|
+
/**
|
|
17
|
+
* Why a call the model asked for was not run.
|
|
18
|
+
*
|
|
19
|
+
* A declined call is not a failed call: nothing broke, the loop simply refused
|
|
20
|
+
* to spend more on exploration. The distinction matters to the model, which
|
|
21
|
+
* answers a failure by retrying and a refusal by finishing.
|
|
22
|
+
*/
|
|
23
|
+
type ToolDeclineReason = ExhaustedBudget | 'usage-required';
|
|
24
|
+
type TurnEndReason = {
|
|
25
|
+
readonly kind: 'completed';
|
|
26
|
+
} | {
|
|
27
|
+
readonly kind: 'concluded-by-tool';
|
|
28
|
+
readonly toolName: string;
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: 'budget-exhausted';
|
|
31
|
+
readonly budget: ExhaustedBudget;
|
|
32
|
+
readonly forcedFinalAnswer: boolean;
|
|
33
|
+
/** Exploration stopped at the reporting reserve, before the hard token ceiling. */
|
|
34
|
+
readonly trigger?: 'report-reserve';
|
|
35
|
+
} | {
|
|
36
|
+
readonly kind: 'max-tokens';
|
|
37
|
+
} | {
|
|
38
|
+
readonly kind: 'usage-unavailable';
|
|
39
|
+
readonly modelCallId: string;
|
|
40
|
+
} | {
|
|
41
|
+
readonly kind: 'aborted';
|
|
42
|
+
} | {
|
|
43
|
+
readonly kind: 'error';
|
|
44
|
+
readonly failure: ModelFailure;
|
|
45
|
+
};
|
|
46
|
+
interface TurnOutcome {
|
|
47
|
+
readonly reason: TurnEndReason;
|
|
48
|
+
readonly text: string;
|
|
49
|
+
readonly steps: number;
|
|
50
|
+
/** Exact legacy aggregate; absent whenever any possibly-billed call lacks authoritative usage. */
|
|
51
|
+
readonly usage?: TokenUsage;
|
|
52
|
+
/** Canonical coverage-aware usage for every logical model call in this turn. */
|
|
53
|
+
readonly usageReport: RunUsageReport;
|
|
54
|
+
readonly toolCalls: number;
|
|
55
|
+
readonly traceId: string;
|
|
56
|
+
}
|
|
57
|
+
interface Traced {
|
|
58
|
+
readonly trace: TraceRef;
|
|
59
|
+
}
|
|
60
|
+
type AssistantContentTiming = 'standalone' | 'before-tools' | 'after-tools' | 'between-tools';
|
|
61
|
+
type StreamedAssistantTextPhase = AssistantTextPhase | 'unknown';
|
|
62
|
+
type CompactionTrigger = 'pressure' | 'context-overflow' | 'manual';
|
|
63
|
+
type AgentMaintenanceEvent = {
|
|
64
|
+
readonly type: 'compaction-start';
|
|
65
|
+
readonly compactionId: string;
|
|
66
|
+
readonly trigger: CompactionTrigger;
|
|
67
|
+
readonly estimatedInputTokens: number;
|
|
68
|
+
} | {
|
|
69
|
+
readonly type: 'compaction-end';
|
|
70
|
+
readonly compactionId: string;
|
|
71
|
+
readonly trigger: CompactionTrigger;
|
|
72
|
+
readonly status: 'completed' | 'failed';
|
|
73
|
+
readonly shadowedSeqs: readonly number[];
|
|
74
|
+
readonly estimatedTokensBefore: number;
|
|
75
|
+
readonly estimatedTokensAfter: number;
|
|
76
|
+
readonly thresholdTokens?: number;
|
|
77
|
+
readonly estimatedNonCompactableTokens?: number;
|
|
78
|
+
readonly backoffReason?: CompactionBackoffReason;
|
|
79
|
+
readonly cooldownSteps?: number;
|
|
80
|
+
readonly summary?: string;
|
|
81
|
+
readonly error?: string;
|
|
82
|
+
readonly usage?: TokenUsage;
|
|
83
|
+
};
|
|
84
|
+
type AgentEvent = TraceEvent | (AgentMaintenanceEvent & Traced) | ({
|
|
85
|
+
readonly type: 'turn-start';
|
|
86
|
+
readonly turn: number;
|
|
87
|
+
} & Traced) | ({
|
|
88
|
+
readonly type: 'step-start';
|
|
89
|
+
readonly turn: number;
|
|
90
|
+
readonly step: number;
|
|
91
|
+
readonly forcedFinal?: true;
|
|
92
|
+
} & Traced) | ({
|
|
93
|
+
readonly type: 'text-delta';
|
|
94
|
+
readonly index: number;
|
|
95
|
+
readonly text: string;
|
|
96
|
+
readonly phase: StreamedAssistantTextPhase;
|
|
97
|
+
} & Traced) |
|
|
98
|
+
/** Authoritative text and phase for a model-round block, before step-end.
|
|
99
|
+
* A final-answer block is local to this agent/round, not whole-team completion.
|
|
100
|
+
* incomplete marks output retained from an error, abort or output-token limit. */
|
|
101
|
+
({
|
|
102
|
+
readonly type: 'text-end';
|
|
103
|
+
readonly index: number;
|
|
104
|
+
readonly text: string;
|
|
105
|
+
readonly phase: AssistantTextPhase;
|
|
106
|
+
readonly incomplete?: true;
|
|
107
|
+
} & Traced) | ({
|
|
108
|
+
readonly type: 'reasoning-delta';
|
|
109
|
+
readonly index: number;
|
|
110
|
+
readonly text: string;
|
|
111
|
+
} & Traced) | ({
|
|
112
|
+
readonly type: 'image-delta';
|
|
113
|
+
readonly itemId: string;
|
|
114
|
+
readonly data: string;
|
|
115
|
+
readonly mediaType: ImageMediaType;
|
|
116
|
+
readonly partialIndex?: number;
|
|
117
|
+
} & Traced) | ({
|
|
118
|
+
readonly type: 'assistant-message';
|
|
119
|
+
readonly message: Message;
|
|
120
|
+
} & Traced) | ({
|
|
121
|
+
readonly type: 'assistant-text';
|
|
122
|
+
readonly messageId: MessageId;
|
|
123
|
+
readonly text: string;
|
|
124
|
+
readonly phase: AssistantTextPhase;
|
|
125
|
+
readonly timing: AssistantContentTiming;
|
|
126
|
+
readonly toolCallIds: readonly ToolCallId[];
|
|
127
|
+
readonly afterToolCallIds: readonly ToolCallId[];
|
|
128
|
+
} & Traced) | ({
|
|
129
|
+
readonly type: 'assistant-native-tool';
|
|
130
|
+
readonly messageId: MessageId;
|
|
131
|
+
readonly call: NativeToolCallBlock;
|
|
132
|
+
} & Traced) | ({
|
|
133
|
+
/** Provider-emitted reasoning summary/content, never fabricated hidden chain-of-thought. */
|
|
134
|
+
readonly type: 'assistant-reasoning';
|
|
135
|
+
readonly messageId: MessageId;
|
|
136
|
+
readonly text: string;
|
|
137
|
+
readonly timing: AssistantContentTiming;
|
|
138
|
+
readonly toolCallIds: readonly ToolCallId[];
|
|
139
|
+
readonly afterToolCallIds: readonly ToolCallId[];
|
|
140
|
+
} & Traced) | ({
|
|
141
|
+
readonly type: 'tool-call';
|
|
142
|
+
readonly call: ToolCallRequest;
|
|
143
|
+
} & Traced) | ({
|
|
144
|
+
readonly type: 'tool-result';
|
|
145
|
+
readonly call: ToolCallRequest;
|
|
146
|
+
readonly result: ToolExecutionResult;
|
|
147
|
+
} & Traced) | ({
|
|
148
|
+
readonly type: 'approval-request';
|
|
149
|
+
readonly request: ApprovalRequest;
|
|
150
|
+
} & Traced) | ({
|
|
151
|
+
readonly type: 'usage';
|
|
152
|
+
readonly usage: TokenUsage;
|
|
153
|
+
} & Traced) | ({
|
|
154
|
+
readonly type: 'step-end';
|
|
155
|
+
readonly turn: number;
|
|
156
|
+
readonly step: number;
|
|
157
|
+
} & Traced) | ({
|
|
158
|
+
readonly type: 'turn-end';
|
|
159
|
+
readonly outcome: TurnOutcome;
|
|
160
|
+
} & Traced);
|
|
161
|
+
interface BeforeStepContext {
|
|
162
|
+
readonly turn: number;
|
|
163
|
+
readonly step: number;
|
|
164
|
+
readonly messages: readonly Message[];
|
|
165
|
+
readonly snapshot: HistorySnapshot;
|
|
166
|
+
readonly signal: AbortSignal;
|
|
167
|
+
readonly logger?: SdkLogger;
|
|
168
|
+
emit(event: AgentMaintenanceEvent): Promise<void>;
|
|
169
|
+
}
|
|
170
|
+
type StepDecision = {
|
|
171
|
+
readonly kind: 'proceed';
|
|
172
|
+
readonly prepend?: readonly Message[];
|
|
173
|
+
} | {
|
|
174
|
+
readonly kind: 'reject';
|
|
175
|
+
readonly reason: string;
|
|
176
|
+
};
|
|
177
|
+
interface RequestErrorContext {
|
|
178
|
+
readonly turn: number;
|
|
179
|
+
readonly step: number;
|
|
180
|
+
readonly failure: ModelFailure;
|
|
181
|
+
readonly snapshot: HistorySnapshot;
|
|
182
|
+
readonly signal: AbortSignal;
|
|
183
|
+
readonly logger?: SdkLogger;
|
|
184
|
+
emit(event: AgentMaintenanceEvent): Promise<void>;
|
|
185
|
+
}
|
|
186
|
+
type CheckpointContext = {
|
|
187
|
+
readonly kind: 'before-model-request';
|
|
188
|
+
readonly request: GenerateOptions;
|
|
189
|
+
readonly snapshot: HistorySnapshot;
|
|
190
|
+
readonly signal?: AbortSignal;
|
|
191
|
+
readonly logger?: SdkLogger;
|
|
192
|
+
} | {
|
|
193
|
+
readonly kind: 'before-tool-dispatch';
|
|
194
|
+
readonly call: ToolCallRequest;
|
|
195
|
+
readonly snapshot: HistorySnapshot;
|
|
196
|
+
readonly signal?: AbortSignal;
|
|
197
|
+
readonly logger?: SdkLogger;
|
|
198
|
+
};
|
|
199
|
+
interface TurnEndContext {
|
|
200
|
+
readonly outcome: TurnOutcome;
|
|
201
|
+
readonly snapshot: HistorySnapshot;
|
|
202
|
+
/** True when the loop still has capacity to consume context appended by this hook. */
|
|
203
|
+
readonly canContinue: boolean;
|
|
204
|
+
}
|
|
205
|
+
interface TurnHooks {
|
|
206
|
+
readonly beforeStep?: (ctx: BeforeStepContext) => Promise<StepDecision> | StepDecision;
|
|
207
|
+
readonly onRequestError?: (ctx: RequestErrorContext) => Promise<'retry' | 'fail'> | 'retry' | 'fail';
|
|
208
|
+
readonly checkpoint?: (ctx: CheckpointContext) => Promise<void> | void;
|
|
209
|
+
readonly onTurnEnd?: (ctx: TurnEndContext) => Promise<void> | void;
|
|
210
|
+
}
|
|
211
|
+
//#endregion
|
|
212
|
+
export { AgentEvent, AgentMaintenanceEvent, AssistantContentTiming, BeforeStepContext, CheckpointContext, type CompactionBackoffReason, CompactionTrigger, ExhaustedBudget, RequestErrorContext, StepDecision, StreamedAssistantTextPhase, ToolDeclineReason, TurnEndContext, TurnEndReason, TurnHooks, TurnOutcome };
|
|
213
|
+
//# sourceMappingURL=events.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.d.ts","names":[],"sources":["../../../src/agent/loop/events.ts"],"mappings":";;;;;;;;;;;;;;KAgBY;;;;;;;;KAcA,oBAAoB;KAEpB;WACG;;WACA;WAAoC;;WACpC;WAAmC,QAAQ;WAA0B;;WAErE;;WACA;;WACA;WAAoC;;WACpC;;WACA;WAAwB,SAAS;;UAE/B;WACN,QAAQ;WACR;WACA;;WAEA,QAAQ;;WAER,aAAa;WACb;WACA;;UAGD;WAAkB,OAAO;;KACvB;KACA,6BAA6B;KAC7B;KACA;WAEC;WACA;WACA,SAAS;WACT;;WAGA;WACA;WACA,SAAS;WACT;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;WAChB;WACA;WACA;WACA,QAAQ;;KAET,aAAa,cACpB,wBAAwB;WACb;WAA6B;IAAiB;WAC9C;WAA6B;WAAuB;WAAuB;IAAuB;WAClG;WAA6B;WAAwB;WAAuB,OAAO;IAA+B;;;;;WAIlH;WAA2B;WAAwB;WAAuB,OAAO;WAA6B;IAAsB;WACpI;WAAkC;WAAwB;IAAiB;WAE9E;WACA;WACA;WACA,WAAW;WACX;IACP;WACU;WAAoC,SAAS;IAAY;WAE5D;WACA,WAAW;WACX;WACA,OAAO;WACP,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WAEO;WACA,WAAW;WACX,MAAM;IACb;;WAGO;WACA,WAAW;WACX;WACA,QAAQ;WACR,sBAAsB;WACtB,2BAA2B;IAClC;WACU;WAA4B,MAAM;IAAoB;WACtD;WAA8B,MAAM;WAA0B,QAAQ;IAAwB;WAC9F;WAAmC,SAAS;IAAoB;WAChE;WAAwB,OAAO;IAAe;WAC9C;WAA2B;WAAuB;IAAiB;WACnE;WAA2B,SAAS;IAAgB;UAEnD;WACN;WACA;WACA,mBAAmB;WACnB,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAA0B,mBAAmB;;WAC7C;WAAyB;;UACvB;WACN;WACA;WACA,SAAS;WACT,UAAU;WACV,QAAQ;WACR,SAAS;EAClB,KAAK,OAAO,wBAAwB;;KAE1B;WACG;WAAuC,SAAS;WAA0B,UAAU;WACpF,SAAS;WAAsB,SAAS;;WACxC;WAAuC,MAAM;WAA0B,UAAU;WACjF,SAAS;WAAsB,SAAS;;UACtC;WACN,SAAS;WACT,UAAU;;WAEV;;UAEM;WACN,cAAc,KAAK,sBAAsB,QAAQ,gBAAgB;WACjE,kBAAkB,KAAK,wBAAwB;WAC/C,cAAc,KAAK,sBAAsB;WACzC,aAAa,KAAK,mBAAmB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class{slot;taker;space;ended=!1;failure;async push(e){if(this.ended||(this.slot!==void 0&&await new Promise(e=>{this.space=e}),this.ended))return;let t=this.taker;if(t!==void 0){this.taker=void 0,t.resolve({done:!1,value:e});return}await new Promise(t=>{this.slot={value:e,consumed:t}})}async take(){if(this.slot!==void 0){let e=this.slot;return this.slot=void 0,e.consumed(),this.space?.(),this.space=void 0,{done:!1,value:e.value}}if(this.failure!==void 0)throw this.failure;return this.ended?{done:!0,value:void 0}:await new Promise((e,t)=>{this.taker={resolve:e,reject:t}})}close(){this.ended=!0,this.slot?.consumed(),this.slot=void 0,this.space?.(),this.space=void 0,this.taker?.resolve({done:!0,value:void 0}),this.taker=void 0}fail(e){this.failure=e,this.ended=!0,this.slot?.consumed(),this.slot=void 0,this.space?.(),this.space=void 0,this.taker?.reject(e),this.taker=void 0}};export{e as AwaitedEventQueue};
|
|
2
|
+
//# sourceMappingURL=queue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.js","names":[],"sources":["../../../src/agent/loop/queue.ts"],"sourcesContent":["/** Capacity-one queue whose producer waits until the consumer takes the event. */\nexport class AwaitedEventQueue<T> {\n private slot: { value: T; consumed: () => void } | undefined\n private taker: {\n readonly resolve: (item: IteratorResult<T>) => void\n readonly reject: (error: unknown) => void\n } | undefined\n private space: (() => void) | undefined\n private ended = false\n private failure: unknown\n\n async push(value: T): Promise<void> {\n if (this.ended) return\n if (this.slot !== undefined) await new Promise<void>(resolve => { this.space = resolve })\n if (this.ended) return\n const taker = this.taker\n if (taker !== undefined) {\n this.taker = undefined\n taker.resolve({ done: false, value })\n return\n }\n await new Promise<void>(resolve => { this.slot = { value, consumed: resolve } })\n }\n\n async take(): Promise<IteratorResult<T>> {\n if (this.slot !== undefined) {\n const slot = this.slot\n this.slot = undefined\n slot.consumed()\n this.space?.()\n this.space = undefined\n return { done: false, value: slot.value }\n }\n if (this.failure !== undefined) throw this.failure\n if (this.ended) return { done: true, value: undefined }\n return await new Promise((resolve, reject) => { this.taker = { resolve, reject } })\n }\n\n close(): void {\n this.ended = true\n this.slot?.consumed()\n this.slot = undefined\n this.space?.()\n this.space = undefined\n this.taker?.resolve({ done: true, value: undefined })\n this.taker = undefined\n }\n\n fail(error: unknown): void {\n this.failure = error\n this.ended = true\n this.slot?.consumed()\n this.slot = undefined\n this.space?.()\n this.space = undefined\n this.taker?.reject(error)\n this.taker = undefined\n }\n}\n"],"mappings":"AACA,IAAa,EAAb,KAAkC,CAChC,KACA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,IAAA,EACf,CACF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { AgentEvent } from "./events.js";
|
|
2
|
+
import { RunTurnOptions } from "./turn/types.js";
|
|
3
|
+
//#region src/agent/loop/run-turn.d.ts
|
|
4
|
+
/** Run one bounded turn as a backpressured event stream. */
|
|
5
|
+
declare function runTurn(options: RunTurnOptions): AsyncIterable<AgentEvent>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { type RunTurnOptions, runTurn };
|
|
8
|
+
//# sourceMappingURL=run-turn.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-turn.d.ts","names":[],"sources":["../../../src/agent/loop/run-turn.ts"],"mappings":";;;;iBA0BgB,QAAQ,SAAS,iBAAiB,cAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createSpanId as n,createTraceId as r}from"../../observation/context.js";import{createUserMessage as i}from"../../message/message.js";import{authoritativeTokenUsage as a,budgetTokenTotal as o,summarizeModelCallUsage as s}from"../accounting/usage.js";import{ContextSectionRuntime as c}from"../context/section.js";import{AwaitedEventQueue as l}from"./queue.js";import{runToolCalls as ee}from"./schedule.js";import{positiveFinite as u,resolveBounds as d,snapshotRunTurnOptions as f}from"./turn/config.js";import{codedRuntimeError as p,errorCodeOf as m,messageOf as h,now as g}from"./turn/common.js";import{runHook as te,runOptionalHook as ne}from"./turn/hooks.js";import{emitAssistantContent as _,maintenanceEmitter as v,textOf as y}from"./turn/content.js";import{repeatKey as b,repeatedSuffixCycle as re,toolActionPattern as ie}from"./turn/repetition.js";import{accountingUsageStop as x}from"./turn/usage-stop.js";import{modelRound as S}from"./turn/model-round.js";function C(e){return e.toolChoice===`none`?!1:(e.tools?.names().length??0)>0||(e.nativeTools?.length??0)>0}function w(n){return{async*[Symbol.asyncIterator](){let r=f(n),i=new l,a=new AbortController,o=u(r.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=T(r,r.signal===void 0?a.signal:AbortSignal.any([r.signal,a.signal]),t=>i.push(e(t))).then(()=>i.close(),e=>i.fail(e));try{for(;;){let e=await i.take();if(e.done)break;yield e.value}await s}finally{if(a.abort(Error(`turn event consumer stopped`)),i.close(),!await t(s,o))throw p(`turn producer ignored cancellation for more than ${o}ms`,`TURN_TEARDOWN_TIMEOUT`,a.signal.reason)}}}}async function T(e,t,l){let u=d(e.bounds),f=u.maxTotalTokens===`auto`?1/0:u.maxTotalTokens,p=u.maxSteps===`auto`?1/0:u.maxSteps,w=e.trace?.traceId??r(),T={traceId:w,spanId:n(),parentSpanId:e.trace?.parentSpanId??null},E=Math.max(1,e.history.entries().filter(e=>e.event.kind===`user`&&e.event.message.source.kind===`user`).length),D=g(),O=0,k=0,ae=[...u.toolBudgetRemindAt].filter(e=>e>0&&e<u.maxToolCalls).sort((e,t)=>t-e),A=0,j=0,M,N=!1,P=0,F=0,I=``,L=[],R,z,B,V=[],H=v(l,T),oe=t=>{let n=i({source:{kind:`app`,producer:`tool-loop-budget-guard`},content:[{type:`text`,text:t}]}),r=M;if(r!==void 0)try{M=e.history.append({kind:`user`,message:n},{op:`replace`,from:r,to:r,targets:[r]}).seq;return}catch{M=void 0}M=e.history.append({kind:`user`,message:n}).seq},U=e.contextSections===void 0||e.contextSections.length===0?void 0:new c({sections:e.contextSections,history:e.history,...e.logger===void 0?{}:{logger:e.logger},guard:(n,r)=>te(n,e,t,r),scope:{agentId:e.trace?.agentId,conversationId:e.trace?.conversationId}}),W=[],G=!1,K=!1,q=C(e),se=e.outputFormat?.type===`json_schema`&&q,J=e.accounting?.startOperation(`turn`,{data:{turn:E,model:e.config.model}}),Y=!1,X,Z=()=>{if(t.aborted)return{kind:`aborted`};let n=x(e.accounting);if(n!==void 0)return n;if(X!==void 0)return X;let r=o(s(L));return r!==void 0&&r>=f?{kind:`budget-exhausted`,budget:`tokens`,forcedFinalAnswer:!1}:void 0};try{await l({type:`span-start`,trace:T,at:D,name:`invoke_agent ${e.trace?.agentId??`agent`}`,kind:`invoke_agent`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.id":e.trace?.agentId??`agent`,"gen_ai.agent.name":e.trace?.agentName??e.trace?.agentId??`agent`,"gen_ai.request.model":e.config.model,...e.trace?.conversationId===void 0?{}:{"gen_ai.conversation.id":e.trace.conversationId}}}),G=!0,await l({type:`turn-start`,turn:E,trace:T});turnLifecycle:for(;;){for(;R===void 0&&O<p&&!t.aborted&&(R=Z(),R===void 0);){let n=o(s(L));if(u.maxTotalTokens!==`auto`&&n!==void 0){let t=[.5,.75,.9].filter(e=>n>=f*e).length;if(t>P){P=t;let r=Math.max(0,f-n);e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-token-guard`},content:[{type:`text`,text:`Token budget: ${r} of ${u.maxTotalTokens} aggregate tokens remain. Each request also spends input tokens on the accumulated context. `+(t>=2?`Stop broad exploration. `:`Prioritize outstanding verification and reporting. `)+`Reserve capacity for the required self-check, honest todo reconciliation and substantive final report. State unavailable evidence and unfinished work; do not claim it is verified. No extra model call is allowed after the hard token limit.`}]})})}}!N&&O>0&&p-O<=2&&(N=!0,e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-step-guard`},content:[{type:`text`,text:`${p-O} work steps remain. Finish essential verification, update any task list honestly, and submit the result if required. Summarize findings, evidence, and unfinished work; do not start new exploration.`}]})})),U!==void 0&&(await U.reconcile(O,W,t),W=[]);let r=O+1,a=await S(e,t,l,H,T,E,r,se?`process`:e.outputFormat?.type===`json_schema`?`final`:`standard`);if(O++,a.report!==void 0&&L.push(a.report),a.message!==void 0&&(e.history.append({kind:`assistant`,message:a.message,...a.finish.kind===`aborted`?{interrupted:!0}:{},...a.usage===void 0?{}:{usage:a.usage}}),await l({type:`assistant-message`,message:a.message,trace:a.trace}),await _(a,l),I=y(a.message.content)),X=x(e.accounting)??(a.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:a.usageUnavailable?{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`}:void 0),t.aborted||a.finish.kind===`aborted`){R={kind:`aborted`};break}if(a.finish.kind===`error`&&X!==void 0){R={kind:`error`,failure:a.finish.failure};break}if(a.usageRequired&&(a.calls.length===0||e.tools===void 0)){R=X;break}if(a.finish.kind===`error`&&!a.usageRequired){if(R=Z(),R!==void 0)break;let n=await ne(e.hooks?.onRequestError,[{turn:E,step:r,failure:a.finish.failure,snapshot:e.history.snapshot(),signal:t,...e.logger===void 0?{}:{logger:e.logger},emit:H}],e,t,`onRequestError`),i=x(e.accounting);if(i!==void 0){R=t.aborted?{kind:`aborted`}:i;break}if(n===`retry`&&O<p)continue;R={kind:`error`,failure:a.finish.failure};break}if(a.finish.kind===`max-tokens`&&!a.usageRequired){R={kind:`max-tokens`};break}if(a.calls.length===0&&a.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}if(a.calls.length===0&&se){if(R=Z(),R!==void 0)break;e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`structured-output-finalizer`},content:[{type:`text`,text:`The process phase is complete. Return the final answer now in the requested output format. Do not call tools.`}]})});let n=await S(e,t,l,H,T,E,O+1,`final`);O++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await _(n,l),I=y(n.message.content)),R=n.finish.kind===`aborted`?{kind:`aborted`}:n.finish.kind===`error`?{kind:`error`,failure:n.finish.failure}:n.finish.kind===`max-tokens`?{kind:`max-tokens`}:n.usageRequired?{kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}}:n.usageUnavailable?x(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`}:{kind:`completed`};break}if(a.droppedDuplicateCalls!==void 0&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-duplicate-guard`},content:[{type:`text`,text:`You reused the tool-call id ${a.droppedDuplicateCalls.map(e=>`'${e}'`).join(`, `)}. A result pairs to exactly one call, so the repeat was not run and only the first call of that id has a result. Give every call its own id, and call again if you still need what the dropped one would have done.`}]})}),a.calls.length===0||e.tools===void 0){R={kind:`completed`};break}let c=a.calls.filter(t=>e.tools?.get(t.toolName)?.budgetExempt!==!0).length,d=Math.max(0,u.maxToolCalls-k),m=B,h=a.calls.map(e=>{let t=b(e),n=m?.key===t?m.count+1:1;return m={key:t,count:n},n}).some(e=>e>=u.repeatToolLimit),g=ie(a.calls),v=re([...V,g],u.maxToolCycleLength),C=v!==void 0&&v.repetitions>=u.toolCycleLimit,w=s(L),D=o(w),M=D!==void 0&&D>=f,z=h||C||M||a.usageRequired,G=M?`tokens`:C?`tool-call-cycle`:h?`repeated-tool-call`:a.usageRequired?`usage-required`:`tool-calls`,K=u.onExhausted!==`continue`,q=await ee({calls:a.calls,catalog:e.tools,history:e.history,position:{turn:E,step:r,...e.accounting===void 0?{}:{runId:e.accounting.runId},...e.trace?.conversationId===void 0?{}:{conversationId:e.trace.conversationId}},signal:t,parentTrace:T,maxParallel:u.maxParallel,dispatchLimit:z?0:K?d:a.calls.length,declineReason:G,maxResultBytes:u.maxToolResultBytes,maxResultTokens:u.maxToolResultTokens,resultOverflow:u.toolResultOverflow,...e.spillStore===void 0?{}:{spillStore:e.spillStore},maxDurationMs:u.maxToolDurationMs,teardownTimeoutMs:u.toolTeardownTimeoutMs,...e.logger===void 0?{}:{logger:e.logger},...e.interceptors===void 0?{}:{interceptors:e.interceptors},...e.approvals===void 0?{}:{approvals:e.approvals},...e.accounting===void 0?{}:{accounting:e.accounting},emit:l,...e.hooks?.checkpoint===void 0?{}:{checkpoint:n=>te(Promise.resolve(e.hooks?.checkpoint?.(n)),e,t,`checkpoint`)}});U!==void 0&&q.results.length===a.calls.length&&W.push(...a.calls.map((e,t)=>({toolName:e.toolName,rawArguments:e.rawArguments,failed:q.results[t]?.isError??!0}))),k+=q.budgeted;let J=Math.max(0,u.maxToolCalls-k),Y=ae.filter(e=>J<=e).length;if(Y>A&&J>0&&(A=Y,oe(`Tool budget: ${J} of ${u.maxToolCalls} calls remain in this turn. Stop broad exploration, make the necessary edits, and reserve calls for`+(K?` verification. When the budget runs out no further work call will run, so finish with what you can still verify.`:` verification. Past the budget you are expected to be wrapping up, not opening new lines of work.`))),!K&&J===0){let e=Math.floor(k/u.maxToolCalls);e>j&&(j=e,oe(`Tool budget spent: ${k} calls made against a budget of ${u.maxToolCalls}. Do not start new substantive work. Finish what is in flight, verify what you can, and answer — stating plainly what is unverified or unfinished.`))}await l({type:`step-end`,turn:E,step:r,trace:a.trace}),V.push(g);let ce=h;for(let t=0;t<a.calls.length;t++){let n=a.calls[t],r=q.results[t];if(n===void 0||r===void 0)continue;F=r.isError?F+1:0;let o=b(n),s=B?.key===o?B.count+1:1;B={key:o,count:s},s===u.repeatToolWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-repeat-guard`},content:[{type:`text`,text:`You have called ${n.toolName} with the same arguments ${s} consecutive times. Reassess before repeating it.`}]})}),s>=u.repeatToolLimit&&(ce=!0)}if(v?.repetitions===u.toolCycleWarningAt&&e.history.append({kind:`user`,message:i({source:{kind:`app`,producer:`tool-loop-cycle-guard`},content:[{type:`text`,text:`Tool-use pattern repeated ${v.repetitions} times across ${v.period} step(s). Reassess the approach and identify concrete new evidence before continuing.`}]})}),q.concluded){R={kind:`concluded-by-tool`,toolName:q.concludedBy??`unknown`};break}if(t.aborted){R={kind:`aborted`};break}if(a.usageRequired){R=X;break}if(a.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:a.report?.modelCallId??`unknown`};break}let Q,$=u.maxTotalTokens!==`auto`&&u.finalReportReserveTokens>0&&D!==void 0&&D>=f-u.finalReportReserveTokens;if(M||$?Q=`tokens`:C?Q=`tool-call-cycle`:K&&c>d?Q=`tool-calls`:F>=u.maxConsecutiveToolErrors?Q=`consecutive-tool-errors`:ce?Q=`repeated-tool-call`:O>=p&&(Q=`steps`),Q!==void 0){let n=(Q!==`tokens`||$&&!M)&&u.onExhausted!==`stop`&&Z()===void 0;if(n){let n=await S(e,t,l,H,T,E,O+1,`forced-final`);if(O++,n.report!==void 0&&L.push(n.report),n.message!==void 0&&(e.history.append({kind:`assistant`,message:n.message,...n.usage===void 0?{}:{usage:n.usage}}),await l({type:`assistant-message`,message:n.message,trace:n.trace}),await _(n,l),I=y(n.message.content)),n.finish.kind===`aborted`){R={kind:`aborted`};break}if(n.finish.kind===`error`){R={kind:`error`,failure:n.finish.failure};break}if(n.finish.kind===`max-tokens`){R={kind:`max-tokens`};break}if(n.usageRequired){R={kind:`error`,failure:{message:`provider usage is required by the configured run policy`,code:`USAGE_REQUIRED`}};break}if(n.usageUnavailable){R=x(e.accounting)??{kind:`usage-unavailable`,modelCallId:n.report?.modelCallId??`unknown`};break}}R={kind:`budget-exhausted`,budget:Q,forcedFinalAnswer:n,...Q===`tokens`&&$&&!M?{trigger:`report-reserve`}:{}}}}R===void 0&&(R=t.aborted?{kind:`aborted`}:{kind:`budget-exhausted`,budget:`steps`,forcedFinalAnswer:!1});let n=s(L),r=a(n),c={reason:R,text:I,steps:O,usageReport:n,toolCalls:k,traceId:w,...r===void 0?{}:{usage:r}},d=e.history.entries().length,m=R.kind===`completed`&&O<p&&Z()===void 0;if(await ne(e.hooks?.onTurnEnd,[{outcome:c,snapshot:e.history.snapshot(),canContinue:m}],e,t,`onTurnEnd`),m&&e.history.entries().length>d&&!t.aborted){R=void 0;continue turnLifecycle}z=c;break}await l({type:`span-end`,trace:T,at:g(),status:z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,output:{reason:z.reason,text:I},...z.usage===void 0?{}:{usage:z.usage},...z.reason.kind===`error`?{error:{type:`ModelError`,message:z.reason.failure.message,code:z.reason.failure.code}}:{}}),K=!0,J!==void 0&&(e.accounting?.endOperation(J,z.reason.kind===`error`?`error`:z.reason.kind===`aborted`?`aborted`:`success`,{data:{reason:z.reason.kind,steps:O,toolCalls:k}}),Y=!0),await l({type:`turn-end`,outcome:z,trace:T})}catch(n){let r=m(n);throw G&&!K&&await l({type:`span-end`,trace:T,at:g(),status:t.aborted?`aborted`:`error`,error:{type:n instanceof Error?n.name:`RuntimeError`,message:h(n),...r===void 0?{}:{code:r}}}).catch(()=>void 0),J!==void 0&&!Y&&(e.accounting?.endOperation(J,t.aborted?`aborted`:`error`,{error:n}),Y=!0),n}}export{w as runTurn};
|
|
2
|
+
//# sourceMappingURL=run-turn.js.map
|