stitchkit 0.133.1 → 0.134.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/README.md +14 -11
- package/dist/agent-executor/acp/v1-connect.d.ts +5 -0
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-map.d.ts +13 -3
- package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-probe.d.ts +3 -0
- package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-protocol.d.ts +61 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +3 -0
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +2 -0
- package/dist/agent-executor/codex/connect.d.ts.map +1 -1
- package/dist/agent-executor/codex/driver.d.ts +3 -0
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/contract.d.ts +42 -0
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine-process.d.ts +20 -0
- package/dist/agent-executor/engine-process.d.ts.map +1 -1
- package/dist/agent-executor/executor-contract.d.ts +42 -0
- package/dist/agent-executor/executor-contract.d.ts.map +1 -1
- package/dist/agent-executor/handoff-schemas.d.ts +30 -0
- package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
- package/dist/agent-executor/projection.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +4 -1
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -1
- package/dist/agent-executor/vocabulary.d.ts +100 -0
- package/dist/agent-executor/vocabulary.d.ts.map +1 -1
- package/dist/agent-parts/model.d.ts +1559 -0
- package/dist/agent-parts/model.d.ts.map +1 -0
- package/dist/agent-parts/parts.d.ts +21 -0
- package/dist/agent-parts/parts.d.ts.map +1 -1
- package/dist/agent-runtime/ai-sdk-convert.d.ts +15 -0
- package/dist/agent-runtime/ai-sdk-convert.d.ts.map +1 -0
- package/dist/agent-runtime/ai-sdk.d.ts +31 -0
- package/dist/agent-runtime/ai-sdk.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-media.d.ts +11 -0
- package/dist/agent-runtime/anthropic-media.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-messages.d.ts +24 -0
- package/dist/agent-runtime/anthropic-messages.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-options.d.ts +79 -0
- package/dist/agent-runtime/anthropic-options.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-response.d.ts +19 -0
- package/dist/agent-runtime/anthropic-response.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-sse.d.ts +4 -0
- package/dist/agent-runtime/anthropic-sse.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic.d.ts +27 -0
- package/dist/agent-runtime/anthropic.d.ts.map +1 -0
- package/dist/agent-runtime/branch-observations.d.ts +25 -25
- package/dist/agent-runtime/branch-provider.d.ts +86 -0
- package/dist/agent-runtime/branch-provider.d.ts.map +1 -1
- package/dist/agent-runtime/branch-replay.d.ts +30 -0
- package/dist/agent-runtime/branch-replay.d.ts.map +1 -1
- package/dist/agent-runtime/browser-control-contract.d.ts +204 -0
- package/dist/agent-runtime/browser-control-contract.d.ts.map +1 -1
- package/dist/agent-runtime/browser-controller-view.d.ts +44 -0
- package/dist/agent-runtime/browser-controller-view.d.ts.map +1 -0
- package/dist/agent-runtime/browser-controller.d.ts +12 -8
- package/dist/agent-runtime/browser-controller.d.ts.map +1 -1
- package/dist/agent-runtime/child-budget-policy.d.ts +2 -3
- package/dist/agent-runtime/child-budget-policy.d.ts.map +1 -1
- package/dist/agent-runtime/compaction.d.ts +27 -10
- package/dist/agent-runtime/compaction.d.ts.map +1 -1
- package/dist/agent-runtime/control-interaction-schema.d.ts +157 -0
- package/dist/agent-runtime/control-interaction-schema.d.ts.map +1 -0
- package/dist/agent-runtime/control-schema.d.ts +183 -27
- package/dist/agent-runtime/control-schema.d.ts.map +1 -1
- package/dist/agent-runtime/control-view.d.ts +64 -0
- package/dist/agent-runtime/control-view.d.ts.map +1 -0
- package/dist/agent-runtime/conversations.d.ts +10 -0
- package/dist/agent-runtime/conversations.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tool-selection.d.ts +2 -2
- package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tool-types.d.ts +2 -2
- package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tools-internal.d.ts +8 -11
- package/dist/agent-runtime/deferred-tools-internal.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
- package/dist/agent-runtime/event-schema.d.ts +80 -0
- package/dist/agent-runtime/event-schema.d.ts.map +1 -1
- package/dist/agent-runtime/harness-contract.d.ts +2 -2
- package/dist/agent-runtime/harness-contract.d.ts.map +1 -1
- package/dist/agent-runtime/harness-control.d.ts.map +1 -1
- package/dist/agent-runtime/harness-realtime.d.ts.map +1 -1
- package/dist/agent-runtime/harness.d.ts +2 -2
- package/dist/agent-runtime/harness.d.ts.map +1 -1
- package/dist/agent-runtime/history.d.ts +25 -16
- package/dist/agent-runtime/history.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-attempt.d.ts +7 -3
- package/dist/agent-runtime/invocation-attempt.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-payload.d.ts +13 -7
- package/dist/agent-runtime/invocation-payload.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-stream.d.ts +20 -0
- package/dist/agent-runtime/invocation-stream.d.ts.map +1 -0
- package/dist/agent-runtime/invocations.d.ts +2 -2
- package/dist/agent-runtime/invocations.d.ts.map +1 -1
- package/dist/agent-runtime/models-driver-step.d.ts +212 -0
- package/dist/agent-runtime/models-driver-step.d.ts.map +1 -0
- package/dist/agent-runtime/models-driver-telemetry.d.ts +42 -0
- package/dist/agent-runtime/models-driver-telemetry.d.ts.map +1 -0
- package/dist/agent-runtime/models-driver.d.ts +235 -0
- package/dist/agent-runtime/models-driver.d.ts.map +1 -0
- package/dist/agent-runtime/models.d.ts +3 -26
- package/dist/agent-runtime/models.d.ts.map +1 -1
- package/dist/agent-runtime/observability.d.ts +64 -0
- package/dist/agent-runtime/observability.d.ts.map +1 -1
- package/dist/agent-runtime/openai-messages.d.ts +11 -0
- package/dist/agent-runtime/openai-messages.d.ts.map +1 -0
- package/dist/agent-runtime/openai-options.d.ts +91 -0
- package/dist/agent-runtime/openai-options.d.ts.map +1 -0
- package/dist/agent-runtime/openai-response.d.ts +77 -0
- package/dist/agent-runtime/openai-response.d.ts.map +1 -0
- package/dist/agent-runtime/openai-sse-state.d.ts +54 -0
- package/dist/agent-runtime/openai-sse-state.d.ts.map +1 -0
- package/dist/agent-runtime/openai-sse.d.ts +4 -0
- package/dist/agent-runtime/openai-sse.d.ts.map +1 -0
- package/dist/agent-runtime/openai.d.ts +31 -0
- package/dist/agent-runtime/openai.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-admission.d.ts +3 -0
- package/dist/agent-runtime/openrouter-admission.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-benchmarks.d.ts +17 -0
- package/dist/agent-runtime/openrouter-benchmarks.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog-cache.d.ts +70 -0
- package/dist/agent-runtime/openrouter-catalog-cache.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog-query.d.ts +57 -0
- package/dist/agent-runtime/openrouter-catalog-query.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog.d.ts +189 -14
- package/dist/agent-runtime/openrouter-catalog.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-models.d.ts +168 -31
- package/dist/agent-runtime/openrouter-models.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-options.d.ts +45 -15
- package/dist/agent-runtime/openrouter-options.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-response.d.ts +22 -0
- package/dist/agent-runtime/openrouter-response.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter.d.ts +21 -24
- package/dist/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/agent-runtime/owned-provider-stream.d.ts +4 -4
- package/dist/agent-runtime/owned-provider-stream.d.ts.map +1 -1
- package/dist/agent-runtime/prompt.d.ts +3 -3
- package/dist/agent-runtime/prompt.d.ts.map +1 -1
- package/dist/agent-runtime/protocol.d.ts +28 -3
- package/dist/agent-runtime/protocol.d.ts.map +1 -1
- package/dist/agent-runtime/provider-cache.d.ts +30 -0
- package/dist/agent-runtime/provider-cache.d.ts.map +1 -0
- package/dist/agent-runtime/provider-content.d.ts +147 -0
- package/dist/agent-runtime/provider-content.d.ts.map +1 -1
- package/dist/agent-runtime/provider-failure.d.ts +51 -26
- package/dist/agent-runtime/provider-failure.d.ts.map +1 -1
- package/dist/agent-runtime/provider-history.d.ts +13 -0
- package/dist/agent-runtime/provider-history.d.ts.map +1 -0
- package/dist/agent-runtime/provider-http.d.ts +68 -0
- package/dist/agent-runtime/provider-http.d.ts.map +1 -0
- package/dist/agent-runtime/provider-journal.d.ts +149 -0
- package/dist/agent-runtime/provider-journal.d.ts.map +1 -1
- package/dist/agent-runtime/provider-json-schema-strip.d.ts +8 -0
- package/dist/agent-runtime/provider-json-schema-strip.d.ts.map +1 -0
- package/dist/agent-runtime/provider-json-schema.d.ts +28 -0
- package/dist/agent-runtime/provider-json-schema.d.ts.map +1 -0
- package/dist/agent-runtime/provider-media.d.ts +49 -0
- package/dist/agent-runtime/provider-media.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat-helpers.d.ts +27 -0
- package/dist/agent-runtime/provider-openai-chat-helpers.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat-sse.d.ts +25 -0
- package/dist/agent-runtime/provider-openai-chat-sse.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat.d.ts +27 -0
- package/dist/agent-runtime/provider-openai-chat.d.ts.map +1 -0
- package/dist/agent-runtime/provider-origin.d.ts +3 -12
- package/dist/agent-runtime/provider-origin.d.ts.map +1 -1
- package/dist/agent-runtime/provider-sse.d.ts +30 -0
- package/dist/agent-runtime/provider-sse.d.ts.map +1 -0
- package/dist/agent-runtime/provider-stream-parts.d.ts +5 -0
- package/dist/agent-runtime/provider-stream-parts.d.ts.map +1 -0
- package/dist/agent-runtime/provider-stream-segments.d.ts +63 -0
- package/dist/agent-runtime/provider-stream-segments.d.ts.map +1 -0
- package/dist/agent-runtime/provider-usage.d.ts +24 -0
- package/dist/agent-runtime/provider-usage.d.ts.map +1 -0
- package/dist/agent-runtime/retry-policy.d.ts +19 -3
- package/dist/agent-runtime/retry-policy.d.ts.map +1 -1
- package/dist/agent-runtime/run-acquisition.d.ts +4 -4
- package/dist/agent-runtime/run-acquisition.d.ts.map +1 -1
- package/dist/agent-runtime/run-approval.d.ts +82 -0
- package/dist/agent-runtime/run-approval.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-retry.d.ts +24 -0
- package/dist/agent-runtime/run-complete-retry.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-stream.d.ts +9 -0
- package/dist/agent-runtime/run-complete-stream.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-tools.d.ts +21 -0
- package/dist/agent-runtime/run-complete-tools.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-types.d.ts +168 -0
- package/dist/agent-runtime/run-complete-types.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete.d.ts +25 -0
- package/dist/agent-runtime/run-complete.d.ts.map +1 -0
- package/dist/agent-runtime/run-driver-compose.d.ts +21 -0
- package/dist/agent-runtime/run-driver-compose.d.ts.map +1 -0
- package/dist/agent-runtime/run-execution-state.d.ts +23 -10
- package/dist/agent-runtime/run-execution-state.d.ts.map +1 -1
- package/dist/agent-runtime/run-execution.d.ts +2 -2
- package/dist/agent-runtime/run-execution.d.ts.map +1 -1
- package/dist/agent-runtime/run-failure.d.ts +2 -2
- package/dist/agent-runtime/run-failure.d.ts.map +1 -1
- package/dist/agent-runtime/run-history-parts.d.ts +14 -0
- package/dist/agent-runtime/run-history-parts.d.ts.map +1 -0
- package/dist/agent-runtime/run-loop-events.d.ts +126 -0
- package/dist/agent-runtime/run-loop-events.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-attempts.d.ts +2 -2
- package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -1
- package/dist/agent-runtime/run-model-messages.d.ts +9 -0
- package/dist/agent-runtime/run-model-messages.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-step.d.ts +43 -0
- package/dist/agent-runtime/run-model-step.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-stream.d.ts +27 -0
- package/dist/agent-runtime/run-model-stream.d.ts.map +1 -0
- package/dist/agent-runtime/run-operation-lifecycle.d.ts +8 -4
- package/dist/agent-runtime/run-operation-lifecycle.d.ts.map +1 -1
- package/dist/agent-runtime/run-prompt-history.d.ts +8 -13
- package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -1
- package/dist/agent-runtime/run-provider-ledger.d.ts +7 -4
- package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -1
- package/dist/agent-runtime/run-step-barriers.d.ts +58 -16
- package/dist/agent-runtime/run-step-barriers.d.ts.map +1 -1
- package/dist/agent-runtime/run-step-helpers.d.ts +49 -0
- package/dist/agent-runtime/run-step-helpers.d.ts.map +1 -0
- package/dist/agent-runtime/run-step-prepare.d.ts +34 -0
- package/dist/agent-runtime/run-step-prepare.d.ts.map +1 -0
- package/dist/agent-runtime/run-step-spend.d.ts +85 -10
- package/dist/agent-runtime/run-step-spend.d.ts.map +1 -1
- package/dist/agent-runtime/run-stream-parts.d.ts +13 -9
- package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -1
- package/dist/agent-runtime/run-stream-recorded.d.ts +8 -0
- package/dist/agent-runtime/run-stream-recorded.d.ts.map +1 -0
- package/dist/agent-runtime/run-stream-step-text.d.ts +29 -0
- package/dist/agent-runtime/run-stream-step-text.d.ts.map +1 -0
- package/dist/agent-runtime/run-terminal.d.ts +3 -3
- package/dist/agent-runtime/run-terminal.d.ts.map +1 -1
- package/dist/agent-runtime/run-tool-approval-flow.d.ts +36 -0
- package/dist/agent-runtime/run-tool-approval-flow.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-approval-records.d.ts +24 -0
- package/dist/agent-runtime/run-tool-approval-records.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-call.d.ts +73 -0
- package/dist/agent-runtime/run-tool-call.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-errors.d.ts +29 -0
- package/dist/agent-runtime/run-tool-errors.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-executor.d.ts +34 -0
- package/dist/agent-runtime/run-tool-executor.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-progress.d.ts +2 -2
- package/dist/agent-runtime/run-tool-progress.d.ts.map +1 -1
- package/dist/agent-runtime/run-turn-preparation.d.ts +7 -6
- package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -1
- package/dist/agent-runtime/run-unacquired.d.ts +2 -2
- package/dist/agent-runtime/run-unacquired.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-control.d.ts +4 -4
- package/dist/agent-runtime/runtime-control.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-internals.d.ts +35 -44
- package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-recovery.d.ts +3 -3
- package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-state.d.ts +3 -3
- package/dist/agent-runtime/runtime-state.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-submit.d.ts +2 -2
- package/dist/agent-runtime/runtime-submit.d.ts.map +1 -1
- package/dist/agent-runtime/runtime.d.ts +51 -16
- package/dist/agent-runtime/runtime.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox-process-linux.d.ts +8 -0
- package/dist/agent-runtime/sandbox-process-linux.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-macos.d.ts +21 -0
- package/dist/agent-runtime/sandbox-process-macos.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-spec.d.ts +114 -0
- package/dist/agent-runtime/sandbox-process-spec.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-wrapper.d.ts +19 -0
- package/dist/agent-runtime/sandbox-process-wrapper.d.ts.map +1 -0
- package/dist/agent-runtime/schemas-message.d.ts +10 -0
- package/dist/agent-runtime/schemas-message.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-provider.d.ts +2 -0
- package/dist/agent-runtime/schemas-provider.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-run.d.ts +10 -0
- package/dist/agent-runtime/schemas-run.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-usage-state.d.ts +6 -0
- package/dist/agent-runtime/schemas-usage-state.d.ts.map +1 -0
- package/dist/agent-runtime/schemas-usage.d.ts +8 -0
- package/dist/agent-runtime/schemas-usage.d.ts.map +1 -1
- package/dist/agent-runtime/sql-rows.d.ts +20 -10
- package/dist/agent-runtime/sql-rows.d.ts.map +1 -1
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts +40 -20
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +1 -1
- package/dist/agent-runtime/store-conformance-support.d.ts +20 -10
- package/dist/agent-runtime/store-conformance-support.d.ts.map +1 -1
- package/dist/agent-runtime/store-driver-contract.d.ts +70 -0
- package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
- package/dist/agent-runtime/store-events.d.ts +120 -0
- package/dist/agent-runtime/store-events.d.ts.map +1 -1
- package/dist/agent-runtime/store.d.ts +140 -0
- package/dist/agent-runtime/store.d.ts.map +1 -1
- package/dist/agent-runtime/terminal-commit.d.ts +10 -0
- package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
- package/dist/agent-runtime/testing.d.ts +20 -0
- package/dist/agent-runtime/testing.d.ts.map +1 -1
- package/dist/browser/client-call-arguments.d.ts.map +1 -1
- package/dist/browser/client-executors.d.ts.map +1 -1
- package/dist/browser/client-url.d.ts.map +1 -1
- package/dist/browser/client.d.ts +6 -0
- package/dist/browser/client.d.ts.map +1 -1
- package/dist/browser/device-presence-client.d.ts +42 -0
- package/dist/browser/device-presence-client.d.ts.map +1 -0
- package/dist/browser/device-presence-ops.d.ts +47 -0
- package/dist/browser/device-presence-ops.d.ts.map +1 -0
- package/dist/browser/device-presence-relay-adapter.d.ts +37 -0
- package/dist/browser/device-presence-relay-adapter.d.ts.map +1 -0
- package/dist/browser/http-fetch.d.ts +7 -2
- package/dist/browser/http-fetch.d.ts.map +1 -1
- package/dist/browser/http-helpers.d.ts +15 -0
- package/dist/browser/http-helpers.d.ts.map +1 -0
- package/dist/browser/http.d.ts +8 -0
- package/dist/browser/http.d.ts.map +1 -1
- package/dist/contract/client-types.d.ts +8 -0
- package/dist/contract/client-types.d.ts.map +1 -1
- package/dist/contract/runtime-context.d.ts +13 -1
- package/dist/contract/runtime-context.d.ts.map +1 -1
- package/dist/device-relay/agent-handlers.d.ts +45 -0
- package/dist/device-relay/agent-handlers.d.ts.map +1 -0
- package/dist/device-relay/agent.d.ts +80 -0
- package/dist/device-relay/agent.d.ts.map +1 -0
- package/dist/device-relay/broker.d.ts +49 -0
- package/dist/device-relay/broker.d.ts.map +1 -0
- package/dist/device-relay/contract.d.ts +614 -0
- package/dist/device-relay/contract.d.ts.map +1 -0
- package/dist/device-relay/encoding.d.ts +30 -0
- package/dist/device-relay/encoding.d.ts.map +1 -0
- package/dist/device-relay/hub-connection.d.ts +43 -0
- package/dist/device-relay/hub-connection.d.ts.map +1 -0
- package/dist/device-relay/hub-dispatch.d.ts +19 -0
- package/dist/device-relay/hub-dispatch.d.ts.map +1 -0
- package/dist/device-relay/hub-handshake.d.ts +20 -0
- package/dist/device-relay/hub-handshake.d.ts.map +1 -0
- package/dist/device-relay/hub-shared-streams.d.ts +24 -0
- package/dist/device-relay/hub-shared-streams.d.ts.map +1 -0
- package/dist/device-relay/hub-streams.d.ts +57 -0
- package/dist/device-relay/hub-streams.d.ts.map +1 -0
- package/dist/device-relay/hub.d.ts +117 -0
- package/dist/device-relay/hub.d.ts.map +1 -0
- package/dist/entrypoints/agent-executor/acp.d.ts +1 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +224 -47
- package/dist/entrypoints/agent-executor/claude-sdk.js +15 -15
- package/dist/entrypoints/agent-executor/claude.js +13 -15
- package/dist/entrypoints/agent-executor/codex.js +88 -48
- package/dist/entrypoints/agent-executor/testing/claude-sdk.js +5 -5
- package/dist/entrypoints/agent-executor/testing.js +31 -30
- package/dist/entrypoints/agent-executor.d.ts +2 -2
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +23 -17
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +9 -0
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/ai-sdk.js +821 -0
- package/dist/entrypoints/agent-runtime/anthropic.d.ts +4 -0
- package/dist/entrypoints/agent-runtime/anthropic.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/anthropic.js +1260 -0
- package/dist/entrypoints/agent-runtime/browser.d.ts +4 -1
- package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/browser.js +449 -50
- package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
- package/dist/entrypoints/agent-runtime/harness.js +24 -19
- package/dist/entrypoints/agent-runtime/openai.d.ts +4 -0
- package/dist/entrypoints/agent-runtime/openai.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/openai.js +1246 -0
- package/dist/entrypoints/agent-runtime/openrouter.d.ts +5 -2
- package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/openrouter.js +2355 -371
- package/dist/entrypoints/agent-runtime/postgres.js +12 -10
- package/dist/entrypoints/agent-runtime/realtime.js +11 -10
- package/dist/entrypoints/agent-runtime/sandbox.d.ts +3 -0
- package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/sandbox.js +530 -7
- package/dist/entrypoints/agent-runtime/sqlite/bun.js +13 -11
- package/dist/entrypoints/agent-runtime/sqlite/node.js +13 -11
- package/dist/entrypoints/agent-runtime/testing.d.ts +1 -1
- package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/testing.js +56 -15
- package/dist/entrypoints/agent-runtime.d.ts +14 -6
- package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime.js +1412 -115
- package/dist/entrypoints/application/diagnostic-journal.js +6 -6
- package/dist/entrypoints/application/directory-inbox.js +6 -6
- package/dist/entrypoints/application/opentelemetry.js +3 -3
- package/dist/entrypoints/application.js +17 -17
- package/dist/entrypoints/cli/publish.js +8 -8
- package/dist/entrypoints/cli.js +14 -15
- package/dist/entrypoints/contract.d.ts +1 -0
- package/dist/entrypoints/contract.d.ts.map +1 -1
- package/dist/entrypoints/contract.js +13 -9
- package/dist/entrypoints/device-relay.d.ts +10 -0
- package/dist/entrypoints/device-relay.d.ts.map +1 -0
- package/dist/entrypoints/device-relay.js +2517 -0
- package/dist/entrypoints/files/packaging.js +3 -3
- package/dist/entrypoints/files.js +11 -11
- package/dist/entrypoints/geo.js +5 -5
- package/dist/entrypoints/google.js +1 -1
- package/dist/entrypoints/handler.js +6 -6
- package/dist/entrypoints/http.js +9 -9
- package/dist/entrypoints/index.js +21 -17
- package/dist/entrypoints/live.js +4 -4
- package/dist/entrypoints/node.js +13 -13
- package/dist/entrypoints/observability.js +9 -9
- package/dist/entrypoints/process/bootstrap.js +1 -1
- package/dist/entrypoints/process.js +5 -5
- package/dist/entrypoints/react.js +4 -4
- package/dist/entrypoints/realtime.d.ts +3 -0
- package/dist/entrypoints/realtime.d.ts.map +1 -1
- package/dist/entrypoints/realtime.js +413 -4
- package/dist/entrypoints/release.js +1 -1
- package/dist/entrypoints/remote.js +10 -10
- package/dist/entrypoints/server.d.ts +1 -0
- package/dist/entrypoints/server.d.ts.map +1 -1
- package/dist/entrypoints/server.js +546 -40
- package/dist/entrypoints/service-host/macos.js +10 -10
- package/dist/entrypoints/service-host/work.js +7 -7
- package/dist/entrypoints/service-host.js +15 -15
- package/dist/entrypoints/spend.js +3 -3
- package/dist/entrypoints/sync.js +4 -4
- package/dist/entrypoints/telegram/screens.js +6 -6
- package/dist/entrypoints/telegram.js +20 -20
- package/dist/entrypoints/testing.js +14 -14
- package/dist/entrypoints/tools/agent.d.ts +2 -1
- package/dist/entrypoints/tools/agent.d.ts.map +1 -1
- package/dist/entrypoints/tools/agent.js +8 -7
- package/dist/entrypoints/tools/connections.js +5 -5
- package/dist/entrypoints/tools/invoker.js +3 -4
- package/dist/entrypoints/tools/mcp.js +8 -9
- package/dist/entrypoints/tools/toolkit.js +32 -13
- package/dist/entrypoints/tools.d.ts +3 -1
- package/dist/entrypoints/tools.d.ts.map +1 -1
- package/dist/entrypoints/tools.js +37 -35
- package/dist/entrypoints/tracking/contract.js +1 -1
- package/dist/entrypoints/tracking/performance.js +4 -4
- package/dist/entrypoints/tracking.js +3 -3
- package/dist/{index-09f7w2qq.js → index-02kdtrcd.js} +1 -1
- package/dist/{index-y53cqwke.js → index-033tyx59.js} +1 -1
- package/dist/{index-9ft4n9j1.js → index-05b65gj4.js} +2 -2
- package/dist/{index-d04w81fz.js → index-0sxj3y45.js} +1 -1
- package/dist/{index-dm6nxkn1.js → index-18pf56dq.js} +4 -6
- package/dist/index-1gmgwfn3.js +439 -0
- package/dist/index-23wn8sgf.js +47 -0
- package/dist/{index-tqjamnax.js → index-27srek2g.js} +15 -13
- package/dist/{index-2nwvn7m2.js → index-29v1p1f4.js} +2 -2
- package/dist/index-36dmtzjr.js +194 -0
- package/dist/{index-ycr4pk0z.js → index-42n9jycn.js} +3 -3
- package/dist/{index-ke02kxsr.js → index-43k180c2.js} +1 -1
- package/dist/{index-pbekeqzm.js → index-5c4m8zdf.js} +2 -2
- package/dist/{index-qggqqja2.js → index-5dxgx3yj.js} +1 -1
- package/dist/{index-x5ayy5bn.js → index-5gdexvke.js} +3 -1
- package/dist/{index-t1a2jrg7.js → index-5xsxvk2x.js} +1 -1
- package/dist/{index-mbd92r1w.js → index-654rhe5d.js} +1 -1
- package/dist/{index-2dzc7mv9.js → index-67pnt4bh.js} +1 -1
- package/dist/index-6kpwkpgx.js +415 -0
- package/dist/{index-s43tr4my.js → index-6kwdfb9m.js} +18 -3
- package/dist/{index-1qwd54n3.js → index-6nzzj7qr.js} +1 -1
- package/dist/{index-rkjfzs0a.js → index-6p5pshcd.js} +2 -2
- package/dist/{index-118aebbg.js → index-6t4c98gr.js} +1 -1
- package/dist/{index-pws5c3x6.js → index-6xw1wf4m.js} +51 -32
- package/dist/{index-kwsr7j5k.js → index-6yb4stq3.js} +1 -1
- package/dist/{index-8jf4bt7v.js → index-76yhxa41.js} +8 -8
- package/dist/{index-7416mhyh.js → index-79vqbjcz.js} +1 -1
- package/dist/{index-13wmzpa6.js → index-7an2fs5h.js} +1 -1
- package/dist/index-7qza24g1.js +14 -0
- package/dist/{index-gtaaxe9d.js → index-8cek82ar.js} +1 -1
- package/dist/index-9f60gnfn.js +393 -0
- package/dist/{index-stpy56r3.js → index-aacwkve4.js} +209 -10
- package/dist/{index-rpyn7geq.js → index-ac3rfec5.js} +2 -2
- package/dist/{index-d2drhb9c.js → index-b0mh2t9x.js} +2 -2
- package/dist/index-b23s6e2c.js +158 -0
- package/dist/{index-an7vcmwf.js → index-bvpevwt6.js} +5 -5
- package/dist/{index-msxf2r8x.js → index-by8w2461.js} +1 -1
- package/dist/{index-8t9dr41h.js → index-c0yym4a0.js} +4 -4
- package/dist/{index-wddcfbng.js → index-c7fj4yw9.js} +1 -1
- package/dist/{index-tf70nm22.js → index-cb4nnvfr.js} +8 -6
- package/dist/{index-205456mf.js → index-d3s070eh.js} +2 -2
- package/dist/{index-apf5g7y9.js → index-dz6tstcp.js} +2 -2
- package/dist/{index-agy5fqgf.js → index-e1y74yra.js} +15 -8
- package/dist/index-edtg4tak.js +55 -0
- package/dist/{index-pq6g1k9t.js → index-ek9w11r0.js} +2 -2
- package/dist/{index-x46y9z26.js → index-epyj7ptp.js} +7 -5
- package/dist/{index-6kmjcm81.js → index-er483f3w.js} +93 -4
- package/dist/{index-827bgv33.js → index-f16b7rze.js} +1 -1
- package/dist/{index-gbhj370g.js → index-fec05c9k.js} +21 -21
- package/dist/{index-9wdrwx3b.js → index-fjac2w5e.js} +20 -22
- package/dist/{index-6918kxbf.js → index-fthw8dwa.js} +1 -0
- package/dist/{index-2mz8hj58.js → index-g04hszcm.js} +1 -1
- package/dist/{index-rw8ze745.js → index-ga6avd48.js} +1 -1
- package/dist/{index-paff5y0r.js → index-grhhsrd5.js} +9 -7
- package/dist/{index-mxt0wfjy.js → index-h20qcyh5.js} +5 -2
- package/dist/index-j3r7r1mh.js +150 -0
- package/dist/{index-vgytj9wp.js → index-jmaw365j.js} +1 -1
- package/dist/{index-t5g5rm9n.js → index-jzdbkanz.js} +5 -3
- package/dist/index-k137ezb6.js +79 -0
- package/dist/{index-tazm4dxf.js → index-kdw0n92g.js} +1 -1
- package/dist/{index-wh70tmpd.js → index-ke6jtxkd.js} +1 -1
- package/dist/index-kgj8j7bv.js +83 -0
- package/dist/{index-9kpxz49v.js → index-kgkevngs.js} +1 -1
- package/dist/{index-hab790s6.js → index-kp1j7cc8.js} +4 -4
- package/dist/{index-jcge9tx3.js → index-krekhmp7.js} +142 -123
- package/dist/{index-3y2tzhr8.js → index-ky79wwgs.js} +4 -4
- package/dist/{index-39rmc00v.js → index-mfe9a266.js} +1 -1
- package/dist/{index-qpzyahe3.js → index-mgr0mdqp.js} +5 -2
- package/dist/{index-n20tybgk.js → index-mh3jdb25.js} +2 -2
- package/dist/{index-g5fgeb6v.js → index-mkmep637.js} +1 -1
- package/dist/{index-02r5sq9p.js → index-mrng24wq.js} +19 -21
- package/dist/index-mx2gya05.js +465 -0
- package/dist/{index-8yt3rwe7.js → index-n2t87ggz.js} +5 -5
- package/dist/index-nfeafbzh.js +7379 -0
- package/dist/{index-j0ef04jw.js → index-nfm15ej7.js} +4 -4
- package/dist/index-pd9e8rz4.js +193 -0
- package/dist/{index-zwgwyvdt.js → index-pdcbjd6a.js} +1 -1
- package/dist/{index-q427q23r.js → index-pjjh91vw.js} +2 -2
- package/dist/{index-gnjgkecx.js → index-q46b16xz.js} +1 -1
- package/dist/{index-9xr44d2g.js → index-qv5v6w9c.js} +330 -106
- package/dist/{index-tmv3ez1h.js → index-qymek778.js} +69 -12
- package/dist/{index-yrr3n391.js → index-ry8m2mhg.js} +2 -2
- package/dist/{index-93n6jwy0.js → index-s0n0nnz5.js} +3 -3
- package/dist/{index-1p8q0yrt.js → index-t5zp1jjj.js} +5 -7
- package/dist/{index-2rf33y2h.js → index-tav72wz5.js} +4 -2
- package/dist/{index-jpecjm30.js → index-tgehj4bp.js} +1 -1
- package/dist/{index-ma26mfnt.js → index-v5hmyef8.js} +1 -1
- package/dist/index-vebzvse6.js +230 -0
- package/dist/index-vv0hxrmy.js +295 -0
- package/dist/index-vxm0ya3f.js +707 -0
- package/dist/{index-t3qcac2a.js → index-w3s79kcb.js} +1 -1
- package/dist/{index-r97ppg0g.js → index-x1r7kxzd.js} +1 -1
- package/dist/{index-kynwa08q.js → index-xrsryvd2.js} +2 -2
- package/dist/{index-3mcbr8sx.js → index-xtxxt87z.js} +1 -1
- package/dist/index-zk839vzf.js +231 -0
- package/dist/{index-9c76vfxf.js → index-zyyerdny.js} +4 -4
- package/dist/internal/base64.d.ts +9 -0
- package/dist/internal/base64.d.ts.map +1 -0
- package/dist/internal/deadline-budget.d.ts +57 -0
- package/dist/internal/deadline-budget.d.ts.map +1 -0
- package/dist/internal/deadline.d.ts.map +1 -1
- package/dist/internal/timers.d.ts +2 -0
- package/dist/internal/timers.d.ts.map +1 -1
- package/dist/realtime/device-presence-contract.d.ts +194 -0
- package/dist/realtime/device-presence-contract.d.ts.map +1 -0
- package/dist/server/context-contribution.d.ts.map +1 -1
- package/dist/server/contract-method.d.ts.map +1 -1
- package/dist/server/device-presence-handlers.d.ts +54 -0
- package/dist/server/device-presence-handlers.d.ts.map +1 -0
- package/dist/server/device-presence-registry.d.ts +35 -0
- package/dist/server/device-presence-registry.d.ts.map +1 -0
- package/dist/server/device-presence.d.ts +45 -0
- package/dist/server/device-presence.d.ts.map +1 -0
- package/dist/server/endpoint-dispatch.d.ts.map +1 -1
- package/dist/server/middleware/cors.d.ts +3 -1
- package/dist/server/middleware/cors.d.ts.map +1 -1
- package/dist/server/types.d.ts +4 -11
- package/dist/server/types.d.ts.map +1 -1
- package/dist/service-host/systemd-render-shared.d.ts.map +1 -1
- package/dist/tools/agent-messages.d.ts +6 -0
- package/dist/tools/agent-messages.d.ts.map +1 -0
- package/dist/tools/agent-tool-error.d.ts +2 -2
- package/dist/tools/agent-tools.d.ts +153 -0
- package/dist/tools/agent-tools.d.ts.map +1 -0
- package/dist/tools/agent.d.ts +6 -56
- package/dist/tools/agent.d.ts.map +1 -1
- package/dist/tools/runtime-tool.d.ts +3 -4
- package/dist/tools/runtime-tool.d.ts.map +1 -1
- package/dist/tools/toolkit.d.ts +3 -1
- package/dist/tools/toolkit.d.ts.map +1 -1
- package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -1
- package/llms/agent-executor-acp.txt +4 -4
- package/llms/agent-executor-codex.txt +1 -1
- package/llms/agent-executor.txt +7 -3
- package/llms/agent-runtime-ai-sdk.txt +26 -0
- package/llms/agent-runtime-anthropic.txt +33 -0
- package/llms/agent-runtime-browser.txt +22 -8
- package/llms/agent-runtime-harness.txt +2 -2
- package/llms/agent-runtime-openai.txt +31 -0
- package/llms/agent-runtime-openrouter.txt +17 -7
- package/llms/agent-runtime-sandbox.txt +53 -1
- package/llms/agent-runtime-testing.txt +4 -2
- package/llms/agent-runtime.2.txt +158 -271
- package/llms/agent-runtime.3.txt +289 -243
- package/llms/agent-runtime.4.txt +273 -216
- package/llms/agent-runtime.5.txt +209 -2
- package/llms/agent-runtime.txt +238 -181
- package/llms/contract.txt +2 -1
- package/llms/device-relay.txt +34 -0
- package/llms/realtime.txt +20 -0
- package/llms/server.2.txt +125 -1
- package/llms/server.3.txt +111 -122
- package/llms/server.4.txt +1 -1
- package/llms/server.5.txt +3 -1
- package/llms/server.txt +31 -1
- package/llms/spend.txt +11 -6
- package/llms/stitchkit.2.txt +21 -43
- package/llms/stitchkit.3.txt +43 -0
- package/llms/stitchkit.txt +93 -84
- package/llms/tools-agent.txt +7 -5
- package/llms/tools-toolkit.txt +1 -1
- package/llms/tools.4.txt +7 -2
- package/llms/{upgrading-0.128.0-0.133.0.txt → upgrading-0.128.0-0.134.0.txt} +173 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +983 -212
- package/llms.txt +21 -17
- package/package.json +18 -7
- package/dist/index-0p0s5hrj.js +0 -249
- package/dist/index-1dn2wjq6.js +0 -135
- package/dist/index-1psbyyhj.js +0 -21
- package/dist/index-34k82crg.js +0 -3961
- package/dist/index-5n3a8hd8.js +0 -102
- package/dist/index-97rp94ff.js +0 -8
- package/dist/index-bn2baakz.js +0 -336
- package/dist/index-eh71zr32.js +0 -14
- package/dist/index-emgrmavr.js +0 -1193
- package/dist/index-fzd477xk.js +0 -135
- package/dist/index-vgzhw2zk.js +0 -304
- package/dist/internal/ai-sdk-typed.d.ts +0 -14
- package/dist/internal/ai-sdk-typed.d.ts.map +0 -1
- package/dist/tools/runtime-call-context.d.ts +0 -15
- package/dist/tools/runtime-call-context.d.ts.map +0 -1
- package/dist/{index-vmbxj75t.js → index-jwtmw39p.js} +0 -0
- package/dist/{index-877e9y8r.js → index-sk03xe0n.js} +3 -3
- package/dist/{index-21cfxc4z.js → index-vh4291qh.js} +3 -3
package/dist/index-34k82crg.js
DELETED
|
@@ -1,3961 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AgentMessagePartSchema2
|
|
3
|
-
} from "./index-2rf33y2h.js";
|
|
4
|
-
import {
|
|
5
|
-
AgentMessageSchema2,
|
|
6
|
-
AgentAssistantPlaceholderSchema2,
|
|
7
|
-
AgentProvenanceSchema2,
|
|
8
|
-
AgentRunOperationSchema2,
|
|
9
|
-
runStateForTerminalReason2,
|
|
10
|
-
AgentRunSchema2,
|
|
11
|
-
AgentSnapshotSchema2
|
|
12
|
-
} from "./index-bn2baakz.js";
|
|
13
|
-
import {
|
|
14
|
-
InvocationPayloadSchema,
|
|
15
|
-
InvocationExpiredPayloadSchema,
|
|
16
|
-
PurgeInvocationPayloadsInputSchema2,
|
|
17
|
-
ModelInvocationTraceSchema2,
|
|
18
|
-
CompletionInvocationInputSchema2,
|
|
19
|
-
InvocationCallerSchema,
|
|
20
|
-
InvocationStartedSchema,
|
|
21
|
-
ModelInvocationRecordSchema2,
|
|
22
|
-
InvocationStoredPayloadSchema,
|
|
23
|
-
ModelInvocationPayloadReadSchema2,
|
|
24
|
-
isModelInvocationRecord,
|
|
25
|
-
createToolChronology,
|
|
26
|
-
advanceToolChronology,
|
|
27
|
-
canProjectToolChronology,
|
|
28
|
-
isAssistantHistoryEvidence2,
|
|
29
|
-
isCompleteAgentHistoryTurn,
|
|
30
|
-
assistantStatus
|
|
31
|
-
} from "./index-vgzhw2zk.js";
|
|
32
|
-
import {
|
|
33
|
-
withStoreRetries,
|
|
34
|
-
AgentRuntimeConflictError2,
|
|
35
|
-
AgentRunUnsettledError2,
|
|
36
|
-
appliedSnapshot,
|
|
37
|
-
terminalOfSnapshot,
|
|
38
|
-
terminalOfRunView,
|
|
39
|
-
commitAgentRunTerminal,
|
|
40
|
-
findRun,
|
|
41
|
-
jsonValue,
|
|
42
|
-
providerEnvelope,
|
|
43
|
-
providerResponseIdentity,
|
|
44
|
-
appendText,
|
|
45
|
-
abortTerminalReason,
|
|
46
|
-
mergeModelTotals,
|
|
47
|
-
statedUsage,
|
|
48
|
-
normalizeSdkUsage,
|
|
49
|
-
createIdleDeadline,
|
|
50
|
-
adoptSnapshot,
|
|
51
|
-
transientSequence,
|
|
52
|
-
runUsage,
|
|
53
|
-
updateReasoning,
|
|
54
|
-
checkpoint,
|
|
55
|
-
DEFAULT_STEP_SPEND_TIMEOUT_MS,
|
|
56
|
-
normalizeStepUsage,
|
|
57
|
-
recordStepSpend,
|
|
58
|
-
InvocationReceiptError,
|
|
59
|
-
invocationHash,
|
|
60
|
-
createInvocationPayloads,
|
|
61
|
-
isOwnInputRefusal,
|
|
62
|
-
markProviderOrigin,
|
|
63
|
-
hasProviderOrigin,
|
|
64
|
-
markProviderStream,
|
|
65
|
-
wrapInvocationModel
|
|
66
|
-
} from "./index-emgrmavr.js";
|
|
67
|
-
import {
|
|
68
|
-
AGENT_TOOL_PROGRESS_MESSAGE_MAX2,
|
|
69
|
-
agentDurableEventId2
|
|
70
|
-
} from "./index-paff5y0r.js";
|
|
71
|
-
import {
|
|
72
|
-
ToolExecutionControlError2,
|
|
73
|
-
isToolExecutionControlError2
|
|
74
|
-
} from "./index-6kmjcm81.js";
|
|
75
|
-
import {
|
|
76
|
-
contractOperationEffects2
|
|
77
|
-
} from "./index-werjqesf.js";
|
|
78
|
-
import {
|
|
79
|
-
createLocalStepDurability2
|
|
80
|
-
} from "./index-kynwa08q.js";
|
|
81
|
-
import {
|
|
82
|
-
isActiveRunState,
|
|
83
|
-
canonicalAgentJson2,
|
|
84
|
-
issueRunContext,
|
|
85
|
-
ProviderJournalMessageSchema,
|
|
86
|
-
ProviderJournalRequestSchema,
|
|
87
|
-
ProviderJournalResponseSchema
|
|
88
|
-
} from "./index-9xr44d2g.js";
|
|
89
|
-
import {
|
|
90
|
-
createRuntimeToolContext
|
|
91
|
-
} from "./index-eh71zr32.js";
|
|
92
|
-
import {
|
|
93
|
-
createMutationQueue
|
|
94
|
-
} from "./index-sykb5ag7.js";
|
|
95
|
-
import {
|
|
96
|
-
messageOf
|
|
97
|
-
} from "./index-r9kq5ark.js";
|
|
98
|
-
import {
|
|
99
|
-
listContractToolNames2
|
|
100
|
-
} from "./index-pq6g1k9t.js";
|
|
101
|
-
import {
|
|
102
|
-
AgentToolError2,
|
|
103
|
-
isAgentToolError2
|
|
104
|
-
} from "./index-1psbyyhj.js";
|
|
105
|
-
import {
|
|
106
|
-
assertPositiveSafeInteger
|
|
107
|
-
} from "./index-gr0kxymw.js";
|
|
108
|
-
import {
|
|
109
|
-
isRecord,
|
|
110
|
-
transportResult,
|
|
111
|
-
mapObjectTypeBoundary
|
|
112
|
-
} from "./index-ps3djm8d.js";
|
|
113
|
-
import {
|
|
114
|
-
assertTimerMs,
|
|
115
|
-
withDeadline
|
|
116
|
-
} from "./index-agy5fqgf.js";
|
|
117
|
-
import {
|
|
118
|
-
raceAbort,
|
|
119
|
-
linkAbortSignals
|
|
120
|
-
} from "./index-rptj3qnc.js";
|
|
121
|
-
|
|
122
|
-
// src/agent-runtime/context-refusal.ts
|
|
123
|
-
class AgentContextOverflowError2 extends Error {
|
|
124
|
-
name = "AgentContextOverflowError";
|
|
125
|
-
constructor(message = "Agent context exceeds the configured model budget", options) {
|
|
126
|
-
super(message, options);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// src/agent-runtime/coordinator.ts
|
|
131
|
-
function assertCloseBudgets(options) {
|
|
132
|
-
assertTimerMs("Agent session close gracePeriodMs", options.gracePeriodMs, { min: 0 });
|
|
133
|
-
assertTimerMs("Agent session close forceTimeoutMs", options.forceTimeoutMs, { min: 0 });
|
|
134
|
-
}
|
|
135
|
-
function createAgentSessionCoordinator2() {
|
|
136
|
-
const lanes = new Map;
|
|
137
|
-
let closed = false;
|
|
138
|
-
const waitWithin = async (settled, timeoutMs) => {
|
|
139
|
-
if (timeoutMs === 0)
|
|
140
|
-
return false;
|
|
141
|
-
return (await withDeadline(settled, timeoutMs)).settled;
|
|
142
|
-
};
|
|
143
|
-
const laneFor = (key) => {
|
|
144
|
-
const existing = lanes.get(key);
|
|
145
|
-
if (existing)
|
|
146
|
-
return existing;
|
|
147
|
-
const created = { queue: [] };
|
|
148
|
-
lanes.set(key, created);
|
|
149
|
-
return created;
|
|
150
|
-
};
|
|
151
|
-
const startNext = (key, lane) => {
|
|
152
|
-
if (lane.active)
|
|
153
|
-
return;
|
|
154
|
-
const next = lane.queue.shift();
|
|
155
|
-
if (!next) {
|
|
156
|
-
lanes.delete(key);
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
next.start();
|
|
160
|
-
};
|
|
161
|
-
return {
|
|
162
|
-
submit(input) {
|
|
163
|
-
const accepted = Promise.withResolvers();
|
|
164
|
-
const result = Promise.withResolvers();
|
|
165
|
-
if (closed) {
|
|
166
|
-
const error = new Error("Agent session coordinator is closed");
|
|
167
|
-
accepted.reject(error);
|
|
168
|
-
result.reject(error);
|
|
169
|
-
return { accepted: accepted.promise, result: result.promise };
|
|
170
|
-
}
|
|
171
|
-
const lane = laneFor(input.key);
|
|
172
|
-
const pending = {
|
|
173
|
-
priority: input.policy === "interrupt-next",
|
|
174
|
-
reject(reason) {
|
|
175
|
-
accepted.reject(reason);
|
|
176
|
-
result.reject(reason);
|
|
177
|
-
},
|
|
178
|
-
async start() {
|
|
179
|
-
const controller = new AbortController;
|
|
180
|
-
const settlement = Promise.withResolvers();
|
|
181
|
-
lane.active = { controller, settled: settlement.promise };
|
|
182
|
-
try {
|
|
183
|
-
const coordinated = await input.create(controller.signal);
|
|
184
|
-
accepted.resolve();
|
|
185
|
-
result.resolve(await coordinated.execute());
|
|
186
|
-
} catch (error) {
|
|
187
|
-
accepted.reject(error);
|
|
188
|
-
result.reject(error);
|
|
189
|
-
} finally {
|
|
190
|
-
settlement.resolve();
|
|
191
|
-
lane.active = undefined;
|
|
192
|
-
startNext(input.key, lane);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
};
|
|
196
|
-
if (input.policy === "interrupt" || input.policy === "interrupt-next") {
|
|
197
|
-
lane.active?.controller.abort("user-interrupt");
|
|
198
|
-
}
|
|
199
|
-
if (input.policy === "supersede")
|
|
200
|
-
lane.active?.controller.abort("supersede");
|
|
201
|
-
if (pending.priority) {
|
|
202
|
-
const firstOrdinary = lane.queue.findIndex((queued) => !queued.priority);
|
|
203
|
-
if (firstOrdinary === -1)
|
|
204
|
-
lane.queue.push(pending);
|
|
205
|
-
else
|
|
206
|
-
lane.queue.splice(firstOrdinary, 0, pending);
|
|
207
|
-
} else {
|
|
208
|
-
lane.queue.push(pending);
|
|
209
|
-
}
|
|
210
|
-
startNext(input.key, lane);
|
|
211
|
-
return { accepted: accepted.promise, result: result.promise };
|
|
212
|
-
},
|
|
213
|
-
stop(key, reason = "user-interrupt") {
|
|
214
|
-
const lane = lanes.get(key);
|
|
215
|
-
if (!lane?.active)
|
|
216
|
-
return false;
|
|
217
|
-
lane.active.controller.abort(reason);
|
|
218
|
-
return true;
|
|
219
|
-
},
|
|
220
|
-
async close(options = {}) {
|
|
221
|
-
assertCloseBudgets(options);
|
|
222
|
-
closed = true;
|
|
223
|
-
const error = new Error("Agent session coordinator is closed");
|
|
224
|
-
for (const lane of lanes.values()) {
|
|
225
|
-
for (const pending of lane.queue.splice(0))
|
|
226
|
-
pending.reject(error);
|
|
227
|
-
}
|
|
228
|
-
const active = [...lanes.values()].map((lane) => lane.active).filter((run) => run !== undefined);
|
|
229
|
-
const settlements = active.map((run) => run.settled);
|
|
230
|
-
const outstanding = new Set(settlements);
|
|
231
|
-
for (const settled of settlements) {
|
|
232
|
-
settled.then(() => {
|
|
233
|
-
outstanding.delete(settled);
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
const drain = Promise.all(settlements).then(() => {
|
|
237
|
-
return;
|
|
238
|
-
});
|
|
239
|
-
const finished = () => ({
|
|
240
|
-
settled: outstanding.size === 0,
|
|
241
|
-
timedOut: outstanding.size > 0,
|
|
242
|
-
remaining: outstanding.size
|
|
243
|
-
});
|
|
244
|
-
if (options.gracePeriodMs !== undefined && await waitWithin(drain, options.gracePeriodMs)) {
|
|
245
|
-
return finished();
|
|
246
|
-
}
|
|
247
|
-
for (const run of active)
|
|
248
|
-
run.controller.abort("shutdown");
|
|
249
|
-
if (options.forceTimeoutMs === undefined) {
|
|
250
|
-
await drain;
|
|
251
|
-
return finished();
|
|
252
|
-
}
|
|
253
|
-
await waitWithin(drain, options.forceTimeoutMs);
|
|
254
|
-
return finished();
|
|
255
|
-
},
|
|
256
|
-
isRunning(key) {
|
|
257
|
-
return lanes.get(key)?.active !== undefined;
|
|
258
|
-
}
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// src/agent-runtime/deferred-tools-internal.ts
|
|
263
|
-
var repairs = new WeakMap;
|
|
264
|
-
var catalogs = new WeakMap;
|
|
265
|
-
function registerDeferredToolRepair(prepareStep, repair) {
|
|
266
|
-
repairs.set(prepareStep, repair);
|
|
267
|
-
}
|
|
268
|
-
function deferredToolRepair(prepareStep) {
|
|
269
|
-
return prepareStep ? repairs.get(prepareStep) : undefined;
|
|
270
|
-
}
|
|
271
|
-
function registerDeferredToolCatalog(tools, searchName, names) {
|
|
272
|
-
const search = tools[searchName];
|
|
273
|
-
if (search && typeof search === "object")
|
|
274
|
-
catalogs.set(search, names);
|
|
275
|
-
}
|
|
276
|
-
function carryDeferredToolCatalog(from, to) {
|
|
277
|
-
for (const [name, tool] of Object.entries(from)) {
|
|
278
|
-
const names = tool && typeof tool === "object" ? catalogs.get(tool) : undefined;
|
|
279
|
-
const next = to[name];
|
|
280
|
-
if (names && next && typeof next === "object")
|
|
281
|
-
catalogs.set(next, names);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
function deferredToolCatalog(tools, searchName) {
|
|
285
|
-
const search = tools[searchName];
|
|
286
|
-
return search && typeof search === "object" ? catalogs.get(search) : undefined;
|
|
287
|
-
}
|
|
288
|
-
function repairedSearchCall(toolCall, searchName) {
|
|
289
|
-
return {
|
|
290
|
-
...toolCall,
|
|
291
|
-
toolName: searchName,
|
|
292
|
-
input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
|
|
293
|
-
};
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// src/agent-runtime/history.ts
|
|
297
|
-
import { modelMessageSchema as modelMessageSchema2 } from "ai";
|
|
298
|
-
|
|
299
|
-
// src/internal/ai-sdk-typed.ts
|
|
300
|
-
import { modelMessageSchema, streamText } from "ai";
|
|
301
|
-
function streamAgentTextBoundary(options) {
|
|
302
|
-
return streamText(options);
|
|
303
|
-
}
|
|
304
|
-
function modelMessageWithApprovalSignature(input) {
|
|
305
|
-
const parsed = modelMessageSchema.parse(input);
|
|
306
|
-
const rawContent = isRecord(input) ? input.content : undefined;
|
|
307
|
-
if (parsed.role !== "assistant" || typeof parsed.content === "string" || !Array.isArray(rawContent)) {
|
|
308
|
-
return parsed;
|
|
309
|
-
}
|
|
310
|
-
const content = parsed.content.map((part, index) => {
|
|
311
|
-
const raw = rawContent[index];
|
|
312
|
-
if (part.type !== "tool-approval-request" || !isRecord(raw) || typeof raw.signature !== "string") {
|
|
313
|
-
return part;
|
|
314
|
-
}
|
|
315
|
-
return { ...part, signature: raw.signature };
|
|
316
|
-
});
|
|
317
|
-
return transportResult({ ...parsed, content });
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// src/agent-runtime/history.ts
|
|
321
|
-
function providerOptions(envelope) {
|
|
322
|
-
if (!envelope)
|
|
323
|
-
return;
|
|
324
|
-
return envelope.provider === "ai-sdk" ? envelope.data : { [envelope.provider]: envelope.data };
|
|
325
|
-
}
|
|
326
|
-
function textContent(parts) {
|
|
327
|
-
return parts.filter((part) => part.type === "text").map((part) => part.text).join(`
|
|
328
|
-
`);
|
|
329
|
-
}
|
|
330
|
-
function unrepresented(parts, rendered) {
|
|
331
|
-
const missing = new Set;
|
|
332
|
-
for (const part of parts) {
|
|
333
|
-
if (!rendered.has(part.type))
|
|
334
|
-
missing.add(part.type);
|
|
335
|
-
}
|
|
336
|
-
return [...missing];
|
|
337
|
-
}
|
|
338
|
-
function decide(message, action, reason, rendered) {
|
|
339
|
-
if (action === "omitted" || !rendered)
|
|
340
|
-
return { messageId: message.id, action, reason };
|
|
341
|
-
const omittedParts = unrepresented(message.parts, rendered);
|
|
342
|
-
return {
|
|
343
|
-
messageId: message.id,
|
|
344
|
-
action,
|
|
345
|
-
reason,
|
|
346
|
-
...omittedParts.length > 0 && { omittedParts }
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
var INTERRUPTION_NOTE = "[interrupted: this turn was cut off before it finished]";
|
|
350
|
-
var FAILURE_NOTE = "[failed: partial evidence from a run that did not complete successfully]";
|
|
351
|
-
async function userMessage(message, options) {
|
|
352
|
-
const rendered = new Set;
|
|
353
|
-
const text = textContent(message.parts);
|
|
354
|
-
const content = [];
|
|
355
|
-
if (text) {
|
|
356
|
-
content.push({ type: "text", text });
|
|
357
|
-
rendered.add("text");
|
|
358
|
-
}
|
|
359
|
-
for (const part of message.parts) {
|
|
360
|
-
if (part.type !== "file")
|
|
361
|
-
continue;
|
|
362
|
-
if (options.resolveFile) {
|
|
363
|
-
content.push({
|
|
364
|
-
type: "file",
|
|
365
|
-
data: await options.resolveFile(part, message),
|
|
366
|
-
mediaType: part.mediaType,
|
|
367
|
-
...part.filename && { filename: part.filename }
|
|
368
|
-
});
|
|
369
|
-
rendered.add("file");
|
|
370
|
-
continue;
|
|
371
|
-
}
|
|
372
|
-
const fallback = options.unresolvedFile ?? "omit";
|
|
373
|
-
if (fallback === "error") {
|
|
374
|
-
throw new Error(`No history file resolver configured for ${part.reference}`);
|
|
375
|
-
}
|
|
376
|
-
if (fallback === "text") {
|
|
377
|
-
const described = part.filename ?? part.mediaType;
|
|
378
|
-
content.push({
|
|
379
|
-
type: "text",
|
|
380
|
-
text: described ? `[attachment: ${described}]` : "[attachment]"
|
|
381
|
-
});
|
|
382
|
-
rendered.add("file");
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
if (content.length === 0)
|
|
386
|
-
return { rendered };
|
|
387
|
-
return { message: modelMessageSchema2.parse({ role: "user", content }), rendered };
|
|
388
|
-
}
|
|
389
|
-
function assistantMessages(message, marker) {
|
|
390
|
-
const rendered = new Set;
|
|
391
|
-
const messages = [];
|
|
392
|
-
let role;
|
|
393
|
-
let content = [];
|
|
394
|
-
const flush = () => {
|
|
395
|
-
if (!role || content.length === 0)
|
|
396
|
-
return;
|
|
397
|
-
messages.push(modelMessageWithApprovalSignature({ role, content }));
|
|
398
|
-
content = [];
|
|
399
|
-
};
|
|
400
|
-
const append = (nextRole, part) => {
|
|
401
|
-
if (role !== nextRole) {
|
|
402
|
-
flush();
|
|
403
|
-
role = nextRole;
|
|
404
|
-
}
|
|
405
|
-
content.push(part);
|
|
406
|
-
};
|
|
407
|
-
for (const part of message.parts) {
|
|
408
|
-
if (part.type === "text") {
|
|
409
|
-
append("assistant", { type: "text", text: part.text });
|
|
410
|
-
rendered.add("text");
|
|
411
|
-
}
|
|
412
|
-
if (part.type === "reasoning") {
|
|
413
|
-
append("assistant", {
|
|
414
|
-
type: "reasoning",
|
|
415
|
-
text: part.text,
|
|
416
|
-
...part.provider && { providerOptions: providerOptions(part.provider) }
|
|
417
|
-
});
|
|
418
|
-
rendered.add("reasoning");
|
|
419
|
-
}
|
|
420
|
-
if (part.type === "tool-call") {
|
|
421
|
-
append("assistant", {
|
|
422
|
-
type: "tool-call",
|
|
423
|
-
toolCallId: part.callId,
|
|
424
|
-
toolName: part.toolName,
|
|
425
|
-
input: part.input,
|
|
426
|
-
...part.provider && { providerOptions: providerOptions(part.provider) }
|
|
427
|
-
});
|
|
428
|
-
rendered.add("tool-call");
|
|
429
|
-
}
|
|
430
|
-
if (part.type === "tool-result") {
|
|
431
|
-
const output = part.outcome === "success" ? { type: "json", value: part.output ?? null } : { type: "error-json", value: part.output ?? { message: part.outcome } };
|
|
432
|
-
append("tool", {
|
|
433
|
-
type: "tool-result",
|
|
434
|
-
toolCallId: part.callId,
|
|
435
|
-
toolName: part.toolName,
|
|
436
|
-
output
|
|
437
|
-
});
|
|
438
|
-
rendered.add("tool-result");
|
|
439
|
-
}
|
|
440
|
-
if (part.type === "tool-approval-request") {
|
|
441
|
-
append("assistant", {
|
|
442
|
-
type: "tool-approval-request",
|
|
443
|
-
approvalId: part.approvalId,
|
|
444
|
-
toolCallId: part.callId,
|
|
445
|
-
...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
|
|
446
|
-
...part.signature && { signature: part.signature }
|
|
447
|
-
});
|
|
448
|
-
rendered.add("tool-approval-request");
|
|
449
|
-
}
|
|
450
|
-
if (part.type === "tool-approval-response") {
|
|
451
|
-
append("tool", {
|
|
452
|
-
type: "tool-approval-response",
|
|
453
|
-
approvalId: part.approvalId,
|
|
454
|
-
approved: part.approved,
|
|
455
|
-
...part.reason && { reason: part.reason }
|
|
456
|
-
});
|
|
457
|
-
rendered.add("tool-approval-response");
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
if (marker === "failed" || marker && (messages.length > 0 || content.length > 0)) {
|
|
461
|
-
append("assistant", {
|
|
462
|
-
type: "text",
|
|
463
|
-
text: marker === "interrupted" ? INTERRUPTION_NOTE : FAILURE_NOTE
|
|
464
|
-
});
|
|
465
|
-
rendered.add("control");
|
|
466
|
-
}
|
|
467
|
-
flush();
|
|
468
|
-
return { messages, rendered };
|
|
469
|
-
}
|
|
470
|
-
function interruptedSystemNote(message) {
|
|
471
|
-
const rendered = new Set;
|
|
472
|
-
const text = textContent(message.parts);
|
|
473
|
-
if (!text)
|
|
474
|
-
return { rendered };
|
|
475
|
-
rendered.add("text");
|
|
476
|
-
rendered.add("control");
|
|
477
|
-
return { text: `[interrupted] partial response: ${text}`, rendered };
|
|
478
|
-
}
|
|
479
|
-
async function projectAgentHistoryDetailed2(messages, options = {}) {
|
|
480
|
-
const projected = [];
|
|
481
|
-
const system = [];
|
|
482
|
-
const decisions = [];
|
|
483
|
-
const interruptedRule = options.interruptedAssistant ?? "assistant-marked";
|
|
484
|
-
let observedUser = false;
|
|
485
|
-
let chronology = createToolChronology();
|
|
486
|
-
let conversationId;
|
|
487
|
-
for (const message of messages) {
|
|
488
|
-
if (message.conversationId !== conversationId) {
|
|
489
|
-
conversationId = message.conversationId;
|
|
490
|
-
chronology = createToolChronology();
|
|
491
|
-
observedUser = false;
|
|
492
|
-
}
|
|
493
|
-
if (message.role === "assistant" && !isAssistantHistoryEvidence2(message.status, options.evidencePolicy)) {
|
|
494
|
-
decisions.push(decide(message, "omitted", message.status === "superseded" ? "superseded" : "draft-or-failed"));
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
if (message.status === "streaming" || message.status === "failed" && options.evidencePolicy?.failedAssistant !== "assistant-marked") {
|
|
498
|
-
decisions.push(decide(message, "omitted", "draft-or-failed"));
|
|
499
|
-
continue;
|
|
500
|
-
}
|
|
501
|
-
if (message.role === "user") {
|
|
502
|
-
const user = await userMessage(message, options);
|
|
503
|
-
if (chronology.pending === 0)
|
|
504
|
-
chronology = createToolChronology();
|
|
505
|
-
observedUser = true;
|
|
506
|
-
if (user.message) {
|
|
507
|
-
projected.push(user.message);
|
|
508
|
-
decisions.push(decide(message, "projected", "projected", user.rendered));
|
|
509
|
-
} else {
|
|
510
|
-
decisions.push(decide(message, "omitted", "empty"));
|
|
511
|
-
}
|
|
512
|
-
continue;
|
|
513
|
-
}
|
|
514
|
-
if (message.role === "system" || message.role === "summary") {
|
|
515
|
-
const content = textContent(message.parts);
|
|
516
|
-
if (content) {
|
|
517
|
-
system.push(content);
|
|
518
|
-
decisions.push(decide(message, "projected", "projected", new Set(["text"])));
|
|
519
|
-
} else {
|
|
520
|
-
decisions.push(decide(message, "omitted", "empty"));
|
|
521
|
-
}
|
|
522
|
-
continue;
|
|
523
|
-
}
|
|
524
|
-
if (!observedUser && options.leadingAssistant !== "allow") {
|
|
525
|
-
if (options.leadingAssistant === "error") {
|
|
526
|
-
throw new Error(`Assistant message ${message.id} precedes the first user message`);
|
|
527
|
-
}
|
|
528
|
-
decisions.push(decide(message, "omitted", "leading-assistant"));
|
|
529
|
-
continue;
|
|
530
|
-
}
|
|
531
|
-
const interrupted = message.status === "interrupted";
|
|
532
|
-
if (interrupted && interruptedRule === "omit") {
|
|
533
|
-
decisions.push(decide(message, "omitted", "interrupted"));
|
|
534
|
-
continue;
|
|
535
|
-
}
|
|
536
|
-
if (interrupted && interruptedRule === "system-note") {
|
|
537
|
-
const note = interruptedSystemNote(message);
|
|
538
|
-
if (note.text) {
|
|
539
|
-
system.push(note.text);
|
|
540
|
-
decisions.push(decide(message, "projected", "projected", note.rendered));
|
|
541
|
-
} else {
|
|
542
|
-
decisions.push(decide(message, "omitted", "empty"));
|
|
543
|
-
}
|
|
544
|
-
continue;
|
|
545
|
-
}
|
|
546
|
-
const nextChronology = advanceToolChronology(chronology, message.parts);
|
|
547
|
-
if (!nextChronology || !canProjectToolChronology(nextChronology)) {
|
|
548
|
-
if (options.incompleteToolTurn === "error") {
|
|
549
|
-
throw new Error(`Assistant message ${message.id} has incomplete tool chronology`);
|
|
550
|
-
}
|
|
551
|
-
decisions.push(decide(message, "omitted", "incomplete-tool-turn"));
|
|
552
|
-
continue;
|
|
553
|
-
}
|
|
554
|
-
const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
|
|
555
|
-
chronology = nextChronology;
|
|
556
|
-
projected.push(...assistant.messages);
|
|
557
|
-
decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
|
|
558
|
-
}
|
|
559
|
-
return { messages: projected, decisions, system };
|
|
560
|
-
}
|
|
561
|
-
async function projectAgentHistory2(messages, options = {}) {
|
|
562
|
-
return [...(await projectAgentHistoryDetailed2(messages, options)).messages];
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
// src/agent-runtime/invocations.ts
|
|
566
|
-
import { randomUUID } from "node:crypto";
|
|
567
|
-
import { hostname } from "node:os";
|
|
568
|
-
import { generateText } from "ai";
|
|
569
|
-
import { z as z2 } from "zod";
|
|
570
|
-
|
|
571
|
-
// src/agent-runtime/invocation-read.ts
|
|
572
|
-
import { z } from "zod";
|
|
573
|
-
var InvocationReadInputSchema = z.object({
|
|
574
|
-
conversationId: z.string().min(1),
|
|
575
|
-
fromSeq: z.int().positive().optional(),
|
|
576
|
-
limit: z.int().positive().max(1e4)
|
|
577
|
-
}).strict();
|
|
578
|
-
async function readInvocationRecords(store, input) {
|
|
579
|
-
const page = await store.readEvents(InvocationReadInputSchema.parse(input));
|
|
580
|
-
return {
|
|
581
|
-
items: page.items.flatMap((event) => {
|
|
582
|
-
if (![
|
|
583
|
-
"invocation/started",
|
|
584
|
-
"invocation/finished",
|
|
585
|
-
"provider/request",
|
|
586
|
-
"provider/response"
|
|
587
|
-
].includes(event.kind))
|
|
588
|
-
return [];
|
|
589
|
-
if (!isModelInvocationRecord(event.payload))
|
|
590
|
-
return [];
|
|
591
|
-
return [
|
|
592
|
-
{
|
|
593
|
-
seq: event.seq,
|
|
594
|
-
occurredAt: event.occurredAt,
|
|
595
|
-
record: ModelInvocationRecordSchema2.parse(event.payload)
|
|
596
|
-
}
|
|
597
|
-
];
|
|
598
|
-
}),
|
|
599
|
-
...page.nextSeq !== undefined && { nextSeq: page.nextSeq }
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
function decodeStoredPayload(payloads, conversationId, raw) {
|
|
603
|
-
const expired = InvocationExpiredPayloadSchema.safeParse(raw);
|
|
604
|
-
if (expired.success) {
|
|
605
|
-
return ModelInvocationPayloadReadSchema2.parse({
|
|
606
|
-
status: "expired",
|
|
607
|
-
artifactId: expired.data.artifactId,
|
|
608
|
-
sha256: expired.data.sha256,
|
|
609
|
-
bytes: expired.data.bytes,
|
|
610
|
-
expiredAt: expired.data.expiredAt
|
|
611
|
-
});
|
|
612
|
-
}
|
|
613
|
-
const live = InvocationPayloadSchema.parse(raw);
|
|
614
|
-
const payload = payloads.decrypt(conversationId, live);
|
|
615
|
-
return ModelInvocationPayloadReadSchema2.parse({
|
|
616
|
-
status: "available",
|
|
617
|
-
artifactId: live.artifactId,
|
|
618
|
-
sha256: live.sha256,
|
|
619
|
-
bytes: live.bytes,
|
|
620
|
-
payload
|
|
621
|
-
});
|
|
622
|
-
}
|
|
623
|
-
async function readInvocationPayload(store, payloads, input) {
|
|
624
|
-
const keyed = await store.findEventOnce?.({
|
|
625
|
-
conversationId: input.conversationId,
|
|
626
|
-
kind: "provider/payload",
|
|
627
|
-
key: input.artifactId
|
|
628
|
-
});
|
|
629
|
-
if (keyed)
|
|
630
|
-
return decodeStoredPayload(payloads, input.conversationId, keyed.payload);
|
|
631
|
-
let fromSeq;
|
|
632
|
-
do {
|
|
633
|
-
const page = await store.readEvents({
|
|
634
|
-
conversationId: input.conversationId,
|
|
635
|
-
fromSeq,
|
|
636
|
-
limit: 1000
|
|
637
|
-
});
|
|
638
|
-
for (const event of page.items) {
|
|
639
|
-
if (event.kind !== "provider/payload")
|
|
640
|
-
continue;
|
|
641
|
-
const stored = InvocationStoredPayloadSchema.parse(event.payload);
|
|
642
|
-
if (stored.artifactId === input.artifactId) {
|
|
643
|
-
return decodeStoredPayload(payloads, input.conversationId, stored);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
fromSeq = page.nextSeq;
|
|
647
|
-
} while (fromSeq !== undefined);
|
|
648
|
-
throw new Error("Invocation artifact not found");
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
// src/agent-runtime/invocations.ts
|
|
652
|
-
var executingProcess = { instanceId: randomUUID(), pid: process.pid, hostname: hostname() };
|
|
653
|
-
var agentBindings = new WeakMap;
|
|
654
|
-
function beginAgentInvocation(ledger, store, input, context) {
|
|
655
|
-
const binding = agentBindings.get(ledger);
|
|
656
|
-
if (!binding || binding.store !== store)
|
|
657
|
-
throw new TypeError("Agent and invocations must share the same store");
|
|
658
|
-
return binding.start(input, context);
|
|
659
|
-
}
|
|
660
|
-
function withReceipt(result, writer) {
|
|
661
|
-
const [receiptError] = writer.receiptErrors;
|
|
662
|
-
return receiptError === undefined ? result : { ...result, receiptError };
|
|
663
|
-
}
|
|
664
|
-
async function generateWithFallback(models, writer, input, abortSignal) {
|
|
665
|
-
for (const [step, key] of input.models.entries()) {
|
|
666
|
-
abortSignal.throwIfAborted();
|
|
667
|
-
const selected = models.resolve(key);
|
|
668
|
-
try {
|
|
669
|
-
const result = await generateText({
|
|
670
|
-
model: wrapInvocationModel(writer, selected, step),
|
|
671
|
-
prompt: input.prompt,
|
|
672
|
-
...input.settings,
|
|
673
|
-
maxRetries: 0,
|
|
674
|
-
abortSignal
|
|
675
|
-
});
|
|
676
|
-
return result.text;
|
|
677
|
-
} catch (error) {
|
|
678
|
-
if (!hasProviderOrigin(error) || abortSignal.aborted || step === input.models.length - 1)
|
|
679
|
-
throw error;
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
throw new Error("No completion model attempt available");
|
|
683
|
-
}
|
|
684
|
-
function finishInvocation(writer, status, failure) {
|
|
685
|
-
return writer.append({
|
|
686
|
-
...writer.identity,
|
|
687
|
-
type: "invocation/finished",
|
|
688
|
-
status,
|
|
689
|
-
...failure && { failure }
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
async function runCompletion(config, payloads, writer, input, signal) {
|
|
693
|
-
const invocationId = writer.identity.invocationId;
|
|
694
|
-
const deadline = AbortSignal.timeout(input.timeoutMs);
|
|
695
|
-
const { signal: abortSignal, release } = linkAbortSignals(signal, deadline);
|
|
696
|
-
let text;
|
|
697
|
-
try {
|
|
698
|
-
text = await generateWithFallback(config.models, writer, input, abortSignal);
|
|
699
|
-
} catch (error) {
|
|
700
|
-
const status = abortSignal.aborted ? "cancelled" : "failed";
|
|
701
|
-
release();
|
|
702
|
-
try {
|
|
703
|
-
const artifact = await payloads.write(writer.identity, { error });
|
|
704
|
-
await finishInvocation(writer, status, {
|
|
705
|
-
artifactId: artifact.artifactId,
|
|
706
|
-
payloadSha256: artifact.sha256
|
|
707
|
-
});
|
|
708
|
-
} catch (receiptError) {
|
|
709
|
-
writer.receiptErrors.push(receiptError);
|
|
710
|
-
await finishInvocation(writer, status).catch((appendError) => {
|
|
711
|
-
writer.receiptErrors.push(appendError);
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
return withReceipt({ invocationId, outcome: status }, writer);
|
|
715
|
-
}
|
|
716
|
-
release();
|
|
717
|
-
try {
|
|
718
|
-
await finishInvocation(writer, "succeeded");
|
|
719
|
-
} catch (receiptError) {
|
|
720
|
-
writer.receiptErrors.push(receiptError);
|
|
721
|
-
}
|
|
722
|
-
return withReceipt({ invocationId, outcome: "succeeded", text }, writer);
|
|
723
|
-
}
|
|
724
|
-
function createModelInvocationLedger2(config) {
|
|
725
|
-
const { store } = config;
|
|
726
|
-
const appendOnce = store.appendEventOnce?.bind(store);
|
|
727
|
-
if (!appendOnce)
|
|
728
|
-
throw new TypeError("Model invocations require atomic store.appendEventOnce");
|
|
729
|
-
const maxPayloadBytes = z2.int().min(1024).max(64 * 1024 * 1024).parse(config.maxPayloadBytes ?? 4 * 1024 * 1024);
|
|
730
|
-
const payloads = createInvocationPayloads(store, config.payloadKey, maxPayloadBytes);
|
|
731
|
-
const authorize = async (input) => InvocationCallerSchema.parse(await config.authorize(input));
|
|
732
|
-
const start = async (input) => {
|
|
733
|
-
const trace = ModelInvocationTraceSchema2.parse(input.trace);
|
|
734
|
-
const caller = await authorize({
|
|
735
|
-
context: input.context,
|
|
736
|
-
conversationId: input.conversationId,
|
|
737
|
-
action: input.mode === "completion" ? "complete" : "agent",
|
|
738
|
-
trace
|
|
739
|
-
});
|
|
740
|
-
const fingerprint = invocationHash({
|
|
741
|
-
mode: input.mode,
|
|
742
|
-
caller,
|
|
743
|
-
trace,
|
|
744
|
-
requested: input.requested
|
|
745
|
-
});
|
|
746
|
-
const identity = {
|
|
747
|
-
conversationId: input.conversationId,
|
|
748
|
-
invocationId: randomUUID(),
|
|
749
|
-
operationId: trace.operationId,
|
|
750
|
-
...input.runId && { runId: input.runId }
|
|
751
|
-
};
|
|
752
|
-
const started = InvocationStartedSchema.parse({
|
|
753
|
-
...identity,
|
|
754
|
-
type: "invocation/started",
|
|
755
|
-
mode: input.mode,
|
|
756
|
-
trace,
|
|
757
|
-
caller,
|
|
758
|
-
executingProcess,
|
|
759
|
-
fingerprint,
|
|
760
|
-
requested: { models: input.models, payloadSha256: invocationHash(input.requested) }
|
|
761
|
-
});
|
|
762
|
-
const admission = await appendOnce({ conversationId: input.conversationId, kind: "invocation/started", payload: started }, input.key);
|
|
763
|
-
const previous = InvocationStartedSchema.parse(admission.event.payload);
|
|
764
|
-
if (previous.fingerprint !== fingerprint)
|
|
765
|
-
throw new Error("Invocation idempotency key conflicts with an existing request");
|
|
766
|
-
const writer = {
|
|
767
|
-
identity: { ...identity, invocationId: previous.invocationId },
|
|
768
|
-
process: executingProcess,
|
|
769
|
-
payloads,
|
|
770
|
-
onAttempt: config.onAttempt,
|
|
771
|
-
receiptErrors: [],
|
|
772
|
-
async append(record) {
|
|
773
|
-
const parsed = ModelInvocationRecordSchema2.parse(record);
|
|
774
|
-
await store.appendEvent({
|
|
775
|
-
conversationId: input.conversationId,
|
|
776
|
-
kind: parsed.type,
|
|
777
|
-
payload: parsed
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
};
|
|
781
|
-
return { writer, duplicate: admission.outcome === "duplicate" };
|
|
782
|
-
};
|
|
783
|
-
const ledger = {
|
|
784
|
-
async complete(rawInput, context, signal) {
|
|
785
|
-
const input = CompletionInvocationInputSchema2.parse(rawInput);
|
|
786
|
-
const { writer, duplicate } = await start({
|
|
787
|
-
conversationId: input.conversationId,
|
|
788
|
-
key: `completion:${input.idempotencyKey}`,
|
|
789
|
-
trace: input.trace,
|
|
790
|
-
mode: "completion",
|
|
791
|
-
context,
|
|
792
|
-
requested: input,
|
|
793
|
-
models: input.models
|
|
794
|
-
});
|
|
795
|
-
if (duplicate)
|
|
796
|
-
return { invocationId: writer.identity.invocationId, outcome: "duplicate" };
|
|
797
|
-
return runCompletion(config, payloads, writer, input, signal);
|
|
798
|
-
},
|
|
799
|
-
async read(rawInput, context) {
|
|
800
|
-
const input = InvocationReadInputSchema.parse(rawInput);
|
|
801
|
-
await authorize({ context, conversationId: input.conversationId, action: "read" });
|
|
802
|
-
return readInvocationRecords(store, input);
|
|
803
|
-
},
|
|
804
|
-
async readPayload(input, context) {
|
|
805
|
-
await authorize({
|
|
806
|
-
context,
|
|
807
|
-
conversationId: input.conversationId,
|
|
808
|
-
action: "read-payload"
|
|
809
|
-
});
|
|
810
|
-
return readInvocationPayload(store, payloads, input);
|
|
811
|
-
},
|
|
812
|
-
async purgePayloads(rawInput, context) {
|
|
813
|
-
const input = PurgeInvocationPayloadsInputSchema2.parse(rawInput);
|
|
814
|
-
await authorize({
|
|
815
|
-
context,
|
|
816
|
-
...input.conversationId !== undefined && { conversationId: input.conversationId },
|
|
817
|
-
action: "purge-payloads"
|
|
818
|
-
});
|
|
819
|
-
if (!store.purgeExpiredPayloads) {
|
|
820
|
-
throw new TypeError("Model invocation payload purge requires store.purgeExpiredPayloads");
|
|
821
|
-
}
|
|
822
|
-
return store.purgeExpiredPayloads(input);
|
|
823
|
-
}
|
|
824
|
-
};
|
|
825
|
-
agentBindings.set(ledger, {
|
|
826
|
-
store,
|
|
827
|
-
async start(input, context) {
|
|
828
|
-
const { conversationId, id: runId } = input.run;
|
|
829
|
-
const view = await store.loadRun({ conversationId, runId });
|
|
830
|
-
if (view?.run.state !== "running" || view.run.ownerId !== input.run.ownerId || view.run.fencingToken !== input.run.fencingToken) {
|
|
831
|
-
throw new Error("Invocation requires an owned running agent run");
|
|
832
|
-
}
|
|
833
|
-
const { writer } = await start({
|
|
834
|
-
conversationId,
|
|
835
|
-
runId,
|
|
836
|
-
trace: input.trace,
|
|
837
|
-
key: `agent:${runId}`,
|
|
838
|
-
context,
|
|
839
|
-
mode: "agent",
|
|
840
|
-
models: [],
|
|
841
|
-
requested: { runId }
|
|
842
|
-
});
|
|
843
|
-
return {
|
|
844
|
-
wrap: (selected, step, override) => wrapInvocationModel(writer, selected, step, override),
|
|
845
|
-
finish: (status) => finishInvocation(writer, status)
|
|
846
|
-
};
|
|
847
|
-
}
|
|
848
|
-
});
|
|
849
|
-
return ledger;
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
// src/agent-runtime/managed-tools.ts
|
|
853
|
-
async function assertFence(config, input) {
|
|
854
|
-
const rejected = await config.assertCurrent(input);
|
|
855
|
-
if (rejected)
|
|
856
|
-
throw new ToolExecutionControlError2(rejected);
|
|
857
|
-
}
|
|
858
|
-
function createAgentToolFenceLifecycle2(config) {
|
|
859
|
-
const callContext = (ctx, endpoint) => ({
|
|
860
|
-
runId: config.runId,
|
|
861
|
-
...config.context?.(ctx, endpoint)
|
|
862
|
-
});
|
|
863
|
-
return {
|
|
864
|
-
async beforeHandle(ctx, endpoint) {
|
|
865
|
-
await assertFence(config, callContext(ctx, endpoint));
|
|
866
|
-
},
|
|
867
|
-
async afterHandle(ctx, result, endpoint) {
|
|
868
|
-
const current = callContext(ctx, endpoint);
|
|
869
|
-
await assertFence(config, current);
|
|
870
|
-
await config.onSettled?.(current);
|
|
871
|
-
return result;
|
|
872
|
-
}
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
// src/agent-runtime/prompt.ts
|
|
877
|
-
import { z as z3 } from "zod";
|
|
878
|
-
var AgentTokenCountSchema2 = z3.object({
|
|
879
|
-
value: z3.int().nonnegative().optional(),
|
|
880
|
-
provenance: AgentProvenanceSchema2.extract([
|
|
881
|
-
"measured",
|
|
882
|
-
"computed",
|
|
883
|
-
"estimated",
|
|
884
|
-
"unavailable"
|
|
885
|
-
])
|
|
886
|
-
});
|
|
887
|
-
function budgetTurns(messages, evidencePolicy) {
|
|
888
|
-
const turns = [];
|
|
889
|
-
let current = [];
|
|
890
|
-
const flush = () => {
|
|
891
|
-
if (current.length === 0)
|
|
892
|
-
return;
|
|
893
|
-
turns.push({
|
|
894
|
-
messages: current,
|
|
895
|
-
complete: isCompleteAgentHistoryTurn(current, evidencePolicy),
|
|
896
|
-
protectedSystem: false
|
|
897
|
-
});
|
|
898
|
-
current = [];
|
|
899
|
-
};
|
|
900
|
-
for (const message of messages) {
|
|
901
|
-
if (message.role === "system" || message.role === "summary") {
|
|
902
|
-
flush();
|
|
903
|
-
turns.push({ messages: [message], complete: true, protectedSystem: true });
|
|
904
|
-
continue;
|
|
905
|
-
}
|
|
906
|
-
if (message.role === "user")
|
|
907
|
-
flush();
|
|
908
|
-
current.push(message);
|
|
909
|
-
}
|
|
910
|
-
flush();
|
|
911
|
-
return turns;
|
|
912
|
-
}
|
|
913
|
-
async function selectAgentHistory2(options) {
|
|
914
|
-
if (!Number.isSafeInteger(options.availableTokens) || options.availableTokens < 0) {
|
|
915
|
-
throw new TypeError("availableTokens must be a non-negative safe integer");
|
|
916
|
-
}
|
|
917
|
-
const keepRecentTurns = options.keepRecentTurns ?? 1;
|
|
918
|
-
if (!Number.isSafeInteger(keepRecentTurns) || keepRecentTurns < 0) {
|
|
919
|
-
throw new TypeError("keepRecentTurns must be a non-negative safe integer");
|
|
920
|
-
}
|
|
921
|
-
const spoken = options.messages.filter((message) => message.role !== "assistant" || isAssistantHistoryEvidence2(message.status, options.evidencePolicy));
|
|
922
|
-
const counts = new Map;
|
|
923
|
-
let total = 0;
|
|
924
|
-
let estimated = false;
|
|
925
|
-
for (const message of spoken) {
|
|
926
|
-
const count = AgentTokenCountSchema2.parse(await options.estimateMessage(message));
|
|
927
|
-
counts.set(message.id, count);
|
|
928
|
-
const value = knownValue(count);
|
|
929
|
-
if (value === undefined) {
|
|
930
|
-
return {
|
|
931
|
-
messages: [...spoken],
|
|
932
|
-
decisions: options.messages.map((candidate) => ({
|
|
933
|
-
messageId: candidate.id,
|
|
934
|
-
action: candidate.role === "assistant" && !isAssistantHistoryEvidence2(candidate.status, options.evidencePolicy) ? "removed" : "kept",
|
|
935
|
-
reason: candidate.role === "assistant" && !isAssistantHistoryEvidence2(candidate.status, options.evidencePolicy) ? "unspeakable" : "token-count-unavailable",
|
|
936
|
-
tokens: counts.get(candidate.id) ?? { provenance: "unavailable" }
|
|
937
|
-
})),
|
|
938
|
-
totalTokens: { provenance: "unavailable" },
|
|
939
|
-
outcome: "unavailable"
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
total += value;
|
|
943
|
-
if (count.provenance === "estimated")
|
|
944
|
-
estimated = true;
|
|
945
|
-
}
|
|
946
|
-
const turns = budgetTurns(spoken, options.evidencePolicy);
|
|
947
|
-
const completeIndexes = turns.map((turn, index) => ({ turn, index })).filter(({ turn }) => turn.complete && !turn.protectedSystem).map(({ index }) => index);
|
|
948
|
-
const protectedRecent = new Set(completeIndexes.slice(-keepRecentTurns));
|
|
949
|
-
const removed = new Set;
|
|
950
|
-
for (let index = 0;index < turns.length && total > options.availableTokens; index += 1) {
|
|
951
|
-
const turn = turns[index];
|
|
952
|
-
if (!turn || turn.protectedSystem || !turn.complete || protectedRecent.has(index))
|
|
953
|
-
continue;
|
|
954
|
-
for (const message of turn.messages) {
|
|
955
|
-
removed.add(message.id);
|
|
956
|
-
total -= knownValue(counts.get(message.id) ?? { provenance: "unavailable" }) ?? 0;
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
const messages = spoken.filter((message) => !removed.has(message.id));
|
|
960
|
-
const decisions = options.messages.map((message) => {
|
|
961
|
-
if (message.role === "assistant" && !isAssistantHistoryEvidence2(message.status, options.evidencePolicy)) {
|
|
962
|
-
return {
|
|
963
|
-
messageId: message.id,
|
|
964
|
-
action: "removed",
|
|
965
|
-
reason: "unspeakable",
|
|
966
|
-
tokens: { provenance: "unavailable" }
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
const turnIndex = turns.findIndex((turn) => turn.messages.some((item) => item.id === message.id));
|
|
970
|
-
const turn = turns[turnIndex];
|
|
971
|
-
let reason = "within-budget";
|
|
972
|
-
if (removed.has(message.id))
|
|
973
|
-
reason = "oldest-eligible-turn";
|
|
974
|
-
else if (turn?.protectedSystem)
|
|
975
|
-
reason = "protected-system";
|
|
976
|
-
else if (turn && !turn.complete)
|
|
977
|
-
reason = "protected-incomplete-turn";
|
|
978
|
-
else if (protectedRecent.has(turnIndex))
|
|
979
|
-
reason = "protected-recent-turn";
|
|
980
|
-
return {
|
|
981
|
-
messageId: message.id,
|
|
982
|
-
action: removed.has(message.id) ? "removed" : "kept",
|
|
983
|
-
reason,
|
|
984
|
-
tokens: counts.get(message.id) ?? { provenance: "unavailable" }
|
|
985
|
-
};
|
|
986
|
-
});
|
|
987
|
-
return {
|
|
988
|
-
messages,
|
|
989
|
-
decisions,
|
|
990
|
-
totalTokens: { value: total, provenance: estimated ? "estimated" : "computed" },
|
|
991
|
-
outcome: total > options.availableTokens ? "oversized" : removed.size > 0 ? "truncated" : "fits"
|
|
992
|
-
};
|
|
993
|
-
}
|
|
994
|
-
function knownValue(value) {
|
|
995
|
-
return value.provenance === "unavailable" ? undefined : value.value;
|
|
996
|
-
}
|
|
997
|
-
function composeAgentPrompt2(sections) {
|
|
998
|
-
return async (options) => {
|
|
999
|
-
const event = z3.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
|
|
1000
|
-
const rendered = [];
|
|
1001
|
-
let systemTotal = 0;
|
|
1002
|
-
let userTotal = 0;
|
|
1003
|
-
let systemUnavailable = false;
|
|
1004
|
-
let userUnavailable = false;
|
|
1005
|
-
let systemEstimated = false;
|
|
1006
|
-
let userEstimated = false;
|
|
1007
|
-
for (const section of sections) {
|
|
1008
|
-
const role = section.role ?? "system";
|
|
1009
|
-
const text = await section.render({
|
|
1010
|
-
context: options.context,
|
|
1011
|
-
signal: options.signal,
|
|
1012
|
-
event
|
|
1013
|
-
});
|
|
1014
|
-
rendered.push({ name: section.name, stability: section.stability, role, text });
|
|
1015
|
-
let count;
|
|
1016
|
-
if (section.estimateTokens) {
|
|
1017
|
-
count = AgentTokenCountSchema2.parse(await section.estimateTokens(text));
|
|
1018
|
-
} else if (options.estimateFallback) {
|
|
1019
|
-
count = AgentTokenCountSchema2.parse(await options.estimateFallback(text));
|
|
1020
|
-
} else
|
|
1021
|
-
count = { provenance: "unavailable" };
|
|
1022
|
-
const value = knownValue(count);
|
|
1023
|
-
if (role === "user") {
|
|
1024
|
-
if (value === undefined)
|
|
1025
|
-
userUnavailable = true;
|
|
1026
|
-
else
|
|
1027
|
-
userTotal += value;
|
|
1028
|
-
if (count.provenance === "estimated")
|
|
1029
|
-
userEstimated = true;
|
|
1030
|
-
} else {
|
|
1031
|
-
if (value === undefined)
|
|
1032
|
-
systemUnavailable = true;
|
|
1033
|
-
else
|
|
1034
|
-
systemTotal += value;
|
|
1035
|
-
if (count.provenance === "estimated")
|
|
1036
|
-
systemEstimated = true;
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
const instructionTokens = systemUnavailable ? { provenance: "unavailable" } : { value: systemTotal, provenance: systemEstimated ? "estimated" : "computed" };
|
|
1040
|
-
const userInstructionTokens = userUnavailable ? { provenance: "unavailable" } : { value: userTotal, provenance: userEstimated ? "estimated" : "computed" };
|
|
1041
|
-
let availableHistoryTokens;
|
|
1042
|
-
let contextDecision = "unavailable";
|
|
1043
|
-
if (options.budget) {
|
|
1044
|
-
if (!Number.isSafeInteger(options.budget.contextWindow) || options.budget.contextWindow < 0 || !Number.isSafeInteger(options.budget.reservedOutput) || options.budget.reservedOutput < 0) {
|
|
1045
|
-
throw new TypeError("contextWindow and reservedOutput must be non-negative safe integers");
|
|
1046
|
-
}
|
|
1047
|
-
const reserveValues = [
|
|
1048
|
-
options.budget.reservedOutput,
|
|
1049
|
-
knownValue(AgentTokenCountSchema2.parse(options.budget.toolSchemas)),
|
|
1050
|
-
knownValue(AgentTokenCountSchema2.parse(options.budget.attachments)),
|
|
1051
|
-
knownValue(AgentTokenCountSchema2.parse(options.budget.providerOverhead)),
|
|
1052
|
-
knownValue(instructionTokens)
|
|
1053
|
-
];
|
|
1054
|
-
if (reserveValues.every((value) => value !== undefined)) {
|
|
1055
|
-
availableHistoryTokens = options.budget.contextWindow - reserveValues.reduce((sum, value) => sum + (value ?? 0), 0);
|
|
1056
|
-
const historyTokens = options.historyTokens ? knownValue(AgentTokenCountSchema2.parse(options.historyTokens)) : undefined;
|
|
1057
|
-
if (historyTokens !== undefined) {
|
|
1058
|
-
if (availableHistoryTokens < 0)
|
|
1059
|
-
contextDecision = "oversized";
|
|
1060
|
-
else if (historyTokens <= availableHistoryTokens)
|
|
1061
|
-
contextDecision = "fits";
|
|
1062
|
-
else
|
|
1063
|
-
contextDecision = options.oversizePolicy === "compact" ? "requires-compaction" : "oversized";
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
const instructionText = rendered.filter((section) => section.role === "system").map((section) => section.text).join(`
|
|
1068
|
-
|
|
1069
|
-
`);
|
|
1070
|
-
const userInstructions = rendered.filter((section) => section.role === "user" && section.text.trim().length > 0).map((section) => ({ name: section.name, text: section.text }));
|
|
1071
|
-
return {
|
|
1072
|
-
instructions: options.adaptInstructions ? await options.adaptInstructions(instructionText) : instructionText,
|
|
1073
|
-
sections: rendered,
|
|
1074
|
-
userInstructions,
|
|
1075
|
-
instructionTokens,
|
|
1076
|
-
userInstructionTokens,
|
|
1077
|
-
finalizeSeed: (inserted) => {
|
|
1078
|
-
const seedTokens = inserted ? knownValue(userInstructionTokens) : 0;
|
|
1079
|
-
if (availableHistoryTokens === undefined || seedTokens === undefined)
|
|
1080
|
-
return { contextDecision: "unavailable" };
|
|
1081
|
-
const available = availableHistoryTokens - seedTokens;
|
|
1082
|
-
const history = options.historyTokens ? knownValue(options.historyTokens) : undefined;
|
|
1083
|
-
const decision = history === undefined ? "unavailable" : available < 0 ? "oversized" : history <= available ? "fits" : options.oversizePolicy === "compact" ? "requires-compaction" : "oversized";
|
|
1084
|
-
return { availableHistoryTokens: available, contextDecision: decision };
|
|
1085
|
-
},
|
|
1086
|
-
contextDecision,
|
|
1087
|
-
...availableHistoryTokens !== undefined && { availableHistoryTokens }
|
|
1088
|
-
};
|
|
1089
|
-
};
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
// src/agent-runtime/provider-failure.ts
|
|
1093
|
-
var BY_STATUS = {
|
|
1094
|
-
402: "insufficient-credits",
|
|
1095
|
-
404: "model-unavailable",
|
|
1096
|
-
408: "timeout",
|
|
1097
|
-
413: "context-overflow",
|
|
1098
|
-
429: "rate-limited"
|
|
1099
|
-
};
|
|
1100
|
-
var BY_MESSAGE = [
|
|
1101
|
-
[/insufficient|not enough credit|payment required|quota exceeded/i, "insufficient-credits"],
|
|
1102
|
-
[/rate.?limit|too many requests|slow down/i, "rate-limited"],
|
|
1103
|
-
[
|
|
1104
|
-
/no endpoints found|model not found|unknown model|no allowed providers/i,
|
|
1105
|
-
"model-unavailable"
|
|
1106
|
-
],
|
|
1107
|
-
[/context length|maximum context|too many tokens|prompt is too long/i, "context-overflow"],
|
|
1108
|
-
[/timed? ?out|deadline exceeded|etimedout/i, "timeout"],
|
|
1109
|
-
[/abort|cancell?ed/i, "cancelled"]
|
|
1110
|
-
];
|
|
1111
|
-
var RETRYABLE = new Set([
|
|
1112
|
-
"rate-limited",
|
|
1113
|
-
"timeout",
|
|
1114
|
-
"insufficient-credits",
|
|
1115
|
-
"stream-cut"
|
|
1116
|
-
]);
|
|
1117
|
-
|
|
1118
|
-
class AgentProviderStreamCutError2 extends Error {
|
|
1119
|
-
reason = "stream-cut";
|
|
1120
|
-
constructor(message = "Provider stream ended before a terminal part") {
|
|
1121
|
-
super(message);
|
|
1122
|
-
this.name = "AgentProviderStreamCutError";
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
function statusOf(value) {
|
|
1126
|
-
if (!isRecord(value))
|
|
1127
|
-
return;
|
|
1128
|
-
for (const key of ["statusCode", "status", "code"]) {
|
|
1129
|
-
const candidate = value[key];
|
|
1130
|
-
if (typeof candidate === "number" && candidate >= 400 && candidate < 600)
|
|
1131
|
-
return candidate;
|
|
1132
|
-
}
|
|
1133
|
-
const nested = value.cause ?? value.response ?? value.error;
|
|
1134
|
-
return nested === value ? undefined : statusOf(nested);
|
|
1135
|
-
}
|
|
1136
|
-
function classifyProviderFailure2(error) {
|
|
1137
|
-
if (error instanceof AgentProviderStreamCutError2) {
|
|
1138
|
-
return { reason: "stream-cut", retryable: true, evidence: "none" };
|
|
1139
|
-
}
|
|
1140
|
-
const status = statusOf(error);
|
|
1141
|
-
const byStatus = status === undefined ? undefined : BY_STATUS[status];
|
|
1142
|
-
if (byStatus) {
|
|
1143
|
-
return {
|
|
1144
|
-
reason: byStatus,
|
|
1145
|
-
status,
|
|
1146
|
-
retryable: RETRYABLE.has(byStatus),
|
|
1147
|
-
evidence: "status"
|
|
1148
|
-
};
|
|
1149
|
-
}
|
|
1150
|
-
const message = messageOf(error);
|
|
1151
|
-
for (const [pattern, reason] of BY_MESSAGE) {
|
|
1152
|
-
if (pattern.test(message)) {
|
|
1153
|
-
return {
|
|
1154
|
-
reason,
|
|
1155
|
-
...status !== undefined && { status },
|
|
1156
|
-
retryable: RETRYABLE.has(reason),
|
|
1157
|
-
evidence: "message"
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
return {
|
|
1162
|
-
reason: "unknown",
|
|
1163
|
-
...status !== undefined && { status },
|
|
1164
|
-
retryable: false,
|
|
1165
|
-
evidence: "none"
|
|
1166
|
-
};
|
|
1167
|
-
}
|
|
1168
|
-
function isToolResultFailure2(output) {
|
|
1169
|
-
const parsed = typeof output === "string" ? parseJson(output) : output;
|
|
1170
|
-
if (!isRecord(parsed))
|
|
1171
|
-
return false;
|
|
1172
|
-
if ("error" in parsed)
|
|
1173
|
-
return true;
|
|
1174
|
-
return isRecord(parsed.value) && "error" in parsed.value;
|
|
1175
|
-
}
|
|
1176
|
-
function parseJson(value) {
|
|
1177
|
-
try {
|
|
1178
|
-
return JSON.parse(value);
|
|
1179
|
-
} catch {
|
|
1180
|
-
return;
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
// src/agent-runtime/retry-policy.ts
|
|
1185
|
-
function assertAgentRetryPolicy(subject, policy) {
|
|
1186
|
-
assertPositiveSafeInteger(`${subject}.maxAttempts`, policy.maxAttempts, TypeError, {
|
|
1187
|
-
absent: "refused"
|
|
1188
|
-
});
|
|
1189
|
-
}
|
|
1190
|
-
async function recordAgentRetryDecision2(input) {
|
|
1191
|
-
assertAgentRetryPolicy("Retry policy", input.policy);
|
|
1192
|
-
const retry = input.failure.retryable && input.attempt < input.policy.maxAttempts;
|
|
1193
|
-
const delayMs = retry ? input.policy.delayMs({ attempt: input.attempt, failure: input.failure }) : 0;
|
|
1194
|
-
assertTimerMs("Retry delayMs", delayMs, { min: 0, absent: "refused" });
|
|
1195
|
-
if (retry) {
|
|
1196
|
-
await input.store.appendEvent({
|
|
1197
|
-
conversationId: input.conversationId,
|
|
1198
|
-
kind: "retry/scheduled",
|
|
1199
|
-
payload: { attempt: input.attempt + 1, delayMs, reason: input.failure.reason }
|
|
1200
|
-
});
|
|
1201
|
-
}
|
|
1202
|
-
return { retry, delayMs };
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
// src/agent-runtime/run-step-barriers.ts
|
|
1206
|
-
class AgentStepBarrierError2 extends Error {
|
|
1207
|
-
bound;
|
|
1208
|
-
constructor(bound, message) {
|
|
1209
|
-
super(message);
|
|
1210
|
-
this.bound = bound;
|
|
1211
|
-
this.name = "AgentStepBarrierError";
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
function assertStepBarriers(barriers) {
|
|
1215
|
-
if (!barriers)
|
|
1216
|
-
return;
|
|
1217
|
-
assertPositiveSafeInteger("stepBarriers.maxToolCallsPerStep", barriers.maxToolCallsPerStep, RangeError);
|
|
1218
|
-
assertPositiveSafeInteger("stepBarriers.maxReasoningCharsPerStep", barriers.maxReasoningCharsPerStep, RangeError);
|
|
1219
|
-
if (barriers.stepText !== undefined && !["immediate", "after-tools"].includes(barriers.stepText))
|
|
1220
|
-
throw new RangeError("stepBarriers.stepText must be 'immediate' or 'after-tools'");
|
|
1221
|
-
}
|
|
1222
|
-
function isAsyncIterable(value) {
|
|
1223
|
-
return value !== null && typeof value === "object" && typeof Reflect.get(value, Symbol.asyncIterator) === "function";
|
|
1224
|
-
}
|
|
1225
|
-
function isAsyncGeneratorFunction(value) {
|
|
1226
|
-
return Object.prototype.toString.call(value) === "[object AsyncGeneratorFunction]";
|
|
1227
|
-
}
|
|
1228
|
-
async function finalOutput(value) {
|
|
1229
|
-
if (!isAsyncIterable(value))
|
|
1230
|
-
return value;
|
|
1231
|
-
let last;
|
|
1232
|
-
for await (const output of value)
|
|
1233
|
-
last = output;
|
|
1234
|
-
return last;
|
|
1235
|
-
}
|
|
1236
|
-
function createStepLedger(barriers) {
|
|
1237
|
-
let current;
|
|
1238
|
-
return (messages, toolCallId, toolName, input) => {
|
|
1239
|
-
if (current === undefined || current.messages !== messages)
|
|
1240
|
-
current = { messages, count: 0, calls: new Map, entities: new Map };
|
|
1241
|
-
const ledger = current;
|
|
1242
|
-
const known = ledger.calls.get(toolCallId);
|
|
1243
|
-
if (known)
|
|
1244
|
-
return known;
|
|
1245
|
-
ledger.count += 1;
|
|
1246
|
-
const limit = barriers.maxToolCallsPerStep;
|
|
1247
|
-
const refused = limit !== undefined && ledger.count > limit;
|
|
1248
|
-
const own = Promise.withResolvers();
|
|
1249
|
-
const dependencies = refused ? undefined : barriers.toolDependencies?.({ toolName, input });
|
|
1250
|
-
const writes = new Set(dependencies?.writes ?? []);
|
|
1251
|
-
const reads = new Set([...dependencies?.reads ?? []].filter((entity) => !writes.has(entity)));
|
|
1252
|
-
const stateOf = (entity) => {
|
|
1253
|
-
const known = ledger.entities.get(entity);
|
|
1254
|
-
if (known)
|
|
1255
|
-
return known;
|
|
1256
|
-
const fresh = { reads: [] };
|
|
1257
|
-
ledger.entities.set(entity, fresh);
|
|
1258
|
-
return fresh;
|
|
1259
|
-
};
|
|
1260
|
-
const ahead = [];
|
|
1261
|
-
for (const entity of reads) {
|
|
1262
|
-
const state = stateOf(entity);
|
|
1263
|
-
if (state.write)
|
|
1264
|
-
ahead.push(state.write);
|
|
1265
|
-
state.reads.push(own.promise);
|
|
1266
|
-
}
|
|
1267
|
-
for (const entity of writes) {
|
|
1268
|
-
const state = stateOf(entity);
|
|
1269
|
-
if (state.write)
|
|
1270
|
-
ahead.push(state.write);
|
|
1271
|
-
ahead.push(...state.reads);
|
|
1272
|
-
state.write = own.promise;
|
|
1273
|
-
state.reads = [];
|
|
1274
|
-
}
|
|
1275
|
-
const entry = { refused, ahead, settle: () => own.resolve() };
|
|
1276
|
-
ledger.calls.set(toolCallId, entry);
|
|
1277
|
-
return entry;
|
|
1278
|
-
};
|
|
1279
|
-
}
|
|
1280
|
-
function isPromiseLike(value) {
|
|
1281
|
-
return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
|
|
1282
|
-
}
|
|
1283
|
-
function settleOnDecision(entry, produce, skipsExecute) {
|
|
1284
|
-
let result;
|
|
1285
|
-
try {
|
|
1286
|
-
result = produce();
|
|
1287
|
-
} catch (error) {
|
|
1288
|
-
entry.settle();
|
|
1289
|
-
throw error;
|
|
1290
|
-
}
|
|
1291
|
-
if (isPromiseLike(result)) {
|
|
1292
|
-
return Promise.resolve(result).then((value) => {
|
|
1293
|
-
if (skipsExecute(value))
|
|
1294
|
-
entry.settle();
|
|
1295
|
-
return value;
|
|
1296
|
-
}, (error) => {
|
|
1297
|
-
entry.settle();
|
|
1298
|
-
throw error;
|
|
1299
|
-
});
|
|
1300
|
-
}
|
|
1301
|
-
if (skipsExecute(result))
|
|
1302
|
-
entry.settle();
|
|
1303
|
-
return result;
|
|
1304
|
-
}
|
|
1305
|
-
function approvalSkipsExecute(decision) {
|
|
1306
|
-
if (decision === undefined)
|
|
1307
|
-
return false;
|
|
1308
|
-
const status = typeof decision === "object" && decision !== null && "type" in decision ? Reflect.get(decision, "type") : decision;
|
|
1309
|
-
return status !== "approved" && status !== "not-applicable";
|
|
1310
|
-
}
|
|
1311
|
-
var callLimitRefusal = (limit) => new AgentToolError2({
|
|
1312
|
-
code: "STEP_TOOL_CALL_LIMIT",
|
|
1313
|
-
message: `Refused: a step may make at most ${limit} tool calls; make the rest in the next step`
|
|
1314
|
-
});
|
|
1315
|
-
function applyStepBarriers(tools, toolApproval, barriers) {
|
|
1316
|
-
if (!barriers || barriers.maxToolCallsPerStep === undefined && !barriers.toolDependencies)
|
|
1317
|
-
return { tools, toolApproval };
|
|
1318
|
-
const enter = createStepLedger(barriers);
|
|
1319
|
-
const limit = barriers.maxToolCallsPerStep;
|
|
1320
|
-
const executableTools = new Set;
|
|
1321
|
-
const wrapped = mapObjectTypeBoundary(tools, (name, tool) => {
|
|
1322
|
-
const toolName = String(name);
|
|
1323
|
-
const execute = tool.execute;
|
|
1324
|
-
if (typeof execute !== "function")
|
|
1325
|
-
return tool;
|
|
1326
|
-
executableTools.add(toolName);
|
|
1327
|
-
const { onInputAvailable, needsApproval } = tool;
|
|
1328
|
-
const settled = (entry, result) => {
|
|
1329
|
-
if (isAsyncIterable(result))
|
|
1330
|
-
return async function* () {
|
|
1331
|
-
try {
|
|
1332
|
-
yield* result;
|
|
1333
|
-
} finally {
|
|
1334
|
-
entry.settle();
|
|
1335
|
-
}
|
|
1336
|
-
}();
|
|
1337
|
-
return Promise.resolve(result).then(finalOutput).finally(entry.settle);
|
|
1338
|
-
};
|
|
1339
|
-
return {
|
|
1340
|
-
...tool,
|
|
1341
|
-
onInputAvailable: async (options) => {
|
|
1342
|
-
const entry = enter(options.messages, options.toolCallId, toolName, options.input);
|
|
1343
|
-
if (!onInputAvailable)
|
|
1344
|
-
return;
|
|
1345
|
-
try {
|
|
1346
|
-
await onInputAvailable.call(tool, options);
|
|
1347
|
-
} catch (error) {
|
|
1348
|
-
entry.settle();
|
|
1349
|
-
throw error;
|
|
1350
|
-
}
|
|
1351
|
-
},
|
|
1352
|
-
...needsApproval !== undefined && {
|
|
1353
|
-
needsApproval: (input, options) => {
|
|
1354
|
-
const entry = enter(options.messages, options.toolCallId, toolName, input);
|
|
1355
|
-
if (entry.refused)
|
|
1356
|
-
return false;
|
|
1357
|
-
return settleOnDecision(entry, () => typeof needsApproval === "function" ? needsApproval.call(tool, input, options) : needsApproval, (value) => Boolean(value));
|
|
1358
|
-
}
|
|
1359
|
-
},
|
|
1360
|
-
execute: (input, options) => {
|
|
1361
|
-
const entry = enter(options.messages, options.toolCallId, toolName, input);
|
|
1362
|
-
if (entry.refused) {
|
|
1363
|
-
entry.settle();
|
|
1364
|
-
throw callLimitRefusal(limit);
|
|
1365
|
-
}
|
|
1366
|
-
if (entry.ahead.length === 0) {
|
|
1367
|
-
try {
|
|
1368
|
-
return settled(entry, execute.call(tool, input, options));
|
|
1369
|
-
} catch (error) {
|
|
1370
|
-
entry.settle();
|
|
1371
|
-
throw error;
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
const waitAhead = () => {
|
|
1375
|
-
const all = Promise.all(entry.ahead);
|
|
1376
|
-
return options.abortSignal ? raceAbort(all, options.abortSignal) : all;
|
|
1377
|
-
};
|
|
1378
|
-
const start = () => waitAhead().then(() => execute.call(tool, input, options));
|
|
1379
|
-
if (isAsyncGeneratorFunction(execute))
|
|
1380
|
-
return async function* () {
|
|
1381
|
-
try {
|
|
1382
|
-
const result = await start();
|
|
1383
|
-
if (isAsyncIterable(result))
|
|
1384
|
-
yield* result;
|
|
1385
|
-
} finally {
|
|
1386
|
-
entry.settle();
|
|
1387
|
-
}
|
|
1388
|
-
}();
|
|
1389
|
-
return Promise.resolve().then(start).then(finalOutput).finally(entry.settle);
|
|
1390
|
-
}
|
|
1391
|
-
};
|
|
1392
|
-
});
|
|
1393
|
-
carryDeferredToolCatalog(tools, wrapped);
|
|
1394
|
-
return { tools: wrapped, toolApproval: boundApproval(toolApproval, enter, executableTools) };
|
|
1395
|
-
}
|
|
1396
|
-
function boundApproval(approval, enter, executableTools) {
|
|
1397
|
-
if (approval === undefined)
|
|
1398
|
-
return;
|
|
1399
|
-
if (typeof approval === "function")
|
|
1400
|
-
return (options) => {
|
|
1401
|
-
if (!executableTools.has(options.toolCall.toolName) || options.toolCall.providerExecuted === true) {
|
|
1402
|
-
return approval(options);
|
|
1403
|
-
}
|
|
1404
|
-
const entry = enter(options.messages, options.toolCall.toolCallId, options.toolCall.toolName, options.toolCall.input);
|
|
1405
|
-
if (entry.refused)
|
|
1406
|
-
return "not-applicable";
|
|
1407
|
-
return settleOnDecision(entry, () => approval(options), approvalSkipsExecute);
|
|
1408
|
-
};
|
|
1409
|
-
return mapObjectTypeBoundary(approval, (name, decide) => {
|
|
1410
|
-
const toolName = String(name);
|
|
1411
|
-
if (!executableTools.has(toolName) || decide === undefined)
|
|
1412
|
-
return decide;
|
|
1413
|
-
return (input, options) => {
|
|
1414
|
-
const entry = enter(options.messages, options.toolCallId, toolName, input);
|
|
1415
|
-
if (entry.refused)
|
|
1416
|
-
return "not-applicable";
|
|
1417
|
-
return settleOnDecision(entry, () => typeof decide === "function" ? Reflect.apply(decide, undefined, [input, options]) : decide, approvalSkipsExecute);
|
|
1418
|
-
};
|
|
1419
|
-
});
|
|
1420
|
-
}
|
|
1421
|
-
function createToolDependencyResolver2(input) {
|
|
1422
|
-
const effects = new Map;
|
|
1423
|
-
for (const contract of input.contracts ?? []) {
|
|
1424
|
-
const byEndpoint = contractOperationEffects2(contract);
|
|
1425
|
-
for (const entry of listContractToolNames2([contract])) {
|
|
1426
|
-
const effect = byEndpoint[entry.method];
|
|
1427
|
-
if (effect !== undefined)
|
|
1428
|
-
effects.set(entry.name, effect);
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
for (const [toolName, effect] of Object.entries(input.effects ?? {})) {
|
|
1432
|
-
if (effects.has(toolName))
|
|
1433
|
-
throw new RangeError(`Tool "${toolName}" already has the effect of its contract endpoint`);
|
|
1434
|
-
effects.set(toolName, effect);
|
|
1435
|
-
}
|
|
1436
|
-
return ({ toolName, input: callInput }) => {
|
|
1437
|
-
const effect = effects.get(toolName);
|
|
1438
|
-
const entity = effect && input.entityOf(toolName, callInput);
|
|
1439
|
-
if (entity === undefined || effect === undefined)
|
|
1440
|
-
return;
|
|
1441
|
-
return effect === "write" ? { writes: [entity] } : { reads: [entity] };
|
|
1442
|
-
};
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
// src/agent-runtime/runtime-control.ts
|
|
1446
|
-
async function interruptAgentRun(state, input) {
|
|
1447
|
-
const { store } = state.config;
|
|
1448
|
-
const view = await store.loadRun({
|
|
1449
|
-
conversationId: input.conversationId,
|
|
1450
|
-
runId: input.runId
|
|
1451
|
-
});
|
|
1452
|
-
if (!view)
|
|
1453
|
-
throw new AgentRuntimeConflictError2("run lookup");
|
|
1454
|
-
const requested = await store.requestRunInterrupt({
|
|
1455
|
-
conversationId: input.conversationId,
|
|
1456
|
-
runId: input.runId,
|
|
1457
|
-
expectedRevision: view.run.revision
|
|
1458
|
-
});
|
|
1459
|
-
if (requested.outcome === "applied") {
|
|
1460
|
-
const interruptedRun = findRun(requested.snapshot.runs, input.runId);
|
|
1461
|
-
await state.publish({
|
|
1462
|
-
type: "run-state",
|
|
1463
|
-
eventId: agentDurableEventId2("run-state", interruptedRun.id, requested.snapshot.version),
|
|
1464
|
-
conversationId: interruptedRun.conversationId,
|
|
1465
|
-
runId: interruptedRun.id,
|
|
1466
|
-
snapshotVersion: requested.snapshot.version,
|
|
1467
|
-
state: interruptedRun.state,
|
|
1468
|
-
emittedAt: state.now().toISOString()
|
|
1469
|
-
});
|
|
1470
|
-
state.coordinator.stop(input.conversationKey ?? input.conversationId, "user-interrupt");
|
|
1471
|
-
}
|
|
1472
|
-
return requested;
|
|
1473
|
-
}
|
|
1474
|
-
async function abandonAgentRun(state, input) {
|
|
1475
|
-
if (input.staleOwner !== true) {
|
|
1476
|
-
throw new TypeError("Abandoning a run requires explicit staleOwner evidence");
|
|
1477
|
-
}
|
|
1478
|
-
const releaseAdmission = state.gate.begin();
|
|
1479
|
-
try {
|
|
1480
|
-
const abandoned = await state.config.store.recoverRun({
|
|
1481
|
-
conversationId: input.conversationId,
|
|
1482
|
-
runId: input.runId,
|
|
1483
|
-
expectedRevision: input.expectedRevision,
|
|
1484
|
-
action: "abandon"
|
|
1485
|
-
});
|
|
1486
|
-
if (abandoned.outcome === "applied") {
|
|
1487
|
-
const abandonedRun = findRun(abandoned.snapshot.runs, input.runId);
|
|
1488
|
-
await state.publish({
|
|
1489
|
-
type: "run-state",
|
|
1490
|
-
eventId: agentDurableEventId2("run-state", abandonedRun.id, abandoned.snapshot.version),
|
|
1491
|
-
conversationId: abandonedRun.conversationId,
|
|
1492
|
-
runId: abandonedRun.id,
|
|
1493
|
-
snapshotVersion: abandoned.snapshot.version,
|
|
1494
|
-
state: abandonedRun.state,
|
|
1495
|
-
emittedAt: state.now().toISOString()
|
|
1496
|
-
});
|
|
1497
|
-
}
|
|
1498
|
-
return abandoned;
|
|
1499
|
-
} finally {
|
|
1500
|
-
releaseAdmission();
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
async function closeAgentRuntime(state, options) {
|
|
1504
|
-
assertCloseBudgets(options);
|
|
1505
|
-
state.gate.closed = true;
|
|
1506
|
-
const startedAt = performance.now();
|
|
1507
|
-
state.injection?.clear();
|
|
1508
|
-
const stranded = await state.gate.drain(options.forceTimeoutMs);
|
|
1509
|
-
const spent = Math.max(0, Math.round(performance.now() - startedAt));
|
|
1510
|
-
const remainingBudget = (value) => value === undefined ? undefined : Math.max(0, value - spent);
|
|
1511
|
-
const grace = remainingBudget(options.gracePeriodMs);
|
|
1512
|
-
const force = remainingBudget(options.forceTimeoutMs);
|
|
1513
|
-
const result = await state.coordinator.close({
|
|
1514
|
-
...grace !== undefined && { gracePeriodMs: grace },
|
|
1515
|
-
...force !== undefined && { forceTimeoutMs: force }
|
|
1516
|
-
});
|
|
1517
|
-
if (stranded === 0)
|
|
1518
|
-
return result;
|
|
1519
|
-
return { settled: false, timedOut: true, remaining: result.remaining + stranded };
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
// src/agent-runtime/runtime-admission-gate.ts
|
|
1523
|
-
var closedError = () => new Error("[stitchkit] agent runtime is closed and admits no further work");
|
|
1524
|
-
function refuse() {
|
|
1525
|
-
const error = closedError();
|
|
1526
|
-
const accepted = Promise.reject(error);
|
|
1527
|
-
const result = Promise.reject(error);
|
|
1528
|
-
accepted.catch(() => {
|
|
1529
|
-
return;
|
|
1530
|
-
});
|
|
1531
|
-
result.catch(() => {
|
|
1532
|
-
return;
|
|
1533
|
-
});
|
|
1534
|
-
return { accepted, result };
|
|
1535
|
-
}
|
|
1536
|
-
function createRuntimeAdmissionGate() {
|
|
1537
|
-
const admissionsInFlight = new Set;
|
|
1538
|
-
const begin = () => {
|
|
1539
|
-
const handoff = Promise.withResolvers();
|
|
1540
|
-
admissionsInFlight.add(handoff);
|
|
1541
|
-
return () => {
|
|
1542
|
-
if (admissionsInFlight.delete(handoff))
|
|
1543
|
-
handoff.resolve();
|
|
1544
|
-
};
|
|
1545
|
-
};
|
|
1546
|
-
const drain = async (budgetMs) => {
|
|
1547
|
-
const pending = [...admissionsInFlight].map((handoff) => handoff.promise);
|
|
1548
|
-
if (pending.length === 0)
|
|
1549
|
-
return 0;
|
|
1550
|
-
let stranded = pending.length;
|
|
1551
|
-
const settled = Promise.all(pending.map((promise) => promise.then(() => {
|
|
1552
|
-
stranded -= 1;
|
|
1553
|
-
})));
|
|
1554
|
-
if (budgetMs === undefined) {
|
|
1555
|
-
await settled;
|
|
1556
|
-
return 0;
|
|
1557
|
-
}
|
|
1558
|
-
await withDeadline(settled, budgetMs);
|
|
1559
|
-
return stranded;
|
|
1560
|
-
};
|
|
1561
|
-
return { closed: false, begin, drain };
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
// src/agent-runtime/runtime-recovery.ts
|
|
1565
|
-
function resumeAgentRun(state, rawInput) {
|
|
1566
|
-
const { config, coordinator } = state;
|
|
1567
|
-
if (state.gate.closed)
|
|
1568
|
-
return refuse();
|
|
1569
|
-
const context = config.protocol.parseContext(rawInput.context);
|
|
1570
|
-
const accepted = Promise.withResolvers();
|
|
1571
|
-
const result = Promise.withResolvers();
|
|
1572
|
-
let acquisitionSettled = false;
|
|
1573
|
-
const resolveAcquisition = () => {
|
|
1574
|
-
acquisitionSettled = true;
|
|
1575
|
-
accepted.resolve();
|
|
1576
|
-
};
|
|
1577
|
-
const rejectAcquisition = (error) => {
|
|
1578
|
-
if (!acquisitionSettled)
|
|
1579
|
-
accepted.reject(error);
|
|
1580
|
-
};
|
|
1581
|
-
const handedOff = state.gate.begin();
|
|
1582
|
-
(async () => {
|
|
1583
|
-
try {
|
|
1584
|
-
const recovered = await config.store.loadRun({
|
|
1585
|
-
conversationId: rawInput.conversationId,
|
|
1586
|
-
runId: rawInput.runId
|
|
1587
|
-
});
|
|
1588
|
-
if (!recovered)
|
|
1589
|
-
throw new AgentRuntimeConflictError2("run lookup");
|
|
1590
|
-
const recoveredRun = recovered.run;
|
|
1591
|
-
if (recoveredRun.state !== "queued") {
|
|
1592
|
-
throw new Error("Only a queued recovered agent run can be resumed");
|
|
1593
|
-
}
|
|
1594
|
-
const ticket = coordinator.submit({
|
|
1595
|
-
key: rawInput.conversationKey ?? rawInput.conversationId,
|
|
1596
|
-
policy: "queue",
|
|
1597
|
-
create: (signal) => ({
|
|
1598
|
-
runId: recoveredRun.id,
|
|
1599
|
-
execute: () => state.executeRun({
|
|
1600
|
-
acceptedRun: recoveredRun,
|
|
1601
|
-
context,
|
|
1602
|
-
signal,
|
|
1603
|
-
key: rawInput.conversationKey ?? rawInput.conversationId,
|
|
1604
|
-
onAcquired: resolveAcquisition
|
|
1605
|
-
})
|
|
1606
|
-
})
|
|
1607
|
-
});
|
|
1608
|
-
ticket.accepted.catch(() => {
|
|
1609
|
-
return;
|
|
1610
|
-
});
|
|
1611
|
-
ticket.result.then(result.resolve, (error) => {
|
|
1612
|
-
rejectAcquisition(error);
|
|
1613
|
-
result.reject(error);
|
|
1614
|
-
});
|
|
1615
|
-
} catch (error) {
|
|
1616
|
-
rejectAcquisition(error);
|
|
1617
|
-
result.reject(error);
|
|
1618
|
-
} finally {
|
|
1619
|
-
handedOff();
|
|
1620
|
-
}
|
|
1621
|
-
})();
|
|
1622
|
-
return { accepted: accepted.promise, result: result.promise };
|
|
1623
|
-
}
|
|
1624
|
-
async function recoverAgentRuns(state, options) {
|
|
1625
|
-
if (state.gate.closed)
|
|
1626
|
-
throw closedError();
|
|
1627
|
-
const pageSize = options.pageSize ?? 100;
|
|
1628
|
-
const maxRuns = options.maxRuns ?? 1000;
|
|
1629
|
-
if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 1000) {
|
|
1630
|
-
throw new TypeError("Recovery pageSize must be an integer between 1 and 1000");
|
|
1631
|
-
}
|
|
1632
|
-
assertPositiveSafeInteger("Recovery maxRuns", maxRuns);
|
|
1633
|
-
const ordered = await collectRecoverable(state, options, pageSize, maxRuns);
|
|
1634
|
-
const outcomes = [];
|
|
1635
|
-
const scheduledRuns = new Map;
|
|
1636
|
-
for (const item of ordered) {
|
|
1637
|
-
if (options.signal?.aborted)
|
|
1638
|
-
break;
|
|
1639
|
-
if (state.gate.closed)
|
|
1640
|
-
break;
|
|
1641
|
-
const releaseAdmission = state.gate.begin();
|
|
1642
|
-
try {
|
|
1643
|
-
outcomes.push(await recoverItem(state, options, item, scheduledRuns));
|
|
1644
|
-
} catch (error) {
|
|
1645
|
-
outcomes.push({
|
|
1646
|
-
conversationId: item.conversationId,
|
|
1647
|
-
runId: item.run.id,
|
|
1648
|
-
outcome: "failed",
|
|
1649
|
-
error
|
|
1650
|
-
});
|
|
1651
|
-
} finally {
|
|
1652
|
-
releaseAdmission();
|
|
1653
|
-
}
|
|
1654
|
-
}
|
|
1655
|
-
return outcomes;
|
|
1656
|
-
}
|
|
1657
|
-
async function collectRecoverable(state, options, pageSize, maxRuns) {
|
|
1658
|
-
const { store } = state.config;
|
|
1659
|
-
const recoverable = [];
|
|
1660
|
-
let cursor;
|
|
1661
|
-
while (recoverable.length < maxRuns && !options.signal?.aborted && !state.gate.closed) {
|
|
1662
|
-
const page = await store.scanRecoverable({
|
|
1663
|
-
...cursor && { cursor },
|
|
1664
|
-
limit: Math.min(pageSize, maxRuns - recoverable.length)
|
|
1665
|
-
});
|
|
1666
|
-
recoverable.push(...page.items);
|
|
1667
|
-
cursor = page.nextCursor;
|
|
1668
|
-
if (!cursor || page.items.length === 0)
|
|
1669
|
-
break;
|
|
1670
|
-
}
|
|
1671
|
-
const grouped = new Map;
|
|
1672
|
-
for (const item of recoverable) {
|
|
1673
|
-
const items = grouped.get(item.conversationId) ?? [];
|
|
1674
|
-
items.push(item);
|
|
1675
|
-
grouped.set(item.conversationId, items);
|
|
1676
|
-
}
|
|
1677
|
-
const ordered = [];
|
|
1678
|
-
for (const [conversationId, items] of grouped) {
|
|
1679
|
-
const active = await store.listActiveRuns(conversationId);
|
|
1680
|
-
const position = new Map(active.map((run, index) => [run.id, index]));
|
|
1681
|
-
ordered.push(...items.sort((left, right) => {
|
|
1682
|
-
const leftPosition = position.get(left.run.id);
|
|
1683
|
-
const rightPosition = position.get(right.run.id);
|
|
1684
|
-
if (leftPosition === undefined && rightPosition === undefined)
|
|
1685
|
-
return 0;
|
|
1686
|
-
if (leftPosition === undefined)
|
|
1687
|
-
return 1;
|
|
1688
|
-
if (rightPosition === undefined)
|
|
1689
|
-
return -1;
|
|
1690
|
-
return leftPosition - rightPosition;
|
|
1691
|
-
}));
|
|
1692
|
-
}
|
|
1693
|
-
return ordered;
|
|
1694
|
-
}
|
|
1695
|
-
async function recoverItem(state, options, item, scheduledRuns) {
|
|
1696
|
-
const { store } = state.config;
|
|
1697
|
-
const active = await store.listActiveRuns(item.conversationId);
|
|
1698
|
-
const position = active.findIndex((run) => run.id === item.run.id);
|
|
1699
|
-
const scheduled = scheduledRuns.get(item.conversationId) ?? new Set;
|
|
1700
|
-
const blockedByUnscheduledPredecessor = position > 0 && active.slice(0, position).some((run) => !scheduled.has(run.id));
|
|
1701
|
-
if (blockedByUnscheduledPredecessor) {
|
|
1702
|
-
return { conversationId: item.conversationId, runId: item.run.id, outcome: "skipped" };
|
|
1703
|
-
}
|
|
1704
|
-
const decision = await options.decide?.(item) ?? (item.run.state === "queued" ? { action: "resume" } : { action: "skip" });
|
|
1705
|
-
if (state.gate.closed)
|
|
1706
|
-
throw closedError();
|
|
1707
|
-
if (decision.action === "skip") {
|
|
1708
|
-
return { conversationId: item.conversationId, runId: item.run.id, outcome: "skipped" };
|
|
1709
|
-
}
|
|
1710
|
-
if (decision.action === "abandon") {
|
|
1711
|
-
const abandoned = await store.recoverRun({
|
|
1712
|
-
conversationId: item.conversationId,
|
|
1713
|
-
runId: item.run.id,
|
|
1714
|
-
expectedRevision: item.run.revision,
|
|
1715
|
-
action: "abandon"
|
|
1716
|
-
});
|
|
1717
|
-
if (abandoned.outcome !== "applied") {
|
|
1718
|
-
throw new AgentRuntimeConflictError2("recovery abandon");
|
|
1719
|
-
}
|
|
1720
|
-
return { conversationId: item.conversationId, runId: item.run.id, outcome: "abandoned" };
|
|
1721
|
-
}
|
|
1722
|
-
if (decision.action === "requeue") {
|
|
1723
|
-
const requeued = await store.recoverRun({
|
|
1724
|
-
conversationId: item.conversationId,
|
|
1725
|
-
runId: item.run.id,
|
|
1726
|
-
expectedRevision: item.run.revision,
|
|
1727
|
-
action: "requeue",
|
|
1728
|
-
replaySafe: true
|
|
1729
|
-
});
|
|
1730
|
-
if (requeued.outcome !== "applied") {
|
|
1731
|
-
throw new AgentRuntimeConflictError2("recovery requeue");
|
|
1732
|
-
}
|
|
1733
|
-
}
|
|
1734
|
-
const context = await options.resolveContext(item);
|
|
1735
|
-
const resumed = resumeAgentRun(state, {
|
|
1736
|
-
conversationId: item.conversationId,
|
|
1737
|
-
runId: item.run.id,
|
|
1738
|
-
context
|
|
1739
|
-
});
|
|
1740
|
-
resumed.result.catch(() => {
|
|
1741
|
-
return;
|
|
1742
|
-
});
|
|
1743
|
-
await resumed.accepted;
|
|
1744
|
-
scheduled.add(item.run.id);
|
|
1745
|
-
scheduledRuns.set(item.conversationId, scheduled);
|
|
1746
|
-
return {
|
|
1747
|
-
conversationId: item.conversationId,
|
|
1748
|
-
runId: item.run.id,
|
|
1749
|
-
outcome: decision.action === "requeue" ? "requeued" : "resumed",
|
|
1750
|
-
result: resumed.result
|
|
1751
|
-
};
|
|
1752
|
-
}
|
|
1753
|
-
|
|
1754
|
-
// src/agent-runtime/admission-lanes.ts
|
|
1755
|
-
function createRuntimeAdmissionLanes() {
|
|
1756
|
-
const lanes = new Map;
|
|
1757
|
-
const admit = (runId) => {
|
|
1758
|
-
const admission = { runId, completion: Promise.withResolvers() };
|
|
1759
|
-
admission.completion.promise.catch(() => {
|
|
1760
|
-
return;
|
|
1761
|
-
});
|
|
1762
|
-
return admission;
|
|
1763
|
-
};
|
|
1764
|
-
return {
|
|
1765
|
-
reserve(key, runId) {
|
|
1766
|
-
const existing = lanes.get(key);
|
|
1767
|
-
const lane = existing ?? { acceptanceTail: Promise.resolve() };
|
|
1768
|
-
if (!existing)
|
|
1769
|
-
lanes.set(key, lane);
|
|
1770
|
-
if (!lane.head) {
|
|
1771
|
-
lane.head = admit(runId);
|
|
1772
|
-
return { lane, admission: lane.head, shouldSchedule: true };
|
|
1773
|
-
}
|
|
1774
|
-
if (!lane.pending) {
|
|
1775
|
-
lane.pending = admit(runId);
|
|
1776
|
-
return { lane, admission: lane.pending, shouldSchedule: true };
|
|
1777
|
-
}
|
|
1778
|
-
return { lane, admission: lane.pending, shouldSchedule: false };
|
|
1779
|
-
},
|
|
1780
|
-
settle(key, admission) {
|
|
1781
|
-
const lane = lanes.get(key);
|
|
1782
|
-
if (!lane)
|
|
1783
|
-
return;
|
|
1784
|
-
if (lane.head?.runId === admission.runId) {
|
|
1785
|
-
lane.head = lane.pending;
|
|
1786
|
-
lane.pending = undefined;
|
|
1787
|
-
} else if (lane.pending?.runId === admission.runId) {
|
|
1788
|
-
lane.pending = undefined;
|
|
1789
|
-
}
|
|
1790
|
-
if (!lane.head && !lane.pending)
|
|
1791
|
-
lanes.delete(key);
|
|
1792
|
-
},
|
|
1793
|
-
async waitForAcceptances(lane) {
|
|
1794
|
-
while (true) {
|
|
1795
|
-
const tail = lane.acceptanceTail;
|
|
1796
|
-
await tail.catch(() => {
|
|
1797
|
-
return;
|
|
1798
|
-
});
|
|
1799
|
-
if (tail === lane.acceptanceTail)
|
|
1800
|
-
return;
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
};
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
// src/agent-runtime/injection.ts
|
|
1807
|
-
function createAgentInjectionRegistry() {
|
|
1808
|
-
const offered = new Map;
|
|
1809
|
-
return {
|
|
1810
|
-
offer(key, entry) {
|
|
1811
|
-
const existing = offered.get(key);
|
|
1812
|
-
if (!existing) {
|
|
1813
|
-
offered.set(key, [entry]);
|
|
1814
|
-
return;
|
|
1815
|
-
}
|
|
1816
|
-
if (existing.some((candidate) => candidate.input.id === entry.input.id))
|
|
1817
|
-
return;
|
|
1818
|
-
existing.push(entry);
|
|
1819
|
-
},
|
|
1820
|
-
take(key, excludeRunId) {
|
|
1821
|
-
const existing = offered.get(key);
|
|
1822
|
-
if (!existing)
|
|
1823
|
-
return [];
|
|
1824
|
-
const taken = existing.filter((candidate) => candidate.runId !== excludeRunId);
|
|
1825
|
-
const kept = existing.filter((candidate) => candidate.runId === excludeRunId);
|
|
1826
|
-
if (kept.length === 0)
|
|
1827
|
-
offered.delete(key);
|
|
1828
|
-
else
|
|
1829
|
-
offered.set(key, kept);
|
|
1830
|
-
return taken;
|
|
1831
|
-
},
|
|
1832
|
-
withdraw(key, runId) {
|
|
1833
|
-
const existing = offered.get(key);
|
|
1834
|
-
if (!existing)
|
|
1835
|
-
return;
|
|
1836
|
-
const kept = existing.filter((candidate) => candidate.runId !== runId);
|
|
1837
|
-
if (kept.length === 0)
|
|
1838
|
-
offered.delete(key);
|
|
1839
|
-
else
|
|
1840
|
-
offered.set(key, kept);
|
|
1841
|
-
},
|
|
1842
|
-
clear() {
|
|
1843
|
-
offered.clear();
|
|
1844
|
-
}
|
|
1845
|
-
};
|
|
1846
|
-
}
|
|
1847
|
-
|
|
1848
|
-
// src/agent-runtime/run-operation-lifecycle.ts
|
|
1849
|
-
import { wrapLanguageModel } from "ai";
|
|
1850
|
-
function createAgentRunOperationLifecycle(config) {
|
|
1851
|
-
let active;
|
|
1852
|
-
let providerCallId;
|
|
1853
|
-
let checkpointedStep = -1;
|
|
1854
|
-
const checkpointWaiters = new Map;
|
|
1855
|
-
const record = (operation) => config.serialize(async () => {
|
|
1856
|
-
const current = config.currentRun();
|
|
1857
|
-
const snapshot = appliedSnapshot(await config.store.recordRunOperation({
|
|
1858
|
-
conversationId: current.conversationId,
|
|
1859
|
-
runId: current.id,
|
|
1860
|
-
expectedRevision: current.revision,
|
|
1861
|
-
ownerId: config.runtimeEpoch,
|
|
1862
|
-
...current.fencingToken !== undefined && { fencingToken: current.fencingToken },
|
|
1863
|
-
operation
|
|
1864
|
-
}), "run operation");
|
|
1865
|
-
config.acceptSnapshot(snapshot);
|
|
1866
|
-
const run = findRun(snapshot.runs, current.id);
|
|
1867
|
-
active = operation;
|
|
1868
|
-
await config.publish({
|
|
1869
|
-
type: "run-operation",
|
|
1870
|
-
eventId: agentDurableEventId2("run-operation", run.id, snapshot.version),
|
|
1871
|
-
conversationId: run.conversationId,
|
|
1872
|
-
runId: run.id,
|
|
1873
|
-
snapshotVersion: snapshot.version,
|
|
1874
|
-
operation,
|
|
1875
|
-
emittedAt: config.now().toISOString()
|
|
1876
|
-
});
|
|
1877
|
-
});
|
|
1878
|
-
const startModelRequest = async (callId, step) => {
|
|
1879
|
-
await record(AgentRunOperationSchema2.parse({
|
|
1880
|
-
operationId: `${callId}:${step}`,
|
|
1881
|
-
kind: "model-request",
|
|
1882
|
-
phase: "started",
|
|
1883
|
-
step,
|
|
1884
|
-
startedAt: config.now().toISOString()
|
|
1885
|
-
}));
|
|
1886
|
-
};
|
|
1887
|
-
return {
|
|
1888
|
-
noteProviderCall(callId) {
|
|
1889
|
-
providerCallId = callId;
|
|
1890
|
-
},
|
|
1891
|
-
async prepareModel(model, step, fallbackCallId) {
|
|
1892
|
-
if (step > checkpointedStep + 1) {
|
|
1893
|
-
const waiter = checkpointWaiters.get(step - 1) ?? Promise.withResolvers();
|
|
1894
|
-
checkpointWaiters.set(step - 1, waiter);
|
|
1895
|
-
await waiter.promise;
|
|
1896
|
-
}
|
|
1897
|
-
if (typeof model === "string") {
|
|
1898
|
-
await startModelRequest(fallbackCallId, step);
|
|
1899
|
-
return model;
|
|
1900
|
-
}
|
|
1901
|
-
return wrapLanguageModel({
|
|
1902
|
-
model,
|
|
1903
|
-
middleware: {
|
|
1904
|
-
specificationVersion: "v4",
|
|
1905
|
-
wrapStream: async ({ doStream }) => {
|
|
1906
|
-
const callId = providerCallId;
|
|
1907
|
-
providerCallId = undefined;
|
|
1908
|
-
if (!callId) {
|
|
1909
|
-
throw new Error("AgentRuntime model call reached the provider without lifecycle identity");
|
|
1910
|
-
}
|
|
1911
|
-
await startModelRequest(callId, step);
|
|
1912
|
-
try {
|
|
1913
|
-
const result = await doStream();
|
|
1914
|
-
return { ...result, stream: markProviderStream(result.stream) };
|
|
1915
|
-
} catch (error) {
|
|
1916
|
-
throw isOwnInputRefusal(error) ? error : markProviderOrigin(error);
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
1919
|
-
}
|
|
1920
|
-
});
|
|
1921
|
-
},
|
|
1922
|
-
checkpointStep(step) {
|
|
1923
|
-
checkpointedStep = Math.max(checkpointedStep, step);
|
|
1924
|
-
for (const [waitingFor, waiter] of checkpointWaiters) {
|
|
1925
|
-
if (waitingFor > checkpointedStep)
|
|
1926
|
-
continue;
|
|
1927
|
-
checkpointWaiters.delete(waitingFor);
|
|
1928
|
-
waiter.resolve();
|
|
1929
|
-
}
|
|
1930
|
-
},
|
|
1931
|
-
failStepCheckpoints(error) {
|
|
1932
|
-
for (const waiter of checkpointWaiters.values())
|
|
1933
|
-
waiter.reject(error);
|
|
1934
|
-
checkpointWaiters.clear();
|
|
1935
|
-
},
|
|
1936
|
-
startCompaction(operationId) {
|
|
1937
|
-
return record(AgentRunOperationSchema2.parse({
|
|
1938
|
-
operationId,
|
|
1939
|
-
kind: "compaction",
|
|
1940
|
-
phase: "started",
|
|
1941
|
-
startedAt: config.now().toISOString()
|
|
1942
|
-
}));
|
|
1943
|
-
},
|
|
1944
|
-
firstOutput() {
|
|
1945
|
-
if (active?.kind !== "model-request" || active.phase !== "started") {
|
|
1946
|
-
return Promise.resolve();
|
|
1947
|
-
}
|
|
1948
|
-
return record(AgentRunOperationSchema2.parse({
|
|
1949
|
-
...active,
|
|
1950
|
-
phase: "first-output",
|
|
1951
|
-
firstOutputAt: config.now().toISOString()
|
|
1952
|
-
}));
|
|
1953
|
-
},
|
|
1954
|
-
finish(phase) {
|
|
1955
|
-
if (!active || ["completed", "failed", "cancelled"].includes(active.phase)) {
|
|
1956
|
-
return Promise.resolve();
|
|
1957
|
-
}
|
|
1958
|
-
return record(AgentRunOperationSchema2.parse({
|
|
1959
|
-
...active,
|
|
1960
|
-
phase,
|
|
1961
|
-
finishedAt: config.now().toISOString()
|
|
1962
|
-
}));
|
|
1963
|
-
}
|
|
1964
|
-
};
|
|
1965
|
-
}
|
|
1966
|
-
|
|
1967
|
-
// src/agent-runtime/run-acquisition.ts
|
|
1968
|
-
async function acquireRun(dependencies, input) {
|
|
1969
|
-
const { config, runtimeEpoch, now, idleTimeoutMs, injection } = dependencies;
|
|
1970
|
-
injection?.withdraw(input.key, input.acceptedRun.id);
|
|
1971
|
-
const queued = await withStoreRetries(() => config.store.loadRun({
|
|
1972
|
-
conversationId: input.acceptedRun.conversationId,
|
|
1973
|
-
runId: input.acceptedRun.id
|
|
1974
|
-
}));
|
|
1975
|
-
if (!queued)
|
|
1976
|
-
throw new AgentRuntimeConflictError2("run lookup");
|
|
1977
|
-
if (queued.run.terminalReason === "absorbed") {
|
|
1978
|
-
const { absorbedIntoRunId } = queued.run;
|
|
1979
|
-
const absorbing = absorbedIntoRunId ? await withStoreRetries(() => config.store.loadRun({
|
|
1980
|
-
conversationId: queued.run.conversationId,
|
|
1981
|
-
runId: absorbedIntoRunId
|
|
1982
|
-
})) : undefined;
|
|
1983
|
-
if (!absorbing?.assistant || !absorbing.run.terminalReason) {
|
|
1984
|
-
throw new AgentRuntimeConflictError2("absorbed run resolution");
|
|
1985
|
-
}
|
|
1986
|
-
input.onAcquired?.();
|
|
1987
|
-
return {
|
|
1988
|
-
kind: "absorbed",
|
|
1989
|
-
result: {
|
|
1990
|
-
run: absorbing.run,
|
|
1991
|
-
message: absorbing.assistant,
|
|
1992
|
-
reason: absorbing.run.terminalReason,
|
|
1993
|
-
snapshotVersion: absorbing.snapshotVersion,
|
|
1994
|
-
...absorbing.run.terminalPolicyName && {
|
|
1995
|
-
policyName: absorbing.run.terminalPolicyName
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
};
|
|
1999
|
-
}
|
|
2000
|
-
const queuedRun = queued.run;
|
|
2001
|
-
const acquired = appliedSnapshot(await withStoreRetries(() => config.store.acquireRun({
|
|
2002
|
-
conversationId: queuedRun.conversationId,
|
|
2003
|
-
runId: queuedRun.id,
|
|
2004
|
-
expectedRevision: queuedRun.revision,
|
|
2005
|
-
ownerId: runtimeEpoch
|
|
2006
|
-
})), "run acquisition");
|
|
2007
|
-
const run = findRun(acquired.runs, input.acceptedRun.id);
|
|
2008
|
-
input.onAcquired?.();
|
|
2009
|
-
const trace = config.observe?.rootTrace();
|
|
2010
|
-
const runStartedAt = performance.now();
|
|
2011
|
-
const assistant = AgentMessageSchema2.parse({
|
|
2012
|
-
schemaVersion: 1,
|
|
2013
|
-
id: run.assistantMessageId,
|
|
2014
|
-
conversationId: run.conversationId,
|
|
2015
|
-
runId: run.id,
|
|
2016
|
-
role: "assistant",
|
|
2017
|
-
status: "streaming",
|
|
2018
|
-
parts: [],
|
|
2019
|
-
createdAt: now().toISOString(),
|
|
2020
|
-
updatedAt: now().toISOString()
|
|
2021
|
-
});
|
|
2022
|
-
const state = {
|
|
2023
|
-
run,
|
|
2024
|
-
snapshot: acquired,
|
|
2025
|
-
observedVersion: acquired.version,
|
|
2026
|
-
assistant,
|
|
2027
|
-
parts: [],
|
|
2028
|
-
absorbed: new Map,
|
|
2029
|
-
eventsSinceCheckpoint: 0,
|
|
2030
|
-
sequence: 0,
|
|
2031
|
-
settledToolCalls: new Set,
|
|
2032
|
-
terminalReason: "success",
|
|
2033
|
-
nonModelUsage: input.acceptedRun.usage,
|
|
2034
|
-
modelUsage: undefined,
|
|
2035
|
-
abandonedUsage: undefined,
|
|
2036
|
-
usage: input.acceptedRun.usage,
|
|
2037
|
-
sawProviderFinish: false,
|
|
2038
|
-
step: 0,
|
|
2039
|
-
stepGuard: { text: "", toolFailed: false, reasoningChars: 0 },
|
|
2040
|
-
selectedModel: undefined,
|
|
2041
|
-
internalCause: undefined,
|
|
2042
|
-
providerStreamCleanupFailure: undefined,
|
|
2043
|
-
reasoningPartIndex: undefined,
|
|
2044
|
-
firstOutputAt: undefined,
|
|
2045
|
-
terminalPolicyName: undefined,
|
|
2046
|
-
lastPromptTokens: { provenance: "unavailable" }
|
|
2047
|
-
};
|
|
2048
|
-
const idleDeadline = createIdleDeadline(input.signal, idleTimeoutMs);
|
|
2049
|
-
const serialize = createMutationQueue();
|
|
2050
|
-
const operationLifecycle = createAgentRunOperationLifecycle({
|
|
2051
|
-
store: config.store,
|
|
2052
|
-
runtimeEpoch,
|
|
2053
|
-
serialize,
|
|
2054
|
-
currentRun: () => state.run,
|
|
2055
|
-
acceptSnapshot: (next) => adoptSnapshot(state, next),
|
|
2056
|
-
publish: dependencies.publish,
|
|
2057
|
-
now
|
|
2058
|
-
});
|
|
2059
|
-
return {
|
|
2060
|
-
kind: "acquired",
|
|
2061
|
-
execution: {
|
|
2062
|
-
dependencies,
|
|
2063
|
-
input,
|
|
2064
|
-
state,
|
|
2065
|
-
trace,
|
|
2066
|
-
runStartedAt,
|
|
2067
|
-
idleDeadline,
|
|
2068
|
-
executionSignal: idleDeadline.signal,
|
|
2069
|
-
serialize,
|
|
2070
|
-
operationLifecycle
|
|
2071
|
-
}
|
|
2072
|
-
};
|
|
2073
|
-
}
|
|
2074
|
-
async function beginRunExecution(execution) {
|
|
2075
|
-
const { config, publish, runtimeEpoch, generateId, now } = execution.dependencies;
|
|
2076
|
-
const { state, trace } = execution;
|
|
2077
|
-
const { run, assistant } = state;
|
|
2078
|
-
await publish({
|
|
2079
|
-
type: "run-state",
|
|
2080
|
-
eventId: agentDurableEventId2("run-state", run.id, state.observedVersion),
|
|
2081
|
-
conversationId: run.conversationId,
|
|
2082
|
-
runId: run.id,
|
|
2083
|
-
snapshotVersion: state.observedVersion,
|
|
2084
|
-
state: run.state,
|
|
2085
|
-
emittedAt: now().toISOString()
|
|
2086
|
-
});
|
|
2087
|
-
config.observe?.emit({
|
|
2088
|
-
schemaVersion: 1,
|
|
2089
|
-
eventId: generateId(),
|
|
2090
|
-
type: "run-started",
|
|
2091
|
-
conversationId: run.conversationId,
|
|
2092
|
-
runId: run.id,
|
|
2093
|
-
traceId: trace?.traceId ?? generateId(),
|
|
2094
|
-
spanId: trace?.spanId ?? generateId(),
|
|
2095
|
-
...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
|
|
2096
|
-
state: run.state,
|
|
2097
|
-
queueWaitMs: Math.max(0, now().getTime() - new Date(run.createdAt).getTime()),
|
|
2098
|
-
emittedAt: now().toISOString()
|
|
2099
|
-
});
|
|
2100
|
-
adoptSnapshot(state, appliedSnapshot(await config.store.checkpointRunAssistant({
|
|
2101
|
-
conversationId: run.conversationId,
|
|
2102
|
-
runId: run.id,
|
|
2103
|
-
expectedRevision: run.revision,
|
|
2104
|
-
ownerId: runtimeEpoch,
|
|
2105
|
-
...run.fencingToken !== undefined && { fencingToken: run.fencingToken },
|
|
2106
|
-
assistant
|
|
2107
|
-
}), "assistant draft"));
|
|
2108
|
-
}
|
|
2109
|
-
|
|
2110
|
-
// src/agent-runtime/run-failure.ts
|
|
2111
|
-
function failureThisRuntimeOwns(error) {
|
|
2112
|
-
if (error instanceof InvocationReceiptError)
|
|
2113
|
-
return "runtime_failure";
|
|
2114
|
-
if (error instanceof AgentContextOverflowError2)
|
|
2115
|
-
return "context_overflow";
|
|
2116
|
-
if (error instanceof AgentRuntimeConflictError2)
|
|
2117
|
-
return "storage_conflict";
|
|
2118
|
-
if (error instanceof AgentStepBarrierError2)
|
|
2119
|
-
return "policy_stop";
|
|
2120
|
-
if (isOwnInputRefusal(error))
|
|
2121
|
-
return "runtime_failure";
|
|
2122
|
-
return;
|
|
2123
|
-
}
|
|
2124
|
-
function withLaterFailure(primary, later, what) {
|
|
2125
|
-
return new AggregateError([primary, later], `${primary instanceof Error ? primary.message : String(primary)} (${what} also failed: ${later instanceof Error ? later.message : String(later)})`);
|
|
2126
|
-
}
|
|
2127
|
-
async function classifyRunFailure(execution, error) {
|
|
2128
|
-
const { config, runtimeEpoch } = execution.dependencies;
|
|
2129
|
-
const { state, operationLifecycle, executionSignal } = execution;
|
|
2130
|
-
operationLifecycle.failStepCheckpoints(error);
|
|
2131
|
-
const cleanupFailure = state.providerStreamCleanupFailure;
|
|
2132
|
-
state.internalCause = cleanupFailure === undefined ? error : withLaterFailure(error, cleanupFailure, "provider stream cleanup");
|
|
2133
|
-
let latest;
|
|
2134
|
-
try {
|
|
2135
|
-
latest = await config.store.loadRun({
|
|
2136
|
-
conversationId: state.run.conversationId,
|
|
2137
|
-
runId: state.run.id
|
|
2138
|
-
});
|
|
2139
|
-
} catch (readFailure) {
|
|
2140
|
-
state.internalCause = withLaterFailure(state.internalCause, readFailure, "the run read");
|
|
2141
|
-
}
|
|
2142
|
-
const latestRun = latest?.run;
|
|
2143
|
-
const durableInterrupt = latestRun?.ownerId === runtimeEpoch && latestRun.state === "interrupt_requested";
|
|
2144
|
-
if (durableInterrupt && latest && latestRun) {
|
|
2145
|
-
state.observedVersion = latest.snapshotVersion;
|
|
2146
|
-
state.run = latestRun;
|
|
2147
|
-
}
|
|
2148
|
-
const staleOwner = isToolExecutionControlError2(error) && error.reason === "stale_run";
|
|
2149
|
-
if (!staleOwner) {
|
|
2150
|
-
try {
|
|
2151
|
-
await operationLifecycle.finish(executionSignal.aborted || durableInterrupt ? "cancelled" : "failed");
|
|
2152
|
-
} catch (finishFailure) {
|
|
2153
|
-
state.internalCause = withLaterFailure(state.internalCause, finishFailure, "closing the operations");
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
if (isToolExecutionControlError2(error) || executionSignal.aborted || durableInterrupt) {
|
|
2157
|
-
state.terminalReason = executionSignal.aborted ? abortTerminalReason(executionSignal) : "interrupted";
|
|
2158
|
-
state.parts.push(AgentMessagePartSchema2.parse({
|
|
2159
|
-
type: "control",
|
|
2160
|
-
reason: isToolExecutionControlError2(error) && error.reason === "stale_run" ? "stale-run" : "run-interrupted"
|
|
2161
|
-
}));
|
|
2162
|
-
} else if (error instanceof AgentContextOverflowError2) {
|
|
2163
|
-
state.terminalReason = "context_overflow";
|
|
2164
|
-
} else if (error instanceof AgentRuntimeConflictError2) {
|
|
2165
|
-
state.terminalReason = "storage_conflict";
|
|
2166
|
-
} else {
|
|
2167
|
-
state.terminalReason = failureThisRuntimeOwns(error) ?? (hasProviderOrigin(error) ? "provider_failure" : "runtime_failure");
|
|
2168
|
-
}
|
|
2169
|
-
}
|
|
2170
|
-
|
|
2171
|
-
// src/agent-runtime/run-model-attempts.ts
|
|
2172
|
-
import { setTimeout as delay } from "node:timers/promises";
|
|
2173
|
-
import {
|
|
2174
|
-
stepCountIs
|
|
2175
|
-
} from "ai";
|
|
2176
|
-
|
|
2177
|
-
// src/agent-runtime/owned-provider-stream.ts
|
|
2178
|
-
var DEFAULT_CLEANUP_TIMEOUT_MS = 1000;
|
|
2179
|
-
async function settleCleanup(operation, timeoutMs) {
|
|
2180
|
-
if (!(await withDeadline(operation, timeoutMs)).settled)
|
|
2181
|
-
throw new Error(`Provider stream cleanup exceeded ${timeoutMs} ms`);
|
|
2182
|
-
}
|
|
2183
|
-
async function* ownedProviderStream(input) {
|
|
2184
|
-
const iterator = input.stream[Symbol.asyncIterator]();
|
|
2185
|
-
let completed = false;
|
|
2186
|
-
try {
|
|
2187
|
-
for (;; ) {
|
|
2188
|
-
const next = await iterator.next();
|
|
2189
|
-
if (next.done) {
|
|
2190
|
-
completed = true;
|
|
2191
|
-
return;
|
|
2192
|
-
}
|
|
2193
|
-
yield next.value;
|
|
2194
|
-
}
|
|
2195
|
-
} finally {
|
|
2196
|
-
if (!completed) {
|
|
2197
|
-
input.abort();
|
|
2198
|
-
const cleanup = iterator.return?.();
|
|
2199
|
-
if (cleanup) {
|
|
2200
|
-
try {
|
|
2201
|
-
await settleCleanup(cleanup, input.cleanupTimeoutMs ?? DEFAULT_CLEANUP_TIMEOUT_MS);
|
|
2202
|
-
} catch (error) {
|
|
2203
|
-
input.onCleanupFailure(error);
|
|
2204
|
-
}
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
}
|
|
2208
|
-
}
|
|
2209
|
-
|
|
2210
|
-
// src/agent-runtime/run-provider-ledger.ts
|
|
2211
|
-
import { createHash } from "node:crypto";
|
|
2212
|
-
function withoutBinaryParts(message) {
|
|
2213
|
-
const reference = (value) => {
|
|
2214
|
-
if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
|
|
2215
|
-
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
|
|
2216
|
-
return {
|
|
2217
|
-
binary: true,
|
|
2218
|
-
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
2219
|
-
bytes: bytes.byteLength
|
|
2220
|
-
};
|
|
2221
|
-
}
|
|
2222
|
-
if (value instanceof URL)
|
|
2223
|
-
return value.toString();
|
|
2224
|
-
if (Array.isArray(value))
|
|
2225
|
-
return value.map(reference);
|
|
2226
|
-
if (value && typeof value === "object") {
|
|
2227
|
-
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
|
|
2228
|
-
key,
|
|
2229
|
-
reference(entry)
|
|
2230
|
-
]));
|
|
2231
|
-
}
|
|
2232
|
-
return value;
|
|
2233
|
-
};
|
|
2234
|
-
return reference(message);
|
|
2235
|
-
}
|
|
2236
|
-
async function createRunProviderLedger(input) {
|
|
2237
|
-
const { store, state } = input;
|
|
2238
|
-
if (input.audited) {
|
|
2239
|
-
return {
|
|
2240
|
-
async recordRequest() {},
|
|
2241
|
-
async recordResponse(response) {
|
|
2242
|
-
return providerResponseIdentity(response.id, state.selectedModel?.resolveResponseProvider?.({
|
|
2243
|
-
providerMetadata: response.providerMetadata
|
|
2244
|
-
}));
|
|
2245
|
-
}
|
|
2246
|
-
};
|
|
2247
|
-
}
|
|
2248
|
-
const requestModelId = input.selectedModel.descriptor.modelId;
|
|
2249
|
-
const knownMessageShas = new Set;
|
|
2250
|
-
{
|
|
2251
|
-
let fromSeq;
|
|
2252
|
-
do {
|
|
2253
|
-
const page = await store.readEvents({
|
|
2254
|
-
conversationId: state.run.conversationId,
|
|
2255
|
-
...fromSeq && { fromSeq },
|
|
2256
|
-
limit: 1e4
|
|
2257
|
-
});
|
|
2258
|
-
for (const event of page.items) {
|
|
2259
|
-
if (event.kind !== "provider/message")
|
|
2260
|
-
continue;
|
|
2261
|
-
const sha = event.payload?.sha256;
|
|
2262
|
-
if (typeof sha === "string")
|
|
2263
|
-
knownMessageShas.add(sha);
|
|
2264
|
-
}
|
|
2265
|
-
fromSeq = page.nextSeq;
|
|
2266
|
-
} while (fromSeq !== undefined);
|
|
2267
|
-
}
|
|
2268
|
-
return {
|
|
2269
|
-
async recordRequest(request) {
|
|
2270
|
-
const messageShas = [];
|
|
2271
|
-
for (const message of request.messages) {
|
|
2272
|
-
const body = canonicalAgentJson2(JSON.parse(JSON.stringify(withoutBinaryParts(message))));
|
|
2273
|
-
const sha256 = createHash("sha256").update(body).digest("hex");
|
|
2274
|
-
messageShas.push(sha256);
|
|
2275
|
-
if (knownMessageShas.has(sha256))
|
|
2276
|
-
continue;
|
|
2277
|
-
await store.appendEvent({
|
|
2278
|
-
conversationId: state.run.conversationId,
|
|
2279
|
-
kind: "provider/message",
|
|
2280
|
-
payload: ProviderJournalMessageSchema.parse({ sha256, message: JSON.parse(body) })
|
|
2281
|
-
});
|
|
2282
|
-
knownMessageShas.add(sha256);
|
|
2283
|
-
}
|
|
2284
|
-
const instructionsSha256 = createHash("sha256").update(typeof request.instructions === "string" ? request.instructions : canonicalAgentJson2(JSON.parse(JSON.stringify(withoutBinaryParts(request.instructions))))).digest("hex");
|
|
2285
|
-
const bodySha256 = createHash("sha256").update(instructionsSha256).update(messageShas.join(",")).digest("hex");
|
|
2286
|
-
await store.appendEvent({
|
|
2287
|
-
conversationId: state.run.conversationId,
|
|
2288
|
-
kind: "provider/request",
|
|
2289
|
-
payload: ProviderJournalRequestSchema.parse({
|
|
2290
|
-
runId: state.run.id,
|
|
2291
|
-
attempt: request.attempt,
|
|
2292
|
-
stepNumber: request.stepNumber,
|
|
2293
|
-
modelId: requestModelId,
|
|
2294
|
-
instructionsSha256,
|
|
2295
|
-
messageShas,
|
|
2296
|
-
bodySha256
|
|
2297
|
-
})
|
|
2298
|
-
});
|
|
2299
|
-
},
|
|
2300
|
-
async recordResponse(response) {
|
|
2301
|
-
const identity = providerResponseIdentity(response.id, state.selectedModel?.resolveResponseProvider?.({
|
|
2302
|
-
providerMetadata: response.providerMetadata
|
|
2303
|
-
}));
|
|
2304
|
-
await store.appendEvent({
|
|
2305
|
-
conversationId: state.run.conversationId,
|
|
2306
|
-
kind: "provider/response",
|
|
2307
|
-
payload: ProviderJournalResponseSchema.parse({
|
|
2308
|
-
runId: state.run.id,
|
|
2309
|
-
attempt: response.attempt,
|
|
2310
|
-
stepNumber: response.stepNumber,
|
|
2311
|
-
response: identity,
|
|
2312
|
-
usage: response.usage
|
|
2313
|
-
})
|
|
2314
|
-
});
|
|
2315
|
-
return identity;
|
|
2316
|
-
}
|
|
2317
|
-
};
|
|
2318
|
-
}
|
|
2319
|
-
|
|
2320
|
-
// src/agent-runtime/run-stream-parts.ts
|
|
2321
|
-
function transientHead(execution) {
|
|
2322
|
-
const { state } = execution;
|
|
2323
|
-
return {
|
|
2324
|
-
conversationId: state.run.conversationId,
|
|
2325
|
-
runId: state.run.id,
|
|
2326
|
-
runtimeEpoch: execution.dependencies.runtimeEpoch,
|
|
2327
|
-
sequence: transientSequence(state)
|
|
2328
|
-
};
|
|
2329
|
-
}
|
|
2330
|
-
function isOutputPart(part) {
|
|
2331
|
-
return part.type === "text-delta" && part.text.length > 0 || part.type === "reasoning-delta" && part.text.length > 0 || part.type === "tool-input-delta" && part.delta.length > 0 || part.type === "tool-call";
|
|
2332
|
-
}
|
|
2333
|
-
var TOOL_STATUS_PARTS = [
|
|
2334
|
-
"tool-call",
|
|
2335
|
-
"tool-result",
|
|
2336
|
-
"tool-error",
|
|
2337
|
-
"tool-output-denied"
|
|
2338
|
-
];
|
|
2339
|
-
var STRUCTURAL_BOUNDARY_PARTS = [
|
|
2340
|
-
...TOOL_STATUS_PARTS,
|
|
2341
|
-
"tool-approval-request",
|
|
2342
|
-
"tool-approval-response",
|
|
2343
|
-
"finish-step"
|
|
2344
|
-
];
|
|
2345
|
-
async function applyTextPart(execution, part) {
|
|
2346
|
-
const { publish, now } = execution.dependencies;
|
|
2347
|
-
const { state } = execution;
|
|
2348
|
-
const barriers = execution.dependencies.config.loop?.stepBarriers;
|
|
2349
|
-
if (part.type === "text-delta" && barriers?.stepText === "after-tools") {
|
|
2350
|
-
state.stepGuard.text += part.text;
|
|
2351
|
-
} else if (part.type === "text-delta") {
|
|
2352
|
-
appendText(state.parts, part.text);
|
|
2353
|
-
await publish({
|
|
2354
|
-
type: "assistant-delta",
|
|
2355
|
-
...transientHead(execution),
|
|
2356
|
-
textDelta: part.text,
|
|
2357
|
-
emittedAt: now().toISOString()
|
|
2358
|
-
});
|
|
2359
|
-
} else if (part.type === "reasoning-start") {
|
|
2360
|
-
state.reasoningPartIndex = undefined;
|
|
2361
|
-
updateReasoning(state, "", part.providerMetadata);
|
|
2362
|
-
const provider = providerEnvelope(part.providerMetadata);
|
|
2363
|
-
await publish({
|
|
2364
|
-
type: "reasoning-start",
|
|
2365
|
-
...transientHead(execution),
|
|
2366
|
-
...provider && { provider },
|
|
2367
|
-
emittedAt: now().toISOString()
|
|
2368
|
-
});
|
|
2369
|
-
} else if (part.type === "reasoning-delta") {
|
|
2370
|
-
const limit = barriers?.maxReasoningCharsPerStep;
|
|
2371
|
-
state.stepGuard.reasoningChars += part.text.length;
|
|
2372
|
-
if (limit !== undefined && state.stepGuard.reasoningChars > limit) {
|
|
2373
|
-
state.terminalPolicyName = "stepBarriers.maxReasoningCharsPerStep";
|
|
2374
|
-
throw new AgentStepBarrierError2("reasoning", `A step reasoned past its bound of ${limit} characters`);
|
|
2375
|
-
}
|
|
2376
|
-
updateReasoning(state, part.text, part.providerMetadata);
|
|
2377
|
-
const provider = providerEnvelope(part.providerMetadata);
|
|
2378
|
-
await publish({
|
|
2379
|
-
type: "reasoning-delta",
|
|
2380
|
-
...transientHead(execution),
|
|
2381
|
-
textDelta: part.text,
|
|
2382
|
-
...provider && { provider },
|
|
2383
|
-
emittedAt: now().toISOString()
|
|
2384
|
-
});
|
|
2385
|
-
} else if (part.type === "reasoning-end") {
|
|
2386
|
-
updateReasoning(state, "", part.providerMetadata);
|
|
2387
|
-
state.reasoningPartIndex = undefined;
|
|
2388
|
-
const provider = providerEnvelope(part.providerMetadata);
|
|
2389
|
-
await publish({
|
|
2390
|
-
type: "reasoning-end",
|
|
2391
|
-
...transientHead(execution),
|
|
2392
|
-
...provider && { provider },
|
|
2393
|
-
emittedAt: now().toISOString()
|
|
2394
|
-
});
|
|
2395
|
-
}
|
|
2396
|
-
}
|
|
2397
|
-
async function applyToolPart(execution, part) {
|
|
2398
|
-
const { state } = execution;
|
|
2399
|
-
if (part.type === "tool-call") {
|
|
2400
|
-
const provider = providerEnvelope(part.providerMetadata);
|
|
2401
|
-
state.parts.push(AgentMessagePartSchema2.parse({
|
|
2402
|
-
type: "tool-call",
|
|
2403
|
-
callId: part.toolCallId,
|
|
2404
|
-
toolName: part.toolName,
|
|
2405
|
-
input: jsonValue(part.input),
|
|
2406
|
-
...provider && { provider }
|
|
2407
|
-
}));
|
|
2408
|
-
await checkpoint(execution, {
|
|
2409
|
-
callId: part.toolCallId,
|
|
2410
|
-
toolName: part.toolName,
|
|
2411
|
-
status: "started",
|
|
2412
|
-
input: jsonValue(part.input)
|
|
2413
|
-
});
|
|
2414
|
-
} else if (part.type === "tool-result") {
|
|
2415
|
-
if (part.preliminary === true)
|
|
2416
|
-
return;
|
|
2417
|
-
state.settledToolCalls.add(part.toolCallId);
|
|
2418
|
-
state.parts.push(AgentMessagePartSchema2.parse({
|
|
2419
|
-
type: "tool-result",
|
|
2420
|
-
callId: part.toolCallId,
|
|
2421
|
-
toolName: part.toolName,
|
|
2422
|
-
outcome: "success",
|
|
2423
|
-
output: jsonValue(part.output)
|
|
2424
|
-
}));
|
|
2425
|
-
await checkpoint(execution, {
|
|
2426
|
-
callId: part.toolCallId,
|
|
2427
|
-
toolName: part.toolName,
|
|
2428
|
-
status: "completed",
|
|
2429
|
-
output: jsonValue(part.output)
|
|
2430
|
-
});
|
|
2431
|
-
} else if (part.type === "tool-error") {
|
|
2432
|
-
state.settledToolCalls.add(part.toolCallId);
|
|
2433
|
-
state.internalCause = part.error;
|
|
2434
|
-
if (isToolExecutionControlError2(part.error)) {
|
|
2435
|
-
await checkpoint(execution, {
|
|
2436
|
-
callId: part.toolCallId,
|
|
2437
|
-
toolName: part.toolName,
|
|
2438
|
-
status: "interrupted"
|
|
2439
|
-
});
|
|
2440
|
-
throw part.error;
|
|
2441
|
-
}
|
|
2442
|
-
state.stepGuard.toolFailed = true;
|
|
2443
|
-
const output = isAgentToolError2(part.error) ? jsonValue(part.error.output) : { message: "Tool execution failed" };
|
|
2444
|
-
state.parts.push(AgentMessagePartSchema2.parse({
|
|
2445
|
-
type: "tool-result",
|
|
2446
|
-
callId: part.toolCallId,
|
|
2447
|
-
toolName: part.toolName,
|
|
2448
|
-
outcome: "error",
|
|
2449
|
-
output
|
|
2450
|
-
}));
|
|
2451
|
-
await checkpoint(execution, {
|
|
2452
|
-
callId: part.toolCallId,
|
|
2453
|
-
toolName: part.toolName,
|
|
2454
|
-
status: "failed",
|
|
2455
|
-
output
|
|
2456
|
-
});
|
|
2457
|
-
} else if (part.type === "tool-output-denied") {
|
|
2458
|
-
state.settledToolCalls.add(part.toolCallId);
|
|
2459
|
-
state.stepGuard.toolFailed = true;
|
|
2460
|
-
state.parts.push(AgentMessagePartSchema2.parse({
|
|
2461
|
-
type: "tool-result",
|
|
2462
|
-
callId: part.toolCallId,
|
|
2463
|
-
toolName: part.toolName,
|
|
2464
|
-
outcome: "error",
|
|
2465
|
-
output: { message: "Tool output denied" }
|
|
2466
|
-
}));
|
|
2467
|
-
await checkpoint(execution, {
|
|
2468
|
-
callId: part.toolCallId,
|
|
2469
|
-
toolName: part.toolName,
|
|
2470
|
-
status: "failed",
|
|
2471
|
-
output: { message: "Tool output denied" }
|
|
2472
|
-
});
|
|
2473
|
-
}
|
|
2474
|
-
}
|
|
2475
|
-
async function applyRecordedPart(execution, part) {
|
|
2476
|
-
const { config } = execution.dependencies;
|
|
2477
|
-
const { parts } = execution.state;
|
|
2478
|
-
if (part.type === "source") {
|
|
2479
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2480
|
-
type: "source",
|
|
2481
|
-
sourceId: part.id,
|
|
2482
|
-
...part.sourceType === "url" && { url: part.url },
|
|
2483
|
-
...part.title && { title: part.title }
|
|
2484
|
-
}));
|
|
2485
|
-
} else if (part.type === "file" && config.persistGeneratedFile) {
|
|
2486
|
-
const persisted = await config.persistGeneratedFile(part.file);
|
|
2487
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2488
|
-
type: "file",
|
|
2489
|
-
mediaType: part.file.mediaType,
|
|
2490
|
-
reference: persisted.reference,
|
|
2491
|
-
...persisted.filename && { filename: persisted.filename }
|
|
2492
|
-
}));
|
|
2493
|
-
} else if (part.type === "file") {
|
|
2494
|
-
throw new Error("persistGeneratedFile is required for generated file output");
|
|
2495
|
-
} else if (part.type === "reasoning-file" && config.persistGeneratedFile) {
|
|
2496
|
-
const persisted = await config.persistGeneratedFile(part.file);
|
|
2497
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2498
|
-
type: "file",
|
|
2499
|
-
mediaType: part.file.mediaType,
|
|
2500
|
-
reference: persisted.reference,
|
|
2501
|
-
...persisted.filename && { filename: persisted.filename }
|
|
2502
|
-
}));
|
|
2503
|
-
} else if (part.type === "reasoning-file") {
|
|
2504
|
-
throw new Error("persistGeneratedFile is required for generated reasoning files");
|
|
2505
|
-
} else if (part.type === "tool-approval-request") {
|
|
2506
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2507
|
-
type: "tool-approval-request",
|
|
2508
|
-
approvalId: part.approvalId,
|
|
2509
|
-
callId: part.toolCall.toolCallId,
|
|
2510
|
-
...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
|
|
2511
|
-
...part.signature && { signature: part.signature }
|
|
2512
|
-
}));
|
|
2513
|
-
} else if (part.type === "tool-approval-response") {
|
|
2514
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2515
|
-
type: "tool-approval-response",
|
|
2516
|
-
approvalId: part.approvalId,
|
|
2517
|
-
approved: part.approved,
|
|
2518
|
-
...part.reason && { reason: part.reason }
|
|
2519
|
-
}));
|
|
2520
|
-
} else if (part.type === "custom") {
|
|
2521
|
-
const provider = providerEnvelope(part.providerMetadata);
|
|
2522
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2523
|
-
type: "provider",
|
|
2524
|
-
envelope: {
|
|
2525
|
-
schemaVersion: 1,
|
|
2526
|
-
provider: "ai-sdk-custom",
|
|
2527
|
-
data: { kind: part.kind, ...provider && { provider: provider.data } }
|
|
2528
|
-
}
|
|
2529
|
-
}));
|
|
2530
|
-
} else if (part.type === "raw") {
|
|
2531
|
-
parts.push(AgentMessagePartSchema2.parse({
|
|
2532
|
-
type: "provider",
|
|
2533
|
-
envelope: {
|
|
2534
|
-
schemaVersion: 1,
|
|
2535
|
-
provider: "ai-sdk-raw",
|
|
2536
|
-
data: { value: jsonValue(part.rawValue) }
|
|
2537
|
-
}
|
|
2538
|
-
}));
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
async function applyFinishStep(execution, scope, part) {
|
|
2542
|
-
if (part.type !== "finish-step")
|
|
2543
|
-
return;
|
|
2544
|
-
await releaseStepText(execution);
|
|
2545
|
-
await recordStepSpend(execution, {
|
|
2546
|
-
phase: "step",
|
|
2547
|
-
part,
|
|
2548
|
-
attempt: scope.providerAttempt,
|
|
2549
|
-
selectedModel: scope.selectedModel,
|
|
2550
|
-
ledger: scope.ledger
|
|
2551
|
-
});
|
|
2552
|
-
await execution.operationLifecycle.finish(part.finishReason === "error" ? "failed" : "completed");
|
|
2553
|
-
execution.state.step += 1;
|
|
2554
|
-
}
|
|
2555
|
-
async function releaseStepText(execution) {
|
|
2556
|
-
const { state } = execution;
|
|
2557
|
-
const { text, toolFailed } = state.stepGuard;
|
|
2558
|
-
state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
|
|
2559
|
-
if (text.length === 0 || toolFailed)
|
|
2560
|
-
return;
|
|
2561
|
-
appendText(state.parts, text);
|
|
2562
|
-
if (state.firstOutputAt === undefined)
|
|
2563
|
-
state.firstOutputAt = performance.now();
|
|
2564
|
-
await execution.operationLifecycle.firstOutput();
|
|
2565
|
-
const { publish, now } = execution.dependencies;
|
|
2566
|
-
await publish({
|
|
2567
|
-
type: "assistant-delta",
|
|
2568
|
-
...transientHead(execution),
|
|
2569
|
-
textDelta: text,
|
|
2570
|
-
emittedAt: now().toISOString()
|
|
2571
|
-
});
|
|
2572
|
-
}
|
|
2573
|
-
async function applyStreamPart(execution, scope, part) {
|
|
2574
|
-
const { state } = execution;
|
|
2575
|
-
switch (part.type) {
|
|
2576
|
-
case "text-delta":
|
|
2577
|
-
case "reasoning-start":
|
|
2578
|
-
case "reasoning-delta":
|
|
2579
|
-
case "reasoning-end":
|
|
2580
|
-
await applyTextPart(execution, part);
|
|
2581
|
-
break;
|
|
2582
|
-
case "tool-call":
|
|
2583
|
-
case "tool-result":
|
|
2584
|
-
case "tool-error":
|
|
2585
|
-
case "tool-output-denied":
|
|
2586
|
-
await applyToolPart(execution, part);
|
|
2587
|
-
break;
|
|
2588
|
-
case "source":
|
|
2589
|
-
case "file":
|
|
2590
|
-
case "reasoning-file":
|
|
2591
|
-
case "tool-approval-request":
|
|
2592
|
-
case "tool-approval-response":
|
|
2593
|
-
case "custom":
|
|
2594
|
-
case "raw":
|
|
2595
|
-
await applyRecordedPart(execution, part);
|
|
2596
|
-
break;
|
|
2597
|
-
case "abort":
|
|
2598
|
-
state.terminalReason = "interrupted";
|
|
2599
|
-
break;
|
|
2600
|
-
case "error":
|
|
2601
|
-
state.terminalReason = failureThisRuntimeOwns(part.error) ?? "provider_failure";
|
|
2602
|
-
state.internalCause = part.error;
|
|
2603
|
-
break;
|
|
2604
|
-
case "start-step":
|
|
2605
|
-
state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
|
|
2606
|
-
break;
|
|
2607
|
-
case "finish-step":
|
|
2608
|
-
await applyFinishStep(execution, scope, part);
|
|
2609
|
-
break;
|
|
2610
|
-
case "finish":
|
|
2611
|
-
if (part.finishReason !== "stop") {
|
|
2612
|
-
if (state.terminalReason === "success") {
|
|
2613
|
-
state.terminalReason = part.finishReason === "error" ? "provider_failure" : "provider_stop";
|
|
2614
|
-
state.internalCause ??= { finishReason: part.finishReason };
|
|
2615
|
-
}
|
|
2616
|
-
}
|
|
2617
|
-
state.sawProviderFinish = true;
|
|
2618
|
-
state.modelUsage = mergeModelTotals(normalizeSdkUsage(part.totalUsage), state.modelUsage);
|
|
2619
|
-
state.usage = runUsage(state);
|
|
2620
|
-
break;
|
|
2621
|
-
}
|
|
2622
|
-
}
|
|
2623
|
-
|
|
2624
|
-
// src/agent-runtime/run-tool-progress.ts
|
|
2625
|
-
var TOOL_PROGRESS_MIN_INTERVAL_MS = 250;
|
|
2626
|
-
function finite(value) {
|
|
2627
|
-
return value !== undefined && Number.isFinite(value) ? value : undefined;
|
|
2628
|
-
}
|
|
2629
|
-
function createToolProgressReporter(execution, toolName, callId, signal) {
|
|
2630
|
-
let lastPublishedAt;
|
|
2631
|
-
return async (update) => {
|
|
2632
|
-
if (signal?.aborted || execution.state.settledToolCalls.has(callId))
|
|
2633
|
-
return;
|
|
2634
|
-
const now = execution.dependencies.now();
|
|
2635
|
-
if (lastPublishedAt !== undefined && now.getTime() - lastPublishedAt < TOOL_PROGRESS_MIN_INTERVAL_MS) {
|
|
2636
|
-
return;
|
|
2637
|
-
}
|
|
2638
|
-
lastPublishedAt = now.getTime();
|
|
2639
|
-
const message = update.message?.slice(0, AGENT_TOOL_PROGRESS_MESSAGE_MAX2);
|
|
2640
|
-
const progress = finite(update.progress);
|
|
2641
|
-
const total = finite(update.total);
|
|
2642
|
-
await execution.dependencies.publish({
|
|
2643
|
-
type: "tool-progress",
|
|
2644
|
-
...transientHead(execution),
|
|
2645
|
-
callId,
|
|
2646
|
-
toolName,
|
|
2647
|
-
...message !== undefined && { message },
|
|
2648
|
-
...progress !== undefined && { progress },
|
|
2649
|
-
...total !== undefined && { total },
|
|
2650
|
-
emittedAt: now.toISOString()
|
|
2651
|
-
});
|
|
2652
|
-
};
|
|
2653
|
-
}
|
|
2654
|
-
|
|
2655
|
-
// src/agent-runtime/run-model-attempts.ts
|
|
2656
|
-
function createStopConditions(execution, turn) {
|
|
2657
|
-
const { config, maxSteps } = execution.dependencies;
|
|
2658
|
-
const { state } = execution;
|
|
2659
|
-
const maxStepCondition = stepCountIs(maxSteps);
|
|
2660
|
-
const stopConditions = [
|
|
2661
|
-
async (options) => {
|
|
2662
|
-
const stopped = await maxStepCondition(options);
|
|
2663
|
-
if (stopped && state.terminalPolicyName === undefined)
|
|
2664
|
-
state.terminalPolicyName = "max-steps";
|
|
2665
|
-
return stopped;
|
|
2666
|
-
}
|
|
2667
|
-
];
|
|
2668
|
-
for (const policy of config.loop?.stopPolicies ?? []) {
|
|
2669
|
-
stopConditions.push(async (options) => {
|
|
2670
|
-
const stopped = await policy.when({ ...options, ...turn.runtimeContext });
|
|
2671
|
-
if (stopped && state.terminalPolicyName === undefined)
|
|
2672
|
-
state.terminalPolicyName = policy.name;
|
|
2673
|
-
return stopped;
|
|
2674
|
-
});
|
|
2675
|
-
}
|
|
2676
|
-
return stopConditions;
|
|
2677
|
-
}
|
|
2678
|
-
async function takeInjectedMessages(context) {
|
|
2679
|
-
const { execution, turn, loop } = context;
|
|
2680
|
-
const { state } = execution;
|
|
2681
|
-
const taken = execution.dependencies.injection?.take(execution.input.key, state.run.id) ?? [];
|
|
2682
|
-
if (taken.length === 0)
|
|
2683
|
-
return [];
|
|
2684
|
-
loop.takenThisAttempt.push(...taken);
|
|
2685
|
-
const messages = [];
|
|
2686
|
-
for (const entry of taken) {
|
|
2687
|
-
messages.push(...await turn.projection.projectInputs([entry.input]));
|
|
2688
|
-
const ids = state.absorbed.get(entry.runId) ?? [];
|
|
2689
|
-
ids.push(entry.input.id);
|
|
2690
|
-
state.absorbed.set(entry.runId, ids);
|
|
2691
|
-
}
|
|
2692
|
-
return messages;
|
|
2693
|
-
}
|
|
2694
|
-
async function prepareAttemptStep(context, attempt, options) {
|
|
2695
|
-
const { execution, turn, loop, ledger } = context;
|
|
2696
|
-
const { config, generateId } = execution.dependencies;
|
|
2697
|
-
const { state } = execution;
|
|
2698
|
-
const previousStep = options.steps.at(-1);
|
|
2699
|
-
if (previousStep) {
|
|
2700
|
-
state.lastPromptTokens = normalizeStepUsage(state.selectedModel, previousStep.usage, previousStep.providerMetadata).inputTokens;
|
|
2701
|
-
}
|
|
2702
|
-
const prepared = await config.loop?.prepareStep?.({
|
|
2703
|
-
...options,
|
|
2704
|
-
...turn.runtimeContext
|
|
2705
|
-
});
|
|
2706
|
-
const injected = await takeInjectedMessages(context);
|
|
2707
|
-
const preparedStep = injected.length === 0 ? prepared : {
|
|
2708
|
-
...prepared,
|
|
2709
|
-
messages: [...prepared?.messages ?? options.messages, ...injected]
|
|
2710
|
-
};
|
|
2711
|
-
const providerMessages = preparedStep?.messages ?? options.messages;
|
|
2712
|
-
const model = await execution.operationLifecycle.prepareModel(execution.invocation ? execution.invocation.wrap(turn.selectedModel, options.stepNumber, preparedStep?.model) : preparedStep?.model ?? turn.selectedModel.model, options.stepNumber, generateId());
|
|
2713
|
-
const override = preparedStep;
|
|
2714
|
-
if (override?.instructions !== undefined)
|
|
2715
|
-
loop.instructionsOverride = override.instructions;
|
|
2716
|
-
else if (override?.system !== undefined)
|
|
2717
|
-
loop.instructionsOverride = override.system;
|
|
2718
|
-
await ledger.recordRequest({
|
|
2719
|
-
stepNumber: options.stepNumber,
|
|
2720
|
-
attempt: attempt.providerAttempt,
|
|
2721
|
-
instructions: loop.instructionsOverride ?? turn.projection.withCarriedSystem(turn.prompt.instructions),
|
|
2722
|
-
messages: providerMessages
|
|
2723
|
-
});
|
|
2724
|
-
return { ...preparedStep, model };
|
|
2725
|
-
}
|
|
2726
|
-
function runToolDurability(context, toolName, toolCallId, signal) {
|
|
2727
|
-
const { config } = context.execution.dependencies;
|
|
2728
|
-
const { state } = context.execution;
|
|
2729
|
-
const port = config.durability;
|
|
2730
|
-
if (typeof port === "function")
|
|
2731
|
-
return port({
|
|
2732
|
-
store: config.store,
|
|
2733
|
-
conversationId: state.run.conversationId,
|
|
2734
|
-
runId: state.run.id,
|
|
2735
|
-
toolName,
|
|
2736
|
-
toolCallId,
|
|
2737
|
-
signal
|
|
2738
|
-
});
|
|
2739
|
-
return createLocalStepDurability2({
|
|
2740
|
-
store: config.store,
|
|
2741
|
-
conversationId: state.run.conversationId,
|
|
2742
|
-
runId: JSON.stringify([state.run.id, toolName, toolCallId]),
|
|
2743
|
-
signal
|
|
2744
|
-
});
|
|
2745
|
-
}
|
|
2746
|
-
function startAttemptStream(context, attempt, stopConditions, attemptSignal) {
|
|
2747
|
-
const { execution, turn } = context;
|
|
2748
|
-
const { config } = execution.dependencies;
|
|
2749
|
-
const { idleDeadline, operationLifecycle } = execution;
|
|
2750
|
-
const { tools } = turn;
|
|
2751
|
-
return streamAgentTextBoundary({
|
|
2752
|
-
model: turn.selectedModel.model,
|
|
2753
|
-
tools,
|
|
2754
|
-
toolsContext: Object.fromEntries(Object.entries(tools).filter(([, tool]) => tool.contextSchema === undefined).map(([toolName]) => [
|
|
2755
|
-
toolName,
|
|
2756
|
-
createRuntimeToolContext((toolCallId, signal) => ({
|
|
2757
|
-
...config.durability && {
|
|
2758
|
-
durability: runToolDurability(context, toolName, toolCallId, signal)
|
|
2759
|
-
},
|
|
2760
|
-
reportProgress: createToolProgressReporter(execution, toolName, toolCallId, signal)
|
|
2761
|
-
}))
|
|
2762
|
-
])),
|
|
2763
|
-
instructions: turn.projection.withCarriedSystem(turn.prompt.instructions),
|
|
2764
|
-
messages: turn.history,
|
|
2765
|
-
abortSignal: attemptSignal,
|
|
2766
|
-
maxRetries: 0,
|
|
2767
|
-
stopWhen: stopConditions,
|
|
2768
|
-
onLanguageModelCallStart: (event) => {
|
|
2769
|
-
idleDeadline.start();
|
|
2770
|
-
operationLifecycle.noteProviderCall(event.callId);
|
|
2771
|
-
},
|
|
2772
|
-
onLanguageModelCallEnd: () => idleDeadline.stop(),
|
|
2773
|
-
onToolExecutionStart: () => idleDeadline.suspend(),
|
|
2774
|
-
onToolExecutionEnd: () => idleDeadline.resume(),
|
|
2775
|
-
repairToolCall: deferredToolRepair(config.loop?.prepareStep),
|
|
2776
|
-
...turn.toolApproval && {
|
|
2777
|
-
toolApproval: turn.toolApproval,
|
|
2778
|
-
runtimeContext: execution.input.context
|
|
2779
|
-
},
|
|
2780
|
-
...config.loop?.toolApprovalSecret && {
|
|
2781
|
-
experimental_toolApprovalSecret: config.loop.toolApprovalSecret
|
|
2782
|
-
},
|
|
2783
|
-
prepareStep: (options) => prepareAttemptStep(context, attempt, options)
|
|
2784
|
-
});
|
|
2785
|
-
}
|
|
2786
|
-
async function drainAbandonedPart(context, attempt, part) {
|
|
2787
|
-
if (part.type !== "finish-step")
|
|
2788
|
-
return;
|
|
2789
|
-
await recordStepSpend(context.execution, {
|
|
2790
|
-
phase: "abandoned-attempt",
|
|
2791
|
-
part,
|
|
2792
|
-
attempt: attempt.providerAttempt,
|
|
2793
|
-
selectedModel: context.turn.selectedModel,
|
|
2794
|
-
ledger: context.ledger
|
|
2795
|
-
});
|
|
2796
|
-
}
|
|
2797
|
-
async function retryAfterProviderError(context, attempt, error) {
|
|
2798
|
-
const { execution, loop } = context;
|
|
2799
|
-
const { config, injection } = execution.dependencies;
|
|
2800
|
-
const { state, executionSignal } = execution;
|
|
2801
|
-
const retry = config.loop?.retry;
|
|
2802
|
-
if (!retry || failureThisRuntimeOwns(error) !== undefined)
|
|
2803
|
-
return false;
|
|
2804
|
-
const invokedTool = state.parts.slice(attempt.attemptPartStart).some((candidate) => candidate.type === "tool-call");
|
|
2805
|
-
const decision = invokedTool ? { retry: false, delayMs: 0 } : await recordAgentRetryDecision2({
|
|
2806
|
-
store: config.store,
|
|
2807
|
-
conversationId: state.run.conversationId,
|
|
2808
|
-
attempt: loop.retryAttempt,
|
|
2809
|
-
failure: classifyProviderFailure2(error),
|
|
2810
|
-
policy: retry
|
|
2811
|
-
});
|
|
2812
|
-
if (!decision.retry)
|
|
2813
|
-
return false;
|
|
2814
|
-
await execution.operationLifecycle.finish("failed");
|
|
2815
|
-
state.parts.splice(attempt.attemptPartStart);
|
|
2816
|
-
for (const entry of loop.takenThisAttempt) {
|
|
2817
|
-
injection?.offer(execution.input.key, entry);
|
|
2818
|
-
const ids = state.absorbed.get(entry.runId);
|
|
2819
|
-
if (ids) {
|
|
2820
|
-
const kept = ids.filter((id) => id !== entry.input.id);
|
|
2821
|
-
if (kept.length === 0)
|
|
2822
|
-
state.absorbed.delete(entry.runId);
|
|
2823
|
-
else
|
|
2824
|
-
state.absorbed.set(entry.runId, kept);
|
|
2825
|
-
}
|
|
2826
|
-
}
|
|
2827
|
-
loop.takenThisAttempt = [];
|
|
2828
|
-
await checkpoint(execution);
|
|
2829
|
-
state.eventsSinceCheckpoint = 0;
|
|
2830
|
-
if (decision.delayMs > 0) {
|
|
2831
|
-
await delay(decision.delayMs, undefined, { signal: executionSignal });
|
|
2832
|
-
}
|
|
2833
|
-
loop.retryAttempt += 1;
|
|
2834
|
-
await config.store.appendEvent({
|
|
2835
|
-
conversationId: state.run.conversationId,
|
|
2836
|
-
kind: "retry/started",
|
|
2837
|
-
payload: { attempt: loop.retryAttempt }
|
|
2838
|
-
});
|
|
2839
|
-
attempt.retrying = true;
|
|
2840
|
-
attempt.draining = true;
|
|
2841
|
-
return true;
|
|
2842
|
-
}
|
|
2843
|
-
async function consumeAttempt(context, attempt, stream) {
|
|
2844
|
-
const { execution, turn, ledger } = context;
|
|
2845
|
-
const { checkpointEveryEvents } = execution.dependencies;
|
|
2846
|
-
const { state, idleDeadline, operationLifecycle } = execution;
|
|
2847
|
-
const scope = {
|
|
2848
|
-
selectedModel: turn.selectedModel,
|
|
2849
|
-
ledger,
|
|
2850
|
-
providerAttempt: attempt.providerAttempt
|
|
2851
|
-
};
|
|
2852
|
-
for await (const part of ownedProviderStream({
|
|
2853
|
-
stream,
|
|
2854
|
-
abort: () => attempt.attemptAbort.abort(new Error("Agent runtime released provider stream")),
|
|
2855
|
-
onCleanupFailure: (error) => {
|
|
2856
|
-
state.providerStreamCleanupFailure = error;
|
|
2857
|
-
}
|
|
2858
|
-
})) {
|
|
2859
|
-
idleDeadline.touch();
|
|
2860
|
-
if (attempt.draining) {
|
|
2861
|
-
await drainAbandonedPart(context, attempt, part);
|
|
2862
|
-
continue;
|
|
2863
|
-
}
|
|
2864
|
-
state.eventsSinceCheckpoint += 1;
|
|
2865
|
-
if (part.type === "error" && await retryAfterProviderError(context, attempt, part.error)) {
|
|
2866
|
-
continue;
|
|
2867
|
-
}
|
|
2868
|
-
const held = part.type === "text-delta" && context.execution.dependencies.config.loop?.stepBarriers?.stepText === "after-tools";
|
|
2869
|
-
if (isOutputPart(part) && !held) {
|
|
2870
|
-
if (state.firstOutputAt === undefined)
|
|
2871
|
-
state.firstOutputAt = performance.now();
|
|
2872
|
-
await operationLifecycle.firstOutput();
|
|
2873
|
-
}
|
|
2874
|
-
await applyStreamPart(execution, scope, part);
|
|
2875
|
-
if (TOOL_STATUS_PARTS.includes(part.type)) {
|
|
2876
|
-
state.eventsSinceCheckpoint = 0;
|
|
2877
|
-
continue;
|
|
2878
|
-
}
|
|
2879
|
-
const structuralBoundary = STRUCTURAL_BOUNDARY_PARTS.includes(part.type);
|
|
2880
|
-
if (structuralBoundary || state.eventsSinceCheckpoint >= checkpointEveryEvents) {
|
|
2881
|
-
await checkpoint(execution);
|
|
2882
|
-
state.eventsSinceCheckpoint = 0;
|
|
2883
|
-
if (part.type === "finish-step")
|
|
2884
|
-
operationLifecycle.checkpointStep(state.step - 1);
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
}
|
|
2888
|
-
async function runModelAttempts(execution, turn) {
|
|
2889
|
-
const { config, publish, now } = execution.dependencies;
|
|
2890
|
-
const { state } = execution;
|
|
2891
|
-
const stopConditions = createStopConditions(execution, turn);
|
|
2892
|
-
const loop = {
|
|
2893
|
-
retryAttempt: 1,
|
|
2894
|
-
takenThisAttempt: [],
|
|
2895
|
-
instructionsOverride: undefined
|
|
2896
|
-
};
|
|
2897
|
-
const ledger = await createRunProviderLedger({
|
|
2898
|
-
store: config.store,
|
|
2899
|
-
state,
|
|
2900
|
-
selectedModel: turn.selectedModel,
|
|
2901
|
-
audited: execution.invocation !== undefined
|
|
2902
|
-
});
|
|
2903
|
-
const context = { execution, turn, loop, ledger };
|
|
2904
|
-
for (;; ) {
|
|
2905
|
-
const attempt = {
|
|
2906
|
-
providerAttempt: loop.retryAttempt,
|
|
2907
|
-
attemptPartStart: state.parts.length,
|
|
2908
|
-
retrying: false,
|
|
2909
|
-
draining: false,
|
|
2910
|
-
attemptAbort: new AbortController
|
|
2911
|
-
};
|
|
2912
|
-
const link = linkAbortSignals(execution.executionSignal, attempt.attemptAbort.signal);
|
|
2913
|
-
try {
|
|
2914
|
-
const result = startAttemptStream(context, attempt, stopConditions, link.signal);
|
|
2915
|
-
await consumeAttempt(context, attempt, result.stream);
|
|
2916
|
-
} finally {
|
|
2917
|
-
link.release();
|
|
2918
|
-
}
|
|
2919
|
-
if (!attempt.retrying)
|
|
2920
|
-
break;
|
|
2921
|
-
state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
|
|
2922
|
-
await publish({
|
|
2923
|
-
type: "attempt-reset",
|
|
2924
|
-
conversationId: state.run.conversationId,
|
|
2925
|
-
runId: state.run.id,
|
|
2926
|
-
runtimeEpoch: execution.dependencies.runtimeEpoch,
|
|
2927
|
-
sequence: transientSequence(state),
|
|
2928
|
-
attempt: loop.retryAttempt,
|
|
2929
|
-
emittedAt: now().toISOString()
|
|
2930
|
-
});
|
|
2931
|
-
}
|
|
2932
|
-
}
|
|
2933
|
-
|
|
2934
|
-
// src/agent-runtime/run-terminal.ts
|
|
2935
|
-
async function settleStreamOutcome(execution) {
|
|
2936
|
-
const { config, now } = execution.dependencies;
|
|
2937
|
-
const { state, executionSignal } = execution;
|
|
2938
|
-
await execution.operationLifecycle.finish(executionSignal.aborted ? "cancelled" : state.terminalReason === "provider_failure" ? "failed" : "completed");
|
|
2939
|
-
if (state.terminalPolicyName !== undefined)
|
|
2940
|
-
state.terminalReason = "policy_stop";
|
|
2941
|
-
if (executionSignal.aborted)
|
|
2942
|
-
state.terminalReason = abortTerminalReason(executionSignal);
|
|
2943
|
-
const awaitsApproval = state.parts.some((part) => part.type === "tool-approval-request");
|
|
2944
|
-
if (!awaitsApproval && config.protocol.acceptTerminal && (state.terminalReason === "success" || state.terminalReason === "policy_stop" || state.terminalReason === "provider_stop")) {
|
|
2945
|
-
const candidate = AgentMessageSchema2.parse({
|
|
2946
|
-
...state.assistant,
|
|
2947
|
-
status: assistantStatus(state.terminalReason),
|
|
2948
|
-
parts: state.parts,
|
|
2949
|
-
updatedAt: now().toISOString()
|
|
2950
|
-
});
|
|
2951
|
-
if (!await config.protocol.acceptTerminal({
|
|
2952
|
-
message: candidate,
|
|
2953
|
-
reason: state.terminalReason,
|
|
2954
|
-
...state.terminalPolicyName && { policyName: state.terminalPolicyName }
|
|
2955
|
-
})) {
|
|
2956
|
-
state.terminalReason = "output_rejected";
|
|
2957
|
-
state.internalCause = new Error("Agent terminal output was rejected by the protocol");
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
}
|
|
2961
|
-
function emitSpend(execution, report) {
|
|
2962
|
-
const { config, generateId, now } = execution.dependencies;
|
|
2963
|
-
const { state, trace, runStartedAt } = execution;
|
|
2964
|
-
config.observe?.emit({
|
|
2965
|
-
schemaVersion: 1,
|
|
2966
|
-
eventId: report.eventId,
|
|
2967
|
-
type: "run-terminal",
|
|
2968
|
-
conversationId: state.run.conversationId,
|
|
2969
|
-
runId: state.run.id,
|
|
2970
|
-
traceId: trace?.traceId ?? generateId(),
|
|
2971
|
-
spanId: trace?.spanId ?? generateId(),
|
|
2972
|
-
...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
|
|
2973
|
-
state: report.state,
|
|
2974
|
-
terminalReason: report.reason,
|
|
2975
|
-
...state.selectedModel && { modelId: state.selectedModel.descriptor.modelId },
|
|
2976
|
-
durationMs: performance.now() - runStartedAt,
|
|
2977
|
-
usage: report.usage,
|
|
2978
|
-
...state.internalCause !== undefined && { internalCause: state.internalCause },
|
|
2979
|
-
...state.firstOutputAt !== undefined && { ttftMs: state.firstOutputAt - runStartedAt },
|
|
2980
|
-
emittedAt: now().toISOString()
|
|
2981
|
-
});
|
|
2982
|
-
}
|
|
2983
|
-
async function stopChildrenAfterExplicitStop(execution, committedByCaller) {
|
|
2984
|
-
const { config } = execution.dependencies;
|
|
2985
|
-
const { state } = execution;
|
|
2986
|
-
if (config.children && committedByCaller && (state.terminalReason === "interrupted" || state.terminalReason === "cancelled" || state.terminalReason === "timeout" || state.terminalReason === "shutdown")) {
|
|
2987
|
-
try {
|
|
2988
|
-
await config.children.stopChildren(state.run.conversationId);
|
|
2989
|
-
} catch (error) {
|
|
2990
|
-
state.internalCause ??= error;
|
|
2991
|
-
}
|
|
2992
|
-
}
|
|
2993
|
-
}
|
|
2994
|
-
async function commitRunTerminal(execution) {
|
|
2995
|
-
const { config, publish, runtimeEpoch, now } = execution.dependencies;
|
|
2996
|
-
const { state, runStartedAt } = execution;
|
|
2997
|
-
state.assistant = AgentMessageSchema2.parse({
|
|
2998
|
-
...state.assistant,
|
|
2999
|
-
status: assistantStatus(state.terminalReason),
|
|
3000
|
-
parts: state.parts,
|
|
3001
|
-
updatedAt: now().toISOString()
|
|
3002
|
-
});
|
|
3003
|
-
const spent = statedUsage(state.usage);
|
|
3004
|
-
const unsettledEventId = (version) => agentDurableEventId2("terminal", `${state.run.id}:${runtimeEpoch}`, version);
|
|
3005
|
-
let terminal;
|
|
3006
|
-
try {
|
|
3007
|
-
terminal = await commitAgentRunTerminal({
|
|
3008
|
-
store: config.store,
|
|
3009
|
-
runtimeEpoch,
|
|
3010
|
-
candidate: {
|
|
3011
|
-
run: state.run,
|
|
3012
|
-
assistant: state.assistant,
|
|
3013
|
-
reason: state.terminalReason,
|
|
3014
|
-
...state.terminalPolicyName && { policyName: state.terminalPolicyName },
|
|
3015
|
-
usage: spent,
|
|
3016
|
-
...state.absorbed.size > 0 && runStateForTerminalReason2(state.terminalReason) === "completed" && {
|
|
3017
|
-
absorb: [...state.absorbed].map(([runId, inputMessageIds]) => ({
|
|
3018
|
-
runId,
|
|
3019
|
-
inputMessageIds
|
|
3020
|
-
}))
|
|
3021
|
-
}
|
|
3022
|
-
},
|
|
3023
|
-
now
|
|
3024
|
-
});
|
|
3025
|
-
} catch (error) {
|
|
3026
|
-
emitSpend(execution, {
|
|
3027
|
-
eventId: unsettledEventId(state.observedVersion),
|
|
3028
|
-
state: state.run.state,
|
|
3029
|
-
reason: state.terminalReason,
|
|
3030
|
-
usage: spent
|
|
3031
|
-
});
|
|
3032
|
-
if (error instanceof AgentRuntimeConflictError2)
|
|
3033
|
-
throw error;
|
|
3034
|
-
throw new AgentRunUnsettledError2(state.run, runtimeEpoch, error);
|
|
3035
|
-
}
|
|
3036
|
-
state.observedVersion = terminal.snapshotVersion;
|
|
3037
|
-
state.run = terminal.run;
|
|
3038
|
-
state.assistant = terminal.assistant;
|
|
3039
|
-
state.terminalReason = terminal.reason;
|
|
3040
|
-
state.terminalPolicyName = terminal.policyName;
|
|
3041
|
-
const terminalMetrics = terminal.committedByCaller ? {
|
|
3042
|
-
partial: !state.sawProviderFinish,
|
|
3043
|
-
durationMs: performance.now() - runStartedAt,
|
|
3044
|
-
usage: spent,
|
|
3045
|
-
...state.firstOutputAt !== undefined && {
|
|
3046
|
-
ttftMs: state.firstOutputAt - runStartedAt
|
|
3047
|
-
}
|
|
3048
|
-
} : undefined;
|
|
3049
|
-
await stopChildrenAfterExplicitStop(execution, terminal.committedByCaller);
|
|
3050
|
-
emitSpend(execution, {
|
|
3051
|
-
eventId: terminal.committedByCaller ? agentDurableEventId2("terminal", state.run.id, state.observedVersion) : unsettledEventId(state.observedVersion),
|
|
3052
|
-
state: state.run.state,
|
|
3053
|
-
reason: state.terminalReason,
|
|
3054
|
-
usage: spent
|
|
3055
|
-
});
|
|
3056
|
-
for (const settled of terminal.absorbed ?? []) {
|
|
3057
|
-
await publish({
|
|
3058
|
-
type: "run-state",
|
|
3059
|
-
eventId: agentDurableEventId2("run-state", settled.id, state.observedVersion),
|
|
3060
|
-
conversationId: settled.conversationId,
|
|
3061
|
-
runId: settled.id,
|
|
3062
|
-
snapshotVersion: state.observedVersion,
|
|
3063
|
-
state: settled.state,
|
|
3064
|
-
emittedAt: now().toISOString()
|
|
3065
|
-
});
|
|
3066
|
-
}
|
|
3067
|
-
if (terminalMetrics) {
|
|
3068
|
-
await publish({
|
|
3069
|
-
type: "terminal",
|
|
3070
|
-
eventId: agentDurableEventId2("terminal", state.run.id, state.observedVersion),
|
|
3071
|
-
conversationId: state.run.conversationId,
|
|
3072
|
-
runId: state.run.id,
|
|
3073
|
-
snapshotVersion: state.observedVersion,
|
|
3074
|
-
reason: state.terminalReason,
|
|
3075
|
-
...state.terminalPolicyName && { policyName: state.terminalPolicyName },
|
|
3076
|
-
message: state.assistant,
|
|
3077
|
-
metrics: terminalMetrics,
|
|
3078
|
-
emittedAt: now().toISOString()
|
|
3079
|
-
});
|
|
3080
|
-
}
|
|
3081
|
-
return {
|
|
3082
|
-
run: state.run,
|
|
3083
|
-
message: state.assistant,
|
|
3084
|
-
reason: state.terminalReason,
|
|
3085
|
-
snapshotVersion: state.observedVersion,
|
|
3086
|
-
...terminalMetrics && { metrics: terminalMetrics },
|
|
3087
|
-
...state.terminalPolicyName && { policyName: state.terminalPolicyName }
|
|
3088
|
-
};
|
|
3089
|
-
}
|
|
3090
|
-
|
|
3091
|
-
// src/agent-runtime/run-prompt-history.ts
|
|
3092
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
3093
|
-
|
|
3094
|
-
// src/agent-runtime/state-slots.ts
|
|
3095
|
-
import { z as z4 } from "zod";
|
|
3096
|
-
function defineStateSlot2(input) {
|
|
3097
|
-
if (input.name.length === 0)
|
|
3098
|
-
throw new TypeError("State slot name must not be empty");
|
|
3099
|
-
const version = input.version ?? 1;
|
|
3100
|
-
if (!Number.isInteger(version) || version < 1) {
|
|
3101
|
-
throw new TypeError("State slot version must be a positive integer");
|
|
3102
|
-
}
|
|
3103
|
-
return {
|
|
3104
|
-
name: input.name,
|
|
3105
|
-
version,
|
|
3106
|
-
schema: input.schema,
|
|
3107
|
-
...input.description && { description: input.description }
|
|
3108
|
-
};
|
|
3109
|
-
}
|
|
3110
|
-
var StateSetPayloadSchema = z4.object({
|
|
3111
|
-
name: z4.string().min(1),
|
|
3112
|
-
version: z4.int().positive(),
|
|
3113
|
-
value: z4.json(),
|
|
3114
|
-
actor: z4.enum(["agent", "human", "system"])
|
|
3115
|
-
}).strict();
|
|
3116
|
-
function slotRegistry(definitions) {
|
|
3117
|
-
const result = new Map;
|
|
3118
|
-
for (const definition of definitions) {
|
|
3119
|
-
if (result.has(definition.name))
|
|
3120
|
-
throw new TypeError(`Duplicate state slot: ${definition.name}`);
|
|
3121
|
-
result.set(definition.name, definition);
|
|
3122
|
-
}
|
|
3123
|
-
return result;
|
|
3124
|
-
}
|
|
3125
|
-
function createAgentStateSlotStore2(input) {
|
|
3126
|
-
const definitions = slotRegistry(input.definitions);
|
|
3127
|
-
const set = async (request) => {
|
|
3128
|
-
const definition = definitions.get(request.name);
|
|
3129
|
-
if (!definition)
|
|
3130
|
-
throw new TypeError(`Unknown state slot: ${request.name}`);
|
|
3131
|
-
const value = definition.schema.parse(request.value);
|
|
3132
|
-
const payload = StateSetPayloadSchema.parse({
|
|
3133
|
-
name: definition.name,
|
|
3134
|
-
version: definition.version,
|
|
3135
|
-
value,
|
|
3136
|
-
actor: request.actor
|
|
3137
|
-
});
|
|
3138
|
-
const event = await input.store.appendEvent({
|
|
3139
|
-
conversationId: request.conversationId,
|
|
3140
|
-
kind: "state/set",
|
|
3141
|
-
payload
|
|
3142
|
-
});
|
|
3143
|
-
return {
|
|
3144
|
-
name: definition.name,
|
|
3145
|
-
version: definition.version,
|
|
3146
|
-
value,
|
|
3147
|
-
updatedAt: event.occurredAt,
|
|
3148
|
-
seq: event.seq
|
|
3149
|
-
};
|
|
3150
|
-
};
|
|
3151
|
-
const list = async (conversationId) => {
|
|
3152
|
-
const values = new Map;
|
|
3153
|
-
let cursor = 1;
|
|
3154
|
-
for (;; ) {
|
|
3155
|
-
const page = await input.store.readEvents({
|
|
3156
|
-
conversationId,
|
|
3157
|
-
fromSeq: cursor,
|
|
3158
|
-
limit: 1000
|
|
3159
|
-
});
|
|
3160
|
-
for (const event of page.items) {
|
|
3161
|
-
if (event.kind !== "state/set")
|
|
3162
|
-
continue;
|
|
3163
|
-
const payload = StateSetPayloadSchema.parse(event.payload);
|
|
3164
|
-
const definition = definitions.get(payload.name);
|
|
3165
|
-
if (!definition || definition.version !== payload.version)
|
|
3166
|
-
continue;
|
|
3167
|
-
values.set(payload.name, {
|
|
3168
|
-
name: payload.name,
|
|
3169
|
-
version: payload.version,
|
|
3170
|
-
value: definition.schema.parse(payload.value),
|
|
3171
|
-
updatedAt: event.occurredAt,
|
|
3172
|
-
seq: event.seq
|
|
3173
|
-
});
|
|
3174
|
-
}
|
|
3175
|
-
if (page.nextSeq === undefined)
|
|
3176
|
-
break;
|
|
3177
|
-
cursor = page.nextSeq;
|
|
3178
|
-
}
|
|
3179
|
-
return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
3180
|
-
};
|
|
3181
|
-
const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
|
|
3182
|
-
return { set, get, list };
|
|
3183
|
-
}
|
|
3184
|
-
function renderAgentStateSlots2(values) {
|
|
3185
|
-
if (values.length === 0)
|
|
3186
|
-
return;
|
|
3187
|
-
return [
|
|
3188
|
-
"Durable conversation state (authoritative; newer than compacted history):",
|
|
3189
|
-
...values.map((slot) => `${slot.name}: ${JSON.stringify(slot.value)}`)
|
|
3190
|
-
].join(`
|
|
3191
|
-
`);
|
|
3192
|
-
}
|
|
3193
|
-
var agentGoalStateSlot2 = defineStateSlot2({
|
|
3194
|
-
name: "goal",
|
|
3195
|
-
description: "The durable objective and lifecycle of this conversation.",
|
|
3196
|
-
schema: z4.object({
|
|
3197
|
-
objective: z4.string().min(1),
|
|
3198
|
-
status: z4.enum(["active", "complete", "blocked"])
|
|
3199
|
-
}).strict()
|
|
3200
|
-
});
|
|
3201
|
-
var agentTodoStateSlot2 = defineStateSlot2({
|
|
3202
|
-
name: "todo",
|
|
3203
|
-
description: "The durable ordered work plan for this conversation.",
|
|
3204
|
-
schema: z4.object({
|
|
3205
|
-
items: z4.array(z4.object({
|
|
3206
|
-
step: z4.string().min(1),
|
|
3207
|
-
status: z4.enum(["pending", "in_progress", "completed"])
|
|
3208
|
-
}).strict())
|
|
3209
|
-
}).strict()
|
|
3210
|
-
});
|
|
3211
|
-
|
|
3212
|
-
// src/agent-runtime/run-prompt-history.ts
|
|
3213
|
-
function snapshotForRunPrompt(snapshot, runId) {
|
|
3214
|
-
const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
|
|
3215
|
-
if (runIndex < 0)
|
|
3216
|
-
throw new AgentRuntimeConflictError2("prompt run lookup");
|
|
3217
|
-
const ownedIds = new Set(snapshot.runs.flatMap((candidate) => [
|
|
3218
|
-
...candidate.inputMessageIds,
|
|
3219
|
-
candidate.assistantMessageId
|
|
3220
|
-
]));
|
|
3221
|
-
const eligibleIds = new Set(snapshot.runs.slice(0, runIndex + 1).flatMap((candidate) => [...candidate.inputMessageIds, candidate.assistantMessageId]));
|
|
3222
|
-
return AgentSnapshotSchema2.parse({
|
|
3223
|
-
...snapshot,
|
|
3224
|
-
messages: snapshot.messages.filter((message) => !ownedIds.has(message.id) || eligibleIds.has(message.id))
|
|
3225
|
-
});
|
|
3226
|
-
}
|
|
3227
|
-
var USER_INSTRUCTION_SEED_KEY = "prompt.user-instructions";
|
|
3228
|
-
function seededInstructionMessage(input) {
|
|
3229
|
-
return AgentMessageSchema2.parse({
|
|
3230
|
-
schemaVersion: 1,
|
|
3231
|
-
id: createHash2("sha256").update(`${input.conversationId}\x00${input.seedKey}\x00${input.index}`).digest("hex"),
|
|
3232
|
-
conversationId: input.conversationId,
|
|
3233
|
-
role: "user",
|
|
3234
|
-
status: "committed",
|
|
3235
|
-
parts: [{ type: "text", text: input.text }],
|
|
3236
|
-
createdAt: input.createdAt,
|
|
3237
|
-
updatedAt: input.createdAt
|
|
3238
|
-
});
|
|
3239
|
-
}
|
|
3240
|
-
async function loadDurableSystem(config, conversationId) {
|
|
3241
|
-
if (config.stateSlots && config.stateSlots.length > 0) {
|
|
3242
|
-
const slotValues = await createAgentStateSlotStore2({
|
|
3243
|
-
store: config.store,
|
|
3244
|
-
definitions: config.stateSlots
|
|
3245
|
-
}).list(conversationId);
|
|
3246
|
-
const renderedSlots = renderAgentStateSlots2(slotValues);
|
|
3247
|
-
if (renderedSlots)
|
|
3248
|
-
return [renderedSlots];
|
|
3249
|
-
}
|
|
3250
|
-
return [];
|
|
3251
|
-
}
|
|
3252
|
-
function detailedProjection(config, source) {
|
|
3253
|
-
return projectAgentHistoryDetailed2(source, {
|
|
3254
|
-
...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
|
|
3255
|
-
...config.history?.unresolvedFile && {
|
|
3256
|
-
unresolvedFile: config.history.unresolvedFile
|
|
3257
|
-
},
|
|
3258
|
-
...config.history?.interruptedAssistant && {
|
|
3259
|
-
interruptedAssistant: config.history.interruptedAssistant
|
|
3260
|
-
},
|
|
3261
|
-
...config.history?.evidencePolicy && {
|
|
3262
|
-
evidencePolicy: config.history.evidencePolicy
|
|
3263
|
-
}
|
|
3264
|
-
});
|
|
3265
|
-
}
|
|
3266
|
-
function createRunHistoryProjection(input) {
|
|
3267
|
-
const { config, durableSystem } = input;
|
|
3268
|
-
let carriedSystem = durableSystem;
|
|
3269
|
-
return {
|
|
3270
|
-
async projectHistory(source) {
|
|
3271
|
-
if (config.history?.project)
|
|
3272
|
-
return config.history.project(source.messages);
|
|
3273
|
-
const detailed = await detailedProjection(config, source.messages);
|
|
3274
|
-
const run = input.currentRun();
|
|
3275
|
-
for (const decision of detailed.decisions) {
|
|
3276
|
-
if (decision.action === "omitted" && run.inputMessageIds.includes(decision.messageId) && source.messages.some((message) => message.id === decision.messageId && message.role === "tool")) {
|
|
3277
|
-
throw new Error(`Invalid approval continuation ${decision.messageId}: ${decision.reason}`);
|
|
3278
|
-
}
|
|
3279
|
-
}
|
|
3280
|
-
carriedSystem = [...durableSystem, ...detailed.system];
|
|
3281
|
-
return [...detailed.messages];
|
|
3282
|
-
},
|
|
3283
|
-
async projectInputs(source) {
|
|
3284
|
-
if (config.history?.project)
|
|
3285
|
-
return config.history.project(source);
|
|
3286
|
-
const detailed = await detailedProjection(config, source);
|
|
3287
|
-
return [...detailed.messages];
|
|
3288
|
-
},
|
|
3289
|
-
withCarriedSystem(instructions) {
|
|
3290
|
-
if (carriedSystem.length === 0)
|
|
3291
|
-
return instructions;
|
|
3292
|
-
const composed = typeof instructions === "string" ? [{ role: "system", content: instructions }] : Array.isArray(instructions) ? instructions : [instructions];
|
|
3293
|
-
return [
|
|
3294
|
-
...composed,
|
|
3295
|
-
...carriedSystem.map((content) => ({ role: "system", content }))
|
|
3296
|
-
];
|
|
3297
|
-
}
|
|
3298
|
-
};
|
|
3299
|
-
}
|
|
3300
|
-
|
|
3301
|
-
// src/agent-runtime/run-turn-preparation.ts
|
|
3302
|
-
async function compactHistory(execution) {
|
|
3303
|
-
const { config, runtimeEpoch, generateId } = execution.dependencies;
|
|
3304
|
-
const { state, operationLifecycle, executionSignal } = execution;
|
|
3305
|
-
const compact = config.history?.compact;
|
|
3306
|
-
if (!compact)
|
|
3307
|
-
return;
|
|
3308
|
-
await operationLifecycle.startCompaction(generateId());
|
|
3309
|
-
let compacted;
|
|
3310
|
-
try {
|
|
3311
|
-
compacted = await compact({
|
|
3312
|
-
conversationId: state.run.conversationId,
|
|
3313
|
-
store: config.store,
|
|
3314
|
-
signal: executionSignal
|
|
3315
|
-
});
|
|
3316
|
-
} catch (error) {
|
|
3317
|
-
const latest = await config.store.loadRun({
|
|
3318
|
-
conversationId: state.run.conversationId,
|
|
3319
|
-
runId: state.run.id
|
|
3320
|
-
});
|
|
3321
|
-
if (latest?.run.ownerId === runtimeEpoch) {
|
|
3322
|
-
state.observedVersion = latest.snapshotVersion;
|
|
3323
|
-
state.run = latest.run;
|
|
3324
|
-
}
|
|
3325
|
-
await operationLifecycle.finish(executionSignal.aborted ? "cancelled" : "failed");
|
|
3326
|
-
throw error;
|
|
3327
|
-
}
|
|
3328
|
-
if (compacted.usage) {
|
|
3329
|
-
await recordStepSpend(execution, {
|
|
3330
|
-
phase: "compaction",
|
|
3331
|
-
usage: compacted.usage,
|
|
3332
|
-
attempt: compacted.attempts
|
|
3333
|
-
});
|
|
3334
|
-
}
|
|
3335
|
-
adoptSnapshot(state, compacted.snapshot);
|
|
3336
|
-
await operationLifecycle.finish("completed");
|
|
3337
|
-
}
|
|
3338
|
-
function createRuntimeContext(execution) {
|
|
3339
|
-
const { runtimeEpoch, config } = execution.dependencies;
|
|
3340
|
-
const { state, executionSignal } = execution;
|
|
3341
|
-
const assertCurrent = async () => {
|
|
3342
|
-
if (executionSignal.aborted)
|
|
3343
|
-
return "run_interrupted";
|
|
3344
|
-
const current = await config.store.loadRun({
|
|
3345
|
-
conversationId: state.run.conversationId,
|
|
3346
|
-
runId: state.run.id
|
|
3347
|
-
});
|
|
3348
|
-
const currentRun = current?.run;
|
|
3349
|
-
if (!currentRun || currentRun.ownerId !== runtimeEpoch)
|
|
3350
|
-
return "stale_run";
|
|
3351
|
-
if (currentRun.fencingToken !== state.run.fencingToken)
|
|
3352
|
-
return "stale_run";
|
|
3353
|
-
if (currentRun.state === "interrupt_requested")
|
|
3354
|
-
return "run_interrupted";
|
|
3355
|
-
if (currentRun.state !== "running")
|
|
3356
|
-
return "stale_run";
|
|
3357
|
-
return;
|
|
3358
|
-
};
|
|
3359
|
-
const toolFenceLifecycle = createAgentToolFenceLifecycle2({
|
|
3360
|
-
runId: state.run.id,
|
|
3361
|
-
assertCurrent,
|
|
3362
|
-
context: () => ({
|
|
3363
|
-
...state.run.fencingToken !== undefined && { fencingToken: state.run.fencingToken }
|
|
3364
|
-
})
|
|
3365
|
-
});
|
|
3366
|
-
return issueRunContext({
|
|
3367
|
-
context: execution.input.context,
|
|
3368
|
-
get run() {
|
|
3369
|
-
return state.run;
|
|
3370
|
-
},
|
|
3371
|
-
signal: executionSignal,
|
|
3372
|
-
toolFenceLifecycle,
|
|
3373
|
-
get contextUsage() {
|
|
3374
|
-
const descriptor = state.selectedModel?.descriptor;
|
|
3375
|
-
if (!descriptor)
|
|
3376
|
-
return;
|
|
3377
|
-
return { usedTokens: state.lastPromptTokens, contextWindow: descriptor.contextWindow };
|
|
3378
|
-
},
|
|
3379
|
-
get selectedModel() {
|
|
3380
|
-
return state.selectedModel;
|
|
3381
|
-
}
|
|
3382
|
-
});
|
|
3383
|
-
}
|
|
3384
|
-
async function seedUserInstructions(execution, prompt) {
|
|
3385
|
-
const { config, now } = execution.dependencies;
|
|
3386
|
-
const { state } = execution;
|
|
3387
|
-
if (!prompt.userInstructions || prompt.userInstructions.length === 0)
|
|
3388
|
-
return;
|
|
3389
|
-
const conversationId = state.run.conversationId;
|
|
3390
|
-
const seededAt = now().toISOString();
|
|
3391
|
-
const seeded = await config.store.seedConversationInput({
|
|
3392
|
-
conversationId,
|
|
3393
|
-
seedKey: USER_INSTRUCTION_SEED_KEY,
|
|
3394
|
-
inputs: prompt.userInstructions.map((section, index) => seededInstructionMessage({
|
|
3395
|
-
conversationId,
|
|
3396
|
-
seedKey: USER_INSTRUCTION_SEED_KEY,
|
|
3397
|
-
index,
|
|
3398
|
-
text: section.text,
|
|
3399
|
-
createdAt: seededAt
|
|
3400
|
-
}))
|
|
3401
|
-
});
|
|
3402
|
-
const seededSnapshot = appliedSnapshot(seeded, "user instruction seed");
|
|
3403
|
-
const previousIds = new Set(state.snapshot.messages.map((message) => message.id));
|
|
3404
|
-
const inserted = seededSnapshot.messages.some((message) => !previousIds.has(message.id) && message.role === "user" && message.runId === undefined);
|
|
3405
|
-
adoptSnapshot(state, seededSnapshot);
|
|
3406
|
-
return inserted;
|
|
3407
|
-
}
|
|
3408
|
-
async function prepareTurn(execution) {
|
|
3409
|
-
const { config } = execution.dependencies;
|
|
3410
|
-
const { state, executionSignal } = execution;
|
|
3411
|
-
const runtimeContext = createRuntimeContext(execution);
|
|
3412
|
-
execution.runtimeContext = runtimeContext;
|
|
3413
|
-
await compactHistory(execution);
|
|
3414
|
-
const selectedModel = await config.models.resolve({
|
|
3415
|
-
context: execution.input.context,
|
|
3416
|
-
conversationId: state.run.conversationId,
|
|
3417
|
-
run: state.run,
|
|
3418
|
-
snapshot: state.snapshot
|
|
3419
|
-
});
|
|
3420
|
-
state.selectedModel = selectedModel;
|
|
3421
|
-
let promptSnapshot = snapshotForRunPrompt(state.snapshot, state.run.id);
|
|
3422
|
-
const [composedPrompt, rawTools] = await Promise.all([
|
|
3423
|
-
config.prompt({
|
|
3424
|
-
context: execution.input.context,
|
|
3425
|
-
signal: executionSignal,
|
|
3426
|
-
event: promptSnapshot.runs[0]?.id === state.run.id ? "session.started" : "turn.started",
|
|
3427
|
-
model: selectedModel,
|
|
3428
|
-
snapshot: promptSnapshot
|
|
3429
|
-
}),
|
|
3430
|
-
config.tools(runtimeContext)
|
|
3431
|
-
]);
|
|
3432
|
-
const { tools, toolApproval } = applyStepBarriers(rawTools, config.loop?.toolApproval, config.loop?.stepBarriers);
|
|
3433
|
-
let prompt = composedPrompt;
|
|
3434
|
-
const userInstructionsInserted = await seedUserInstructions(execution, prompt);
|
|
3435
|
-
if (userInstructionsInserted !== undefined) {
|
|
3436
|
-
promptSnapshot = snapshotForRunPrompt(state.snapshot, state.run.id);
|
|
3437
|
-
}
|
|
3438
|
-
if (prompt.finalizeSeed)
|
|
3439
|
-
prompt = { ...prompt, ...prompt.finalizeSeed(userInstructionsInserted ?? false) };
|
|
3440
|
-
if (prompt.contextDecision === "oversized") {
|
|
3441
|
-
throw new AgentContextOverflowError2;
|
|
3442
|
-
}
|
|
3443
|
-
if (prompt.contextDecision === "requires-compaction") {
|
|
3444
|
-
throw new AgentContextOverflowError2("Agent context still exceeds the model budget after compaction");
|
|
3445
|
-
}
|
|
3446
|
-
const projection = createRunHistoryProjection({
|
|
3447
|
-
config,
|
|
3448
|
-
currentRun: () => state.run,
|
|
3449
|
-
durableSystem: await loadDurableSystem(config, state.run.conversationId)
|
|
3450
|
-
});
|
|
3451
|
-
const history = [...await projection.projectHistory(promptSnapshot)];
|
|
3452
|
-
return { selectedModel, runtimeContext, prompt, tools, toolApproval, history, projection };
|
|
3453
|
-
}
|
|
3454
|
-
|
|
3455
|
-
// src/agent-runtime/run-unacquired.ts
|
|
3456
|
-
async function closeUnacquiredRun(dependencies, input, failure, executing) {
|
|
3457
|
-
const { config, publish, runtimeEpoch, generateId, now } = dependencies;
|
|
3458
|
-
const { conversationId, id: runId } = input.acceptedRun;
|
|
3459
|
-
const view = await withStoreRetries(() => config.store.loadRun({ conversationId, runId })).catch(() => {
|
|
3460
|
-
throw new AgentRunUnsettledError2(input.acceptedRun, runtimeEpoch, failure);
|
|
3461
|
-
});
|
|
3462
|
-
if (!view || !isActiveRunState(view.run.state))
|
|
3463
|
-
throw failure;
|
|
3464
|
-
const { run } = view;
|
|
3465
|
-
if (run.ownerId !== undefined && run.ownerId !== runtimeEpoch)
|
|
3466
|
-
throw failure;
|
|
3467
|
-
if (executing.has(runId))
|
|
3468
|
-
throw failure;
|
|
3469
|
-
const unsettled = new AgentRunUnsettledError2(run, runtimeEpoch, failure);
|
|
3470
|
-
if (failure instanceof AgentRuntimeConflictError2 && run.ownerId === undefined)
|
|
3471
|
-
throw unsettled;
|
|
3472
|
-
const abandoned = await withStoreRetries(() => config.store.recoverRun({
|
|
3473
|
-
conversationId,
|
|
3474
|
-
runId,
|
|
3475
|
-
expectedRevision: run.revision,
|
|
3476
|
-
action: "abandon"
|
|
3477
|
-
})).catch(() => {
|
|
3478
|
-
return;
|
|
3479
|
-
});
|
|
3480
|
-
const terminal = abandoned?.outcome === "applied" ? terminalOfSnapshot(abandoned.snapshot, runId) : await withStoreRetries(() => config.store.loadRun({ conversationId, runId })).then((latest) => latest ? terminalOfRunView(latest, conversationId) : undefined, () => {
|
|
3481
|
-
return;
|
|
3482
|
-
});
|
|
3483
|
-
if (terminal?.reason !== "abandoned")
|
|
3484
|
-
throw unsettled;
|
|
3485
|
-
input.onAcquired?.();
|
|
3486
|
-
const version = terminal.snapshotVersion;
|
|
3487
|
-
const usage = statedUsage(terminal.run.usage);
|
|
3488
|
-
const emittedAt = now().toISOString();
|
|
3489
|
-
await publish({
|
|
3490
|
-
type: "run-state",
|
|
3491
|
-
eventId: agentDurableEventId2("run-state", runId, version),
|
|
3492
|
-
conversationId,
|
|
3493
|
-
runId,
|
|
3494
|
-
snapshotVersion: version,
|
|
3495
|
-
state: terminal.run.state,
|
|
3496
|
-
emittedAt
|
|
3497
|
-
});
|
|
3498
|
-
config.observe?.emit({
|
|
3499
|
-
schemaVersion: 1,
|
|
3500
|
-
eventId: agentDurableEventId2("terminal", runId, version),
|
|
3501
|
-
type: "run-terminal",
|
|
3502
|
-
conversationId,
|
|
3503
|
-
runId,
|
|
3504
|
-
traceId: generateId(),
|
|
3505
|
-
spanId: generateId(),
|
|
3506
|
-
state: terminal.run.state,
|
|
3507
|
-
terminalReason: terminal.reason,
|
|
3508
|
-
durationMs: 0,
|
|
3509
|
-
usage,
|
|
3510
|
-
internalCause: failure,
|
|
3511
|
-
emittedAt
|
|
3512
|
-
});
|
|
3513
|
-
const metrics = { partial: true, durationMs: 0, usage };
|
|
3514
|
-
await publish({
|
|
3515
|
-
type: "terminal",
|
|
3516
|
-
eventId: agentDurableEventId2("terminal", runId, version),
|
|
3517
|
-
conversationId,
|
|
3518
|
-
runId,
|
|
3519
|
-
snapshotVersion: version,
|
|
3520
|
-
reason: terminal.reason,
|
|
3521
|
-
message: terminal.assistant,
|
|
3522
|
-
metrics,
|
|
3523
|
-
emittedAt
|
|
3524
|
-
});
|
|
3525
|
-
return {
|
|
3526
|
-
run: terminal.run,
|
|
3527
|
-
message: terminal.assistant,
|
|
3528
|
-
reason: terminal.reason,
|
|
3529
|
-
snapshotVersion: version,
|
|
3530
|
-
metrics
|
|
3531
|
-
};
|
|
3532
|
-
}
|
|
3533
|
-
|
|
3534
|
-
// src/agent-runtime/run-execution.ts
|
|
3535
|
-
function createRunExecutor(dependencies) {
|
|
3536
|
-
const executing = new Set;
|
|
3537
|
-
return async function executeRun(input) {
|
|
3538
|
-
let acquisition;
|
|
3539
|
-
try {
|
|
3540
|
-
acquisition = await acquireRun(dependencies, input);
|
|
3541
|
-
} catch (error) {
|
|
3542
|
-
return closeUnacquiredRun(dependencies, input, error, executing);
|
|
3543
|
-
}
|
|
3544
|
-
if (acquisition.kind === "absorbed")
|
|
3545
|
-
return acquisition.result;
|
|
3546
|
-
const { execution } = acquisition;
|
|
3547
|
-
const runId = execution.state.run.id;
|
|
3548
|
-
executing.add(runId);
|
|
3549
|
-
let result;
|
|
3550
|
-
try {
|
|
3551
|
-
try {
|
|
3552
|
-
await beginRunExecution(execution);
|
|
3553
|
-
const invocations = dependencies.config.invocations;
|
|
3554
|
-
if (invocations) {
|
|
3555
|
-
const trace = await invocations.trace({
|
|
3556
|
-
context: input.context,
|
|
3557
|
-
conversationId: execution.state.run.conversationId,
|
|
3558
|
-
run: execution.state.run
|
|
3559
|
-
});
|
|
3560
|
-
execution.invocationTrace = trace;
|
|
3561
|
-
execution.invocation = await beginAgentInvocation(invocations.ledger, dependencies.config.store, { run: execution.state.run, trace }, input.context);
|
|
3562
|
-
}
|
|
3563
|
-
const turn = await prepareTurn(execution);
|
|
3564
|
-
await runModelAttempts(execution, turn);
|
|
3565
|
-
await settleStreamOutcome(execution);
|
|
3566
|
-
} catch (error) {
|
|
3567
|
-
await classifyRunFailure(execution, error);
|
|
3568
|
-
} finally {
|
|
3569
|
-
execution.idleDeadline.dispose();
|
|
3570
|
-
}
|
|
3571
|
-
result = await commitRunTerminal(execution);
|
|
3572
|
-
} finally {
|
|
3573
|
-
executing.delete(runId);
|
|
3574
|
-
execution.idleDeadline.release();
|
|
3575
|
-
}
|
|
3576
|
-
await execution.invocation?.finish(result.reason === "success" ? "succeeded" : ["interrupted", "cancelled", "timeout", "shutdown"].includes(result.reason) ? "cancelled" : "failed");
|
|
3577
|
-
return result;
|
|
3578
|
-
};
|
|
3579
|
-
}
|
|
3580
|
-
|
|
3581
|
-
// src/agent-runtime/runtime-state.ts
|
|
3582
|
-
function resolveLoopLimits(config) {
|
|
3583
|
-
const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
|
|
3584
|
-
const maxSteps = config.loop?.maxSteps ?? 50;
|
|
3585
|
-
const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
|
|
3586
|
-
const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
|
|
3587
|
-
const stepSpendTimeoutMs = config.stepSpendTimeoutMs ?? DEFAULT_STEP_SPEND_TIMEOUT_MS;
|
|
3588
|
-
assertPositiveSafeInteger("checkpointEveryEvents", checkpointEveryEvents);
|
|
3589
|
-
assertPositiveSafeInteger("maxSteps", maxSteps);
|
|
3590
|
-
assertTimerMs("idleTimeoutMs", idleTimeoutMs);
|
|
3591
|
-
assertTimerMs("stepSpendTimeoutMs", stepSpendTimeoutMs);
|
|
3592
|
-
if (config.loop?.retry)
|
|
3593
|
-
assertAgentRetryPolicy("loop.retry", config.loop.retry);
|
|
3594
|
-
assertStepBarriers(config.loop?.stepBarriers);
|
|
3595
|
-
const policyNames = new Set(["max-steps"]);
|
|
3596
|
-
for (const policy of config.loop?.stopPolicies ?? []) {
|
|
3597
|
-
if (!policy.name || policyNames.has(policy.name)) {
|
|
3598
|
-
throw new TypeError("Agent stop policy names must be non-empty and unique");
|
|
3599
|
-
}
|
|
3600
|
-
policyNames.add(policy.name);
|
|
3601
|
-
}
|
|
3602
|
-
return {
|
|
3603
|
-
checkpointEveryEvents,
|
|
3604
|
-
maxSteps,
|
|
3605
|
-
...idleTimeoutMs !== undefined && { idleTimeoutMs },
|
|
3606
|
-
stepSpendTimeoutMs
|
|
3607
|
-
};
|
|
3608
|
-
}
|
|
3609
|
-
function createAgentRuntimeState(config) {
|
|
3610
|
-
const coordinator = createAgentSessionCoordinator2();
|
|
3611
|
-
const generateId = config.generateId ?? (() => crypto.randomUUID());
|
|
3612
|
-
const now = config.now ?? (() => new Date);
|
|
3613
|
-
const runtimeEpoch = generateId();
|
|
3614
|
-
const admissionLanes = createRuntimeAdmissionLanes();
|
|
3615
|
-
const injectionPossible = typeof config.runs?.inputPolicy === "function" || config.runs?.inputPolicy === "inject";
|
|
3616
|
-
const injection = injectionPossible ? createAgentInjectionRegistry() : undefined;
|
|
3617
|
-
const { checkpointEveryEvents, maxSteps, idleTimeoutMs, stepSpendTimeoutMs } = resolveLoopLimits(config);
|
|
3618
|
-
const publish = async (event) => {
|
|
3619
|
-
try {
|
|
3620
|
-
await config.publish?.(event);
|
|
3621
|
-
} catch (error) {
|
|
3622
|
-
try {
|
|
3623
|
-
await config.onPublishError?.({ event, error });
|
|
3624
|
-
} catch {}
|
|
3625
|
-
}
|
|
3626
|
-
};
|
|
3627
|
-
const executeRun = createRunExecutor({
|
|
3628
|
-
config,
|
|
3629
|
-
publish,
|
|
3630
|
-
runtimeEpoch,
|
|
3631
|
-
generateId,
|
|
3632
|
-
now,
|
|
3633
|
-
checkpointEveryEvents,
|
|
3634
|
-
maxSteps,
|
|
3635
|
-
...idleTimeoutMs !== undefined && { idleTimeoutMs },
|
|
3636
|
-
stepSpendTimeoutMs,
|
|
3637
|
-
...injection && { injection }
|
|
3638
|
-
});
|
|
3639
|
-
return {
|
|
3640
|
-
config,
|
|
3641
|
-
coordinator,
|
|
3642
|
-
tickets: new Map,
|
|
3643
|
-
generateId,
|
|
3644
|
-
now,
|
|
3645
|
-
admissionLanes,
|
|
3646
|
-
gate: createRuntimeAdmissionGate(),
|
|
3647
|
-
...injection && { injection },
|
|
3648
|
-
publish,
|
|
3649
|
-
executeRun
|
|
3650
|
-
};
|
|
3651
|
-
}
|
|
3652
|
-
|
|
3653
|
-
// src/agent-runtime/runtime-submit.ts
|
|
3654
|
-
function submitAgentInput(state, rawInput) {
|
|
3655
|
-
if (state.gate.closed) {
|
|
3656
|
-
const refused = refuse();
|
|
3657
|
-
const admission = Promise.reject(closedError());
|
|
3658
|
-
admission.catch(() => {
|
|
3659
|
-
return;
|
|
3660
|
-
});
|
|
3661
|
-
return { ...refused, admission };
|
|
3662
|
-
}
|
|
3663
|
-
const input = parseSubmittedInput(state, rawInput);
|
|
3664
|
-
const context = state.config.protocol.parseContext(input.context);
|
|
3665
|
-
const conversationTickets = state.tickets.get(input.conversationId);
|
|
3666
|
-
const existingTicket = conversationTickets?.get(input.idempotencyKey);
|
|
3667
|
-
if (existingTicket)
|
|
3668
|
-
return existingTicket;
|
|
3669
|
-
const submission = createSubmission(state, rawInput, input, context);
|
|
3670
|
-
const publicTicket = registerTicket(state, submission, conversationTickets);
|
|
3671
|
-
const handedOff = state.gate.begin();
|
|
3672
|
-
admitSubmission(state, submission, handedOff);
|
|
3673
|
-
return publicTicket;
|
|
3674
|
-
}
|
|
3675
|
-
function parseSubmittedInput(state, rawInput) {
|
|
3676
|
-
const { protocol } = state.config;
|
|
3677
|
-
const metadata = rawInput.metadata === undefined ? undefined : protocol.parseInputMetadata(rawInput.metadata);
|
|
3678
|
-
const input = {
|
|
3679
|
-
conversationId: rawInput.conversationId,
|
|
3680
|
-
idempotencyKey: rawInput.idempotencyKey,
|
|
3681
|
-
context: rawInput.context,
|
|
3682
|
-
parts: rawInput.parts.map((part) => protocol.parsePart(part)),
|
|
3683
|
-
role: rawInput.role ?? "user",
|
|
3684
|
-
...metadata !== undefined && { metadata }
|
|
3685
|
-
};
|
|
3686
|
-
if (input.role === "tool" && (input.parts.length === 0 || input.parts.some((part) => part.type !== "tool-approval-response"))) {
|
|
3687
|
-
throw new TypeError("Tool-role Agent input only accepts approval responses");
|
|
3688
|
-
}
|
|
3689
|
-
return input;
|
|
3690
|
-
}
|
|
3691
|
-
function createSubmission(state, rawInput, input, context) {
|
|
3692
|
-
const { config, generateId } = state;
|
|
3693
|
-
const key = config.runs?.key?.(input) ?? input.conversationId;
|
|
3694
|
-
const policy = typeof config.runs?.inputPolicy === "function" ? config.runs.inputPolicy(input) : config.runs?.inputPolicy ?? "queue";
|
|
3695
|
-
const nowIso = state.now().toISOString();
|
|
3696
|
-
const inputMessageId = rawInput.recordIds?.inputMessageId ?? generateId();
|
|
3697
|
-
const runId = rawInput.recordIds?.runId ?? generateId();
|
|
3698
|
-
const assistantMessageId = rawInput.recordIds?.assistantMessageId ?? generateId();
|
|
3699
|
-
const userMessage = AgentMessageSchema2.parse({
|
|
3700
|
-
schemaVersion: 1,
|
|
3701
|
-
id: inputMessageId,
|
|
3702
|
-
conversationId: input.conversationId,
|
|
3703
|
-
role: input.role,
|
|
3704
|
-
status: "committed",
|
|
3705
|
-
parts: input.parts,
|
|
3706
|
-
...input.metadata && { metadata: input.metadata },
|
|
3707
|
-
createdAt: nowIso,
|
|
3708
|
-
updatedAt: nowIso
|
|
3709
|
-
});
|
|
3710
|
-
const queuedRun = AgentRunSchema2.parse({
|
|
3711
|
-
schemaVersion: 1,
|
|
3712
|
-
id: runId,
|
|
3713
|
-
conversationId: input.conversationId,
|
|
3714
|
-
inputMessageIds: [inputMessageId],
|
|
3715
|
-
assistantMessageId,
|
|
3716
|
-
state: "queued",
|
|
3717
|
-
revision: 0,
|
|
3718
|
-
...policy === "interrupt-next" && { queuePriority: "interrupt-next" },
|
|
3719
|
-
createdAt: nowIso,
|
|
3720
|
-
updatedAt: nowIso
|
|
3721
|
-
});
|
|
3722
|
-
const outerAccepted = Promise.withResolvers();
|
|
3723
|
-
outerAccepted.promise.catch(() => {
|
|
3724
|
-
return;
|
|
3725
|
-
});
|
|
3726
|
-
const outerAdmission = Promise.withResolvers();
|
|
3727
|
-
outerAdmission.promise.catch(() => {
|
|
3728
|
-
return;
|
|
3729
|
-
});
|
|
3730
|
-
const outerResult = Promise.withResolvers();
|
|
3731
|
-
const reservation = config.runs?.coalescePending && policy !== "interrupt-next" ? state.admissionLanes.reserve(key, runId) : undefined;
|
|
3732
|
-
const previousAcceptance = reservation?.lane.acceptanceTail ?? Promise.resolve();
|
|
3733
|
-
const acceptanceDone = Promise.withResolvers();
|
|
3734
|
-
if (reservation) {
|
|
3735
|
-
reservation.lane.acceptanceTail = previousAcceptance.catch(() => {
|
|
3736
|
-
return;
|
|
3737
|
-
}).then(() => acceptanceDone.promise);
|
|
3738
|
-
}
|
|
3739
|
-
return {
|
|
3740
|
-
input,
|
|
3741
|
-
context,
|
|
3742
|
-
key,
|
|
3743
|
-
policy,
|
|
3744
|
-
runId,
|
|
3745
|
-
userMessage,
|
|
3746
|
-
queuedRun,
|
|
3747
|
-
...reservation && { reservation },
|
|
3748
|
-
previousAcceptance,
|
|
3749
|
-
acceptanceDone,
|
|
3750
|
-
outerAccepted,
|
|
3751
|
-
outerAdmission,
|
|
3752
|
-
outerResult
|
|
3753
|
-
};
|
|
3754
|
-
}
|
|
3755
|
-
function registerTicket(state, submission, conversationTickets) {
|
|
3756
|
-
const { input, key } = submission;
|
|
3757
|
-
const publicTicket = {
|
|
3758
|
-
accepted: submission.outerAccepted.promise,
|
|
3759
|
-
admission: submission.outerAdmission.promise,
|
|
3760
|
-
result: submission.outerResult.promise
|
|
3761
|
-
};
|
|
3762
|
-
const currentConversationTickets = conversationTickets ?? new Map;
|
|
3763
|
-
currentConversationTickets.set(input.idempotencyKey, publicTicket);
|
|
3764
|
-
if (!conversationTickets) {
|
|
3765
|
-
state.tickets.set(input.conversationId, currentConversationTickets);
|
|
3766
|
-
}
|
|
3767
|
-
const forgetTicket = () => {
|
|
3768
|
-
if (submission.offeredRunId !== undefined) {
|
|
3769
|
-
state.injection?.withdraw(key, submission.offeredRunId);
|
|
3770
|
-
}
|
|
3771
|
-
if (currentConversationTickets.get(input.idempotencyKey) !== publicTicket)
|
|
3772
|
-
return;
|
|
3773
|
-
currentConversationTickets.delete(input.idempotencyKey);
|
|
3774
|
-
if (currentConversationTickets.size === 0)
|
|
3775
|
-
state.tickets.delete(input.conversationId);
|
|
3776
|
-
};
|
|
3777
|
-
submission.outerResult.promise.then(forgetTicket, forgetTicket);
|
|
3778
|
-
return publicTicket;
|
|
3779
|
-
}
|
|
3780
|
-
async function admitSubmission(state, submission, handedOff) {
|
|
3781
|
-
const { config } = state;
|
|
3782
|
-
const { input, reservation, key } = submission;
|
|
3783
|
-
try {
|
|
3784
|
-
await submission.previousAcceptance.catch(() => {
|
|
3785
|
-
return;
|
|
3786
|
-
});
|
|
3787
|
-
await config.models.preflight?.({
|
|
3788
|
-
context: submission.context,
|
|
3789
|
-
conversationId: input.conversationId
|
|
3790
|
-
});
|
|
3791
|
-
if (state.gate.closed)
|
|
3792
|
-
throw closedError();
|
|
3793
|
-
const acceptance = await config.store.acceptInputAndAssignRun({
|
|
3794
|
-
idempotencyKey: input.idempotencyKey,
|
|
3795
|
-
input: submission.userMessage,
|
|
3796
|
-
run: submission.queuedRun,
|
|
3797
|
-
...reservation && !reservation.shouldSchedule && {
|
|
3798
|
-
coalesceIntoRunId: reservation.admission.runId
|
|
3799
|
-
}
|
|
3800
|
-
});
|
|
3801
|
-
const admission = projectAdmission(submission, acceptance);
|
|
3802
|
-
submission.outerAdmission.resolve(admission);
|
|
3803
|
-
await publishAdmission(state, admission);
|
|
3804
|
-
submission.outerAccepted.resolve();
|
|
3805
|
-
if (acceptance.outcome === "duplicate") {
|
|
3806
|
-
settleDuplicate(state, submission, admission, acceptance.assistant);
|
|
3807
|
-
return;
|
|
3808
|
-
}
|
|
3809
|
-
if (submission.policy === "inject") {
|
|
3810
|
-
submission.offeredRunId = admission.run.id;
|
|
3811
|
-
state.injection?.offer(key, { runId: admission.run.id, input: admission.input });
|
|
3812
|
-
}
|
|
3813
|
-
if (reservation && !reservation.shouldSchedule) {
|
|
3814
|
-
reservation.admission.completion.promise.then(submission.outerResult.resolve, submission.outerResult.reject);
|
|
3815
|
-
return;
|
|
3816
|
-
}
|
|
3817
|
-
handOffToCoordinator(state, submission, admission.run);
|
|
3818
|
-
} catch (error) {
|
|
3819
|
-
submission.outerAccepted.reject(error);
|
|
3820
|
-
submission.outerAdmission.reject(error);
|
|
3821
|
-
submission.outerResult.reject(error);
|
|
3822
|
-
if (reservation?.shouldSchedule) {
|
|
3823
|
-
reservation.admission.completion.reject(error);
|
|
3824
|
-
state.admissionLanes.settle(key, reservation.admission);
|
|
3825
|
-
}
|
|
3826
|
-
} finally {
|
|
3827
|
-
submission.acceptanceDone.resolve();
|
|
3828
|
-
handedOff();
|
|
3829
|
-
}
|
|
3830
|
-
}
|
|
3831
|
-
function projectAdmission(submission, acceptance) {
|
|
3832
|
-
const acceptedSnapshot = appliedSnapshot(acceptance, "input acceptance");
|
|
3833
|
-
const assignedRunId = acceptance.outcome === "duplicate" ? acceptance.runId : submission.reservation?.admission.runId ?? submission.runId;
|
|
3834
|
-
const acceptedRun = acceptance.outcome === "duplicate" ? acceptance.run : findRun(acceptedSnapshot.runs, assignedRunId);
|
|
3835
|
-
const actualInputMessageId = acceptance.outcome === "duplicate" ? acceptance.inputMessageId : submission.userMessage.id;
|
|
3836
|
-
const acceptedInput = acceptance.outcome === "duplicate" ? acceptance.input : acceptedSnapshot.messages.find((candidate) => candidate.id === actualInputMessageId);
|
|
3837
|
-
if (!acceptedInput) {
|
|
3838
|
-
throw new AgentRuntimeConflictError2("admission input projection");
|
|
3839
|
-
}
|
|
3840
|
-
const assistantPlaceholder = AgentAssistantPlaceholderSchema2.parse({
|
|
3841
|
-
schemaVersion: 1,
|
|
3842
|
-
id: acceptedRun.assistantMessageId,
|
|
3843
|
-
conversationId: acceptedRun.conversationId,
|
|
3844
|
-
runId: acceptedRun.id,
|
|
3845
|
-
status: "pending",
|
|
3846
|
-
createdAt: acceptedRun.createdAt,
|
|
3847
|
-
updatedAt: acceptedRun.updatedAt
|
|
3848
|
-
});
|
|
3849
|
-
const acceptedAssistant = acceptance.outcome === "duplicate" ? acceptance.assistant ?? assistantPlaceholder : assistantPlaceholder;
|
|
3850
|
-
return {
|
|
3851
|
-
inputMessageId: acceptedInput.id,
|
|
3852
|
-
runId: acceptedRun.id,
|
|
3853
|
-
assistantMessageId: assistantPlaceholder.id,
|
|
3854
|
-
input: acceptedInput,
|
|
3855
|
-
run: acceptedRun,
|
|
3856
|
-
assistant: acceptedAssistant,
|
|
3857
|
-
snapshotVersion: acceptedSnapshot.version
|
|
3858
|
-
};
|
|
3859
|
-
}
|
|
3860
|
-
async function publishAdmission(state, admission) {
|
|
3861
|
-
const { run, snapshotVersion } = admission;
|
|
3862
|
-
await state.publish({
|
|
3863
|
-
type: "admission",
|
|
3864
|
-
eventId: agentDurableEventId2("admission", run.id, snapshotVersion),
|
|
3865
|
-
conversationId: run.conversationId,
|
|
3866
|
-
runId: run.id,
|
|
3867
|
-
snapshotVersion,
|
|
3868
|
-
input: admission.input,
|
|
3869
|
-
run,
|
|
3870
|
-
assistant: admission.assistant,
|
|
3871
|
-
emittedAt: state.now().toISOString()
|
|
3872
|
-
});
|
|
3873
|
-
await state.publish({
|
|
3874
|
-
type: "run-state",
|
|
3875
|
-
eventId: agentDurableEventId2("run-state", run.id, snapshotVersion),
|
|
3876
|
-
conversationId: run.conversationId,
|
|
3877
|
-
runId: run.id,
|
|
3878
|
-
snapshotVersion,
|
|
3879
|
-
state: run.state,
|
|
3880
|
-
emittedAt: state.now().toISOString()
|
|
3881
|
-
});
|
|
3882
|
-
}
|
|
3883
|
-
function settleDuplicate(state, submission, admission, retainedAssistant) {
|
|
3884
|
-
const { reservation, key, outerResult } = submission;
|
|
3885
|
-
const acceptedRun = admission.run;
|
|
3886
|
-
const refuseDuplicate = (error) => {
|
|
3887
|
-
outerResult.reject(error);
|
|
3888
|
-
if (reservation?.shouldSchedule) {
|
|
3889
|
-
reservation.admission.completion.reject(error);
|
|
3890
|
-
state.admissionLanes.settle(key, reservation.admission);
|
|
3891
|
-
}
|
|
3892
|
-
};
|
|
3893
|
-
if (!acceptedRun.terminalReason) {
|
|
3894
|
-
refuseDuplicate(new Error("Duplicate input is already owned by another runtime execution"));
|
|
3895
|
-
return;
|
|
3896
|
-
}
|
|
3897
|
-
const message = retainedAssistant;
|
|
3898
|
-
if (!message) {
|
|
3899
|
-
refuseDuplicate(new Error("Duplicate terminal admission has no retained canonical assistant"));
|
|
3900
|
-
return;
|
|
3901
|
-
}
|
|
3902
|
-
outerResult.resolve({
|
|
3903
|
-
run: acceptedRun,
|
|
3904
|
-
message,
|
|
3905
|
-
reason: acceptedRun.terminalReason,
|
|
3906
|
-
snapshotVersion: admission.snapshotVersion,
|
|
3907
|
-
...acceptedRun.terminalPolicyName && {
|
|
3908
|
-
policyName: acceptedRun.terminalPolicyName
|
|
3909
|
-
}
|
|
3910
|
-
});
|
|
3911
|
-
if (reservation?.shouldSchedule) {
|
|
3912
|
-
reservation.admission.completion.reject(new Error("Reserved run resolved to a duplicate durable input"));
|
|
3913
|
-
state.admissionLanes.settle(key, reservation.admission);
|
|
3914
|
-
}
|
|
3915
|
-
}
|
|
3916
|
-
function handOffToCoordinator(state, submission, acceptedRun) {
|
|
3917
|
-
const { reservation, key, context, outerResult } = submission;
|
|
3918
|
-
const ticket = state.coordinator.submit({
|
|
3919
|
-
key,
|
|
3920
|
-
policy: submission.policy,
|
|
3921
|
-
create: async (signal) => {
|
|
3922
|
-
if (reservation)
|
|
3923
|
-
await state.admissionLanes.waitForAcceptances(reservation.lane);
|
|
3924
|
-
return {
|
|
3925
|
-
runId: acceptedRun.id,
|
|
3926
|
-
execute: () => state.executeRun({ acceptedRun, context, signal, key })
|
|
3927
|
-
};
|
|
3928
|
-
}
|
|
3929
|
-
});
|
|
3930
|
-
ticket.accepted.catch(() => {
|
|
3931
|
-
return;
|
|
3932
|
-
});
|
|
3933
|
-
if (reservation) {
|
|
3934
|
-
ticket.result.then(reservation.admission.completion.resolve, reservation.admission.completion.reject);
|
|
3935
|
-
reservation.admission.completion.promise.then((value) => {
|
|
3936
|
-
state.admissionLanes.settle(key, reservation.admission);
|
|
3937
|
-
outerResult.resolve(value);
|
|
3938
|
-
}, (error) => {
|
|
3939
|
-
state.admissionLanes.settle(key, reservation.admission);
|
|
3940
|
-
outerResult.reject(error);
|
|
3941
|
-
});
|
|
3942
|
-
} else {
|
|
3943
|
-
ticket.result.then(outerResult.resolve, outerResult.reject);
|
|
3944
|
-
}
|
|
3945
|
-
}
|
|
3946
|
-
|
|
3947
|
-
// src/agent-runtime/runtime.ts
|
|
3948
|
-
function createAgentRuntime2(config) {
|
|
3949
|
-
const state = createAgentRuntimeState(config);
|
|
3950
|
-
return {
|
|
3951
|
-
submit: (rawInput) => submitAgentInput(state, rawInput),
|
|
3952
|
-
resume: (rawInput) => resumeAgentRun(state, rawInput),
|
|
3953
|
-
interrupt: (input) => interruptAgentRun(state, input),
|
|
3954
|
-
abandon: (input) => abandonAgentRun(state, input),
|
|
3955
|
-
recover: (options) => recoverAgentRuns(state, options),
|
|
3956
|
-
stop: (conversationKey, reason) => state.coordinator.stop(conversationKey, reason),
|
|
3957
|
-
close: (options = {}) => closeAgentRuntime(state, options)
|
|
3958
|
-
};
|
|
3959
|
-
}
|
|
3960
|
-
|
|
3961
|
-
export { AgentContextOverflowError2, createAgentSessionCoordinator2, registerDeferredToolRepair, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, projectAgentHistoryDetailed2, projectAgentHistory2, createModelInvocationLedger2, createAgentToolFenceLifecycle2, AgentTokenCountSchema2, selectAgentHistory2, composeAgentPrompt2, AgentProviderStreamCutError2, classifyProviderFailure2, isToolResultFailure2, recordAgentRetryDecision2, AgentStepBarrierError2, createToolDependencyResolver2, defineStateSlot2, createAgentStateSlotStore2, renderAgentStateSlots2, agentGoalStateSlot2, agentTodoStateSlot2, createAgentRuntime2 };
|