eve 0.33.3 → 0.35.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 +40 -0
- package/README.md +3 -3
- package/dist/src/channel/channel-address.d.ts +3 -6
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +2 -3
- package/dist/src/channel/delivery-metadata.d.ts +9 -0
- package/dist/src/channel/delivery-metadata.js +1 -0
- package/dist/src/channel/routes.d.ts +1 -0
- package/dist/src/channel/session.d.ts +3 -4
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +20 -3
- package/dist/src/chunks/{use-eve-agent-B-Hky2f4.js → use-eve-agent-COmP-H8R.js} +39 -3
- package/dist/src/chunks/{use-eve-agent-3oBnxzhV.js → use-eve-agent-CnppTEFk.js} +39 -3
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/commands/trace-detail.d.ts +3 -2
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +4 -6
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -2
- package/dist/src/client/agent-info-schema.d.ts +12 -4
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +4 -4
- package/dist/src/compiled/@chat-adapter/slack/index.js +1 -1
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +32 -3
- package/dist/src/compiled/@vercel/otel/index.d.ts +45 -2
- package/dist/src/compiled/@workflow/core/index.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/world/env-config.d.ts +1 -0
- package/dist/src/compiled/@workflow/world/events.d.ts +92 -35
- package/dist/src/compiled/@workflow/world/index.d.ts +3 -2
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +25 -23
- package/dist/src/compiled/@workflow/world/queue.d.ts +4 -0
- package/dist/src/compiled/@workflow/world/runs.d.ts +4 -0
- package/dist/src/compiled/@workflow/world/slot-identity.d.ts +53 -0
- package/dist/src/compiled/@workflow/world/spec-version.d.ts +36 -1
- package/dist/src/compiled/@workflow/world/steps.d.ts +4 -0
- package/dist/src/compiled/@workflow/world/ulid.d.ts +6 -0
- package/dist/src/compiled/@workflow/world-local/index.js +4 -4
- package/dist/src/compiled/@workflow/world-vercel/index.js +13 -17
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-6OqdYdi4.js → attribute-changes-BoH7JsWp.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/dist-DlFv0aHY.js +40 -0
- package/dist/src/compiled/_chunks/workflow/env-config-DxamfI7T.js +1 -0
- package/dist/src/compiled/_chunks/workflow/frames-CTpeJYEQ.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{functions-CXb61C6h.js → functions-CeeNvKsq.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-BPQHjeY5.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-DQ5dOyjm.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-id-BdE0MZz9.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-CzdoBiqy.js +1 -0
- package/dist/src/compiled/_chunks/workflow/spec-version-DBUVfF_R.js +1 -0
- package/dist/src/compiled/_chunks/workflow/undici-CUIybhQ2.js +95 -0
- package/dist/src/compiled/_chunks/workflow/wait-until-DK2lnH6U.js +15 -0
- package/dist/src/compiled/_chunks/workflow/{wrapper-CDq65xJV.js → wrapper-CMGju7QA.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/ws-transport-Csi6Cydc.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +14 -14
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +8 -8
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-extension.d.ts +3 -3
- package/dist/src/compiler/normalize-extension.js +1 -1
- package/dist/src/compiler/normalize-instructions.d.ts +1 -1
- package/dist/src/compiler/normalize-instructions.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -3
- package/dist/src/context/build-dynamic-tools.d.ts +7 -0
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-instruction-lifecycle.d.ts +5 -1
- package/dist/src/context/dynamic-instruction-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +7 -0
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +18 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/discover/filesystem.d.ts +1 -1
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/discover/manifest.d.ts +1 -1
- package/dist/src/discover/manifest.js +1 -1
- package/dist/src/evals/cli/eval.js +2 -2
- package/dist/src/evals/index.d.ts +2 -2
- package/dist/src/evals/reporters/index.d.ts +1 -1
- package/dist/src/evals/runner/artifacts.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/runner/execute-eval.d.ts +5 -0
- package/dist/src/evals/runner/execute-eval.js +1 -1
- package/dist/src/evals/runner/execute-task.d.ts +3 -0
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/runner/reporters/braintrust.js +1 -1
- package/dist/src/evals/runner/reporters/types.d.ts +28 -2
- package/dist/src/evals/runner/run-evals.js +1 -1
- package/dist/src/evals/session.d.ts +11 -2
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/evals/types.d.ts +10 -1
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +1 -5
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-turn-step.d.ts +5 -0
- package/dist/src/execution/dispatch-turn-step.js +1 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +1 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +2 -1
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/route-child-delivery.d.ts +3 -4
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/route-proxied-deliver-step.d.ts +34 -0
- package/dist/src/execution/route-proxied-deliver-step.js +1 -0
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session-command-inbox.d.ts +2 -2
- package/dist/src/execution/session-command-wire.js +1 -1
- package/dist/src/execution/session.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-adapter.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/tool-auth.d.ts +9 -0
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +1 -27
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/execution/workflow-trace-context.d.ts +11 -0
- package/dist/src/execution/workflow-trace-context.js +1 -0
- package/dist/src/harness/ai-sdk-hook-bridge.d.ts +1 -1
- package/dist/src/harness/ai-sdk-hook-bridge.js +1 -1
- package/dist/src/harness/ai-sdk-telemetry.d.ts +19 -0
- package/dist/src/harness/ai-sdk-telemetry.js +1 -0
- package/dist/src/harness/approval-candidates.d.ts +109 -0
- package/dist/src/harness/approval-candidates.js +1 -0
- package/dist/src/harness/approval-delivery-coordinator.d.ts +39 -0
- package/dist/src/harness/approval-delivery-coordinator.js +1 -0
- package/dist/src/harness/authorization.d.ts +1 -0
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/channel-delivery-instrumentation.d.ts +25 -0
- package/dist/src/harness/channel-delivery-instrumentation.js +1 -0
- package/dist/src/harness/emission.d.ts +2 -2
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +1 -0
- package/dist/src/harness/hitl/approval-input-requests.js +1 -1
- package/dist/src/harness/hitl/pending-input-resolution.d.ts +3 -0
- package/dist/src/harness/hitl/pending-input-resolution.js +1 -1
- package/dist/src/harness/hitl/question-input-requests.js +1 -1
- package/dist/src/harness/hitl/session-limit-input-requests.js +1 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-request-resolution.d.ts +22 -0
- package/dist/src/harness/input-request-resolution.js +1 -0
- package/dist/src/harness/input-requests.d.ts +1 -0
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/{instrumentation-config.d.ts → instrumentation/config.d.ts} +9 -4
- package/dist/src/harness/instrumentation/config.js +1 -0
- package/dist/src/harness/instrumentation/content.d.ts +5 -0
- package/dist/src/harness/instrumentation/content.js +1 -0
- package/dist/src/harness/instrumentation/dispatch.d.ts +2 -0
- package/dist/src/harness/instrumentation/dispatch.js +1 -0
- package/dist/src/harness/instrumentation/lifecycle.d.ts +491 -0
- package/dist/src/harness/instrumentation/lifecycle.js +1 -0
- package/dist/src/harness/{instrumentation-native-events.d.ts → instrumentation/native-events.d.ts} +10 -1
- package/dist/src/harness/instrumentation/native-events.js +1 -0
- package/dist/src/harness/instrumentation/providers.d.ts +50 -0
- package/dist/src/harness/instrumentation/providers.js +1 -0
- package/dist/src/harness/{instrumentation-runtime.d.ts → instrumentation/runtime.d.ts} +7 -2
- package/dist/src/harness/{instrumentation-runtime.js → instrumentation/runtime.js} +1 -1
- package/dist/src/harness/instrumentation/setup-context.d.ts +12 -0
- package/dist/src/harness/instrumentation/setup-context.js +1 -0
- package/dist/src/harness/instrumentation/state.d.ts +59 -0
- package/dist/src/harness/instrumentation/state.js +1 -0
- package/dist/src/harness/messages.d.ts +2 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/parent-lineage.d.ts +1 -1
- package/dist/src/harness/pending-input-batches.d.ts +2 -0
- package/dist/src/harness/pending-input-batches.js +1 -1
- package/dist/src/harness/prepare-trace-context.d.ts +16 -0
- package/dist/src/harness/prepare-trace-context.js +1 -0
- package/dist/src/harness/runtime-action-settlement-state.d.ts +3 -0
- package/dist/src/harness/runtime-action-settlement-state.js +1 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/stale-input-responses.js +1 -1
- package/dist/src/harness/tool-call-action.d.ts +9 -0
- package/dist/src/harness/tool-call-action.js +1 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/types.d.ts +16 -2
- package/dist/src/internal/application/compiled-artifacts.d.ts +13 -4
- package/dist/src/internal/application/compiled-artifacts.js +5 -4
- package/dist/src/internal/application/dev-environment.d.ts +12 -0
- package/dist/src/internal/application/dev-environment.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/approval.d.ts +3 -0
- package/dist/src/internal/authored-definition/approval.js +1 -0
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/authored-definition/core.d.ts +3 -3
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/helpers/markdown.js +1 -1
- package/dist/src/internal/instrumentation-layout.d.ts +28 -0
- package/dist/src/internal/instrumentation-layout.js +1 -0
- package/dist/src/internal/instrumentation.d.ts +1 -1
- package/dist/src/internal/materialized-authored-modules.d.ts +13 -2
- package/dist/src/internal/materialized-authored-modules.js +1 -1
- package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
- package/dist/src/internal/nitro/host/local-tracing-runtime-plugin.d.ts +5 -1
- package/dist/src/internal/nitro/host/local-tracing-runtime-plugin.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +4 -3
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +2 -3
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/vercel/project-link.d.ts +1 -1
- package/dist/src/internal/vercel/project-link.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +10 -9
- package/dist/src/internal/vercel-agent-summary.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/message.d.ts +51 -2
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/traceparent.d.ts +10 -0
- package/dist/src/protocol/traceparent.js +1 -0
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/github/auth.d.ts +30 -0
- package/dist/src/public/channels/github/auth.js +2 -2
- package/dist/src/public/channels/github/defaults.d.ts +4 -3
- package/dist/src/public/channels/github/defaults.js +5 -2
- package/dist/src/public/channels/github/dispatch.d.ts +3 -2
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +10 -5
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/index.d.ts +1 -1
- package/dist/src/public/channels/slack/defaults.js +3 -3
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +11 -3
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/definitions/approval.d.ts +57 -16
- package/dist/src/public/definitions/approval.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +4 -2
- package/dist/src/public/definitions/instructions.d.ts +14 -4
- package/dist/src/public/definitions/instructions.js +1 -1
- package/dist/src/public/definitions/tool.d.ts +5 -8
- package/dist/src/public/instructions/index.d.ts +1 -2
- package/dist/src/public/instructions/index.js +1 -1
- package/dist/src/public/instrumentation/index.d.ts +36 -20
- package/dist/src/public/instrumentation/index.js +1 -1
- package/dist/src/public/instrumentation/otel.d.ts +32 -0
- package/dist/src/public/instrumentation/otel.js +1 -0
- package/dist/src/public/instrumentation/provider.d.ts +117 -0
- package/dist/src/public/instrumentation/provider.js +1 -0
- package/dist/src/public/tools/approval/approval-helpers.d.ts +4 -4
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/actions/results.d.ts +3 -3
- package/dist/src/runtime/agent/bootstrap.d.ts +2 -0
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/attributes/emit.js +1 -1
- package/dist/src/runtime/connections/principal.d.ts +3 -0
- package/dist/src/runtime/connections/principal.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +3 -5
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/connections/types.d.ts +5 -0
- package/dist/src/runtime/prompt/compose.d.ts +1 -1
- package/dist/src/runtime/prompt/compose.js +3 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/types.d.ts +4 -3
- package/dist/src/setup/index.d.ts +1 -0
- package/dist/src/setup/index.js +1 -1
- package/dist/src/setup/project-resolution.d.ts +3 -3
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/version-tokens.js +1 -1
- package/dist/src/setup/slack-connect-lifecycle.d.ts +0 -9
- package/dist/src/setup/slack-connect-lifecycle.js +1 -1
- package/dist/src/setup/slackbot.d.ts +2 -1
- package/dist/src/setup/slackbot.js +1 -1
- package/dist/src/setup/verified-remote-agent.d.ts +30 -0
- package/dist/src/setup/verified-remote-agent.js +1 -0
- package/dist/src/shared/agent-definition.d.ts +9 -0
- package/dist/src/shared/channel-definition.d.ts +3 -1
- package/dist/src/shared/dynamic-tool-definition.d.ts +3 -4
- package/dist/src/shared/instructions-definition.d.ts +15 -11
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tracing/agent-action-instrumentation.d.ts +31 -0
- package/dist/src/tracing/agent-action-instrumentation.js +1 -0
- package/dist/src/tracing/agent-approval-instrumentation.d.ts +13 -0
- package/dist/src/tracing/agent-approval-instrumentation.js +1 -0
- package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +13 -0
- package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -0
- package/dist/src/tracing/agent-otel-content.d.ts +6 -0
- package/dist/src/tracing/agent-otel-content.js +2 -2
- package/dist/src/tracing/agent-otel-provider.d.ts +10 -8
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-session-context.d.ts +17 -0
- package/dist/src/tracing/agent-otel-session-context.js +1 -0
- package/dist/src/tracing/agent-otel-usage.d.ts +4 -0
- package/dist/src/tracing/agent-otel-usage.js +1 -0
- package/dist/src/tracing/agent-span-id-generator.d.ts +2 -0
- package/dist/src/tracing/agent-span-id-generator.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +28 -0
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -0
- package/dist/src/tracing/agent-trace-context-store.d.ts +8 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/agent-trace-span-processor.d.ts +0 -1
- package/dist/src/tracing/agent-trace-span-processor.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +33 -3
- package/dist/src/tracing/agent-trace-state.js +1 -1
- package/dist/src/tracing/batch-span-processor.d.ts +20 -0
- package/dist/src/tracing/batch-span-processor.js +1 -0
- package/dist/src/tracing/content-attributes.d.ts +28 -0
- package/dist/src/tracing/content-attributes.js +1 -0
- package/dist/src/tracing/content-span-processor.d.ts +19 -0
- package/dist/src/tracing/content-span-processor.js +1 -0
- package/dist/src/tracing/install-instrumentation-runtime.d.ts +19 -0
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -0
- package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
- package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/local-traces.d.ts +56 -0
- package/dist/src/tracing/local-traces.js +1 -0
- package/dist/src/tracing/otel-declaration.d.ts +150 -0
- package/dist/src/tracing/otel-declaration.js +1 -0
- package/dist/src/tracing/otel-registration.d.ts +21 -0
- package/dist/src/tracing/otel-registration.js +1 -0
- package/dist/src/tracing/vercel-runtime-span-exporter.d.ts +5 -0
- package/dist/src/tracing/vercel-runtime-span-exporter.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +18 -20
- package/docs/agent-config.md +5 -5
- package/docs/channels/eve.mdx +10 -56
- package/docs/channels/github.mdx +1 -1
- package/docs/channels/meta.json +1 -0
- package/docs/concepts/context-control.md +32 -56
- package/docs/concepts/default-harness.md +2 -2
- package/docs/concepts/execution-model-and-durability.mdx +4 -4
- package/docs/concepts/meta.json +3 -1
- package/docs/concepts/sessions-runs-and-streaming.md +22 -10
- package/docs/{guides → concepts}/state.md +3 -3
- package/docs/connections/mcp.mdx +6 -89
- package/docs/connections/meta.json +1 -0
- package/docs/connections/openapi.mdx +5 -69
- package/docs/connections/overview.mdx +29 -3
- package/docs/evals/meta.json +1 -0
- package/docs/evals/reporters.mdx +14 -4
- package/docs/extensions.md +1 -1
- package/docs/getting-started.mdx +175 -13
- package/docs/guides/auth-and-route-protection.md +3 -18
- package/docs/guides/client/meta.json +2 -1
- package/docs/guides/client/output-schema.mdx +2 -2
- package/docs/guides/client/overview.mdx +1 -1
- package/docs/guides/deployment/meta.json +1 -0
- package/docs/guides/deployment/overview.md +1 -1
- package/docs/guides/deployment/self-hosting.md +3 -3
- package/docs/guides/deployment/vercel.mdx +1 -1
- package/docs/guides/dev-tui.md +3 -13
- package/docs/guides/dynamic-capabilities.md +26 -4
- package/docs/guides/frontend/meta.json +2 -1
- package/docs/guides/frontend/nextjs.mdx +1 -10
- package/docs/guides/frontend/nuxt.mdx +1 -10
- package/docs/guides/frontend/overview.mdx +12 -3
- package/docs/guides/frontend/sveltekit.mdx +1 -10
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +39 -126
- package/docs/guides/frontend/use-eve-agent-vue.mdx +40 -139
- package/docs/guides/instrumentation.md +37 -15
- package/docs/guides/meta.json +1 -5
- package/docs/guides/remote-agents.md +9 -9
- package/docs/guides/session-context.md +34 -103
- package/docs/install-integrations.mdx +1 -1
- package/docs/instructions.mdx +45 -12
- package/docs/meta.json +24 -13
- package/docs/patterns/dynamic-scheduling.md +1 -1
- package/docs/patterns/meta.json +1 -0
- package/docs/patterns/multi-tenant-approvals.md +1 -1
- package/docs/patterns/multi-tenant-auth.md +1 -1
- package/docs/patterns/multi-tenant-memory.md +4 -3
- package/docs/{guides → protocols}/acp.md +1 -1
- package/docs/protocols/meta.json +5 -0
- package/docs/reference/cli.md +34 -34
- package/docs/reference/meta.json +1 -1
- package/docs/reference/typescript-api.md +4 -2
- package/docs/{subagents.mdx → subagents/index.mdx} +2 -2
- package/docs/subagents/meta.json +5 -0
- package/docs/{guides/dynamic-workflows.md → subagents/workflow-tool.md} +6 -6
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tools/meta.json +1 -0
- package/docs/tools/overview.mdx +1 -1
- package/docs/tutorial/connect-a-warehouse.mdx +1 -1
- package/docs/tutorial/meta.json +1 -0
- package/docs/tutorial/remember-definitions.mdx +2 -2
- package/docs/tutorial/ship-it.mdx +2 -2
- package/package.json +10 -4
- package/dist/src/compiled/_chunks/workflow/dist-C8PhDW9B.js +0 -1
- package/dist/src/compiled/_chunks/workflow/functions-xMPAeWFr.js +0 -1
- package/dist/src/compiled/_chunks/workflow/node-Smb57EnG.js +0 -40
- package/dist/src/compiled/_chunks/workflow/resume-hook-BrduAuFX.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-CX7_sJnW.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-tsb2HjWK.js +0 -1
- package/dist/src/compiled/_chunks/workflow/undici-BNc_0O4m.js +0 -95
- package/dist/src/compiled/_chunks/workflow/wait-until-BYKVqrwc.js +0 -15
- package/dist/src/harness/instrumentation-config.js +0 -1
- package/dist/src/harness/instrumentation-lifecycle.d.ts +0 -171
- package/dist/src/harness/instrumentation-lifecycle.js +0 -1
- package/dist/src/harness/instrumentation-native-events.js +0 -1
- package/dist/src/harness/otel-integration.d.ts +0 -12
- package/dist/src/harness/otel-integration.js +0 -1
- package/docs/installation.mdx +0 -66
- package/docs/project-structure.mdx +0 -53
- package/docs/reference/project-layout.md +0 -123
- /package/dist/src/harness/{instrumentation-runtime-context.d.ts → instrumentation/runtime-context.d.ts} +0 -0
- /package/dist/src/harness/{instrumentation-runtime-context.js → instrumentation/runtime-context.js} +0 -0
- /package/docs/{guides → protocols}/ucp.mdx +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dispatchTurnStep}from"#execution/
|
|
1
|
+
import{dispatchTurnStep}from"#execution/dispatch-turn-step.js";import{TurnControlReceiver}from"#execution/turn-control-receiver.js";async function dispatchAndAwaitTurn(t){let n=new TurnControlReceiver({bufferedDeliveries:t.bufferedDeliveries,bufferedSessionControls:t.bufferedSessionControls,commandInbox:t.commandInbox,token:t.controlToken});try{return await dispatchTurnStep({capabilities:t.capabilities,completionToken:n.token,delivery:t.delivery,mode:t.mode,parentWritable:t.parentWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),{action:await n.waitForAction(),dispose:()=>n.dispose()}}catch(e){throw await n.dispose(),e}}export{dispatchAndAwaitTurn};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{activeTurnId}from"#harness/active-turn-id.js";import{
|
|
1
|
+
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{activeTurnId}from"#harness/active-turn-id.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let t=migrateTurnWorkflowInput(e);return t.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(t):runLegacyTurnWorkflow(t)}async function runTurnOwnedWorkflow(n){let i=createHook({token:`${n.completionToken}:inbox`}),s=i[Symbol.asyncIterator](),u=new TurnExecutionCursor({controlToken:n.completionToken,parentWritable:n.stepInput.parentWritable,serializedContext:n.stepInput.serializedContext,sessionState:n.stepInput.sessionState}),d=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(d++)}`,f=[],p=n.stepInput.input,m=!1,h;try{try{await claimHookOwnership(i),m=!0}catch(e){if(isHookConflictError(e))return;throw e}for(n.driverCapabilities?.cancelledTurnSettle===!0&&(h=await createTurnCancellationControl({controlToken:n.completionToken,expectedTurnId:activeTurnId(n.stepInput.sessionState.emissionState)}));;){let t=await turnStep(u.createStepInput(p,h?.signal)),a=t.action===`dispatch-workflow-runtime-actions`||t.action===`park`?t.pendingRuntimeActionKeys:void 0;if(t.action===`cancelled`||h?.signal.aborted===!0&&a===void 0){await finishCancelledTurn({bufferedDeliveries:f,cancellation:h,cursor:u});return}if(t.sleepDurationMs!==void 0&&await waitForTurnSleep(t.sleepDurationMs,h)===`cancel`){await finishCancelledTurn({bufferedDeliveries:f,cancellation:h,cursor:u});return}if(t.action===`done`){await h?.dispose(),await u.finish(t,{kind:`done`,output:t.output??``,isError:t.isError,usage:t.usage,usageDelta:t.usageDelta},f);return}if(a!==void 0){await u.adopt(t);let n=await(t.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:i.token,parentWritable:u.parentWritable,serializedContext:u.serializedContext,sessionState:u.sessionState}),c=n.results.length===0?void 0:Date.now();await u.adopt(n);let l=await waitForRuntimeActionResults({bufferedDeliveries:f,cancellation:h,cursor:u,inboxToken:i.token,initialAcceptedAtMs:c,initialResults:n.results,iterator:s,nextDeliveryRequestId,pendingActionKeys:a});if(l===`cancelled`){p=void 0;continue}if(l===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:f,cancellation:h,cursor:u});return}p={kind:`runtime-action-result`,...l};continue}if(t.action===`park`){if(!(t.hasPendingAuthorization||t.hasPendingInputBatch&&n.capabilities?.requestInput===!0||n.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await h?.dispose(),await u.finish(t,{authorizationAttemptIds:t.authorizationAttemptIds,authorizationNames:t.authorizationNames,kind:`park`,settled:t.settled},f);return}await u.adopt(t),p=void 0}}catch(e){throw await u.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{h!==void 0&&await h.dispose(),m&&await disposeHook(i)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,n=[...e.initialResults],r=new Map;if(e.initialAcceptedAtMs!==void 0)for(let t of e.initialResults)r.set(getRuntimeActionResultKey(t),e.initialAcceptedAtMs);for(;;){let a=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(a!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),{acceptedAtMsByCallId:Object.fromEntries(a.map(e=>[e.callId,r.get(getRuntimeActionResultKey(e))])),results:a};e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let o=e.iterator.next();o.catch(()=>{});let s=await(e.cancellation===void 0?o:Promise.race([o,e.cancellation.requested]));if(s===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(s.done)throw Error(`Turn inbox closed before runtime actions completed.`);let c=s.value;if(c.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state,i=c.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e));if(i.length>0){let e=Date.now();n.push(...i);for(let t of i)r.set(getRuntimeActionResultKey(t),e)}continue}if(c.kind===`subagent-input-request`||c.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:c,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(c.kind===`driver-delivery`&&c.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:c.requestId}),t=void 0;let n=await routeDeliverToChildren({delivery:c.delivery,parentWritable:e.cursor.parentWritable,sessionState:e.cursor.sessionState});if(await e.cursor.adopt(n),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push(n.remainder)}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationAttemptIds:n.authorizationAttemptIds,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:a,workflowStartedAt:f}=getWorkflowMetadata(),p=e.serializedContext[`eve.continuationToken`]||``,m=e.serializedContext[`eve.mode`],h=e.serializedContext[`eve.capabilities`],g=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=a;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let n=readRootSessionId(e.serializedContext),r=readSerializedSubagentDepth(e.serializedContext),i=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:c}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:p,dynamicSubagentAgentConfig:i,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:n,sessionId:a,subagentDepth:r});v.lastSessionState=c,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let l=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:m,serializedContext:e.serializedContext,sessionState:c,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(f.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return l.kind===`result`?l.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:m,serializedContext:l.serializedContext,sessionState:l.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:_,serializedContext:e.serializedContext}),m===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:a,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=e.sessionState,a=new Set(e.expectedAttemptIds);for(let e of n.keys())a.has(e)||n.delete(e);for(;;){if(a.size>0&&[...a].every(e=>n.has(e))){let e=[...a].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:a.size>0,bufferedDeliveries:i,bufferedSessionControls:o,commandInbox:s,deferDeliveries:t.mode===`task`&&a.size>0,driverWritable:t.driverWritable,sessionState:r});if(r=e.sessionState,e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&a.has(e.attemptId)&&!n.has(e.attemptId)&&n.set(e.attemptId,t)}if(e.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],o=[],s=createSessionCommandInbox(),c=sessionCommandHookToken(t.sessionState.sessionId);await s.claimStable(c),await s.claimAuthorization(`${t.sessionState.sessionId}:auth`);let u=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:c}),d,runTurn=async e=>{let n=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:o,capabilities:t.capabilities,commandInbox:s,controlToken:nextTurnControlToken(),delivery:e.delivery,mode:t.mode,parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});return await d?.(),d=n.dispose,n.action};try{t.sessionState.continuationToken&&await s.rekeyContinuation(t.sessionState.continuationToken),await u?.start();let e=await runTurn({delivery:t.initialInput,serializedContext:t.serializedContext,sessionState:t.sessionState});for(t.crashCleanupState.lastSessionState=e.sessionState;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState},t.crashCleanupState.lastSessionState=e.sessionState}e.sessionState.continuationToken&&await s.rekeyContinuation(e.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:e.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[],sessionState:e.sessionState});if(e={...e,sessionState:r.sessionState},t.crashCleanupState.lastSessionState=e.sessionState,r.kind===`authorization-resume`){e=await runTurn({delivery:{kind:`deliver`,payloads:r.payloads},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:e.serializedContext,sessionState:e.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({sessionState:e.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({delivery:{kind:r.kind},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=e.sessionState;continue}r.deliver.caller!==void 0&&(t.crashCleanupState.caller=r.deliver.caller),e=await runTurn({delivery:{auth:r.deliver.auth,kind:`deliver`,payloads:[r.remainder],requestId:r.deliver.requestId},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState}}finally{await d?.(),await u?.dispose(),await s.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:r?void 0:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:r?void 0:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:s,workflowStartedAt:f}=getWorkflowMetadata(),p=e.serializedContext[`eve.continuationToken`]||``,m=e.serializedContext[`eve.mode`],h=e.serializedContext[`eve.capabilities`],g=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=s;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let i=readRootSessionId(e.serializedContext),a=readSerializedSubagentDepth(e.serializedContext),o=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:c}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:p,dynamicSubagentAgentConfig:o,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:i,sessionId:s,subagentDepth:a});v.lastSessionState=c,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let l=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{deliveryMetadata:e.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...e.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:m,serializedContext:e.serializedContext,sessionState:c,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(f.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return l.kind===`result`?l.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:m,serializedContext:l.serializedContext,sessionState:l.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:_,serializedContext:e.serializedContext}),m===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:s,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=e.sessionState,s=new Set(e.expectedAttemptIds);for(let e of n.keys())s.has(e)||n.delete(e);for(;;){if(s.size>0&&[...s].every(e=>n.has(e))){let e=[...s].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:s.size>0,bufferedDeliveries:i,bufferedSessionControls:a,commandInbox:o,deferDeliveries:t.mode===`task`&&s.size>0,driverWritable:t.driverWritable,sessionState:r});if(r=e.sessionState,e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&s.has(e.attemptId)&&!n.has(e.attemptId)&&n.set(e.attemptId,t)}if(e.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],o=createSessionCommandInbox(),c=sessionCommandHookToken(t.sessionState.sessionId);await o.claimStable(c),await o.claimAuthorization(`${t.sessionState.sessionId}:auth`);let u=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:c}),d,runTurn=async e=>{let n=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,capabilities:t.capabilities,commandInbox:o,controlToken:nextTurnControlToken(),delivery:e.delivery,mode:t.mode,parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});return await d?.(),d=n.dispose,n.action};try{t.sessionState.continuationToken&&await o.rekeyContinuation(t.sessionState.continuationToken),await u?.start();let e=await runTurn({delivery:t.initialInput,serializedContext:t.serializedContext,sessionState:t.sessionState});for(t.crashCleanupState.lastSessionState=e.sessionState;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState},t.crashCleanupState.lastSessionState=e.sessionState}e.sessionState.continuationToken&&await o.rekeyContinuation(e.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:e.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[],sessionState:e.sessionState});if(e={...e,sessionState:r.sessionState},t.crashCleanupState.lastSessionState=e.sessionState,r.kind===`authorization-resume`){e=await runTurn({delivery:{kind:`deliver`,payloads:r.payloads},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:e.serializedContext,sessionState:e.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({sessionState:e.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({delivery:{kind:r.kind},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=e.sessionState;continue}r.deliver.caller!==void 0&&(t.crashCleanupState.caller=r.deliver.caller),e=await runTurn({delivery:{...r.remainder,kind:`deliver`},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState}}finally{await d?.(),await u?.dispose(),await o.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:r?void 0:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:r?void 0:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f=l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId),i.continuationToken){let e=await waitForCommandHookOwner(i.continuationToken);if(e.runId!==p.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:i.continuationToken,ownerSessionId:e.runId,sessionId:p.runId})}let m,getEvents=()=>(m??=parseNdjsonStream(()=>getRun(p.runId).getReadable()),m);return{get events(){return getEvents()},sessionId:p.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeHook(e,sessionHookPayload(n)))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function sessionHookPayload(e){return e.kind===`send`?sendCommandToDelivery(e):e}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),{kind:`cancel`,turnId:e.turnId})}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}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{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";
|
|
2
1
|
import type { HarnessSession, SettledTurn, StepInput } from "#harness/types.js";
|
|
3
2
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
4
3
|
import type { JsonObject } from "#shared/json.js";
|
|
5
4
|
import type { RunMode } from "#shared/run-mode.js";
|
|
6
5
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
7
|
-
import {
|
|
6
|
+
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
8
7
|
/**
|
|
9
8
|
* Result of one durable harness step, consumed by the turn workflow.
|
|
10
9
|
*
|
|
@@ -79,28 +78,3 @@ export declare function resolveEffectiveOutputSchema(input: {
|
|
|
79
78
|
readonly mode: RunMode;
|
|
80
79
|
readonly session: HarnessSession;
|
|
81
80
|
}): HarnessSession;
|
|
82
|
-
export type RoutedDeliverResult = {
|
|
83
|
-
readonly kind: "cancel-turn";
|
|
84
|
-
readonly sessionState: DurableSessionState;
|
|
85
|
-
} | {
|
|
86
|
-
readonly kind: "continue";
|
|
87
|
-
/** `undefined` when the entire payload was routed to descendants. */
|
|
88
|
-
readonly remainder: DeliverPayload | undefined;
|
|
89
|
-
readonly sessionState: DurableSessionState;
|
|
90
|
-
};
|
|
91
|
-
/**
|
|
92
|
-
* Splits an inbound deliver payload into parent-local and
|
|
93
|
-
* proxied-child buckets and forwards the child buckets via
|
|
94
|
-
* `resumeHook`. Successfully forwarded request IDs are retired in the
|
|
95
|
-
* returned snapshot so later deliveries cannot route through stale entries.
|
|
96
|
-
*/
|
|
97
|
-
export declare function routeProxiedDeliverStep(input: {
|
|
98
|
-
readonly auth?: SessionAuthContext | null;
|
|
99
|
-
readonly parentWritable: WritableStream<Uint8Array>;
|
|
100
|
-
readonly payload: DeliverPayload;
|
|
101
|
-
readonly sessionState: DurableSessionState;
|
|
102
|
-
}): Promise<RoutedDeliverResult>;
|
|
103
|
-
/** Starts a per-turn child workflow for the current driver session. */
|
|
104
|
-
export declare function dispatchTurnStep(input: TurnWorkflowDispatchInput): Promise<{
|
|
105
|
-
readonly runId: string;
|
|
106
|
-
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(f,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},p=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=buildAdapterContext(l,c),g;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,h):defaultDeliverResult(n);r!=null&&e.push(r)}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),g={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...h.state}}),o.input?.kind===`deliver`&&g===void 0){let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let _=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.subagentRegistry.dynamicResolvers??[],x=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,S=u.resolvedAgent.dynamicToolResolvers??[],C={...u.graph.root,turnAgent:d.turnAgent},w=buildRuntimeIdentity(C),T=process.env.VERCEL_DEPLOYMENT_ID?.trim(),E=T?`deployment:${T}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!getHarnessEmissionState(m.state).sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,E),c.set(SessionDynamicToolRuntimeRevisionKey,E);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:b,event:e,messages:m.history,persistentSessions:x,runtimeRevision:E}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,runtimeRevision:E})])}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,h);setChannelContext(c,{...l,state:{...h.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:b,event:n,messages:t??[],persistentSessions:x}),await dispatchDynamicToolEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:g,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);isHarnessBetweenTurns(t)&&(e=await emitTurnPreamble(handleEvent,{},e,w),t=setHarnessEmissionState(t,e));for(let{authorization:t,result:n}of p)await handleEvent(createAuthorizationCompletedEvent({authorization:t,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:C,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,g)})}catch(e){if(!isTurnCancellation(e))throw e;return D.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){if(O===`task`&&hasPendingInputBatch(k.session.state))throw D.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let r of n.forChildren)await resumeHook(r.childContinuationToken,sendCommandToDelivery({auth:e.auth,kind:`send`,payload:r.payload})),t=retireProxyInputRequests(t,r.retireRequestIds);let r=n.forChildren.length===0?e.sessionState:replaceDurableSessionSnapshot({session:t,state:e.sessionState});return n.parentAction===void 0?{kind:`continue`,remainder:n.forSelf,sessionState:r}:{...n.parentAction,sessionState:r}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(f,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},p=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=getInstrumentationRuntime(),g=getHarnessEmissionState(m.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:h?.hooks,rootSessionId:m.rootSessionId??m.sessionId,sequence:g.sequence,sessionId:m.sessionId,turnId:activeTurnId(g)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:h?.hooks,includeTurn:!1,outcome:`failed`})),await h?.forceFlush()},_=buildAdapterContext(l,c),v;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,_):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),v={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{..._.state}}),o.input?.kind===`deliver`&&v===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:h?.hooks,includeTurn:!1,outcome:`completed`})),await h?.forceFlush();let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let y=u.hookRegistry,b=u.resolvedAgent.dynamicInstructionsResolvers??[],x=u.resolvedAgent.dynamicSkillResolvers??[],S=u.subagentRegistry.dynamicResolvers??[],C=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,w=u.resolvedAgent.dynamicToolResolvers??[],T={...u.graph.root,turnAgent:d.turnAgent},E=buildRuntimeIdentity(T);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!g.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:E});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,persistentSessions:C,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:w,event:e,messages:m.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,_);setChannelContext(c,{...l,state:{..._.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:y,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:S,event:n,messages:t??[],persistentSessions:C}),await dispatchDynamicToolEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:x,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:b,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:v,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:E,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,E,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of p){let r=f?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:T,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,v)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;D.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(o.serializedContext,t),t),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){if(O===`task`&&hasPendingInputBatch(k.session.state))throw D.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}export{resolveEffectiveOutputSchema,turnStep};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ContextContainer } from "#context/container.js";
|
|
2
|
+
import type { HarnessEmissionState } from "#harness/emission.js";
|
|
3
|
+
import type { HarnessSession } from "#harness/types.js";
|
|
4
|
+
import type { RuntimeIdentity, RuntimeTraceContext } from "#protocol/message.js";
|
|
5
|
+
/** Prepares native tracing for workflow-owned preambles emitted outside the tool loop. */
|
|
6
|
+
export declare function prepareWorkflowPreambleTrace(input: {
|
|
7
|
+
readonly ctx: ContextContainer;
|
|
8
|
+
readonly emissionState: HarnessEmissionState;
|
|
9
|
+
readonly runtimeIdentity: RuntimeIdentity;
|
|
10
|
+
readonly session: HarnessSession;
|
|
11
|
+
}): Promise<RuntimeTraceContext | undefined>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ParentSessionKey,ParentTraceContextKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{resolveParentLineage}from"#harness/parent-lineage.js";import{prepareTurnTraceContext}from"#harness/prepare-trace-context.js";async function prepareWorkflowPreambleTrace(e){let t=e.ctx.get(ParentSessionKey);return await prepareTurnTraceContext({agentName:e.runtimeIdentity.agentName,instrumentation:getInstrumentationRuntime(),parentLineage:resolveParentLineage(t,e.ctx.get(ChannelKey)),parentTraceContext:e.ctx.get(ParentTraceContextKey),rootSessionId:t?.rootSessionId??e.session.rootSessionId??e.session.sessionId,sequence:e.emissionState.sequence,sessionId:e.session.sessionId,sessionStarted:e.emissionState.sessionStarted,turnId:`turn_${e.emissionState.sequence}`})}export{prepareWorkflowPreambleTrace};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { Telemetry } from "ai";
|
|
2
|
-
import type { InstrumentationAttemptScope, InstrumentationContextRunner, InstrumentationHooks } from "#harness/instrumentation
|
|
2
|
+
import type { InstrumentationAttemptScope, InstrumentationContextRunner, InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
|
|
3
3
|
/** Creates one provider-neutral AI SDK bridge for one actual model attempt. */
|
|
4
4
|
export declare function createAiSdkHookBridge(scope: InstrumentationAttemptScope, hooks: InstrumentationHooks, runInContext?: InstrumentationContextRunner): Telemetry;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function createAiSdkHookBridge(
|
|
1
|
+
import{attemptIdempotencyKey,modelCallIdempotencyKey,toolCallIdempotencyKey}from"#harness/instrumentation/lifecycle.js";import{structuralProviderMetadata}from"#harness/instrumentation/content.js";function createAiSdkHookBridge(i,a,o=directRunInContext){let s={capturesContent:a.capturesContent,modelKeys:new Map,scope:i,toolKeys:new Map};return{onStart(e){s.operation=Object.freeze({modelId:e.modelId,operationId:e.operationId,provider:e.provider})},async onStepStart(e){s.stepNumber=e.stepNumber;let t=toStepAttemptStarted(s);t!==void 0&&await a.publish(t)},async onLanguageModelCallStart(e){let n=modelCallIdempotencyKey(s.scope,s.stepNumber??0);s.modelKeys.set(e.callId,n);let r=toModelCallStarted(s,n,e);await a.publish(r)},executeLanguageModelCall({callId:e,execute:t}){let n=s.modelKeys.get(e);return n===void 0?t():o({idempotencyKey:n,scope:i,type:`model.call`},t)},async onLanguageModelCallEnd(e){let t=s.modelKeys.get(e.callId);if(t===void 0)return;s.modelKeys.delete(e.callId);let n=toModelCallCompleted(s,t,e);await a.publish(n)},async onStepEnd(t){if(t.providerMetadata===void 0)return;let n=s.capturesContent?t.providerMetadata:structuralProviderMetadata(t.providerMetadata);await a.publish(Object.freeze({idempotencyKey:attemptIdempotencyKey(s.scope),providerMetadata:n,scope:s.scope,type:`step.attempt.metadata`}))},async onToolExecutionStart(e){let t=toolCallIdempotencyKey(s.scope,e.toolCall.toolCallId,s.stepNumber??0);s.toolKeys.set(e.toolCall.toolCallId,t);let r=toToolCallStarted(s,t,e);await a.publish(r)},executeTool({toolCallId:e,execute:t}){let n=s.toolKeys.get(e);return n===void 0?t():o({idempotencyKey:n,scope:i,type:`tool.call`},t)},async onToolExecutionEnd(e){let t=e.toolCall.toolCallId,n=s.toolKeys.get(t);if(n===void 0)return;s.toolKeys.delete(t);let r=toToolCallCompleted(s,n,e);await a.publish(r)},async onAbort(e){await failOpenOperations(e.reason)},async onError(e){await failOpenOperations(e.error)}};async function failOpenOperations(e){let t=[];for(let n of s.modelKeys.values())t.push(a.publish(Object.freeze({error:e,idempotencyKey:n,scope:i,type:`model.call.failed`})));for(let n of s.toolKeys.values())t.push(a.publish(Object.freeze({error:e,idempotencyKey:n,scope:i,type:`tool.call.failed`})));s.modelKeys.clear(),s.toolKeys.clear(),await Promise.all(t)}}const directRunInContext=(e,t)=>t();function toStepAttemptStarted(t){if(!(t.operation===void 0||t.stepNumber===void 0))return Object.freeze({idempotencyKey:attemptIdempotencyKey(t.scope),operation:t.operation,scope:t.scope,type:`step.attempt.started`})}function toModelCallStarted(e,t,n){return Object.freeze({idempotencyKey:t,input:e.capturesContent?Object.freeze({instructions:n.instructions,messages:Object.freeze([...n.messages])}):void 0,model:Object.freeze({modelId:n.modelId,provider:n.provider}),scope:e.scope,type:`model.call.started`})}function toModelCallCompleted(e,t,n){return Object.freeze({content:e.capturesContent?toContentParts(n.content):void 0,finishReason:n.finishReason,idempotencyKey:t,scope:e.scope,type:`model.call.completed`,usage:toUsage(n.usage)})}function toUsage(e){return Object.freeze({inputTokenDetails:Object.freeze({cacheReadTokens:e.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:e.inputTokenDetails?.cacheWriteTokens}),inputTokens:e.inputTokens,outputTokens:e.outputTokens})}function toContentParts(e){let t=[];for(let n of e)switch(n.type){case`text`:case`reasoning`:t.push(Object.freeze({text:n.text,type:n.type}));break;case`tool-call`:t.push(Object.freeze({callId:n.toolCallId,input:n.input,toolName:n.toolName,type:`tool-call`}));break;case`tool-result`:t.push(Object.freeze({callId:n.toolCallId,input:n.input,output:n.output,toolName:n.toolName,type:`tool-result`}));break;case`tool-error`:t.push(Object.freeze({callId:n.toolCallId,error:n.error,input:n.input,toolName:n.toolName,type:`tool-error`}));break;default:break}return Object.freeze(t)}function toToolCallStarted(e,t,n){return Object.freeze({callId:n.toolCall.toolCallId,idempotencyKey:t,input:e.capturesContent?n.toolCall.input:void 0,scope:e.scope,toolName:n.toolCall.toolName,type:`tool.call.started`})}function toToolCallCompleted(e,t,n){return Object.freeze({idempotencyKey:t,output:toToolOutput(n.toolOutput,e.capturesContent),scope:e.scope,type:`tool.call.completed`})}function toToolOutput(e,t){return e.type===`tool-result`?Object.freeze(t?{output:e.output,type:`result`}:{type:`result`}):Object.freeze(t?{error:e.error,type:`error`}:{type:`error`})}export{createAiSdkHookBridge};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Telemetry } from "ai";
|
|
2
|
+
/**
|
|
3
|
+
* Registers the AI SDK OpenTelemetry integration once so that model
|
|
4
|
+
* calls emit OTel spans, including runtime-context attributes. Safe to
|
|
5
|
+
* call multiple times — only the first call has an effect.
|
|
6
|
+
*
|
|
7
|
+
* In AI SDK v7 the built-in OTel tracing was moved to `@ai-sdk/otel`
|
|
8
|
+
* and must be registered explicitly.
|
|
9
|
+
*/
|
|
10
|
+
export declare function ensureOtelIntegration(): void;
|
|
11
|
+
/**
|
|
12
|
+
* Every integration currently registered with the AI SDK — eve's own, plus any
|
|
13
|
+
* an authored instrumentation module added with `registerTelemetry`.
|
|
14
|
+
*
|
|
15
|
+
* A per-call `integrations` list replaces the registered ones rather than
|
|
16
|
+
* adding to them, so anything that passes integrations per call has to carry
|
|
17
|
+
* these forward or they stop receiving events.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getRegisteredTelemetryIntegrations(): readonly Telemetry[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{registerTelemetry}from"ai";import{OpenTelemetry}from"#compiled/@ai-sdk/otel/index.js";let registered=!1;function ensureOtelIntegration(){registered||(registered=!0,registerTelemetry(new OpenTelemetry({runtimeContext:!0})))}function getRegisteredTelemetryIntegrations(){return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS??[]}export{ensureOtelIntegration,getRegisteredTelemetryIntegrations};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { AuthorizationChallenge } from "#harness/authorization.js";
|
|
3
|
+
import type { SessionStateMap } from "#harness/types.js";
|
|
4
|
+
export type ApprovalCandidateStatus = "pending" | "authorization-required" | "allowed" | "rejected" | "failed" | "timed-out" | "stale";
|
|
5
|
+
export interface ApprovalCandidateAuditRecord {
|
|
6
|
+
readonly candidateId: string;
|
|
7
|
+
readonly requestId: string;
|
|
8
|
+
readonly responder: ApprovalResponderIdentity;
|
|
9
|
+
readonly status: ApprovalCandidateStatus;
|
|
10
|
+
readonly createdAt: number;
|
|
11
|
+
readonly completedAt?: number;
|
|
12
|
+
readonly eventEmitted?: boolean;
|
|
13
|
+
readonly expiresAt?: number;
|
|
14
|
+
readonly reason?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ApprovalResponderIdentity {
|
|
17
|
+
readonly authenticator: string;
|
|
18
|
+
readonly issuer?: string;
|
|
19
|
+
readonly principalId: string;
|
|
20
|
+
readonly principalType: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ApprovalSettlementAuditRecord {
|
|
23
|
+
readonly actor: ApprovalResponderIdentity;
|
|
24
|
+
readonly outcome: "allowed" | "cancelled";
|
|
25
|
+
readonly requestId: string;
|
|
26
|
+
readonly settledAt: number;
|
|
27
|
+
readonly candidateId?: string;
|
|
28
|
+
readonly eventEmitted?: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface ActiveApprovalCandidate {
|
|
31
|
+
readonly candidateId: string;
|
|
32
|
+
readonly requestId: string;
|
|
33
|
+
readonly responder: SessionAuthContext;
|
|
34
|
+
readonly status: "pending" | "authorization-required";
|
|
35
|
+
readonly createdAt: number;
|
|
36
|
+
readonly expiresAt: number;
|
|
37
|
+
readonly authorizationChallenges?: readonly AuthorizationChallenge[];
|
|
38
|
+
readonly pendingEventEmitted?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface ApprovalStateTransition {
|
|
41
|
+
readonly changed: boolean;
|
|
42
|
+
readonly state: SessionStateMap | undefined;
|
|
43
|
+
}
|
|
44
|
+
/** Creates or deduplicates one responder's Allow candidate for a pending request. */
|
|
45
|
+
export declare function createApprovalCandidate(input: {
|
|
46
|
+
readonly candidateIdPrefix: string;
|
|
47
|
+
readonly createdAt: number;
|
|
48
|
+
readonly expiresAt: number;
|
|
49
|
+
readonly requestId: string;
|
|
50
|
+
readonly responder: SessionAuthContext;
|
|
51
|
+
readonly state: SessionStateMap | undefined;
|
|
52
|
+
}): ApprovalStateTransition;
|
|
53
|
+
/** Marks the pending candidate event as emitted. */
|
|
54
|
+
export declare function markApprovalCandidatePendingEventEmitted(input: {
|
|
55
|
+
readonly candidateId: string;
|
|
56
|
+
readonly state: SessionStateMap | undefined;
|
|
57
|
+
}): SessionStateMap | undefined;
|
|
58
|
+
/** Marks a terminal candidate history event as emitted. */
|
|
59
|
+
export declare function markApprovalCandidateHistoryEventEmitted(input: {
|
|
60
|
+
readonly candidateId: string;
|
|
61
|
+
readonly state: SessionStateMap | undefined;
|
|
62
|
+
}): SessionStateMap | undefined;
|
|
63
|
+
/** Marks a terminal settlement event as emitted. */
|
|
64
|
+
export declare function markApprovalSettlementEventEmitted(input: {
|
|
65
|
+
readonly requestId: string;
|
|
66
|
+
readonly state: SessionStateMap | undefined;
|
|
67
|
+
}): SessionStateMap | undefined;
|
|
68
|
+
/** Marks a candidate as waiting on a private authorization challenge. */
|
|
69
|
+
export declare function markApprovalCandidateAuthorizationRequired(input: {
|
|
70
|
+
readonly authorizationChallenges: readonly AuthorizationChallenge[];
|
|
71
|
+
readonly candidateId: string;
|
|
72
|
+
readonly expiresAt?: number;
|
|
73
|
+
readonly state: SessionStateMap | undefined;
|
|
74
|
+
}): SessionStateMap | undefined;
|
|
75
|
+
/** Finishes one candidate without settling the shared request. */
|
|
76
|
+
export declare function finishApprovalCandidate(input: {
|
|
77
|
+
readonly candidateId: string;
|
|
78
|
+
readonly completedAt: number;
|
|
79
|
+
readonly reason?: string;
|
|
80
|
+
readonly state: SessionStateMap | undefined;
|
|
81
|
+
readonly status: Exclude<ApprovalCandidateStatus, "pending" | "authorization-required">;
|
|
82
|
+
}): SessionStateMap | undefined;
|
|
83
|
+
/** Expires active candidates whose deterministic deadline has passed. */
|
|
84
|
+
export declare function expireApprovalCandidates(input: {
|
|
85
|
+
readonly now: number;
|
|
86
|
+
readonly state: SessionStateMap | undefined;
|
|
87
|
+
}): SessionStateMap | undefined;
|
|
88
|
+
/** Atomically settles an allowed candidate; every losing candidate becomes stale. */
|
|
89
|
+
export declare function settleAllowedCandidate(input: {
|
|
90
|
+
readonly candidateId: string;
|
|
91
|
+
readonly settledAt: number;
|
|
92
|
+
readonly state: SessionStateMap | undefined;
|
|
93
|
+
}): ApprovalStateTransition;
|
|
94
|
+
/** Atomically settles a direct authenticated approval response. */
|
|
95
|
+
export declare function settleDirectApprovalResponse(input: {
|
|
96
|
+
readonly actor: SessionAuthContext;
|
|
97
|
+
readonly outcome: "allowed" | "cancelled";
|
|
98
|
+
readonly requestId: string;
|
|
99
|
+
readonly settledAt: number;
|
|
100
|
+
readonly state: SessionStateMap | undefined;
|
|
101
|
+
}): ApprovalStateTransition;
|
|
102
|
+
/** Returns one active candidate by id. */
|
|
103
|
+
export declare function getActiveApprovalCandidate(state: SessionStateMap | undefined, candidateId: string): ActiveApprovalCandidate | undefined;
|
|
104
|
+
/** Returns a copy of the durable candidate/audit state for inspection and replay. */
|
|
105
|
+
export declare function getApprovalAuditState(state: SessionStateMap | undefined): {
|
|
106
|
+
readonly activeCandidates: readonly ActiveApprovalCandidate[];
|
|
107
|
+
readonly candidateHistory: readonly ApprovalCandidateAuditRecord[];
|
|
108
|
+
readonly settlements: readonly ApprovalSettlementAuditRecord[];
|
|
109
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const APPROVAL_STATE_KEY=`eve.runtime.hitl.approvalState`;function createApprovalCandidate(e){let t=expireApprovalCandidates({now:e.createdAt,state:e.state}),n=readApprovalState(t);if(n.settlements[e.requestId]!==void 0)return{changed:!1,state:t};let r=e.responder;if(Object.values(n.activeCandidates).find(t=>t.requestId===e.requestId&&sameResponder(t.responder,r))!==void 0)return{changed:!1,state:t};let i=n.activeCandidates[e.candidateIdPrefix]!==void 0||n.candidateHistory.some(t=>t.candidateId===e.candidateIdPrefix)?`${e.candidateIdPrefix}.${n.nextCandidateSequence.toString(36)}`:e.candidateIdPrefix;if(n.activeCandidates[i]!==void 0||n.candidateHistory.some(e=>e.candidateId===i))throw Error(`Approval candidate id collision: "${i}".`);let a={candidateId:i,createdAt:e.createdAt,expiresAt:e.expiresAt,requestId:e.requestId,responder:r,status:`pending`};return{changed:!0,state:writeApprovalState(t,{...n,activeCandidates:{...n.activeCandidates,[a.candidateId]:a},nextCandidateSequence:n.nextCandidateSequence+1})}}function markApprovalCandidatePendingEventEmitted(e){let t=readApprovalState(e.state),n=t.activeCandidates[e.candidateId];return n===void 0||n.pendingEventEmitted===!0?e.state:writeApprovalState(e.state,{...t,activeCandidates:{...t.activeCandidates,[e.candidateId]:{...n,pendingEventEmitted:!0}}})}function markApprovalCandidateHistoryEventEmitted(e){let t=readApprovalState(e.state),n=!1,r=t.candidateHistory.map(t=>t.candidateId!==e.candidateId||t.eventEmitted===!0?t:(n=!0,{...t,eventEmitted:!0}));return n?writeApprovalState(e.state,{...t,candidateHistory:r}):e.state}function markApprovalSettlementEventEmitted(e){let t=readApprovalState(e.state),n=t.settlements[e.requestId];return n===void 0||n.eventEmitted===!0?e.state:writeApprovalState(e.state,{...t,settlements:{...t.settlements,[e.requestId]:{...n,eventEmitted:!0}}})}function markApprovalCandidateAuthorizationRequired(e){let t=readApprovalState(e.state),n=t.activeCandidates[e.candidateId];if(n===void 0)return e.state;let r={...n,authorizationChallenges:e.authorizationChallenges,expiresAt:e.expiresAt??n.expiresAt,status:`authorization-required`};return writeApprovalState(e.state,{...t,activeCandidates:{...t.activeCandidates,[e.candidateId]:r}})}function finishApprovalCandidate(e){let t=readApprovalState(e.state),n=t.activeCandidates[e.candidateId];if(n===void 0)return e.state;let r={...t.activeCandidates};return delete r[e.candidateId],writeApprovalState(e.state,{...t,activeCandidates:r,candidateHistory:[...t.candidateHistory,toCandidateAuditRecord({candidate:n,completedAt:e.completedAt,reason:e.reason,status:e.status})]})}function expireApprovalCandidates(e){let t=e.state,n=Object.values(readApprovalState(t).activeCandidates);for(let r of n)r.expiresAt>e.now||(t=finishApprovalCandidate({candidateId:r.candidateId,completedAt:e.now,state:t,status:`timed-out`}));return t}function settleAllowedCandidate(e){let t=expireApprovalCandidates({now:e.settledAt,state:e.state}),n=readApprovalState(t),r=n.activeCandidates[e.candidateId];if(r===void 0){let r=n.candidateHistory.find(t=>t.candidateId===e.candidateId);if((r&&n.settlements[r.requestId])!==void 0)return{changed:!1,state:t};throw Error(`Unknown approval candidate "${e.candidateId}".`)}return settleRequest({actor:projectResponder(r.responder),candidateId:r.candidateId,outcome:`allowed`,requestId:r.requestId,settledAt:e.settledAt,state:t})}function settleDirectApprovalResponse(e){let t=expireApprovalCandidates({now:e.settledAt,state:e.state});return settleRequest({actor:projectResponder(e.actor),outcome:e.outcome,requestId:e.requestId,settledAt:e.settledAt,state:t})}function getActiveApprovalCandidate(e,t){return readApprovalState(e).activeCandidates[t]}function getApprovalAuditState(e){let t=readApprovalState(e);return{activeCandidates:Object.values(t.activeCandidates),candidateHistory:t.candidateHistory,settlements:Object.values(t.settlements)}}function settleRequest(e){let t=readApprovalState(e.state);if(t.settlements[e.requestId]!==void 0)return{changed:!1,state:e.state};let n={actor:e.actor,candidateId:e.candidateId,outcome:e.outcome,requestId:e.requestId,settledAt:e.settledAt},r={},i=[...t.candidateHistory];for(let n of Object.values(t.activeCandidates)){if(n.requestId!==e.requestId){r[n.candidateId]=n;continue}i.push(toCandidateAuditRecord({candidate:n,completedAt:e.settledAt,status:n.candidateId===e.candidateId?`allowed`:`stale`}))}let a={activeCandidates:r,candidateHistory:i,nextCandidateSequence:t.nextCandidateSequence,settlements:{...t.settlements,[e.requestId]:n}};return{changed:!0,state:writeApprovalState(e.state,a)}}function toCandidateAuditRecord(e){let{authorizationChallenges:t,responder:n,...r}=e.candidate;return{...r,completedAt:e.completedAt,responder:projectResponder(n),reason:e.reason,status:e.status}}function projectResponder(e){return{authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType}}function sameResponder(e,t){return e.authenticator===t.authenticator&&e.issuer===t.issuer&&e.principalId===t.principalId&&e.principalType===t.principalType}function readApprovalState(t){let n=t?.[APPROVAL_STATE_KEY];if(typeof n!=`object`||!n)return{activeCandidates:{},candidateHistory:[],nextCandidateSequence:0,settlements:{}};let r=n;return{activeCandidates:typeof r.activeCandidates==`object`&&r.activeCandidates!==null?r.activeCandidates:{},candidateHistory:Array.isArray(r.candidateHistory)?r.candidateHistory:[],nextCandidateSequence:typeof r.nextCandidateSequence==`number`&&Number.isSafeInteger(r.nextCandidateSequence)&&r.nextCandidateSequence>=0?r.nextCandidateSequence:deriveNextCandidateSequence(r),settlements:typeof r.settlements==`object`&&r.settlements!==null?r.settlements:{}}}function deriveNextCandidateSequence(e){return Object.keys(e.activeCandidates??{}).length+(Array.isArray(e.candidateHistory)?e.candidateHistory.length:0)}function writeApprovalState(t,n){return{...t,[APPROVAL_STATE_KEY]:n}}export{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,markApprovalCandidateHistoryEventEmitted,markApprovalCandidatePendingEventEmitted,markApprovalSettlementEventEmitted,settleAllowedCandidate,settleDirectApprovalResponse};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type AuthorizationChallenge } from "#harness/authorization.js";
|
|
2
|
+
import type { HarnessSession, HarnessToolMap, StepInput } from "#harness/types.js";
|
|
3
|
+
export interface ApprovalDeliveryResult {
|
|
4
|
+
readonly challenges: readonly AuthorizationChallenge[];
|
|
5
|
+
readonly feedback: readonly string[];
|
|
6
|
+
readonly kind: "continue" | "continue-coordination" | "authorization-required" | "park";
|
|
7
|
+
readonly session: HarnessSession;
|
|
8
|
+
readonly stepInput?: StepInput;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Advances approval state by one durable phase.
|
|
12
|
+
*
|
|
13
|
+
* | State | Input | Transition |
|
|
14
|
+
* | --- | --- | --- |
|
|
15
|
+
* | pending request | Approve | create responder-bound candidate |
|
|
16
|
+
* | pending request | Cancel | settle cancelled and stale candidates |
|
|
17
|
+
* | pending candidate | coordinator pass | run current authorizer |
|
|
18
|
+
* | pending candidate | allowed | settle approved and stale competitors |
|
|
19
|
+
* | pending candidate | rejected/error/expiry | append terminal history |
|
|
20
|
+
* | pending candidate | authorization required | persist private challenge |
|
|
21
|
+
* | authorization required | matching callback | re-run current authorizer |
|
|
22
|
+
* | settled request | any later response | no state change |
|
|
23
|
+
*
|
|
24
|
+
* Delivery ingestion returns before authorizer work so Cancel and candidate
|
|
25
|
+
* creation commit before long-running policy execution. Candidate results also
|
|
26
|
+
* commit before lifecycle events are projected by the next stack layer.
|
|
27
|
+
*/
|
|
28
|
+
/** Returns whether this invocation should prepare tools for persisted policy work. */
|
|
29
|
+
export declare function shouldPrepareApprovalPolicyTools(input: {
|
|
30
|
+
readonly now?: number;
|
|
31
|
+
readonly session: HarnessSession;
|
|
32
|
+
readonly stepInput?: StepInput;
|
|
33
|
+
}): boolean;
|
|
34
|
+
export declare function coordinateApprovalDelivery(input: {
|
|
35
|
+
readonly now?: number;
|
|
36
|
+
readonly session: HarnessSession;
|
|
37
|
+
readonly stepInput?: StepInput;
|
|
38
|
+
readonly tools: HarnessToolMap;
|
|
39
|
+
}): Promise<ApprovalDeliveryResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AuthKey,SessionKey}from"#context/keys.js";import{contextStorage}from"#context/container.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{buildApprovalResponseAuth,handleApprovalResponsePolicyError}from"#execution/tool-auth.js";import{clearPendingAuthorization,getAuthorizationResult,getPendingAuthorization,isAuthorizationSignal}from"#harness/authorization.js";import{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,settleAllowedCandidate,settleDirectApprovalResponse}from"#harness/approval-candidates.js";import{isApprovalRequest}from"#harness/input-request-class.js";import{getPendingInputBatches}from"#harness/pending-input-batches.js";const UNAUTHENTICATED_APPROVAL_FEEDBACK=`Authentication is required to respond to this approval.`;function shouldPrepareApprovalPolicyTools(e){let t=getPendingInputBatches(e.session.state),n=[...(e.stepInput?.attributedInputResponses??[]).map(({response:e})=>e),...e.stepInput?.inputResponses??[]];if(t.some(e=>e.requests.some(e=>isApprovalRequest(e)&&n.some(t=>t.requestId===e.requestId))))return!1;let r=e.now??Date.now();return getApprovalAuditState(e.session.state).activeCandidates.some(e=>e.expiresAt>r&&(e.status===`pending`||(e.authorizationChallenges?.some(e=>getAuthorizationResult(e.name)!==void 0)??!1)))}async function coordinateApprovalDelivery(i){let a=i.now??Date.now(),l=getApprovalAuditState(i.session.state).activeCandidates.filter(e=>e.expiresAt<=a).flatMap(e=>e.authorizationChallenges?.map(e=>e.name)??[]),u=expireApprovalCandidates({now:a,state:i.session.state}),d={...i.session,state:clearPendingAuthorization(u,l)},f=getApprovalAuditState(d.state),p=getPendingInputBatches(d.state),m=new Set(p.flatMap(e=>e.requests.map(e=>e.requestId))),h=new Set(f.settlements.filter(e=>e.outcome===`allowed`&&m.has(e.requestId)).map(e=>e.requestId)),g=new Set(f.settlements.map(e=>e.requestId)),_=hasResponseForRequest(i.stepInput,g),v=_?removeConsumedResponses(i.stepInput,g):i.stepInput;if(_&&h.size===0&&!hasMeaningfulInput(v))return deliveryResult(d,v,`park`);if(p.length===0)return deliveryResult(d,v);let y=v,b=new Set(p.flatMap(e=>e.responseAuthRequiredRequestIds??[])),x=p.flatMap(e=>e.requests),S=new Map(x.map(e=>[e.requestId,e]));if(y?.message!==void 0&&(y.attributedInputResponses?.length??0)===0&&(y.inputResponses?.length??0)===0&&f.activeCandidates.length===0&&b.size>0)return deliveryResult(d,{...y,message:void 0,messageAuth:void 0},`park`,[],[`Please use the Approve or Cancel buttons to respond to this approval.`]);let C=[],w=[],T=new Set,E=!1,D=getApprovalAuditState(d.state).activeCandidates,O=[...y?.attributedInputResponses??[],...(y?.inputResponses??[]).map(e=>({auth:void 0,response:e}))];for(let{auth:i,response:o}of O){let s=S.get(o.requestId);if(s===void 0||!isApprovalRequest(s))continue;if(!b.has(o.requestId)){let r=contextStorage.getStore(),s=i===void 0?r?.get(AuthKey)??r?.get(SessionKey)?.auth.current??null:i;if(s!==null&&(o.optionId===`approve`||o.optionId===`cancel`)){let e=settleDirectApprovalResponse({actor:s,outcome:o.optionId===`approve`?`allowed`:`cancelled`,requestId:o.requestId,settledAt:a,state:d.state});d={...d,state:e.state},E||=e.changed}continue}if(T.add(o.requestId),o.optionId===`cancel`){let e=i===void 0?buildCallbackContext().session.auth.current:i;if(e===null){w.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let t=settleDirectApprovalResponse({actor:e,outcome:`cancelled`,requestId:o.requestId,settledAt:a,state:d.state});d={...d,state:t.state},E||=t.changed;continue}if(o.optionId!==`approve`)continue;let c=i===void 0?buildCallbackContext().session.auth.current:i;if(c===null){w.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let l=createApprovalCandidate({candidateIdPrefix:approvalCandidateIdPrefix(s.requestId,c),createdAt:a,expiresAt:a+6e5,requestId:s.requestId,responder:c,state:d.state});d={...d,state:l.state},E||=l.changed}let k=removeConsumedResponses(y,T);if(T.size>0)return deliveryResult(d,k,E?`continue-coordination`:`continue`,[],w);if(E)return deliveryResult(d,k,`continue`,[],w);let A=new Set(getPendingAuthorization(d.state)?.challenges.map(e=>e.name)??[]);for(let e of D){if(e.status===`authorization-required`){let t=e.authorizationChallenges??[];if(!t.some(e=>getAuthorizationResult(e.name)!==void 0)){C.push(...t.filter(e=>!A.has(e.name)));continue}}let t=S.get(e.requestId);if(t===void 0||getActiveApprovalCandidate(d.state,e.candidateId)===void 0)continue;let n=await authorizeCandidate({candidateId:e.candidateId,now:a,request:t,responder:e.responder,session:d,tools:i.tools});d=n.session,E||=n.didCommit,C.push(...n.challenges),getApprovalAuditState(d.state).settlements.find(t=>t.requestId===e.requestId)?.outcome===`allowed`&&h.add(e.requestId)}let j=appendAllowedResponses(k,h);return h.size>0?deliveryResult(d,j,`continue`):E?deliveryResult(d,j,`continue-coordination`):deliveryResult(d,j,C.length>0?`authorization-required`:`continue`,C)}async function authorizeCandidate(e){let t={...e.session,state:expireApprovalCandidates({now:e.now,state:e.session.state})};if(getActiveApprovalCandidate(t.state,e.candidateId)===void 0)return{challenges:[],didCommit:!1,session:t};let n=e.tools.get(e.request.action.toolName)?.approval,o=n!==void 0&&typeof n!=`function`?n.response:void 0;if(o===void 0)return failCandidate({...e,reason:`Approval authorization is temporarily unavailable. Please try again.`,session:t});try{let n=buildCallbackContext(),a=await withAuthorizerTimeout(o({auth:buildApprovalResponseAuth({responder:e.responder,scope:e.candidateId}),request:{callId:e.request.action.callId,requestId:e.request.requestId,toolInput:e.request.action.input,toolName:e.request.action.toolName},response:{decision:`approve`},responder:e.responder,session:{id:n.session.id,initiator:n.session.auth.initiator,parent:n.session.parent,turn:n.session.turn}}));if(a.status===`rejected`)return t={...t,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:a.reason,state:t.state,status:`rejected`})},{challenges:[],didCommit:!0,session:t};if(a.status!==`allowed`)return failCandidate({...e,session:t});let s=settleAllowedCandidate({candidateId:e.candidateId,settledAt:e.now,state:t.state});return{challenges:[],didCommit:s.changed,session:{...t,state:s.state}}}catch(n){let r=await handleApprovalResponsePolicyError(n).catch(()=>void 0);if(isAuthorizationSignal(r)){let n=r.challenges.map(e=>Date.parse(e.challenge.expiresAt??``)).filter(Number.isFinite).sort((e,t)=>e-t)[0];return t={...t,state:markApprovalCandidateAuthorizationRequired({authorizationChallenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),candidateId:e.candidateId,expiresAt:n,state:t.state})},{challenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),didCommit:!0,session:t}}return failCandidate({...e,session:t})}}function failCandidate(e){let t=e.reason??`We couldn’t verify your approval. Please try again.`;return{challenges:[],didCommit:!0,session:{...e.session,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:t,state:e.session.state,status:`failed`})}}}function hasResponseForRequest(e,t){return e?.attributedInputResponses?.some(({response:e})=>t.has(e.requestId))===!0||e?.inputResponses?.some(e=>t.has(e.requestId))===!0}function hasMeaningfulInput(e){return e?.message!==void 0||(e?.attributedInputResponses?.length??0)>0||(e?.inputResponses?.length??0)>0||(e?.runtimeActionResults?.length??0)>0}function appendAllowedResponses(e,t){return t.size===0?e:{...e,inputResponses:[...e?.inputResponses??[],...[...t].map(e=>({optionId:`approve`,requestId:e}))]}}function removeConsumedResponses(e,t){if(e===void 0)return;let n=(e.attributedInputResponses??[]).filter(({response:e})=>!t.has(e.requestId)),r=[...(e.inputResponses??[]).filter(e=>!t.has(e.requestId)),...n.map(({response:e})=>e)];return{...e,attributedInputResponses:void 0,inputResponses:r}}function deliveryResult(e,t,n=`continue`,r=[],i=[]){return{challenges:r,feedback:i,kind:n,session:e,stepInput:t}}function approvalCandidateIdPrefix(e,t){let n=[t.authenticator,t.issuer??``,t.principalType,t.principalId].join(`:`);return`${encodeCandidateIdPart(e)}.${encodeCandidateIdPart(n)}`}function encodeCandidateIdPart(e){return Array.from(e,e=>e.codePointAt(0).toString(36)).join(`-`)}async function withAuthorizerTimeout(e){let t;try{return await Promise.race([Promise.resolve(e),new Promise((e,n)=>{t=setTimeout(()=>n(Error(`Approval response authorizer timed out.`)),1e4)})])}finally{t!==void 0&&clearTimeout(t)}}export{coordinateApprovalDelivery,shouldPrepareApprovalPolicyTools};
|
|
@@ -39,6 +39,7 @@ declare const AUTHORIZATION_PENDING_BRAND: "__eveAuthorizationPending";
|
|
|
39
39
|
export interface AuthorizationChallenge {
|
|
40
40
|
/** Opaque identity of this exact authorization attempt. */
|
|
41
41
|
readonly attemptId?: string;
|
|
42
|
+
readonly candidateId?: string;
|
|
42
43
|
readonly name: string;
|
|
43
44
|
readonly challenge: ConnectionAuthorizationChallenge;
|
|
44
45
|
readonly hookUrl: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.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 redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}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 consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,i){let a=loadContext(),o=a.get(SessionIdKey),s=a.get(CallbackBaseUrlKey);return!o||!s?void 0:`${s}${createEveConnectionCallbackRoutePath(r,i,authHookToken(o))}`}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`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){let n=getPendingAuthorization(e)?.challenges??[],r=getSupersededAuthorizationChallenges(e,t.challenges);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...n.filter(e=>!r.includes(e)),...t.challenges]}}}function getSupersededAuthorizationChallenges(e,t){return(getPendingAuthorization(e)?.challenges??[]).filter(e=>t.some(t=>e.name===t.name&&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(e.attemptId??e.name));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 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{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.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 redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}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 consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,i){let a=loadContext(),o=a.get(SessionIdKey),s=a.get(CallbackBaseUrlKey);return!o||!s?void 0:`${s}${createEveConnectionCallbackRoutePath(r,i,authHookToken(o))}`}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`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){let n=getPendingAuthorization(e)?.challenges??[],r=getSupersededAuthorizationChallenges(e,t.challenges);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...n.filter(e=>!r.includes(e)),...t.challenges]}}}function getSupersededAuthorizationChallenges(e,t){return(getPendingAuthorization(e)?.challenges??[]).filter(e=>t.some(t=>e.name===t.name&&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(e.attemptId??e.name));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 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{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DeliverHookPayload } from "#channel/types.js";
|
|
2
|
+
import type { AlsContext } from "#context/container.js";
|
|
3
|
+
import type { InstrumentationChannelDeliveryOutcome, InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
|
|
4
|
+
interface ChannelDeliveryStartInstrumentation {
|
|
5
|
+
readonly agentName?: string;
|
|
6
|
+
readonly ctx: AlsContext;
|
|
7
|
+
readonly delivery: DeliverHookPayload;
|
|
8
|
+
readonly hooks: InstrumentationHooks | undefined;
|
|
9
|
+
readonly rootSessionId: string;
|
|
10
|
+
readonly sequence: number;
|
|
11
|
+
readonly sessionId: string;
|
|
12
|
+
readonly turnId: string;
|
|
13
|
+
}
|
|
14
|
+
interface ChannelDeliveryTerminalInstrumentation {
|
|
15
|
+
readonly ctx: AlsContext;
|
|
16
|
+
readonly error?: unknown;
|
|
17
|
+
readonly errorCode?: string;
|
|
18
|
+
readonly hooks: InstrumentationHooks | undefined;
|
|
19
|
+
readonly includeTurn: boolean;
|
|
20
|
+
readonly outcome: InstrumentationChannelDeliveryOutcome;
|
|
21
|
+
}
|
|
22
|
+
export declare function instrumentChannelDelivery(input: ChannelDeliveryStartInstrumentation): Promise<void>;
|
|
23
|
+
export declare function instrumentChannelDelivery(input: ChannelDeliveryTerminalInstrumentation): Promise<void>;
|
|
24
|
+
export declare function channelDeliveryErrorCode(error: unknown): string;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ActiveChannelDeliveriesKey,ParentTraceContextKey}from"#context/keys.js";import{channelDeliveryIdempotencyKey}from"#harness/instrumentation/lifecycle.js";async function instrumentChannelDelivery(n){if(!(`delivery`in n)){let t=n.ctx.get(ActiveChannelDeliveriesKey);if(t===void 0||n.hooks===void 0)return;let r=`channel.delivery.${n.outcome}`;for(let e of t)await n.hooks.publish({agentName:e.agentName,delivery:e.delivery,error:n.error,errorCode:n.errorCode,idempotencyKey:channelDeliveryIdempotencyKey(e.sessionId,e.delivery.deliveryId),outcome:n.outcome,rootSessionId:e.rootSessionId,sequence:n.includeTurn?e.sequence:void 0,sessionId:e.sessionId,turnId:n.includeTurn?e.turnId:void 0,type:r});n.ctx.delete(ActiveChannelDeliveriesKey);return}if(n.hooks===void 0||n.delivery.deliveryMetadata===void 0)return;let r=[];for(let e of n.delivery.deliveryMetadata){let i=n.delivery.payloads[e.payloadIndex],a={channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,requestId:e.requestId,requestTraceContext:e.requestTraceContext},o=!n.hooks.capturesContent||i===void 0?void 0:projectDeliveryInput(i),s={agentName:n.agentName,delivery:a,rootSessionId:n.rootSessionId,sequence:n.sequence,sessionId:n.sessionId,turnId:n.turnId};r.push(s),await n.hooks.publish({agentName:s.agentName,delivery:a,idempotencyKey:channelDeliveryIdempotencyKey(n.sessionId,a.deliveryId),input:o,parentTraceContext:n.ctx.get(ParentTraceContextKey),rootSessionId:n.rootSessionId,sessionId:n.sessionId,type:`channel.delivery.started`})}r.length>0&&n.ctx.set(ActiveChannelDeliveriesKey,r)}function projectDeliveryInput(e){let t={};return e.context!==void 0&&(t.context=e.context),e.message!==void 0&&(t.message=e.message),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.inputResponses!==void 0&&(t.inputResponses=e.inputResponses.map(e=>{let t={};return e.optionId!==void 0&&(t.optionId=e.optionId),e.text!==void 0&&(t.text=e.text),t})),t}function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}export{channelDeliveryErrorCode,instrumentChannelDelivery};
|
|
@@ -5,7 +5,7 @@ type ToolResponsePart = Extract<ModelMessage, {
|
|
|
5
5
|
type InlineToolResultPart = Extract<ToolResponsePart, {
|
|
6
6
|
type: "tool-result";
|
|
7
7
|
}>;
|
|
8
|
-
import type { AssistantStepFinishReason, RuntimeIdentity } from "#protocol/message.js";
|
|
8
|
+
import type { AssistantStepFinishReason, RuntimeIdentity, RuntimeTraceContext } from "#protocol/message.js";
|
|
9
9
|
import type { RunMode } from "#shared/run-mode.js";
|
|
10
10
|
import type { JsonObject } from "#shared/json.js";
|
|
11
11
|
import type { HarnessEmissionState } from "#harness/emission-state.js";
|
|
@@ -16,7 +16,7 @@ export type { HarnessEmissionState } from "#harness/emission-state.js";
|
|
|
16
16
|
* Emits `session.started` (once), `turn.started`, and `message.received` at the
|
|
17
17
|
* beginning of a new turn. Returns updated emission state.
|
|
18
18
|
*/
|
|
19
|
-
export declare function emitTurnPreamble(emitFn: HarnessEmitFn, input: StepInput, state: HarnessEmissionState, runtimeIdentity?: RuntimeIdentity): Promise<HarnessEmissionState>;
|
|
19
|
+
export declare function emitTurnPreamble(emitFn: HarnessEmitFn, input: StepInput, state: HarnessEmissionState, runtimeIdentity?: RuntimeIdentity, traceContext?: RuntimeTraceContext): Promise<HarnessEmissionState>;
|
|
20
20
|
/**
|
|
21
21
|
* Emits `step.started` for one model call.
|
|
22
22
|
*/
|