eve 0.71.3 → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +22 -6
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/ai/decide.d.ts +7 -0
- package/dist/src/ai/decide.js +1 -0
- package/dist/src/chunks/{use-eve-agent-CFCaYnrI.js → use-eve-agent-C1GYGCtb.js} +698 -388
- package/dist/src/chunks/{use-eve-agent-DcDhXNv1.js → use-eve-agent-hZJ7CB8t.js} +698 -388
- package/dist/src/cli/commands/integration-setup.js +1 -1
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/commands/trace-detail.d.ts +1 -1
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-flow.d.ts +1 -0
- package/dist/src/cli/dev/tui/setup-panel.d.ts +1 -0
- package/dist/src/cli/dev/tui/setup-panel.js +2 -1
- package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +2 -2
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +2 -2
- package/dist/src/cli/dev/tui/transcript-parts.d.ts +2 -1
- package/dist/src/cli/dev/tui/transcript-parts.js +1 -1
- package/dist/src/cli/dev/tui/transcript.js +1 -1
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/client/conversation-projection.d.ts +4 -0
- package/dist/src/client/conversation-projection.js +1 -0
- package/dist/src/client/conversation-reducer.js +1 -1
- package/dist/src/client/conversation-state.d.ts +5 -26
- package/dist/src/client/conversation-state.js +1 -1
- package/dist/src/client/index.d.ts +1 -0
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-action-parts.d.ts +1 -11
- package/dist/src/client/message-action-parts.js +1 -1
- package/dist/src/client/message-reducer.d.ts +3 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/tool-call-state.d.ts +23 -0
- package/dist/src/client/tool-call-state.js +1 -0
- package/dist/src/client/tool-part-state.d.ts +7 -0
- package/dist/src/client/tool-part-state.js +1 -0
- package/dist/src/compiled/.vendor-stamp.json +10 -10
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +1453 -1358
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +1 -2
- package/dist/src/compiled/@ai-sdk/code-mode/index.d.ts +172 -163
- package/dist/src/compiled/@ai-sdk/code-mode/index.js +15 -20
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +772 -733
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -8
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +887 -790
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +1722 -1691
- package/dist/src/compiled/@ai-sdk/openai/index.js +3 -14
- package/dist/src/compiled/@ai-sdk/otel/index.d.ts +216 -159
- package/dist/src/compiled/@ai-sdk/otel/index.js +3 -3
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +7542 -7271
- package/dist/src/compiled/@ai-sdk/provider/index.js +1 -3
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +1799 -1600
- package/dist/src/compiled/@eve/catalog/index.js +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-DXLdlucM.js +15 -0
- package/dist/src/compiled/_chunks/workflow/experimental-decision-BrfWf6-n.js +3 -0
- package/dist/src/compiler/extension-compatibility.d.ts +36 -20
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-metadata.d.ts +1 -0
- package/dist/src/context/providers/session.js +1 -1
- package/dist/src/evals/define-eval.d.ts +1 -1
- package/dist/src/evals/judge.d.ts +1 -1
- package/dist/src/evals/judge.js +2 -2
- package/dist/src/evals/types.d.ts +8 -8
- package/dist/src/execution/cancel-descendant-turns-step.d.ts +1 -0
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/durable-session-read.d.ts +5 -0
- package/dist/src/execution/durable-session-read.js +1 -0
- package/dist/src/execution/durable-session-store.d.ts +4 -10
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/dynamic-connections.d.ts +3 -3
- package/dist/src/execution/dynamic-connections.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
- package/dist/src/execution/legacy-session/snapshot.d.ts +3 -0
- package/dist/src/execution/legacy-session/snapshot.js +1 -1
- package/dist/src/execution/model-call-batching.js +1 -1
- package/dist/src/execution/node-step.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +7 -2
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/answer-caller.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +3 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -1
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/pending-turn-state.d.ts +8 -3
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/task-tool-tracing-step.d.ts +5 -0
- package/dist/src/execution/session/task-tool-tracing-step.js +1 -0
- package/dist/src/execution/session/turn-step-result.js +1 -1
- 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 +1 -0
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +4 -6
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/start.d.ts +3 -3
- package/dist/src/execution/tasks/start.js +1 -1
- package/dist/src/execution/tasks/steps.d.ts +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.d.ts +5 -1
- package/dist/src/execution/terminal-session-completion-step.js +1 -1
- 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-tools.js +1 -1
- package/dist/src/execution/tools/workflow/harness-definition.js +1 -1
- package/dist/src/execution/tools/workflow/step.js +1 -1
- package/dist/src/execution/tools/workflow/withdraw-step.d.ts +7 -9
- package/dist/src/execution/tools/workflow/withdraw-step.js +1 -1
- package/dist/src/execution/workflow-trace-context.d.ts +2 -2
- package/dist/src/harness/authorization.d.ts +4 -2
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/{compaction.js → compaction/engine.js} +1 -1
- package/dist/src/harness/compaction/step.d.ts +46 -0
- package/dist/src/harness/compaction/step.js +1 -0
- package/dist/src/harness/coordination.d.ts +32 -68
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/current-messages.d.ts +1 -3
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/emission.d.ts +4 -52
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +1 -0
- package/dist/src/harness/final-output.d.ts +5 -0
- package/dist/src/harness/final-output.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +115 -0
- package/dist/src/harness/hitl/approvals.js +1 -0
- package/dist/src/harness/hitl/approved-call-callers.d.ts +14 -0
- package/dist/src/harness/hitl/approved-call-callers.js +1 -0
- package/dist/src/harness/hitl/approved-calls.d.ts +37 -0
- package/dist/src/harness/hitl/approved-calls.js +1 -0
- package/dist/src/harness/hitl/budget.d.ts +21 -0
- package/dist/src/harness/hitl/budget.js +1 -0
- package/dist/src/harness/{approval-candidates.d.ts → hitl/candidates.d.ts} +9 -18
- package/dist/src/harness/hitl/candidates.js +1 -0
- package/dist/src/harness/hitl/coordinator.js +1 -0
- package/dist/src/harness/hitl/delivery.d.ts +37 -0
- package/dist/src/harness/hitl/delivery.js +1 -0
- package/dist/src/harness/hitl/index.d.ts +49 -0
- package/dist/src/harness/hitl/index.js +1 -0
- package/dist/src/harness/hitl/intake.d.ts +67 -0
- package/dist/src/harness/hitl/intake.js +1 -0
- package/dist/src/harness/{stale-input-responses.d.ts → hitl/stale-responses.d.ts} +5 -3
- package/dist/src/harness/hitl/stale-responses.js +3 -0
- package/dist/src/harness/inline-tool-authorization.d.ts +4 -0
- package/dist/src/harness/inline-tool-authorization.js +1 -1
- package/dist/src/harness/input-extraction.d.ts +1 -10
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-request-resolution.d.ts +1 -5
- package/dist/src/harness/input-request-resolution.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +78 -0
- package/dist/src/harness/model-call/call.js +1 -0
- package/dist/src/harness/{model-call-error.d.ts → model-call/errors.d.ts} +1 -1
- package/dist/src/harness/model-call/failure.d.ts +52 -0
- package/dist/src/harness/model-call/failure.js +1 -0
- package/dist/src/harness/model-call/model.d.ts +18 -0
- package/dist/src/harness/model-call/model.js +1 -0
- package/dist/src/harness/model-call/recovery.d.ts +52 -0
- package/dist/src/harness/model-call/recovery.js +1 -0
- package/dist/src/harness/model-call/request.d.ts +30 -0
- package/dist/src/harness/model-call/request.js +3 -0
- package/dist/src/harness/model-call/response.d.ts +39 -0
- package/dist/src/harness/model-call/response.js +1 -0
- package/dist/src/harness/model-call/retry.d.ts +11 -0
- package/dist/src/harness/model-call/retry.js +1 -0
- package/dist/src/harness/model-call/run.d.ts +38 -0
- package/dist/src/harness/model-call/run.js +1 -0
- package/dist/src/harness/model-call/tools.d.ts +48 -0
- package/dist/src/harness/model-call/tools.js +1 -0
- package/dist/src/harness/model-call/usage.d.ts +23 -0
- package/dist/src/harness/model-call/usage.js +1 -0
- package/dist/src/harness/nested-actions.d.ts +2 -2
- package/dist/src/harness/provider-tools.d.ts +2 -2
- package/dist/src/harness/provider-tools.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +4 -12
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/session-machine/commit.d.ts +28 -0
- package/dist/src/harness/session-machine/commit.js +1 -0
- package/dist/src/harness/session-machine/current.d.ts +29 -0
- package/dist/src/harness/session-machine/current.js +1 -0
- package/dist/src/harness/session-machine/events.d.ts +6 -0
- package/dist/src/harness/session-machine/events.js +1 -0
- package/dist/src/harness/session-machine/resolver-events.d.ts +12 -0
- package/dist/src/harness/session-machine/resolver-events.js +1 -0
- package/dist/src/harness/session-machine/state.d.ts +47 -0
- package/dist/src/harness/session-machine/state.js +1 -0
- package/dist/src/harness/session-machine/transitions.d.ts +188 -0
- package/dist/src/harness/session-machine/transitions.js +1 -0
- package/dist/src/harness/session-machine/view.d.ts +58 -0
- package/dist/src/harness/session-machine/view.js +1 -0
- package/dist/src/harness/step/after-model.d.ts +7 -0
- package/dist/src/harness/step/after-model.js +1 -0
- package/dist/src/harness/step/context.d.ts +59 -0
- package/dist/src/harness/step/context.js +1 -0
- package/dist/src/harness/step/intake.d.ts +34 -0
- package/dist/src/harness/step/intake.js +1 -0
- package/dist/src/harness/step/prompt.d.ts +37 -0
- package/dist/src/harness/step/prompt.js +1 -0
- package/dist/src/harness/step-hooks.d.ts +8 -13
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.d.ts +7 -22
- package/dist/src/harness/tool-loop.js +1 -3
- package/dist/src/harness/tools.d.ts +13 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +1 -1
- package/dist/src/harness/types.d.ts +6 -0
- package/dist/src/instrumentation/ai-sdk-hook-bridge.d.ts +1 -1
- package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -1
- package/dist/src/instrumentation/content.js +1 -1
- package/dist/src/instrumentation/dispatch.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +28 -56
- package/dist/src/instrumentation/native-events.d.ts +2 -1
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/provider.d.ts +1 -1
- package/dist/src/instrumentation/runtime-context.d.ts +2 -3
- package/dist/src/instrumentation/runtime-context.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +11 -1
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/state.d.ts +6 -1
- package/dist/src/instrumentation/state.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/attachments/limited-read.d.ts +16 -0
- package/dist/src/internal/attachments/limited-read.js +1 -0
- package/dist/src/internal/authored-definition/schema-backed.d.ts +2 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/mcp/published-tools.d.ts +13 -0
- package/dist/src/internal/mcp/published-tools.js +1 -0
- package/dist/src/internal/mcp/request-trace-context.d.ts +12 -0
- package/dist/src/internal/mcp/request-trace-context.js +1 -0
- package/dist/src/internal/mcp/streamable-http-server.d.ts +7 -3
- package/dist/src/internal/mcp/streamable-http-server.js +1 -1
- package/dist/src/internal/model-auth/transport.d.ts +3 -3
- package/dist/src/internal/model-auth/transport.js +1 -1
- package/dist/src/models/auto.d.ts +5 -5
- package/dist/src/models/auto.js +2 -2
- package/dist/src/protocol/message.d.ts +7 -0
- package/dist/src/protocol/message.js +1 -1
- package/dist/src/protocol/session-projection.d.ts +159 -0
- package/dist/src/protocol/session-projection.js +1 -0
- package/dist/src/public/ai/index.d.ts +1 -1
- package/dist/src/public/ai/index.js +1 -1
- package/dist/src/public/channels/chat-sdk/attachment-refs.d.ts +15 -0
- package/dist/src/public/channels/chat-sdk/attachment-refs.js +1 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/chat-sdk/messageToUserContent.d.ts +11 -5
- package/dist/src/public/channels/chat-sdk/messageToUserContent.js +1 -1
- package/dist/src/public/channels/discord/attachments.d.ts +15 -0
- package/dist/src/public/channels/discord/attachments.js +1 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/discord/inbound.d.ts +13 -0
- package/dist/src/public/channels/discord/inbound.js +1 -1
- package/dist/src/public/channels/linear/inbound-uploads.d.ts +21 -0
- package/dist/src/public/channels/linear/inbound-uploads.js +1 -0
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/linq/inboundContent.d.ts +7 -1
- package/dist/src/public/channels/linq/inboundContent.js +1 -1
- package/dist/src/public/channels/linq/linqChannel.js +1 -1
- package/dist/src/public/channels/mcp.d.ts +17 -2
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/channels/photon/attachments.d.ts +21 -0
- package/dist/src/public/channels/photon/attachments.js +1 -0
- package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
- package/dist/src/public/channels/slack/attachments.d.ts +3 -1
- package/dist/src/public/channels/slack/attachments.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/attachments.d.ts +4 -4
- package/dist/src/public/channels/teams/attachments.js +1 -1
- package/dist/src/public/channels/telegram/attachments.js +1 -1
- package/dist/src/public/channels/twilio/api.d.ts +7 -0
- package/dist/src/public/channels/twilio/api.js +1 -1
- package/dist/src/public/channels/twilio/inbound.d.ts +7 -0
- package/dist/src/public/channels/twilio/inbound.js +2 -2
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/definitions/connections/mcp.d.ts +1 -1
- package/dist/src/public/definitions/connections/openapi.d.ts +1 -1
- package/dist/src/react/index.d.ts +1 -0
- package/dist/src/react/index.js +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +2 -2
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.d.ts +2 -0
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/cli/prompt-ui.d.ts +3 -0
- package/dist/src/setup/cli/prompt-ui.js +3 -1
- package/dist/src/setup/cli/select-component.d.ts +1 -0
- package/dist/src/setup/cli/select-component.js +1 -1
- package/dist/src/setup/flows/ensure-vercel-project.d.ts +2 -0
- package/dist/src/setup/flows/ensure-vercel-project.js +1 -1
- package/dist/src/setup/integrations/discord/api.js +1 -1
- package/dist/src/setup/integrations/web/auth-options.d.ts +4 -0
- package/dist/src/setup/integrations/web/auth-options.js +1 -0
- package/dist/src/setup/integrations/web/auth-scaffold.d.ts +7 -0
- package/dist/src/setup/integrations/web/auth-scaffold.js +1 -0
- package/dist/src/setup/integrations/web/provision-auth.d.ts +3 -0
- package/dist/src/setup/integrations/web/provision-auth.js +1 -0
- package/dist/src/setup/integrations/web/setup.d.ts +11 -6
- package/dist/src/setup/integrations/web/setup.js +3 -3
- package/dist/src/setup/prompter.d.ts +2 -0
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +1 -0
- package/dist/src/setup/scaffold/update/web-options.js +1 -1
- package/dist/src/setup/vercel-project-api.d.ts +9 -0
- package/dist/src/setup/vercel-project-api.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +4 -2
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/shared/web-search.d.ts +1 -1
- package/dist/src/subagents/adapter.js +1 -1
- package/dist/src/subagents/event-proxy-step.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +4 -28
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/svelte/index.d.ts +2 -0
- package/dist/src/svelte/index.js +39 -2
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/approval/policies.d.ts +5 -5
- package/dist/src/tools/approval/policies.js +1 -1
- package/dist/src/tools/framework/agent.js +1 -1
- package/dist/src/tools/provided/agent-router.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/ask-question.js +2 -2
- package/dist/src/tools/provided/bash.js +1 -1
- package/dist/src/tools/provided/framework-tool.d.ts +3 -0
- package/dist/src/tools/provided/framework-tool.js +1 -0
- package/dist/src/tools/provided/glob.js +2 -2
- package/dist/src/tools/provided/grep.js +2 -2
- package/dist/src/tools/provided/load-skill.js +1 -1
- package/dist/src/tools/provided/no-reply.js +1 -1
- package/dist/src/tools/provided/read-file.js +2 -2
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/provided/sleep.js +1 -1
- package/dist/src/tools/provided/task-cancel.js +1 -1
- package/dist/src/tools/provided/task-wait.js +1 -1
- package/dist/src/tools/provided/web-fetch.js +2 -2
- package/dist/src/tools/provided/web-search.js +1 -1
- package/dist/src/tools/provided/workflow.js +1 -1
- package/dist/src/tools/provided/write-file.js +2 -2
- package/dist/src/tracing/agent-approval-instrumentation.d.ts +2 -2
- package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-usage.d.ts +1 -1
- package/dist/src/tracing/agent-otel-usage.js +1 -1
- package/dist/src/tracing/agent-span-contract.d.ts +0 -1
- package/dist/src/tracing/agent-span-contract.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +16 -6
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-codec.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +7 -3
- package/dist/src/tracing/invoke-tool-span.js +1 -1
- package/dist/src/tracing/local-trace-analysis.js +1 -1
- package/dist/src/vue/index.d.ts +2 -0
- package/dist/src/vue/index.js +39 -2
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +2 -2
- package/docs/channels/chat-sdk.mdx +3 -1
- package/docs/channels/custom.mdx +2 -0
- package/docs/channels/discord.mdx +5 -4
- package/docs/channels/eve.mdx +65 -0
- package/docs/channels/linear.mdx +1 -1
- package/docs/channels/linq.mdx +2 -0
- package/docs/channels/mcp.mdx +39 -1
- package/docs/channels/photon.mdx +5 -0
- package/docs/channels/teams.mdx +4 -7
- package/docs/channels/twilio.mdx +1 -1
- package/docs/concepts/built-in-tools.md +12 -0
- package/docs/concepts/sessions-runs-and-streaming.md +3 -3
- package/docs/connections/overview.mdx +1 -1
- package/docs/dynamic-configuration/meta.json +1 -1
- package/docs/evals/judge.mdx +16 -16
- package/docs/evals/overview.mdx +1 -1
- package/docs/guides/{evaluate.md → decide.md} +35 -35
- package/docs/guides/dynamic-capabilities.md +1 -1
- package/docs/guides/frontend/overview.mdx +3 -1
- package/docs/guides/hooks.md +1 -1
- package/docs/guides/instrumentation/instrumentation.mdx +23 -22
- package/docs/guides/instrumentation/otel.mdx +13 -2
- package/docs/reference/cli.md +3 -3
- package/docs/reference/typescript-api.md +4 -2
- package/docs/tools/human-in-the-loop.md +6 -4
- package/docs/tools/workflows.mdx +4 -4
- package/package.json +11 -11
- package/dist/src/ai/evaluate.d.ts +0 -7
- package/dist/src/ai/evaluate.js +0 -1
- package/dist/src/client/message-task-parts.d.ts +0 -8
- package/dist/src/client/message-task-parts.js +0 -1
- package/dist/src/compiled/_chunks/workflow/dist-C3ZE62yI.js +0 -25
- package/dist/src/compiled/_chunks/workflow/experimental-evaluation-Dm32egEG.js +0 -5
- package/dist/src/harness/active-turn-id.d.ts +0 -11
- package/dist/src/harness/active-turn-id.js +0 -1
- package/dist/src/harness/approval-candidates.js +0 -1
- package/dist/src/harness/approval-delivery-coordinator.js +0 -1
- package/dist/src/harness/approved-call-callers.d.ts +0 -11
- package/dist/src/harness/approved-call-callers.js +0 -1
- package/dist/src/harness/cancelled-turn-emission.d.ts +0 -12
- package/dist/src/harness/cancelled-turn-emission.js +0 -1
- package/dist/src/harness/emission-state.d.ts +0 -36
- package/dist/src/harness/emission-state.js +0 -1
- package/dist/src/harness/held-requests.d.ts +0 -18
- package/dist/src/harness/held-requests.js +0 -1
- package/dist/src/harness/hitl/approval-input-requests.d.ts +0 -27
- package/dist/src/harness/hitl/approval-input-requests.js +0 -1
- package/dist/src/harness/hitl/pending-input-resolution.d.ts +0 -54
- package/dist/src/harness/hitl/pending-input-resolution.js +0 -1
- package/dist/src/harness/hitl/session-limit-input-requests.d.ts +0 -12
- package/dist/src/harness/hitl/session-limit-input-requests.js +0 -1
- package/dist/src/harness/input-requests.d.ts +0 -37
- package/dist/src/harness/input-requests.js +0 -1
- package/dist/src/harness/pending-input-batches.d.ts +0 -81
- package/dist/src/harness/pending-input-batches.js +0 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +0 -45
- package/dist/src/harness/session-limit-enforcement.js +0 -1
- package/dist/src/harness/stale-input-responses.js +0 -3
- package/dist/src/harness/workflow-dispatch.d.ts +0 -30
- package/dist/src/harness/workflow-dispatch.js +0 -1
- package/dist/src/public/channels/linear/inbound-images.d.ts +0 -19
- package/dist/src/public/channels/linear/inbound-images.js +0 -1
- package/dist/src/tracing/agent-action-instrumentation.d.ts +0 -26
- package/dist/src/tracing/agent-action-instrumentation.js +0 -1
- /package/dist/src/harness/{compaction.d.ts → compaction/engine.d.ts} +0 -0
- /package/dist/src/harness/{compaction-prompt.d.ts → compaction/prompt.d.ts} +0 -0
- /package/dist/src/harness/{compaction-prompt.js → compaction/prompt.js} +0 -0
- /package/dist/src/harness/{session-limit-continuation.d.ts → hitl/budget-request.d.ts} +0 -0
- /package/dist/src/harness/{session-limit-continuation.js → hitl/budget-request.js} +0 -0
- /package/dist/src/harness/{approval-delivery-coordinator.d.ts → hitl/coordinator.d.ts} +0 -0
- /package/dist/src/harness/{model-call-error.js → model-call/errors.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{isUserMessageKind,validateHarnessModelMessages}from"#harness/messages.js";import{
|
|
1
|
+
import{initialSessionProjection}from"#protocol/session-projection.js";import{isObject}from"#shared/guards.js";import{isUserMessageKind,validateHarnessModelMessages}from"#harness/messages.js";import{SESSION_PROJECTION_STATE_KEY}from"#harness/session-machine/view.js";import{DURABLE_SESSION_VERSION}from"#execution/durable-session-store.js";const PRESERVED_FRAMEWORK_STATE=new Set([`eve.harness.turnUsage`,`eve.harness.reportedSessionUsage`,`eve.harness.sessionRuntimeTokenLimit`]);function readLegacySnapshot(e){let t=e.snapshot;if(!isObject(t)||t.version!==1||!isObject(t.session)||t.session.sessionId!==e.sessionId||!Array.isArray(t.session.history))throw Error(`Unsupported legacy session snapshot.`);return t.session}function importConversation(e){let{history:t,...n}=e,r=Object.fromEntries(Object.entries(e.state??{}).filter(([e])=>!e.startsWith(`eve.`)||PRESERVED_FRAMEWORK_STATE.has(e)));return{history:normalizeHistory(t),sessionState:{version:DURABLE_SESSION_VERSION,sessionId:e.sessionId,continuationToken:e.continuationToken,hasProxyInputRequests:!1,snapshot:{session:{...n,state:{...r,[SESSION_PROJECTION_STATE_KEY]:importProjection(e)}}}}}}function importProjection(e){let t=e.state?.[`eve.harness.emission`],n=initialSessionProjection();if(!isObject(t)||typeof t.sequence!=`number`)return n;let r=t.sessionStarted===!0?{started:!0}:{},i=typeof t.turnId==`string`?t.turnId:``;if(i===``)return{...n,...r,nextSequence:t.sequence};let a=typeof t.stepIndex==`number`?t.stepIndex:0;return{...n,...r,activeTurnId:i,nextSequence:t.sequence+1,turns:{[i]:{turnId:i,sequence:t.sequence,status:`active`,...a>0&&{stepIndex:a-1}}}}}function normalizeHistory(e){let t=[],n=new Map,settle=()=>{n.size!==0&&(t.push({role:`tool`,content:[...n].map(([e,t])=>({type:`tool-result`,toolCallId:e,toolName:t,output:{type:`error-text`,value:`Interrupted by the session upgrade. Start this work again if it is still needed.`}}))}),n.clear())};for(let r of e){let e=r;if(e.role===`assistant`&&Array.isArray(e.content))e={...e,content:e.content.filter(e=>e.type!==`tool-approval-request`)};else if(e.role===`tool`&&(e={...e,content:e.content.filter(e=>e.type!==`tool-approval-response`)},e.content.length===0))continue;if(e.role!==`tool`&&settle(),e.role===`assistant`&&Array.isArray(e.content))for(let t of e.content)t.type===`tool-call`&&n.set(t.toolCallId,t.toolName);if(e.role===`tool`)for(let t of e.content)t.type===`tool-result`&&n.delete(t.toolCallId);let i=e.kind;t.push(e.role===`user`&&!isUserMessageKind(i)?{...e,kind:`user`}:e)}return settle(),validateHarnessModelMessages(t)}export{importConversation,importProjection,normalizeHistory,readLegacySnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{derivePendingState}from"#execution/session/pending-turn-state.js";async function runModelCallBatch(e){let t=e.initialSession,n=e.initialInput,r=0;for(;;){let i=await e.runStep({firstCall:r===0,session:t,stepInput:n});if(r++,e.steeringSignal?.aborted===!0||i.steered===!0||!shouldRunAnotherModelCall({completedModelCalls:r,modelCallsPerStep:e.modelCallsPerStep,result:i}))return i;t=i.session,n=void 0}}function shouldRunAnotherModelCall(e){if(e.completedModelCalls>=e.modelCallsPerStep||typeof e.result.next!=`function`)return!1;let t=derivePendingState(e.result.session);return!t.hasPendingAuthorization&&!t.hasPendingInputBatch&&(t.pendingCoordinationCallIds?.length??0)===0}export{runModelCallBatch};
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";async function runModelCallBatch(e){let t=e.initialSession,n=e.initialInput,r=0;for(;;){let i=await e.runStep({firstCall:r===0,session:t,stepInput:n});if(r++,e.steeringSignal?.aborted===!0||i.steered===!0||!shouldRunAnotherModelCall({completedModelCalls:r,modelCallsPerStep:e.modelCallsPerStep,result:i}))return i;t=i.session,n=void 0}}function shouldRunAnotherModelCall(e){if(e.completedModelCalls>=e.modelCallsPerStep||typeof e.result.next!=`function`)return!1;let t=derivePendingState(e.result.session,storedProjection(e.result.session.state));return!t.hasPendingAuthorization&&!t.hasPendingInputBatch&&(t.pendingCoordinationCallIds?.length??0)===0}export{runModelCallBatch};
|
|
@@ -6,6 +6,7 @@ import { type RuntimeModelResolutionScope } from "#runtime/agent/resolve-model.j
|
|
|
6
6
|
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
7
7
|
import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
|
|
8
8
|
import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";
|
|
9
|
+
import type { ToolLoopHarnessConfig } from "#harness/types.js";
|
|
9
10
|
/**
|
|
10
11
|
* Factory that creates a {@link Runtime} for the given compiled
|
|
11
12
|
* artifacts source and optional node id. Matches the signature of
|
|
@@ -42,6 +43,7 @@ interface CreateExecutionNodeStepInput {
|
|
|
42
43
|
readonly sequence: number;
|
|
43
44
|
readonly turnId: string;
|
|
44
45
|
}) => Promise<void>;
|
|
46
|
+
readonly signInCompletions?: ToolLoopHarnessConfig["signInCompletions"];
|
|
45
47
|
readonly historyProjector?: HistoryViewProjector;
|
|
46
48
|
readonly historyView?: PreparedHistoryView;
|
|
47
49
|
readonly instrumentation: ExecutionInstrumentation | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/harness-definition.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/harness-definition.js";import{isFrameworkTool}from"#tools/provided/framework-tool.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{preparePersistedStepDynamicToolMetadata}from"#context/dynamic-tool-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{workflowIdForHandling}from"#runtime/subagents/workflow-reference.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{WEB_SEARCH_TOOL_NAME,resolveWebSearchActivityLabel}from"#harness/provider-tool-schemas.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel,e.abortSignal),r=createNodeHarnessTools({node:e.node}),i=e.instrumentation,a=i?.prepareExecution(),o=createToolLoopHarness({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,handleEvent:e.handleEvent,historyProjector:e.historyProjector,historyView:e.historyView,instrumentation:a,prepareApprovalTurn:e.prepareApprovalTurn,signInCompletions:e.signInCompletions,resolveStepDynamicTools:t=>preparePersistedStepDynamicToolMetadata({...t,resolvers:e.node.agent.dynamicToolResolvers??[]}),dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?o:async(e,t)=>{try{return await o(e,t)}finally{await i.flush()}}}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),n={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:t.version},r=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),i=process.env.VERCEL_GIT_COMMIT_REF?.trim(),a=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return r||i||a?{...n,build:{deployedAt:a||void 0,gitBranch:i||void 0,gitSha:r||void 0}}:n}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t,n){return r=>dispatchDynamicModelEvent({abortSignal:n,ctx:r.ctx,dynamicModel:t,event:r.event,messages:r.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t}function resolveHarnessToolDefinition(e){let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name),n=workflowIdForHandling(e.tool.behavior?.handling);return n===void 0?t===null?(log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null):createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}):t===null?createPreparedWorkflowToolHarnessDefinition(e.tool):createWorkflowToolHarnessDefinition({executeInput:t.definition.executeInput,definition:createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}),workflowId:n})}function createRegisteredHarnessToolDefinition(e){let t=e.definition,n=t.execute;return{availableInSubagents:t.availableInSubagents,label:t.label??(t.owner.kind===`framework`&&t.name===WEB_SEARCH_TOOL_NAME?{start:resolveWebSearchActivityLabel}:void 0),approvalKey:t.approvalKey,behavior:e.behavior,description:t.description,endsTurn:t.endsTurn,executeInput:t.executeInput,execute:resolveAuthoredExecute({rawExecute:n,scope:t.name}),frameworkTool:isFrameworkTool(t)||t.owner.kind===`framework`,frameworkAction:t.behavior?.presentation===`load-skill`?`load-skill`:void 0,inputSchema:t.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:t.name,approval:t.approval,outputSchema:t.outputSchema,rootOnly:e.rootOnly,toModelOutput:t.toModelOutput}}function resolveAuthoredExecute(e){let{rawExecute:t,scope:n}=e;return t===void 0?void 0:createToolExecuteWithAuth({execute:t,scope:n})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthKey,TurnDeliveryIdsKey}from"#context/keys.js";import
|
|
1
|
+
import{AuthKey,TurnDeliveryIdsKey}from"#context/keys.js";import"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{storedProjection}from"#harness/session-machine/view.js";import{resolveRemoteAgentStreamHeaders,respondToRemoteAgentSession}from"#execution/agent-sessions/remote.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{publishSessionEvents,relaySessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{sessionView}from"#harness/session-machine/commit.js";import{hold,receiveRelayedAnswer,routeAnswer}from"#harness/session-machine/transitions.js";import{getProxyInputRequests,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{hasDelegatedSessionContext}from"#execution/delegated-session-context.js";import{setChannelContext}from"#execution/channel-context.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendWorkflowAskAnswers,toToolInputResponseResponder}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";return await withSessionStateDelta(e,routeProxiedDeliver)}async function routeProxiedDeliver(e){let t=getProxyInputRequests(readDurableSession(e.sessionState).state),{delivery:n,serializedContext:r}=await deliverChannelInputResponses({...e,routable:e=>t.has(e.requestId)}),i=readDurableSession(e.sessionState),a=new Map,o=new Map,s,c=!hasDelegatedSessionContext(r)&&n.caller===void 0,l=new Set,u=[],d=[];for(let[e,t]of n.payloads.entries()){let r=routeDeliverPayload({allowRoute:e=>!l.has(e),payload:t,resolveMessage:c,state:i.state});s??=r.parentAction,r.forSelf!==void 0&&a.set(e,r.forSelf);for(let[t,i]of r.forChildren.entries()){if(i.workflowAsk!==void 0)for(let{requestId:e}of i.resolved.resolutions)l.add(e);if(i.message!==void 0){let{sequence:t,turnId:r}=i.resolved.event;u.push(receiveRelayedAnswer({message:i.message,sequence:t,turnId:r}));for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&d.push(t.deliveryId)}let a=JSON.stringify([i.childContinuationToken,i.childSessionInbox?.sessionId??``,i.remote?.sessionId??``,i.resolved.event.sequence,i.resolved.event.stepIndex,i.resolved.event.turnId,i.inputSource??null]),s=o.get(a)??{workflowAsk:i.workflowAsk,remote:i.remote,childContinuationToken:i.childContinuationToken,childSessionInbox:i.childSessionInbox,event:i.resolved.event,metadata:[],payloads:[],resolutions:new Map},c=s.payloads.length;s.payloads.push(i.payload);for(let e of i.resolved.resolutions)s.resolutions.has(e.requestId)||s.resolutions.set(e.requestId,e);if(r.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&s.metadata.push({...t,payloadIndex:c});o.set(a,s)}}let f=!1,p=[];for(let e of o.values()){if(e.workflowAsk!==void 0){let t=coalesceDeliverPayloads(e.payloads).inputResponses??[];await sendWorkflowAskAnswers(e.workflowAsk,t,toToolInputResponseResponder(n.auth))}else{let t={...n,deliveryMetadata:e.metadata.length===0?void 0:e.metadata,payloads:e.payloads},i=e.remote;if(i!==void 0){let t=await deserializeContext(r),a=await resolveRemoteAgentStreamHeaders({bundle:t.require(BundleKey),name:i.name,resolverId:i.resolverId,url:i.url});await respondToRemoteAgentSession({remote:i,headers:a,auth:n.auth,responses:coalesceDeliverPayloads(e.payloads).inputResponses??[]})}else await resumeSessionInbox(e.childSessionInbox??e.childContinuationToken,t)}p.push({event:e.event,resolutions:[...e.resolutions.values()]}),i=retireProxyInputRequests(i,[...e.resolutions.keys()]),f=!0}let m=sessionView(storedProjection(i.state),i.state),h=[...routeAnswer(m,{children:p}).events];h.length>0&&a.size===0&&s===void 0&&getProxyInputRequests(i.state).size>0&&h.push(...hold(m,{on:`input`}).events);let g={serializedContext:r,sessionState:f?replaceDurableSessionSnapshot({session:i,state:e.sessionState}):e.sessionState};u.length>0&&(g=await publishSessionEvents({serializedContext:joinTurnDeliveryIds(g.serializedContext,d),sessionState:g.sessionState,sessionWritable:e.sessionWritable},u));let _=await relaySessionEvents({...g,sessionWritable:e.sessionWritable},h);if(s!==void 0)return{..._,...s};let v=[...a].sort(([e],[t])=>e-t),y=v.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),b=v.length===0?void 0:{...n,deliveryMetadata:y.length===0?void 0:y,payloads:v.map(([,e])=>e)};return{..._,kind:`continue`,remainder:b}}function joinTurnDeliveryIds(e,t){if(t.length===0)return e;let n=e[TurnDeliveryIdsKey.name]??[];return{...e,[TurnDeliveryIdsKey.name]:[...new Set([...n,...t])]}}async function mapHeldInputResponsesStep(e){"use step";return await withSessionStateDelta(e,async()=>{let t=new Set(e.requestIds),n=await deliverChannelInputResponses({...e,routable:e=>t.has(e.requestId)});return n.delivery===e.delivery?{delivery:void 0}:{delivery:n.delivery,serializedContext:n.serializedContext}})}async function deliverChannelInputResponses(e){let{routable:t}=e;if(!e.delivery.payloads.some(e=>e.inputResponses?.some(e=>!t(e))===!0))return e;let n=await deserializeContext(e.serializedContext),r=n.require(ChannelKey);if(r.deliver===void 0)return e;e.delivery.auth!==void 0&&n.set(AuthKey,e.delivery.auth??null);let i=r.state??{},a=!1,o=[];for(let s of e.delivery.payloads){if(s.inputResponses===void 0){o.push(s);continue}let e=[];for(let o of s.inputResponses){if(t(o)){e.push(o);continue}let c=buildAdapterContext({...r,state:structuredClone(i)},n),l=(await r.deliver({...s,inputResponses:[o],message:void 0},c))?.inputResponses?.filter(t)??[];if(l.length===0){e.push(o);continue}a=!0,i=c.state,e.push(...l)}o.push({...s,inputResponses:e})}if(!a)return e;let s=await deserializeContext(e.serializedContext);return setChannelContext(s,{...r,state:i}),{delivery:{...e.delivery,payloads:o},serializedContext:serializeContext(s)}}export{mapHeldInputResponsesStep,routeProxiedDeliverStep};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { type ChannelAdapterContext } from "#channel/adapter.js";
|
|
2
2
|
import { type ContextContainer } from "#context/container.js";
|
|
3
3
|
import { type DurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
|
|
4
|
-
import type { HarnessTurnRef } from "#harness/emission-state.js";
|
|
5
4
|
import { type HarnessModelMessage } from "#harness/messages.js";
|
|
6
5
|
import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";
|
|
7
6
|
import { type MessageStreamEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
7
|
+
import { type SessionProjection } from "#protocol/session-projection.js";
|
|
8
8
|
/**
|
|
9
9
|
* Whose event a session publishes. Every event reaches the channel adapter, the
|
|
10
10
|
* session stream, and stream-event hooks. The session's own events also reach
|
|
@@ -128,6 +128,8 @@ export declare function openSessionEventPublisher(input: {
|
|
|
128
128
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
129
129
|
readonly inputSource?: string;
|
|
130
130
|
}): SessionEventPublisher;
|
|
131
|
+
/** The session's projection as of the last event it published. */
|
|
132
|
+
export declare function readSessionProjection(ctx: ContextContainer): SessionProjection;
|
|
131
133
|
type TerminalSessionEvent = Extract<UnstampedMessageStreamEvent, {
|
|
132
134
|
type: "session.completed" | "session.failed";
|
|
133
135
|
}>;
|
|
@@ -147,7 +149,10 @@ export declare function publishTerminalSessionEvent(input: {
|
|
|
147
149
|
readonly serializedContext: Record<string, unknown>;
|
|
148
150
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
149
151
|
/** The session's last turn, for channel handlers' `ctx.session.turn`. */
|
|
150
|
-
readonly turn?:
|
|
152
|
+
readonly turn?: {
|
|
153
|
+
readonly id: string;
|
|
154
|
+
readonly sequence: number;
|
|
155
|
+
};
|
|
151
156
|
/** The turn the event ends, for instrumentation. */
|
|
152
157
|
readonly turnId?: string;
|
|
153
158
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{
|
|
1
|
+
import"#protocol/session-projection.js";import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{currentProjection,enterSessionProjection,recordPublishedEvent,saveSessionProjection}from"#harness/session-machine/current.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{dropClosedRecords}from"#harness/session-machine/commit.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{forwardSessionInput}from"#execution/forward-session-input.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.publish-session-events`);async function publishSessionEvents(e,t){return await publishEventsFromStep(e,`own`,t)}async function relaySessionEvents(e,t){return await publishEventsFromStep(e,`relayed`,t)}async function publishEventsFromStep(e,t,n){if(n.length===0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let{published:r}=await publishFromSessionStep(await restoreSessionStep(e),{origin:t,async publish(e){for(let t of n)await e(t)}});return r}async function restoreSessionStep(e){return{ctx:await deserializeContext(e.serializedContext),durableSession:readDurableSession(e.sessionState),sessionWritable:e.sessionWritable}}async function publishFromSessionStep(e,t){let{ctx:n}=e,r=await publishInSessionScope(e,t),i=t.updateSession?.(r.session,r.result)??{session:r.session},a=readSessionProjection(n),o=reconcileSessionContinuationToken(n,saveSessionProjection(dropClosedRecords(i.session,a),n));return{published:{serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:o}),...`history`in o&&{history:o.history}},result:i.result}}async function publishInSessionScope(e,t){let{ctx:n}=e;enterSessionProjection(n,e.durableSession.state);let r=resolveEffectiveAgentRuntime(n.require(BundleKey),n),i=hydrateDurableSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},durable:e.durableSession,turnAgent:r.turnAgent}),a=e.history===void 0?i:{...i,history:validateHarnessModelMessages(e.history)},o=t.origin===`own`?bindSessionInstrumentation({agentName:r.turnAgent.id,ctx:n,rootSessionId:a.rootSessionId??a.sessionId,sessionId:a.sessionId}):void 0,s=openSessionEventPublisher({ctx:n,inputSource:t.inputSource,origin:t.origin,sessionWritable:e.sessionWritable});try{return await withContextScope(n,a,async e=>{let r=o?.createHandleEvent({handleEvent:s.publish,turnId:activeTurnId(turnPosition(readSessionProjection(n)))})??s.publish;return{result:await t.publish(r,e),session:e}})}finally{await o?.flush(),s.writer.release()}}function openSessionEventPublisher(e){let{ctx:t,origin:n}=e,r=createSessionEventDispatcher(e),i=openSessionEventWriter({deliveryIds:()=>n===`own`?t.get(TurnDeliveryIdsKey):void 0,sessionWritable:e.sessionWritable}),emit=async e=>{let n=await i.write(await r.deliver(e));return recordPublishedEvent(t,n),n};return{dispatcher:r,writer:i,emit,async publish(e){await r.runHooks(await emit(e))}}}function createSessionEventDispatcher(e){let{ctx:t,inputSource:n}=e,r=t.require(ChannelKey),i=buildAdapterContext(r,t);return{adapterCtx:i,async deliver(e){let a=await forwardSessionInput(t,e,n)?e:await callAdapterEventHandler(r,e,n===void 0?i:{...i,inputSource:n});return setChannelContext(t,{...r,state:{...i.state}}),a},async runHooks(e,n){await dispatchStreamEventHooks({cancelTurn:n,ctx:t,event:e,registry:t.require(BundleKey).hookRegistry})}}}function openSessionEventWriter(e){let t=e.sessionWritable.getWriter(),n=!1,release=()=>{n||(n=!0,t.releaseLock())};return{async write(n){let r=stampMessageStreamEvent(n,e.deliveryIds());return await t.write(encodeMessageStreamEvent(r)),r},close:async()=>{await t.close(),release()},release}}function readSessionProjection(e){return currentProjection(e)}async function publishTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n={errorId:e.errorId,sessionId:t},{type:r}=e.event,i,a;try{i=await deserializeContext(e.serializedContext),enterSessionProjection(i,void 0),a=openSessionEventPublisher({ctx:i,origin:`own`,sessionWritable:e.sessionWritable})}catch(t){log.error(`failed to restore context for terminal ${r} event`,{...n,error:t}),await writeUnroutedSessionEvent(e.sessionWritable,e.event).catch(e=>log.error(`failed to write terminal ${r} event`,{...n,error:e}));return}let o=i.get(AuthKey)??null;i.setVirtualContext(SessionKey,{auth:{current:o,initiator:i.get(InitiatorAuthKey)??o},parent:i.get(ParentSessionKey),sessionId:t,turn:e.turn??{id:`turn_0`,sequence:0}});let publish=async e=>{await a.emit(e),await a.writer.close()},s;try{s=bindSessionInstrumentation({agentName:i.require(BundleKey).turnAgent.id,ctx:i,rootSessionId:i.get(ParentSessionKey)?.rootSessionId??t,sessionId:t})}catch(e){log.error(`failed to bind instrumentation for terminal ${r} event`,{...n,error:e})}let c=s?.createHandleEvent({handleEvent:publish,turnId:e.turnId})??publish;try{await contextStorage.run(i,()=>c(e.event))}catch(e){log.error(`failed to publish terminal ${r} event`,{...n,error:e})}finally{a.writer.release();try{await s?.flush()}catch(e){log.error(`failed to flush instrumentation after terminal ${r} event`,{...n,error:e})}}}async function writeUnroutedSessionEvent(e,t){let n=openSessionEventWriter({deliveryIds:()=>void 0,sessionWritable:e});try{await n.write(t),await n.close()}finally{n.release()}}export{openSessionEventPublisher,publishFromSessionStep,publishSessionEvents,publishTerminalSessionEvent,readSessionProjection,relaySessionEvents,restoreSessionStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{coalesceDeliveries}from"#harness/messages.js";import{activeTurnId}from"#harness/
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{activeTurnId,storedProjection,turnPosition}from"#harness/session-machine/view.js";import{readDurableSession}from"#execution/durable-session-read.js";import{mapHeldInputResponsesStep}from"#execution/proxied-deliver-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{isSteeringDelivery,isSteeringMessage}from"#execution/session/input-queue.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";var ActiveTurn=class{admitted=new Set;routedToChildren=new Set;mappedForHeldRequest=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;identity;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;caller;compacted=!1;constructor(e,t){this.input=e,this.caller=t.caller,this.identity={callerCallId:t.caller?.callId,principal:t.principal},this.expectedTurnId=activeTurnId(turnPosition(storedProjection(readDurableSession(e.cursor.sessionState).state))),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(e){let t=[];for(;;){let n=this.input.queue.takeSteering(this.admitted,this.identity,e);if(n===void 0)break;for(let e of n.sequences)this.admitted.delete(e);let r=await routeSelectedDelivery(n,this.input.cursor);if(r.kind===`cancel-turn`){this.abort();break}r.kind===`turn`&&t.push(r.delivery)}if(this.resetSteering(),t.length===0)return;let n=t.length===1?t[0]:coalesceDeliveries(t);return n.caller!==void 0&&(this.caller=n.caller),n}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.`);if(await this.admit(i))return{kind:`input`}}}async takeInputResponses(e){for(let t of this.admitted){let n=this.input.queue.delivery(t);if(n===void 0)continue;let r=n.payloads.flatMap(e=>e.inputResponses??[]);if(r.length===0)continue;if(!r.some(t=>e.has(t.requestId))){if(this.mappedForHeldRequest.has(t))continue;this.mappedForHeldRequest.add(t);let r=n,i=await this.input.cursor.advance(t=>mapHeldInputResponsesStep({delivery:r,requestIds:[...e],...t}));if(i.delivery===void 0)continue;n=i.delivery}this.admitted.delete(t);let i=isSteeringDelivery(n,this.identity,{heldOnPerson:!0})?void 0:splitAnswers(n);return this.input.queue.replaceDelivery(t,i?.rest),i?.answers??n}}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`:return this.admitted.add(t.admission.sequence),!0;case`runtime-action-result`:return this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results}),!1;case`workflow`:return this.runtimeResults.push({kind:`workflow`,message:t.message}),!1;case`cancel`:return this.cancelsThisTurn(e)&&this.abort(),!1;case`consumed`:return e.kind===`authorization-callback`}}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}function splitAnswers(e){let t=e.payloads.flatMap(e=>e.inputResponses===void 0?[]:[{inputResponses:e.inputResponses}]),n=e.payloads.flatMap(e=>{let{inputResponses:t,...n}=e;return Object.keys(n).length===0?[]:[n]});return{answers:{...e,payloads:t},rest:n.length===0?void 0:{...e,payloads:n}}}export{ActiveTurn};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{openInputs}from"#protocol/session-projection.js";import{storedProjection}from"#harness/session-machine/view.js";function attributeAnswers(e){let{stepInput:t}=e,n=t?.inputResponses??[];if(t===void 0||t.message!==void 0||n.length===0)return;let r=new Map(openInputs(storedProjection(e.state)).flatMap(e=>e.taskId===void 0&&e.callId===void 0?[[e.request.requestId,e.request.kind]]:[]));if(!n.every(e=>r.has(e.requestId)))return;let i=n.filter(e=>r.get(e.requestId)===`tool-approval`),a=n.filter(e=>r.get(e.requestId)!==`tool-approval`),{inputResponses:o,...s}=t,c={...s,attributedInputResponses:[...t.attributedInputResponses??[],...i.map(t=>({auth:e.responder,response:t}))]};return a.length===0?c:{...c,inputResponses:a}}export{attributeAnswers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";const MIN_SESSION_CHECKPOINT_VERSION=8,CHECKPOINT_UPGRADES={8:e=>{let{mode:t,...n}=e;return{...n,serializedContext:omitKeys(readRecord(n,`serializedContext`),[`eve.mode`])}},9:(e,t)=>{let n=readRecord(e,`sessionState`),r=readRecord(n,`snapshot`),{taskId:i,...a}=readRecord(r,`session`);return{...e,serializedContext:upgradeLegacyCaller(omitKeys(readRecord(e,`serializedContext`),[`eve.activityObserver`,`eve.activityPendingBlockers`,`eve.activityRootTurnId`,`eve.connectionSearchResults`,`eve.internal.backgroundToolExecution`,`eve.runtime.taskDeliveryPolicy`,`eve.turnTaskDelivery`])),sessionState:{...n,snapshot:{...r,session:{...a,history:readArray(a,`history`).map(renameBackgroundTaskMessage),state:upgradeSessionState(a.state,t)}}}}},10:e=>{let t=readRecord(e,`sessionState`),n=readRecord(t,`snapshot`),{history:r,...i}=readRecord(n,`session`);return t.version!==1&&refuse(`durable session version is not 1`),Array.isArray(r)||refuse(`session history is missing`),{...e,history:r,sessionState:{...t,snapshot:{...n,session:i},version:2}}}};function migrateSessionCheckpoint(e){if(!isObject(e))return{kind:`incompatible`,detail:`checkpoint is not an object`};let{version:t}=e;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<8||t>SESSION_CHECKPOINT_VERSION)return{kind:`incompatible`,detail:`checkpoint version ${JSON.stringify(t)} is outside the supported range 8-${SESSION_CHECKPOINT_VERSION}`};let n={childRunIdsToStop:[]},r=e;try{for(let e=t;e<SESSION_CHECKPOINT_VERSION;e++){let t=CHECKPOINT_UPGRADES[e];t===void 0&&refuse(`no upgrade from checkpoint version ${e}`),r={...t(r,n),version:e+1}}}catch(e){if(!(e instanceof CheckpointRefusal))throw e;return{kind:`incompatible`,detail:`checkpoint version ${t}: ${e.message}`}}return isCurrentCheckpoint(r)?{kind:`current`,checkpoint:r,childRunIdsToStop:n.childRunIdsToStop}:{kind:`incompatible`,detail:`checkpoint version ${t} is incomplete`}}function isCurrentCheckpoint(e){return isObject(e)&&e.version===SESSION_CHECKPOINT_VERSION&&Array.isArray(e.history)&&isObject(e.serializedContext)&&isObject(e.sessionState)}var CheckpointRefusal=class extends Error{};function refuse(e){throw new CheckpointRefusal(e)}function readRecord(e,t){let n=e[t];return isObject(n)||refuse(`${t} is not an object`),n}function readArray(e,t){let n=e[t];return Array.isArray(n)||refuse(`${t} is not an array`),n}function omitKeys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}function upgradeLegacyCaller(e){let t=e[`eve.sessionCallback`];if(!isObject(t))return e;let{taskId:n,...r}=t;return{...e,"eve.legacyRemoteAgentCaller":typeof n==`string`&&n.length>0?{taskId:n}:{},"eve.sessionCallback":r}}function renameBackgroundTaskMessage(e){return isObject(e)&&e.role===`user`&&e.kind===`execution.background_task`?{...e,kind:`task.result`}:e}function upgradeSessionState(e,t){return isObject(e)?omitKeys(e,[...dropSettledWorkflowToolRuns(e),...stopIdleSubagents(e,t)]):e}function dropSettledWorkflowToolRuns(e){let t=e[`eve.workflowTool`];if(!isObject(t)||t.version!==3)return[];let n=t.runs;return(!Array.isArray(n)||!n.every(e=>isObject(e)&&e.lifetime===`session`&&isObject(e.task)&&e.task.outcome!==void 0))&&refuse(`workflow tool run registry version 3 holds unsettled runs`),[`eve.workflowTool`]}function stopIdleSubagents(e,t){let n=e[`eve.agent.handles`];if(n===void 0)return[];(!isObject(n)||!Array.isArray(n.handles))&&refuse(`subagent handles are malformed`);for(let e of n.handles){(!isObject(e)||e.phase!==`parked`&&e.phase!==`available`)&&refuse(`a subagent session is still working`);let n=e.address;isObject(n)&&(n.kind===`agent/local`||n.kind===`agent/self`)&&typeof n.sessionId==`string`&&n.sessionId.length>0&&t.childRunIdsToStop.push(n.sessionId)}return[`eve.agent.handles`]}export{MIN_SESSION_CHECKPOINT_VERSION,migrateSessionCheckpoint};
|
|
1
|
+
import{initialSessionProjection}from"#protocol/session-projection.js";import{isObject}from"#shared/guards.js";import{getBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";const MIN_SESSION_CHECKPOINT_VERSION=8,CHECKPOINT_UPGRADES={8:e=>{let{mode:t,...n}=e;return{...n,serializedContext:omitKeys(readRecord(n,`serializedContext`),[`eve.mode`])}},9:(e,t)=>{let n=readRecord(e,`sessionState`),r=readRecord(n,`snapshot`),{taskId:i,...a}=readRecord(r,`session`);return{...e,serializedContext:upgradeLegacyCaller(omitKeys(readRecord(e,`serializedContext`),[`eve.activityObserver`,`eve.activityPendingBlockers`,`eve.activityRootTurnId`,`eve.connectionSearchResults`,`eve.internal.backgroundToolExecution`,`eve.runtime.taskDeliveryPolicy`,`eve.turnTaskDelivery`])),sessionState:{...n,snapshot:{...r,session:{...a,history:readArray(a,`history`).map(renameBackgroundTaskMessage),state:upgradeSessionState(a.state,t)}}}}},10:e=>{let t=readRecord(e,`sessionState`),n=readRecord(t,`snapshot`),{history:r,...i}=readRecord(n,`session`);return t.version!==1&&refuse(`durable session version is not 1`),Array.isArray(r)||refuse(`session history is missing`),{...e,history:r,sessionState:{...t,snapshot:{...n,session:i},version:2}}},11:upgradeIdleLifecycle};function migrateSessionCheckpoint(e){if(!isObject(e))return{kind:`incompatible`,detail:`checkpoint is not an object`};let{version:t}=e;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<8||t>SESSION_CHECKPOINT_VERSION)return{kind:`incompatible`,detail:`checkpoint version ${JSON.stringify(t)} is outside the supported range 8-${SESSION_CHECKPOINT_VERSION}`};let n={childRunIdsToStop:[]},r=e;try{for(let e=t;e<SESSION_CHECKPOINT_VERSION;e++){let t=CHECKPOINT_UPGRADES[e];t===void 0&&refuse(`no upgrade from checkpoint version ${e}`),r={...t(r,n),version:e+1}}}catch(e){if(!(e instanceof CheckpointRefusal))throw e;return{kind:`incompatible`,detail:`checkpoint version ${t}: ${e.message}`}}return isCurrentCheckpoint(r)?{kind:`current`,checkpoint:r,childRunIdsToStop:n.childRunIdsToStop}:{kind:`incompatible`,detail:`checkpoint version ${t} is incomplete`}}function upgradeIdleLifecycle(e){let t=readRecord(e,`sessionState`);t.version!==2&&refuse(`durable session version is not 2`);let n=readRecord(t,`snapshot`),r=readRecord(n,`session`),i=r.state===void 0?{}:readRecord(r,`state`),a=i[`eve.harness.emission`]??t.emissionState;(!isObject(a)||typeof a.sessionStarted!=`boolean`||!Number.isSafeInteger(a.sequence)||a.sequence<0||!Number.isSafeInteger(a.stepIndex)||a.stepIndex<0||a.turnId!==``)&&refuse(`lifecycle position is malformed or a turn is still open`),[`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>i[e]!==void 0)&&refuse(`session holds pending work`);let o=i[`eve.runtime.pendingInputBatches`];o!==void 0&&(!Array.isArray(o)||o.length>0)&&refuse(`session holds pending input`);let s=i[`eve.runtime.proxyInputRequests`];(t.hasProxyInputRequests!==!1||s!==void 0&&(!isObject(s)||Object.keys(s).length>0))&&refuse(`session holds relayed input`);try{getBlockingWorkflowToolRuns(i).length>0&&refuse(`session holds workflow runs`)}catch(e){if(e instanceof CheckpointRefusal)throw e;refuse(`workflow tool run registry is incompatible`)}let c=i[`eve.runtime.hitl.approvalState`];c!==void 0&&(!isObject(c)||!isObject(c.activeCandidates)||Object.keys(c.activeCandidates).length>0)&&refuse(`session holds approval candidates or malformed approval state`);let l=i[`eve.runtime.hitl.approvedTools`]??[];(!Array.isArray(l)||!l.every(e=>typeof e==`string`))&&refuse(`approval grants are malformed`),(i[`eve.harness.turnState`]!==void 0||i[`eve.harness.sessionProjection`]!==void 0)&&refuse(`v11 checkpoint already contains machine state`);let u={...initialSessionProjection(),nextSequence:a.sequence};a.sessionStarted&&(u.started=!0);let d={...omitKeys(i,[`eve.harness.emission`,`eve.runtime.hitl.approvedTools`,`eve.runtime.pendingInputBatches`,`eve.runtime.proxyInputRequests`]),"eve.harness.sessionProjection":u};l.length>0&&(d[`eve.harness.turnState`]={grants:[...l],suspended:[]});let{emissionState:f,...p}=t;return{...e,sessionState:{...p,snapshot:{...n,session:{...r,state:d}}}}}function isCurrentCheckpoint(e){return isObject(e)&&e.version===SESSION_CHECKPOINT_VERSION&&Array.isArray(e.history)&&isObject(e.serializedContext)&&isObject(e.sessionState)}var CheckpointRefusal=class extends Error{};function refuse(e){throw new CheckpointRefusal(e)}function readRecord(e,t){let n=e[t];return isObject(n)||refuse(`${t} is not an object`),n}function readArray(e,t){let n=e[t];return Array.isArray(n)||refuse(`${t} is not an array`),n}function omitKeys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}function upgradeLegacyCaller(e){let t=e[`eve.sessionCallback`];if(!isObject(t))return e;let{taskId:n,...r}=t;return{...e,"eve.legacyRemoteAgentCaller":typeof n==`string`&&n.length>0?{taskId:n}:{},"eve.sessionCallback":r}}function renameBackgroundTaskMessage(e){return isObject(e)&&e.role===`user`&&e.kind===`execution.background_task`?{...e,kind:`task.result`}:e}function upgradeSessionState(e,t){return isObject(e)?omitKeys(e,[...dropSettledWorkflowToolRuns(e),...stopIdleSubagents(e,t)]):e}function dropSettledWorkflowToolRuns(e){let t=e[`eve.workflowTool`];if(!isObject(t)||t.version!==3)return[];let n=t.runs;return(!Array.isArray(n)||!n.every(e=>isObject(e)&&e.lifetime===`session`&&isObject(e.task)&&e.task.outcome!==void 0))&&refuse(`workflow tool run registry version 3 holds unsettled runs`),[`eve.workflowTool`]}function stopIdleSubagents(e,t){let n=e[`eve.agent.handles`];if(n===void 0)return[];(!isObject(n)||!Array.isArray(n.handles))&&refuse(`subagent handles are malformed`);for(let e of n.handles){(!isObject(e)||e.phase!==`parked`&&e.phase!==`available`)&&refuse(`a subagent session is still working`);let n=e.address;isObject(n)&&(n.kind===`agent/local`||n.kind===`agent/self`)&&typeof n.sessionId==`string`&&n.sessionId.length>0&&t.childRunIdsToStop.push(n.sessionId)}return[`eve.agent.handles`]}export{MIN_SESSION_CHECKPOINT_VERSION,migrateSessionCheckpoint};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{liveTaskRuns,readTaskTable}from"#execution/tasks/table.js";import{getSessionUsage,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.js";import{liveTaskRuns,readTaskTable}from"#execution/tasks/table.js";import{getSessionUsage,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&liveTaskRuns(readTaskTable(r.snapshot?.session?.state)).length>0&&await terminateChildSessionsStep({sessionState:r});let i=r?.snapshot.session,a=i===void 0?void 0:getSessionUsage(i);e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n,turn:lastPublishedTurn(i?.state),usage:a}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId,usage:a});let o=settledResult(e,t);if(t.caller!==void 0){let e={output:o.output,usage:o.turnUsage};o.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:o.isError,output:o.output,usage:o.sessionUsage,usageDelta:o.turnUsage}}function settledResult(e,t){let n=t.cursor.sessionState?.snapshot.session,r=n===void 0||t.caller===void 0?{}:{sessionUsage:getSessionUsage(n),turnUsage:takeSessionUsageDelta(n).delta};switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return t.caller===void 0?{isError:!1,output:``}:{isError:!0,output:`The session ended before the delegated task completed.`,...r};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error),...r}}}function lastPublishedTurn(e){let t=Object.values(storedProjection(e).turns).reduce((e,t)=>e===void 0||t.sequence>e.sequence?t:e,void 0);return t===void 0?void 0:{id:t.turnId,sequence:t.sequence}}export{finalizeSession};
|
|
@@ -2,7 +2,9 @@ import type { SessionCheckpointMigration } from "#execution/session/checkpoint-m
|
|
|
2
2
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
3
|
import { type SessionOwnerActivation } from "#execution/session/handoff.js";
|
|
4
4
|
/** Parses retained work with this deployment's code before deciding whether it can move. */
|
|
5
|
-
export declare function isSessionStateIdleForHandoff(
|
|
5
|
+
export declare function isSessionStateIdleForHandoff(input: {
|
|
6
|
+
readonly sessionState: DurableSessionState;
|
|
7
|
+
}): boolean;
|
|
6
8
|
/** Reads durable work using the source deployment's handoff contract. */
|
|
7
9
|
export declare function isSessionIdleForHandoffStep(input: {
|
|
8
10
|
readonly sessionState: DurableSessionState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{walkCauseChain}from"#shared/errors.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getResolvedRuntimeAgentNode}from"#runtime/graph.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{IncompatibleStateLayoutError,deserializeContext}from"#context/serialize.js";import{EntityConflictError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{cancelRun,getWorld,resumeHook}from"#internal/workflow/runtime.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";const log=createLogger(`execution.handoff`);function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e),n=getBlockingWorkflowToolRuns(t);if([`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>t?.[e]!==void 0))return!1;let r=t?.[`eve.runtime.pendingInputBatches`];if(r!==void 0&&(!Array.isArray(r)||r.length>0))return!1;let i=t?.[`eve.runtime.proxyInputRequests`];
|
|
1
|
+
import{openInputs,openSignIns}from"#protocol/session-projection.js";import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{walkCauseChain}from"#shared/errors.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{queuedInput,storedProjection}from"#harness/session-machine/view.js";import{getResolvedRuntimeAgentNode}from"#runtime/graph.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{IncompatibleStateLayoutError,deserializeContext}from"#context/serialize.js";import{EntityConflictError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{cancelRun,getWorld,resumeHook}from"#internal/workflow/runtime.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";const log=createLogger(`execution.handoff`);function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e.sessionState),n=getBlockingWorkflowToolRuns(t);if([`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>t?.[e]!==void 0))return!1;let r=t?.[`eve.runtime.pendingInputBatches`];if(r!==void 0&&(!Array.isArray(r)||r.length>0))return!1;let i=t?.[`eve.runtime.proxyInputRequests`];if(i!==void 0&&(!isObject(i)||Object.keys(i).length>0))return!1;let a=storedProjection(t);return n.length===0&&a.activeTurnId===void 0&&openInputs(a).length===0&&openSignIns(a).length===0&&queuedInput(t)===void 0}async function isSessionIdleForHandoffStep(e){"use step";return isSessionStateIdleForHandoff(e)}async function validateSessionCheckpointStep(e){"use step";let{migration:t}=e,unreadable=t=>(log.warn(`session handoff refused: this deployment cannot read the checkpoint`,{detail:t,readableCheckpointVersion:SESSION_CHECKPOINT_VERSION,sessionId:e.sessionId}),{kind:`incompatible`,reason:`checkpoint-version`});if(t.kind===`incompatible`)return unreadable(t.detail);let{checkpoint:n}=t,r=n.sessionTimeoutMs;if(r!==!1&&(typeof r!=`number`||!Number.isFinite(r)||r<0))throw Error(`Session checkpoint contains an invalid timeout duration.`);let i;try{i=await deserializeContext(n.serializedContext)}catch(e){if(e instanceof IncompatibleStateLayoutError)return unreadable(e.message);throw e}let a=i.require(BundleKey),o=readDurableSession(n.sessionState).sandboxState?.session;if(o!=null&&o.providerName!==void 0){let e=getResolvedRuntimeAgentNode(a.graph,a.nodeId).sandboxRegistry.sandbox.inheritance?.definition??getResolvedRuntimeAgentNode(a.graph,a.nodeId).sandboxRegistry.sandbox.definition;if(e.kind!==`independent`)throw Error(`Session checkpoint sandbox has no resolved provider.`);let t=getSandboxEnvironmentRuntime(e.environment);if(o.providerName!==t.providerName||o.stateProtocolVersion!==t.stateProtocolVersion)throw Error(`Session checkpoint sandbox provider state is incompatible.`)}if(!isSessionStateIdleForHandoff(n))throw Error(`Session checkpoint contains pending work and cannot be handed off.`);return{kind:`valid`}}async function stopUntrackedChildSessionsStep(e){"use step";let t=await getWorld();for(let n of e.runIds)if(n!==e.sessionId)try{await cancelRun(t,n,{cancelReason:`Session upgraded`})}catch(t){[...walkCauseChain(t)].some(e=>EntityConflictError.is(e)||RunExpiredError.is(e)||WorkflowRunNotFoundError.is(e))||logError(log,`could not stop a subagent session after handoff`,t,{childRunId:n,sessionId:e.sessionId})}}async function reportSessionHandoffRetainedStep(e){"use step";log.warn(`session handoff failed; the current owner keeps the session`,{...e,checkpointVersion:SESSION_CHECKPOINT_VERSION})}async function signalSessionOwnerActivationStep(e){"use step";await resumeHook(e.token,e.activation)}async function signalSessionAnchorStep(e){"use step";await resumeHook(e.token,e.result)}export{isSessionIdleForHandoffStep,isSessionStateIdleForHandoff,reportSessionHandoffRetainedStep,signalSessionAnchorStep,signalSessionOwnerActivationStep,stopUntrackedChildSessionsStep,validateSessionCheckpointStep};
|
|
@@ -13,7 +13,7 @@ import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.
|
|
|
13
13
|
* A newer successor must always accept older checkpoints: every bump adds the
|
|
14
14
|
* upgrade from the previous version in `checkpoint-migrations.ts`.
|
|
15
15
|
*/
|
|
16
|
-
export declare const SESSION_CHECKPOINT_VERSION =
|
|
16
|
+
export declare const SESSION_CHECKPOINT_VERSION = 12;
|
|
17
17
|
/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
|
|
18
18
|
export interface SessionCheckpoint {
|
|
19
19
|
readonly version: typeof SESSION_CHECKPOINT_VERSION;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{sessionHandoffMarkerToken}from"#execution/session-inbox/address.js";import{startSessionOwnerStep}from"#execution/workflow-runtime.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook}from"#execution/hook-ownership.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{isSessionIdleForHandoffStep,reportSessionHandoffRetainedStep}from"#execution/session/handoff-steps.js";import{readAcceptedDeploymentId}from"#execution/session/accepted-deployment.js";const SESSION_CHECKPOINT_VERSION=
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{sessionHandoffMarkerToken}from"#execution/session-inbox/address.js";import{startSessionOwnerStep}from"#execution/workflow-runtime.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook}from"#execution/hook-ownership.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{isSessionIdleForHandoffStep,reportSessionHandoffRetainedStep}from"#execution/session/handoff-steps.js";import{readAcceptedDeploymentId}from"#execution/session/accepted-deployment.js";const SESSION_CHECKPOINT_VERSION=12;function sessionAnchorToken(e){return`${e}:anchor`}var SessionHandoff=class{input;anchor;incompatibleTargetDeploymentIds=new Set;constructor(e){this.input=e}async tryTransfer(e,t,n={}){let{delivery:r}=e,i=readAcceptedDeploymentId(r);return(i===void 0||i===this.input.deploymentId)&&n.compaction!==void 0?e.handoffEligible?await this.tryCompactionTransfer(t,{...n.compaction,delivery:r}):{kind:`retained`,reason:`busy`}:i===void 0?{kind:`retained`,reason:`missing-deployment`}:i===this.input.deploymentId?{kind:`retained`,reason:`same-deployment`}:this.incompatibleTargetDeploymentIds.has(i)?{kind:`retained`,reason:`known-incompatible`}:e.handoffEligible?await this.transfer(t,i,{delivery:r}):{kind:`retained`,reason:`busy`}}async tryCompactionTransfer(e,t){let{deploymentId:n}=this.input;return this.incompatibleTargetDeploymentIds.has(n)?{kind:`retained`,reason:`known-incompatible`}:await this.transfer(e,n,{...t,reason:`compaction`})}async transfer(e,t,n){let{inbox:r}=this.input;if(!await isSessionIdleForHandoffStep({sessionState:e.sessionState}))return{kind:`retained`,reason:`not-idle`};let i={...this.input.checkpoint,...e,version:12},a=sessionHookTokens(e);await this.ensureAnchor();let o=a.map(e=>createHook({token:sessionHandoffMarkerToken(e)}));await Promise.all(o.map(e=>claimHookOwnership(e)));let s;try{let e=await r.release();if(e.length>0)return await this.recover(a,e),{kind:`retained`,reason:`accepted-during-release`};let o=[];try{let e=await this.startAndActivate(i,n,t);if(e.kind===`active`)return{kind:`transferred`};o=e.payloads,e.kind===`incompatible`?(this.incompatibleTargetDeploymentIds.add(t),s={reason:`checkpoint-incompatible`}):s={error:e.error,reason:`activation-failed`}}catch(e){s={error:e,reason:`activation-failed`}}await this.recover(a,o)}finally{await Promise.all(o.map(e=>disposeHook(e)))}return await this.reportRetained(s.reason,t,s.error),{kind:`retained`,reason:s.reason}}async awaitAnchoredResult(){if(this.anchor===void 0)throw Error(`Session anchor was never claimed.`);try{return await this.anchor}finally{await this.disposeAnchor()}}async disposeAnchor(){if(this.anchor===void 0)return;let e=this.anchor;this.anchor=void 0,await disposeHook(e)}async startAndActivate(e,t,n){let r=createHook({token:`${getWorkflowMetadata().workflowRunId}:handoff`});await claimHookOwnership(r);try{return await startSessionOwnerStep({...t,activationToken:r.token,anchorRunId:this.input.sessionId,checkpoint:e,targetDeploymentId:n}),await r}finally{await disposeHook(r)}}async recover(e,t){await this.input.inbox.claimSessionHooks(e),this.input.inbox.restore(t)}async reportRetained(e,t,n){let r=isObject(n)&&typeof n.message==`string`?n.message:void 0;await reportSessionHandoffRetainedStep({error:r,reason:e,sessionId:this.input.sessionId,sourceDeploymentId:this.input.deploymentId,targetDeploymentId:t})}async ensureAnchor(){this.input.isInitialOwner&&this.anchor===void 0&&(this.anchor=createHook({token:sessionAnchorToken(this.input.sessionId)}),await claimHookOwnership(this.anchor))}};export{SESSION_CHECKPOINT_VERSION,SessionHandoff,sessionAnchorToken};
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TaskToolCall } from "#execution/tasks/calls.js";
|
|
2
2
|
import type { HarnessSession } from "#harness/types.js";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
import { type SessionProjection } from "#protocol/session-projection.js";
|
|
4
|
+
/**
|
|
5
|
+
* Derives the workflow fields used to select the next action at the park boundary. Whether the
|
|
6
|
+
* session awaits input or a sign-in is the projection's; which callbacks resume it, and which
|
|
7
|
+
* calls wait on the runtime, is execution state.
|
|
8
|
+
*/
|
|
9
|
+
export declare function derivePendingState(session: HarnessSession, projection: SessionProjection): {
|
|
5
10
|
readonly authorizationAttemptIds?: readonly string[];
|
|
6
11
|
readonly hasPendingAuthorization: boolean;
|
|
7
12
|
readonly hasPendingInputBatch: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{openSignIns}from"#protocol/session-projection.js";import{runtimeWait}from"#harness/session-machine/view.js";import{sessionView}from"#harness/session-machine/commit.js";import{ownOpenRequestIds}from"#harness/session-machine/transitions.js";import{getPendingAuthorization}from"#harness/authorization.js";function derivePendingState(e,t){let n={authorizationAttemptIds:getPendingAuthorization(e.state)?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),hasPendingAuthorization:openSignIns(t).length>0,hasPendingInputBatch:ownOpenRequestIds(sessionView(t,e.state)).size>0},r=runtimeWait(e.state);return r===void 0?n:{...n,hasRunsToDispatch:r.tasks.length>0,pendingCoordinationCallIds:r.callIds,pendingTaskToolCalls:r.taskToolCalls}}export{derivePendingState};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type SessionStepState } from "#execution/publish-session-events.js";
|
|
2
|
+
import { type ExecutionInstrumentation } from "#instrumentation/runtime.js";
|
|
3
|
+
/** The step output preserves the start time when the workflow resumes in another worker. */
|
|
4
|
+
export declare function startTaskToolCallsStep(): Promise<number>;
|
|
5
|
+
export declare function traceTaskToolCallStep(target: SessionStepState, call: Parameters<ExecutionInstrumentation["instrumentTaskToolCall"]>[0]): Promise<Omit<import("#execution/publish-session-events.js").PublishedSessionEvents, keyof import("#execution/session/state-delta.js").SessionStateValues> & import("#execution/session/state-delta.js").SessionStateTransition>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{publishFromSessionStep,restoreSessionStep}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";async function startTaskToolCallsStep(){"use step";return Date.now()}async function traceTaskToolCallStep(e,t){"use step";return await withSessionStateDelta(e,async e=>{let n=await restoreSessionStep(e),{published:r}=await publishFromSessionStep(n,{origin:`own`,async publish(e,r){await bindSessionInstrumentation({ctx:n.ctx,agentName:resolveEffectiveAgentRuntime(n.ctx.require(BundleKey),n.ctx).turnAgent.id,rootSessionId:r.rootSessionId??r.sessionId,sessionId:r.sessionId})?.instrumentTaskToolCall(t)}});return r})}export{startTaskToolCallsStep,traceTaskToolCallStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{createDurableSessionValues}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{createDurableSessionValues}from"#execution/durable-session-store.js";import{sessionView}from"#harness/session-machine/commit.js";import{ownOpenRequestIds}from"#harness/session-machine/transitions.js";import{derivePendingState}from"#execution/session/pending-turn-state.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=storedProjection(e.session.state),r=derivePendingState(e.session,t);return{action:`held`,authorizationAttemptIds:r.authorizationAttemptIds??[],hasPendingInputBatch:r.hasPendingInputBatch,hold:`request`,inputRequestIds:[...ownOpenRequestIds(sessionView(t,e.session.state))],...n}}if(e.next===null){let{hasRunsToDispatch:r,pendingCoordinationCallIds:i,pendingTaskToolCalls:a}=derivePendingState(e.session,storedProjection(e.session.state)),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};
|
|
@@ -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{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{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.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{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.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{attributeAnswers}from"#execution/session/answer-caller.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),f=a.has(InitiatorAuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=n===void 0?u?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;p!==void 0&&a.set(AuthKey,p);let m={...hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),history:validateHarnessModelMessages(e.history)},h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.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,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:y}=v.dispatcher,b=new AbortController,x=e.abortSignal===void 0?b.signal:AbortSignal.any([e.abortSignal,b.signal]);try{let l=bindDynamicConnections(a,s.resolvedAgent),p={...s.graph.root,turnAgent:c.turnAgent},S=!1,C=createTurnEventHandler({abortSignal:x,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:b,ctx:a,dynamicConnections:l,effectiveAgent:c,effectiveNode:p,instrumentation:g,publisher:v}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(S=!0),await C(e,t)},w=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,T;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}T=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let E=n?.auth===void 0?void 0:attributeAnswers({responder:n.auth,state:i.state,stepInput:T});if(E!==void 0&&(T=E,d===void 0?a.delete(AuthKey):a.set(AuthKey,d),f||a.delete(InitiatorAuthKey)),n!==void 0&&T===void 0&&!isHarnessBetweenTurns(m))d===void 0?a.delete(AuthKey):a.set(AuthKey,d),y.state=w;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.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),T={...T,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&T===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t),serializedContext:n,...r}}let D=s.subagentRegistry.dynamicResolvers??[],O=s.resolvedAgent.dynamicToolResolvers??[],k=buildRuntimeIdentity(p);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:D,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}))]),isHarnessBetweenTurns(m)||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:O})}}catch(e){throw await failChannelDeliveries(e),e}let A=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,j=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:x,capabilities:j,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>l.dispatch(createTurnStartedEvent(e)),historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:p})(r,n)},M,N;try{throwIfTurnAborted(x),N=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:T,initialSession:m,modelCallsPerStep:A,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,handleEvent),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&T?.outputSchema!==void 0?{...t,outputSchema:T.outputSchema}:t,i=getHarnessEmissionState(r.state);if(await l.rehydrate(i,k,isHarnessBetweenTurns(r)?void 0:{sequence:i.sequence,turnId:activeTurnId(i)}),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,h.messages(r)),prepareMemoryPreamble(a,{history:r.history,input:t,projector:h.projector,state:r.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(handleEvent,{},e,h.projector({messages:[...r.history,...t],state:r.state}),k,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 handleEvent(createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(r,n)});return r.settledTurn===void 0&&throwIfTurnAborted(x),M={result:r,serializedContext:serializeContext(a)},r}})}catch(t){if(!isTurnCancellation(t)&&!x.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:M,ctx:a,initialSession:m,stepInput:T})}let P=reconcileSessionContinuationToken(a,N.session);agentTraceState.pruneAgentTraceState(a,P.sessionId,P.state);let F=serializeContext(a);N={...N,session:P};let I=resolveSessionStepResult(N,F);return I.action===`done`&&await v.writer.close(),S?{...I,compacted:!0}:I}finally{v.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{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,isBetweenTurns,turnPosition}from"#harness/session-machine/view.js";import{currentProjection,enterSessionProjection,saveSessionProjection}from"#harness/session-machine/current.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{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{dropClosedRecords}from"#harness/session-machine/commit.js";import{sessionStartedForResolvers,turnStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.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{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{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.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);enterSessionProjection(a,i.state);let 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),f=a.has(InitiatorAuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=n===void 0?u?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;p!==void 0&&a.set(AuthKey,p);let m={...hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),history:validateHarnessModelMessages(e.history)},h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=turnPosition(currentProjection(a)),v=isBetweenTurns(currentProjection(a));if(!_.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,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},y=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:b}=y.dispatcher,x=new AbortController,S=e.abortSignal===void 0?x.signal:AbortSignal.any([e.abortSignal,x.signal]);try{let l=bindDynamicConnections(a,s.resolvedAgent),p={...s.graph.root,turnAgent:c.turnAgent},C=!1,w=createTurnEventHandler({abortSignal:S,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:x,ctx:a,dynamicConnections:l,effectiveAgent:c,effectiveNode:p,instrumentation:g,publisher:y}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(C=!0),await w(e,t)},T=n!==void 0&&!v?structuredClone(b.state):void 0,E;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,b):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}E=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let D=n?.auth===void 0?void 0:attributeAnswers({responder:n.auth,state:i.state,stepInput:E});if(D!==void 0&&(E=D,d===void 0?a.delete(AuthKey):a.set(AuthKey,d),f||a.delete(InitiatorAuthKey)),n!==void 0&&E===void 0&&!v)d===void 0?a.delete(AuthKey):a.set(AuthKey,d),b.state=T;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.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),E={...E,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{...b.state}};setChannelContext(a,e)}if(n!==void 0&&E===void 0&&v){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=saveSessionProjection(reconcileSessionContinuationToken(a,m),a),n=serializeContext(a),r=t===m?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t,currentProjection(a)),serializedContext:n,...r}}let O=s.subagentRegistry.dynamicResolvers??[],k=s.resolvedAgent.dynamicToolResolvers??[],A=buildRuntimeIdentity(p);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=sessionStartedForResolvers(A);await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:k,event:e,messages:h.initial.messages,runtimeRevision:t}))]),v||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:turnStartedForResolvers({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:k})}}catch(e){throw await failChannelDeliveries(e),e}let j=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,M=a.get(CapabilitiesKey),runHarnessStep=async(t,n,r)=>{let i=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:S,capabilities:M,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>l.dispatch(turnStartedForResolvers(e)),signInCompletions:r,historyProjector:h.projector,historyView:h.prepare(i),instrumentation:g,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:p})(i,n)},N,P;try{throwIfTurnAborted(S),P=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:E,initialSession:m,modelCallsPerStep:j,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,handleEvent),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&E?.outputSchema!==void 0?{...t,outputSchema:E.outputSchema}:t,i=turnPosition(currentProjection(a));await l.rehydrate(i,A,isBetweenTurns(currentProjection(a))?void 0:{sequence:i.sequence,turnId:activeTurnId(i)});let o=e&&u!==void 0?u.map(({challenge:e})=>e):void 0;return runHarnessStep(r,n,o)});r.settledTurn===void 0&&throwIfTurnAborted(S);let i={...r,session:saveSessionProjection(r.session,a)};return N={result:i,serializedContext:serializeContext(a)},i}})}catch(t){if(!isTurnCancellation(t)&&!S.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:N,ctx:a,initialSession:m,stepInput:E})}let F=saveSessionProjection(dropClosedRecords(reconcileSessionContinuationToken(a,P.session),currentProjection(a)),a);agentTraceState.pruneAgentTraceState(a,F.sessionId,F.state);let I=serializeContext(a);P={...P,session:F};let L=resolveSessionStepResult(P,I);return L.action===`done`&&await y.writer.close(),C?{...L,compacted:!0}:L}finally{y.writer.release()}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.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";import{sessionView}from"#harness/session-machine/commit.js";import{hold}from"#harness/session-machine/transitions.js";async function publishTurnWaitingStep(e){"use step";return await withSessionStateDelta(e,async e=>{let t=readDurableSession(e.sessionState),n=sessionView(storedProjection(t.state),t.state),{events:r}=hold(n,{on:`tasks`});return r.length===0?{serializedContext:e.serializedContext,sessionState:e.sessionState}:await publishSessionEvents(e,r)})}export{publishTurnWaitingStep};
|
|
@@ -76,6 +76,7 @@ export declare class SessionExecution {
|
|
|
76
76
|
* deferred calls.
|
|
77
77
|
*/
|
|
78
78
|
private answerTaskToolCalls;
|
|
79
|
+
private traceTaskWait;
|
|
79
80
|
/** Aborts the `abortSignal` of every workflow tool call the wait has no result for yet. */
|
|
80
81
|
private interruptWaitedWorkflowCalls;
|
|
81
82
|
}
|
|
@@ -1 +1 @@
|
|
|
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{
|
|
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{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{taskToolResult}from"#execution/tasks/calls.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";import{startTaskToolCallsStep,traceTaskToolCallStep}from"#execution/session/task-tool-tracing-step.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`),{...t,...n.caller!==void 0&&{caller:n.caller},...n.compacted&&{compacted:!0}}}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}));a.compacted===!0&&(e.compacted=!0);let 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({serializedContext:e.serializedContext,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=await 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);try{for(;;){a=await 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))}}finally{for(let e of a)await this.traceTaskWait(e,void 0,!0)}}async 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);await this.traceTaskWait(a,o,t),n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[],r=e.length===0?0:await startTaskToolCallsStep();for(let i of e)if(i.kind===`task_wait`)n.push(startTaskWait(i,r));else{let e;try{e=await answerTaskCancel(this.input.cursor,i)}catch(e){throw await this.input.cursor.advance(e=>traceTaskToolCallStep(e,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},failed:!0})),e}await this.input.cursor.advance(t=>traceTaskToolCallStep(t,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},output:e.output})),t(e)}let i=await this.resolveTaskWaits(n,!1,t);return i.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),i}async traceTaskWait(e,t,n=!1){await this.input.cursor.advance(r=>traceTaskToolCallStep(r,{callId:e.callId,toolName:`task_wait`,startedAtMs:e.startedAtMs,completedAtMs:Date.now(),input:e.input,output:t,failed:n}))}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,t){let{callId:n,timeoutMs:r}=e,i=r===void 0?void 0:sleep(r).then(()=>n);return{callId:n,startedAtMs:t,input:r===void 0?{}:{timeoutSeconds:r/1e3},timedOut:r===0,timer:i}}function mayWaitOnWorkflowToolRuns(e){try{return getBlockingWorkflowToolRuns(e.snapshot?.session?.state).length>0}catch{return!0}}export{SessionExecution,hasDelegatedCallerContext};
|
|
@@ -10,7 +10,7 @@ export interface CancelledTurnSettleResult {
|
|
|
10
10
|
/** What the session spent since its caller's last report, when asked to report it. */
|
|
11
11
|
readonly usage?: TokenUsage;
|
|
12
12
|
}
|
|
13
|
-
/** Takes the history because the
|
|
13
|
+
/** Takes the history because the steps the cancel stopped commit to it. */
|
|
14
14
|
interface CancelledTurnSettleInput extends SessionHistoryStepState {
|
|
15
15
|
/**
|
|
16
16
|
* Whether a caller receives the turn's usage. Only then is it marked
|
|
@@ -19,11 +19,9 @@ interface CancelledTurnSettleInput extends SessionHistoryStepState {
|
|
|
19
19
|
readonly reportUsage: boolean;
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
|
-
* Settles one cancelled turn
|
|
23
|
-
* session
|
|
24
|
-
*
|
|
25
|
-
* owner, whose wake sources exclude the cancel hook, so a queued cancel wake
|
|
26
|
-
* cannot re-dispatch it.
|
|
22
|
+
* Settles one cancelled turn through the machine's `cancel`, and persists
|
|
23
|
+
* the between-turns session. Runs in the owner, whose wake sources exclude the
|
|
24
|
+
* cancel hook, so a queued cancel wake cannot re-dispatch it.
|
|
27
25
|
*/
|
|
28
26
|
export declare function settleCancelledTurnStep(input: CancelledTurnSettleInput): Promise<WithSessionStateDelta<CancelledTurnSettleResult>>;
|
|
29
27
|
/** {@link settleCancelledTurnStep} for a caller that is already a step and adopts the whole state. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{runtimeWait,storedProjection}from"#harness/session-machine/view.js";import{currentProjection}from"#harness/session-machine/current.js";import{getTurnUsageState,takeSessionUsageDelta}from"#harness/turn-tag-state.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{applyTransition,sessionView}from"#harness/session-machine/commit.js";import{cancel}from"#harness/session-machine/transitions.js";import{retireCancelledCandidates}from"#harness/hitl/index.js";async function settleCancelledTurnStep(e){"use step";return await withSessionStateDelta(e,settleCancelledTurn)}async function settleCancelledTurn(e){let t={...await restoreSessionStep(e),history:e.history},n=t.durableSession.state,r=runtimeWait(n)?.event.turnId??storedProjection(n).activeTurnId??``,{published:i,result:a}=await publishFromSessionStep(t,{origin:`own`,publish:(e,n)=>applyTransition(n,cancel(sessionView(currentProjection(t.ctx),n.state)),e),updateSession(t,n){let i=removeBlockingWorkflowToolRuns(retireCancelledCandidates({...n,outputSchema:void 0}),r);if(!e.reportUsage||getTurnUsageState(n.state)===void 0)return{session:i};let a=takeSessionUsageDelta(i);return{result:a.delta,session:a.session}}});return a===void 0?i:{...i,usage:a}}export{settleCancelledTurn,settleCancelledTurnStep};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";
|
|
2
2
|
import type { HarnessSessionBase } from "#harness/types.js";
|
|
3
|
-
import {
|
|
3
|
+
import type { TaskStartedStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";
|
|
5
5
|
type TaskDispatchInput = StartWorkflowTaskInput & {
|
|
6
6
|
readonly taskId: string;
|
|
7
7
|
};
|
|
8
|
-
/** The call's answer, and the
|
|
8
|
+
/** The call's answer, and the task start the dispatch step reports for it. */
|
|
9
9
|
interface TaskDispatchResult {
|
|
10
10
|
readonly result: RuntimeToolResultActionResult;
|
|
11
11
|
readonly session: HarnessSessionBase;
|
|
12
|
-
readonly started?: TaskStartedStreamEvent;
|
|
12
|
+
readonly started?: TaskStartedStreamEvent["data"];
|
|
13
13
|
}
|
|
14
14
|
/** The entry of a run that does a task's work. */
|
|
15
15
|
type TaskRunEntry = Extract<WorkflowToolRunEntry, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{TOO_MANY_TASKS_CODE,UNKNOWN_TASK_CODE}from"#protocol/task-tools.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{TOO_MANY_TASKS_CODE,UNKNOWN_TASK_CODE}from"#protocol/task-tools.js";import{renderTaskReceipt,renderTaskSentReceipt,renderTooManyTasksError,renderUnknownTaskError}from"#execution/tasks/render.js";import{MAX_WORKING_TASKS,findTask,isTaskAvailable,isTaskWorking,readTaskTable,recordTaskCall,recordTaskRun,removeTask,workingTasks,writeTaskTable}from"#execution/tasks/table.js";import{startFailureResult,startWorkflowToolCallRun}from"#execution/tools/workflow/start.js";import{sendTaskRunCommands}from"#execution/tasks/steps.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";const log=createLogger(`execution.tasks`);async function startTaskRun(e){let{entry:t,session:n,task:r}=e,{taskId:i}=t,a={...e,taskId:i},o=startReceipt(a,t.entryPoint===`serve`),s=readTaskTable(n.state),c=findTask(s,i);if(c===void 0||!isTaskWorking(c))return{result:o,session:n};let l=tooManyTasks(a,s);if(l!==void 0)return{result:l,session:writeTaskTable(n,removeTask(s,i))};let u;try{u=await startWorkflowToolCallRun(e,t)}catch(e){return logError(log,`task run failed to start`,e,{taskId:i,toolName:r.toolName}),{result:startFailureResult(r,e),session:writeTaskTable(n,removeTask(s,i))}}return{result:o,session:writeTaskTable(n,recordTaskRun(s,i,u)),started:taskStartedEvent(a,c)}}async function sendToTask(e){let{session:t,task:n,taskId:r}=e,i=readTaskTable(t.state),a=findTask(i,r);if(!isTaskAvailable(a,n.toolName))return{result:unknownTaskResult(e),session:t};if(!isTaskWorking(a)){let n=tooManyTasks(e,i);if(n!==void 0)return{result:n,session:t}}let o=recordTaskCall(i,r,{agentContext:e.agentContext,auth:e.auth,callId:n.callId,executeInput:n.executeInput,input:n.input,sequence:e.batchEvent.sequence,stepIndex:e.batchEvent.stepIndex,turnId:e.batchEvent.turnId});return o.send!==void 0&&await sendTaskRunCommands(o.send),{result:toolResult(e,renderTaskSentReceipt(r)),session:writeTaskTable(t,o.table),started:taskStartedEvent(e,a)}}function tooManyTasks(e,t){let n=workingTasks(t).filter(e=>e.run!==void 0);if(n.length<MAX_WORKING_TASKS)return;let r=n.map(e=>e.id);return createRuntimeToolResultFromValue({callId:e.task.callId,isError:!0,output:{code:TOO_MANY_TASKS_CODE,message:renderTooManyTasksError(MAX_WORKING_TASKS,r)},toolName:e.task.toolName})}function unknownTaskResult(e){return createRuntimeToolResultFromValue({callId:e.task.callId,isError:!0,output:{code:UNKNOWN_TASK_CODE,message:renderUnknownTaskError(e.taskId,e.task.toolName)},toolName:e.task.toolName})}function taskStartedEvent(e,t){return{callId:e.task.callId,kind:t.kind,name:e.task.toolName,taskId:e.taskId,turnId:e.batchEvent.turnId}}function startReceipt(e,t){return toolResult(e,renderTaskReceipt({id:e.taskId,resumable:t,tool:e.task.toolName}))}function toolResult(e,t){return createRuntimeToolResultFromValue({callId:e.task.callId,output:t,toolName:e.task.toolName})}export{sendToTask,startTaskRun};
|