eve 0.47.7 → 0.49.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 +35 -0
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/delivery-metadata.d.ts +1 -0
- package/dist/src/channel/delivery-metadata.js +1 -1
- package/dist/src/channel/types.d.ts +20 -8
- package/dist/src/chunks/{use-eve-agent-Dg5S44kG.js → use-eve-agent-BZnOzAVd.js} +25 -5
- package/dist/src/chunks/{use-eve-agent-B5zw1dwj.js → use-eve-agent-Bgp6INfi.js} +25 -5
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/integration-connect.d.ts +2 -1
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/register-integration-commands.d.ts +3 -1
- package/dist/src/cli/commands/register-integration-commands.js +1 -1
- package/dist/src/cli/commands/registry-metadata.d.ts +30 -0
- package/dist/src/cli/commands/registry-metadata.js +1 -1
- package/dist/src/cli/commands/registry-package.d.ts +6 -0
- package/dist/src/cli/commands/registry-package.js +1 -1
- package/dist/src/cli/commands/registry-pnpm-build-policy-flow.d.ts +30 -0
- package/dist/src/cli/commands/registry-pnpm-build-policy-flow.js +1 -0
- package/dist/src/cli/commands/registry-pnpm-build-policy.d.ts +12 -0
- package/dist/src/cli/commands/registry-pnpm-build-policy.js +6 -0
- package/dist/src/cli/commands/registry-recovery.d.ts +4 -0
- package/dist/src/cli/commands/registry-recovery.js +1 -1
- package/dist/src/cli/commands/registry.d.ts +1 -1
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/dev/command-options.d.ts +2 -0
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/blocks.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.d.ts +17 -0
- package/dist/src/cli/dev/tui/registry-result-message.js +3 -0
- package/dist/src/cli/dev/tui/runner.d.ts +11 -4
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +9 -3
- package/dist/src/cli/dev/tui/setup-commands.js +2 -3
- package/dist/src/cli/dev/tui/setup-flow.d.ts +15 -5
- package/dist/src/cli/dev/tui/setup-panel.d.ts +6 -1
- package/dist/src/cli/dev/tui/setup-panel.js +4 -4
- package/dist/src/cli/dev/tui/setup-selection-input.d.ts +1 -0
- package/dist/src/cli/dev/tui/setup-selection-input.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/cli/dev/tui/tui.d.ts +3 -4
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/run.js +2 -2
- package/dist/src/client/agent-info-schema.d.ts +1 -0
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/open-stream.d.ts +1 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +7 -6
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +6 -0
- package/dist/src/compiled/@workflow/builders/LICENSE.md +201 -0
- package/dist/src/compiled/@workflow/builders/index.d.ts +62 -0
- package/dist/src/compiled/@workflow/builders/index.js +1 -0
- package/dist/src/compiled/@workflow/core/attribute-changes.d.ts +2 -4
- package/dist/src/compiled/@workflow/core/capabilities.d.ts +10 -9
- package/dist/src/compiled/@workflow/core/capture-stack.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/class-serialization.d.ts +8 -8
- package/dist/src/compiled/@workflow/core/context-violation-error.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/describe-error.d.ts +7 -7
- package/dist/src/compiled/@workflow/core/encryption.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +49 -14
- package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +4 -4
- package/dist/src/compiled/@workflow/core/global.d.ts +4 -2
- package/dist/src/compiled/@workflow/core/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/log-format.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/private.d.ts +40 -78
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/replay-payload-cache.d.ts +13 -17
- package/dist/src/compiled/@workflow/core/runtime/compute-instance.d.ts +4 -3
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +27 -27
- package/dist/src/compiled/@workflow/core/runtime/count-step-started-events.d.ts +7 -7
- package/dist/src/compiled/@workflow/core/runtime/deployment-guard.d.ts +7 -7
- package/dist/src/compiled/@workflow/core/runtime/get-port-lazy.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime/get-world-lazy.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +30 -49
- package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +21 -10
- package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +31 -15
- package/dist/src/compiled/@workflow/core/runtime/quickjs-serde.d.ts +10 -10
- package/dist/src/compiled/@workflow/core/runtime/replay-budget.d.ts +4 -4
- package/dist/src/compiled/@workflow/core/runtime/replay-recovery-reporter.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +20 -12
- package/dist/src/compiled/@workflow/core/runtime/resume-latency.d.ts +37 -30
- package/dist/src/compiled/@workflow/core/runtime/run-id-time.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime/run.d.ts +22 -5
- package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +4 -4
- package/dist/src/compiled/@workflow/core/runtime/start.d.ts +3 -3
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +14 -14
- package/dist/src/compiled/@workflow/core/runtime/step-latency.d.ts +42 -25
- package/dist/src/compiled/@workflow/core/runtime/step-ownership.d.ts +6 -6
- package/dist/src/compiled/@workflow/core/runtime/step-single-flight.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +38 -24
- package/dist/src/compiled/@workflow/core/runtime/unserializable-step.d.ts +34 -0
- package/dist/src/compiled/@workflow/core/runtime/vm-mode.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime/wait-continuation.d.ts +31 -9
- package/dist/src/compiled/@workflow/core/runtime/wait-until.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime/world-compatibility.d.ts +20 -9
- package/dist/src/compiled/@workflow/core/runtime/world-init.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/sealed-box.d.ts +7 -7
- package/dist/src/compiled/@workflow/core/serialization/codec-devalue-vm.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization/codec-devalue.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization/codec.d.ts +4 -4
- package/dist/src/compiled/@workflow/core/serialization/compression.d.ts +12 -11
- package/dist/src/compiled/@workflow/core/serialization/encryption.d.ts +7 -7
- package/dist/src/compiled/@workflow/core/serialization/format.d.ts +6 -6
- package/dist/src/compiled/@workflow/core/serialization/hardened.d.ts +23 -22
- package/dist/src/compiled/@workflow/core/serialization/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization/reducers/class-vm.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization/reducers/step-function-vm.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization/types.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/serialization/workflow-vm.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization-format.d.ts +11 -11
- package/dist/src/compiled/@workflow/core/serialization.d.ts +18 -19
- package/dist/src/compiled/@workflow/core/source-map.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/step/writable-stream.d.ts +3 -3
- package/dist/src/compiled/@workflow/core/symbols.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +71 -20
- package/dist/src/compiled/@workflow/core/telemetry.d.ts +15 -3
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/vm/script-cache.d.ts +9 -11
- package/dist/src/compiled/@workflow/core/workflow/abort-controller.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow/set-attributes.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow/world-init-stub.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +18 -18
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/analytics.d.ts +3 -2
- package/dist/src/compiled/@workflow/world/attributes-validation.d.ts +28 -0
- package/dist/src/compiled/@workflow/world/attributes.d.ts +8 -107
- package/dist/src/compiled/@workflow/world/env-config.d.ts +5 -5
- package/dist/src/compiled/@workflow/world/event-metadata.d.ts +132 -0
- package/dist/src/compiled/@workflow/world/events.d.ts +42 -96
- package/dist/src/compiled/@workflow/world/hooks.d.ts +12 -11
- package/dist/src/compiled/@workflow/world/index.d.ts +3 -3
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +94 -39
- package/dist/src/compiled/@workflow/world/queue.d.ts +29 -22
- package/dist/src/compiled/@workflow/world/runs.d.ts +20 -0
- package/dist/src/compiled/@workflow/world/slot-identity.d.ts +3 -3
- package/dist/src/compiled/@workflow/world/spec-version.d.ts +82 -15
- package/dist/src/compiled/@workflow/world/ulid.d.ts +2 -2
- package/dist/src/compiled/@workflow/world-local/index.js +5 -5
- package/dist/src/compiled/@workflow/world-vercel/index.js +12 -12
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-DXbpwBdw.js → attribute-changes-BwAadFfB.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/debug-log-CVPstO1D.js +1 -0
- package/dist/src/compiled/_chunks/workflow/dist-CgbVZs5l.js +40 -0
- package/dist/src/compiled/_chunks/workflow/dist-DjojkP5e.js +3 -0
- package/dist/src/compiled/_chunks/workflow/frames-CZ9eHShe.js +3 -0
- package/dist/src/compiled/_chunks/workflow/global-singleton-BNinwFrL.js +1 -0
- package/dist/src/compiled/_chunks/workflow/private-CZFMABEf.js +1 -0
- package/dist/src/compiled/_chunks/workflow/resume-hook-BToMtPbH.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-DzyAoGh4.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-3_A5uOp-.js +1 -0
- package/dist/src/compiled/_chunks/workflow/undici-DfxNX5og.js +95 -0
- package/dist/src/compiled/_chunks/workflow/wait-until-BtySPYD0.js +15 -0
- package/dist/src/compiled/_chunks/workflow/ws-transport-PnVVxT0R.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +2 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/context/keys.d.ts +3 -8
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +7 -7
- package/dist/src/execution/accepted-delivery-deployment.d.ts +7 -0
- package/dist/src/execution/accepted-delivery-deployment.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.d.ts +4 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/continuation-conflict-step.d.ts +10 -0
- package/dist/src/execution/continuation-conflict-step.js +1 -0
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/delegation-tool.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +14 -31
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-start.d.ts +33 -0
- package/dist/src/execution/dispatch-runtime-actions-start.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-turn-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.d.ts +2 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.js +1 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +25 -3
- package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
- package/dist/src/execution/dynamic-connections.js +1 -1
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/finalize-terminal-session.d.ts +17 -0
- package/dist/src/execution/finalize-terminal-session.js +1 -0
- package/dist/src/execution/inline-turn.d.ts +29 -0
- package/dist/src/execution/inline-turn.js +1 -0
- package/dist/src/execution/next-driver-action.d.ts +9 -4
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/pending-turn-state.d.ts +1 -0
- package/dist/src/execution/pending-turn-state.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +2 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/runtime-errors.d.ts +0 -12
- package/dist/src/execution/runtime-errors.js +1 -1
- package/dist/src/execution/session-command-token.d.ts +2 -0
- package/dist/src/execution/session-command-token.js +1 -1
- package/dist/src/execution/session-timeout-steps.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/stable-workflow-names.d.ts +12 -0
- package/dist/src/execution/stable-workflow-names.js +1 -0
- package/dist/src/execution/subagent-event-proxy-step.d.ts +3 -0
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +2 -1
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/subagent-start-local.js +1 -1
- package/dist/src/execution/subagent-start-remote.d.ts +2 -0
- package/dist/src/execution/subagent-start-remote.js +1 -1
- package/dist/src/execution/tasks/child/steps.d.ts +2 -0
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/run-parent.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.js +1 -1
- package/dist/src/execution/terminal-session-event.d.ts +13 -0
- package/dist/src/execution/terminal-session-event.js +1 -0
- package/dist/src/execution/terminal-session-failure-step.d.ts +1 -0
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/tool-run/answer.d.ts +3 -0
- package/dist/src/execution/tool-run/answer.js +1 -0
- package/dist/src/execution/tool-run/background.d.ts +14 -0
- package/dist/src/execution/tool-run/background.js +1 -0
- package/dist/src/execution/tool-run/cancel.d.ts +7 -0
- package/dist/src/execution/tool-run/cancel.js +1 -0
- package/dist/src/execution/tool-run/dispatch.d.ts +24 -0
- package/dist/src/execution/tool-run/dispatch.js +1 -0
- package/dist/src/execution/tool-run/emit-run-report-step.d.ts +7 -0
- package/dist/src/execution/tool-run/emit-run-report-step.js +1 -0
- package/dist/src/execution/tool-run/messages.d.ts +70 -0
- package/dist/src/execution/tool-run/messages.js +1 -0
- package/dist/src/execution/tool-run/owner-channels.d.ts +29 -0
- package/dist/src/execution/tool-run/owner-channels.js +1 -0
- package/dist/src/execution/tool-run/owner-inbox.d.ts +11 -0
- package/dist/src/execution/tool-run/owner-inbox.js +1 -0
- package/dist/src/execution/tool-run/owner.d.ts +13 -0
- package/dist/src/execution/tool-run/owner.js +1 -0
- package/dist/src/execution/tool-run/resume-hook-step.d.ts +4 -0
- package/dist/src/execution/tool-run/resume-hook-step.js +1 -0
- package/dist/src/execution/tool-run/run-control.d.ts +18 -0
- package/dist/src/execution/tool-run/run-control.js +1 -0
- package/dist/src/execution/tool-run/start.d.ts +11 -0
- package/dist/src/execution/tool-run/start.js +1 -0
- package/dist/src/execution/tool-run/types.d.ts +21 -0
- package/dist/src/execution/tool-run/types.js +1 -0
- package/dist/src/execution/tool-run/workflow.d.ts +9 -0
- package/dist/src/execution/tool-run/workflow.js +1 -0
- package/dist/src/execution/tools/subagent/local.js +1 -1
- package/dist/src/execution/turn-cancellation-control.d.ts +2 -0
- package/dist/src/execution/turn-cancellation-control.js +1 -1
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +4 -2
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
- package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v1.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.d.ts +0 -2
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v2.migration.d.ts +3 -0
- package/dist/src/execution/wire/session-inbox-wire.v2.migration.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.d.ts +480 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.migration.d.ts +3 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.migration.js +1 -0
- package/dist/src/execution/workflow-entry-finalization.js +1 -1
- package/dist/src/execution/workflow-entry.d.ts +5 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-registry.d.ts +5 -0
- package/dist/src/execution/workflow-registry.js +1 -0
- package/dist/src/execution/workflow-runtime.d.ts +17 -19
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/execution/workflow-webhook-route.d.ts +4 -0
- package/dist/src/execution/workflow-webhook-route.js +1 -0
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +10 -0
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +2 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tool-runs.d.ts +21 -0
- package/dist/src/harness/tool-runs.js +1 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/instrumentation/content-policy.d.ts +3 -1
- package/dist/src/instrumentation/content-policy.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +2 -2
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/attachments/errors.d.ts +3 -0
- package/dist/src/internal/authored-module-loader.d.ts +7 -1
- package/dist/src/internal/authored-module-loader.js +3 -3
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/authored-runtime-modules.d.ts +2 -0
- package/dist/src/internal/authored-runtime-modules.js +1 -1
- package/dist/src/internal/nitro/development-generation.d.ts +2 -0
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.d.ts +17 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.d.ts +19 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.js +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +17 -2
- package/dist/src/internal/workflow-bundle/builder-support.js +4 -3
- package/dist/src/internal/workflow-bundle/builder.d.ts +2 -2
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.d.ts +2 -0
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +3 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +6 -2
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +3 -0
- package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.d.ts +7 -0
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.js +1 -0
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +15 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -4
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/baggage.d.ts +6 -0
- package/dist/src/protocol/baggage.js +1 -0
- package/dist/src/public/channels/slack/attachments.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +7 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/attachments.d.ts +2 -2
- package/dist/src/public/channels/teams/attachments.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/attachments.js +1 -1
- package/dist/src/public/definitions/remote-agent.d.ts +6 -3
- package/dist/src/public/workflow/index.d.ts +3 -0
- package/dist/src/public/workflow/index.js +1 -0
- package/dist/src/public/workflow-modules.d.js +1 -0
- package/dist/src/public/workflow-modules.d.ts +11 -0
- package/dist/src/runtime/actions/keys.js +1 -1
- package/dist/src/runtime/tools/registry.js +1 -1
- package/dist/src/setup/connection-connector.d.ts +4 -2
- package/dist/src/setup/connection-connector.js +2 -2
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/flows/provider.d.ts +5 -0
- package/dist/src/setup/flows/provider.js +4 -4
- package/dist/src/setup/flows/registry-session.d.ts +24 -7
- package/dist/src/setup/flows/registry-session.js +1 -1
- package/dist/src/setup/flows/registry.d.ts +35 -29
- package/dist/src/setup/flows/registry.js +2 -1
- package/dist/src/setup/integrations/web/setup.d.ts +0 -2
- package/dist/src/setup/integrations/web/setup.js +1 -1
- package/dist/src/setup/prompter.d.ts +24 -4
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/connections/catalog.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/shared/dispatch-action.d.ts +6 -0
- package/dist/src/shared/forwarded-trace-policy.d.ts +28 -0
- package/dist/src/shared/forwarded-trace-policy.js +1 -0
- package/dist/src/shared/instrumentation-decision.d.ts +3 -0
- package/dist/src/shared/instrumentation-decision.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/behavior.d.ts +6 -0
- package/dist/src/tools/definition.d.ts +39 -3
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.d.ts +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/otel-declaration.d.ts +5 -3
- package/dist/src/tracing/otel-registration.d.ts +1 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +6 -0
- package/docs/channels/eve.mdx +14 -6
- package/docs/channels/mcp.mdx +4 -1
- package/docs/channels/teams.mdx +6 -1
- package/docs/concepts/sessions-runs-and-streaming.md +4 -2
- package/docs/guides/auth-and-route-protection.md +5 -1
- package/docs/guides/client/messages.mdx +6 -0
- package/docs/guides/dev-tui.md +30 -18
- package/docs/guides/instrumentation.md +1 -1
- package/docs/guides/remote-agents.md +25 -0
- package/docs/install-integrations.mdx +2 -0
- package/docs/instructions.mdx +1 -1
- package/docs/memory/custom-provider.md +214 -0
- package/docs/memory/file.md +129 -0
- package/docs/memory/meta.json +5 -0
- package/docs/memory/overview.mdx +282 -0
- package/docs/patterns/multi-tenant-memory.md +12 -20
- package/docs/reference/cli.md +2 -2
- package/docs/tools/meta.json +1 -1
- package/docs/tools/overview.mdx +7 -0
- package/docs/tools/workflows.mdx +288 -0
- package/package.json +18 -7
- package/dist/src/compiled/_chunks/workflow/dist-CqvWKNQv.js +0 -3
- package/dist/src/compiled/_chunks/workflow/dist-Dk0aQqFO.js +0 -40
- package/dist/src/compiled/_chunks/workflow/dist-DpYyXbJv.js +0 -1
- package/dist/src/compiled/_chunks/workflow/env-config-L94XftKz.js +0 -1
- package/dist/src/compiled/_chunks/workflow/frames-Dl2Hcma4.js +0 -3
- package/dist/src/compiled/_chunks/workflow/private-CuQ4HTFC.js +0 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-E-Nkx8q_.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-cIeex2KF.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-CxFsdxB_.js +0 -1
- package/dist/src/compiled/_chunks/workflow/spec-version-DBUVfF_R.js +0 -1
- package/dist/src/compiled/_chunks/workflow/undici-DznrXKcM.js +0 -95
- package/dist/src/compiled/_chunks/workflow/wait-until-BZHmJCAW.js +0 -15
- package/dist/src/compiled/_chunks/workflow/ws-transport-Ct6yyRWZ.js +0 -1
- package/dist/src/internal/authored-directive-prologue.d.ts +0 -4
- package/dist/src/internal/authored-directive-prologue.js +0 -1
- package/docs/memory.md +0 -408
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{CHANNEL_CONTEXT_KEY_NAME,SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult}from"#execution/delegated-parent-result.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{finalizeDone,finalizeExpiredSession}from"#execution/workflow-entry-finalization.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";async function workflowEntry(n){"use workflow";let{workflowRunId:r,workflowStartedAt:i}=getWorkflowMetadata(),s=n.serializedContext[`eve.continuationToken`]||``,l=n.serializedContext[`eve.mode`],p=n.serializedContext[`eve.capabilities`],g=n.serializedContext[`eve.bundle`];n.serializedContext[`eve.sessionId`]=r;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let a=readRootSessionId(n.serializedContext),o=readSerializedSubagentDepth(n.serializedContext),m=n.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:h}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:s,dynamicSubagentAgentConfig:m,inheritedLimits:n.limits,nodeId:g.nodeId,outputSchema:n.input.outputSchema,rootSessionId:a,sessionId:r,subagentDepth:o,taskOwned:isTaskOwnedSerializedContext(n.serializedContext)});v.lastSessionState=h,hasGuaranteedRootLineage(n.serializedContext)||(v.caller=await resolveInitialTurnCallerStep({serializedContext:n.serializedContext})),v.callerResolved=!0;let y=await runDriverLoop({capabilities:p,driverWritable:_,initialInput:{deliveryMetadata:n.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...n.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[attachClientContext({message:n.input.message,context:n.input.context,outputSchema:n.input.outputSchema},readClientContext(n.input))],requestId:readChannelRequestId(n.serializedContext)},crashCleanupState:v,mode:l,serializedContext:n.serializedContext,sessionState:h,sessionTimeoutDeadline:n.sessionTimeoutMs===!1?void 0:new Date(i.getTime()+(n.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return y.kind===`result`?y.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:l,serializedContext:y.serializedContext,sessionState:y.sessionState})}catch(e){if(v.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:n.serializedContext,sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:_,serializedContext:n.serializedContext}),l===`task`)await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:n.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(n.serializedContext,e),serializedContext:n.serializedContext});else{let t=await resolveCallerForCrash(v,n.serializedContext);t!==void 0&&await notifyTurnCallerStep({caller:t,lifecycle:`terminal`,sessionId:r,settled:{isError:!0,output:e}})}throw createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}function hasGuaranteedRootLineage(e){if(e[SESSION_CALLBACK_CONTEXT_KEY_NAME]!==void 0||e[`eve.parentSession`]!==void 0||e[`eve.subagentDepth`]!==void 0)return!1;let t=e[CHANNEL_CONTEXT_KEY_NAME];if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`kind`);return typeof n==`string`&&n!==SUBAGENT_ADAPTER_KIND}async function runDriverLoop(e){let t=new Map,nextParkedActivity=async n=>{let r=new Set(n.expectedAttemptIds);for(let e of t.keys())r.has(e)||t.delete(e);for(;;){if(r.size>0&&[...r].every(e=>t.has(e))){let e=[...r].map(e=>t.get(e));return t.clear(),{kind:`authorization-resume`,payloads:e}}let n=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,commandInbox:l,deferDeliveries:e.mode===`task`&&r.size>0,driverWritable:e.driverWritable,seenTaskDeliveries:c,stateCursor:f});if(n.kind!==`authorization`)return n;for(let e of n.payloads){let n=e.authorizationCallback;typeof n?.attemptId==`string`&&r.has(n.attemptId)&&!t.has(n.attemptId)&&t.set(n.attemptId,e)}if(n.closed){let e=[...t.values()];return t.clear(),{kind:`authorization-resume`,payloads:e}}}},r=0,nextTurnControlToken=()=>`${e.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],o=new Set,c=new Set,l=createSessionCommandInbox(),u=sessionCommandHookToken(e.sessionState.sessionId);await l.claimStable(u),await l.claimAuthorization(`${e.sessionState.sessionId}:auth`);let d=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,token:u}),f=new SessionStateCursor({serializedContext:e.serializedContext,sessionState:e.sessionState}),m,runTurn=async t=>{let n=e.crashCleanupState.caller;n?.taskId!==void 0&&(c.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:f.sessionState.sessionId,childTurnId:activeTurnId(f.sessionState.emissionState)}));let r=n===void 0?f.serializedContext:await bindTurnCallerContextStep({caller:n,serializedContext:f.serializedContext}),s=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,capabilities:e.capabilities,commandInbox:l,controlToken:nextTurnControlToken(),delivery:t,mode:e.mode,parentWritable:e.driverWritable,serializedContext:r,seenTaskDeliveries:c,sessionState:f.sessionState});return await m?.(),m=s.dispose,f.adoptState(s.action),e.crashCleanupState.lastSessionState=f.sessionState,s.action};try{if(e.sessionState.continuationToken)try{await l.rekeyContinuation(e.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await d?.start();let t=await runTurn(e.initialInput);for(;;){if(t.kind===`done`)return{kind:`result`,result:await finalizeDone({action:t,caller:e.crashCleanupState.caller,mode:e.mode})};if(t.kind!==`park`)throw Error(`Driver received unexpected turn action "${t.kind}".`);if(t.cancelled===!0){let t=await settleCancelledTurnStep({parentWritable:e.driverWritable,serializedContext:f.serializedContext,sessionState:f.sessionState});f.adoptState(t);let n={caller:e.crashCleanupState.caller,sessionId:f.sessionState.sessionId};await notifyCancelledTaskCallerStep(t.usage===void 0?n:{...n,usage:t.usage}),e.crashCleanupState.lastSessionState=f.sessionState}f.sessionState.continuationToken&&await l.rekeyContinuation(f.sessionState.continuationToken);let n=t.settled;t.cancelled!==!0&&n!==void 0?(e.crashCleanupState.caller!==void 0&&await notifyTurnCallerStep({caller:e.crashCleanupState.caller,lifecycle:`parked`,sessionId:f.sessionState.sessionId,settled:n}),e.crashCleanupState.caller=void 0):t.cancelled===!0&&(e.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:t.authorizationAttemptIds??[]});if(e.crashCleanupState.lastSessionState=f.sessionState,r.kind===`authorization-resume`){t=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:f.serializedContext,sessionState:f.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:f.serializedContext,sessionState:f.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){t=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return await terminateChildSessionsStep({serializedContext:f.serializedContext,sessionState:f.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:f.serializedContext,sessionState:f.sessionState});let n=await settleCancelledTurnStep({parentWritable:e.driverWritable,serializedContext:f.serializedContext,sessionState:f.sessionState});f.adoptState(n),t={...t,settled:void 0},e.crashCleanupState.caller=void 0,e.crashCleanupState.lastSessionState=f.sessionState;continue}r.delivery.caller!==void 0&&(e.crashCleanupState.caller=r.delivery.caller),t=await runTurn(r.delivery)}}finally{await m?.(),await d?.dispose(),await l.dispose()}}export{workflowEntry};
|
|
1
|
+
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{CHANNEL_CONTEXT_KEY_NAME,SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{activeTurnId}from"#harness/active-turn-id.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult}from"#execution/delegated-parent-result.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{finalizeDone}from"#execution/workflow-entry-finalization.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{finalizeTerminalSession}from"#execution/finalize-terminal-session.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{settleContinuationConflictStep}from"#execution/continuation-conflict-step.js";async function workflowEntry(r){"use workflow";let{workflowRunId:i,workflowStartedAt:l}=getWorkflowMetadata(),u=r.serializedContext[`eve.continuationToken`]||``,m=r.serializedContext[`eve.mode`],h=r.serializedContext[`eve.capabilities`],_=r.serializedContext[`eve.bundle`];r.serializedContext[`eve.sessionId`]=i;let S=getWritable(),w={activeTurnId:void 0,caller:void 0,callerResolved:!1,lastSessionState:void 0,serializedContext:r.serializedContext,terminalEmitted:!1};try{let a=readRootSessionId(r.serializedContext),o=readSerializedSubagentDepth(r.serializedContext),g=r.serializedContext[`eve.dynamicSubagentAgentConfig`],v=createSessionCommandInbox(),y=sessionCommandHookToken(i),b=`${i}:auth`,x,C;try{let[n,d,p,T]=await Promise.allSettled([createSessionStep({compiledArtifactsSource:_.source,continuationToken:u,dynamicSubagentAgentConfig:g,inheritedLimits:r.limits,nodeId:_.nodeId,outputSchema:r.input.outputSchema,rootSessionId:a,sessionId:i,subagentDepth:o,taskOwned:isTaskOwnedSerializedContext(r.serializedContext)}),v.claimStable(y),v.claimAuthorization(b),v.rekeyContinuation(u)]);if(n.status===`rejected`)throw n.reason;if(d.status===`rejected`)throw d.reason;if(p.status===`rejected`)throw p.reason;if(T.status===`rejected`){if(isHookConflictError(T.reason))return(r.activityCollectorRunId!==void 0||r.continuationConflictCommand!==void 0)&&await settleContinuationConflictStep({activityCollectorRunId:r.activityCollectorRunId,command:r.continuationConflictCommand,continuationToken:u,ownerSessionId:typeof T.reason.conflictingRunId==`string`?T.reason.conflictingRunId:void 0}),{output:``};throw T.reason}x=n.value.state,w.lastSessionState=x,hasGuaranteedRootLineage(r.serializedContext)||(w.caller=await resolveInitialTurnCallerStep({serializedContext:r.serializedContext})),w.callerResolved=!0,C=await runDriverLoop({capabilities:h,commandInbox:v,driverWritable:S,initialInput:{deliveryMetadata:r.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...r.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[attachClientContext({message:r.input.message,context:r.input.context,outputSchema:r.input.outputSchema},readClientContext(r.input))],requestId:readChannelRequestId(r.serializedContext)},crashCleanupState:w,mode:m,serializedContext:r.serializedContext,sessionState:x,sessionTimeoutDeadline:r.sessionTimeoutMs===!1?void 0:new Date(l.getTime()+(r.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS)),stableCommandToken:y})}finally{await v.dispose()}return C.kind===`result`?C.result:await finalizeTerminalSession({caller:w.caller,driverWritable:S,mode:m,notifyCaller:C.notifyCaller,serializedContext:C.serializedContext,sessionState:C.sessionState,terminalState:w})}catch(e){if(w.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:w.serializedContext,sessionState:w.lastSessionState}),!w.terminalEmitted)if(await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:S,serializedContext:w.serializedContext,turnId:w.activeTurnId}),m===`task`)await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:r.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(r.serializedContext,e),serializedContext:r.serializedContext});else{let t=await resolveCallerForCrash(w,r.serializedContext);t!==void 0&&await notifyTurnCallerStep({caller:t,lifecycle:`terminal`,sessionId:i,settled:{isError:!0,output:e}})}throw createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}function hasGuaranteedRootLineage(e){if(e[SESSION_CALLBACK_CONTEXT_KEY_NAME]!==void 0||e[`eve.parentSession`]!==void 0||e[`eve.subagentDepth`]!==void 0)return!1;let t=e[CHANNEL_CONTEXT_KEY_NAME];if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`kind`);return typeof n==`string`&&n!==SUBAGENT_ADAPTER_KIND}async function runDriverLoop(e){let t=e.commandInbox,n=new Map,nextParkedActivity=async r=>{let c=new Set(r.expectedAttemptIds);for(let e of n.keys())c.has(e)||n.delete(e);for(;;){if(c.size>0&&[...c].every(e=>n.has(e))){let e=[...c].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let r=await nextTurnDelivery({awaitAuthorizationCallbacks:c.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,commandInbox:t,deferDeliveries:e.mode===`task`&&c.size>0,driverWritable:e.driverWritable,seenTaskDeliveries:s,stateCursor:l});if(r.kind!==`authorization`)return r;for(let e of r.payloads){let t=e.authorizationCallback;typeof t?.attemptId==`string`&&c.has(t.attemptId)&&!n.has(t.attemptId)&&n.set(t.attemptId,e)}if(r.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e}}}},r=0,nextTurnControlToken=()=>`${e.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],o=new Set,s=new Set,c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,token:e.stableCommandToken}),l=new SessionStateCursor({serializedContext:e.serializedContext,sessionState:e.sessionState}),d,runTurn=async n=>{let r=e.crashCleanupState.caller;r?.taskId!==void 0&&(s.add(r.taskId),await notifyTaskTurnStartedStep({caller:r,childSessionId:l.sessionState.sessionId,childTurnId:activeTurnId(l.sessionState.emissionState)}));let c=r===void 0?l.serializedContext:await bindTurnCallerContextStep({caller:r,serializedContext:l.serializedContext}),f=activeTurnId(l.sessionState.emissionState);e.crashCleanupState.activeTurnId=f;let p=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,capabilities:e.capabilities,commandInbox:t,controlToken:nextTurnControlToken(),delivery:n,mode:e.mode,parentWritable:e.driverWritable,serializedContext:c,seenTaskDeliveries:s,sessionState:l.sessionState});return e.crashCleanupState.activeTurnId=p.action.kind===`park`&&p.action.cancelled===!0?f:void 0,e.crashCleanupState.lastSessionState=p.action.sessionState,e.crashCleanupState.serializedContext=p.action.serializedContext,p.action.kind===`done`&&(e.crashCleanupState.terminalEmitted=!0),await d?.(),d=p.dispose,l.adoptState(p.action),p.action};try{await c?.start();let n=await runTurn(e.initialInput);for(;;){if(n.kind===`done`)return{kind:`result`,result:await finalizeDone({action:n,caller:e.crashCleanupState.caller,mode:e.mode})};if(n.kind!==`park`)throw Error(`Driver received unexpected turn action "${n.kind}".`);if(n.cancelled===!0){let t=await settleCancelledTurnStep({parentWritable:e.driverWritable,serializedContext:l.serializedContext,sessionState:l.sessionState});l.adoptState(t),e.crashCleanupState.activeTurnId=void 0,e.crashCleanupState.lastSessionState=l.sessionState,e.crashCleanupState.serializedContext=l.serializedContext;let n={caller:e.crashCleanupState.caller,sessionId:l.sessionState.sessionId};await notifyCancelledTaskCallerStep(t.usage===void 0?n:{...n,usage:t.usage})}l.sessionState.continuationToken&&await t.rekeyContinuation(l.sessionState.continuationToken);let r=n.settled;n.cancelled!==!0&&r!==void 0?(e.crashCleanupState.caller!==void 0&&await notifyTurnCallerStep({caller:e.crashCleanupState.caller,lifecycle:`parked`,sessionId:l.sessionState.sessionId,settled:r}),e.crashCleanupState.caller=void 0):n.cancelled===!0&&(e.crashCleanupState.caller=void 0);let i=await nextParkedActivity({expectedAttemptIds:n.authorizationAttemptIds??[]});if(e.crashCleanupState.lastSessionState=l.sessionState,e.crashCleanupState.serializedContext=l.serializedContext,i.kind===`authorization-resume`){n=await runTurn({kind:`deliver`,payloads:i.payloads});continue}if(i.kind===`expired`)return{kind:`terminal`,notifyCaller:!0,serializedContext:l.serializedContext,sessionState:l.sessionState};if(i.kind===`reset`)return{kind:`terminal`,notifyCaller:!1,serializedContext:l.serializedContext,sessionState:l.sessionState};if(i.kind===`clear`||i.kind===`compact`){n=await runTurn({kind:i.kind});continue}if(i.kind===`closed`)return{kind:`terminal`,notifyCaller:!1,serializedContext:l.serializedContext,sessionState:l.sessionState};if(i.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:l.serializedContext,sessionState:l.sessionState});let t=await settleCancelledTurnStep({parentWritable:e.driverWritable,serializedContext:l.serializedContext,sessionState:l.sessionState});l.adoptState(t),n={...n,settled:void 0},e.crashCleanupState.caller=void 0,e.crashCleanupState.lastSessionState=l.sessionState,e.crashCleanupState.serializedContext=l.serializedContext;continue}i.delivery.caller!==void 0&&(e.crashCleanupState.caller=i.delivery.caller),n=await runTurn(i.delivery)}}finally{await d?.(),await c?.dispose()}}export{workflowEntry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const WORKFLOW_REGISTRY_GLOBAL=`__private_workflows`;function readRegisteredWorkflow(e){return globalThis[WORKFLOW_REGISTRY_GLOBAL]?.get(e)}export{WORKFLOW_REGISTRY_GLOBAL,readRegisteredWorkflow};
|
|
@@ -2,18 +2,6 @@ import type { CancelTurnInput, CancelTurnResult, Runtime } from "#channel/types.
|
|
|
2
2
|
import { type Run, type StartOptionsWithoutDeploymentId, type WorkflowFunction, type WorkflowMetadata } from "#internal/workflow/runtime.js";
|
|
3
3
|
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
4
4
|
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
|
|
5
|
-
export declare const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE = "deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";
|
|
6
|
-
/**
|
|
7
|
-
* Workflow function names whose bundled id is stable across deployments
|
|
8
|
-
* (no `@<pkg.version>` stamp). The bundler reads this set when emitting
|
|
9
|
-
* the workflow id so cross-deployment routing — `start(ref, args, {
|
|
10
|
-
* deploymentId: "latest" })` — finds the same workflow on a newer
|
|
11
|
-
* deployment even when the eve version differs.
|
|
12
|
-
*
|
|
13
|
-
* Both halves of the contract (bundler output and runtime reference
|
|
14
|
-
* template) read this single set so they cannot drift.
|
|
15
|
-
*/
|
|
16
|
-
export declare const STABLE_WORKFLOW_NAMES: ReadonlySet<string>;
|
|
17
5
|
interface WorkflowHookRecord {
|
|
18
6
|
readonly runId: string;
|
|
19
7
|
}
|
|
@@ -28,10 +16,9 @@ export declare const workflowEntryReference: {
|
|
|
28
16
|
};
|
|
29
17
|
/**
|
|
30
18
|
* Stable workflow reference used by the driver to dispatch per-turn
|
|
31
|
-
* child workflow runs. The id omits the package version stamp so
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* version differs from the caller's deployment.
|
|
19
|
+
* child workflow runs. The id omits the package version stamp so an
|
|
20
|
+
* explicitly stamped accepting deployment can resolve the workflow even
|
|
21
|
+
* when its eve version differs from the driver's deployment.
|
|
35
22
|
*/
|
|
36
23
|
export declare const turnWorkflowReference: {
|
|
37
24
|
workflowId: string;
|
|
@@ -48,6 +35,10 @@ export declare const taskRunWorkflowReference: {
|
|
|
48
35
|
export declare const activityCollectorWorkflowReference: {
|
|
49
36
|
workflowId: string;
|
|
50
37
|
};
|
|
38
|
+
/** Stable workflow reference for authored workflow tool runs. */
|
|
39
|
+
export declare const toolRunWorkflowReference: {
|
|
40
|
+
workflowId: string;
|
|
41
|
+
};
|
|
51
42
|
/**
|
|
52
43
|
* Creates a workflow-backed runtime whose long-lived driver owns the
|
|
53
44
|
* event stream and dispatches each turn as a child workflow run.
|
|
@@ -59,10 +50,17 @@ export declare function createWorkflowRuntime(config: {
|
|
|
59
50
|
}): Runtime;
|
|
60
51
|
/** Requests cancellation through a session's stable command inbox. */
|
|
61
52
|
export declare function requestWorkflowTurnCancellation(input: CancelTurnInput): Promise<CancelTurnResult>;
|
|
53
|
+
/**
|
|
54
|
+
* Resolves hook ownership for replay-idempotent work already running inside a
|
|
55
|
+
* durable step. Request handlers must return from start/resume acceptance and
|
|
56
|
+
* leave ownership arbitration to the workflow.
|
|
57
|
+
*/
|
|
62
58
|
export declare function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord>;
|
|
59
|
+
/** Starts a workflow on the deployment executing this call. */
|
|
60
|
+
export declare function startWorkflowOnCurrentDeployment<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs, options?: StartOptionsWithoutDeploymentId): Promise<Run<unknown> | Run<TResult>>;
|
|
63
61
|
/**
|
|
64
|
-
* Starts
|
|
65
|
-
*
|
|
62
|
+
* Starts on the deployment that accepted a delivery when one was stamped,
|
|
63
|
+
* otherwise stays on the deployment executing this call.
|
|
66
64
|
*/
|
|
67
|
-
export declare function
|
|
65
|
+
export declare function startWorkflowOnAcceptedDeployment<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs, acceptedDeploymentId: string | undefined, options?: StartOptionsWithoutDeploymentId): Promise<Run<unknown> | Run<TResult>>;
|
|
68
66
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import{createEveActivityRoutePath}from"#protocol/routes.js";import{createLogger,logError}from"#internal/logging.js";import{getChannelActivityPresentation}from"#channel/activity-renderer.js";import{
|
|
1
|
+
import{randomBytes}from"node:crypto";import{createEveActivityRoutePath}from"#protocol/routes.js";import{createLogger,logError}from"#internal/logging.js";import{getChannelActivityPresentation}from"#channel/activity-renderer.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{ActivityObserverKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{cancelRun,getHookByToken,getRun,getWorld,start}from"#internal/workflow/runtime.js";import{createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{serializeContext}from"#context/serialize.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{initializeSessionInstrumentation}from"#instrumentation/runtime.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";import{isAgentTraceContext}from"#tracing/agent-trace-context.js";import{ACTIVITY_COLLECTOR_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME,TOOL_RUN_WORKFLOW_NAME,TURN_WORKFLOW_NAME,WORKFLOW_ENTRY_NAME}from"#execution/stable-workflow-names.js";const EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`},activityCollectorWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`},toolRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TOOL_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(n){return{async createSession(a){let o=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:n.compiledArtifactsSource,nodeId:n.nodeId}),s=buildRunContext({bundle:o,dynamicSubagentAgentConfig:n.dynamicSubagentAgentConfig,run:a}),c=resolveEffectiveAgentRuntime(o,s);initializeSessionInstrumentation({agentName:c.turnAgent.id,ctx:s,parentTraceContext:a.parentTraceContext});let l=c.limits?.sessionTimeoutMs,u,d=a.activityObserver;if(a.parent===void 0&&d===void 0&&(getChannelActivityPresentation(a.adapter)?.renderers.length??0)>0){let n=serializeContext(s),r=randomBytes(32).toString(`base64url`),i={expiresAt:new Date(Date.now()+(typeof l==`number`?l:864e5)).toISOString(),serializedContext:n,token:r};try{u=(await startWorkflowOnCurrentDeployment(activityCollectorWorkflowReference,[i])).runId,d={sink:{url:createWorkflowCallbackUrl(resolveWorkflowCallbackBaseUrl(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:3000`),createEveActivityRoutePath(r)),version:1}},s.set(ActivityObserverKey,d)}catch{await cancelActivityCollector(u),u=void 0,log.warn(`failed to start activity collector`)}}let f=serializeContext(s),p=readParentLineage(f),m={input:a.input,limits:a.limits,serializedContext:f};u!==void 0&&(m.activityCollectorRunId=u),a.continuationConflictCommand!==void 0&&(m.continuationConflictCommand=a.continuationConflictCommand),l!==void 0&&(m.sessionTimeoutMs=l);let h={...p.sessionId===void 0?buildSessionAttributes({inputMessage:a.title??a.input.message,serializedContext:f}):buildSubagentRootAttributes({identity:{nodeId:o.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:p.callId,parentSessionId:p.sessionId,parentTurnId:p.turnId,rootSessionId:p.rootSessionId??p.sessionId,serializedContext:f}),...a.externalInvocation===void 0?{}:buildInvocationAttributes(a.externalInvocation)},g;try{g=await startWorkflowOnCurrentDeployment(workflowEntryReference,[m],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(h)})}catch(e){throw await cancelActivityCollector(u),logError(log,`failed to start workflow run`,e,{continuationToken:a.continuationToken}),e}let _,getEvents=()=>(_??=parseNdjsonStream(()=>getRun(g.runId).getReadable()),_);return{get events(){return getEvents()},sessionId:g.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(t){if(HookNotFoundError.is(t))return;throw logError(log,`failed to resolve session by continuation token`,t,{continuationToken:e}),t}}}}async function cancelActivityCollector(e){if(e!==void 0)try{await cancelRun(await getWorld(),e,{cancelReason:`Root session creation did not complete`})}catch{log.warn(`failed to cancel unowned activity collector`)}}async function dispatchWorkflowCommand(e,t){let n;try{n=normalizeWorkflowHook(await resumeSessionInbox(e,t))}catch(n){if(isInactiveCommandTarget(n))return inactiveCommandResult(t);throw logError(log,`failed to dispatch session command`,n,{command:t.kind,token:e}),n}return t.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(n.runId),n.runId),activeCommandResult(t,n.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowOnCurrentDeployment(e,t,n){return await startWorkflowOnDeployment(e,t,process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0,n)}async function startWorkflowOnAcceptedDeployment(e,t,n,r){return n===void 0?await startWorkflowOnCurrentDeployment(e,t,r):await startWorkflowOnDeployment(e,t,n,r)}async function startWorkflowOnDeployment(e,t,n,r){return await withWorkflowStartContext(async()=>n===void 0?r===void 0?await start(e,t):await start(e,t,r):await start(e,t,{...r,deploymentId:n}))}async function withWorkflowStartContext(e){let t=context.active(),n=isAgentTraceContext(t)?trace.deleteSpan(t):t;return await context.with(n,e)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{activityCollectorWorkflowReference,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowOnAcceptedDeployment,startWorkflowOnCurrentDeployment,taskRunWorkflowReference,toolRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{coalesceTurnInputs}from"#harness/messages.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{activeTurnId}from"#harness/active-turn-id.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&(c.set(TurnTaskDeliveryKey,`none`),c.delete(TurnTaskStateKey));let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&d&&f.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`task-update`);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=bindSessionInstrumentation({agentName:f.turnAgent.id,ctx:c,rootSessionId:g.rootSessionId??g.sessionId,sessionId:g.sessionId}),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>v?.instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>v?.instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await v?.flush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(d&&c.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:s.state,turnId:activeTurnId(y)});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),c.set(TurnTaskStateKey,e.context))}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>v?.instrumentChannelDelivery({ctx:c,includeTurn:!1,outcome:`completed`})),await v?.flush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),r=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r,tasksEnabled:d}}let S=u.hookRegistry,C=bindDynamicConnections(c,u.resolvedAgent),w=u.resolvedAgent.dynamicInstructionsResolvers??[],T=u.resolvedAgent.dynamicSkillResolvers??[],E=u.subagentRegistry.dynamicResolvers??[],D=u.resolvedAgent.dynamicToolResolvers??[],O={...u.graph.root,turnAgent:f.turnAgent},k=buildRuntimeIdentity(O);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:E,event:e,messages:_.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:D,event:e,messages:_.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:c,event:createTurnStartedEvent({sequence:y.sequence,turnId:activeTurnId(y)}),messages:_.initial.messages,resolvers:D})}}catch(e){throw await failChannelDeliveries(e),e}let A=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await A.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e),r=await dispatchMemoryLifecycleEvent({abortSignal:o.abortSignal,appRoot:O.agent?.metadata?.appRoot??``,ctx:c,event:e,memories:O.agent?.memories??[],messages:t,nodeId:u.nodeId??`__root__`});observeSessionActivity({ctx:c,event:n,sessionId:g.sessionId}),await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:r,scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await C.dispatch(n),await dispatchDynamicSubagentEvent({ctx:c,resolvers:E,event:n,messages:r}),await dispatchDynamicToolEvent({ctx:c,resolvers:D,event:n,messages:r}),await dispatchDynamicSkillEvent({ctx:c,resolvers:T,event:n,messages:r}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:w,event:n,messages:r})},j=c.require(ModeKey),M;try{throwIfTurnAborted(o.abortSignal),M=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:j,session:e});if(await C.rehydrate(y,k,isHarnessBetweenTurns(t)),h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:v});try{e=await emitTurnPreamble(handleEvent,{},e,k,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),instrumentation:v,mode:j,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:O,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;A.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c),r=await preserveCancelledTurnMessage(n?.backgroundTaskSession??g,x);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:r}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:createDurableSessionState({session:r})}}let N=reconcileSessionContinuationToken(c,M.session),P=serializeContext(c);M={...M,session:N};let F=createDurableSessionState({session:M.session}),I=readTurnSleepDurationMs(c),L=I===void 0?{}:{sleepDurationMs:I},R=M.backgroundTasks===void 0||M.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:M.backgroundTaskSession}),backgroundTasks:M.backgroundTasks};if(M.next!==null&&typeof M.next==`object`&&`done`in M.next){if(j===`task`&&hasPendingInputBatch(M.session.state))throw A.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await A.close();let e=getTurnUsageState(M.session.state)?.session;return{action:`done`,...R,output:M.next.output,isError:M.next.isError,...L,serializedContext:P,sessionState:F,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(M.session).delta}}if(M.next===null){A.releaseLock();let e=getPendingWorkflowInterrupt(M.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...R,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...L,serializedContext:P,sessionState:F};let t=derivePendingState(M.session);if(M.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(M.session);return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:createDurableSessionState({session:n}),settled:{output:M.settledTurn.output,isError:M.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:F,tasksEnabled:d}}return A.releaseLock(),{action:`continue`,...R,...L,serializedContext:P,sessionState:F}}export{turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{coalesceTurnInputs}from"#harness/messages.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{deferMismatchedInlineTurnStep}from"#execution/accepted-delivery-deployment.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(a){"use step";let o=deferMismatchedInlineTurnStep(a);if(o!==void 0)return o;let s=a,c=await readDurableSession(s.sessionState),l=await deserializeContext(s.serializedContext);a.input?.kind===`deliver`&&(l.set(TurnTaskDeliveryKey,`none`),l.delete(TurnTaskStateKey));let u=l.require(ChannelKey),d=l.require(BundleKey),f=d.resolvedAgent.config?.experimental?.tasks===!0;l.set(TasksEnabledKey,f);let p=resolveEffectiveAgentRuntime(d,l),m=isTaskOwnedSerializedContext(s.serializedContext)&&f&&p.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`task-update`);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let h=getPendingAuthorization(c.state),g;if(h&&s.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(h,s.input.payloads);if(s={...s,input:{...s.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);l.set(PendingAuthorizationResultKey,n),c={...c,state:clearPendingAuthorization(c.state,n.map(e=>e.attemptId??e.name))},g=e,t.length===0&&(s={...s,input:void 0})}}s.input?.kind===`deliver`&&s.input.auth!==void 0&&l.set(AuthKey,s.input.auth??null);let _=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.thresholdPercent},durable:c,turnAgent:p.turnAgent}),v=createExecutionHistoryView(_),y=bindSessionInstrumentation({agentName:p.turnAgent.id,ctx:l,rootSessionId:_.rootSessionId??_.sessionId,sessionId:_.sessionId}),b=getHarnessEmissionState(_.state);a.input?.kind===`deliver`&&await contextStorage.run(l,()=>y?.instrumentChannelDelivery({agentName:d.turnAgent.id,ctx:l,delivery:a.input,rootSessionId:_.rootSessionId??_.sessionId,sequence:b.sequence,sessionId:_.sessionId,turnId:activeTurnId(b)}));let failChannelDeliveries=async e=>{await contextStorage.run(l,()=>y?.instrumentChannelDelivery({ctx:l,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await y?.flush()},x=buildAdapterContext(u,l),S;if(s.input?.kind===`deliver`){let e=[];try{for(let n of s.input.payloads){let r=u.deliver?await u.deliver(n,x):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}S=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else s.input?.kind===`runtime-action-result`&&(s.input.acceptedAtMsByCallId!==void 0&&l.set(RuntimeActionSettlementTimesKey,s.input.acceptedAtMsByCallId),S={runtimeActionResults:s.input.results});if(S!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:c.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(l.set(TurnTaskDeliveryKey,e.phase),S={...S,context:[...S.context??[],e.context]})}if(f&&l.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:c.state,turnId:activeTurnId(b)});e!==void 0&&(l.set(TurnTaskDeliveryKey,e.phase),l.set(TurnTaskStateKey,e.context))}if(s.input?.kind===`deliver`&&setChannelContext(l,{...u,state:{...x.state}}),s.input?.kind===`deliver`&&S===void 0){await contextStorage.run(l,()=>y?.instrumentChannelDelivery({ctx:l,includeTurn:!1,outcome:`completed`})),await y?.flush();let e=reconcileSessionContinuationToken(l,_),t=serializeContext(l),r=e===_?s.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r,tasksEnabled:f}}let C=d.hookRegistry,w=bindDynamicConnections(l,d.resolvedAgent),T=d.resolvedAgent.dynamicInstructionsResolvers??[],E=d.resolvedAgent.dynamicSkillResolvers??[],D=d.subagentRegistry.dynamicResolvers??[],O=d.resolvedAgent.dynamicToolResolvers??[],k={...d.graph.root,turnAgent:p.turnAgent},A=buildRuntimeIdentity(k);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(d.compiledArtifactsSource);if(!b.sessionStarted)l.set(SessionDynamicSubagentRuntimeRevisionKey,t),l.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:A});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:l,resolvers:D,event:e,messages:v.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:l,resolvers:O,event:e,messages:v.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:l,event:createTurnStartedEvent({sequence:b.sequence,turnId:activeTurnId(b)}),messages:v.initial.messages,resolvers:O})}}catch(e){throw await failChannelDeliveries(e),e}let j=s.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(u,t,x);setChannelContext(l,{...u,state:{...x.state}});let r=stampMessageStreamEvent(n);return await j.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(l,e)?stampMessageStreamEvent(e):await emit(e),r=await dispatchMemoryLifecycleEvent({abortSignal:s.abortSignal,appRoot:k.agent?.metadata?.appRoot??``,ctx:l,event:e,memories:k.agent?.memories??[],messages:t,nodeId:d.nodeId??`__root__`});observeSessionActivity({ctx:l,event:n,sessionId:_.sessionId}),await dispatchStreamEventHooks({ctx:l,registry:C,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:l,dynamicModel:p.turnAgent.dynamicModel,event:n,messages:r,scope:{moduleMap:d.moduleMap,nodeId:d.nodeId}}),await w.dispatch(n),await dispatchDynamicSubagentEvent({ctx:l,resolvers:D,event:n,messages:r}),await dispatchDynamicToolEvent({ctx:l,resolvers:O,event:n,messages:r}),await dispatchDynamicSkillEvent({ctx:l,resolvers:E,event:n,messages:r}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:T,event:n,messages:r})},M=l.require(ModeKey),N;try{throwIfTurnAborted(s.abortSignal),N=await runBackgroundStep(l,_,async e=>{l.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:S,mode:M,session:e});if(await w.rehydrate(b,A,isHarnessBetweenTurns(t)),g){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(l,v.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:y});try{e=await emitTurnPreamble(handleEvent,{},e,A,r)}finally{n=drainDynamicInstructionUserMessages(l),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of g){let r=h?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.thresholdPercent},session:e,systemPromptAdditions:m?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:p.turnAgent}),i=f?await appendTaskAgentAnnouncement(r,v.messages(r)):r;return createExecutionNodeStep({abortSignal:s.abortSignal,capabilities:n,clearOnly:s.input?.kind===`clear`,compactOnly:s.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:v.projector,historyView:v.prepare(i),instrumentation:y,mode:M,modelResolutionScope:{moduleMap:d.moduleMap,nodeId:d.nodeId},node:k,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,S)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;j.releaseLock();let t=serializeContext(l),n=readRetainedBackgroundToolResult(l),r=await preserveCancelledTurnMessage(n?.backgroundTaskSession??_,S);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:r}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(s.serializedContext,t),t),t),sessionState:createDurableSessionState({session:r})}}let P=reconcileSessionContinuationToken(l,N.session),F=serializeContext(l);N={...N,session:P};let I=createDurableSessionState({session:N.session}),L=readTurnSleepDurationMs(l),R=L===void 0?{}:{sleepDurationMs:L},z=N.backgroundTasks===void 0||N.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:N.backgroundTaskSession}),backgroundTasks:N.backgroundTasks};if(N.next!==null&&typeof N.next==`object`&&`done`in N.next){if(M===`task`&&hasPendingInputBatch(N.session.state))throw j.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await j.close();let e=getTurnUsageState(N.session.state)?.session;return{action:`done`,...z,output:N.next.output,isError:N.next.isError,...R,serializedContext:F,sessionState:I,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(N.session).delta}}if(N.next===null){j.releaseLock();let e=getPendingWorkflowInterrupt(N.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...z,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...R,serializedContext:F,sessionState:I};let t=derivePendingState(N.session);if(N.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(N.session);return{action:`park`,...z,...t,...R,serializedContext:F,sessionState:createDurableSessionState({session:n}),settled:{output:N.settledTurn.output,isError:N.settledTurn.isError,usage:e},tasksEnabled:f}}return{action:`park`,...z,...t,...R,serializedContext:F,sessionState:I,tasksEnabled:f}}return j.releaseLock(),{action:`continue`,...z,...R,serializedContext:F,sessionState:I}}export{turnStep};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { RouteContext } from "#public/definitions/channel.js";
|
|
2
|
+
/** The path `createWebhook()` mints, so external systems call back without knowing eve. */
|
|
3
|
+
export declare const WORKFLOW_WEBHOOK_ROUTE_PATTERN = "/.well-known/workflow/v1/webhook/:token";
|
|
4
|
+
export declare function handleWorkflowWebhookRequest(request: Request, ctx: RouteContext): Promise<Response>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{walkCauseChain}from"#shared/errors.js";import{resumeWebhook}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";const WORKFLOW_WEBHOOK_ROUTE_PATTERN=`/.well-known/workflow/v1/webhook/:token`;async function handleWorkflowWebhookRequest(t,n){let r=n.params.token;if(typeof r!=`string`||r.length===0)return Response.json({error:`Missing webhook token.`,ok:!1},{status:400});try{return await resumeWebhook(r,t)}catch(e){for(let t of walkCauseChain(e))if(HookNotFoundError.is(t))return Response.json({error:`Webhook not pending.`,ok:!1},{status:404});throw e}}export{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{loadContext}from"#context/container.js";import{SandboxKey}from"#context/keys.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{basename}from"node:path";import{
|
|
1
|
+
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{loadContext}from"#context/container.js";import{SandboxKey}from"#context/keys.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{basename}from"node:path";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{fileDataToBytes}from"#internal/attachments/data.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{decodeSandboxRef,encodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const ATTACHMENTS_ROOT=`/workspace/attachments`,log=createLogger(`harness.attachment-staging`),UNSAFE_FILENAME_CHARS=/[^\w.-]+/g;async function stageAttachmentsForAdapter(e,t,n){if(typeof e==`string`)return e;let r=reconstitueFilePartUrls(e);return Promise.all(r.map(async e=>e.type===`file`?stageFilePart(e,t,n):e))}async function stageAttachmentsToSandbox(e){if(typeof e==`string`||!Array.isArray(e)||!hasFileParts(e))return e;let n=loadContext(),r=n.get(SandboxKey);if(r===void 0)return e;let o=await r.get();if(o===null)return e;let s=n.get(ChannelKey);return stageAttachmentsForAdapter(e,o,s?buildAdapterContext(s,n):{ctx:n,state:{},session:buildSessionHandle(n)})}async function hydrateSandboxAttachments(e){if(!messagesContainSandboxRef(e))return e;let t=loadContext().get(SandboxKey);if(t===void 0)throw Error(`Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. Hydration must run inside a step scope with the framework sandbox provider installed.`);let n=await t.get();if(n===null)throw Error(`Cannot hydrate sandbox-ref FilePart: SandboxKey is bound but no active sandbox session is available.`);return Promise.all(e.map(async e=>{if(!messageContainsSandboxRef(e))return e;let t=await hydrateMessageContent(e.content,n);return{...e,content:t}}))}function hasFileParts(e){for(let t of e)if(t.type===`file`)return!0;return!1}function messagesContainSandboxRef(e){for(let t of e)if(messageContainsSandboxRef(t))return!0;return!1}function messageContainsSandboxRef(e){let t=e.content;if(!Array.isArray(t))return!1;for(let e of t)if(isSandboxRefFilePart(e))return!0;return!1}function isSandboxRefFilePart(e){return typeof e==`object`&&!!e&&e.type===`file`&&isSandboxRefUrl(e.data)}async function hydrateMessageContent(e,t){return Array.isArray(e)?Promise.all(e.map(async e=>{if(!isSandboxRefFilePart(e))return e;let n=e,r=decodeSandboxRef(n.data);if(!shouldInlineSandboxRefAsBytes(r))return renderSandboxRefAsTextPart(r);let i=await t.readBinaryFile({path:r.path});return i===null?(log.warn(`sandbox-ref attachment bytes missing on hydration — degrading to text reference`,{mediaType:r.mediaType,path:r.path,size:r.size}),{text:`FileNotFound: Current snapshot may be newer and does not contain ${r.path}.`,type:`text`}):{...n,data:i,mediaType:r.mediaType}})):e}function shouldInlineSandboxRefAsBytes(e){return e.mediaType.startsWith(`image/`)?e.size<=3145728:e.mediaType===`application/pdf`&&e.size<=20971520}function renderSandboxRefAsTextPart(e){return{text:`Attached file ${e.path} (${e.mediaType})`,type:`text`}}async function stageFilePart(e,t,n){if(isSandboxRefUrl(e.data))return e;if(e.data instanceof URL&&e.data.protocol!==`data:`){let r;try{r=await tryFetchFile(e.data.href,n)}catch(t){if(!(t instanceof EveAttachmentError))throw t;let n=e.filename?.trim()||`file`;return log.warn(`attachment resolver failed — degrading to text part`,{adapterKind:t.adapterKind,error:t.cause,filename:n,kind:t.kind}),{text:`Attachment ${n} could not be retrieved: ${t.message}`,type:`text`}}return r===null?e:stageResolvedBytes(e,r,t)}let r=await fileDataToBytes(e.data);return r===null?e:stageResolvedBytes(e,{bytes:r},t)}async function stageResolvedBytes(e,t,n){let r=t.bytes,i=sha256Prefix(r),a=t.mediaType??e.mediaType??`application/octet-stream`,o=safeFilename(t.filename??e.filename,i),s=`${ATTACHMENTS_ROOT}/${i}/${o}`;await n.writeBinaryFile({content:r,path:s});let c=n.resolvePath(s);return{...e,data:encodeSandboxRef({mediaType:a,path:c,size:r.byteLength}),filename:c,mediaType:a}}async function tryFetchFile(e,t){let n=t.ctx.get(ChannelKey);if(n?.fetchFile===void 0)return null;let i=getAdapterKind(n);try{let r=await n.fetchFile(e,t);return r===null?null:Buffer.isBuffer(r)?{bytes:r}:r}catch(e){throw e instanceof EveAttachmentError?e:new EveAttachmentError({adapterKind:i,cause:e,kind:`resolver-threw`,message:`Attachment retrieval failed in the "${i}" channel.`})}}function reconstitueFilePartUrls(e){let t=!1,n=e.map(e=>e.type===`file`&&isSerializedUrlFilePart(e.data)?(t=!0,{...e,data:deserializeUrlFilePart(e.data)}):e);return t?n:e}function sha256Prefix(t){return createHash(`sha256`).update(t).digest(`hex`).slice(0,16)}function safeFilename(e,t){if(e===void 0)return`file-${t}`;let n=basename(e).replace(UNSAFE_FILENAME_CHARS,`_`);return n.length>0?n:`file-${t}`}export{ATTACHMENTS_ROOT,hydrateSandboxAttachments,stageAttachmentsForAdapter,stageAttachmentsToSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{
|
|
1
|
+
import{createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r,i){let a=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r,trace:i})),await e(createTurnStartedEvent({sequence:n.sequence,trace:i,turnId:a})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:a})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:a}}async function emitStepStarted(e,t,n,r){await e(createStepStartedEvent({modelId:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),r)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n,r){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId}),r),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(o,s,c,l,u){let d=``,f=``,p=`stop`,m,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=new Set,x=[],S=[],C=new Map,flushCurrentMessage=async()=>{f.length!==0&&(await o(createMessageCompletedEvent({finishReason:`tool-calls`,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),f=``)},emitActionInput=async(t,n,r,i)=>o(createActionInputAppendedEvent({callId:t,inputTextDelta:r,inputTextOffset:i,sequence:s.sequence,stepIndex:s.stepIndex,toolName:n,turnId:s.turnId})),emitActionRequest=async e=>{g.has(e.callId)||(f.trim().length>0&&await flushCurrentMessage(),g.add(e.callId),await o(createActionsRequestedEvent({actions:[e],sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},collectProviderToolCall=async e=>{if(v.has(e.toolCallId)||(v.add(e.toolCallId),g.has(e.toolCallId)))return;g.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){b.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(t.toolError));return}l.observe(t.request)},emitActionResult=async e=>{_.has(e.callId)||(_.add(e.callId),await o(createActionResultEvent({result:e,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},emitActionPartial=async e=>{await o(createActionPartialEvent({result:e,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}))},emitToolCall=async e=>{if(isInvalidToolCall(e)){b.add(e.toolCallId);return}if(!(u===void 0||u.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:u.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});b.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of c)if(m===void 0)switch(e.type){case`reasoning-delta`:await l.flush(),d+=e.text,await o(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`text-delta`:await l.flush(),d.trim().length>0&&(await o(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),d=``),f+=e.text,await o(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`tool-input-start`:if(u===void 0||e.providerExecuted===!0||u.excludedActionToolNames.has(e.toolName)){C.delete(e.id);break}await l.flush(),f.trim().length>0&&await flushCurrentMessage(),C.set(e.id,{offset:0,toolName:e.toolName}),await emitActionInput(e.id,e.toolName,``,0);break;case`tool-input-delta`:{let t=C.get(e.id);if(t===void 0)break;await l.flush();let n=t.offset;t.offset+=e.delta.length,await emitActionInput(e.id,t.toolName,e.delta,n);break}case`tool-input-end`:C.delete(e.id);break;case`tool-call`:{let t=e;C.delete(t.toolCallId),h.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await l.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0){t.providerExecuted!==!0&&await emitActionPartial(createRuntimeToolResultFromStepResult(t));break}if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await l.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(h.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;g.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId));break}if(await l.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){y.add(e.toolCallId),x.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await l.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):g.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),y.add(t.toolCallId),S.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:p=normalizeAssistantStepFinishReason(e.finishReason),await l.flush();break;case`error`:m=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await l.flush(),m!==void 0)throw m;return d.trim().length>0&&await o(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),p!==`tool-calls`&&hasEmptyDeliverySentinel(f)?await o(createMessageCompletedEvent({finishReason:p,message:null,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})):f.trim().length>0&&await o(createMessageCompletedEvent({finishReason:p,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),{emittedActionCallIds:g,handledInlineToolResultCallIds:y,invalidInputToolCallIds:b,inlineAuthorizationResults:x,trailingInlineToolResultParts:S}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
|
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
|
|
2
2
|
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
|
|
3
3
|
import type { InputRequestKind } from "#shared/input.js";
|
|
4
|
+
/**
|
|
5
|
+
* Marks a continuation token as a bare hook a workflow tool run created for one
|
|
6
|
+
* request, resumed with the plain response, rather than a child session inbox.
|
|
7
|
+
*/
|
|
8
|
+
export interface AnswerHookRoute {
|
|
9
|
+
readonly runId: string;
|
|
10
|
+
}
|
|
4
11
|
/** Routing and control metadata for one descendant-owned input request. */
|
|
5
12
|
export interface ProxyInputRequest {
|
|
13
|
+
readonly answerHook?: AnswerHookRoute;
|
|
6
14
|
/** Batch semantics are optional so sessions written before this field remain routable. */
|
|
7
15
|
readonly batch?: ProxyInputRequestBatch;
|
|
8
16
|
readonly childContinuationToken: string;
|
|
@@ -52,6 +60,8 @@ export declare function upsertProxyInputRequestState(input: {
|
|
|
52
60
|
* child subagent finishes so stale clicks no longer route to it.
|
|
53
61
|
*/
|
|
54
62
|
export declare function clearProxyInputRequestsForChild(session: HarnessSession, childContinuationToken: string): HarnessSession;
|
|
63
|
+
/** Removes every proxy route the predicate selects. */
|
|
64
|
+
export declare function clearProxyInputRequestsWhere(session: HarnessSession, select: (route: ProxyInputRequest) => boolean): HarnessSession;
|
|
55
65
|
/** Removes only the request IDs whose responses were successfully forwarded. */
|
|
56
66
|
export declare function retireProxyInputRequests<T extends {
|
|
57
67
|
readonly state?: SessionStateMap;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLoopbackHostname}from"#shared/network-address.js";const PROXY_INPUT_REQUESTS_KEY=`eve.runtime.proxyInputRequests`,PROXY_INPUT_REQUEST_KINDS={question:!0,"session-limit":!0,"tool-approval":!0};function createTaskInputRequestId(e,t){return`${e}:${t}`}function getProxyInputRequests(e){return new Map(Object.entries(readMap(e)))}function hasProxyInputRequests(e){for(let t of Object.keys(readMap(e)))return!0;return!1}function upsertProxyInputRequests(e){return{...e.session,state:upsertProxyInputRequestState({entries:e.entries,forChildContinuationToken:e.forChildContinuationToken,state:e.session.state})}}function upsertProxyInputRequestState(e){let n={};for(let[t,r]of Object.entries(readMap(e.state)))r.childContinuationToken!==e.forChildContinuationToken&&(n[t]=r);for(let[t,r]of e.entries)n[t]=r;let r={...e.state};return Object.keys(n).length===0?delete r[PROXY_INPUT_REQUESTS_KEY]:r[PROXY_INPUT_REQUESTS_KEY]=n,Object.keys(r).length>0?r:void 0}function clearProxyInputRequestsForChild(e,t){let n=readMap(e.state),r={},i=!1;for(let[e,a]of Object.entries(n)){if(a
|
|
1
|
+
import{isLoopbackHostname}from"#shared/network-address.js";const PROXY_INPUT_REQUESTS_KEY=`eve.runtime.proxyInputRequests`,PROXY_INPUT_REQUEST_KINDS={question:!0,"session-limit":!0,"tool-approval":!0};function createTaskInputRequestId(e,t){return`${e}:${t}`}function getProxyInputRequests(e){return new Map(Object.entries(readMap(e)))}function hasProxyInputRequests(e){for(let t of Object.keys(readMap(e)))return!0;return!1}function upsertProxyInputRequests(e){return{...e.session,state:upsertProxyInputRequestState({entries:e.entries,forChildContinuationToken:e.forChildContinuationToken,state:e.session.state})}}function upsertProxyInputRequestState(e){let n={};for(let[t,r]of Object.entries(readMap(e.state)))r.childContinuationToken!==e.forChildContinuationToken&&(n[t]=r);for(let[t,r]of e.entries)n[t]=r;let r={...e.state};return Object.keys(n).length===0?delete r[PROXY_INPUT_REQUESTS_KEY]:r[PROXY_INPUT_REQUESTS_KEY]=n,Object.keys(r).length>0?r:void 0}function clearProxyInputRequestsForChild(e,t){return clearProxyInputRequestsWhere(e,e=>e.childContinuationToken===t)}function clearProxyInputRequestsWhere(e,t){let n=readMap(e.state),r={},i=!1;for(let[e,a]of Object.entries(n)){if(t(a)){i=!0;continue}r[e]=a}return i?writeMap(e,r):e}function retireProxyInputRequests(e,t){let n={...readMap(e.state)},r=!1;for(let e of t)Object.hasOwn(n,e)&&(delete n[e],r=!0);return r?writeMap(e,n):e}function clearProxyInputRequestsForTask(e,t){return clearProxyInputRequestsWhere(e,e=>e.taskId===t)}function clearAllProxyInputRequests(e){return hasProxyInputRequests(e.state)?writeMap(e,{}):e}function toProxyInputRequestEntries(e,t){let n={approvalRequestIds:e.event.requests.flatMap(e=>e.kind===`tool-approval`?[e.requestId]:[]),requestIds:e.event.requests.map(e=>e.requestId)};return e.event.requests.map(r=>{let i={batch:n,childContinuationToken:e.childContinuationToken,kind:r.kind};return t!==void 0&&(i.taskId=t),[r.requestId,i]})}function readMap(e){let n=e?.[PROXY_INPUT_REQUESTS_KEY];if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n)){let n=parseProxyInputRequest(t,e);n!==void 0&&(r[e]=n)}return r}function writeMap(e,n){let r={...e.state};return Object.keys(n).length===0?(delete r[PROXY_INPUT_REQUESTS_KEY],{...e,state:Object.keys(r).length>0?r:void 0}):(r[PROXY_INPUT_REQUESTS_KEY]=n,{...e,state:r})}function parseProxyInputRequest(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||!(`childContinuationToken`in e)||!(`kind`in e)||typeof e.childContinuationToken!=`string`||!isInputRequestKind(e.kind))return;let n=`taskId`in e?e.taskId:void 0,r=`childRequestId`in e?e.childRequestId:void 0,i=`childResponseUrl`in e?e.childResponseUrl:void 0;if(n!==void 0&&(typeof n!=`string`||n.length===0)||r!==void 0&&(typeof r!=`string`||r.length===0)||n===void 0!=(r===void 0)||i!==void 0&&(typeof i!=`string`||!isAllowedChildResponseUrl(i)))return;let a=`batch`in e?parseProxyInputRequestBatch(e.batch):void 0,o=`answerHook`in e?parseAnswerHookRoute(e.answerHook):void 0;if(`answerHook`in e&&o===void 0)return;let s={childContinuationToken:e.childContinuationToken,kind:e.kind};return o!==void 0&&(s.answerHook=o),a!==void 0&&a.requestIds.includes(t)&&(s.batch=a),typeof r==`string`&&(s.childRequestId=r),typeof i==`string`&&(s.childResponseUrl=i),typeof n==`string`&&(s.taskId=n),s}function parseAnswerHookRoute(e){if(!(typeof e!=`object`||!e||!(`runId`in e)))return typeof e.runId==`string`&&e.runId.length>0?{runId:e.runId}:void 0}function parseProxyInputRequestBatch(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`approvalRequestIds`in e)||!(`requestIds`in e)||!isStringArray(e.approvalRequestIds)||!isStringArray(e.requestIds))return;let t=new Set(e.requestIds);if(!(t.size!==e.requestIds.length||e.approvalRequestIds.some(e=>!t.has(e))))return{approvalRequestIds:e.approvalRequestIds,requestIds:e.requestIds}}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function isAllowedChildResponseUrl(t){let n;try{n=new URL(t)}catch{return!1}return n.protocol===`https:`||n.protocol===`http:`&&isLoopbackHostname(n.hostname)}function isInputRequestKind(e){return typeof e==`string`&&Object.hasOwn(PROXY_INPUT_REQUEST_KINDS,e)}export{clearAllProxyInputRequests,clearProxyInputRequestsForChild,clearProxyInputRequestsForTask,clearProxyInputRequestsWhere,createTaskInputRequestId,getProxyInputRequests,hasProxyInputRequests,retireProxyInputRequests,toProxyInputRequestEntries,upsertProxyInputRequestState,upsertProxyInputRequests};
|
|
@@ -64,6 +64,8 @@ export declare function resolvePendingRuntimeActions(input: {
|
|
|
64
64
|
readonly emit?: HarnessEmitFn;
|
|
65
65
|
readonly session: HarnessSession;
|
|
66
66
|
readonly stepInput?: StepInput;
|
|
67
|
+
/** Definitions whose `toModelOutput` projects a workflow tool's result for the model. */
|
|
68
|
+
readonly tools?: HarnessToolMap;
|
|
67
69
|
}): Promise<ResolvePendingRuntimeActionsResult>;
|
|
68
70
|
/**
|
|
69
71
|
* Projects one AI SDK tool call into the eve runtime-action contract.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{getPendingDispatchActionKey}from"#runtime/actions/keys.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function readSubagentResultOutcome(e){return e.origin===`child`?e.outcome:void 0}function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){assertUniqueRuntimeActionCallIds(e.actions);let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function assertUniqueRuntimeActionCallIds(e){let t=new Set;for(let n of e){if(t.has(n.callId))throw Error(`Runtime action batch contains duplicate callId "${n.callId}".`);t.add(n.callId)}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results,state:e.session.state})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getPendingDispatchActionKey(e)),results:e.results.filter(t=>isResultBoundToRunningHandle(e.state,t))})}async function resolvePendingRuntimeActions(t){let
|
|
1
|
+
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{findToolRun,removeToolRun}from"#harness/tool-runs.js";import{clearProxyInputRequestsForChild,clearProxyInputRequestsWhere}from"#harness/proxy-input-requests.js";import{getPendingDispatchActionKey}from"#runtime/actions/keys.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";import{normalizeToolModelOutput}from"#harness/tool-model-output.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function readSubagentResultOutcome(e){return e.origin===`child`?e.outcome:void 0}function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){assertUniqueRuntimeActionCallIds(e.actions);let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function assertUniqueRuntimeActionCallIds(e){let t=new Set;for(let n of e){if(t.has(n.callId))throw Error(`Runtime action batch contains duplicate callId "${n.callId}".`);t.add(n.callId)}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results,state:e.session.state})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getPendingDispatchActionKey(e)),results:e.results.filter(t=>isResultBoundToRunningHandle(e.state,t))})}async function resolvePendingRuntimeActions(t){let a=getPendingRuntimeActionBatch(t.session.state);if(a===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let o=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(o===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of o){if(n.kind===`subagent-result`&&n.isError!==!0){let e=readBackgroundTaskReceipt(n),r={callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName};await t.emit({data:e===void 0?r:{...r,backgroundTask:e},type:`subagent.completed`})}await t.emit(createActionResultEvent({result:n,sequence:a.event.sequence,stepIndex:a.event.stepIndex,turnId:a.event.turnId}))}let s=t.session;for(let e of o){if(e.kind!==`subagent-result`||e.origin!==`child`||readBackgroundTaskReceipt(e)!==void 0)continue;let t=findRunningAgentHandle(s.state,{callId:e.callId});if(t===void 0)continue;let r=readSubagentResultOutcome(e);if(r===void 0)continue;r.kind===`terminal`&&`continuationToken`in t.address&&(s=clearProxyInputRequestsForChild(s,t.address.continuationToken));let i=settleAgentTurn(s,{operationId:t.operation.id,outcome:r});i.kind===`settled`&&(s=i.session)}for(let e of o){if(e.kind!==`tool-result`)continue;let t=findToolRun(s.state,e.callId);t!==void 0&&(s=removeToolRun(clearProxyInputRequestsWhere(s,e=>e.answerHook?.runId===t.runId),t.callId))}let c={...s.state};delete c[PENDING_RUNTIME_ACTION_BATCH_KEY],s={...s,state:Object.keys(c).length>0?c:void 0};for(let e of o){if(e.kind!==`subagent-result`)continue;let t=readSubagentResultOutcome(e);t!==void 0&&(s=setTurnUsageState(s,accumulateSessionUsage({previous:getTurnUsageState(s.state),usage:t.usageDelta})))}let l=[];for(let e of o){switch(e.kind){case`load-skill-result`:l.push({output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`});continue;case`subagent-result`:l.push({output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`});continue;case`tool-result`:l.push({output:await projectToolResultOutput(e,t.tools?.get(e.toolName)),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`});continue}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}let u=[...s.history,...a.responseMessages];return l.length>0&&u.push({content:l,role:`tool`}),{messages:u,outcome:`resolved`,session:s}}function readBackgroundTaskReceipt(e){return`backgroundTask`in e?e.backgroundTask:void 0}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName),n=resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName});if(t?.behavior?.presentation===`load-skill`)return{callId:e.toolCall.toolCallId,input:n,kind:`load-skill`};let r=t?.execution===`background`||t?.behavior?.handling?.kind!==`dispatch`?void 0:t.behavior.handling.target;return t!==void 0&&(r?.kind===`self-agent-call`||r?.kind===`subagent-call`)?{callId:e.toolCall.toolCallId,description:t.description,input:n,kind:`subagent-call`,name:t.name,nodeId:r.nodeId,subagentName:r.subagentName}:t!==void 0&&r?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:n,kind:`remote-agent-call`,name:t.name,nodeId:r.nodeId,remoteAgentName:r.remoteAgentName}:{callId:e.toolCall.toolCallId,input:n,kind:`tool-call`,toolName:e.toolCall.toolName}}function createPendingDispatchActionFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);if(t===void 0)throw Error(`Unknown tool "${e.toolCall.toolName}" in dispatch projection.`);let n=t.behavior?.handling;if(n?.kind!==`dispatch`||t.execution===`background`)throw Error(`Tool "${e.toolCall.toolName}" is not a durable dispatch tool.`);return{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),target:n.target,toolName:t.name}}function resolveToolCallInputObject(e,n){if(e==null||typeof e==`string`&&e.trim()===``)return{};try{return parseJsonObject(typeof e==`string`?parseJsonStringInput(e):e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function parseJsonStringInput(e){return JSON.parse(e)}async function projectToolResultOutput(e,t){return e.isError===!0||t?.toModelOutput===void 0?toToolResultOutput(e):normalizeToolModelOutput({output:await t.toModelOutput(e.output),toolCallId:e.callId,toolName:e.toolName})}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{assertUniqueRuntimeActionCallIds,clearPendingRuntimeActionBatch,createPendingDispatchActionFromToolCall,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,resolvePendingRuntimeActions,resolveToolCallInputObject,setPendingRuntimeActionBatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{appendPendingInputBatch}from"#harness/input-requests.js";import{bumpSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{SessionLimitDeclinedError}from"#harness/turn-cancellation.js";import{appendPendingInputBatch}from"#harness/input-requests.js";import{bumpSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:bumpSessionRuntimeTokenLimits(e.session)};if(!(e.config.mode===`conversation`||e.session.continuationToken!==``)){let t=getSessionTokenLimitViolation(e.session);return{result:t===null?{next:{done:!0,output:``},session:e.session}:await failSessionTokenLimit({...e,violation:t}),session:e.session}}throw new SessionLimitDeclinedError}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return t.limit>0&&n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let i=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,violation:t.violation}),a=t.emissionState,o=appendPendingInputBatch({event:{sequence:a.sequence,stepIndex:a.stepIndex,turnId:a.turnId},requests:[i],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[i],sequence:a.sequence,stepIndex:a.stepIndex,turnId:a.turnId})),t.config.mode===`conversation`&&(a=await emitTurnEpilogue(t.emit,a,t.config.mode)),{next:null,session:setHarnessEmissionState(o,a)}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let n=getSessionTokenUsage(e.session),r=formatSessionTokenLimitMessage(e.violation.kind),i={inputTokens:n.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:n.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:i,message:r,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`||void 0,output:e.config.mode===`task`?r:``},session:e.session}}export{applySessionLimitContinuation,enforceSessionTokenLimit};
|