eve 0.47.2 → 0.47.5
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 +36 -0
- package/bin/eve.js +4 -0
- package/dist/src/channel/activity-renderer.d.ts +21 -0
- package/dist/src/channel/activity-renderer.js +1 -0
- package/dist/src/channel/activity-sink.d.ts +2 -0
- package/dist/src/channel/activity-sink.js +1 -0
- package/dist/src/channel/auth/oidc.js +1 -1
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/compiled-channel.d.ts +2 -0
- package/dist/src/channel/compiled-channel.js +2 -2
- package/dist/src/channel/forwarded-principal.js +1 -1
- package/dist/src/channel/session.d.ts +3 -2
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +11 -0
- package/dist/src/chunks/{use-eve-agent-CacMaX4P.js → use-eve-agent-DjYwFJF7.js} +1 -0
- package/dist/src/chunks/{use-eve-agent-kmlFdOBB.js → use-eve-agent-DkUB0Ok4.js} +1 -0
- package/dist/src/cli/dev/tui/status-line.d.ts +6 -0
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +37 -0
- package/dist/src/compiled/@vercel/otel/index.d.ts +11 -0
- package/dist/src/compiler/extension-compatibility.d.ts +11 -9
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +14 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-connection.d.ts +9 -2
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/compiler/validate-artifact.js +1 -1
- package/dist/src/context/dynamic-connection-lifecycle.d.ts +9 -0
- package/dist/src/context/dynamic-connection-lifecycle.js +1 -0
- package/dist/src/context/keys.d.ts +5 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/context/providers/connection.js +1 -1
- package/dist/src/dynamic/definition.d.ts +6 -3
- package/dist/src/dynamic/definition.js +1 -1
- package/dist/src/eve-channel/activity-observer-request.d.ts +7 -0
- package/dist/src/eve-channel/activity-observer-request.js +1 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.d.ts +3 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/activity-collector.d.ts +12 -0
- package/dist/src/execution/activity-collector.js +1 -0
- package/dist/src/execution/activity-events.d.ts +7 -0
- package/dist/src/execution/activity-events.js +1 -0
- package/dist/src/execution/activity-route.d.ts +2 -0
- package/dist/src/execution/activity-route.js +1 -0
- package/dist/src/execution/activity-text.d.ts +3 -0
- package/dist/src/execution/activity-text.js +1 -0
- package/dist/src/execution/activity-work-id.d.ts +9 -0
- package/dist/src/execution/activity-work-id.js +1 -0
- package/dist/src/execution/activity-work.d.ts +20 -0
- package/dist/src/execution/activity-work.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.d.ts +3 -1
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/cancelled-turn-message.d.ts +2 -0
- package/dist/src/execution/cancelled-turn-message.js +1 -0
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +8 -0
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dynamic-connections.d.ts +9 -0
- package/dist/src/execution/dynamic-connections.js +1 -0
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/node-step.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +3 -1
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
- package/dist/src/execution/session-activity-projection.d.ts +14 -0
- package/dist/src/execution/session-activity-projection.js +1 -0
- package/dist/src/execution/session-activity-renderer-step.d.ts +15 -0
- package/dist/src/execution/session-activity-renderer-step.js +1 -0
- package/dist/src/execution/session-activity.d.ts +6 -0
- package/dist/src/execution/session-activity.js +1 -0
- package/dist/src/execution/session-callback-request.d.ts +1 -0
- package/dist/src/execution/session-callback-request.js +1 -1
- package/dist/src/execution/session-callback-route.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-start-local.d.ts +1 -0
- package/dist/src/execution/subagent-start-local.js +1 -1
- package/dist/src/execution/subagent-start-remote.d.ts +1 -0
- package/dist/src/execution/subagent-start-remote.js +1 -1
- package/dist/src/execution/subagent-tool.d.ts +2 -1
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/execution/submit-activity.d.ts +7 -0
- package/dist/src/execution/submit-activity.js +1 -0
- package/dist/src/execution/tasks/child/steps.d.ts +8 -0
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/update.js +1 -1
- package/dist/src/execution/tasks/child/workflow.d.ts +3 -0
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/delegate.d.ts +3 -0
- package/dist/src/execution/tasks/parent/delegate.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/tools/connection-search.js +2 -2
- package/dist/src/execution/tools/load-skill.js +1 -1
- package/dist/src/execution/tools/subagent/local.js +1 -1
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/web-fetch/request.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
- package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.d.ts +4 -0
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v2.d.ts +478 -0
- package/dist/src/execution/wire/session-inbox-wire.v2.js +1 -0
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +4 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/execution/workflow-trace-context.d.ts +3 -6
- package/dist/src/execution/workflow-trace-context.js +1 -1
- package/dist/src/harness/approval-delivery-coordinator.js +1 -1
- package/dist/src/harness/authorization.d.ts +11 -4
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/inline-tool-authorization.d.ts +13 -1
- package/dist/src/harness/inline-tool-authorization.js +1 -1
- package/dist/src/harness/model-call-error.js +1 -1
- package/dist/src/harness/semantic-errors/rule.d.ts +5 -2
- package/dist/src/harness/semantic-errors/rules/gateway.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tool-model-output.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +1 -1
- package/dist/src/harness/types.d.ts +2 -2
- package/dist/src/{harness → instrumentation}/ai-sdk-hook-bridge.d.ts +1 -1
- package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -0
- package/dist/src/{harness → instrumentation}/ai-sdk-telemetry.d.ts +5 -1
- package/dist/src/instrumentation/ai-sdk-telemetry.js +1 -0
- package/dist/src/{harness/channel-delivery-instrumentation.d.ts → instrumentation/channel-delivery.d.ts} +5 -7
- package/dist/src/instrumentation/channel-delivery.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/config.d.ts +0 -10
- package/dist/src/instrumentation/config.js +1 -0
- package/dist/src/instrumentation/content-policy.d.ts +5 -0
- package/dist/src/instrumentation/content-policy.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/content.d.ts +1 -1
- package/dist/src/{harness/instrumentation → instrumentation}/dispatch.d.ts +1 -1
- package/dist/src/instrumentation/dispatch.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/lifecycle.d.ts +34 -35
- package/dist/src/instrumentation/lifecycle.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/native-events.d.ts +1 -1
- package/dist/src/instrumentation/native-events.js +1 -0
- package/dist/src/{harness → instrumentation}/parent-lineage.d.ts +1 -1
- package/dist/src/instrumentation/prepare-trace-context.d.ts +24 -0
- package/dist/src/instrumentation/prepare-trace-context.js +1 -0
- package/dist/src/instrumentation/provider.d.ts +13 -9
- package/dist/src/{harness/instrumentation → instrumentation}/providers.d.ts +1 -1
- package/dist/src/instrumentation/providers.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/runtime-context.d.ts +13 -2
- package/dist/src/instrumentation/runtime-context.js +1 -0
- package/dist/src/instrumentation/runtime.d.ts +100 -0
- package/dist/src/instrumentation/runtime.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/state.d.ts +2 -11
- package/dist/src/internal/application/compiled-artifacts.js +4 -4
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/instrumentation.d.ts +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +4 -6
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/user-agent.d.ts +2 -0
- package/dist/src/internal/user-agent.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/activity.d.ts +105 -0
- package/dist/src/protocol/activity.js +1 -0
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/routes.d.ts +4 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +6 -3
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/interactions.d.ts +8 -5
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +66 -1
- package/dist/src/public/channels/slack/slash-command.d.ts +9 -0
- package/dist/src/public/channels/slack/slash-command.js +1 -0
- package/dist/src/public/connections/index.d.ts +2 -0
- package/dist/src/public/connections/index.js +1 -1
- package/dist/src/public/definitions/connections/dynamic.d.ts +23 -0
- package/dist/src/public/definitions/connections/dynamic.js +1 -0
- package/dist/src/public/definitions/connections/mcp.d.ts +8 -0
- package/dist/src/public/definitions/connections/openapi.d.ts +8 -0
- package/dist/src/public/definitions/connections/protocol.d.ts +6 -0
- package/dist/src/public/definitions/connections/protocol.js +1 -1
- package/dist/src/runtime/channels/registry.js +1 -1
- package/dist/src/runtime/connections/authorization-tokens.d.ts +11 -10
- package/dist/src/runtime/connections/instance-identity.d.ts +12 -0
- package/dist/src/runtime/connections/instance-identity.js +1 -0
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/registry.d.ts +2 -0
- package/dist/src/runtime/connections/registry.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +10 -6
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-connection.d.ts +5 -0
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/resolve-dynamic-connection.d.ts +5 -0
- package/dist/src/runtime/resolve-dynamic-connection.js +1 -0
- package/dist/src/runtime/subagents/dynamic-remote-agent-config.js +1 -1
- package/dist/src/runtime/types.d.ts +11 -0
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/gateway-models.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +9 -5
- package/dist/src/shared/trace-policy.d.ts +20 -0
- package/dist/src/shared/trace-policy.js +1 -0
- 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 +1 -1
- package/dist/src/tracing/agent-action-instrumentation.js +1 -1
- package/dist/src/tracing/agent-approval-instrumentation.d.ts +1 -3
- package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
- package/dist/src/tracing/agent-otel-provider.d.ts +4 -4
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-runtime-context.d.ts +5 -0
- package/dist/src/tracing/agent-otel-runtime-context.js +1 -0
- package/dist/src/tracing/agent-otel-session-context.d.ts +3 -3
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-otel-usage.d.ts +4 -2
- package/dist/src/tracing/agent-otel-usage.js +1 -1
- package/dist/src/tracing/agent-span-id-generator.d.ts +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.d.ts +6 -0
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/agent-trace-context.d.ts +3 -0
- package/dist/src/tracing/agent-trace-context.js +1 -0
- package/dist/src/tracing/agent-trace-state.d.ts +10 -1
- package/dist/src/tracing/agent-trace-state.js +1 -1
- package/dist/src/tracing/install-instrumentation-runtime.d.ts +3 -2
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
- 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-trace-reader.d.ts +1 -0
- package/dist/src/tracing/local-trace-reader.js +1 -1
- package/dist/src/tracing/otel-declaration.d.ts +20 -19
- package/dist/src/tracing/otel-declaration.js +1 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/tracing/sampled-trace.d.ts +1 -14
- package/dist/src/tracing/sampled-trace.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/slack.mdx +25 -5
- package/docs/connections/overview.mdx +46 -2
- package/docs/extensions.md +2 -2
- package/docs/getting-started.mdx +1 -1
- package/docs/guides/dynamic-capabilities.md +91 -5
- package/docs/memory.md +7 -4
- package/docs/reference/cli.md +8 -8
- package/docs/reference/typescript-api.md +32 -23
- package/package.json +1 -1
- package/dist/src/execution/subagent-usage-span.d.ts +0 -9
- package/dist/src/execution/subagent-usage-span.js +0 -1
- package/dist/src/harness/ai-sdk-hook-bridge.js +0 -1
- package/dist/src/harness/ai-sdk-telemetry.js +0 -1
- package/dist/src/harness/channel-delivery-instrumentation.js +0 -1
- package/dist/src/harness/instrumentation/config.js +0 -1
- package/dist/src/harness/instrumentation/content-policy.d.ts +0 -7
- package/dist/src/harness/instrumentation/content-policy.js +0 -1
- package/dist/src/harness/instrumentation/dispatch.js +0 -1
- package/dist/src/harness/instrumentation/lifecycle.js +0 -1
- package/dist/src/harness/instrumentation/native-events.js +0 -1
- package/dist/src/harness/instrumentation/providers.js +0 -1
- package/dist/src/harness/instrumentation/runtime-context.js +0 -1
- package/dist/src/harness/instrumentation/runtime.d.ts +0 -21
- package/dist/src/harness/instrumentation/runtime.js +0 -1
- package/dist/src/harness/prepare-trace-context.d.ts +0 -21
- package/dist/src/harness/prepare-trace-context.js +0 -1
- /package/dist/src/{harness/instrumentation → instrumentation}/content.js +0 -0
- /package/dist/src/{harness → instrumentation}/parent-lineage.js +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.d.ts +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.js +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/state.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.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{isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,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{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:c}=getWorkflowMetadata(),d=e.serializedContext[`eve.continuationToken`]||``,f=e.serializedContext[`eve.mode`],p=e.serializedContext[`eve.capabilities`],m=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=s;let g=getWritable(),y={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let a=readRootSessionId(e.serializedContext),o=readSerializedSubagentDepth(e.serializedContext),l=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:u}=await createSessionStep({compiledArtifactsSource:m.source,continuationToken:d,dynamicSubagentAgentConfig:l,inheritedLimits:e.limits,nodeId:m.nodeId,outputSchema:e.input.outputSchema,rootSessionId:a,sessionId:s,subagentDepth:o,taskOwned:isTaskOwnedSerializedContext(e.serializedContext)});y.lastSessionState=u,y.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),y.callerResolved=!0;let h=await runDriverLoop({capabilities:p,driverWritable:g,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:y,mode:f,serializedContext:e.serializedContext,sessionState:u,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(c.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return h.kind===`result`?h.result:await finalizeExpiredSession({caller:y.caller,driverWritable:g,mode:f,serializedContext:h.serializedContext,sessionState:h.sessionState})}catch(t){throw y.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:y.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:g,serializedContext:e.serializedContext}),f===`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(y,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=new Set(e.expectedAttemptIds);for(let e of n.keys())r.has(e)||n.delete(e);for(;;){if(r.size>0&&[...r].every(e=>n.has(e))){let e=[...r].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,commandInbox:u,deferDeliveries:t.mode===`task`&&r.size>0,driverWritable:t.driverWritable,seenTaskDeliveries:l,stateCursor:v});if(e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&r.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}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],o=new Set,l=new Set,u=createSessionCommandInbox(),h=sessionCommandHookToken(t.sessionState.sessionId);await u.claimStable(h),await u.claimAuthorization(`${t.sessionState.sessionId}:auth`);let _=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:h}),v=new SessionStateCursor({serializedContext:t.serializedContext,sessionState:t.sessionState}),y,runTurn=async e=>{let n=t.crashCleanupState.caller;n?.taskId!==void 0&&(l.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:v.sessionState.sessionId,childTurnId:activeTurnId(v.sessionState.emissionState)}));let r=await bindTurnCallerContextStep({caller:n,serializedContext:v.serializedContext}),s=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,capabilities:t.capabilities,commandInbox:u,controlToken:nextTurnControlToken(),delivery:e,mode:t.mode,parentWritable:t.driverWritable,serializedContext:r,seenTaskDeliveries:l,sessionState:v.sessionState});return await y?.(),y=s.dispose,v.adoptState(s.action),t.crashCleanupState.lastSessionState=v.sessionState,s.action};try{if(t.sessionState.continuationToken)try{await u.rekeyContinuation(t.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await _?.start();let e=await runTurn(t.initialInput);for(;;){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 e=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(e);let n={caller:t.crashCleanupState.caller,sessionId:v.sessionState.sessionId};await notifyCancelledTaskCallerStep(e.usage===void 0?n:{...n,usage:e.usage}),t.crashCleanupState.lastSessionState=v.sessionState}v.sessionState.continuationToken&&await u.rekeyContinuation(v.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:v.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[]});if(t.crashCleanupState.lastSessionState=v.sessionState,r.kind===`authorization-resume`){e=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:v.serializedContext,sessionState:v.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:v.serializedContext,sessionState:v.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(n),e={...e,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=v.sessionState;continue}r.delivery.caller!==void 0&&(t.crashCleanupState.caller=r.delivery.caller),e=await runTurn(r.delivery)}}finally{await y?.(),await _?.dispose(),await u.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({serializedContext:e.serializedContext,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({serializedContext:n,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:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage: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{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,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{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:r,workflowStartedAt:c}=getWorkflowMetadata(),d=e.serializedContext[`eve.continuationToken`]||``,f=e.serializedContext[`eve.mode`],p=e.serializedContext[`eve.capabilities`],m=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=r;let g=getWritable(),y={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let t=readRootSessionId(e.serializedContext),n=readSerializedSubagentDepth(e.serializedContext),l=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:u}=await createSessionStep({compiledArtifactsSource:m.source,continuationToken:d,dynamicSubagentAgentConfig:l,inheritedLimits:e.limits,nodeId:m.nodeId,outputSchema:e.input.outputSchema,rootSessionId:t,sessionId:r,subagentDepth:n,taskOwned:isTaskOwnedSerializedContext(e.serializedContext)});y.lastSessionState=u,y.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),y.callerResolved=!0;let h=await runDriverLoop({capabilities:p,driverWritable:g,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:y,mode:f,serializedContext:e.serializedContext,sessionState:u,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(c.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return h.kind===`result`?h.result:await finalizeExpiredSession({caller:y.caller,driverWritable:g,mode:f,serializedContext:h.serializedContext,sessionState:h.sessionState})}catch(t){throw y.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:y.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:g,serializedContext:e.serializedContext}),f===`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(y,e.serializedContext),lifecycle:`terminal`,sessionId:r,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=new Set(e.expectedAttemptIds);for(let e of n.keys())r.has(e)||n.delete(e);for(;;){if(r.size>0&&[...r].every(e=>n.has(e))){let e=[...r].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:a,bufferedSessionControls:o,cancelledTaskIds:s,commandInbox:u,deferDeliveries:t.mode===`task`&&r.size>0,driverWritable:t.driverWritable,seenTaskDeliveries:l,stateCursor:v});if(e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&r.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}}}},i=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(i++)}`,a=[],o=[],s=new Set,l=new Set,u=createSessionCommandInbox(),h=sessionCommandHookToken(t.sessionState.sessionId);await u.claimStable(h),await u.claimAuthorization(`${t.sessionState.sessionId}:auth`);let _=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:h}),v=new SessionStateCursor({serializedContext:t.serializedContext,sessionState:t.sessionState}),y,runTurn=async e=>{let n=t.crashCleanupState.caller;n?.taskId!==void 0&&(l.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:v.sessionState.sessionId,childTurnId:activeTurnId(v.sessionState.emissionState)}));let r=await bindTurnCallerContextStep({caller:n,serializedContext:v.serializedContext}),i=await dispatchAndAwaitTurn({bufferedDeliveries:a,bufferedSessionControls:o,cancelledTaskIds:s,capabilities:t.capabilities,commandInbox:u,controlToken:nextTurnControlToken(),delivery:e,mode:t.mode,parentWritable:t.driverWritable,serializedContext:r,seenTaskDeliveries:l,sessionState:v.sessionState});return await y?.(),y=i.dispose,v.adoptState(i.action),t.crashCleanupState.lastSessionState=v.sessionState,i.action};try{if(t.sessionState.continuationToken)try{await u.rekeyContinuation(t.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await _?.start();let e=await runTurn(t.initialInput);for(;;){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 e=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(e);let n={caller:t.crashCleanupState.caller,sessionId:v.sessionState.sessionId};await notifyCancelledTaskCallerStep(e.usage===void 0?n:{...n,usage:e.usage}),t.crashCleanupState.lastSessionState=v.sessionState}v.sessionState.continuationToken&&await u.rekeyContinuation(v.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:v.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[]});if(t.crashCleanupState.lastSessionState=v.sessionState,r.kind===`authorization-resume`){e=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:v.serializedContext,sessionState:v.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:v.serializedContext,sessionState:v.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(n),e={...e,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=v.sessionState;continue}r.delivery.caller!==void 0&&(t.crashCleanupState.caller=r.delivery.caller),e=await runTurn(r.delivery)}}finally{await y?.(),await _?.dispose(),await u.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({serializedContext:e.serializedContext,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({serializedContext:n,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:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage: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};
|
|
@@ -44,6 +44,10 @@ export declare const sessionTimeoutWorkflowReference: {
|
|
|
44
44
|
export declare const taskRunWorkflowReference: {
|
|
45
45
|
workflowId: string;
|
|
46
46
|
};
|
|
47
|
+
/** Stable workflow reference for root-session activity collectors. */
|
|
48
|
+
export declare const activityCollectorWorkflowReference: {
|
|
49
|
+
workflowId: string;
|
|
50
|
+
};
|
|
47
51
|
/**
|
|
48
52
|
* Creates a workflow-backed runtime whose long-lived driver owns the
|
|
49
53
|
* event stream and dispatches each turn as a child workflow run.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{
|
|
1
|
+
import{randomBytes}from"node:crypto";import{createEveActivityRoutePath}from"#protocol/routes.js";import{createLogger,logError}from"#internal/logging.js";import{getChannelActivityPresentation}from"#channel/activity-renderer.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{ActivityObserverKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{cancelRun,getHookByToken,getRun,getWorld,start}from"#internal/workflow/runtime.js";import{createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{serializeContext}from"#context/serialize.js";import{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{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{initializeSessionInstrumentation}from"#instrumentation/runtime.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";import{isAgentTraceContext}from"#tracing/agent-trace-context.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,ACTIVITY_COLLECTOR_WORKFLOW_NAME=`activityCollectorWorkflow`,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,TASK_RUN_WORKFLOW_NAME,ACTIVITY_COLLECTOR_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}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`},activityCollectorWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`};function createWorkflowRuntime(n){return{async createSession(a){let o=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:n.compiledArtifactsSource,nodeId:n.nodeId}),s=buildRunContext({bundle:o,dynamicSubagentAgentConfig:n.dynamicSubagentAgentConfig,run:a}),c=resolveEffectiveAgentRuntime(o,s);initializeSessionInstrumentation({agentName:c.turnAgent.id,ctx:s,parentTraceContext:a.parentTraceContext});let l=c.limits?.sessionTimeoutMs,u,d=a.activityObserver;if(a.parent===void 0&&d===void 0&&(getChannelActivityPresentation(a.adapter)?.renderers.length??0)>0){let n=serializeContext(s),r=randomBytes(32).toString(`base64url`),i={expiresAt:new Date(Date.now()+(typeof l==`number`?l:864e5)).toISOString(),serializedContext:n,token:r};try{u=(await startWorkflowPreferLatest(activityCollectorWorkflowReference,[i])).runId,d={sink:{url:createWorkflowCallbackUrl(resolveWorkflowCallbackBaseUrl(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:3000`),createEveActivityRoutePath(r)),version:1}},s.set(ActivityObserverKey,d)}catch{await cancelActivityCollector(u),u=void 0,log.warn(`failed to start activity collector`)}}let f=serializeContext(s),p=readParentLineage(f),m={input:a.input,limits:a.limits,serializedContext:f};l!==void 0&&(m.sessionTimeoutMs=l);let h={...p.sessionId===void 0?buildSessionAttributes({inputMessage:a.title??a.input.message,serializedContext:f}):buildSubagentRootAttributes({identity:{nodeId:o.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:p.callId,parentSessionId:p.sessionId,parentTurnId:p.turnId,rootSessionId:p.rootSessionId??p.sessionId,serializedContext:f}),...a.externalInvocation===void 0?{}:buildInvocationAttributes(a.externalInvocation)},g;try{g=await startWorkflowPreferLatest(workflowEntryReference,[m],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(h)})}catch(e){throw await cancelActivityCollector(u),logError(log,`failed to start workflow run`,e,{continuationToken:a.continuationToken}),e}try{if(a.continuationToken){let e=await waitForCommandHookOwner(a.continuationToken);if(e.runId!==g.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:a.continuationToken,ownerSessionId:e.runId,sessionId:g.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(g.runId),g.runId)}catch(e){throw await cancelActivityCollector(u),e}let _,getEvents=()=>(_??=parseNdjsonStream(()=>getRun(g.runId).getReadable()),_);return{get events(){return getEvents()},sessionId:g.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(t){if(HookNotFoundError.is(t))return;throw logError(log,`failed to resolve session by continuation token`,t,{continuationToken:e}),t}}}}async function cancelActivityCollector(e){if(e!==void 0)try{await cancelRun(await getWorld(),e,{cancelReason:`Root session creation did not complete`})}catch{log.warn(`failed to cancel unowned activity collector`)}}async function dispatchWorkflowCommand(e,t){let n;try{n=normalizeWorkflowHook(await resumeSessionInbox(e,t))}catch(n){if(isInactiveCommandTarget(n))return inactiveCommandResult(t);throw logError(log,`failed to dispatch session command`,n,{command:t.kind,token:e}),n}return t.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(n.runId),n.runId),activeCommandResult(t,n.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let n=await waitForCommandHookOwner(e);if(n.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:n.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){let r=context.active(),i=isAgentTraceContext(r)?trace.deleteSpan(r):r;return await context.with(i,async()=>{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,activityCollectorWorkflowReference,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME}from"#tools/framework/task-contract.js";import{coalesceTurnInputs,normalizeUserContent}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-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{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{stageAttachmentsToSandbox}from"#harness/attachment-staging.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&(c.set(TurnTaskDeliveryKey,`none`),c.delete(TurnTaskStateKey));let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&d&&f.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.owner.kind===`framework`&&e.name===TASK_UPDATE_TOOL_NAME);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=getInstrumentationRuntime(),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:v?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:v?.hooks,includeTurn:!1,outcome:`failed`})),await v?.forceFlush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(d&&c.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:s.state,turnId:activeTurnId(y)});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),c.set(TurnTaskStateKey,e.context))}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:v?.hooks,includeTurn:!1,outcome:`completed`})),await v?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),r=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r,tasksEnabled:d}}let S=u.hookRegistry,C=u.resolvedAgent.dynamicInstructionsResolvers??[],w=u.resolvedAgent.dynamicSkillResolvers??[],T=u.subagentRegistry.dynamicResolvers??[],E=u.resolvedAgent.dynamicToolResolvers??[],D={...u.graph.root,turnAgent:f.turnAgent},O=buildRuntimeIdentity(D);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:O});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:_.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:E,event:e,messages:_.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:c,event:createTurnStartedEvent({sequence:y.sequence,turnId:activeTurnId(y)}),messages:_.initial.messages,resolvers:E})}}catch(e){throw await failChannelDeliveries(e),e}let k=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await k.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e),r=await dispatchMemoryLifecycleEvent({abortSignal:o.abortSignal,appRoot:D.agent?.metadata?.appRoot??``,ctx:c,event:e,memories:D.agent?.memories??[],messages:t,nodeId:u.nodeId??`__root__`});await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:r,scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:T,event:n,messages:r}),await dispatchDynamicToolEvent({ctx:c,resolvers:E,event:n,messages:r}),await dispatchDynamicSkillEvent({ctx:c,resolvers:w,event:n,messages:r}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:C,event:n,messages:r})},A=c.require(ModeKey),j;try{throwIfTurnAborted(o.abortSignal),j=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:A,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:O,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,O,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),mode:A,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:D,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;k.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c),r=await preserveCancelledTurnMessage(n?.backgroundTaskSession??g,x);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:r}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:createDurableSessionState({session:r})}}let M=reconcileSessionContinuationToken(c,j.session),N=serializeContext(c);j={...j,session:M};let P=createDurableSessionState({session:j.session}),F=readTurnSleepDurationMs(c),I=F===void 0?{}:{sleepDurationMs:F},L=j.backgroundTasks===void 0||j.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:j.backgroundTaskSession}),backgroundTasks:j.backgroundTasks};if(j.next!==null&&typeof j.next==`object`&&`done`in j.next){if(A===`task`&&hasPendingInputBatch(j.session.state))throw k.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await k.close();let e=getTurnUsageState(j.session.state)?.session;return{action:`done`,...L,output:j.next.output,isError:j.next.isError,...I,serializedContext:N,sessionState:P,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(j.session).delta}}if(j.next===null){k.releaseLock();let e=getPendingWorkflowInterrupt(j.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...L,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...I,serializedContext:N,sessionState:P};let t=derivePendingState(j.session);if(j.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(j.session);return{action:`park`,...L,...t,...I,serializedContext:N,sessionState:createDurableSessionState({session:n}),settled:{output:j.settledTurn.output,isError:j.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...L,...t,...I,serializedContext:N,sessionState:P,tasksEnabled:d}}return k.releaseLock(),{action:`continue`,...L,...I,serializedContext:N,sessionState:P}}async function preserveCancelledTurnMessage(e,t){let n=normalizeUserContent(t?.message);if(n===void 0)return e;let r=await stageAttachmentsToSandbox(n);return{...e,history:[...e.history,{content:r,role:`user`}]}}export{turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{coalesceTurnInputs}from"#harness/messages.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME}from"#tools/framework/task-contract.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{activeTurnId}from"#harness/active-turn-id.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&(c.set(TurnTaskDeliveryKey,`none`),c.delete(TurnTaskStateKey));let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&d&&f.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.owner.kind===`framework`&&e.name===TASK_UPDATE_TOOL_NAME);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=bindSessionInstrumentation({agentName:f.turnAgent.id,ctx:c,rootSessionId:g.rootSessionId??g.sessionId,sessionId:g.sessionId}),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>v?.instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>v?.instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await v?.flush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(d&&c.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:s.state,turnId:activeTurnId(y)});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),c.set(TurnTaskStateKey,e.context))}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>v?.instrumentChannelDelivery({ctx:c,includeTurn:!1,outcome:`completed`})),await v?.flush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),r=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r,tasksEnabled:d}}let S=u.hookRegistry,C=bindDynamicConnections(c,u.resolvedAgent),w=u.resolvedAgent.dynamicInstructionsResolvers??[],T=u.resolvedAgent.dynamicSkillResolvers??[],E=u.subagentRegistry.dynamicResolvers??[],D=u.resolvedAgent.dynamicToolResolvers??[],O={...u.graph.root,turnAgent:f.turnAgent},k=buildRuntimeIdentity(O);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:E,event:e,messages:_.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:D,event:e,messages:_.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:c,event:createTurnStartedEvent({sequence:y.sequence,turnId:activeTurnId(y)}),messages:_.initial.messages,resolvers:D})}}catch(e){throw await failChannelDeliveries(e),e}let A=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await A.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e),r=await dispatchMemoryLifecycleEvent({abortSignal:o.abortSignal,appRoot:O.agent?.metadata?.appRoot??``,ctx:c,event:e,memories:O.agent?.memories??[],messages:t,nodeId:u.nodeId??`__root__`});observeSessionActivity({ctx:c,event:n,sessionId:g.sessionId}),await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:r,scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await C.dispatch(n),await dispatchDynamicSubagentEvent({ctx:c,resolvers:E,event:n,messages:r}),await dispatchDynamicToolEvent({ctx:c,resolvers:D,event:n,messages:r}),await dispatchDynamicSkillEvent({ctx:c,resolvers:T,event:n,messages:r}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:w,event:n,messages:r})},j=c.require(ModeKey),M;try{throwIfTurnAborted(o.abortSignal),M=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:j,session:e});if(await C.rehydrate(y,k,isHarnessBetweenTurns(t)),h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:v});try{e=await emitTurnPreamble(handleEvent,{},e,k,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),instrumentation:v,mode:j,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:O,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;A.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c),r=await preserveCancelledTurnMessage(n?.backgroundTaskSession??g,x);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:r}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:createDurableSessionState({session:r})}}let N=reconcileSessionContinuationToken(c,M.session),P=serializeContext(c);M={...M,session:N};let F=createDurableSessionState({session:M.session}),I=readTurnSleepDurationMs(c),L=I===void 0?{}:{sleepDurationMs:I},R=M.backgroundTasks===void 0||M.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:M.backgroundTaskSession}),backgroundTasks:M.backgroundTasks};if(M.next!==null&&typeof M.next==`object`&&`done`in M.next){if(j===`task`&&hasPendingInputBatch(M.session.state))throw A.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await A.close();let e=getTurnUsageState(M.session.state)?.session;return{action:`done`,...R,output:M.next.output,isError:M.next.isError,...L,serializedContext:P,sessionState:F,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(M.session).delta}}if(M.next===null){A.releaseLock();let e=getPendingWorkflowInterrupt(M.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...R,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...L,serializedContext:P,sessionState:F};let t=derivePendingState(M.session);if(M.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(M.session);return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:createDurableSessionState({session:n}),settled:{output:M.settledTurn.output,isError:M.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:F,tasksEnabled:d}}return A.releaseLock(),{action:`continue`,...R,...L,serializedContext:P,sessionState:F}}export{turnStep};
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import type { ContextContainer } from "#context/container.js";
|
|
2
1
|
import type { HarnessEmissionState } from "#harness/emission.js";
|
|
3
|
-
import type {
|
|
4
|
-
import type {
|
|
2
|
+
import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";
|
|
3
|
+
import type { RuntimeTraceContext } from "#protocol/message.js";
|
|
5
4
|
/** Prepares native tracing for workflow-owned preambles emitted outside the tool loop. */
|
|
6
5
|
export declare function prepareWorkflowPreambleTrace(input: {
|
|
7
|
-
readonly ctx: ContextContainer;
|
|
8
6
|
readonly emissionState: HarnessEmissionState;
|
|
9
|
-
readonly
|
|
10
|
-
readonly session: HarnessSession;
|
|
7
|
+
readonly instrumentation: ExecutionInstrumentation | undefined;
|
|
11
8
|
}): Promise<RuntimeTraceContext | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
async function prepareWorkflowPreambleTrace(e){return await e.instrumentation?.preparePreamble({sequence:e.emissionState.sequence,sessionStarted:e.emissionState.sessionStarted,turnId:`turn_${e.emissionState.sequence}`})}export{prepareWorkflowPreambleTrace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.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=f.settlements.filter(e=>m.has(e.requestId)),g=new Set(f.settlements.map(e=>e.requestId)),_=hasResponseForRequest(i.stepInput,g),v=_?removeConsumedResponses(i.stepInput,g):i.stepInput;if(_&&h.length===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]))
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.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=f.settlements.filter(e=>m.has(e.requestId)),g=new Set(f.settlements.map(e=>e.requestId)),_=hasResponseForRequest(i.stepInput,g),v=_?removeConsumedResponses(i.stepInput,g):i.stepInput;if(_&&h.length===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])),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);let r=getApprovalAuditState(d.state).settlements.find(t=>t.requestId===e.requestId);r!==void 0&&h.push(r)}let j=appendSettledResponses(k,h);return h.length>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 appendSettledResponses(e,t){return t.length===0?e:{...e,inputResponses:[...e?.inputResponses??[],...t.map(e=>({optionId:e.outcome===`allowed`?`approve`:`cancel`,requestId:e.requestId}))]}}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};
|
|
@@ -40,6 +40,8 @@ export interface AuthorizationChallenge {
|
|
|
40
40
|
/** Opaque identity of this exact authorization attempt. */
|
|
41
41
|
readonly attemptId?: string;
|
|
42
42
|
readonly candidateId?: string;
|
|
43
|
+
/** Opaque resolved connection identity; omitted for tool-hosted authorization. */
|
|
44
|
+
readonly instanceId?: string;
|
|
43
45
|
readonly name: string;
|
|
44
46
|
readonly challenge: ConnectionAuthorizationChallenge;
|
|
45
47
|
readonly hookUrl: string;
|
|
@@ -65,6 +67,7 @@ export interface AuthorizationPendingModelOutput {
|
|
|
65
67
|
}
|
|
66
68
|
export interface AuthorizationResult {
|
|
67
69
|
readonly attemptId?: string;
|
|
70
|
+
readonly instanceId?: string;
|
|
68
71
|
readonly resume?: JsonValue;
|
|
69
72
|
readonly callback: AuthorizationCallback;
|
|
70
73
|
readonly hookUrl: string;
|
|
@@ -79,12 +82,12 @@ export interface AuthorizationResult {
|
|
|
79
82
|
*/
|
|
80
83
|
export declare function requestAuthorization(challenges: readonly AuthorizationChallenge[]): AuthorizationSignal;
|
|
81
84
|
/**
|
|
82
|
-
* Returns a copy of `signal` with
|
|
85
|
+
* Returns a model-safe copy of `signal` with runtime-only challenge state stripped.
|
|
83
86
|
*
|
|
84
87
|
* Used for the copy the AI SDK records as a tool output. The shape stays a
|
|
85
88
|
* valid {@link AuthorizationSignal} so every `isAuthorizationSignal` consumer
|
|
86
|
-
* still detects it; the park detector reads the full
|
|
87
|
-
* harness's out-of-band stash.
|
|
89
|
+
* still detects it; the park detector reads the full resume, principal, and
|
|
90
|
+
* resolved-instance state from the harness's out-of-band stash.
|
|
88
91
|
*/
|
|
89
92
|
export declare function redactSignalResume(signal: AuthorizationSignal): AuthorizationSignal;
|
|
90
93
|
/**
|
|
@@ -95,6 +98,8 @@ export declare function redactSignalResume(signal: AuthorizationSignal): Authori
|
|
|
95
98
|
* single-challenge tools).
|
|
96
99
|
*/
|
|
97
100
|
export declare function getAuthorizationResult(name?: string): AuthorizationResult | undefined;
|
|
101
|
+
/** Returns every callback result available to the active step. */
|
|
102
|
+
export declare function getAuthorizationResults(): readonly NamedAuthorizationResult[];
|
|
98
103
|
/**
|
|
99
104
|
* Removes and returns one authorization callback result.
|
|
100
105
|
*
|
|
@@ -102,7 +107,7 @@ export declare function getAuthorizationResult(name?: string): AuthorizationResu
|
|
|
102
107
|
* before completion prevents a failed or replayed callback from poisoning
|
|
103
108
|
* every later tool call in the same step.
|
|
104
109
|
*/
|
|
105
|
-
export declare function consumeAuthorizationResult(name: string): AuthorizationResult | undefined;
|
|
110
|
+
export declare function consumeAuthorizationResult(name: string, instanceId?: string): AuthorizationResult | undefined;
|
|
106
111
|
/**
|
|
107
112
|
* Builds a callback URL for external systems. `name` and `attemptId` identify
|
|
108
113
|
* the exact challenge in the URL path.
|
|
@@ -157,6 +162,8 @@ export interface PendingAuthorizationState {
|
|
|
157
162
|
readonly challenges: readonly AuthorizationChallenge[];
|
|
158
163
|
}
|
|
159
164
|
export declare function setPendingAuthorization(sessionState: Record<string, unknown> | undefined, value: PendingAuthorizationState): Record<string, unknown>;
|
|
165
|
+
/** Keeps the last challenge for each authorization name and principal scope. */
|
|
166
|
+
export declare function resolveActiveAuthorizationChallenges(challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
160
167
|
/** Existing same-scope attempts replaced by newer attempts for the same principal. */
|
|
161
168
|
export declare function getSupersededAuthorizationChallenges(sessionState: Record<string, unknown> | undefined, replacements: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
162
169
|
export declare function clearPendingAuthorization(sessionState: Record<string, unknown> | undefined, attemptIds?: readonly string[]): Record<string, unknown> | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function 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 n=loadContext().get(PendingAuthorizationResultKey);if(!(!n||n.length===0))return e===void 0?n[0]:n.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,n){let r=loadContext(),i=r.get(PendingAuthorizationResultKey);if(!i||i.length===0)return;let a=i.findIndex(t=>t.name===e&&t.instanceId===n);if(a===-1&&n!==void 0&&i.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(a===-1)return;let o=i[a],s=i.filter((e,t)=>t!==a);return r.delete(PendingAuthorizationResultKey),s.length>0&&r.set(PendingAuthorizationResultKey,s),o}function getHookUrl(r,a){let o=loadContext(),s=o.get(SessionIdKey),c=o.get(CallbackBaseUrlKey);return!s||!c?void 0:createWorkflowCallbackUrl(c,createEveConnectionCallbackRoutePath(r,a,authHookToken(s)))}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=resolveActiveAuthorizationChallenges(t.challenges),r=getPendingAuthorization(e)?.challenges??[],i=getSupersededAuthorizationChallenges(e,n);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...r.filter(e=>!i.includes(e)),...n]}}}function resolveActiveAuthorizationChallenges(e){return e.filter((t,n)=>!e.slice(n+1).some(e=>t.name===e.name&&samePrincipal(t.principal,e.principal)))}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,getAuthorizationResults,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,resolveActiveAuthorizationChallenges,setPendingAuthorization};
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
import type { ToolSet, TypedToolResult } from "ai";
|
|
1
|
+
import type { ModelMessage, ToolSet, TypedToolResult } from "ai";
|
|
2
|
+
import { type AuthorizationSignal } from "#harness/authorization.js";
|
|
2
3
|
/** Returns whether an inline tool result represents a pending authorization interrupt. */
|
|
3
4
|
export declare function isInlineAuthorizationToolResult(toolResult: TypedToolResult<ToolSet>): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Resolves authorization interrupts and keeps only protocol-complete sibling
|
|
7
|
+
* calls from the response that produced them.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveInlineAuthorizationInterrupt(input: {
|
|
10
|
+
readonly messages: readonly ModelMessage[];
|
|
11
|
+
readonly toolResults: readonly TypedToolResult<ToolSet>[] | undefined;
|
|
12
|
+
}): {
|
|
13
|
+
readonly challenges: AuthorizationSignal["challenges"];
|
|
14
|
+
readonly history: ModelMessage[];
|
|
15
|
+
} | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";function isInlineAuthorizationToolResult(e){
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput,resolveActiveAuthorizationChallenges}from"#harness/authorization.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";function isInlineAuthorizationToolResult(e){return isPendingAuthorizationToolOutput(e.output)||readAuthorizationSignal(e)!==void 0}function resolveInlineAuthorizationInterrupt(e){let t=[],n=new Set;for(let r of e.toolResults??[]){let e=readAuthorizationSignal(r);e!==void 0&&(t.push(e),n.add(r.toolCallId))}if(t.length!==0)return{challenges:resolveActiveAuthorizationChallenges(t.flatMap(e=>e.challenges)),history:projectCompletedSiblingCalls(e.messages,n)}}function readAuthorizationSignal(n){let r=contextStorage.getStore(),a=r===void 0?void 0:readToolInterrupt(r,n.toolCallId);return a!==void 0&&isAuthorizationSignal(a)?a:isAuthorizationSignal(n.output)?n.output:void 0}function projectCompletedSiblingCalls(e,t){return e.flatMap(e=>{if(e.role===`assistant`&&Array.isArray(e.content)){let n=e.content.some(e=>e.type===`tool-call`&&t.has(e.toolCallId)),r=e.content.filter(e=>e.type!==`tool-call`||!t.has(e.toolCallId)),i=r.some(e=>e.type===`tool-call`);return r.length===0||n&&!i?[]:[{...e,content:r}]}if(e.role===`tool`){let n=e.content.filter(e=>e.type!==`tool-result`||!t.has(e.toolCallId));return n.length===0?[]:[{...e,content:n}]}return[e]})}export{isInlineAuthorizationToolResult,resolveInlineAuthorizationInterrupt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{toError,walkCauseChain}from"#shared/errors.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";const UNSUPPORTED_TOOL_TYPE_REGEX=/tool type ['"]([\w.-]+)['"] is not supported/i;function extractUpstreamRejectionMessage(e){let t=readModelCallErrorSignals(e);if(isTransientHttpStatus(t.statusCode??t.upstreamStatusCode))return null;let n=t.apiErrorMessage;if(n!==void 0)return{name:upstreamRejectionName(t),message:n};if(t.statusCode===400&&isGatewayErrorSignal(t))return{name:`AI Gateway model request rejected`,message:`AI Gateway rejected the model request before the agent produced a response.`};let r=formatApiCallErrorFallback(t);return r===void 0?null:{name:upstreamRejectionName(t),message:r}}function upstreamRejectionName(e){return isGatewayErrorSignal(e)?`AI Gateway model request rejected`:`Model provider API error`}function isTransientHttpStatus(e){return e===408||e===429||e!==void 0&&e>=500}function extractUnsupportedProviderToolTypes(e){let t=new Set;for(let r of walkCauseChain(e)){collectUnsupportedToolTypesFromValue(readObjectField(r,`data`),t);let e=readStringField(r,`responseBody`);if(e!==void 0)try{collectUnsupportedToolTypesFromValue(JSON.parse(e),t)}catch{let n=UNSUPPORTED_TOOL_TYPE_REGEX.exec(e);n?.[1]!==void 0&&t.add(n[1])}}return[...t]}function collectUnsupportedToolTypesFromValue(t,n){if(t!=null){if(typeof t==`string`){let e=UNSUPPORTED_TOOL_TYPE_REGEX.exec(t);e?.[1]!==void 0&&n.add(e[1]);return}if(Array.isArray(t)){for(let e of t)collectUnsupportedToolTypesFromValue(e,n);return}if(isObject(t))for(let e of Object.values(t))collectUnsupportedToolTypesFromValue(e,n)}}function extractModelCallErrorDetails(e){let t=readModelCallErrorSignals(e),n={};return appendJsonField(n,`apiErrorMessage`,t.apiErrorMessage),appendJsonField(n,`gatewayName`,t.gatewayName),appendJsonField(n,`gatewayType`,t.gatewayType),appendJsonField(n,`statusCode`,t.statusCode),appendJsonField(n,`generationId`,t.generationId),appendJsonField(n,`upstreamStatusCode`,t.upstreamStatusCode),appendJsonField(n,`upstreamType`,t.upstreamType),appendJsonField(n,`upstreamMessage`,t.upstreamMessage),appendJsonField(n,`responseBodySnippet`,t.responseBodySnippet),n}function readErrorName(t){if(t instanceof Error||isObject(t)&&typeof t.name==`string`)return t.name}function readErrorMessage(t){return t instanceof Error||isObject(t)&&typeof t.message==`string`?t.message:``}var EmptyModelResponseError=class extends Error{constructor(e){super(`The model did not return a response. Please try again.`,e),this.name=`EmptyModelResponseError`}};function normalizeModelStreamError(e){let n=toError(e);return n===e||Object.defineProperty(n,"cause",{configurable:!0,value:e}),n}function isNoOutputGeneratedError(e){for(let t of walkCauseChain(e))if(readErrorName(t)===`AI_NoOutputGeneratedError`)return!0;return!1}function classifyModelCallError(e){if(isTurnCancellation(e))return`terminal`;if(e instanceof EmptyModelResponseError)return`recoverable`;if(hasRetryableFlag(e))return`retry`;let t=summarizeKnownError(e);if(t?.tags.includes(`config`)===!0)return`terminal`;if(t?.tags.includes(`transient`)===!0)return`retry`;let n=readModelCallErrorSignals(e);if(isRetryableGatewayType(n.upstreamType))return`retry`;if(isTerminalGatewayType(n.upstreamType)||n.gatewayType===`invalid_request_error`||n.gatewayName===`GatewayInvalidRequestError`)return`terminal`;let a=n.statusCode;if(a!==void 0){if(a===408||a===409||a===429||a>=500)return`retry`;if(isAmbiguousGatewayInternalBadRequest(n))return`recoverable`;if(a>=400&&a<500)return`terminal`}return`recoverable`}function hasRetryableFlag(t){for(let r of walkCauseChain(t))if(isObject(r)&&r.isRetryable===!0)return!0;return!1}function readModelCallErrorSignals(e){let t=findGatewayError(e),n=findUpstreamApiCallError(e),r=readStringField(n,`responseBody`),i=readGatewayErrorBody(n);return{apiCallError:n!==void 0,apiErrorMessage:i?.apiErrorMessage??firstInformativeApiMessage([readErrorMessage(n)]),gatewayName:readErrorName(t),gatewayType:readStringField(t,`type`),generationId:readStringField(t,`generationId`)??i?.generationId,responseBodySnippet:r===void 0?void 0:truncateSnippet(r,1e3),statusCode:readStatusCode(t)??readStatusCode(n)??findStatusCode(e),upstreamMessage:i?.message,upstreamStatusCode:readStatusCode(n),upstreamType:i?.type}}function findGatewayError(e){for(let t of walkCauseChain(e)){let e=readErrorName(t),n=readStringField(t,`type`);if(e?.startsWith(`Gateway`)||n?.endsWith(`_error`)||n===`rate_limit_exceeded`)return t}}function findUpstreamApiCallError(e){for(let t of walkCauseChain(e))if(readErrorName(t)===`AI_APICallError`||readStringField(t,`responseBody`)!==void 0||readObjectField(t,`data`)!==void 0||readObjectField(t,`requestBodyValues`)!==void 0)return t}function readGatewayErrorBody(e){let t=readGatewayErrorBodyFromValue(readObjectField(e,`data`));if(t!==void 0)return t;let n=readStringField(e,`responseBody`);if(n!==void 0)try{return readGatewayErrorBodyFromValue(JSON.parse(n))}catch{return}}function readGatewayErrorBodyFromValue(t){if(!isObject(t))return;let n=readObjectField(t,`error`),r=readStringField(t,`generationId`),i=readStringField(n,`message`)??readStringField(t,`message`),a=readStringField(n,`type`)??readStringField(t,`type`),o=firstInformativeApiMessage([i,...readNestedApiErrorMessages(n),...readNestedApiErrorMessages(t)]);return i===void 0&&a===void 0&&r===void 0&&o===void 0?void 0:{apiErrorMessage:o,generationId:r,message:i,type:a}}function readStatusCode(t){if(isObject(t))return typeof t.statusCode==`number`?t.statusCode:void 0}function findStatusCode(e){for(let t of walkCauseChain(e)){let e=readStatusCode(t);if(e!==void 0)return e}}function readStringField(t,n){if(!isObject(t))return;let r=t[n];return typeof r==`string`&&r.length>0?r:void 0}function readObjectField(t,n){if(!isObject(t))return;let r=t[n];return isObject(r)?r:void 0}function readNestedApiErrorMessages(t){if(!isObject(t))return[];let n=[];return appendString(n,readStringField(t,`message`)),appendString(n,readStringField(t,`error_description`)),appendNestedApiFieldMessages(n,t.error),appendNestedApiFieldMessages(n,t.code),n}function appendNestedApiFieldMessages(t,n){if(typeof n==`string`){appendString(t,n);return}isObject(n)&&(appendString(t,readStringField(n,`message`)),appendString(t,readStringField(n,`error`)),appendString(t,readStringField(n,`description`)),appendString(t,readStringField(n,`error_description`)),appendNestedApiFieldMessages(t,n.error))}function appendString(e,t){t!==void 0&&e.push(t)}function firstInformativeApiMessage(e){for(let t of e)if(t!==void 0&&isInformativeApiMessage(t))return truncateSnippet(t,800)}function isInformativeApiMessage(e){let t=e.trim();return t.length>0&&t!==`[object Object]`&&t!==`AI_APICallError`&&t!==`Bad Request`&&t!==`Internal Server Error`}function formatApiCallErrorFallback(e){if(!e.apiCallError)return;let t=e.statusCode??e.upstreamStatusCode,n=e.responseBodySnippet,r=e.upstreamType!==void 0&&isInformativeApiMessage(e.upstreamType)?e.upstreamType:void 0;if(t===void 0&&n===void 0&&r===void 0)return;let i=[t===void 0?void 0:`HTTP ${t}`,r].filter(e=>e!==void 0).join(`, `),a=i.length===0?`Model provider API request failed`:`Model provider API request failed (${i})`;return n===void 0?`${a}.`:`${a}: ${n}`}function isRetryableGatewayType(e){return e===`overloaded_error`||e===`rate_limit_exceeded`||e===`timeout_error`}function isTerminalGatewayType(e){return e===`authentication_error`||e===`invalid_request_error`||e===`model_not_found`}function isGatewayErrorSignal(e){return e.gatewayName!==void 0||e.gatewayType!==void 0}function isAmbiguousGatewayInternalBadRequest(e){return e.statusCode===400&&(e.gatewayName===`GatewayInternalServerError`||e.gatewayType===`internal_server_error`)&&(e.upstreamType===void 0||e.upstreamType===`internal_server_error`)}function appendJsonField(e,t,n){if(typeof n==`string`&&n.length>0){e[t]=n;return}typeof n==`number`&&Number.isFinite(n)&&(e[t]=n)}function truncateSnippet(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}export{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,extractUpstreamRejectionMessage,isNoOutputGeneratedError,normalizeModelStreamError};
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{toError,walkCauseChain}from"#shared/errors.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";const UNSUPPORTED_TOOL_TYPE_REGEX=/tool type ['"]([\w.-]+)['"] is not supported/i;function extractUpstreamRejectionMessage(e){let t=readModelCallErrorSignals(e);if(isTransientHttpStatus(t.statusCode??t.upstreamStatusCode))return null;let n=t.apiErrorMessage;if(n!==void 0)return{name:upstreamRejectionName(t),message:n};if(t.statusCode===400&&isGatewayErrorSignal(t))return{name:`AI Gateway model request rejected`,message:`AI Gateway rejected the model request before the agent produced a response.`};let r=formatApiCallErrorFallback(t);return r===void 0?null:{name:upstreamRejectionName(t),message:r}}function upstreamRejectionName(e){return isGatewayErrorSignal(e)?`AI Gateway model request rejected`:`Model provider API error`}function isTransientHttpStatus(e){return e===408||e===429||e!==void 0&&e>=500}function extractUnsupportedProviderToolTypes(e){let t=new Set;for(let r of walkCauseChain(e)){collectUnsupportedToolTypesFromValue(readObjectField(r,`data`),t);let e=readStringField(r,`responseBody`);if(e!==void 0)try{collectUnsupportedToolTypesFromValue(JSON.parse(e),t)}catch{let n=UNSUPPORTED_TOOL_TYPE_REGEX.exec(e);n?.[1]!==void 0&&t.add(n[1])}}return[...t]}function collectUnsupportedToolTypesFromValue(t,n){if(t!=null){if(typeof t==`string`){let e=UNSUPPORTED_TOOL_TYPE_REGEX.exec(t);e?.[1]!==void 0&&n.add(e[1]);return}if(Array.isArray(t)){for(let e of t)collectUnsupportedToolTypesFromValue(e,n);return}if(isObject(t))for(let e of Object.values(t))collectUnsupportedToolTypesFromValue(e,n)}}function extractModelCallErrorDetails(e){let t=readModelCallErrorSignals(e),n={};return appendJsonField(n,`apiErrorMessage`,t.apiErrorMessage),appendJsonField(n,`gatewayName`,t.gatewayName),appendJsonField(n,`gatewayType`,t.gatewayType),appendJsonField(n,`statusCode`,t.statusCode),appendJsonField(n,`generationId`,t.generationId),appendJsonField(n,`upstreamStatusCode`,t.upstreamStatusCode),appendJsonField(n,`upstreamType`,t.upstreamType),appendJsonField(n,`upstreamMessage`,t.upstreamMessage),appendJsonField(n,`responseBodySnippet`,t.responseBodySnippet),n}function readErrorName(t){if(t instanceof Error||isObject(t)&&typeof t.name==`string`)return t.name}function readErrorMessage(t){return t instanceof Error||isObject(t)&&typeof t.message==`string`?t.message:``}var EmptyModelResponseError=class extends Error{constructor(e){super(`The model did not return a response. Please try again.`,e),this.name=`EmptyModelResponseError`}};function normalizeModelStreamError(e){let n=toError(e);return n===e||Object.defineProperty(n,"cause",{configurable:!0,value:e}),n}function isNoOutputGeneratedError(e){for(let t of walkCauseChain(e))if(readErrorName(t)===`AI_NoOutputGeneratedError`)return!0;return!1}function classifyModelCallError(e){if(isTurnCancellation(e))return`terminal`;if(e instanceof EmptyModelResponseError)return`recoverable`;if(hasRetryableFlag(e))return`retry`;let t=summarizeKnownError(e);if(t?.tags.includes(`recoverable`)===!0)return`recoverable`;if(t?.tags.includes(`config`)===!0)return`terminal`;if(t?.tags.includes(`transient`)===!0)return`retry`;let n=readModelCallErrorSignals(e);if(n.statusCode===402)return`recoverable`;if(isRetryableGatewayType(n.upstreamType))return`retry`;if(isTerminalGatewayType(n.upstreamType)||n.gatewayType===`invalid_request_error`||n.gatewayName===`GatewayInvalidRequestError`)return`terminal`;let a=n.statusCode;if(a!==void 0){if(a===408||a===409||a===429||a>=500)return`retry`;if(isAmbiguousGatewayInternalBadRequest(n))return`recoverable`;if(a>=400&&a<500)return`terminal`}return`recoverable`}function hasRetryableFlag(t){for(let r of walkCauseChain(t))if(isObject(r)&&r.isRetryable===!0)return!0;return!1}function readModelCallErrorSignals(e){let t=findGatewayError(e),n=findUpstreamApiCallError(e),r=readStringField(n,`responseBody`),i=readGatewayErrorBody(n);return{apiCallError:n!==void 0,apiErrorMessage:i?.apiErrorMessage??firstInformativeApiMessage([readErrorMessage(n)]),gatewayName:readErrorName(t),gatewayType:readStringField(t,`type`),generationId:readStringField(t,`generationId`)??i?.generationId,responseBodySnippet:r===void 0?void 0:truncateSnippet(r,1e3),statusCode:readStatusCode(t)??readStatusCode(n)??findStatusCode(e),upstreamMessage:i?.message,upstreamStatusCode:readStatusCode(n),upstreamType:i?.type}}function findGatewayError(e){for(let t of walkCauseChain(e)){let e=readErrorName(t),n=readStringField(t,`type`);if(e?.startsWith(`Gateway`)||n?.endsWith(`_error`)||n===`rate_limit_exceeded`)return t}}function findUpstreamApiCallError(e){for(let t of walkCauseChain(e))if(readErrorName(t)===`AI_APICallError`||readStringField(t,`responseBody`)!==void 0||readObjectField(t,`data`)!==void 0||readObjectField(t,`requestBodyValues`)!==void 0)return t}function readGatewayErrorBody(e){let t=readGatewayErrorBodyFromValue(readObjectField(e,`data`));if(t!==void 0)return t;let n=readStringField(e,`responseBody`);if(n!==void 0)try{return readGatewayErrorBodyFromValue(JSON.parse(n))}catch{return}}function readGatewayErrorBodyFromValue(t){if(!isObject(t))return;let n=readObjectField(t,`error`),r=readStringField(t,`generationId`),i=readStringField(n,`message`)??readStringField(t,`message`),a=readStringField(n,`type`)??readStringField(t,`type`),o=firstInformativeApiMessage([i,...readNestedApiErrorMessages(n),...readNestedApiErrorMessages(t)]);return i===void 0&&a===void 0&&r===void 0&&o===void 0?void 0:{apiErrorMessage:o,generationId:r,message:i,type:a}}function readStatusCode(t){if(isObject(t))return typeof t.statusCode==`number`?t.statusCode:void 0}function findStatusCode(e){for(let t of walkCauseChain(e)){let e=readStatusCode(t);if(e!==void 0)return e}}function readStringField(t,n){if(!isObject(t))return;let r=t[n];return typeof r==`string`&&r.length>0?r:void 0}function readObjectField(t,n){if(!isObject(t))return;let r=t[n];return isObject(r)?r:void 0}function readNestedApiErrorMessages(t){if(!isObject(t))return[];let n=[];return appendString(n,readStringField(t,`message`)),appendString(n,readStringField(t,`error_description`)),appendNestedApiFieldMessages(n,t.error),appendNestedApiFieldMessages(n,t.code),n}function appendNestedApiFieldMessages(t,n){if(typeof n==`string`){appendString(t,n);return}isObject(n)&&(appendString(t,readStringField(n,`message`)),appendString(t,readStringField(n,`error`)),appendString(t,readStringField(n,`description`)),appendString(t,readStringField(n,`error_description`)),appendNestedApiFieldMessages(t,n.error))}function appendString(e,t){t!==void 0&&e.push(t)}function firstInformativeApiMessage(e){for(let t of e)if(t!==void 0&&isInformativeApiMessage(t))return truncateSnippet(t,800)}function isInformativeApiMessage(e){let t=e.trim();return t.length>0&&t!==`[object Object]`&&t!==`AI_APICallError`&&t!==`Bad Request`&&t!==`Internal Server Error`}function formatApiCallErrorFallback(e){if(!e.apiCallError)return;let t=e.statusCode??e.upstreamStatusCode,n=e.responseBodySnippet,r=e.upstreamType!==void 0&&isInformativeApiMessage(e.upstreamType)?e.upstreamType:void 0;if(t===void 0&&n===void 0&&r===void 0)return;let i=[t===void 0?void 0:`HTTP ${t}`,r].filter(e=>e!==void 0).join(`, `),a=i.length===0?`Model provider API request failed`:`Model provider API request failed (${i})`;return n===void 0?`${a}.`:`${a}: ${n}`}function isRetryableGatewayType(e){return e===`overloaded_error`||e===`rate_limit_exceeded`||e===`timeout_error`}function isTerminalGatewayType(e){return e===`authentication_error`||e===`invalid_request_error`||e===`model_not_found`}function isGatewayErrorSignal(e){return e.gatewayName!==void 0||e.gatewayType!==void 0}function isAmbiguousGatewayInternalBadRequest(e){return e.statusCode===400&&(e.gatewayName===`GatewayInternalServerError`||e.gatewayType===`internal_server_error`)&&(e.upstreamType===void 0||e.upstreamType===`internal_server_error`)}function appendJsonField(e,t,n){if(typeof n==`string`&&n.length>0){e[t]=n;return}typeof n==`number`&&Number.isFinite(n)&&(e[t]=n)}function truncateSnippet(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}export{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,extractUpstreamRejectionMessage,isNoOutputGeneratedError,normalizeModelStreamError};
|
|
@@ -6,8 +6,10 @@ import type { ErrorLink, ErrorSignals } from "./signals.js";
|
|
|
6
6
|
* invalid credentials, unknown model id). The model-call classifier
|
|
7
7
|
* treats a matched `config` rule as terminal.
|
|
8
8
|
* - `transient` — the failure is expected to clear on retry.
|
|
9
|
+
* - `recoverable` — the current request cannot proceed, but the same session
|
|
10
|
+
* remains useful after an external fix.
|
|
9
11
|
*/
|
|
10
|
-
export type SemanticErrorTag = "gateway" | "model-provider" | "workflow" | "sandbox" | "system" | "config" | "transient";
|
|
12
|
+
export type SemanticErrorTag = "gateway" | "model-provider" | "workflow" | "sandbox" | "system" | "config" | "transient" | "recoverable";
|
|
11
13
|
/** A predicate over one extracted cause-chain link. */
|
|
12
14
|
export type LinkPredicate = (link: ErrorLink) => boolean;
|
|
13
15
|
/**
|
|
@@ -45,7 +47,8 @@ export interface SemanticErrorSummary {
|
|
|
45
47
|
/**
|
|
46
48
|
* The matched rule's tags, carried so consumers with a recovery policy
|
|
47
49
|
* (the model-call classifier) can read the catalog's judgment —
|
|
48
|
-
* `config` is terminal, `transient` retries
|
|
50
|
+
* `config` is terminal, `transient` retries, and `recoverable` parks the
|
|
51
|
+
* session — without a second registry
|
|
49
52
|
* of the same knowledge.
|
|
50
53
|
*/
|
|
51
54
|
readonly tags: readonly SemanticErrorTag[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{allOf,anyOf,messageMatches,nameIs,typeIs}from"../rule.js";const GATEWAY_AUTH_FAILURE_SUMMARY_NAME=`AI Gateway authentication failed`,gatewayAuthenticationFailure=anyOf(nameIs(`GatewayAuthenticationError`),typeIs(`authentication_error`),messageMatches(/AI Gateway authentication/i)),GATEWAY_RULES=[{id:`gateway-auth-invalid-api-key`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:allOf(gatewayAuthenticationFailure,messageMatches(/Invalid API key/i)),message:`AI Gateway rejected the provided API key.`,hint:"Update or unset `AI_GATEWAY_API_KEY` (check your shell profile if you did not set it for this project) — manage keys at https://vercel.com/dashboard/ai/api-keys. Unsetting it falls back to OIDC via `eve link`."},{id:`gateway-auth-invalid-oidc-token`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:allOf(gatewayAuthenticationFailure,messageMatches(/Invalid OIDC token/i)),message:`AI Gateway rejected the OIDC token.`,hint:"Run `eve link` to refresh `VERCEL_OIDC_TOKEN` in `.env.local`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys."},{id:`gateway-auth-missing-credentials`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:gatewayAuthenticationFailure,message:`AI Gateway received no credentials.`,hint:"Run `eve link` to populate `VERCEL_OIDC_TOKEN`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys."},{id:`model-not-found`,name:`Model not found`,tags:[`gateway`,`config`],when:anyOf(nameIs(`GatewayModelNotFoundError`,`AI_NoSuchModelError`),typeIs(`model_not_found`)),message:`The requested model is not available.`,hint:"Check the model id in `agent.ts` (`model:`) or switch models with `/model` in `eve dev` — browse available models at https://vercel.com/ai-gateway/models."},{id:`gateway-rate-limited`,name:`AI Gateway rate limit exceeded`,tags:[`gateway`,`transient`],when:anyOf(nameIs(`GatewayRateLimitError`),typeIs(`rate_limit_exceeded`)),message:`AI Gateway rate-limited the request.`,hint:`Retries are automatic; if it persists, reduce request volume or review your plan limits at https://vercel.com/ai-gateway.`},{id:`gateway-upstream-unavailable`,name:`Model provider unavailable`,tags:[`gateway`,`transient`],when:anyOf(nameIs(`GatewayTimeoutError`),typeIs(`timeout_error`,`overloaded_error`)),message:`The model provider is overloaded or timing out upstream of AI Gateway.`,hint:"This is transient — retry shortly, or switch models with `/model` in `eve dev`."}];export{GATEWAY_RULES};
|
|
1
|
+
import{allOf,anyOf,messageMatches,nameIs,typeIs}from"../rule.js";const GATEWAY_AUTH_FAILURE_SUMMARY_NAME=`AI Gateway authentication failed`,gatewayAuthenticationFailure=anyOf(nameIs(`GatewayAuthenticationError`),typeIs(`authentication_error`),messageMatches(/AI Gateway authentication/i)),GATEWAY_RULES=[{id:`gateway-billing-required`,name:`AI Gateway billing setup required`,tags:[`gateway`,`config`,`recoverable`],when:messageMatches(/AI Gateway requires a valid credit card on file/),message:e=>e.message,hint:`Add a valid credit card or credits in the Vercel dashboard, then retry.`},{id:`gateway-free-tier-model-restricted`,name:`Model unavailable on AI Gateway free tier`,tags:[`gateway`,`config`,`recoverable`],when:messageMatches(/Free tier users do not have access to this model/),message:e=>e.message,hint:`Switch to a model available on the free tier or upgrade your Vercel plan, then retry.`},{id:`gateway-free-tier-rate-limited`,name:`AI Gateway free tier rate limit exceeded`,tags:[`gateway`,`recoverable`],when:messageMatches(/Free tier requests on this model are rate-limited/),message:e=>e.message,hint:`Wait for the free-tier limit to reset or upgrade your Vercel plan, then retry.`},{id:`gateway-auth-invalid-api-key`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:allOf(gatewayAuthenticationFailure,messageMatches(/Invalid API key/i)),message:`AI Gateway rejected the provided API key.`,hint:"Update or unset `AI_GATEWAY_API_KEY` (check your shell profile if you did not set it for this project) — manage keys at https://vercel.com/dashboard/ai/api-keys. Unsetting it falls back to OIDC via `eve link`."},{id:`gateway-auth-invalid-oidc-token`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:allOf(gatewayAuthenticationFailure,messageMatches(/Invalid OIDC token/i)),message:`AI Gateway rejected the OIDC token.`,hint:"Run `eve link` to refresh `VERCEL_OIDC_TOKEN` in `.env.local`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys."},{id:`gateway-auth-missing-credentials`,name:GATEWAY_AUTH_FAILURE_SUMMARY_NAME,tags:[`gateway`,`config`],when:gatewayAuthenticationFailure,message:`AI Gateway received no credentials.`,hint:"Run `eve link` to populate `VERCEL_OIDC_TOKEN`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys."},{id:`model-not-found`,name:`Model not found`,tags:[`gateway`,`config`],when:anyOf(nameIs(`GatewayModelNotFoundError`,`AI_NoSuchModelError`),typeIs(`model_not_found`)),message:`The requested model is not available.`,hint:"Check the model id in `agent.ts` (`model:`) or switch models with `/model` in `eve dev` — browse available models at https://vercel.com/ai-gateway/models."},{id:`gateway-rate-limited`,name:`AI Gateway rate limit exceeded`,tags:[`gateway`,`transient`],when:anyOf(nameIs(`GatewayRateLimitError`),typeIs(`rate_limit_exceeded`)),message:`AI Gateway rate-limited the request.`,hint:`Retries are automatic; if it persists, reduce request volume or review your plan limits at https://vercel.com/ai-gateway.`},{id:`gateway-upstream-unavailable`,name:`Model provider unavailable`,tags:[`gateway`,`transient`],when:anyOf(nameIs(`GatewayTimeoutError`),typeIs(`timeout_error`,`overloaded_error`)),message:`The model provider is overloaded or timing out upstream of AI Gateway.`,hint:"This is transient — retry shortly, or switch models with `/model` in `eve dev`."}];export{GATEWAY_RULES};
|