eve 0.69.0 → 0.70.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/channel/task-card.d.ts +3 -3
- package/dist/src/channel/task-card.js +1 -1
- package/dist/src/channel/types.d.ts +18 -0
- package/dist/src/chunks/{use-eve-agent-Dab2MnT2.js → use-eve-agent-CJQeE7-t.js} +1873 -1236
- package/dist/src/chunks/{use-eve-agent-D_5129A9.js → use-eve-agent-DdemtY6C.js} +1874 -1234
- package/dist/src/cli/dev/command.js +1 -1
- package/dist/src/cli/dev/console-records-preload.d.ts +1 -0
- package/dist/src/cli/dev/console-records-preload.js +1 -0
- package/dist/src/cli/dev/console-records.d.ts +17 -0
- package/dist/src/cli/dev/console-records.js +3 -0
- package/dist/src/cli/dev/diagnostic-sink.d.ts +1 -0
- package/dist/src/cli/dev/local-server-process.js +1 -1
- package/dist/src/cli/dev/tui/blocks.d.ts +2 -1
- package/dist/src/cli/dev/tui/blocks.js +3 -3
- package/dist/src/cli/dev/tui/conversation-view.d.ts +54 -0
- package/dist/src/cli/dev/tui/conversation-view.js +1 -0
- package/dist/src/cli/dev/tui/flow-drawer.d.ts +5 -2
- package/dist/src/cli/dev/tui/flow-drawer.js +1 -1
- package/dist/src/cli/dev/tui/log-display-mode.d.ts +4 -10
- package/dist/src/cli/dev/tui/log-display-mode.js +1 -1
- package/dist/src/cli/dev/tui/message-queue.d.ts +7 -63
- package/dist/src/cli/dev/tui/message-queue.js +3 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +7 -7
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/question-panel.d.ts +3 -1
- package/dist/src/cli/dev/tui/question-panel.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +58 -195
- package/dist/src/cli/dev/tui/runner.js +3 -3
- package/dist/src/cli/dev/tui/task-activity.d.ts +11 -24
- package/dist/src/cli/dev/tui/task-activity.js +1 -1
- package/dist/src/cli/dev/tui/task-records.d.ts +17 -0
- package/dist/src/cli/dev/tui/task-records.js +1 -0
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +15 -37
- package/dist/src/cli/dev/tui/terminal-renderer.js +10 -13
- package/dist/src/cli/dev/tui/terminal-tool-part.d.ts +2 -0
- package/dist/src/cli/dev/tui/terminal-tool-part.js +1 -0
- package/dist/src/cli/dev/tui/test/fake-eve-server.d.ts +34 -0
- package/dist/src/cli/dev/tui/test/fake-eve-server.js +1 -0
- package/dist/src/cli/dev/tui/test/index.d.ts +1 -0
- package/dist/src/cli/dev/tui/test/index.js +1 -1
- package/dist/src/cli/dev/tui/tool-block-groups.js +1 -1
- package/dist/src/cli/dev/tui/tool-presentation.d.ts +1 -0
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/cli/dev/tui/tool-rows.d.ts +1 -0
- package/dist/src/cli/dev/tui/tool-rows.js +2 -2
- package/dist/src/cli/dev/tui/transcript-parts.d.ts +81 -0
- package/dist/src/cli/dev/tui/transcript-parts.js +3 -0
- package/dist/src/cli/dev/tui/transcript.d.ts +47 -0
- package/dist/src/cli/dev/tui/transcript.js +1 -0
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/dev/tui/turn-clock.d.ts +11 -26
- package/dist/src/cli/dev/tui/turn-clock.js +1 -1
- package/dist/src/cli/dev/tui/types.d.ts +2 -4
- package/dist/src/cli/dev/ui-options.js +1 -1
- package/dist/src/client/agent-stream-follower.d.ts +26 -0
- package/dist/src/client/agent-stream-follower.js +1 -0
- package/dist/src/client/authorization-message-parts.js +1 -1
- package/dist/src/client/conversation-client.d.ts +40 -0
- package/dist/src/client/conversation-client.js +1 -0
- package/dist/src/client/conversation-reducer.d.ts +29 -0
- package/dist/src/client/conversation-reducer.js +1 -0
- package/dist/src/client/conversation-state.d.ts +110 -0
- package/dist/src/client/conversation-state.js +1 -0
- package/dist/src/client/eve-agent-projection.d.ts +24 -7
- package/dist/src/client/eve-agent-projection.js +1 -1
- package/dist/src/client/eve-agent-store-helpers.d.ts +21 -2
- package/dist/src/client/eve-agent-store-helpers.js +2 -2
- package/dist/src/client/eve-agent-store-state.d.ts +15 -3
- package/dist/src/client/eve-agent-store.d.ts +10 -1
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +4 -1
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-reducer-primitives.d.ts +1 -2
- package/dist/src/client/message-reducer-primitives.js +1 -1
- package/dist/src/client/message-reducer-types.d.ts +9 -2
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/message-run-parts.d.ts +10 -6
- package/dist/src/client/message-run-parts.js +1 -1
- package/dist/src/client/optimistic-message-submissions.d.ts +6 -4
- package/dist/src/client/optimistic-message-submissions.js +1 -1
- package/dist/src/client/reducer.d.ts +5 -1
- package/dist/src/client/session-turn-dispatch.d.ts +15 -0
- package/dist/src/client/session-turn-dispatch.js +1 -0
- package/dist/src/client/session-utils.d.ts +27 -10
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +2 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -2
- package/dist/src/compiled/{gray-matter → js-yaml}/LICENSE +2 -2
- package/dist/src/compiled/js-yaml/index.d.ts +12 -0
- package/dist/src/compiled/js-yaml/index.js +34 -0
- package/dist/src/compiler/extension-compatibility.d.ts +18 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/load-binding-namespace.js +1 -1
- package/dist/src/context/keys.d.ts +5 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/provider.d.ts +5 -9
- package/dist/src/context/run-step.d.ts +4 -4
- package/dist/src/context/run-step.js +1 -1
- package/dist/src/context/serialize.d.ts +5 -1
- package/dist/src/context/serialize.js +1 -1
- package/dist/src/evals/loaders/yaml.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/session.js +2 -2
- package/dist/src/evals/types.d.ts +16 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/execution/agent-sessions/context.d.ts +4 -2
- package/dist/src/execution/agent-sessions/context.js +1 -1
- package/dist/src/execution/agent-sessions/steps.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +6 -4
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +4 -2
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +10 -4
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-remote-agent/protocol.d.ts +8 -0
- package/dist/src/execution/legacy-remote-agent/protocol.js +1 -1
- package/dist/src/execution/legacy-session/completion-step.d.ts +2 -0
- package/dist/src/execution/legacy-session/completion-step.js +1 -1
- package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
- package/dist/src/execution/legacy-session/prepare-step.d.ts +1 -0
- package/dist/src/execution/legacy-session/prepare-step.js +1 -1
- package/dist/src/execution/legacy-session/snapshot.d.ts +8 -4
- package/dist/src/execution/legacy-session/snapshot.js +1 -1
- package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +27 -7
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/reconcile-session-continuation-token.d.ts +2 -2
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session/active-turn.d.ts +97 -0
- package/dist/src/execution/session/active-turn.js +1 -0
- package/dist/src/execution/session/checkpoint-migrations.d.ts +23 -0
- package/dist/src/execution/session/checkpoint-migrations.js +1 -0
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +24 -5
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +10 -6
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +19 -13
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/next-input.d.ts +2 -10
- package/dist/src/execution/session/next-input.js +1 -1
- package/dist/src/execution/session/pending-turn-state.d.ts +2 -0
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/program.d.ts +2 -0
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/state-cursor.d.ts +22 -16
- package/dist/src/execution/session/state-cursor.js +1 -1
- package/dist/src/execution/session/state-delta.d.ts +8 -1
- package/dist/src/execution/session/state-delta.js +1 -1
- package/dist/src/execution/session/turn-event-handler.js +1 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step-types.d.ts +20 -4
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn-waiting-step.js +1 -1
- package/dist/src/execution/session/turn.d.ts +22 -3
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/session.d.ts +5 -5
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +5 -4
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/start.d.ts +2 -2
- package/dist/src/execution/tasks/task-id-input.d.ts +1 -1
- package/dist/src/execution/tasks/task-id-input.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.d.ts +2 -0
- package/dist/src/execution/terminal-session-completion-step.js +1 -1
- package/dist/src/execution/terminal-session-failure-step.d.ts +2 -0
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/connection-target.d.ts +5 -0
- package/dist/src/execution/tools/connection-target.js +1 -1
- package/dist/src/execution/tools/connection-tools.js +2 -2
- package/dist/src/execution/tools/workflow/start.d.ts +3 -3
- package/dist/src/harness/authorization.d.ts +15 -2
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/cancelled-turn-emission.d.ts +2 -1
- package/dist/src/harness/cancelled-turn-emission.js +1 -1
- package/dist/src/harness/coordination.d.ts +5 -3
- package/dist/src/harness/emission.d.ts +5 -2
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/held-requests.d.ts +18 -0
- package/dist/src/harness/held-requests.js +1 -0
- package/dist/src/harness/hitl/approval-input-requests.d.ts +16 -0
- package/dist/src/harness/hitl/approval-input-requests.js +1 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-requests.d.ts +0 -4
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/model-call-error.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +4 -4
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/stale-input-responses.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-tag-state.d.ts +2 -0
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +23 -11
- package/dist/src/instrumentation/channel-delivery.d.ts +1 -0
- package/dist/src/instrumentation/channel-delivery.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +4 -0
- package/dist/src/instrumentation/memory.d.ts +2 -0
- package/dist/src/instrumentation/memory.js +1 -1
- package/dist/src/instrumentation/native-events.d.ts +1 -0
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +4 -3
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/session-init.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +14 -6
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/bundler/extension-mount-plugin.js +1 -1
- package/dist/src/internal/helpers/frontmatter.d.ts +24 -0
- package/dist/src/internal/helpers/frontmatter.js +1 -0
- package/dist/src/internal/helpers/markdown.js +1 -3
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/nitro-bundler-config.js +1 -1
- package/dist/src/internal/node-esm-compat-banner.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +27 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +2 -2
- package/dist/src/protocol/message.d.ts +41 -3
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/slack/action-status.d.ts +2 -2
- package/dist/src/public/channels/slack/action-status.js +1 -1
- package/dist/src/public/channels/slack/approval-cards.d.ts +15 -0
- package/dist/src/public/channels/slack/approval-cards.js +2 -0
- package/dist/src/public/channels/slack/auth.d.ts +2 -0
- package/dist/src/public/channels/slack/auth.js +1 -1
- package/dist/src/public/channels/slack/connections.d.ts +15 -11
- package/dist/src/public/channels/slack/connections.js +1 -1
- package/dist/src/public/channels/slack/defaults.d.ts +1 -15
- package/dist/src/public/channels/slack/defaults.js +3 -4
- package/dist/src/public/channels/slack/hitl.js +1 -1
- package/dist/src/public/channels/slack/inbound.d.ts +10 -2
- package/dist/src/public/channels/slack/inbound.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +2 -0
- package/dist/src/public/channels/slack/index.js +1 -1
- package/dist/src/public/channels/slack/input-response.js +1 -1
- package/dist/src/public/channels/slack/interaction-cards.js +1 -1
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/limits.d.ts +5 -3
- package/dist/src/public/channels/slack/private-approval-delivery.js +1 -1
- package/dist/src/public/channels/slack/renderers.d.ts +1 -1
- package/dist/src/public/channels/slack/renderers.js +1 -1
- package/dist/src/public/channels/slack/reply-delivery.d.ts +72 -0
- package/dist/src/public/channels/slack/reply-delivery.js +1 -0
- package/dist/src/public/channels/slack/sign-in-cancel.d.ts +20 -0
- package/dist/src/public/channels/slack/sign-in-cancel.js +1 -0
- package/dist/src/public/channels/slack/slackChannel.d.ts +15 -0
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/slack/task-card.js +1 -1
- package/dist/src/public/channels/teams/defaults.d.ts +1 -1
- package/dist/src/public/channels/teams/defaults.js +2 -2
- package/dist/src/public/definitions/channel.d.ts +1 -0
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/state.d.ts +2 -0
- package/dist/src/public/definitions/state.js +1 -1
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/server.d.ts +2 -0
- package/dist/src/public/next/server.js +1 -2
- package/dist/src/public/nuxt/module.d.ts +6 -0
- package/dist/src/public/nuxt/module.js +1 -1
- package/dist/src/react/index.d.ts +3 -0
- package/dist/src/react/index.js +1 -1
- package/dist/src/react/use-eve-agent.d.ts +7 -5
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/connections/openapi-spec.d.ts +1 -4
- package/dist/src/runtime/connections/openapi-spec.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +2 -0
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/setup/boxes/deploy-project.js +1 -1
- package/dist/src/setup/integrations/web/setup.js +6 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +5 -5
- package/dist/src/setup/scaffold/create/web-template.js +61 -35
- package/dist/src/setup/vercel-project-framework.js +1 -1
- package/dist/src/shared/display-name.d.ts +15 -0
- package/dist/src/shared/display-name.js +1 -0
- package/dist/src/shared/framework-eve-server.d.ts +43 -0
- package/dist/src/shared/framework-eve-server.js +2 -0
- package/dist/src/shared/token-usage.d.ts +2 -0
- package/dist/src/shared/token-usage.js +1 -1
- package/dist/src/shared/trace-root.d.ts +8 -0
- package/dist/src/shared/trace-root.js +1 -0
- package/dist/src/subagents/callback-route.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +3 -3
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/subagents/invocation.d.ts +3 -1
- package/dist/src/subagents/parent-notification.d.ts +7 -7
- package/dist/src/subagents/parent-notification.js +1 -1
- package/dist/src/subagents/tool.js +1 -1
- package/dist/src/svelte/index.d.ts +3 -0
- package/dist/src/svelte/index.js +2 -2
- package/dist/src/svelte/use-eve-agent.d.ts +7 -4
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/load-skill.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tracing/agent-action-instrumentation.js +1 -1
- package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
- package/dist/src/tracing/agent-otel-attributes.d.ts +6 -0
- package/dist/src/tracing/agent-otel-attributes.js +1 -1
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-runtime-context.d.ts +1 -1
- package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-span-contract.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-codec.d.ts +4 -0
- package/dist/src/tracing/agent-trace-context-codec.js +1 -1
- package/dist/src/tracing/agent-trace-span-processor.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +3 -0
- package/dist/src/tracing/conversation-context.d.ts +10 -0
- package/dist/src/tracing/conversation-context.js +1 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/vue/index.d.ts +3 -0
- package/dist/src/vue/index.js +2 -2
- package/dist/src/vue/use-eve-agent.d.ts +7 -3
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/slack.mdx +60 -13
- package/docs/concepts/built-in-tools.md +3 -2
- package/docs/concepts/execution-model-and-durability.mdx +3 -1
- package/docs/concepts/sessions-runs-and-streaming.md +4 -4
- package/docs/connections/overview.mdx +9 -3
- package/docs/evals/reporters.mdx +4 -0
- package/docs/extensions.md +15 -3
- package/docs/guides/client/streaming.mdx +7 -6
- package/docs/guides/deployment/vercel.mdx +2 -1
- package/docs/guides/dev-tui.md +17 -17
- package/docs/guides/dynamic-capabilities.md +1 -1
- package/docs/guides/frontend/nuxt.mdx +24 -4
- package/docs/guides/frontend/overview.mdx +44 -38
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +4 -10
- package/docs/guides/frontend/use-eve-agent-vue.mdx +4 -10
- package/docs/guides/instrumentation/otel.mdx +24 -6
- package/docs/guides/remote-agents.md +26 -8
- package/docs/reference/cli.md +4 -4
- package/docs/tools/human-in-the-loop.md +4 -4
- package/docs/tools/overview.mdx +1 -1
- package/docs/tools/tasks.md +8 -8
- package/package.json +2 -2
- package/dist/src/cli/dev/tui/steering-stream.d.ts +0 -15
- package/dist/src/cli/dev/tui/steering-stream.js +0 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +0 -134
- package/dist/src/cli/dev/tui/subagent-pump.js +0 -1
- package/dist/src/compiled/gray-matter/index.d.ts +0 -62
- package/dist/src/compiled/gray-matter/index.js +0 -48
- package/dist/src/internal/helpers/gray-matter.d.ts +0 -25
- package/dist/src/internal/helpers/gray-matter.js +0 -1
- package/dist/src/public/nuxt/dev-server.d.ts +0 -25
- package/dist/src/public/nuxt/dev-server.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{workingTasks}from"#execution/tasks/table.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{
|
|
1
|
+
import{workingTasks}from"#execution/tasks/table.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({history:e.history,inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0},o;try{try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i,o)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async()=>{for(;;){let e=await nextTurnDelivery({cursor:n,hasWorkingTasks:()=>workingTasks(sessionTaskTable(n)).length>0,inbox:i,queue:o});if(e.kind===`workflow`){await s.handleWorkflowMessage(e.message);continue}if(e.kind===`cancel-working-tasks`){await cancelWorkingTasks(n,`turn_cancelled`);continue}return e}},l=0,runTurn=async e=>{let t=a.caller;a.turnId=`turn_${String(l++)}`;let n=await s.runTurn(e,{caller:t});return n.caller!==void 0&&(a.caller=n.caller),n},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{history:n.history,serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async e=>{let t=await n.advanceWithHistory(t=>settleCancelledTurnStep({...t,reportUsage:e}));return a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity();switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,n]=await Promise.allSettled([runInitialAction(),c?.start()]);if(n.status===`rejected`)throw n.reason;if(t.status===`rejected`)throw t.reason;let r=t.value;if(r.kind!==`action`)return r;let i=r.action;for(;;){if(i.kind===`done`)return{kind:`terminal`,outcome:{action:i,kind:`done`}};if(i.cancelled===!0){let{caller:t}=a,n=await settleCancelledTurn(t!==void 0);if(t!==void 0){let r={caller:t,sessionId:e.sessionId};await notifyCancelledTaskCallerStep(n.usage===void 0?r:{...r,usage:n.usage})}}else i.settled!==void 0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:i.settled}),a.caller=void 0);let t=await nextParkedActivity();switch(t.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:i=await runTurn({control:t.kind});continue;case`cancel-turn`:await s.cancelTurnWork(),await settleCancelledTurn(!1),i={...i,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(t);if(e.kind!==`action`)return e;i=e.action;continue}}}}finally{await c?.dispose()}}export{failSession,runPreparedSession};
|
|
@@ -1,33 +1,39 @@
|
|
|
1
1
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
-
import type { SessionStepState } from "#execution/publish-session-events.js";
|
|
3
|
-
import { type SessionStateTransition } from "#execution/session/state-delta.js";
|
|
2
|
+
import type { SessionHistoryStepState, SessionStepState } from "#execution/publish-session-events.js";
|
|
3
|
+
import { type SessionStateTransition, type SessionStateValues } from "#execution/session/state-delta.js";
|
|
4
4
|
import type { SessionInboxOwnership } from "#execution/session-inbox/inbox.js";
|
|
5
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
5
6
|
/**
|
|
6
|
-
* The one
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* The one set of session values owned by the workflow executing a session.
|
|
8
|
+
* Steps run against it and return deltas; the cursor applies each to the
|
|
9
|
+
* values its step was given and claims any continuation address the step
|
|
10
|
+
* introduced, so every hook the session answers to is registered before the
|
|
11
|
+
* next step runs.
|
|
11
12
|
*/
|
|
12
13
|
export declare class SessionStateCursor {
|
|
13
14
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
14
15
|
private readonly inbox;
|
|
15
16
|
private values;
|
|
16
|
-
constructor(input: {
|
|
17
|
+
constructor(input: SessionStateValues & {
|
|
17
18
|
readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
|
|
18
19
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
19
|
-
readonly serializedContext: Record<string, unknown>;
|
|
20
|
-
readonly sessionState: DurableSessionState;
|
|
21
20
|
});
|
|
22
21
|
get serializedContext(): Record<string, unknown>;
|
|
23
22
|
get sessionState(): DurableSessionState;
|
|
23
|
+
get history(): HarnessModelMessage[];
|
|
24
24
|
/**
|
|
25
|
-
* Runs a session-changing step against the current
|
|
26
|
-
* delta it returns.
|
|
27
|
-
*
|
|
28
|
-
*
|
|
25
|
+
* Runs a session-changing step against the current context and session
|
|
26
|
+
* state and adopts the delta it returns. The step is not given the history,
|
|
27
|
+
* which is the bulk of a long session, so its Workflow step input stays
|
|
28
|
+
* small; it cannot change the history either.
|
|
29
29
|
*/
|
|
30
30
|
advance<T extends SessionStateTransition>(step: (state: SessionStepState) => Promise<T>): Promise<T>;
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/** {@link advance} for a step that reads or changes the history, such as a turn. */
|
|
32
|
+
advanceWithHistory<T extends SessionStateTransition>(step: (state: SessionHistoryStepState) => Promise<T>): Promise<T>;
|
|
33
|
+
/**
|
|
34
|
+
* A delta describes a change to exactly the values its step was given, so
|
|
35
|
+
* values that another step changed in the meantime are a sequencing bug,
|
|
36
|
+
* never a merge.
|
|
37
|
+
*/
|
|
38
|
+
private adopt;
|
|
33
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applySessionStateDelta}from"#execution/session/state-delta.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";var SessionStateCursor=class{sessionWritable;inbox;values;constructor(e){this.inbox=e.inbox,this.sessionWritable=e.sessionWritable,this.values={serializedContext:e.serializedContext,sessionState:e.sessionState}}get serializedContext(){return this.values.serializedContext}get sessionState(){return this.values.sessionState}async advance(e){let
|
|
1
|
+
import{applySessionStateDelta}from"#execution/session/state-delta.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";var SessionStateCursor=class{sessionWritable;inbox;values;constructor(e){this.inbox=e.inbox,this.sessionWritable=e.sessionWritable,this.values={history:e.history,serializedContext:e.serializedContext,sessionState:e.sessionState}}get serializedContext(){return this.values.serializedContext}get sessionState(){return this.values.sessionState}get history(){return this.values.history}async advance(e){let{serializedContext:t,sessionState:n}=this.values;return await this.adopt(()=>e({serializedContext:t,sessionState:n,sessionWritable:this.sessionWritable}),{withHistory:!1})}async advanceWithHistory(e){return await this.adopt(()=>e({...this.values,sessionWritable:this.sessionWritable}),{withHistory:!0})}async adopt(e,t){let n=this.values,r=await e();if(!t.withHistory&&r.stateDelta.history!==void 0)throw Error(`A session step that was not given the history cannot change it.`);let i=applySessionStateDelta(n,r.stateDelta);if(await this.inbox.claimSessionHooks(sessionHookTokens(i)),this.values!==n)throw Error(`Session state changed while a step ran, so its state delta cannot apply.`);return this.values=i,r}};export{SessionStateCursor};
|
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
2
3
|
import { type ValueDelta } from "#shared/value-delta.js";
|
|
3
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* The durable values a session workflow threads through its steps. `history`
|
|
6
|
+
* is separate from `sessionState` so that only the steps that read or change
|
|
7
|
+
* it receive it as input.
|
|
8
|
+
*/
|
|
4
9
|
export interface SessionStateValues {
|
|
5
10
|
readonly serializedContext: Record<string, unknown>;
|
|
6
11
|
readonly sessionState: DurableSessionState;
|
|
12
|
+
readonly history: HarnessModelMessage[];
|
|
7
13
|
}
|
|
8
14
|
/** How a step changed the session's values; an absent value is unchanged. */
|
|
9
15
|
export interface SessionStateDelta {
|
|
10
16
|
readonly serializedContext?: ValueDelta;
|
|
11
17
|
readonly sessionState?: ValueDelta;
|
|
18
|
+
readonly history?: ValueDelta;
|
|
12
19
|
}
|
|
13
20
|
/** A step result the session workflow adopts through its state cursor. */
|
|
14
21
|
export interface SessionStateTransition {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyValueDelta,diffValue,snapshotValue}from"#shared/value-delta.js";async function withSessionStateDelta(e,t){let n=
|
|
1
|
+
import{applyValueDelta,diffValue,snapshotValue}from"#shared/value-delta.js";const SESSION_VALUE_KEYS=[`serializedContext`,`sessionState`,`history`];async function withSessionStateDelta(e,t){let n=Object.fromEntries(SESSION_VALUE_KEYS.map(t=>[t,snapshotValue(e[t])])),{serializedContext:r,sessionState:i,history:a,...o}=await t(e),s={serializedContext:r,sessionState:i,history:a},c={};for(let e of SESSION_VALUE_KEYS){let t=s[e]===void 0?void 0:diffValue(n[e],s[e]);t!==void 0&&(c[e]=t)}return{...o,stateDelta:c}}function applySessionStateDelta(e,t){return{serializedContext:applyValueDelta(e.serializedContext,t.serializedContext),sessionState:applyValueDelta(e.sessionState,t.sessionState),history:applyValueDelta(e.history,t.history)}}export{applySessionStateDelta,withSessionStateDelta};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dispatchDynamicSubagentEvent}from"#context/dynamic-subagent-lifecycle.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{
|
|
1
|
+
import{dispatchDynamicSubagentEvent}from"#context/dynamic-subagent-lifecycle.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{TurnCancelledError,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";const HOOK_CANCELLABLE_EVENTS={"action.input.appended":!0,"action.partial":!0,"action.result":!0,"actions.requested":!0,"agent.started":!1,"approval.candidate":!0,"approval.settled":!0,"authorization.completed":!0,"authorization.required":!0,"compaction.completed":!0,"compaction.requested":!0,"context.cleared":!1,"input.requested":!0,"input.resolved":!0,"message.appended":!0,"message.completed":!0,"message.received":!0,"reasoning.appended":!0,"reasoning.completed":!0,"result.completed":!0,"session.completed":!1,"session.failed":!1,"session.started":!0,"session.waiting":!1,"step.completed":!0,"step.failed":!1,"step.started":!0,"task.settled":!1,"task.started":!1,"turn.cancelled":!1,"turn.completed":!1,"turn.failed":!1,"turn.started":!0,"turn.waiting":!1};function isHookCancellableEvent(e){return HOOK_CANCELLABLE_EVENTS[e]===!0}function createTurnEventHandler(e){let{abortSignal:t,bundle:n,ctx:r,effectiveAgent:i,effectiveNode:a}=e,{publisher:o}=e;return async(s,c)=>{let l=await o.emit(s),u=await dispatchMemoryLifecycleEvent({abortSignal:t,appRoot:a.agent?.metadata?.appRoot??``,ctx:r,event:s,instrumentation:e.instrumentation?.memory,memories:a.agent?.memories??[],messages:c,nodeId:n.nodeId??`__root__`}),d=e.canCancelTurn&&isHookCancellableEvent(l.type)?()=>e.hookCancellation.abort(new TurnCancelledError):void 0;await o.dispatcher.runHooks(l,d),l.type!==`step.started`&&await dispatchDynamicModelEvent({abortSignal:t,ctx:r,dynamicModel:i.turnAgent.dynamicModel,event:l,messages:u,scope:{moduleMap:n.moduleMap,nodeId:n.nodeId}}),await e.dynamicConnections.dispatch(l),await dispatchDynamicSubagentEvent({ctx:r,resolvers:n.subagentRegistry.dynamicResolvers??[],event:l,messages:u}),await dispatchDynamicToolEvent({ctx:r,resolvers:n.resolvedAgent.dynamicToolResolvers??[],event:l,messages:u}),await dispatchDynamicSkillEvent({ctx:r,resolvers:n.resolvedAgent.dynamicSkillResolvers??[],event:l,messages:u}),await dispatchDynamicInstructionEvent({ctx:r,resolvers:n.resolvedAgent.dynamicInstructionsResolvers??[],event:l,messages:u}),d!==void 0&&throwIfTurnAborted(e.hookCancellation.signal)}}export{createTurnEventHandler,isHookCancellableEvent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{
|
|
1
|
+
import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{createDurableSessionValues}from"#execution/durable-session-store.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{getPendingInputBatches}from"#harness/pending-input-batches.js";function resolveSessionStepResult(e,t){let n={serializedContext:t,...createDurableSessionValues(e.session)};if(e.steered)return{action:`steered`,...n};if(e.next!==null&&typeof e.next==`object`&&`done`in e.next){let t=getTurnUsageState(e.session.state)?.session;return{action:`done`,output:e.next.output,isError:e.next.isError,...n,usage:t===void 0?void 0:toUsage(t),usageDelta:takeSessionUsageDelta(e.session).delta}}if(e.held?.kind===`tasks`)return{action:`held`,hold:`tasks`,...n,taskIds:e.held.taskIds};if(e.held?.kind===`request`){let t=derivePendingState(e.session);return{action:`held`,authorizationAttemptIds:t.authorizationAttemptIds??[],hasPendingInputBatch:t.hasPendingInputBatch,hold:`request`,inputRequestIds:getPendingInputBatches(e.session.state).flatMap(e=>e.requests.map(e=>e.requestId)),...n}}if(e.next===null){let{hasRunsToDispatch:r,pendingCoordinationCallIds:i,pendingTaskToolCalls:a}=derivePendingState(e.session),o={hasRunsToDispatch:r,pendingCoordinationCallIds:i,pendingTaskToolCalls:a};if(e.settledTurn!==void 0){let{delta:n,session:r}=takeSessionUsageDelta(e.session);return{action:`park`,...o,serializedContext:t,...createDurableSessionValues(r),settled:{output:e.settledTurn.output,isError:e.settledTurn.isError,usage:n}}}return{action:`park`,...o,...n}}return{action:`continue`,...n}}export{resolveSessionStepResult};
|
|
@@ -2,6 +2,7 @@ import type { DeliverHookPayload, TurnCaller } from "#channel/types.js";
|
|
|
2
2
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
3
|
import type { WithSessionStateDelta } from "#execution/session/state-delta.js";
|
|
4
4
|
import type { TaskToolCall } from "#execution/tasks/calls.js";
|
|
5
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
5
6
|
import type { SettledTurn } from "#harness/types.js";
|
|
6
7
|
import type { RuntimeActionResult } from "#shared/action-types.js";
|
|
7
8
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
@@ -25,15 +26,19 @@ export interface TurnStepPayload {
|
|
|
25
26
|
/** Input for one atomic, session-owner-executed turn step. */
|
|
26
27
|
export interface TurnStepInput {
|
|
27
28
|
readonly abortSignal?: AbortSignal;
|
|
29
|
+
/** The delegated caller to bind into the context before the step runs; sent on a turn's first step. */
|
|
30
|
+
readonly caller?: TurnCaller;
|
|
28
31
|
readonly steeringSignal?: AbortSignal;
|
|
29
32
|
readonly input: TurnStepPayload | undefined;
|
|
30
33
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
31
34
|
readonly serializedContext: Record<string, unknown>;
|
|
32
35
|
readonly sessionState: DurableSessionState;
|
|
36
|
+
readonly history: HarnessModelMessage[];
|
|
33
37
|
}
|
|
34
38
|
interface DurableStepResultFields {
|
|
35
39
|
readonly serializedContext: Record<string, unknown>;
|
|
36
40
|
readonly sessionState: DurableSessionState;
|
|
41
|
+
readonly history: HarnessModelMessage[];
|
|
37
42
|
}
|
|
38
43
|
/** What one turn step's work produces, with the session state it leaves. */
|
|
39
44
|
export type DurableStepResult = ({
|
|
@@ -48,12 +53,24 @@ export type DurableStepResult = ({
|
|
|
48
53
|
/** The model ended the turn while tasks work; the turn waits for them. */
|
|
49
54
|
| {
|
|
50
55
|
readonly action: "held";
|
|
56
|
+
readonly hold: "tasks";
|
|
51
57
|
readonly taskIds: readonly string[];
|
|
58
|
+
}
|
|
59
|
+
/** The turn waits on a sign-in or tool approval it raised. */
|
|
60
|
+
| {
|
|
61
|
+
readonly action: "held";
|
|
62
|
+
readonly authorizationAttemptIds: readonly string[];
|
|
63
|
+
readonly hasPendingInputBatch: boolean;
|
|
64
|
+
readonly hold: "request";
|
|
65
|
+
/** Pending input request ids an answer can resolve. */
|
|
66
|
+
readonly inputRequestIds: readonly string[];
|
|
52
67
|
} | {
|
|
53
68
|
readonly action: "park";
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
69
|
+
/**
|
|
70
|
+
* `false` when every pending call is a task tool call the session answers
|
|
71
|
+
* itself, so the dispatch step can be skipped. Absent, the step runs.
|
|
72
|
+
*/
|
|
73
|
+
readonly hasRunsToDispatch?: boolean;
|
|
57
74
|
readonly pendingCoordinationCallIds?: readonly string[];
|
|
58
75
|
readonly pendingTaskToolCalls?: readonly TaskToolCall[];
|
|
59
76
|
readonly settled?: SettledTurn;
|
|
@@ -74,7 +91,6 @@ export type TurnOutcome = {
|
|
|
74
91
|
readonly usage?: TokenUsage;
|
|
75
92
|
readonly usageDelta?: TokenUsage;
|
|
76
93
|
} | {
|
|
77
|
-
readonly authorizationAttemptIds?: readonly string[];
|
|
78
94
|
readonly cancelled?: true;
|
|
79
95
|
readonly kind: "park";
|
|
80
96
|
readonly settled?: SettledTurn;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.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{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{runStep}from"#context/run-step.js";import{setChannelContext}from"#execution/channel-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.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(e){"use step";return await withSessionStateDelta(e,runSessionStep)}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState);for(let e of r?.delegatedUsage??[])i=countRunUsage(i,e);let a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(i.state),u;if(l&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.payloads);if(n={...n,payloads:t},e.length>0){let r=e.map(e=>e.result.attemptId),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},u=e,t.length===0&&(n=void 0)}}let d=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let f=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),p=createExecutionHistoryView(f),m=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:f.rootSessionId??f.sessionId,sessionId:f.sessionId}),h=getHarnessEmissionState(f.state);if(!h.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>m?.preparePreamble({sequence:h.sequence,sessionStarted:h.sessionStarted})),await contextStorage.run(a,()=>m?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:f.rootSessionId??f.sessionId,sequence:h.sequence,sessionId:f.sessionId,turnId:activeTurnId(h)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>m?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await m?.flush()},g=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:_}=g.dispatcher,v=new AbortController,y=e.abortSignal===void 0?v.signal:AbortSignal.any([e.abortSignal,v.signal]);try{let i=bindDynamicConnections(a,s.resolvedAgent),l={...s.graph.root,turnAgent:c.turnAgent},b=createTurnEventHandler({abortSignal:y,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:v,ctx:a,dynamicConnections:i,effectiveAgent:c,effectiveNode:l,instrumentation:m,publisher:g}),x=n!==void 0&&!isHarnessBetweenTurns(f)?structuredClone(_.state):void 0,S;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,_):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}S=e.length===0?void 0:e.reduce(coalesceTurnInputs)}if(n!==void 0&&S===void 0&&!isHarnessBetweenTurns(f))d===void 0?a.delete(AuthKey):a.set(AuthKey,d),_.state=x;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,h.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!h.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);if(r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),S={...S,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{..._.state}};setChannelContext(a,e)}if(n!==void 0&&S===void 0&&isHarnessBetweenTurns(f)){await contextStorage.run(a,()=>m?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await m?.flush();let t=reconcileSessionContinuationToken(a,f),n=serializeContext(a),r=t===f?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let C=s.subagentRegistry.dynamicResolvers??[],w=s.resolvedAgent.dynamicToolResolvers??[],T=buildRuntimeIdentity(l);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=h.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:T});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:C,event:e,messages:p.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:w,event:e,messages:p.initial.messages,runtimeRevision:t}))]),isHarnessBetweenTurns(f)||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:h.sequence,turnId:activeTurnId(h)}),messages:p.initial.messages,resolvers:w})}}catch(e){throw await failChannelDeliveries(e),e}let E=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,D=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:y,capabilities:D,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:b,prepareApprovalTurn:e=>i.dispatch(createTurnStartedEvent(e)),historyProjector:p.projector,historyView:p.prepare(r),instrumentation:m,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:l})(r,n)},O,k;try{throwIfTurnAborted(y),k=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:S,initialSession:f,modelCallsPerStep:E,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,b),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&S?.outputSchema!==void 0?{...t,outputSchema:S.outputSchema}:t,o=getHarnessEmissionState(r.state);if(await i.rehydrate(o,T,isHarnessBetweenTurns(r)?void 0:{sequence:o.sequence,turnId:activeTurnId(o)}),e&&u){let e=getHarnessEmissionState(r.state);if(u.some(({challenge:e})=>e.candidateId===void 0)&&isHarnessBetweenTurns(r)){let t=createTurnInputMessages(consumeDeferredStepInput({session:r,input:n}).input);prepareDynamicInstructionPreamble(a,p.messages(r)),prepareMemoryPreamble(a,{history:r.history,input:t,projector:p.projector,state:r.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:m});try{e=await emitTurnPreamble(b,{},e,p.projector({messages:[...r.history,...t],state:r.state}),T,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);r={...r,history:validateHarnessModelMessages([...r.history,...e?.recalledMessages??[],...i]),state:e?.state??r.state}}r=setHarnessEmissionState(r,e)}for(let{challenge:t}of u)await b(createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(r,n)});return r.settledTurn===void 0&&throwIfTurnAborted(y),O={result:r,serializedContext:serializeContext(a)},r}})}catch(t){if(!isTurnCancellation(t)&&!y.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:O,ctx:a,initialSession:f,stepInput:S})}let A=reconcileSessionContinuationToken(a,k.session);agentTraceState.pruneAgentTraceState(a,A.sessionId,A.state);let j=serializeContext(a);k={...k,session:A};let M=resolveSessionStepResult(k,j);return M.action===`done`&&await g.writer.close(),M}finally{g.writer.release()}}export{turnStep};
|
|
1
|
+
import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.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{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.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(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState);for(let e of r?.delegatedUsage??[])i=countRunUsage(i,e);let a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(i.state),u;if(l&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.payloads);if(n={...n,payloads:t},e.length>0){let r=e.map(e=>e.result.attemptId),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},u=e,t.length===0&&(n=void 0)}}let d=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let f=n===void 0?u?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;f!==void 0&&a.set(AuthKey,f);let p={...hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),history:validateHarnessModelMessages(e.history)},m=createExecutionHistoryView(p),h=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:p.rootSessionId??p.sessionId,sessionId:p.sessionId}),g=getHarnessEmissionState(p.state);if(!g.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>h?.preparePreamble({sequence:g.sequence,sessionStarted:g.sessionStarted})),await contextStorage.run(a,()=>h?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:p.rootSessionId??p.sessionId,sequence:g.sequence,sessionId:p.sessionId,turnId:activeTurnId(g)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>h?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await h?.flush()},_=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:v}=_.dispatcher,y=new AbortController,b=e.abortSignal===void 0?y.signal:AbortSignal.any([e.abortSignal,y.signal]);try{let i=bindDynamicConnections(a,s.resolvedAgent),l={...s.graph.root,turnAgent:c.turnAgent},f=createTurnEventHandler({abortSignal:b,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:y,ctx:a,dynamicConnections:i,effectiveAgent:c,effectiveNode:l,instrumentation:h,publisher:_}),x=n!==void 0&&!isHarnessBetweenTurns(p)?structuredClone(v.state):void 0,S;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,v):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}S=e.length===0?void 0:e.reduce(coalesceTurnInputs)}if(n!==void 0&&S===void 0&&!isHarnessBetweenTurns(p))d===void 0?a.delete(AuthKey):a.set(AuthKey,d),v.state=x;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,g.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!g.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);if(r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),S={...S,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{...v.state}};setChannelContext(a,e)}if(n!==void 0&&S===void 0&&isHarnessBetweenTurns(p)){await contextStorage.run(a,()=>h?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await h?.flush();let t=reconcileSessionContinuationToken(a,p),n=serializeContext(a),r=t===p?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t),serializedContext:n,...r}}let C=s.subagentRegistry.dynamicResolvers??[],w=s.resolvedAgent.dynamicToolResolvers??[],T=buildRuntimeIdentity(l);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=g.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:T});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:C,event:e,messages:m.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:w,event:e,messages:m.initial.messages,runtimeRevision:t}))]),isHarnessBetweenTurns(p)||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:g.sequence,turnId:activeTurnId(g)}),messages:m.initial.messages,resolvers:w})}}catch(e){throw await failChannelDeliveries(e),e}let E=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,D=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:b,capabilities:D,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:f,prepareApprovalTurn:e=>i.dispatch(createTurnStartedEvent(e)),historyProjector:m.projector,historyView:m.prepare(r),instrumentation:h,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:l})(r,n)},O,k;try{throwIfTurnAborted(b),k=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:S,initialSession:p,modelCallsPerStep:E,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,f),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&S?.outputSchema!==void 0?{...t,outputSchema:S.outputSchema}:t,o=getHarnessEmissionState(r.state);if(await i.rehydrate(o,T,isHarnessBetweenTurns(r)?void 0:{sequence:o.sequence,turnId:activeTurnId(o)}),e&&u){let e=getHarnessEmissionState(r.state);if(u.some(({challenge:e})=>e.candidateId===void 0)&&isHarnessBetweenTurns(r)){let t=createTurnInputMessages(consumeDeferredStepInput({session:r,input:n}).input);prepareDynamicInstructionPreamble(a,m.messages(r)),prepareMemoryPreamble(a,{history:r.history,input:t,projector:m.projector,state:r.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:h});try{e=await emitTurnPreamble(f,{},e,m.projector({messages:[...r.history,...t],state:r.state}),T,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);r={...r,history:validateHarnessModelMessages([...r.history,...e?.recalledMessages??[],...i]),state:e?.state??r.state}}r=setHarnessEmissionState(r,e)}for(let{challenge:t}of u)await f(createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(r,n)});return r.settledTurn===void 0&&throwIfTurnAborted(b),O={result:r,serializedContext:serializeContext(a)},r}})}catch(t){if(!isTurnCancellation(t)&&!b.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:O,ctx:a,initialSession:p,stepInput:S})}let A=reconcileSessionContinuationToken(a,k.session);agentTraceState.pruneAgentTraceState(a,A.sessionId,A.state);let j=serializeContext(a);k={...k,session:A};let M=resolveSessionStepResult(k,j);return M.action===`done`&&await _.writer.close(),M}finally{_.writer.release()}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createTurnWaitingEvent}from"#protocol/message.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";async function publishTurnWaitingStep(e){"use step";return await withSessionStateDelta(e,async e=>{let{sequence:t,turnId:n}=e.sessionState.emissionState;return await publishSessionEvents(e,[createTurnWaitingEvent({sequence:t,turnId:n})])})}export{publishTurnWaitingStep};
|
|
1
|
+
import{createTurnWaitingEvent}from"#protocol/message.js";import{getSessionUsage}from"#harness/turn-tag-state.js";import{readDurableSession}from"#execution/durable-session-store.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";async function publishTurnWaitingStep(e){"use step";return await withSessionStateDelta(e,async e=>{let{sequence:t,turnId:n}=e.sessionState.emissionState,r=getSessionUsage(readDurableSession(e.sessionState));return await publishSessionEvents(e,[createTurnWaitingEvent({on:`tasks`,sequence:t,turnId:n,usage:r})])})}export{publishTurnWaitingStep};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SessionCapabilities, TurnCaller } from "#channel/types.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { SessionInputQueue } from "#execution/session/input-queue.js";
|
|
3
3
|
import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";
|
|
4
4
|
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
|
|
5
5
|
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
|
|
@@ -25,8 +25,8 @@ export declare class SessionExecution {
|
|
|
25
25
|
get cursor(): SessionStateCursor;
|
|
26
26
|
runTurn(delivery: TurnStepPayload | undefined, options?: {
|
|
27
27
|
/**
|
|
28
|
-
* The delegated caller the turn answers
|
|
29
|
-
*
|
|
28
|
+
* The delegated caller the turn answers, including for a first turn whose
|
|
29
|
+
* input carries no caller. The turn's first step binds it into the context.
|
|
30
30
|
*/
|
|
31
31
|
readonly caller?: TurnCaller;
|
|
32
32
|
}): Promise<TurnOutcome>;
|
|
@@ -38,7 +38,19 @@ export declare class SessionExecution {
|
|
|
38
38
|
*/
|
|
39
39
|
private handleBoundaryMessages;
|
|
40
40
|
private runTurnSteps;
|
|
41
|
+
/**
|
|
42
|
+
* Starts the workflow tool runs a parked step requested, and returns the
|
|
43
|
+
* results of any that settled at once. Task tool calls need no dispatch: the
|
|
44
|
+
* session answers them itself.
|
|
45
|
+
*/
|
|
46
|
+
private dispatchRuns;
|
|
41
47
|
handleWorkflowMessage(message: WorkflowToolRunMessage): Promise<RuntimeActionResult | undefined>;
|
|
48
|
+
/**
|
|
49
|
+
* Stops the work a cancelled turn leaves behind: the workflow tool runs it
|
|
50
|
+
* waits on and every working task. A turn that waits on no run, the common
|
|
51
|
+
* case, skips that durable step.
|
|
52
|
+
*/
|
|
53
|
+
cancelTurnWork(): Promise<void>;
|
|
42
54
|
/** `session.cancel()` stops the turn, the calls it waits on, and every working task. */
|
|
43
55
|
private finishCancelledTurn;
|
|
44
56
|
/**
|
|
@@ -46,6 +58,13 @@ export declare class SessionExecution {
|
|
|
46
58
|
* `task_wait` would, until one of them settles or the turn is steered.
|
|
47
59
|
*/
|
|
48
60
|
private waitForHeldTurn;
|
|
61
|
+
/**
|
|
62
|
+
* The turn waits on a sign-in or tool approval it raised. It wakes with the
|
|
63
|
+
* delivery its next step reads: the sign-in callback, an approval answer
|
|
64
|
+
* from any responder, or a message from the turn's own person, which steers
|
|
65
|
+
* the turn and cancels the request. Anyone else's message queues behind it.
|
|
66
|
+
*/
|
|
67
|
+
private waitForHeldRequest;
|
|
49
68
|
private waitForRuntimeActionResults;
|
|
50
69
|
/** Answers every `task_wait` that can return now; returns the ones still waiting. */
|
|
51
70
|
private resolveTaskWaits;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{coalesceDeliveries}from"#harness/messages.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{taskWaitResult}from"#execution/tasks/table.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{activeTurnId}from"#harness/active-turn-id.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{taskToolResult}from"#execution/tasks/calls.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{isSteeringMessage}from"#execution/session/input-queue.js";import{answerTaskCancel,cancelWorkingTasks,isTaskRunMessage,sessionTaskTable}from"#execution/tasks/session.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{applyTaskRunMessageStep}from"#execution/tasks/steps.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{batchAgentStarts,handleWorkflowToolRunMessage}from"#execution/session-workflow-tool-run.js";import{emitAgentStartedStep}from"#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)});try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),n.caller===void 0?t:{...t,caller:n.caller}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1){for(let n of batchAgentStarts(e))n.kind===`message`?await this.handleWorkflowMessage(n.message):t||await this.input.cursor.advance(e=>emitAgentStartedStep({...e,messages:n.messages}))}async runTurnSteps(e,t){let n=t;for(;;){let{cursor:t}=this.input,r=await t.advance(t=>turnStep({...t,abortSignal:e.signal,input:n,steeringSignal:e.steeringSignal})),i=r.action===`park`?r.pendingCoordinationCallIds:void 0,a=r.action===`park`&&r.settled!==void 0;if(await e.admitBoundary(),await this.handleBoundaryMessages(e.takeBoundaryMessages(),r.action===`done`),r.action===`cancelled`||!a&&e.signal.aborted&&i===void 0)return await this.finishCancelledTurn(e);if(r.action===`done`)return{isError:r.isError,kind:`done`,output:r.output??``,usage:r.usage,usageDelta:r.usageDelta};if(r.action===`held`){if(await this.waitForHeldTurn(e)===`cancelled`)return await this.finishCancelledTurn(e);let t=await e.takeSteering();n=t===void 0?void 0:{delivery:t};continue}if(i!==void 0&&r.action===`park`){let a=await t.advance(e=>dispatchCoordinationStep({action:r.action,workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},...e})),o=a.results.length===0?void 0:Date.now(),s=await this.waitForRuntimeActionResults({initialAcceptedAtMs:o,initialResults:a.results,taskToolCalls:r.pendingTaskToolCalls??[],pendingCallIds:i,turn:e});if(s===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:await e.takeSteering(),runtimeResults:s};continue}if(r.action===`park`){if(r.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error("This session cannot request human input, so it cannot wait for a tool approval or question. Sessions started without `capabilities.requestInput`, such as schedules, must not use approval-gated tools.");return{authorizationAttemptIds:r.authorizationAttemptIds,kind:`park`,settled:r.settled}}let o=await e.takeSteering();n=o===void 0?void 0:{delivery:o}}}async handleWorkflowMessage(e){if(isTaskRunMessage(e)){await this.input.cursor.advance(t=>applyTaskRunMessageStep({...t,message:e}));return}return await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:e})}async finishCancelledTurn(e){let{cursor:t}=this.input;return await this.handleBoundaryMessages(e.takeBoundaryMessages(`agent-started`)),await cancelDescendantTurnsStep({sessionState:t.sessionState}),await cancelWorkingTasks(t,`turn_cancelled`),{cancelled:!0,kind:`park`}}async waitForHeldTurn(e){let t=!1;for(;;){let n={interrupted:t,timedOut:!1};if(taskWaitResult(sessionTaskTable(this.input.cursor),n)!==void 0)return`woke`;let r=await e.nextRuntimeEvent([]);if(r===`cancelled`)return r;switch(r.kind){case`steering`:t=!0;continue;case`workflow`:await this.handleWorkflowMessage(r.message);continue;case`runtime-action-result`:case`timeout`:continue}}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=!1,r=new Map,i=new Map;if(e.initialAcceptedAtMs!==void 0)for(let n of t)r.set(n.callId,e.initialAcceptedAtMs);let accept=e=>{t.push(e),r.set(e.callId,Date.now())},a=await this.answerTaskToolCalls(e.taskToolCalls,accept);for(;;){a=this.resolveTaskWaits(a,n,accept);let o=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(o!==void 0){let e=o.flatMap(e=>{let t=i.get(e.callId);return t===void 0?[]:[t]});return{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(e.callId)])),...e.length>0&&{delegatedUsage:e},results:o}}let s=a.flatMap(e=>e.timer===void 0?[]:[e.timer]),c=await e.turn.nextRuntimeEvent(s);if(c===`cancelled`)return c;if(c.kind===`timeout`){for(let e of a)e.callId===c.callId&&(e.timedOut=!0);continue}if(c.kind===`steering`){n||await this.interruptWaitedWorkflowCalls(e.pendingCallIds,t),n=!0;continue}if(c.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,n=c.results.filter(t=>t.kind===`tool-result`&&isInboxToolResultFromRecordedWorkflowToolRun(e,t));if(n.length>0){let e=Date.now();t.push(...n);for(let t of n)r.set(t.callId,e)}continue}let l=await this.handleWorkflowMessage(c.message);l!==void 0&&(accept(l),c.message.kind===`outcome`&&c.message.usage!==void 0&&i.set(l.callId,c.message.usage))}}resolveTaskWaits(e,t,n){let r=sessionTaskTable(this.input.cursor),i=[];for(let a of e){let e=taskWaitResult(r,{interrupted:t,timedOut:a.timedOut});if(e===void 0){i.push(a);continue}let o=renderTaskWaitResult(e,Date.now()-a.startedAtMs);n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[];for(let r of e)r.kind===`task_wait`?n.push(startTaskWait(r)):t(await answerTaskCancel(this.input.cursor,r));let r=this.resolveTaskWaits(n,!1,t);return r.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),r}async interruptWaitedWorkflowCalls(e,t){let n=this.input.cursor.sessionState.snapshot.session.state,r=new Set(t.map(e=>e.callId)),i=e.filter(e=>!r.has(e)).flatMap(e=>{let t=findBlockingWorkflowToolRun(n,e);return t===void 0?[]:[t.address]});await Promise.all(i.map(e=>interruptWorkflowToolRun(e)))}};function startTaskWait(e){let{callId:t,timeoutMs:n}=e,r=n===void 0?void 0:sleep(n).then(()=>t);return{callId:t,startedAtMs:Date.now(),timedOut:!1,timer:r}}var ActiveTurn=class{admitted=new Set;routedToChildren=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;identity;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;caller;constructor(e,t){this.input=e,this.caller=t.caller,this.identity={callerCallId:t.caller?.callId,principal:t.principal},this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringMessage(t,this.identity)&&!this.input.cursor.sessionState.hasProxyInputRequests&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(){let e=[];for(;;){let t=this.input.queue.takeSteering(this.admitted,this.identity);if(t===void 0)break;for(let e of t.sequences)this.admitted.delete(e);let n=await routeSelectedDelivery(t,this.input.cursor);if(n.kind===`cancel-turn`){this.abort();break}n.kind===`turn`&&e.push(n.delivery)}if(this.resetSteering(),e.length===0)return;let t=e.length===1?e[0]:coalesceDeliveries(e);return t.caller!==void 0&&(this.caller=t.caller),t}takeBoundaryMessages(e){let t=[],n=[];for(let r of this.runtimeResults){let i=asBoundaryMessage(r);i===void 0||e!==void 0&&i.kind!==e?n.push(r):t.push(i)}return this.runtimeResults.splice(0,this.runtimeResults.length,...n),t}async nextRuntimeEvent(e){for(;;){let t=await this.routeAdmittedToChildren();if(this.signal.aborted)return`cancelled`;if(t)return{kind:`steering`};let n=this.runtimeResults.shift();if(n!==void 0)return n;let r=await this.waitForInboxOrTimer(e);if(r!==void 0)return{callId:r,kind:`timeout`};let i=await this.input.inbox.next();if(i===void 0)throw Error(`Session inbox closed before runtime actions completed.`);await this.admit(i)}}async waitForInboxOrTimer(e){if(e.length===0||this.input.inbox.hasPending())return;let t=this.input.inbox.whenPending().then(()=>void 0);return await Promise.race([t,...e])}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:this.admitted.add(t.admission.sequence);return;case`runtime-action-result`:this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results});return;case`workflow`:this.runtimeResults.push({kind:`workflow`,message:t.message});return;case`cancel`:this.cancelsThisTurn(e)&&this.abort();return;case`consumed`:return}}async routeAdmittedToChildren(){let e=!1;for(let t of this.admitted){if(this.routedToChildren.has(t))continue;let n=this.input.queue.delivery(t);if(n===void 0){this.admitted.delete(t);continue}this.routedToChildren.add(t);let r=await this.input.cursor.advance(e=>routeDeliverToChildren({delivery:n,...e}));if(r.kind===`cancel-turn`)return this.input.queue.replaceDelivery(t,void 0),this.admitted.delete(t),this.abort(),!1;if(this.input.queue.replaceDelivery(t,r.remainder),r.remainder===void 0){this.admitted.delete(t);continue}isSteeringMessage(r.remainder,this.identity)&&(e=!0)}return e}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};function asBoundaryMessage(e){if(e!==`cancelled`&&e.kind===`workflow`&&(e.message.from.taskId!==void 0||e.message.kind===`agent-started`))return e.message}export{SessionExecution,hasDelegatedCallerContext};
|
|
1
|
+
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{taskWaitResult}from"#execution/tasks/table.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,getBlockingWorkflowToolRuns,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{taskToolResult}from"#execution/tasks/calls.js";import{answerTaskCancel,cancelWorkingTasks,isTaskRunMessage,sessionTaskTable}from"#execution/tasks/session.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{applyTaskRunMessageStep}from"#execution/tasks/steps.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{batchAgentStarts,handleWorkflowToolRunMessage}from"#execution/session-workflow-tool-run.js";import{emitAgentStartedStep}from"#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{ActiveTurn}from"#execution/session/active-turn.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)});try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),n.caller===void 0?t:{...t,caller:n.caller}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1){for(let n of batchAgentStarts(e))n.kind===`message`?await this.handleWorkflowMessage(n.message):t||await this.input.cursor.advance(e=>emitAgentStartedStep({...e,messages:n.messages}))}async runTurnSteps(e,t){let n=t,r=e.caller;for(;;){let{cursor:t}=this.input,i=r;r=void 0;let a=await t.advanceWithHistory(t=>turnStep({...t,abortSignal:e.signal,caller:i,input:n,steeringSignal:e.steeringSignal})),o=a.action===`park`?a.pendingCoordinationCallIds:void 0,s=a.action===`park`&&a.settled!==void 0;if(await e.admitBoundary(),await this.handleBoundaryMessages(e.takeBoundaryMessages(),a.action===`done`),a.action===`cancelled`||!s&&e.signal.aborted&&o===void 0)return await this.finishCancelledTurn(e);if(a.action===`done`)return{isError:a.isError,kind:`done`,output:a.output??``,usage:a.usage,usageDelta:a.usageDelta};if(a.action===`held`&&a.hold===`request`){if(a.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error("This session cannot request human input, so it cannot wait for a tool approval or question. Sessions started without `capabilities.requestInput`, such as schedules, must not use approval-gated tools.");let t=await this.waitForHeldRequest(e,a);if(t===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:t};continue}if(a.action===`held`){if(await this.waitForHeldTurn(e)===`cancelled`)return await this.finishCancelledTurn(e);let t=await e.takeSteering();n=t===void 0?void 0:{delivery:t};continue}if(o!==void 0&&a.action===`park`){let t=a.hasRunsToDispatch===!1?[]:await this.dispatchRuns(),r=t.length===0?void 0:Date.now(),i=await this.waitForRuntimeActionResults({initialAcceptedAtMs:r,initialResults:t,taskToolCalls:a.pendingTaskToolCalls??[],pendingCallIds:o,turn:e});if(i===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:await e.takeSteering(),runtimeResults:i};continue}if(a.action===`park`)return{kind:`park`,settled:a.settled};let c=await e.takeSteering();n=c===void 0?void 0:{delivery:c}}}async dispatchRuns(){return(await this.input.cursor.advance(e=>dispatchCoordinationStep({action:`park`,workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},...e}))).results}async handleWorkflowMessage(e){if(isTaskRunMessage(e)){await this.input.cursor.advance(t=>applyTaskRunMessageStep({...t,message:e}));return}return await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:e})}async cancelTurnWork(){let{cursor:e}=this.input;mayWaitOnWorkflowToolRuns(e.sessionState)&&await cancelDescendantTurnsStep({sessionState:e.sessionState}),await cancelWorkingTasks(e,`turn_cancelled`)}async finishCancelledTurn(e){return await this.handleBoundaryMessages(e.takeBoundaryMessages(`agent-started`)),await this.cancelTurnWork(),{cancelled:!0,kind:`park`}}async waitForHeldTurn(e){let t=!1;for(;;){let n={interrupted:t,timedOut:!1};if(taskWaitResult(sessionTaskTable(this.input.cursor),n)!==void 0)return`woke`;let r=await e.nextRuntimeEvent([]);if(r===`cancelled`)return r;switch(r.kind){case`steering`:t=!0;continue;case`workflow`:await this.handleWorkflowMessage(r.message);continue;case`input`:case`runtime-action-result`:case`timeout`:continue}}}async waitForHeldRequest(e,t){let n=new Set(t.authorizationAttemptIds),r=new Set(t.inputRequestIds);for(;;){let t=this.input.queue.takeAuthorizations(n);if(t!==void 0)return{kind:`deliver`,payloads:t};let i=e.takeInputResponses(r);if(i!==void 0)return i;let a=await e.takeSteering({heldOnPerson:!0});if(a!==void 0)return a;let o=await e.nextRuntimeEvent([]);if(o===`cancelled`)return o;o.kind===`workflow`&&await this.handleWorkflowMessage(o.message)}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=!1,r=new Map,i=new Map;if(e.initialAcceptedAtMs!==void 0)for(let n of t)r.set(n.callId,e.initialAcceptedAtMs);let accept=e=>{t.push(e),r.set(e.callId,Date.now())},a=await this.answerTaskToolCalls(e.taskToolCalls,accept);for(;;){a=this.resolveTaskWaits(a,n,accept);let o=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(o!==void 0){let e=o.flatMap(e=>{let t=i.get(e.callId);return t===void 0?[]:[t]});return{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(e.callId)])),...e.length>0&&{delegatedUsage:e},results:o}}let s=a.flatMap(e=>e.timer===void 0?[]:[e.timer]),c=await e.turn.nextRuntimeEvent(s);if(c===`cancelled`)return c;if(c.kind===`timeout`){for(let e of a)e.callId===c.callId&&(e.timedOut=!0);continue}if(c.kind===`input`)continue;if(c.kind===`steering`){n||await this.interruptWaitedWorkflowCalls(e.pendingCallIds,t),n=!0;continue}if(c.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,n=c.results.filter(t=>t.kind===`tool-result`&&isInboxToolResultFromRecordedWorkflowToolRun(e,t));if(n.length>0){let e=Date.now();t.push(...n);for(let t of n)r.set(t.callId,e)}continue}let l=await this.handleWorkflowMessage(c.message);l!==void 0&&(accept(l),c.message.kind===`outcome`&&c.message.usage!==void 0&&i.set(l.callId,c.message.usage))}}resolveTaskWaits(e,t,n){let r=sessionTaskTable(this.input.cursor),i=[];for(let a of e){let e=taskWaitResult(r,{interrupted:t,timedOut:a.timedOut});if(e===void 0){i.push(a);continue}let o=renderTaskWaitResult(e,Date.now()-a.startedAtMs);n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[];for(let r of e)r.kind===`task_wait`?n.push(startTaskWait(r)):t(await answerTaskCancel(this.input.cursor,r));let r=this.resolveTaskWaits(n,!1,t);return r.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),r}async interruptWaitedWorkflowCalls(e,t){let n=this.input.cursor.sessionState.snapshot.session.state,r=new Set(t.map(e=>e.callId)),i=e.filter(e=>!r.has(e)).flatMap(e=>{let t=findBlockingWorkflowToolRun(n,e);return t===void 0?[]:[t.address]});await Promise.all(i.map(e=>interruptWorkflowToolRun(e)))}};function startTaskWait(e){let{callId:t,timeoutMs:n}=e,r=n===void 0?void 0:sleep(n).then(()=>t);return{callId:t,startedAtMs:Date.now(),timedOut:!1,timer:r}}function mayWaitOnWorkflowToolRuns(e){try{return getBlockingWorkflowToolRuns(e.snapshot?.session?.state).length>0}catch{return!0}}export{SessionExecution,hasDelegatedCallerContext};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DurableSession } from "#execution/durable-session-store.js";
|
|
2
|
-
import type { HarnessSession } from "#harness/types.js";
|
|
2
|
+
import type { HarnessSession, HarnessSessionBase } from "#harness/types.js";
|
|
3
3
|
import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
|
|
4
4
|
export declare const DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION = 40000000;
|
|
5
5
|
/**
|
|
@@ -68,15 +68,15 @@ export declare function refreshSessionFromTurnAgent(input: {
|
|
|
68
68
|
*/
|
|
69
69
|
export declare function mintSubagentContinuationToken(suffix?: string): string;
|
|
70
70
|
/**
|
|
71
|
-
* Projects a {@link
|
|
71
|
+
* Projects a {@link HarnessSessionBase} to {@link DurableSession}.
|
|
72
72
|
*
|
|
73
73
|
* Drops fields rebuilt every turn from `bundle.turnAgent`; keeps
|
|
74
74
|
* `agent.system` and `compaction.lastKnown*` so compaction stays
|
|
75
75
|
* informed after rehydration.
|
|
76
76
|
*/
|
|
77
|
-
export declare function projectToDurableSession(session:
|
|
77
|
+
export declare function projectToDurableSession(session: HarnessSessionBase): DurableSession;
|
|
78
78
|
/**
|
|
79
|
-
* Rehydrates a {@link
|
|
79
|
+
* Rehydrates a {@link HarnessSessionBase} from a {@link DurableSession}
|
|
80
80
|
* plus the current `turnAgent`, rebuilding the runtime-only agent and
|
|
81
81
|
* compaction fields the durable shape omits.
|
|
82
82
|
*/
|
|
@@ -86,5 +86,5 @@ export declare function hydrateDurableSession(input: {
|
|
|
86
86
|
readonly compactionOverrides?: {
|
|
87
87
|
readonly thresholdPercent?: number;
|
|
88
88
|
};
|
|
89
|
-
}):
|
|
89
|
+
}): HarnessSessionBase;
|
|
90
90
|
export {};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";const DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION=4e7;function createCompactionConfig(e={}){let t=e.thresholdPercent??.9,n={recentWindowSize:10,threshold:e.contextWindowTokens===void 0?1e5:Math.max(1,Math.floor(e.contextWindowTokens*t)),thresholdPercent:t};return e.lastKnownInputTokens===void 0?n:{...n,lastKnownInputTokens:e.lastKnownInputTokens,lastKnownPromptMessageCount:e.lastKnownPromptMessageCount}}function createSession(e){let{turnAgent:t}=e,n=createSessionToolDefinitions(t),r={agent:createSessionAgent(t,createSessionSystemPrompt(t),n),compaction:createCompactionConfig({contextWindowTokens:t.model?.contextWindowTokens,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:e.continuationToken,history:[...t.initialMessages??[]],sessionId:e.sessionId};return e.rootSessionId!==void 0&&(r.rootSessionId=e.rootSessionId),r.limits=resolveSessionLimits(e),e.outputSchema!==void 0&&(r.outputSchema=e.outputSchema),r}function createSessionAgent(e,t,n){let r={compactionModelReference:e.compactionModel,reasoning:e.reasoning,system:t,tools:n};if(e.model!==void 0)return{...r,modelReference:e.model};if(e.dynamicModel!==void 0)return{...r,dynamicModel:!0};throw Error(`Cannot create a session before dynamic subagent config is selected.`)}function refreshSessionFromTurnAgent(e){return{...e.session,agent:createSessionAgent(e.turnAgent,createSessionSystemPrompt(e.turnAgent),createSessionToolDefinitions(e.turnAgent)),compaction:createCompactionConfig({contextWindowTokens:e.turnAgent.model?.contextWindowTokens,lastKnownInputTokens:e.session.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.session.compaction.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent})}}function createSessionSystemPrompt(e){let t=formatAvailableSkillsSection(e.availableSkills??[]);return(t===null?e.instructions:[...e.instructions,t]).join(`
|
|
2
2
|
|
|
3
|
-
`)}function mintSubagentContinuationToken(e){return`subagent:${e??crypto.randomUUID()}`}function projectToDurableSession(e){let t={agent:{system:e.agent.system},continuationToken:e.continuationToken,
|
|
3
|
+
`)}function mintSubagentContinuationToken(e){return`subagent:${e??crypto.randomUUID()}`}function projectToDurableSession(e){let t={agent:{system:e.agent.system},continuationToken:e.continuationToken,sessionId:e.sessionId};return(e.compaction.lastKnownInputTokens!==void 0||e.compaction.lastKnownPromptMessageCount!==void 0)&&(t.compaction={lastKnownInputTokens:e.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.compaction.lastKnownPromptMessageCount}),e.rootSessionId!==void 0&&(t.rootSessionId=e.rootSessionId),e.limits!==void 0&&(t.limits=e.limits),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.sandboxState!==void 0&&(t.sandboxState=e.sandboxState),e.state!==void 0&&(t.state=e.state),t}function hydrateDurableSession(e){let{durable:t,turnAgent:n}=e,r=createSessionToolDefinitions(n),i={agent:createSessionAgent(n,t.agent.system,r),compaction:createCompactionConfig({contextWindowTokens:n.model?.contextWindowTokens,lastKnownInputTokens:t.compaction?.lastKnownInputTokens,lastKnownPromptMessageCount:t.compaction?.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:t.continuationToken,sessionId:t.sessionId};return t.rootSessionId!==void 0&&(i.rootSessionId=t.rootSessionId),t.limits!==void 0&&(i.limits=t.limits),t.outputSchema!==void 0&&(i.outputSchema=t.outputSchema),t.sandboxState!==void 0&&(i.sandboxState=t.sandboxState),t.state!==void 0&&(i.state=t.state),i}function createSessionToolDefinitions(e){return e.tools.map(e=>({description:e.description??``,inputSchema:e.inputSchema,name:e.name,outputSchema:e.outputSchema}))}function resolveSessionLimits(e){let t=resolveSessionTokenLimit({authored:e.limits?.maxInputTokensPerSession,fallback:DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION}),n=resolveSessionTokenLimit({authored:e.limits?.maxOutputTokensPerSession,fallback:void 0}),r=resolveSessionTokenLimit({authored:e.limits?.maxTokenCostUsdPerSession,fallback:void 0}),i={};return t!==void 0&&(i.maxInputTokensPerSession=t),n!==void 0&&(i.maxOutputTokensPerSession=n),r!==void 0&&(i.maxTokenCostUsdPerSession=r),i}function resolveSessionTokenLimit(e){return e.authored===!1?void 0:e.authored??e.fallback}export{DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,createCompactionConfig,createSession,hydrateDurableSession,mintSubagentContinuationToken,projectToDurableSession,refreshSessionFromTurnAgent};
|
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
+
import { type SessionHistoryStepState } from "#execution/publish-session-events.js";
|
|
2
3
|
import { type WithSessionStateDelta } from "#execution/session/state-delta.js";
|
|
4
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
3
5
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
4
6
|
export interface CancelledTurnSettleResult {
|
|
5
7
|
readonly serializedContext: Record<string, unknown>;
|
|
6
8
|
readonly sessionState: DurableSessionState;
|
|
9
|
+
readonly history: HarnessModelMessage[];
|
|
7
10
|
/** What the session spent since its caller's last report, when asked to report it. */
|
|
8
11
|
readonly usage?: TokenUsage;
|
|
9
12
|
}
|
|
10
|
-
|
|
13
|
+
/** Takes the history because the turn's pending calls move into it, each answered as cancelled. */
|
|
14
|
+
interface CancelledTurnSettleInput extends SessionHistoryStepState {
|
|
11
15
|
/**
|
|
12
16
|
* Whether a caller receives the turn's usage. Only then is it marked
|
|
13
17
|
* reported; otherwise the next settled turn reports it.
|
|
14
18
|
*/
|
|
15
19
|
readonly reportUsage: boolean;
|
|
16
|
-
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
17
|
-
readonly serializedContext: Record<string, unknown>;
|
|
18
|
-
readonly sessionState: DurableSessionState;
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* Settles one cancelled turn: relays `input.resolved` for every request the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getTurnUsageState,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{commitCancelledCoordinationBatch,getPendingCoordinationBatch}from"#harness/coordination.js";import{removeBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{publishFromSessionStep,restoreSessionStep}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{relayWithdrawnRequests}from"#execution/tools/workflow/withdraw-step.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";async function settleCancelledTurnStep(e){"use step";return await withSessionStateDelta(e,settleCancelledTurn)}async function settleCancelledTurn(e){let t=await relayWithdrawnRequests(e,()=>!0),n=await restoreSessionStep({...t,sessionWritable:e.sessionWritable}),r=n.durableSession.state,{
|
|
1
|
+
import{createInputResolvedEvent}from"#protocol/message.js";import{getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getSessionUsage,getTurnUsageState,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{commitCancelledCoordinationBatch,getPendingCoordinationBatch}from"#harness/coordination.js";import{removeBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{publishFromSessionStep,restoreSessionStep}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{relayWithdrawnRequests}from"#execution/tools/workflow/withdraw-step.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{declinedSignInEvents,withdrawHeldSignIns}from"#harness/held-requests.js";import{cancelApprovalInputBatches,getPendingApprovalRequests}from"#harness/hitl/approval-input-requests.js";const CANCELLED_REASON=`Cancelled.`;async function settleCancelledTurnStep(e){"use step";return await withSessionStateDelta(e,settleCancelledTurn)}async function settleCancelledTurn(e){let t=await relayWithdrawnRequests(e,()=>!0),n={...await restoreSessionStep({...t,sessionWritable:e.sessionWritable}),history:e.history},r=n.durableSession.state,i={completedAt:Date.now(),reason:CANCELLED_REASON},a=withdrawHeldSignIns(r,i),o=getPendingApprovalRequests(r),{published:s,result:c}=await publishFromSessionStep(n,{origin:`own`,async publish(e){let t=getHarnessEmissionState(r);for(let n of declinedSignInEvents(a.withdrawn,CANCELLED_REASON,t))await e(n);return o.length>0&&await e(createInputResolvedEvent({resolutions:o.map(e=>({kind:e.kind,outcome:`cancelled`,requestId:e.requestId})),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await emitCancelledTurn(e,t,getSessionUsage(n.durableSession))},updateSession(t,n){let r={...t,state:withdrawHeldSignIns(t.state,i).state},a=getPendingCoordinationBatch(r.state)?.event.turnId??e.sessionState.emissionState.turnId,o=setHarnessEmissionState(clearPendingSessionLimitPrompt(cancelApprovalInputBatches(commitCancelledCoordinationBatch(removeBlockingWorkflowToolRuns({...r,outputSchema:void 0},a)))),n);if(!e.reportUsage||getTurnUsageState(r.state)===void 0)return{session:o};let s=takeSessionUsageDelta(o);return{result:s.delta,session:s.session}}});return c===void 0?s:{...s,usage:c}}export{settleCancelledTurn,settleCancelledTurnStep};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { HarnessSessionBase } from "#harness/types.js";
|
|
3
3
|
import { type TaskStartedStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";
|
|
5
5
|
type TaskDispatchInput = StartWorkflowTaskInput & {
|
|
@@ -8,7 +8,7 @@ type TaskDispatchInput = StartWorkflowTaskInput & {
|
|
|
8
8
|
/** The call's answer, and the `task.started` event the dispatch step publishes for it. */
|
|
9
9
|
interface TaskDispatchResult {
|
|
10
10
|
readonly result: RuntimeToolResultActionResult;
|
|
11
|
-
readonly session:
|
|
11
|
+
readonly session: HarnessSessionBase;
|
|
12
12
|
readonly started?: TaskStartedStreamEvent;
|
|
13
13
|
}
|
|
14
14
|
/** The entry of a run that does a task's work. */
|
|
@@ -8,7 +8,7 @@ export declare function withTaskIdSchema(schema: ToolSchema): ToolSchema;
|
|
|
8
8
|
/**
|
|
9
9
|
* The tool as the model sees it: its input gains `taskId`, and its description
|
|
10
10
|
* explains it. An agent tool also gets its activity label, the agent and the
|
|
11
|
-
* first sentence of its message: `
|
|
11
|
+
* first sentence of its message: `Researcher: Find the March incidents`.
|
|
12
12
|
*/
|
|
13
13
|
export declare function withTaskIdInput(definition: HarnessToolDefinition): HarnessToolDefinition;
|
|
14
14
|
/** A `serve` tool call's model input, split into the task it names and the tool's own input. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{firstSentence}from"#shared/presentation-text.js";import{isToolSchema,withOptionalStringProperty}from"#tools/schema.js";import{AGENT_SERVE_TOOL_DESCRIPTION,SERVE_TOOL_DESCRIPTION,TASK_ID_INPUT_DESCRIPTION}from"#execution/tasks/render.js";import{AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentTool}from"#execution/tasks/tool-entry-point.js";const TASK_ID_INPUT=`taskId`;function withTaskIdSchema(e){return withOptionalStringProperty(e,{description:TASK_ID_INPUT_DESCRIPTION,name:TASK_ID_INPUT})}function withTaskIdInput(e){let t=e.inputSchema;if(!isToolSchema(t))throw Error(`Tool "${e.name}" has no input schema eve can add taskId to.`);let n=isAgentTool(e),r={...e,description:appendSentence(e.description,n?AGENT_SERVE_TOOL_DESCRIPTION:SERVE_TOOL_DESCRIPTION),inputSchema:withTaskIdSchema(t)};return!n||e.label?.start!==void 0?r:{...r,label:{...e.label,start:t=>agentCallLabel(e.name,t)}}}function agentCallLabel(e,t){let n=typeof t==`object`&&t?t.message:void 0,r=typeof n==`string`?firstSentence(n):void 0;return r===void 0?e:e===AGENT_TOOL_NAME?r:`${e}: ${r}`}function splitTaskIdInput(e){let{[TASK_ID_INPUT]:t,...n}=e;return typeof t==`string`?{input:n,taskId:t}:{input:n}}function appendSentence(e,t){let n=e.trimEnd();return n===``?t:`${n} ${t}`}export{TASK_ID_INPUT,splitTaskIdInput,withTaskIdInput,withTaskIdSchema};
|
|
1
|
+
import{displayTitle}from"#shared/display-name.js";import{firstSentence}from"#shared/presentation-text.js";import{isToolSchema,withOptionalStringProperty}from"#tools/schema.js";import{AGENT_SERVE_TOOL_DESCRIPTION,SERVE_TOOL_DESCRIPTION,TASK_ID_INPUT_DESCRIPTION}from"#execution/tasks/render.js";import{AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentTool}from"#execution/tasks/tool-entry-point.js";const TASK_ID_INPUT=`taskId`;function withTaskIdSchema(e){return withOptionalStringProperty(e,{description:TASK_ID_INPUT_DESCRIPTION,name:TASK_ID_INPUT})}function withTaskIdInput(e){let t=e.inputSchema;if(!isToolSchema(t))throw Error(`Tool "${e.name}" has no input schema eve can add taskId to.`);let n=isAgentTool(e),r={...e,description:appendSentence(e.description,n?AGENT_SERVE_TOOL_DESCRIPTION:SERVE_TOOL_DESCRIPTION),inputSchema:withTaskIdSchema(t)};return!n||e.label?.start!==void 0?r:{...r,label:{...e.label,start:t=>agentCallLabel(e.name,t)}}}function agentCallLabel(e,t){let n=typeof t==`object`&&t?t.message:void 0,r=typeof n==`string`?firstSentence(n):void 0;return r===void 0?displayTitle(e):e===AGENT_TOOL_NAME?r:`${displayTitle(e)}: ${r}`}function splitTaskIdInput(e){let{[TASK_ID_INPUT]:t,...n}=e;return typeof t==`string`?{input:n,taskId:t}:{input:n}}function appendSentence(e,t){let n=e.trimEnd();return n===``?t:`${n} ${t}`}export{TASK_ID_INPUT,splitTaskIdInput,withTaskIdInput,withTaskIdSchema};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import type { TokenUsage } from "#shared/token-usage.js";
|
|
1
2
|
/** Emits a terminal `session.completed` outside a turn. */
|
|
2
3
|
export declare function emitTerminalSessionCompletionStep(input: {
|
|
3
4
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
4
5
|
readonly serializedContext: Record<string, unknown>;
|
|
6
|
+
readonly usage: TokenUsage | undefined;
|
|
5
7
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSessionCompletedEvent}from"#protocol/message.js";import{publishTerminalSessionEvent}from"#execution/publish-session-events.js";async function emitTerminalSessionCompletionStep(e){"use step";await publishTerminalSessionEvent({
|
|
1
|
+
import{createSessionCompletedEvent}from"#protocol/message.js";import{publishTerminalSessionEvent}from"#execution/publish-session-events.js";async function emitTerminalSessionCompletionStep(e){"use step";await publishTerminalSessionEvent({sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,event:createSessionCompletedEvent(e.usage)})}export{emitTerminalSessionCompletionStep};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import type { TokenUsage } from "#shared/token-usage.js";
|
|
1
2
|
/** Emits a terminal `session.failed` to the adapter and durable stream. */
|
|
2
3
|
export declare function emitTerminalSessionFailureStep(input: {
|
|
3
4
|
readonly error: unknown;
|
|
4
5
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
5
6
|
readonly serializedContext: Record<string, unknown>;
|
|
6
7
|
readonly turnId?: string;
|
|
8
|
+
readonly usage: TokenUsage | undefined;
|
|
7
9
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{createSessionFailedEvent}from"#protocol/message.js";import{
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{createSessionFailedEvent}from"#protocol/message.js";import{publishTerminalSessionEvent}from"#execution/publish-session-events.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let t=formatError(e.error),n=summarizeKnownError(e.error),r=t;if(n!==null){let e={...t,message:n.message,name:n.name,semanticErrorId:n.id};r=n.hint===void 0?e:{...e,hint:n.hint}}let i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i}),await publishTerminalSessionEvent({errorId:typeof r.errorId==`string`?r.errorId:void 0,event:createSessionFailedEvent({code:i,details:r,message:a,sessionId:o,usage:e.usage}),sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,turnId:e.turnId})}export{emitTerminalSessionFailureStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{evaluate}from"#ai/evaluate.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.
|
|
1
|
+
import{evaluate}from"#ai/evaluate.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.70.1//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -10,4 +10,9 @@ export interface ExecuteTarget {
|
|
|
10
10
|
}
|
|
11
11
|
export declare function readExecuteTarget(value: unknown): ExecuteTarget | undefined;
|
|
12
12
|
export declare function qualifiedToolName(target: Pick<ExecuteTarget, "connection" | "tool">): string;
|
|
13
|
+
/**
|
|
14
|
+
* How a tool call reads to a person: `Linear: List issues` for a
|
|
15
|
+
* `connection_execute` call, otherwise the tool's display title.
|
|
16
|
+
*/
|
|
17
|
+
export declare function toolCallDisplayName(toolName: string, input: unknown): string;
|
|
13
18
|
export declare function findConnection(registry: ConnectionRegistry, name: string): ResolvedConnectionDefinition | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";const CONNECTION_EXECUTE_TOOL_NAME=`connection_execute`;function readExecuteTarget(e){if(!isObject(e))return;let{connection:t,input:n,tool:r}=e;if(typeof t==`string`&&typeof r==`string`)return{connection:t,input:isObject(n)?n:{},tool:r}}function qualifiedToolName(e){return`${e.connection}__${e.tool}`}function findConnection(e,t){return e.getConnections().find(e=>e.connectionName===t)}export{CONNECTION_EXECUTE_TOOL_NAME,findConnection,qualifiedToolName,readExecuteTarget};
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{displayProperName,displayTitle}from"#shared/display-name.js";const CONNECTION_EXECUTE_TOOL_NAME=`connection_execute`;function readExecuteTarget(e){if(!isObject(e))return;let{connection:t,input:n,tool:r}=e;if(typeof t==`string`&&typeof r==`string`)return{connection:t,input:isObject(n)?n:{},tool:r}}function qualifiedToolName(e){return`${e.connection}__${e.tool}`}function toolCallDisplayName(e,t){let n=e===`connection_execute`?readExecuteTarget(t):void 0;return n===void 0?displayTitle(e):`${displayProperName(n.connection)}: ${displayTitle(n.tool)}`}function findConnection(e,t){return e.getConnections().find(e=>e.connectionName===t)}export{CONNECTION_EXECUTE_TOOL_NAME,findConnection,qualifiedToolName,readExecuteTarget,toolCallDisplayName};
|