eve 0.71.2 → 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 +47 -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/channel/conversation-context.d.ts +4 -1
- package/dist/src/channel/invoke-tool.d.ts +41 -0
- package/dist/src/channel/invoke-tool.js +1 -0
- package/dist/src/channel/routes.d.ts +3 -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/caller-scope.d.ts +7 -0
- package/dist/src/context/caller-scope.js +1 -0
- 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.d.ts +2 -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/invoke-tool.d.ts +35 -0
- package/dist/src/execution/invoke-tool.js +1 -0
- 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 +8 -0
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/sandbox/active-handles.d.ts +6 -0
- package/dist/src/execution/sandbox/active-handles.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/answer-caller.d.ts +15 -0
- package/dist/src/execution/session/answer-caller.js +1 -0
- 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 +7 -0
- 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/authorization-completion.js +1 -1
- package/dist/src/execution/tools/workflow/harness-definition.js +1 -1
- package/dist/src/execution/tools/workflow/step-execution.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-runtime.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 -64
- 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/{session-limit-continuation.d.ts → hitl/budget-request.d.ts} +3 -1
- package/dist/src/harness/hitl/budget-request.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} +13 -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/messages.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 +7 -3
- 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-call-io.d.ts +25 -0
- package/dist/src/harness/tool-call-io.js +1 -0
- package/dist/src/harness/tool-loop.d.ts +7 -22
- package/dist/src/harness/tool-loop.js +1 -3
- package/dist/src/harness/tool-model-output.d.ts +1 -2
- package/dist/src/harness/tools.d.ts +14 -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 -52
- 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/gateway.d.ts +2 -0
- package/dist/src/internal/gateway.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/internal/nitro/host/instrumentation-entry.js +2 -2
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/nitro/routes/route-invoke-tool.d.ts +24 -0
- package/dist/src/internal/nitro/routes/route-invoke-tool.js +1 -0
- 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/index.d.ts +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/channel.d.ts +1 -0
- 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/public/models/openai/chatgpt/model.js +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/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- 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 +3 -3
- package/dist/src/setup/scaffold/create/web-template.js +26 -8
- 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 +8 -1
- package/dist/src/tracing/agent-span-contract.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +16 -5
- 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-span-processor.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +8 -3
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/invoke-tool-span.d.ts +61 -0
- package/dist/src/tracing/invoke-tool-span.js +1 -0
- 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 +3 -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 +4 -2
- package/docs/reference/typescript-api.md +4 -2
- package/docs/tools/human-in-the-loop.md +8 -4
- package/docs/tools/workflows.mdx +4 -4
- package/package.json +13 -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/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 -26
- 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 -31
- 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-continuation.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 -25
- 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/{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
|
@@ -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};
|
|
@@ -2,7 +2,7 @@ import { type TaskRunCommands } from "#execution/tasks/table.js";
|
|
|
2
2
|
import { type SessionStepState } from "#execution/publish-session-events.js";
|
|
3
3
|
import { type SessionStateTransition } from "#execution/session/state-delta.js";
|
|
4
4
|
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
|
|
5
|
-
import {
|
|
5
|
+
import type { TaskCancelReason } from "#protocol/message.js";
|
|
6
6
|
/** The messages a task's run sends that change its record. */
|
|
7
7
|
export type TaskRunMessage = Extract<WorkflowToolRunMessage, {
|
|
8
8
|
readonly kind: "outcome" | "reply" | "started" | "usage";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.js";import{cancelTask,findTask,finishTaskRun,markTaskRunStarted,readTaskTable,recordTaskRunUsage,settleRemainingTaskCalls,settleTaskCalls,writeTaskTable}from"#execution/tasks/table.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.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{finishRun,settleTask}from"#harness/session-machine/transitions.js";import{getProxyInputRequests}from"#harness/proxy-input-requests.js";import{resumeHook}from"#internal/workflow/runtime.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{workflowToolRunFailureOutput}from"#execution/tools/workflow/owner-inbox.js";import{ignoreGoneTarget}from"#execution/tasks/workflow-target.js";async function applyTaskRunMessageStep(e){"use step";return await withSessionStateDelta(e,applyTaskRunMessage)}async function applyTaskRunMessage(e){let{message:t}=e,n=t.from.taskId,r=readDurableSession(e.sessionState);if(n===void 0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let i=readTaskTable(r.state),a=[],o=[];switch(t.kind){case`started`:{let e=markTaskRunStarted(i,n,t.from.runId);i=e.table,e.held!==void 0&&await sendTaskRunCommands(e.held);break}case`reply`:{({session:r,table:i}=countTaskRunUsage(r,i,n,t));let e={output:t.output,status:`completed`},o=findTask(i,n),s=settleTaskCalls(i,{callIds:t.callIds,outcome:e,taskId:n});i=s.table,a.push(...taskSettledEvents(r,o,s.settled,e));break}case`usage`:({session:r,table:i}=countTaskRunUsage(r,i,n,t));break;case`outcome`:{({session:r,table:i}=countTaskRunUsage(r,i,n,t));let e=toOutcome(t),s=findTask(i,n),c=settleRemainingTaskCalls(i,n,e);a.push(...taskSettledEvents(r,s,c.settled,e)),i=finishTaskRun(c.table,n,t.from.runId),o=finishRun(viewOf(r),{requestIds:runRequestIds(r,t.from.runId),taskId:n}).events;break}}let s=await relaySessionEvents({...e,sessionState:saveTable(e.sessionState,r,i)},o);return await publishSessionEvents({...e,...s},a)}async function cancelTasksStep(e){"use step";return await withSessionStateDelta(e,cancelTasks)}async function cancelTasks(e){let t=readDurableSession(e.sessionState),n=readTaskTable(t.state),r=[],i=viewOf(t),a=[],o={reason:e.reason,status:`cancelled`};for(let s of e.taskIds){let e=findTask(n,s),c=cancelTask(n,s);if(n=c.table,r.push(...taskSettledEvents(t,e,c.settled,o)),c.send!==void 0){if(e?.resumable===!1){let e=runRequestIds(t,c.send.run.runId);a.push(...finishRun(i,{requestIds:e,taskId:s}).events)}await sendTaskRunCommands(c.send)}}let s=await relaySessionEvents({...e,sessionState:saveTable(e.sessionState,t,n)},a);return await publishSessionEvents({...e,...s},r)}function taskSettledEvents(e,t,n,r){return t===void 0?[]:settleTask(viewOf(e),{calls:n,outcome:r,task:t}).events}async function sendTaskRunCommands(e){for(let t of e.commands)await ignoreGoneTarget(resumeHook(e.run.hookToken,toControlMessage(t)))}function toControlMessage(e){switch(e.kind){case`cancel`:return{kind:`cancel`,reason:`The task was cancelled.`};case`call`:return{call:e.call,kind:`call`}}}function toOutcome(e){switch(e.result.status){case`completed`:return{output:e.result.output,status:`completed`};case`failed`:return{error:failureMessage(e),status:`failed`};case`cancelled`:return{status:`cancelled`}}}function failureMessage(e){let t=workflowToolRunFailureOutput(e);if(typeof t==`string`)return t;let n=typeof t==`object`&&t?Reflect.get(t,`message`):void 0;return typeof n==`string`?n:JSON.stringify(t)}function countTaskRunUsage(e,t,n,r){let i=findTask(t,n)?.run;return r.usage===void 0||i?.runId!==r.from.runId?{session:e,table:t}:{session:countRunUsage(e,r.usage,i.usage),table:recordTaskRunUsage(t,n,r.usage)}}function runRequestIds(e,t){return[...getProxyInputRequests(e.state)].filter(([,e])=>e.runId===t).map(([e])=>e)}function viewOf(e){return sessionView(storedProjection(e.state),e.state)}function saveTable(e,t,n){return replaceDurableSessionSnapshot({session:writeTaskTable(t,n),state:e})}export{applyTaskRunMessageStep,cancelTasksStep,sendTaskRunCommands};
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
+
type HarnessTurnRef = {
|
|
2
|
+
readonly id: string;
|
|
3
|
+
readonly sequence: number;
|
|
4
|
+
};
|
|
1
5
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
2
6
|
/** Emits a terminal `session.completed` outside a turn. */
|
|
3
7
|
export declare function emitTerminalSessionCompletionStep(input: {
|
|
4
8
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
5
9
|
readonly serializedContext: Record<string, unknown>;
|
|
10
|
+
/** The session's last turn, reported to channel handlers as `ctx.session.turn`. */
|
|
11
|
+
readonly turn?: HarnessTurnRef;
|
|
6
12
|
readonly usage: TokenUsage | undefined;
|
|
7
13
|
}): Promise<void>;
|
|
14
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{publishTerminalSessionEvent}from"#execution/publish-session-events.js";import{sessionCompleted}from"#harness/session-machine/transitions.js";async function emitTerminalSessionCompletionStep(e){"use step";await publishTerminalSessionEvent({...e,event:sessionCompleted(e.usage)})}export{emitTerminalSessionCompletionStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{publishTerminalSessionEvent}from"#execution/publish-session-events.js";import{sessionFailed}from"#harness/session-machine/transitions.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let t=formatError(e.error),n=summarizeKnownError(e.error),r=t;if(n!==null){let e={...t,message:n.message,name:n.name,semanticErrorId:n.id};r=n.hint===void 0?e:{...e,hint:n.hint}}let i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i}),await publishTerminalSessionEvent({errorId:typeof r.errorId==`string`?r.errorId:void 0,event:sessionFailed({code:i,details:r,message:a,sessionId:o,usage:e.usage}),sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,turnId:e.turnId})}export{emitTerminalSessionFailureStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.72.0//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CONNECTION_EXECUTE_TOOL_NAME,findConnection,qualifiedToolName,readExecuteTarget,toolCallDisplayName}from"./connection-target.js";import{connectionExecuteApproval,releaseApprovalPin}from"./connection-approval.js";import{closestToolNames,rankConnectionTools}from"./connection-search-rank.js";import{createLogger}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{loadContext}from"#context/container.js";import{displayProperName}from"#shared/display-name.js";import{toErrorMessage}from"#shared/errors.js";import{defineJsonSchema}from"#tools/schema.js";import{defineDurableCallback}from"#tools/durable-callbacks.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{
|
|
1
|
+
import{CONNECTION_EXECUTE_TOOL_NAME,findConnection,qualifiedToolName,readExecuteTarget,toolCallDisplayName}from"./connection-target.js";import{connectionExecuteApproval,releaseApprovalPin}from"./connection-approval.js";import{closestToolNames,rankConnectionTools}from"./connection-search-rank.js";import{createLogger}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{loadContext}from"#context/container.js";import{displayProperName}from"#shared/display-name.js";import{toErrorMessage}from"#shared/errors.js";import{defineJsonSchema}from"#tools/schema.js";import{defineDurableCallback}from"#tools/durable-callbacks.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{frameworkTool}from"#tools/provided/framework-tool.js";import{isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{getAuthorizationResults}from"#harness/authorization.js";import{createAuthorizationExecution}from"#runtime/connections/scoped-authorization.js";import{reportNestedToolAction}from"#harness/nested-actions.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{connectionToolModelOutput,toConnectionToolResult}from"#runtime/connections/tool-result.js";import{renderToolSignature}from"#runtime/connections/tool-signature.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{defineTool}from"#tools/definition.js";const log=createLogger(`framework.connection-tools`),CONNECTION_SEARCH_TOOL_NAME=`connection_search`,CONNECTION_SEARCH_DESCRIPTION=[`Find tools in your connected services (MCP servers and OpenAPI APIs).`,`Returns each matching tool's connection, name, description, and TypeScript signature.`,"Omit `query` to list a connection's tools. Call a found tool with connection_execute.","Connections the user has not signed in to are listed under `unavailable` with `requiresSignIn`;","when the request needs one, search it again with `connection` and `signIn: true` to ask the user to sign in.",`Prefer connected services over web search or general knowledge when a request relates to them.`].join(` `),CONNECTION_EXECUTE_DESCRIPTION=[`Call one tool from a connected service and return its result.`,"Use the exact `connection` and `tool` names returned by connection_search,","and pass `input` matching the tool's signature."].join(` `),CONNECTION_SEARCH_INPUT_SCHEMA={type:`object`,properties:{query:{type:`string`,description:`Words describing the capability, such as 'list open issues'. Omit to list every tool.`},connection:{type:`string`,description:`Only search this connection.`},signIn:{type:`boolean`,description:"Ask the user to sign in to `connection` first, then search it. Requires `connection`. Use only for a connection listed with `requiresSignIn` that the request needs."},limit:{type:`integer`,minimum:1,maximum:50,description:`Maximum results. Defaults to 10.`},offset:{type:`integer`,minimum:0,description:`Results to skip, for paging.`}},additionalProperties:!1},CONNECTION_EXECUTE_INPUT_SCHEMA={type:`object`,properties:{connection:{type:`string`,description:`Connection name from connection_search.`},tool:{type:`string`,description:`Tool name from connection_search.`},input:{type:`object`,description:`Arguments matching the tool's signature. Defaults to {}.`}},required:[`connection`,`tool`],additionalProperties:!1};function resolveConnectionTools(){let e=loadContext().get(ConnectionRegistryKey);if(e===void 0)return null;let t=e.getConnections().map(t=>e.getConnectionApproval(t.connectionName)).filter(e=>e!==void 0);return{[CONNECTION_SEARCH_TOOL_NAME]:frameworkTool(defineTool({description:CONNECTION_SEARCH_DESCRIPTION,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:defineDurableCallback({callback:searchConnectionTools,closure:{}}),label:{start:defineDurableCallback({callback:connectionSearchLabel,closure:{}})}})),[CONNECTION_EXECUTE_TOOL_NAME]:frameworkTool(defineTool({description:CONNECTION_EXECUTE_DESCRIPTION,inputSchema:CONNECTION_EXECUTE_INPUT_SCHEMA,execute:defineDurableCallback({callback:executeConnectionTool,closure:{}}),label:{start:defineDurableCallback({callback:connectionToolLabel,closure:{}})},toModelOutput:defineDurableCallback({callback:(e,t)=>connectionToolModelOutput(t),closure:{}}),...connectionExecuteApproval(t)}))}}function connectionToolLabel(e,t){return toolCallDisplayName(CONNECTION_EXECUTE_TOOL_NAME,t)}function connectionSearchLabel(e,t){let n=isObject(t)?t.connection:void 0;return typeof n!=`string`||n===``?`Search connected tools`:isObject(t)&&t.signIn===!0?`Connect ${displayProperName(n)}`:`Search ${displayProperName(n)} tools`}async function searchConnectionTools(e,t){let n=isObject(t)?t:{},r=requireRegistry(),i=n.connection===void 0||n.connection===``?void 0:n.connection;if(n.signIn===!0&&i===void 0)throw Error("connection_search with signIn: true requires `connection`. Ask the user to sign in to one connection at a time.");let a=i===void 0?r.getConnections():[requireConnection(r,i)],o=createAuthorizationExecution();await completePendingAuthorizations(r,a,o);let s=[],c=[];for(let e of a){let t=await listConnectionTools(r,e,o,n.signIn===!0);if(`signIn`in t)return t.signIn;if(`unavailable`in t)s.push(t.unavailable);else for(let n of t.tools)c.push({connection:e,tool:n})}let l=s.filter(e=>e.terminal);if(a.length>0&&l.length===a.length)throw Error(l.map(e=>e.error).join(`
|
|
2
2
|
`));let u=rankConnectionTools(n.query??``,c),d=clampInteger(n.limit,1,50,10),f=clampInteger(n.offset,0,2**53-1,0),p={tools:u.slice(f,f+d).map(({connection:e,tool:t})=>({connection:e.connectionName,description:t.description,signature:renderToolSignature({inputSchema:t.inputSchema,name:t.name,outputSchema:t.outputSchema}),tool:t.name})),total:u.length};return s.length>0&&(p.unavailable=s.map(({terminal:e,...t})=>t)),p}async function listConnectionTools(e,t,n,r){let i=t.connectionName;try{return{tools:await e.getClient(i).getToolMetadata()}}catch(t){if(isConnectionAuthorizationRequiredError(t)){let a=await resolveInteractiveAuthorization(e,i);if(a!==void 0&&n.isJustAuthorized(a))return{unavailable:{connection:i,error:`Authorization failed for "${i}": the service rejected the token immediately after authorization.`,terminal:!0}};if(a===void 0){let e=`"${i}" requires authorization and cannot start interactive sign-in.`;if(r)throw Error(e);return{unavailable:{connection:i,error:e,terminal:!1}}}return r?{signIn:await n.handleError(t,a)}:{unavailable:{connection:i,error:`Sign-in required: the user has not signed in to "${i}", so its tools cannot be listed. If the request needs "${i}", call connection_search with connection "${i}" and signIn: true to ask the user to sign in.`,requiresSignIn:!0,terminal:!1}}}return log.warn(`failed to load connection tools`,{connection:i,error:t}),{unavailable:{connection:i,error:isConnectionAuthorizationFailedError(t)?`Authorization failed for "${i}": ${t.message}`:`Failed to load tools for "${i}": ${toErrorMessage(t)}`,terminal:!0}}}}function clampInteger(e,t,n,r){return typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.trunc(e)))}async function executeConnectionTool(e,t,n){let r=readExecuteTarget(t);if(r===void 0)throw Error("connection_execute requires string `connection` and `tool` values.");let i=requireRegistry(),a=requireConnection(i,r.connection);releaseApprovalPin(n.callId,a),assertPendingAuthorizationInstances(i,[a]);let o=await resolveInteractiveAuthorization(i,a.connectionName),s=createAuthorizationExecution();o!==void 0&&await s.complete(o);let c=i.getClient(a.connectionName),l;try{l=await c.getToolMetadata()}catch(e){return await s.handleError(e,o)}let u=l.find(e=>e.name===r.tool);if(u===void 0)throw Error(unknownToolMessage(a,r.tool,l));let d=await validToolInput(a,u,r.input),f=qualifiedToolName(r),p;try{p=await c.executeTool(u.name,d,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){if(isConnectionAuthorizationRequiredError(e))return await s.handleError(e,o);throw reportNestedToolAction(n.callId,{input:d,isError:!0,output:toErrorMessage(e),toolName:f}),e}let m=toConnectionToolResult(a.protocol,u,p);if(!m.ok)throw reportNestedToolAction(n.callId,{input:d,isError:!0,output:m.error,toolName:f}),Error(m.error);return reportNestedToolAction(n.callId,{input:d,output:m.value,toolName:f}),m.value}async function validToolInput(e,t,n){let r=await defineJsonSchema(t.inputSchema)[`~standard`].validate(n);if(r.issues===void 0)return r.value;let i=r.issues.map(e=>{let t=(e.path??[]).map(e=>String(typeof e==`object`?e.key:e)).join(`.`);return t.length>0?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(`Invalid input for "${t.name}" on connection "${e.connectionName}": ${i}. Signature: ${renderToolSignature({inputSchema:t.inputSchema,name:t.name,outputSchema:t.outputSchema})}`)}function unknownToolMessage(e,t,n){let r=closestToolNames(t,n,5),i=r.length>0?` Closest tools: ${r.join(`, `)}.`:` Use connection_search to find its tools.`;return`Connection "${e.connectionName}" has no tool named "${t}".${i}`}async function resolveInteractiveAuthorization(e,t){let n=findConnection(e,t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(r!==void 0&&supportsInteractiveAuthorization(r))return{scope:n.connectionName,instanceId:n.instanceId,connection:{url:n.url??``},authorization:r}}async function completePendingAuthorizations(e,t,n){assertPendingAuthorizationInstances(e,t);let r=getAuthorizationResults();for(let i of t){if(!r.some(e=>e.name===i.connectionName))continue;let t=await resolveInteractiveAuthorization(e,i.connectionName);t!==void 0&&await n.complete(t)}}function assertPendingAuthorizationInstances(e,t){let n=new Set(t.map(e=>e.connectionName));for(let t of getAuthorizationResults())if(t.instanceId!==void 0&&n.has(t.name)&&findConnection(e,t.name)?.instanceId!==t.instanceId)throw Error(`Authorization for "${t.name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`)}function requireRegistry(){let e=loadContext().get(ConnectionRegistryKey);if(e===void 0)throw Error(`This agent has no connections.`);return e}function requireConnection(e,t){let n=findConnection(e,t);if(n!==void 0)return n;let r=e.getConnectionNames();throw Error(r.length===0?`Connection "${t}" is not available. No connections are available right now.`:`Connection "${t}" is not available. Available connections: ${r.join(`, `)}.`)}export{CONNECTION_SEARCH_TOOL_NAME,resolveConnectionTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getStepMetadata,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{
|
|
1
|
+
import{getStepMetadata,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{consumeAuthorizationResult,getAuthorizationResults}from"#harness/authorization.js";import{getRun}from"#internal/workflow/runtime.js";import{completeScopedAuthorization}from"#runtime/connections/scoped-authorization.js";async function completeWorkflowStepAuthorization(e){let t=getAuthorizationResults().find(t=>t.name===e.scope&&t.instanceId===e.instanceId);if(t===void 0)return!1;let{stepId:n,attempt:r}=getStepMetadata(),i=`eve.authorization.${n}.${t.attemptId}`;if(r>1){let t=getRun(getWorkflowMetadata().workflowRunId).getReadable({namespace:i});try{if(await t.getTailIndex()>=0)return consumeAuthorizationResult(e.scope,e.instanceId),!0}finally{await t.cancel().catch(()=>{})}}if(!await completeScopedAuthorization(e))return!1;let a=getWritable({namespace:i}).getWriter();try{await a.write(!0)}finally{a.releaseLock()}return!0}export{completeWorkflowStepAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{UNSPECIFIED_INPUT_SCHEMA,toInputSchema,toOutputSchema}from"#tools/schema.js";import{workflowIdForHandling}from"#runtime/subagents/workflow-reference.js";import{withTaskIdInput}from"#execution/tasks/task-id-input.js";import{entryPointOf}from"#execution/tasks/tool-entry-point.js";function createWorkflowToolHarnessDefinition(e){return{...entryPointOf(e.definition)===`serve`?withTaskIdInput(e.definition):e.definition,execute:void 0,executeInput:e.executeInput,workflowId:e.workflowId}}function createPreparedWorkflowToolHarnessDefinition(e){let t=workflowIdForHandling(e.behavior?.handling);if(t===void 0)throw Error(`Prepared tool "${e.name}" is not backed by a workflow.`);return createWorkflowToolHarnessDefinition({definition:{behavior:e.behavior,description:e.description,inputSchema:toInputSchema(e.inputSchema)??UNSPECIFIED_INPUT_SCHEMA,name:e.name,outputSchema:toOutputSchema(e.outputSchema),rootOnly:e.rootOnly},workflowId:t})}export{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition};
|
|
1
|
+
import{UNSPECIFIED_INPUT_SCHEMA,toInputSchema,toOutputSchema}from"#tools/schema.js";import{workflowIdForHandling}from"#runtime/subagents/workflow-reference.js";import{withTaskIdInput}from"#execution/tasks/task-id-input.js";import{entryPointOf}from"#execution/tasks/tool-entry-point.js";function createWorkflowToolHarnessDefinition(e){return{...entryPointOf(e.definition)===`serve`?withTaskIdInput(e.definition):e.definition,execute:void 0,executeInput:e.executeInput,workflowId:e.workflowId}}function createPreparedWorkflowToolHarnessDefinition(e){let t=workflowIdForHandling(e.behavior?.handling);if(t===void 0)throw Error(`Prepared tool "${e.name}" is not backed by a workflow.`);return createWorkflowToolHarnessDefinition({definition:{frameworkTool:e.kind!==`authored-tool`||e.owner.kind===`framework`,behavior:e.behavior,description:e.description,inputSchema:toInputSchema(e.inputSchema)??UNSPECIFIED_INPUT_SCHEMA,name:e.name,outputSchema:toOutputSchema(e.outputSchema),rootOnly:e.rootOnly},workflowId:t})}export{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SessionIdKey,SessionKey}from"#context/keys.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{
|
|
1
|
+
import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SessionIdKey,SessionKey}from"#context/keys.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;return i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults),contextStorage.run(i,async()=>{let a=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization}),o={...buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}}),agent:()=>unavailableInStep(`ctx.agent()`,`Call ctx.agent() in the workflow body.`),ask:()=>unavailableInStep(`ctx.ask()`,`Call ctx.ask() in the workflow body.`),getToken:a.getToken,requireAuth:a.requireAuth};Object.defineProperty(o,"agents",{get:()=>unavailableInStep(`ctx.agents`,`Read ctx.agents in the workflow body and pass the required serializable metadata into the step.`)});let s;try{s=await a.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?o:e)))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}let c=i.get(PendingAuthorizationResultKey)??[],l=r.authorizationResults.filter(e=>!c.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(s)?{kind:`authorization-required`,signal:s,authorized:l}:{kind:`result`,output:s,authorized:l}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}function unavailableInStep(e,t){throw Object.assign(Error(`${e} is unavailable inside a "use step" function. ${t}`),{fatal:!0})}export{withWorkflowStepAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{runSignIn}from"#harness/session-machine/transitions.js";import{findWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";function workflowToolStep(e,t){return new Proxy(e,{apply(e,n,r){let i=findWorkflowContextArgument(r);return i===void 0?Reflect.apply(e,n,r):executeAuthorizedStep(t,n,r,i)}})}function findWorkflowContextArgument(e){for(let t of e){let e=findWorkflowToolRunContext(t);if(e!==void 0)return{ctx:t,run:e}}}async function executeAuthorizedStep(e,t,n,r){let{ctx:i,run:a}=r,o=[],s=new Map;for(;;){let r=createHook();try{let c;try{c=await invokeAuthorizedStep({args:n,authorizationResults:o,callbackToken:r.token,ctx:i,execute:e,receiver:t})}catch(e){throw i.abortSignal.aborted||await reportPendingAsFailed(a,i.abortSignal,s),e}if(await reconcileCompletedAuthorizations(a,i.abortSignal,s,o,c.authorized),c.kind===`result`)return await reportPendingAsFailed(a,i.abortSignal,s),c.output;await collectAuthorizationCallbacks({authorizationResults:o,callback:r,challenges:c.signal.challenges,ctx:i,pending:s,run:a})}finally{await disposeHook(r)}}}async function invokeAuthorizedStep(e){let{args:t,authorizationResults:n,callbackToken:r,ctx:i,execute:a,receiver:o}=e,s={callId:i.callId,toolName:i.toolName,session:i.session,abortSignal:i.abortSignal,baseUrl:getWorkflowMetadata().url,token:r,authorizationResults:n},c={args:t.map(e=>e===i?null:e),context:s,contextIndexes:t.flatMap((e,t)=>e===i?[t]:[])};return await a.call(o,c)}async function reconcileCompletedAuthorizations(e,t,n,r,i){let a=new Set(i);for(let r of a){let i=n.get(r);i!==void 0&&await reportAuthorization(e,t,i,`authorized`),n.delete(r)}for(let e=r.length-1;e>=0;e--){let t=r[e];t!==void 0&&a.has(t.attemptId)&&r.splice(e,1)}}async function collectAuthorizationCallbacks(e){let{authorizationResults:t,callback:n,challenges:r,ctx:i,pending:a,run:o}=e;for(let e of r){let r=requireAttemptId(e);a.set(r.attemptId,r),await reportAuthorization(o,i.abortSignal,r);try{let e=await waitForCallback(n,r,i.abortSignal);t.push({name:r.name,instanceId:r.instanceId,attemptId:r.attemptId,hookUrl:r.hookUrl,principal:r.principal,resume:r.resume,callback:e})}catch(e){throw i.abortSignal.aborted||await reportAuthorization(o,i.abortSignal,r,`failed`),e}}}function requireAttemptId(e){if(e.attemptId===void 0)throw Error(`Workflow authorization challenge "${e.name}" has no attempt id.`);return e}async function reportPendingAsFailed(e,t,n){for(let r of n.values())await reportAuthorization(e,t,r,`failed`)}async function reportAuthorization(e,t,n,r){let i=runSignIn(e.from,n,r),a=createHook();try{await withAbort(e.owner.send({kind:`request`,from:e.from,replyTo:a.token,request:{kind:`authorization-request`,event:{kind:`subagent-authorization-event`,callId:e.from.callId,childSessionId:e.from.runId,subagentName:e.from.toolName,event:i}}}),t),await withAbort(a,t)}finally{await disposeHook(a)}}async function waitForCallback(e,t,n){let r=e[Symbol.asyncIterator]();for(;;){let e=await withAbort(r.next(),n);if(e.done)throw Error(`Authorization callback closed before sign-in completed.`);let i=readCallback(e.value,t);if(i!==void 0)return i}}async function withAbort(e,t){let abort,n=new Promise((e,n)=>{abort=()=>n(t.reason??Error(`Workflow authorization cancelled.`)),t.addEventListener(`abort`,abort,{once:!0}),t.aborted&&abort()});try{return await Promise.race([e,n])}finally{t.removeEventListener(`abort`,abort)}}function readCallback(e,t){if(typeof e==`object`&&e&&`payloads`in e&&Array.isArray(e.payloads))for(let n of e.payloads){let e=n?.authorizationCallback;if(e?.attemptId!==t.attemptId||e?.connectionName!==t.name)continue;let r=e.callback;if(!(typeof r?.method!=`string`||typeof r.params!=`object`||r.params===null||Array.isArray(r.params))&&Object.values(r.params).every(e=>typeof e==`string`)&&(r.body===void 0||typeof r.body==`string`))return r}}export{workflowToolStep};
|
|
@@ -3,11 +3,10 @@ import { type SessionStateTransition } from "#execution/session/state-delta.js";
|
|
|
3
3
|
import { type ProxyInputRequest } from "#harness/proxy-input-requests.js";
|
|
4
4
|
/**
|
|
5
5
|
* Decides a run's request to withdraw a question. A question the session
|
|
6
|
-
* still offers is
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* decision.
|
|
6
|
+
* still offers is withdrawn, so channels stop offering it. One it no longer
|
|
7
|
+
* offers was already answered or withdrawn when its turn was cancelled. Either
|
|
8
|
+
* way the run hears `withdrawn`, after any answer the session sent it first, so
|
|
9
|
+
* the question resolves from the session's first decision.
|
|
11
10
|
*/
|
|
12
11
|
export declare function withdrawWorkflowToolRunQuestionStep(input: WithdrawQuestionInput): Promise<SessionStateTransition>;
|
|
13
12
|
type WithdrawQuestionInput = SessionStepState & {
|
|
@@ -17,15 +16,14 @@ type WithdrawQuestionInput = SessionStepState & {
|
|
|
17
16
|
};
|
|
18
17
|
/**
|
|
19
18
|
* Withdraws the requests a finished run left open: its own questions and those
|
|
20
|
-
* of the sessions it opened, which ended with it. Nobody can answer them now
|
|
21
|
-
* so each is relayed `cancelled`.
|
|
19
|
+
* of the sessions it opened, which ended with it. Nobody can answer them now.
|
|
22
20
|
*/
|
|
23
21
|
export declare function withdrawFinishedRunQuestionsStep(input: SessionStepState & {
|
|
24
22
|
readonly runId: string;
|
|
25
23
|
}): Promise<SessionStateTransition>;
|
|
26
24
|
/**
|
|
27
|
-
*
|
|
28
|
-
* that
|
|
25
|
+
* Withdraws the relayed requests `select` picks through the machine's `finishRun`, for a step
|
|
26
|
+
* that owns the session. Their routes drop with the save, once the projection shows them closed.
|
|
29
27
|
*/
|
|
30
28
|
export declare function relayWithdrawnRequests(input: SessionStepState, select: (requestId: string, route: ProxyInputRequest) => boolean): Promise<PublishedSessionEvents>;
|
|
31
29
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readDurableSession
|
|
1
|
+
import{storedProjection}from"#harness/session-machine/view.js";import{readDurableSession}from"#execution/durable-session-store.js";import{relaySessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{sessionView}from"#harness/session-machine/commit.js";import{finishRun}from"#harness/session-machine/transitions.js";import{getProxyInputRequests}from"#harness/proxy-input-requests.js";import{resumeHook}from"#internal/workflow/runtime.js";import{ignoreGoneTarget}from"#execution/tasks/workflow-target.js";async function withdrawWorkflowToolRunQuestionStep(e){"use step";return await withSessionStateDelta(e,withdrawWorkflowToolRunQuestion)}async function withdrawWorkflowToolRunQuestion(e){let t={kind:`withdrawn`,requestId:e.requestId};return await ignoreGoneTarget(resumeHook(e.control,t)),await relayWithdrawnRequests(e,(t,n)=>t===e.requestId&&n.workflowAsk!==void 0&&n.runId===e.runId)}async function withdrawFinishedRunQuestionsStep(e){"use step";return await withSessionStateDelta(e,e=>relayWithdrawnRequests(e,(t,n)=>n.runId===e.runId))}async function relayWithdrawnRequests(e,t){let n=readDurableSession(e.sessionState),r=[...getProxyInputRequests(n.state)].filter(([e,n])=>t(e,n)).map(([e])=>e),i=sessionView(storedProjection(n.state),n.state);return await relaySessionEvents(e,finishRun(i,{requestIds:r}).events)}export{relayWithdrawnRequests,withdrawFinishedRunQuestionsStep,withdrawWorkflowToolRunQuestionStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{serializeContext}from"#context/serialize.js";import{AcceptedSessionIdentityError,resolveSessionInbox,resumeSessionInbox}from"#execution/session-inbox/resume.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,getWorld,start}from"#internal/workflow/runtime.js";import{initializeSessionInstrumentation}from"#instrumentation/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{serializeContext}from"#context/serialize.js";import{AcceptedSessionIdentityError,resolveSessionInbox,resumeSessionInbox}from"#execution/session-inbox/resume.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,getWorld,start}from"#internal/workflow/runtime.js";import{initializeSessionInstrumentation}from"#instrumentation/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{readSessionEventStream,readSessionStreamTailIndex}from"#execution/session-event-stream.js";import{SESSION_HANDOFF_VERSION}from"#execution/session/entry-input.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";import{isAgentTraceContext}from"#tracing/agent-trace-context.js";import{SESSION_TIMEOUT_WORKFLOW_NAME,WORKFLOW_ENTRY_NAME,WORKFLOW_TOOL_RUN_WORKFLOW_NAME}from"#execution/stable-workflow-names.js";const EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},workflowToolRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_TOOL_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(t){let n=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),r=buildRunContext({bundle:n,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:t}),i=resolveEffectiveAgentRuntime(n,r);initializeSessionInstrumentation({agentName:i.turnAgent.id,ctx:r});let a=i.limits?.sessionTimeoutMs,o=n.resolvedAgent.config?.experimental?.workflow?.retention,s=serializeContext(r),c=readParentLineage(s),l={kind:`initial`,input:t.input,ownerDeploymentId:await resolveCurrentWorkflowDeploymentId(),serializedContext:s};t.limits!==void 0&&(l.limits=t.limits),t.continuationConflictCommand!==void 0&&(l.continuationConflictCommand=t.continuationConflictCommand),a!==void 0&&(l.sessionTimeoutMs=a),o!==void 0&&(l.retention=o);let u={...c.sessionId===void 0?buildSessionAttributes({serializedContext:s}):buildSubagentRootAttributes({identity:{nodeId:n.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:c.callId,parentSessionId:c.sessionId,parentTurnId:c.turnId,rootSessionId:c.rootSessionId??c.sessionId,serializedContext:s}),...t.externalInvocation===void 0?{}:buildInvocationAttributes(t.externalInvocation)},d;try{let e={allowReservedAttributes:!0,attributes:normalizeEveAttributes(u)};o!==void 0&&(e.experimental_retention=o),d=await startWorkflowOnDeployment(workflowEntryReference,[l],l.ownerDeploymentId,e)}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:t.continuationToken}),e}let f,getEvents=()=>(f??=readSessionEventStream(d.runId),f);return{get events(){return getEvents()},sessionId:d.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowSessionCommand(e)},async getEventStream(e,t){return readSessionEventStream(e,t?.startIndex)},async getStreamTailIndex(e){return await readSessionStreamTailIndex(e)},async resolveContinuation(e){try{return await resolveSessionInbox(e)}catch(t){if(HookNotFoundError.is(t))return;throw logError(log,`failed to resolve session by continuation token`,t,{continuationToken:e}),t}}}}async function startSessionOwnerStep(e){"use step";let{activationToken:t,anchorRunId:n,checkpoint:r,targetDeploymentId:i,...a}=e,o={...a,activationToken:t,checkpoint:r,handoffVersion:SESSION_HANDOFF_VERSION,kind:`handoff`,ownerDeploymentId:i,sessionWritable:getRun(n).getWritable(),sessionId:n};await startWorkflowOnDeployment(workflowEntryReference,[o],i,r.retention===void 0?void 0:{experimental_retention:r.retention})}async function dispatchWorkflowCommand(e,t){let n;try{let r=await resumeSessionInbox(e,t);n={runId:r.ownerRunId,sessionId:await r.sessionId}}catch(n){if(isInactiveCommandTarget(n)){if(t.kind===`send`&&typeof e!=`string`)try{let t=await getRun(e.sessionId).status;if(t===`pending`||t===`running`)return{status:`session_not_active`,retryable:!0}}catch(e){if(!isInactiveCommandTarget(e))throw e}return inactiveCommandResult(t)}throw logError(log,`failed to dispatch session command`,n,{command:t.kind,token:e}),n}if(t.kind===`reset`){let t=typeof e==`string`?e:sessionCommandHookToken(e.sessionId),r=new Set([sessionCommandHookToken(n.sessionId),t]);await Promise.all([...r].map(e=>waitForHookRelease(sessionInboxHookToken(e),n.runId)))}return activeCommandResult(t,n.sessionId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:e.kind===`send`&&e.delivery!==void 0?{sessionId:t,status:`accepted`,deliveryId:e.delivery.deliveryId}:{sessionId:t,status:`accepted`}}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function dispatchWorkflowSessionCommand(e){return await dispatchWorkflowCommand({sessionId:e.sessionId},e.command)}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand({sessionId:e.sessionId},t)}function isInactiveCommandTarget(e){if(e instanceof AcceptedSessionIdentityError)return!1;if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release inbox "${e}".`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowOnCurrentDeployment(e,t,n){return await startWorkflowOnDeployment(e,t,await resolveCurrentWorkflowDeploymentId(),n)}async function startWorkflowOnDeployment(e,t,n,r){return await withWorkflowStartContext(async()=>{if(n.length===0||n===`latest`)throw Error(`Workflow starts require an exact deployment id.`);return await start(e,t,{...r,deploymentId:n})})}async function resolveCurrentWorkflowDeploymentId(){let e=process.env.VERCEL_DEPLOYMENT_ID?.trim()||await(await getWorld()).getDeploymentId();if(e.length===0||e===`latest`)throw Error(`Workflow runtime could not resolve an exact deployment id.`);return e}async function withWorkflowStartContext(e){let t=context.active(),n=isAgentTraceContext(t)?trace.deleteSpan(t):t;return await context.with(n,e)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{createWorkflowRuntime,dispatchWorkflowSessionCommand,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startSessionOwnerStep,startWorkflowOnCurrentDeployment,waitForCommandHookOwner,workflowEntryReference,workflowToolRunWorkflowReference};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { TurnPosition } from "#harness/session-machine/view.js";
|
|
2
2
|
import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";
|
|
3
3
|
import type { RuntimeTraceContext } from "#protocol/message.js";
|
|
4
4
|
/** Prepares native tracing for workflow-owned preambles emitted outside the tool loop. */
|
|
5
5
|
export declare function prepareWorkflowPreambleTrace(input: {
|
|
6
|
-
readonly emissionState:
|
|
6
|
+
readonly emissionState: TurnPosition;
|
|
7
7
|
readonly instrumentation: ExecutionInstrumentation | undefined;
|
|
8
8
|
}): Promise<RuntimeTraceContext | undefined>;
|
|
@@ -139,10 +139,12 @@ export interface PendingAuthorizationState {
|
|
|
139
139
|
readonly challenges: readonly AuthorizationChallenge[];
|
|
140
140
|
}
|
|
141
141
|
export declare function setPendingAuthorization(sessionState: Record<string, unknown> | undefined, value: PendingAuthorizationState): Record<string, unknown>;
|
|
142
|
+
/** The pending sign-ins once `challenges` are asked for: each replaces the attempt it supersedes. */
|
|
143
|
+
export declare function withSignIns(previous: readonly AuthorizationChallenge[], challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
142
144
|
/** Keeps the last challenge for each sign-in and principal. */
|
|
143
145
|
export declare function resolveActiveAuthorizationChallenges(challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
144
|
-
/**
|
|
145
|
-
export declare function
|
|
146
|
+
/** The attempts in `previous` that `replacements` replace: the same sign-in and principal. */
|
|
147
|
+
export declare function supersededChallenges(previous: readonly AuthorizationChallenge[], replacements: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
146
148
|
export declare function clearPendingAuthorization(sessionState: Record<string, unknown> | undefined, attemptIds?: readonly string[]): Record<string, unknown> | undefined;
|
|
147
149
|
export declare function getPendingAuthorization(sessionState: Record<string, unknown> | undefined): PendingAuthorizationState | undefined;
|
|
148
150
|
export declare function hasPendingAuthorization(sessionState: Record<string, unknown> | undefined): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(t&&t.length!==0)return e===void 0?t[0]:t.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,t){let n=loadContext(),r=n.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(n=>n.name===e&&n.instanceId===t);if(i===-1&&t!==void 0&&r.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return n.delete(PendingAuthorizationResultKey),o.length>0&&n.set(PendingAuthorizationResultKey,o),a}function getHookUrl(e,t){let n=loadContext(),r=n.get(SessionIdKey),i=n.get(CallbackBaseUrlKey),a=n.get(AuthorizationHookKey)??(r?authHookToken(r):void 0);if(a&&i)return createWorkflowCallbackUrl(i,createEveConnectionCallbackRoutePath(e,t,a))}function createAuthorizationAttempt(e){let t=createUlid(),n=getHookUrl(e,t);return n===void 0?void 0:{attemptId:t,hookUrl:n}}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return sessionInboxHookToken(sessionCommandHookToken(e))}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),AuthorizationHookKey=new ContextKey(`eve.authorizationHook`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){
|
|
1
|
+
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(t&&t.length!==0)return e===void 0?t[0]:t.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,t){let n=loadContext(),r=n.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(n=>n.name===e&&n.instanceId===t);if(i===-1&&t!==void 0&&r.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return n.delete(PendingAuthorizationResultKey),o.length>0&&n.set(PendingAuthorizationResultKey,o),a}function getHookUrl(e,t){let n=loadContext(),r=n.get(SessionIdKey),i=n.get(CallbackBaseUrlKey),a=n.get(AuthorizationHookKey)??(r?authHookToken(r):void 0);if(a&&i)return createWorkflowCallbackUrl(i,createEveConnectionCallbackRoutePath(e,t,a))}function createAuthorizationAttempt(e){let t=createUlid(),n=getHookUrl(e,t);return n===void 0?void 0:{attemptId:t,hookUrl:n}}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return sessionInboxHookToken(sessionCommandHookToken(e))}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),AuthorizationHookKey=new ContextKey(`eve.authorizationHook`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:withSignIns(getPendingAuthorization(e)?.challenges??[],t.challenges)}}}function withSignIns(e,t){let n=resolveActiveAuthorizationChallenges(t),r=supersededChallenges(e,n);return[...e.filter(e=>!r.includes(e)),...n]}function resolveActiveAuthorizationChallenges(e){return e.filter((t,n)=>!e.slice(n+1).some(e=>sameSignIn(t,e)))}function supersededChallenges(e,t){return e.filter(e=>t.some(t=>sameSignIn(e,t)))}function sameSignIn(e,t){let n=e.grant!==void 0&&e.grant===t.grant&&e.candidateId===t.candidateId;return(e.name===t.name||n)&&samePrincipal(e.principal,t.principal)}function samePrincipal(e,t){return e===void 0||t===void 0?e===t:e.type===`app`||t.type===`app`?e.type===t.type:e.id===t.id&&e.issuer===t.issuer}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(authorizationAttemptKey(e)));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function authorizationAttemptKey(e){return e.attemptId??e.candidateId??e.name}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(typeof t==`object`&&t)return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getAuthorizationResults,getHookUrl,getPendingAuthorization,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,requestAuthorization,resolveActiveAuthorizationChallenges,setPendingAuthorization,supersededChallenges,withSignIns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{generateText}from"ai";import{createFrameworkUserMessage,isFrameworkUserMessage}from"#harness/messages.js";import{
|
|
1
|
+
import{generateText}from"ai";import{createFrameworkUserMessage,isFrameworkUserMessage}from"#harness/messages.js";import{COMPACTION_CHECKPOINT_MARKER,COMPACTION_PROMPT_ENVELOPE,COMPACTION_RESUMPTION_MESSAGE,TRANSCRIPT_PAYLOAD_LIMIT,createCompactionPrompt,sliceUtf16Safe,stubContentOutputFileParts}from"#harness/compaction/prompt.js";import{estimateTokens}from"#harness/token-estimate.js";const COMPACTION_PROMPT_OVERHEAD_TOKENS=estimateTokens([{content:COMPACTION_PROMPT_ENVELOPE.system,role:`system`},createFrameworkUserMessage(`context.compaction`,COMPACTION_PROMPT_ENVELOPE.prompt)]);function getInputTokenCount(e,t,n=0,r=0){let i=t.lastKnownInputTokens,a=t.lastKnownPromptMessageCount;return i===void 0||a===void 0||!Number.isInteger(a)||a<0||a>e.length?estimateTokens(e)+n:i+estimateTokens(e.slice(a))+Math.max(0,n-r)}function shouldCompact(e,t,n=0,r=0){return e.length>0&&getInputTokenCount(e,t,n,r)+COMPACTION_PROMPT_OVERHEAD_TOKENS>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}const COMPACTION_HEURISTICS=[toolResultCapHeuristic];function toolResultCapHeuristic(e){let t=withResumptionGuard([...e.previousCheckpoint===void 0?[]:[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:e.previousCheckpoint,role:`assistant`}],...capToolResults(e.older),...e.recent],e.conversation,e.config.threshold);return evaluateThreshold(t,e.config,`should-compact`,e.tokenEstimateAdjustment).type===`within-limit`?{messages:t,type:`within-limit`}:{type:`insufficient`}}function evaluateThreshold(e,t,n,r=0){let i=n===`should-compact`?COMPACTION_PROMPT_OVERHEAD_TOKENS:0,a=estimateTokens(e)+i+r;return{estimatedTokens:a,type:a<=t.threshold?`within-limit`:`over-limit`}}async function compactMessages(e,t,n,r,i,a,o,s=!1,c){let{conversation:l,previousCheckpoint:u}=extractPreviousCheckpoint(e),d=selectRecentWindowSize(l,s?{...n,recentWindowSize:1}:n);if(!s){let{older:t,recent:r}=splitMessagesForCompaction(l,d);if(t.length===0&&u===void 0)return keepNonToolResultMessages(r);let i=Math.max(0,(c??getInputTokenCount(e,n))-estimateTokens(e));for(let e of COMPACTION_HEURISTICS){let a=e({config:n,conversation:l,older:t,previousCheckpoint:u,recent:r,tokenEstimateAdjustment:i});if(a.type===`within-limit`)return a.messages}}for(;;){let{older:e,recent:s}=splitMessagesForCompaction(l,d),c=createCompactionPrompt({messages:e,previousCheckpoint:u,transcriptBudgetTokens:n.threshold}),f=await generateText({abortSignal:o,headers:a,messages:[createFrameworkUserMessage(`context.compaction`,c.prompt)],model:t,providerOptions:r,system:c.system,telemetry:i?{...i,functionId:`eve.compaction`}:void 0});if(f.text.trim().length===0)throw Error(`The compaction model returned an empty summary. Finish reason: ${f.finishReason}.`);let p=[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:f.text,role:`assistant`}],m=withResumptionGuard([...p,...s],l,n.threshold);if(evaluateThreshold(m,n,`estimate`).type===`within-limit`)return m;let h=withResumptionGuard([...p,...keepNonToolResultMessages(s)],l,n.threshold);if(evaluateThreshold(h,n,`estimate`).type===`within-limit`||d===0)return h;--d}}function capToolResults(e){return e.map(e=>{if(e.role!==`tool`||typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-result`)return e;let n=stubContentOutputFileParts(e.output),r=JSON.stringify(n)??``;return r.length<=TRANSCRIPT_PAYLOAD_LIMIT?n===e.output?e:(t=!0,{...e,output:n}):(t=!0,{...e,output:{type:`text`,value:`[Truncated by eve: tool result reduced during context compaction. Re-run the tool if you need the full output.]\n\n${sliceUtf16Safe(r,TRANSCRIPT_PAYLOAD_LIMIT)}`}})});return t?{...e,content:n}:e})}function withResumptionGuard(e,t,n){let r=e.at(-1)?.role,i=findLastRealUserMessage(t),a=i!==void 0&&e.some(e=>e.role===`user`&&e.content===i.content);return r!==void 0&&r!==`assistant`?r===`tool`&&i!==void 0&&!a&&estimateTokens([i])<=n?[...e,i]:e:[...e,i!==void 0&&!a?i:createFrameworkUserMessage(`execution.continuation`,COMPACTION_RESUMPTION_MESSAGE)]}function findLastRealUserMessage(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`&&typeof n.content==`string`&&!isFrameworkUserMessage(n))return n}}function extractPreviousCheckpoint(e){let t=e[0],n=e[1];return t?.role!==`user`||t.content!==COMPACTION_CHECKPOINT_MARKER||n?.role!==`assistant`?{conversation:[...e],previousCheckpoint:void 0}:{conversation:e.slice(2),previousCheckpoint:assistantMessageText(n)}}function keepNonToolResultMessages(e){let t=[];for(let n of e)if(n.role!==`tool`){if(n.role===`assistant`){let e=assistantMessageText(n);e.length>0&&t.push({content:e,role:`assistant`});continue}t.push(n)}return t}function assistantMessageText(e){return typeof e.content==`string`?e.content.trim():e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim()}function selectRecentWindowSize(e,t){let n=Math.min(t.recentWindowSize,Math.max(e.length-1,0)),r=resolveCompactionSummaryReserve(t),i=0,a=0;for(let o=e.length-1;o>=0&&i<n;--o){let n=e[o];if(n===void 0)continue;let s=estimateTokens([n]);if(a+s+r>t.threshold)break;a+=s,i+=1}return i}function resolveCompactionSummaryReserve(e){return Math.min(2048,Math.max(64,Math.floor(e.threshold/4)))}function splitMessagesForCompaction(e,t){if(t<=0)return{older:[...e],recent:[]};let n=e.length-t;for(;n<e.length&&e[n]?.role===`tool`;)n+=1;return{older:e.slice(0,n),recent:e.slice(n)}}export{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { LanguageModel, TelemetryOptions } from "ai";
|
|
2
|
+
import { type HarnessSession, type StepResult, type ToolLoopHarnessConfig } from "#harness/types.js";
|
|
3
|
+
import { type HarnessModelMessage } from "#harness/messages.js";
|
|
4
|
+
import type { HistoryViewProjector } from "#shared/history-view.js";
|
|
5
|
+
import type { Publish } from "#harness/session-machine/commit.js";
|
|
6
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
7
|
+
import type { Step } from "#harness/step/context.js";
|
|
8
|
+
import { type TurnPosition } from "#harness/session-machine/view.js";
|
|
9
|
+
/**
|
|
10
|
+
* Processes the step result: extracts input requests, decides whether to
|
|
11
|
+
* park, continue the tool loop, or terminate.
|
|
12
|
+
*/
|
|
13
|
+
/** What a step needs from the machine after its model call. */
|
|
14
|
+
/** `session.compact()`: summarizes the history now, then the session waits. */
|
|
15
|
+
export declare function compactHistory(step: Step): Promise<StepResult>;
|
|
16
|
+
export declare function replaceSessionHistory(session: HarnessSession, history: HarnessModelMessage[]): HarnessSession;
|
|
17
|
+
/**
|
|
18
|
+
* Runs the compaction pipeline once if the session's input-token estimate
|
|
19
|
+
* is over the configured threshold. Mutates neither input; returns the new
|
|
20
|
+
* messages array and (possibly updated) session.
|
|
21
|
+
*
|
|
22
|
+
* Kept in the tool-loop (rather than the AI SDK's `prepareStep` hook) so
|
|
23
|
+
* the compacted messages flow through the same `messages` variable the
|
|
24
|
+
* harness uses to rebuild `session.history` after the step.
|
|
25
|
+
*/
|
|
26
|
+
export declare function maybeCompact(input: {
|
|
27
|
+
readonly abortSignal?: AbortSignal;
|
|
28
|
+
readonly auth: SessionAuthContext | null;
|
|
29
|
+
readonly emissionState: TurnPosition;
|
|
30
|
+
readonly force?: boolean;
|
|
31
|
+
readonly historyProjector?: HistoryViewProjector;
|
|
32
|
+
readonly messages: HarnessModelMessage[];
|
|
33
|
+
readonly model: LanguageModel;
|
|
34
|
+
readonly publish: Publish;
|
|
35
|
+
/** Model-visible prompt used only to decide whether durable history needs compaction. */
|
|
36
|
+
readonly promptMessages?: readonly HarnessModelMessage[];
|
|
37
|
+
readonly requestEnvelopeTokens?: number;
|
|
38
|
+
readonly resolveModel: ToolLoopHarnessConfig["resolveModel"];
|
|
39
|
+
readonly runtimeIdentity?: ToolLoopHarnessConfig["runtimeIdentity"];
|
|
40
|
+
readonly session: HarnessSession;
|
|
41
|
+
readonly telemetry?: TelemetryOptions;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
readonly compacted: boolean;
|
|
44
|
+
readonly messages: HarnessModelMessage[];
|
|
45
|
+
readonly session: HarnessSession;
|
|
46
|
+
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{AuthKey,HistoryStateKey}from"#context/keys.js";import{createCompactionCompletedEvent,createCompactionRequestedEvent}from"#protocol/message.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryCompaction}from"#context/memory-lifecycle.js";import{canonicalizeMemoryRecords,shouldCanonicalizeMemory}from"#shared/memory-state.js";import{activeTurnId}from"#harness/session-machine/view.js";import{resolveConversationId}from"#shared/conversation-identity.js";import{idle}from"#harness/session-machine/transitions.js";import{requireSessionModelReference}from"#harness/types.js";import{buildGatewayAttributionHeaders,resolveEffectiveRuntimeModel}from"#harness/model-call/model.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction/engine.js";import{gatewayModelId}from"#harness/model-call/usage.js";import{getRequestEnvelopeTokens}from"#harness/request-envelope.js";import{resolveCallProviderOptions}from"#harness/provider-safety.js";const log=createLogger(`harness.tool-loop`);async function compactHistory(e){let{config:t}=e;if(e.session.history.length>0)try{let n=await resolveEffectiveRuntimeModel({config:t,ctx:e.ctx,session:e.session});e.session=n.session;let r=e.position();e.session=(await maybeCompact({abortSignal:t.abortSignal,auth:e.ctx?.get(AuthKey)??null,emissionState:{...r,turnId:activeTurnId(r)},force:!0,historyProjector:t.historyProjector,messages:[...e.session.history],model:n.model,publish:e.publish,requestEnvelopeTokens:getRequestEnvelopeTokens(e.session),resolveModel:t.resolveModel,runtimeIdentity:t.runtimeIdentity,session:e.session,telemetry:e.instrumentation?.telemetry()})).session}catch(t){logError(log,`manual session compaction failed`,t,{sessionId:e.session.sessionId})}return await e.apply(idle(e.view())),{next:null,session:e.session}}function replaceSessionHistory(e,t){return contextStorage.getStore()?.delete(HistoryStateKey),{...e,history:t,compaction:{recentWindowSize:e.compaction.recentWindowSize,threshold:e.compaction.threshold,thresholdPercent:e.compaction.thresholdPercent}}}async function maybeCompact(e){let{emissionState:t,publish:n}=e,r=e.messages,i=e.session,a=e.promptMessages??r,o=validateHarnessModelMessages(e.historyProjector?.({messages:a,state:i.state})??a),s=e.force===!0||shouldCompact(o,i.compaction,e.requestEnvelopeTokens,getRequestEnvelopeTokens(i)),c=shouldCanonicalizeMemory(r);if(!s&&!c)return{compacted:!1,messages:r,session:i};let l=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:requireSessionModelReference(i),resolveModel:e.resolveModel}),u=i.agent.compactionModelReference??requireSessionModelReference(i),d=resolveCallProviderOptions({auth:e.auth,conversationId:resolveConversationId(i.rootSessionId??i.sessionId),model:l.model,modelReference:u,providerOptions:l.providerOptions});{let a=contextStorage.getStore();a!==void 0&&prepareMemoryCompaction(a,{history:r,state:i.state}),await n(createCompactionRequestedEvent({modelId:gatewayModelId(l.model)??`unknown`,sequence:t.sequence,sessionId:i.sessionId,stepIndex:t.stepIndex,turnId:t.turnId,usageInputTokens:getInputTokenCount(o,i.compaction,e.requestEnvelopeTokens,getRequestEnvelopeTokens(i))}),o)}let f=canonicalizeMemoryRecords(r),p=validateHarnessModelMessages(e.historyProjector?.({messages:f.ordinary,state:i.state})??f.ordinary),m=e.requestEnvelopeTokens??0,h={...i.compaction,threshold:Math.max(1,i.compaction.threshold-m),lastKnownInputTokens:i.compaction.lastKnownInputTokens===void 0?void 0:Math.max(0,i.compaction.lastKnownInputTokens-Math.min(getRequestEnvelopeTokens(i)??0,m))},g=s?await compactMessages([...p],l.model,h,d,e.telemetry,buildGatewayAttributionHeaders(l.model,e.runtimeIdentity),e.abortSignal,e.force===!0,e.requestEnvelopeTokens===void 0?void 0:Math.max(0,getInputTokenCount(o,i.compaction,m,getRequestEnvelopeTokens(i))-m)):[...p];r=validateHarnessModelMessages([...f.memory,...g]);{let a=contextStorage.getStore();if(a!==void 0&&prepareMemoryCompaction(a,{history:r,state:i.state}),await n(createCompactionCompletedEvent({modelId:gatewayModelId(l.model)??`unknown`,sequence:t.sequence,sessionId:i.sessionId,stepIndex:t.stepIndex,turnId:t.turnId}),e.historyProjector?.({messages:r,state:i.state})??r),a!==void 0){let e=drainMemoryCommit(a);e!==void 0&&(r=validateHarnessModelMessages([...r,...e.recalledMessages]),i={...i,state:e.state})}}return{compacted:!0,messages:r,session:replaceSessionHistory(i,r)}}export{compactHistory,maybeCompact,replaceSessionHistory};
|