eve 0.36.0 → 0.37.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +1 -0
- package/dist/src/channel/routes.d.ts +13 -3
- package/dist/src/channel/routes.js +1 -1
- package/dist/src/channel/session-callback.js +1 -1
- package/dist/src/channel/session.d.ts +2 -1
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +41 -0
- package/dist/src/chunks/{use-eve-agent-CnppTEFk.js → use-eve-agent-Bi5fRxcZ.js} +9 -1
- package/dist/src/chunks/{use-eve-agent-COmP-H8R.js → use-eve-agent-DbKUBhl-.js} +9 -1
- package/dist/src/cli/commands/agent-instructions.d.ts +4 -4
- package/dist/src/cli/commands/init-confirm.d.ts +12 -0
- package/dist/src/cli/commands/init-confirm.js +1 -0
- package/dist/src/cli/commands/init-git.js +1 -1
- package/dist/src/cli/commands/init-recovery.d.ts +3 -0
- package/dist/src/cli/commands/init-recovery.js +3 -0
- package/dist/src/cli/commands/init-target.d.ts +21 -0
- package/dist/src/cli/commands/init-target.js +1 -0
- package/dist/src/cli/commands/init.d.ts +6 -5
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +8 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +27 -22
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +16 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/cli/run.d.ts +1 -0
- package/dist/src/cli/run.js +3 -3
- package/dist/src/client/open-stream.d.ts +2 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -1
- package/dist/src/compiled/@modelcontextprotocol/server/LICENSE +216 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +98 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.js +80 -0
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +339 -0
- package/dist/src/compiled/@vercel/sandbox/api-client/index.d.ts +1 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +25 -1
- package/dist/src/compiled/@vercel/sandbox/drive.d.ts +140 -0
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -2
- package/dist/src/compiled/@vercel/sandbox/index.js +13 -13
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +55 -18
- package/dist/src/compiled/@vercel/sandbox-stable/LICENSE +201 -0
- package/dist/src/compiled/@vercel/sandbox-stable/_async-retry.d.ts +8 -0
- package/dist/src/compiled/@vercel/sandbox-stable/_workflow-serde.d.ts +5 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/api-client.d.ts +1456 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/api-error.d.ts +29 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/base-client.d.ts +39 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/file-writer.d.ts +66 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/index.d.ts +2 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/validators.d.ts +899 -0
- package/dist/src/compiled/@vercel/sandbox-stable/api-client/with-retry.d.ts +10 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/error.d.ts +15 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/file.d.ts +18 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/index.d.ts +6 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/oauth.d.ts +111 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/poll-for-token.d.ts +28 -0
- package/dist/src/compiled/@vercel/sandbox-stable/auth/project.d.ts +40 -0
- package/dist/src/compiled/@vercel/sandbox-stable/command.d.ts +292 -0
- package/dist/src/compiled/@vercel/sandbox-stable/constants.d.ts +5 -0
- package/dist/src/compiled/@vercel/sandbox-stable/execution-context.d.ts +116 -0
- package/dist/src/compiled/@vercel/sandbox-stable/filesystem.d.ts +258 -0
- package/dist/src/compiled/@vercel/sandbox-stable/index.d.ts +12 -0
- package/dist/src/compiled/@vercel/sandbox-stable/index.js +1 -0
- package/dist/src/compiled/@vercel/sandbox-stable/network-policy.d.ts +169 -0
- package/dist/src/compiled/@vercel/sandbox-stable/proxy.d.ts +55 -0
- package/dist/src/compiled/@vercel/sandbox-stable/sandbox-user.d.ts +212 -0
- package/dist/src/compiled/@vercel/sandbox-stable/sandbox.d.ts +1216 -0
- package/dist/src/compiled/@vercel/sandbox-stable/session.d.ts +433 -0
- package/dist/src/compiled/@vercel/sandbox-stable/snapshot.d.ts +229 -0
- package/dist/src/compiled/@vercel/sandbox-stable/utils/get-credentials.d.ts +21 -0
- package/dist/src/compiled/@vercel/sandbox-stable/utils/paginator.d.ts +16 -0
- package/dist/src/compiled/@vercel/sandbox-stable/utils/resolveSignal.d.ts +15 -0
- package/dist/src/compiled/@vercel/sandbox-stable/utils/sandbox-snapshot.d.ts +11 -0
- package/dist/src/compiled/@vercel/sandbox-stable/utils/types.d.ts +11 -0
- package/dist/src/compiled/_chunks/node/{auth-BS3UoyvT.js → auth-BaNbsImr.js} +1 -1
- package/dist/src/compiled/_chunks/node/version-BYHw-SDY.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.d.ts +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/context/serialized-dynamic-model-selection.d.ts +2 -0
- package/dist/src/context/serialized-dynamic-model-selection.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.d.ts +15 -1
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/delegated-parent-notification.d.ts +17 -0
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +155 -0
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +18 -14
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +7 -2
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/effective-output-schema.d.ts +21 -0
- package/dist/src/execution/effective-output-schema.js +1 -0
- package/dist/src/execution/eve-workflow-attributes.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +8 -12
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/{route-proxied-deliver-step.d.ts → proxied-deliver-step.d.ts} +7 -4
- package/dist/src/execution/proxied-deliver-step.js +1 -0
- package/dist/src/execution/remote-agent-dispatch.d.ts +32 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/remote-agent-route-url.d.ts +2 -0
- package/dist/src/execution/remote-agent-route-url.js +1 -0
- package/dist/src/execution/route-child-delivery.d.ts +2 -1
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.d.ts +2 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session-callback-step.d.ts +11 -0
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/session-command-wire.js +1 -1
- package/dist/src/execution/session-state-cursor.d.ts +25 -0
- package/dist/src/execution/session-state-cursor.js +1 -0
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +2 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.d.ts +15 -0
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +14 -7
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/subagent-start-local.d.ts +29 -0
- package/dist/src/execution/subagent-start-local.js +1 -0
- package/dist/src/execution/subagent-start-remote.d.ts +23 -0
- package/dist/src/execution/subagent-start-remote.js +1 -0
- package/dist/src/execution/task-event-callback.d.ts +13 -0
- package/dist/src/execution/task-event-callback.js +1 -0
- package/dist/src/execution/task-input-capability.d.ts +4 -0
- package/dist/src/execution/task-input-capability.js +1 -0
- package/dist/src/execution/tasks/child/steps.d.ts +46 -0
- package/dist/src/execution/tasks/child/steps.js +1 -0
- package/dist/src/execution/tasks/child/workflow.d.ts +31 -0
- package/dist/src/execution/tasks/child/workflow.js +1 -0
- package/dist/src/execution/tasks/parent/agent-identity.d.ts +13 -0
- package/dist/src/execution/tasks/parent/agent-identity.js +1 -0
- package/dist/src/execution/tasks/parent/agent-views.d.ts +6 -0
- package/dist/src/execution/tasks/parent/agent-views.js +1 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.d.ts +37 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/control-shared.d.ts +36 -0
- package/dist/src/execution/tasks/parent/control-shared.js +1 -0
- package/dist/src/execution/tasks/parent/delegate.d.ts +70 -0
- package/dist/src/execution/tasks/parent/delegate.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.d.ts +19 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch.d.ts +33 -0
- package/dist/src/execution/tasks/parent/dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +29 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -0
- package/dist/src/execution/tasks/parent/run-parent.d.ts +72 -0
- package/dist/src/execution/tasks/parent/run-parent.js +1 -0
- package/dist/src/execution/tasks/parent/send.d.ts +25 -0
- package/dist/src/execution/tasks/parent/send.js +1 -0
- package/dist/src/execution/tasks/workflow-target.d.ts +2 -0
- package/dist/src/execution/tasks/workflow-target.js +1 -0
- package/dist/src/execution/terminate-child-sessions-step.d.ts +1 -0
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/turn-control-receiver.d.ts +10 -0
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +2 -0
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +2 -8
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +5 -0
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +9 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +7 -21
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +7 -0
- package/dist/src/harness/handles/prompt.d.ts +12 -0
- package/dist/src/harness/handles/prompt.js +2 -1
- package/dist/src/harness/handles/query.js +1 -1
- package/dist/src/harness/handles/store.d.ts +9 -2
- package/dist/src/harness/handles/store.js +1 -1
- package/dist/src/harness/handles/transitions.d.ts +10 -1
- package/dist/src/harness/handles/transitions.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +21 -4
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +2 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/workflow-runtime-action-state.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/invocation/agent-invocation.d.ts +54 -0
- package/dist/src/internal/invocation/agent-invocation.js +1 -0
- package/dist/src/internal/invocation/attributes.d.ts +2 -0
- package/dist/src/internal/invocation/attributes.js +1 -0
- package/dist/src/internal/invocation/metadata.d.ts +9 -0
- package/dist/src/internal/invocation/metadata.js +1 -0
- package/dist/src/internal/invocation/workflow-execution.d.ts +32 -0
- package/dist/src/internal/invocation/workflow-execution.js +1 -0
- package/dist/src/internal/mcp/http-security.d.ts +12 -0
- package/dist/src/internal/mcp/http-security.js +1 -0
- package/dist/src/internal/mcp/protected-resource.d.ts +9 -0
- package/dist/src/internal/mcp/protected-resource.js +1 -0
- package/dist/src/internal/mcp/streamable-http-server.d.ts +51 -0
- package/dist/src/internal/mcp/streamable-http-server.js +1 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +14 -0
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/internal/nitro/routes/runtime-stack.d.ts +2 -0
- package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/message.d.ts +28 -0
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/routes.d.ts +14 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.d.ts +36 -0
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/mcp.d.ts +19 -0
- package/dist/src/public/channels/mcp.js +1 -0
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/sandbox/backends/vercel.d.ts +5 -4
- package/dist/src/public/sandbox/backends/vercel.js +1 -1
- package/dist/src/public/sandbox/vercel-sandbox.d.ts +25 -1
- package/dist/src/public/sandbox/vercel.d.ts +2 -1
- package/dist/src/public/sandbox/vercel.js +1 -1
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/actions/types.d.ts +9 -0
- package/dist/src/runtime/actions/types.js +1 -1
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/connections/authorization-complete-page.js +70 -28
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/framework-tools/tasks.d.ts +95 -0
- package/dist/src/runtime/framework-tools/tasks.js +1 -0
- package/dist/src/runtime/prompt/compose.d.ts +1 -0
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/runtime/task-input-response-route.d.ts +5 -0
- package/dist/src/runtime/task-input-response-route.js +1 -0
- package/dist/src/setup/scaffold/create/add-to-project.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 +0 -1
- package/dist/src/shared/agent-definition.d.ts +7 -0
- package/dist/src/shared/sandbox-network-policy.d.ts +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/json.d.ts +88 -0
- package/dist/src/tasks/json.js +1 -0
- package/dist/src/tasks/session-index.d.ts +48 -0
- package/dist/src/tasks/session-index.js +1 -0
- package/dist/src/tasks/task-id.d.ts +34 -0
- package/dist/src/tasks/task-id.js +1 -0
- package/dist/src/tasks/transitions.d.ts +23 -0
- package/dist/src/tasks/transitions.js +1 -0
- package/dist/src/tasks/types.d.ts +295 -0
- package/dist/src/tasks/types.js +1 -0
- package/dist/src/tasks/wire.d.ts +26 -0
- package/dist/src/tasks/wire.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/eve.mdx +14 -0
- package/docs/guides/client/streaming.mdx +1 -1
- package/docs/reference/cli.md +10 -6
- package/docs/tools/human-in-the-loop.md +3 -1
- package/package.json +8 -1
- package/dist/src/compiled/_chunks/node/version-Cztrk7z6.js +0 -1
- package/dist/src/execution/route-proxied-deliver-step.js +0 -1
|
@@ -14,6 +14,9 @@ export declare const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE = "deploymentId 'late
|
|
|
14
14
|
* template) read this single set so they cannot drift.
|
|
15
15
|
*/
|
|
16
16
|
export declare const STABLE_WORKFLOW_NAMES: ReadonlySet<string>;
|
|
17
|
+
interface WorkflowHookRecord {
|
|
18
|
+
readonly runId: string;
|
|
19
|
+
}
|
|
17
20
|
/**
|
|
18
21
|
* Stable workflow reference used by `start()` to locate the workflow
|
|
19
22
|
* entrypoint registered by the Workflow DevKit builder. The id omits
|
|
@@ -37,6 +40,10 @@ export declare const turnWorkflowReference: {
|
|
|
37
40
|
export declare const sessionTimeoutWorkflowReference: {
|
|
38
41
|
workflowId: string;
|
|
39
42
|
};
|
|
43
|
+
/** Stable workflow reference for durable task runs (`experimental.tasks`). */
|
|
44
|
+
export declare const taskRunWorkflowReference: {
|
|
45
|
+
workflowId: string;
|
|
46
|
+
};
|
|
40
47
|
/**
|
|
41
48
|
* Creates a workflow-backed runtime whose long-lived driver owns the
|
|
42
49
|
* event stream and dispatches each turn as a child workflow run.
|
|
@@ -48,8 +55,10 @@ export declare function createWorkflowRuntime(config: {
|
|
|
48
55
|
}): Runtime;
|
|
49
56
|
/** Requests cancellation through a session's stable command inbox. */
|
|
50
57
|
export declare function requestWorkflowTurnCancellation(input: CancelTurnInput): Promise<CancelTurnResult>;
|
|
58
|
+
export declare function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord>;
|
|
51
59
|
/**
|
|
52
60
|
* Starts a workflow on the latest deployment when latest routing applies,
|
|
53
61
|
* while preserving local/dev worlds that do not implement latest routing.
|
|
54
62
|
*/
|
|
55
63
|
export declare function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs, options?: StartOptionsWithoutDeploymentId): Promise<Run<unknown> | Run<TResult>>;
|
|
64
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f=l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,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]),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}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f={...l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),...i.externalInvocation===void 0?{}:buildInvocationAttributes(i.externalInvocation)},p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(i.continuationToken){let e=await waitForCommandHookOwner(i.continuationToken);if(e.runId!==p.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:i.continuationToken,ownerSessionId:e.runId,sessionId:p.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId);let m,getEvents=()=>(m??=parseNdjsonStream(()=>getRun(p.runId).getReadable()),m);return{get events(){return getEvents()},sessionId:p.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeHook(e,sessionHookPayload(n)))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function sessionHookPayload(e){return e.kind===`send`?sendCommandToDelivery(e):e}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){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 r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { SettledTurn } from "#harness/types.js";
|
|
2
2
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
|
-
import type { JsonObject } from "#shared/json.js";
|
|
4
|
-
import type { RunMode } from "#shared/run-mode.js";
|
|
5
3
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
6
4
|
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
7
5
|
/**
|
|
@@ -44,6 +42,12 @@ export type DurableStepResult = {
|
|
|
44
42
|
readonly hasPendingAuthorization: boolean;
|
|
45
43
|
readonly hasPendingInputBatch: boolean;
|
|
46
44
|
readonly pendingRuntimeActionKeys?: readonly string[];
|
|
45
|
+
/**
|
|
46
|
+
* Selects the dispatch step for `pendingRuntimeActionKeys`:
|
|
47
|
+
* `dispatchTaskStep` when the agent runs `experimental.tasks`,
|
|
48
|
+
* `dispatchRuntimeActionsStep` otherwise (including when absent).
|
|
49
|
+
*/
|
|
50
|
+
readonly tasksEnabled?: boolean;
|
|
47
51
|
readonly sleepDurationMs?: number;
|
|
48
52
|
readonly serializedContext: Record<string, unknown>;
|
|
49
53
|
readonly sessionState: DurableSessionState;
|
|
@@ -60,21 +64,3 @@ export type { TurnStepInput };
|
|
|
60
64
|
* Runs one atomic harness step inside a durable `"use step"` boundary.
|
|
61
65
|
*/
|
|
62
66
|
export declare function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult>;
|
|
63
|
-
/**
|
|
64
|
-
* Resolves the single output schema in effect for this turn, decoupling schema
|
|
65
|
-
* enforcement from {@link RunMode}: downstream the harness reads
|
|
66
|
-
* `session.outputSchema` unconditionally and never re-derives it from mode.
|
|
67
|
-
*
|
|
68
|
-
* A run-scoped (client-supplied) schema on the turn's {@link StepInput} always
|
|
69
|
-
* wins. With no run-scoped schema, a task run adopts the agent's declared
|
|
70
|
-
* return schema — its function-output contract, which only applies when the
|
|
71
|
-
* agent is invoked as a function (subagent / schedule / job), i.e. task mode.
|
|
72
|
-
* A conversation run with no run-scoped schema enforces nothing. Continuation
|
|
73
|
-
* steps (no new `StepInput`) preserve whatever is already in effect.
|
|
74
|
-
*/
|
|
75
|
-
export declare function resolveEffectiveOutputSchema(input: {
|
|
76
|
-
readonly agentOutputSchema: JsonObject | undefined;
|
|
77
|
-
readonly input: StepInput | undefined;
|
|
78
|
-
readonly mode: RunMode;
|
|
79
|
-
readonly session: HarnessSession;
|
|
80
|
-
}): HarnessSession;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(f,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},p=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=getInstrumentationRuntime(),g=getHarnessEmissionState(m.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:h?.hooks,rootSessionId:m.rootSessionId??m.sessionId,sequence:g.sequence,sessionId:m.sessionId,turnId:activeTurnId(g)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:h?.hooks,includeTurn:!1,outcome:`failed`})),await h?.forceFlush()},_=buildAdapterContext(l,c),v;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,_):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),v={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{..._.state}}),o.input?.kind===`deliver`&&v===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:h?.hooks,includeTurn:!1,outcome:`completed`})),await h?.forceFlush();let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let y=u.hookRegistry,b=u.resolvedAgent.dynamicInstructionsResolvers??[],x=u.resolvedAgent.dynamicSkillResolvers??[],S=u.subagentRegistry.dynamicResolvers??[],C=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,w=u.resolvedAgent.dynamicToolResolvers??[],T={...u.graph.root,turnAgent:d.turnAgent},E=buildRuntimeIdentity(T);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!g.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:E});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,persistentSessions:C,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:w,event:e,messages:m.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,_);setChannelContext(c,{...l,state:{..._.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:y,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:S,event:n,messages:t??[],persistentSessions:C}),await dispatchDynamicToolEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:x,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:b,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:v,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:E,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,E,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of p){let r=f?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:T,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,v)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;D.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(o.serializedContext,t),t),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){if(O===`task`&&hasPendingInputBatch(k.session.state))throw D.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}export{resolveEffectiveOutputSchema,turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{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{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0,f=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let p=getPendingAuthorization(s.state),m;if(p&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(p,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))},m=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 h=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),g=getInstrumentationRuntime(),_=getHarnessEmissionState(h.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:g?.hooks,rootSessionId:h.rootSessionId??h.sessionId,sequence:_.sequence,sessionId:h.sessionId,turnId:activeTurnId(_)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:g?.hooks,includeTurn:!1,outcome:`failed`})),await g?.forceFlush()},v=buildAdapterContext(l,c),y;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,v):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}y=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),y={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...v.state}}),o.input?.kind===`deliver`&&y===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:g?.hooks,includeTurn:!1,outcome:`completed`})),await g?.forceFlush();let e=reconcileSessionContinuationToken(c,h),t=serializeContext(c),n=e===h?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let b=u.hookRegistry,x=u.resolvedAgent.dynamicInstructionsResolvers??[],S=u.resolvedAgent.dynamicSkillResolvers??[],C=u.subagentRegistry.dynamicResolvers??[],w=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,T=u.resolvedAgent.dynamicToolResolvers??[],E={...u.graph.root,turnAgent:f.turnAgent},D=buildRuntimeIdentity(E);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!_.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:D});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:C,event:e,messages:h.history,persistentSessions:w,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:h.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let O=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,v);setChannelContext(c,{...l,state:{...v.state}});let r=stampMessageStreamEvent(n);return await O.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{await forwardTaskEventToSessionCallback(c,e);let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:b,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:C,event:n,messages:t??[],persistentSessions:w}),await dispatchDynamicToolEvent({ctx:c,resolvers:T,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:x,event:n,messages:t??[]})},k=c.require(ModeKey),A;try{throwIfTurnAborted(o.abortSignal),A=await runStep(c,h,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:y,mode:k,session:e});if(m){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:D,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,D,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of m){let r=p?.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,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:k,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:E,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,y)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;O.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let j=reconcileSessionContinuationToken(c,A.session),M=serializeContext(c);A={...A,session:j};let N=createDurableSessionState({session:A.session}),P=readTurnSleepDurationMs(c),F=P===void 0?{}:{sleepDurationMs:P};if(A.next!==null&&typeof A.next==`object`&&`done`in A.next){if(k===`task`&&hasPendingInputBatch(A.session.state))throw O.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await O.close();let e=getTurnUsageState(A.session.state)?.session;return{action:`done`,output:A.next.output,isError:A.next.isError,...F,serializedContext:M,sessionState:N,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(A.session).delta}}if(A.next===null){O.releaseLock();let e=getPendingWorkflowInterrupt(A.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...F,serializedContext:M,sessionState:N};let t=derivePendingState(A.session);if(A.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(A.session);return{action:`park`,...t,...F,serializedContext:M,sessionState:createDurableSessionState({session:n}),settled:{output:A.settledTurn.output,isError:A.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...t,...F,serializedContext:M,sessionState:N,tasksEnabled:d}}return O.releaseLock(),{action:`continue`,...F,serializedContext:M,sessionState:N}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let
|
|
1
|
+
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{TASK_TOOL_NAMES}from"#runtime/framework-tools/tasks.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let r=ensureWorkflowContinuationSecurity(e.session),{modelTools:a}=await applyWorkflowTool({continuationSecurity:getWorkflowContinuationSecurity(r),harnessTools:n,lifecycle:e.workflow.lifecycle?.({session:r,tools:n}),maxSubagents:e.workflow.maxSubagents,tools:e.modelTools});return{harnessTools:t,modelTools:a,session:r}}function filterUnavailableDelegationToolDefinitions(e,t){let n=[];for(let r of e)shouldHideDelegationTool(r,t)||n.push(r);return n}function filterUnavailableDelegationToolMap(e,t){let n=new Map;for(let[r,i]of e)shouldHideDelegationTool(i,t)||n.set(r,i);return n}function filterWorkflowHostToolsForRootSession(t,n){let r=new Map,i=resolveSubagentDepth(n);if(n.rootSessionId!==void 0||i.currentDepth>0)return r;for(let[e,n]of t)isDelegatedRuntimeActionTool(n)&&r.set(e,n);return r}function isDelegatedRuntimeActionTool(e){let t=e.runtimeAction;return t?.kind===`subagent-call`||t?.kind===`remote-agent-call`}function shouldHideDelegationTool(t,n){return isRootOnlyFrameworkTool(t)?n.rootSessionId!==void 0||resolveSubagentDepth(n).currentDepth>0:!1}function isRootOnlyFrameworkTool(e){return e.name===AGENT_TOOL_NAME&&e.runtimeAction?.kind===`subagent-call`&&e.runtimeAction.nodeId===ROOT_RUNTIME_AGENT_NODE_ID||TASK_TOOL_NAMES.has(e.name)}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{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 t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,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=getPendingAuthorization(e)?.challenges??[],r=getSupersededAuthorizationChallenges(e,t.challenges);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...n.filter(e=>!r.includes(e)),...t.challenges]}}}function getSupersededAuthorizationChallenges(e,t){return(getPendingAuthorization(e)?.challenges??[]).filter(e=>t.some(t=>e.name===t.name&&samePrincipal(e.principal,t.principal)))}function samePrincipal(e,t){return e===void 0||t===void 0?e===t:e.type===`app`||t.type===`app`?e.type===t.type:e.id===t.id&&e.issuer===t.issuer}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.attemptId??e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
@@ -6,12 +6,19 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
|
6
6
|
*
|
|
7
7
|
* These tools are surfaced to the model without a local `execute` function.
|
|
8
8
|
* The harness records the tool call and the runtime executes it later.
|
|
9
|
+
*
|
|
10
|
+
* `task-control` marks the `experimental.tasks` parent tools
|
|
11
|
+
* (`task_peek`, `task_cancel`): they carry no child
|
|
12
|
+
* address of their own — the dispatch step resolves targets through the
|
|
13
|
+
* session task index by tool name.
|
|
9
14
|
*/
|
|
10
15
|
export type HarnessRuntimeActionDefinition = {
|
|
11
16
|
readonly kind: "remote-agent-call" | "subagent-call";
|
|
12
17
|
readonly nodeId: string;
|
|
13
18
|
readonly remoteAgentName?: string;
|
|
14
19
|
readonly subagentName: string;
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "task-control";
|
|
15
22
|
};
|
|
16
23
|
/**
|
|
17
24
|
* Unified harness-owned tool definition.
|
|
@@ -6,6 +6,15 @@ import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
|
|
|
6
6
|
* than authored user input.
|
|
7
7
|
*/
|
|
8
8
|
export declare const AGENTS_SNIPPET_LABEL = "[Agents]";
|
|
9
|
+
/** Model-safe projection of one persistent task-mode agent. */
|
|
10
|
+
export interface AgentView {
|
|
11
|
+
readonly availability: "available" | "busy";
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly statusLine?: string;
|
|
15
|
+
readonly taskId?: string;
|
|
16
|
+
readonly taskStatus?: "working" | "input_required";
|
|
17
|
+
}
|
|
9
18
|
/** Returns the resumable handles: the only phase the model may continue. */
|
|
10
19
|
export declare function projectParkedAgentHandles(store: AgentHandleStore): readonly Extract<AgentHandle, {
|
|
11
20
|
phase: "parked";
|
|
@@ -16,6 +25,8 @@ export declare function projectParkedAgentHandles(store: AgentHandleStore): read
|
|
|
16
25
|
* delivery coordinates never render.
|
|
17
26
|
*/
|
|
18
27
|
export declare function renderAgentsSnippet(store: AgentHandleStore): string;
|
|
28
|
+
/** Renders task-derived availability without exposing private addresses. */
|
|
29
|
+
export declare function renderAgentViewsSnippet(views: readonly AgentView[]): string;
|
|
19
30
|
/**
|
|
20
31
|
* Returns an append-only announcement when the visible handle listing
|
|
21
32
|
* changed since the last one in history, or `undefined` when it is
|
|
@@ -35,6 +46,7 @@ export declare function renderAgentsSnippet(store: AgentHandleStore): string;
|
|
|
35
46
|
* eve-injected so the model does not attribute it to the user.
|
|
36
47
|
*/
|
|
37
48
|
export declare function resolveAgentsAnnouncement(input: {
|
|
49
|
+
readonly agentViews?: readonly AgentView[];
|
|
38
50
|
readonly messages: readonly ModelMessage[];
|
|
39
51
|
readonly store: AgentHandleStore | undefined;
|
|
40
52
|
}): string | undefined;
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
const AGENTS_SNIPPET_LABEL=`[Agents]`;function projectParkedAgentHandles(e){return e.handles.filter(e=>e.phase===`parked`)}function renderAgentsSnippet(t){let n=projectParkedAgentHandles(t).map(e=>`<agent id="${escapeXml(e.identity.id)}" name="${escapeXml(e.identity.name)}">${escapeXml(e.lastStatus===``?`(no status)`:e.lastStatus)}</agent>`);return[AGENTS_SNIPPET_LABEL,`<agents>`,...n,`</agents>`].join(`
|
|
2
|
-
`)}function
|
|
2
|
+
`)}function renderAgentViewsSnippet(t){let n=t.map(e=>{let t=e.taskId===void 0||e.taskStatus===void 0?``:` taskId="${escapeXml(e.taskId)}" taskStatus="${e.taskStatus}"`,n=e.statusLine??(e.availability===`busy`?`(busy)`:`(available)`);return`<agent id="${escapeXml(e.id)}" name="${escapeXml(e.name)}" availability="${e.availability}"${t}>${escapeXml(n)}</agent>`});return[AGENTS_SNIPPET_LABEL,`<agents>`,...n,`</agents>`].join(`
|
|
3
|
+
`)}function resolveAgentsAnnouncement(e){let t=e.messages.findLast(e=>e.role===`user`&&typeof e.content==`string`&&e.content.startsWith(`[Agents]`)),n=e.store??{handles:[]},r=e.agentViews?.length??projectParkedAgentHandles(n).length;if(t===void 0&&r===0)return;let i=e.agentViews===void 0?renderAgentsSnippet(n):renderAgentViewsSnippet(e.agentViews);return t?.content===i?void 0:i}function escapeXml(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}export{AGENTS_SNIPPET_LABEL,projectParkedAgentHandles,renderAgentViewsSnippet,renderAgentsSnippet,resolveAgentsAnnouncement};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_HANDLES_STATE_KEY}from"#harness/handles/state-key.js";function readAgentHandles(t){let n=t?.[AGENT_HANDLES_STATE_KEY];if(n===void 0)return[];let r=n.handles;return Array.isArray(r)?r:[]}function findRunningAgentHandle(e,t){return readAgentHandles(e).find(e=>e.phase===`running`&&e.operation.callId===t.callId)}function isResultBoundToRunningHandle(e,t){return t.kind!==`subagent-result`||t.origin===`dispatch`||findRunningAgentHandle(e,{callId:t.callId})!==void 0}function isInboxSubagentResultFromRunningHandle(e,t){return findRunningAgentHandle(e,{callId:t.callId})!==void 0}export{findRunningAgentHandle,isInboxSubagentResultFromRunningHandle,isResultBoundToRunningHandle};
|
|
1
|
+
import{AGENT_HANDLES_STATE_KEY}from"#harness/handles/state-key.js";function readAgentHandles(t){let n=t?.[AGENT_HANDLES_STATE_KEY];if(n===void 0)return[];let r=n.handles;return Array.isArray(r)?r:[]}function findRunningAgentHandle(e,t){return readAgentHandles(e).find(e=>e.phase===`running`&&e.operation.callId===t.callId)}function isResultBoundToRunningHandle(e,t){return t.kind!==`subagent-result`||t.origin===`dispatch`||t.backgroundTask!==void 0||findRunningAgentHandle(e,{callId:t.callId})!==void 0}function isInboxSubagentResultFromRunningHandle(e,t){return findRunningAgentHandle(e,{callId:t.callId})!==void 0}export{findRunningAgentHandle,isInboxSubagentResultFromRunningHandle,isResultBoundToRunningHandle};
|
|
@@ -74,7 +74,7 @@ export type AgentAddress = {
|
|
|
74
74
|
/**
|
|
75
75
|
* Durable ownership record for one delegated child.
|
|
76
76
|
*
|
|
77
|
-
*
|
|
77
|
+
* Outside tasks mode, the store owns the full nonterminal lifecycle:
|
|
78
78
|
*
|
|
79
79
|
* - `starting` — the parent committed intent to start; the child may or
|
|
80
80
|
* may not exist yet.
|
|
@@ -82,7 +82,9 @@ export type AgentAddress = {
|
|
|
82
82
|
* - `parked` — the child is idle and resumable; only this phase is
|
|
83
83
|
* model-visible.
|
|
84
84
|
*
|
|
85
|
-
* A terminal child has no handle: settlement deletes it.
|
|
85
|
+
* A terminal child has no legacy handle: settlement deletes it. Tasks mode
|
|
86
|
+
* instead keeps an `addressed` record whose availability is derived from the
|
|
87
|
+
* tasks bound to its persistent child session.
|
|
86
88
|
*/
|
|
87
89
|
export type AgentHandle = {
|
|
88
90
|
readonly phase: "starting";
|
|
@@ -99,6 +101,11 @@ export type AgentHandle = {
|
|
|
99
101
|
readonly identity: AgentIdentity;
|
|
100
102
|
readonly address: AgentAddress;
|
|
101
103
|
readonly lastStatus: string;
|
|
104
|
+
} | {
|
|
105
|
+
/** Persistent task-mode identity and routing, with no execution claim. */
|
|
106
|
+
readonly phase: "addressed";
|
|
107
|
+
readonly identity: AgentIdentity;
|
|
108
|
+
readonly address: AgentAddress;
|
|
102
109
|
};
|
|
103
110
|
/** Lifecycle phase of a delegated agent handle. */
|
|
104
111
|
export type AgentHandlePhase = AgentHandle["phase"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_HANDLES_STATE_KEY}from"./state-key.js";import{z}from"#compiled/zod/index.js";const nonEmptyString=z.string().min(1),identitySchema=z.strictObject({id:nonEmptyString,name:nonEmptyString,nodeId:nonEmptyString}),startOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`start`),parentTurnId:nonEmptyString}),continueOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`continue`),parentTurnId:nonEmptyString,previousStatus:z.string().max(120)}),startTargetSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`)}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`)}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),url:z.url()})]),addressSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`),sessionId:nonEmptyString}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`),sessionId:nonEmptyString}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),sessionId:nonEmptyString,url:z.url()})]),agentHandleSchema=z.discriminatedUnion(`phase`,[z.strictObject({identity:identitySchema,operation:startOperationSchema,phase:z.literal(`starting`),target:startTargetSchema}),z.strictObject({address:addressSchema,identity:identitySchema,operation:z.discriminatedUnion(`kind`,[startOperationSchema,continueOperationSchema]),phase:z.literal(`running`)}),z.strictObject({address:addressSchema,identity:identitySchema,lastStatus:z.string().max(120),phase:z.literal(`parked`)})]),agentHandleStoreSchema=z.strictObject({handles:z.array(agentHandleSchema)}).refine(e=>new Set(e.handles.map(e=>e.identity.id)).size===e.handles.length,{message:`Agent handle ids must be unique.`});function deriveAgentId(e,t){return`ag_${e}:${t.slice(0,12)}`}function formatAgentStatus(e){return(typeof e==`string`?e:JSON.stringify(e)??``).replaceAll(/\s+/g,` `).trim().slice(0,120)}function assertPersistableAgentHandleStore(e){let t=agentHandleStoreSchema.safeParse(e);if(!t.success)throw Error(`Refusing to persist a corrupt agent handle store: ${t.error.message}`);return t.data}function getAgentHandleStore(t){let n=t?.[AGENT_HANDLES_STATE_KEY];if(n===void 0)return;let r=agentHandleStoreSchema.safeParse(n);if(!r.success)throw Error(`Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${r.error.message}`);return r.data}export{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,deriveAgentId,formatAgentStatus,getAgentHandleStore};
|
|
1
|
+
import{AGENT_HANDLES_STATE_KEY}from"./state-key.js";import{z}from"#compiled/zod/index.js";const nonEmptyString=z.string().min(1),identitySchema=z.strictObject({id:nonEmptyString,name:nonEmptyString,nodeId:nonEmptyString}),startOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`start`),parentTurnId:nonEmptyString}),continueOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`continue`),parentTurnId:nonEmptyString,previousStatus:z.string().max(120)}),startTargetSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`)}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`)}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),url:z.url()})]),addressSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`),sessionId:nonEmptyString}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`),sessionId:nonEmptyString}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),sessionId:nonEmptyString,url:z.url()})]),agentHandleSchema=z.discriminatedUnion(`phase`,[z.strictObject({identity:identitySchema,operation:startOperationSchema,phase:z.literal(`starting`),target:startTargetSchema}),z.strictObject({address:addressSchema,identity:identitySchema,operation:z.discriminatedUnion(`kind`,[startOperationSchema,continueOperationSchema]),phase:z.literal(`running`)}),z.strictObject({address:addressSchema,identity:identitySchema,lastStatus:z.string().max(120),phase:z.literal(`parked`)}),z.strictObject({address:addressSchema,identity:identitySchema,phase:z.literal(`addressed`)})]),agentHandleStoreSchema=z.strictObject({handles:z.array(agentHandleSchema)}).refine(e=>new Set(e.handles.map(e=>e.identity.id)).size===e.handles.length,{message:`Agent handle ids must be unique.`});function deriveAgentId(e,t){return`ag_${e}:${t.slice(0,12)}`}function formatAgentStatus(e){return(typeof e==`string`?e:JSON.stringify(e)??``).replaceAll(/\s+/g,` `).trim().slice(0,120)}function assertPersistableAgentHandleStore(e){let t=agentHandleStoreSchema.safeParse(e);if(!t.success)throw Error(`Refusing to persist a corrupt agent handle store: ${t.error.message}`);return t.data}function getAgentHandleStore(t){let n=t?.[AGENT_HANDLES_STATE_KEY];if(n===void 0)return;let r=agentHandleStoreSchema.safeParse(n);if(!r.success)throw Error(`Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${r.error.message}`);return r.data}export{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,deriveAgentId,formatAgentStatus,getAgentHandleStore};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AgentAddress, type AgentHandle, type AgentIdentity, type ContinueOperation, type StartOperation } from "#harness/handles/store.js";
|
|
2
|
-
import type { HarnessSession } from "#harness/types.js";
|
|
2
|
+
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
|
|
3
3
|
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
|
|
4
4
|
/**
|
|
5
5
|
* Records intent to start a fresh child. Must be applied to the step's
|
|
@@ -68,6 +68,15 @@ export declare function confirmAgentStarted(session: HarnessSession, input: {
|
|
|
68
68
|
readonly operationId: string;
|
|
69
69
|
readonly address: AgentAddress;
|
|
70
70
|
}): HarnessSession;
|
|
71
|
+
/** Confirms a task-mode child as a persistent identity/address record. */
|
|
72
|
+
export declare function confirmTaskAgentAddress(session: HarnessSession, input: {
|
|
73
|
+
readonly operationId: string;
|
|
74
|
+
readonly address: AgentAddress;
|
|
75
|
+
}): HarnessSession;
|
|
76
|
+
/** Removes a task-mode address after permanent delivery failure. */
|
|
77
|
+
export declare function removeTaskAgentAddress(session: HarnessSession, agentId: string): HarnessSession;
|
|
78
|
+
/** State-only variant used while consuming a terminal task wake. */
|
|
79
|
+
export declare function removeTaskAgentAddressFromState(state: SessionStateMap | undefined, agentId: string): SessionStateMap;
|
|
71
80
|
/**
|
|
72
81
|
* Resolves a dispatch that definitively failed.
|
|
73
82
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";function prepareAgentStart(e,t){let n=getAgentHandleStore(e.state)?.handles??[];if(n.some(e=>e.identity.id===t.identity.id))throw Error(`Agent handle "${t.identity.id}" already exists.`);return writeHandles(e,[...n,{identity:t.identity,operation:t.operation,phase:`starting`,target:t.target}])}function prepareAgentContinuation(e,t){let n=getAgentHandleStore(e.state)?.handles??[],i=n.find(e=>e.identity.id===t.agentId);if(i===void 0)return{kind:`unknown`};if(i.identity.name!==t.invokedName)return{kind:`mismatch`};if(i.phase===`running`&&i.operation.id===t.operation.id)return{handle:i,kind:`ready`,session:e};if(i.phase!==`parked`)return{kind:`busy`};let a={address:i.address,identity:i.identity,operation:{...t.operation,previousStatus:i.lastStatus},phase:`running`};return{handle:a,kind:`ready`,session:writeHandles(e,n.map(e=>e.identity.id===t.agentId?a:e))}}function findActiveHandle(e,t){return e.find(e=>e.phase
|
|
1
|
+
import{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";function prepareAgentStart(e,t){let n=getAgentHandleStore(e.state)?.handles??[];if(n.some(e=>e.identity.id===t.identity.id))throw Error(`Agent handle "${t.identity.id}" already exists.`);return writeHandles(e,[...n,{identity:t.identity,operation:t.operation,phase:`starting`,target:t.target}])}function prepareAgentContinuation(e,t){let n=getAgentHandleStore(e.state)?.handles??[],i=n.find(e=>e.identity.id===t.agentId);if(i===void 0)return{kind:`unknown`};if(i.identity.name!==t.invokedName)return{kind:`mismatch`};if(i.phase===`running`&&i.operation.id===t.operation.id)return{handle:i,kind:`ready`,session:e};if(i.phase!==`parked`)return{kind:`busy`};let a={address:i.address,identity:i.identity,operation:{...t.operation,previousStatus:i.lastStatus},phase:`running`};return{handle:a,kind:`ready`,session:writeHandles(e,n.map(e=>e.identity.id===t.agentId?a:e))}}function findActiveHandle(e,t){return e.find(e=>(e.phase===`starting`||e.phase===`running`)&&e.operation.id===t)}function confirmAgentStarted(e,t){let n=getAgentHandleStore(e.state)?.handles??[],i=findActiveHandle(n,t.operationId);if(i===void 0)throw Error(`No prepared agent handle for operation "${t.operationId}".`);return i.phase===`running`?e:writeHandles(e,n.map(e=>e===i?{address:t.address,identity:i.identity,operation:i.operation,phase:`running`}:e))}function confirmTaskAgentAddress(e,t){let n=getAgentHandleStore(e.state)?.handles??[],i=findActiveHandle(n,t.operationId);if(i===void 0)throw Error(`No prepared agent handle for operation "${t.operationId}".`);if(i.phase===`running`)throw Error(`Task agent operation "${t.operationId}" was confirmed as a running handle.`);return writeHandles(e,n.map(e=>e===i?{address:t.address,identity:i.identity,phase:`addressed`}:e))}function removeTaskAgentAddress(e,t){return{...e,state:removeTaskAgentAddressFromState(e.state,t)}}function removeTaskAgentAddressFromState(n,i){let a=getAgentHandleStore(n)?.handles??[];return{...n,[AGENT_HANDLES_STATE_KEY]:assertPersistableAgentHandleStore({handles:a.filter(e=>!(e.phase===`addressed`&&e.identity.id===i))})}}function rejectAgentEffect(e,t){let n=getAgentHandleStore(e.state)?.handles??[],i=findActiveHandle(n,t.operationId);if(i===void 0)return e;if(t.disposition===`retryable`&&i.phase===`running`){let{operation:t}=i;if(t.kind===`continue`)return writeHandles(e,n.map(e=>e===i?{address:i.address,identity:i.identity,lastStatus:t.previousStatus,phase:`parked`}:e))}return writeHandles(e,n.filter(e=>e!==i))}function abandonRunningAgentTurns(e){let t=getAgentHandleStore(e.state)?.handles??[];return t.some(e=>e.phase===`running`)?writeHandles(e,t.map(e=>e.phase===`running`?{address:e.address,identity:e.identity,lastStatus:`(cancelled)`,phase:`parked`}:e)):e}function settleAgentTurn(e,t){let i=getAgentHandleStore(e.state)?.handles??[],a=i.find(e=>e.phase===`running`&&e.operation.id===t.operationId);if(a===void 0||a.phase!==`running`)return{kind:`ignored`,reason:`unknown-operation`};if(t.outcome.kind===`terminal`)return{kind:`settled`,session:writeHandles(e,i.filter(e=>e!==a))};let{result:o}=t.outcome,s=o.kind===`succeeded`?formatAgentStatus(o.output):o.kind===`failed`?formatAgentStatus(o.error):`(cancelled)`;return{kind:`settled`,session:writeHandles(e,i.map(e=>e===a?{address:a.address,identity:a.identity,lastStatus:s,phase:`parked`}:e))}}function writeHandles(n,r){return{...n,state:{...n.state,[AGENT_HANDLES_STATE_KEY]:assertPersistableAgentHandleStore({handles:r})}}}export{abandonRunningAgentTurns,confirmAgentStarted,confirmTaskAgentAddress,prepareAgentContinuation,prepareAgentStart,rejectAgentEffect,removeTaskAgentAddress,removeTaskAgentAddressFromState,settleAgentTurn};
|
|
@@ -6,12 +6,20 @@ export interface ProxyInputRequest {
|
|
|
6
6
|
/** Batch semantics are optional so sessions written before this field remain routable. */
|
|
7
7
|
readonly batch?: ProxyInputRequestBatch;
|
|
8
8
|
readonly childContinuationToken: string;
|
|
9
|
+
/** Child-local id restored before forwarding a namespaced task response. */
|
|
10
|
+
readonly childRequestId?: string;
|
|
11
|
+
/** Trusted parent-derived capability URL for a remote task child. */
|
|
12
|
+
readonly childResponseUrl?: string;
|
|
9
13
|
readonly kind: InputRequestKind;
|
|
14
|
+
/** Present when the route is authorized by a parent-owned durable task. */
|
|
15
|
+
readonly taskId?: string;
|
|
10
16
|
}
|
|
11
17
|
export interface ProxyInputRequestBatch {
|
|
12
18
|
readonly approvalRequestIds: readonly string[];
|
|
13
19
|
readonly requestIds: readonly string[];
|
|
14
20
|
}
|
|
21
|
+
/** Parent-visible id for one task-owned child-local input request. */
|
|
22
|
+
export declare function createTaskInputRequestId(taskId: string, childRequestId: string): string;
|
|
15
23
|
/**
|
|
16
24
|
* Returns the proxy-routing map as a fresh `Map`. Never returns a live
|
|
17
25
|
* reference so accidental mutation cannot corrupt session state.
|
|
@@ -23,15 +31,22 @@ export declare function getProxyInputRequests(state: SessionStateMap | undefined
|
|
|
23
31
|
*/
|
|
24
32
|
export declare function hasProxyInputRequests(state: SessionStateMap | undefined): boolean;
|
|
25
33
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
34
|
+
* Replaces prior entries for `forChildContinuationToken` with the provided
|
|
35
|
+
* ones. A child raising a fresh batch overwrites its prior batch so the
|
|
36
|
+
* parent never keeps stale request metadata. Other children's routes stay
|
|
37
|
+
* independently answerable.
|
|
29
38
|
*/
|
|
30
39
|
export declare function upsertProxyInputRequests(input: {
|
|
31
40
|
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
32
41
|
readonly forChildContinuationToken: string;
|
|
33
42
|
readonly session: HarnessSession;
|
|
34
43
|
}): HarnessSession;
|
|
44
|
+
/** State-only variant for control-plane steps that already hold a durable projection. */
|
|
45
|
+
export declare function upsertProxyInputRequestState(input: {
|
|
46
|
+
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
47
|
+
readonly forChildContinuationToken: string;
|
|
48
|
+
readonly state: SessionStateMap | undefined;
|
|
49
|
+
}): SessionStateMap | undefined;
|
|
35
50
|
/**
|
|
36
51
|
* Removes every entry for `childContinuationToken`. Called when a
|
|
37
52
|
* child subagent finishes so stale clicks no longer route to it.
|
|
@@ -41,6 +56,8 @@ export declare function clearProxyInputRequestsForChild(session: HarnessSession,
|
|
|
41
56
|
export declare function retireProxyInputRequests<T extends {
|
|
42
57
|
readonly state?: SessionStateMap;
|
|
43
58
|
}>(session: T, requestIds: readonly string[]): T;
|
|
59
|
+
/** Removes every proxy route owned by one durable task. */
|
|
60
|
+
export declare function clearProxyInputRequestsForTask(session: HarnessSession, taskId: string): HarnessSession;
|
|
44
61
|
/**
|
|
45
62
|
* Removes every proxy entry. Called when a cancelled turn orphans its
|
|
46
63
|
* descendants so stale HITL responses no longer route to them.
|
|
@@ -50,4 +67,4 @@ export declare function clearAllProxyInputRequests(session: HarnessSession): Har
|
|
|
50
67
|
* Projects a {@link SubagentInputRequestHookPayload} into the
|
|
51
68
|
* `(requestId, route)` tuples the session stores.
|
|
52
69
|
*/
|
|
53
|
-
export declare function toProxyInputRequestEntries(payload: SubagentInputRequestHookPayload): readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
70
|
+
export declare function toProxyInputRequestEntries(payload: SubagentInputRequestHookPayload, taskId?: string): readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const PROXY_INPUT_REQUESTS_KEY=`eve.runtime.proxyInputRequests`,PROXY_INPUT_REQUEST_KINDS={question:!0,"session-limit":!0,"tool-approval":!0};function getProxyInputRequests(e){return new Map(Object.entries(readMap(e)))}function hasProxyInputRequests(e){for(let t of Object.keys(readMap(e)))return!0;return!1}function upsertProxyInputRequests(e){
|
|
1
|
+
import{isLoopbackHostname}from"#shared/network-address.js";const PROXY_INPUT_REQUESTS_KEY=`eve.runtime.proxyInputRequests`,PROXY_INPUT_REQUEST_KINDS={question:!0,"session-limit":!0,"tool-approval":!0};function createTaskInputRequestId(e,t){return`${e}:${t}`}function getProxyInputRequests(e){return new Map(Object.entries(readMap(e)))}function hasProxyInputRequests(e){for(let t of Object.keys(readMap(e)))return!0;return!1}function upsertProxyInputRequests(e){return{...e.session,state:upsertProxyInputRequestState({entries:e.entries,forChildContinuationToken:e.forChildContinuationToken,state:e.session.state})}}function upsertProxyInputRequestState(e){let n={};for(let[t,r]of Object.entries(readMap(e.state)))r.childContinuationToken!==e.forChildContinuationToken&&(n[t]=r);for(let[t,r]of e.entries)n[t]=r;let r={...e.state};return Object.keys(n).length===0?delete r[PROXY_INPUT_REQUESTS_KEY]:r[PROXY_INPUT_REQUESTS_KEY]=n,Object.keys(r).length>0?r:void 0}function clearProxyInputRequestsForChild(e,t){let n=readMap(e.state),r={},i=!1;for(let[e,a]of Object.entries(n)){if(a.childContinuationToken===t){i=!0;continue}r[e]=a}return i?writeMap(e,r):e}function retireProxyInputRequests(e,t){let n={...readMap(e.state)},r=!1;for(let e of t)Object.hasOwn(n,e)&&(delete n[e],r=!0);return r?writeMap(e,n):e}function clearProxyInputRequestsForTask(e,t){let n=readMap(e.state),r={},i=!1;for(let[e,a]of Object.entries(n))a.taskId===t?i=!0:r[e]=a;return i?writeMap(e,r):e}function clearAllProxyInputRequests(e){return hasProxyInputRequests(e.state)?writeMap(e,{}):e}function toProxyInputRequestEntries(e,t){let n={approvalRequestIds:e.event.requests.flatMap(e=>e.kind===`tool-approval`?[e.requestId]:[]),requestIds:e.event.requests.map(e=>e.requestId)};return e.event.requests.map(r=>{let i={batch:n,childContinuationToken:e.childContinuationToken,kind:r.kind};return t!==void 0&&(i.taskId=t),[r.requestId,i]})}function readMap(e){let n=e?.[PROXY_INPUT_REQUESTS_KEY];if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n)){let n=parseProxyInputRequest(t,e);n!==void 0&&(r[e]=n)}return r}function writeMap(e,n){let r={...e.state};return Object.keys(n).length===0?(delete r[PROXY_INPUT_REQUESTS_KEY],{...e,state:Object.keys(r).length>0?r:void 0}):(r[PROXY_INPUT_REQUESTS_KEY]=n,{...e,state:r})}function parseProxyInputRequest(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||!(`childContinuationToken`in e)||!(`kind`in e)||typeof e.childContinuationToken!=`string`||!isInputRequestKind(e.kind))return;let n=`taskId`in e?e.taskId:void 0,r=`childRequestId`in e?e.childRequestId:void 0,i=`childResponseUrl`in e?e.childResponseUrl:void 0;if(n!==void 0&&(typeof n!=`string`||n.length===0)||r!==void 0&&(typeof r!=`string`||r.length===0)||n===void 0!=(r===void 0)||i!==void 0&&(typeof i!=`string`||!isAllowedChildResponseUrl(i)))return;let a=`batch`in e?parseProxyInputRequestBatch(e.batch):void 0,o={childContinuationToken:e.childContinuationToken,kind:e.kind};return a!==void 0&&a.requestIds.includes(t)&&(o.batch=a),typeof r==`string`&&(o.childRequestId=r),typeof i==`string`&&(o.childResponseUrl=i),typeof n==`string`&&(o.taskId=n),o}function parseProxyInputRequestBatch(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`approvalRequestIds`in e)||!(`requestIds`in e)||!isStringArray(e.approvalRequestIds)||!isStringArray(e.requestIds))return;let t=new Set(e.requestIds);if(!(t.size!==e.requestIds.length||e.approvalRequestIds.some(e=>!t.has(e))))return{approvalRequestIds:e.approvalRequestIds,requestIds:e.requestIds}}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function isAllowedChildResponseUrl(t){let n;try{n=new URL(t)}catch{return!1}return n.protocol===`https:`||n.protocol===`http:`&&isLoopbackHostname(n.hostname)}function isInputRequestKind(e){return typeof e==`string`&&Object.hasOwn(PROXY_INPUT_REQUEST_KINDS,e)}export{clearAllProxyInputRequests,clearProxyInputRequestsForChild,clearProxyInputRequestsForTask,createTaskInputRequestId,getProxyInputRequests,hasProxyInputRequests,retireProxyInputRequests,toProxyInputRequestEntries,upsertProxyInputRequestState,upsertProxyInputRequests};
|
|
@@ -49,6 +49,8 @@ export declare function setPendingRuntimeActionBatch(input: {
|
|
|
49
49
|
readonly responseMessages: readonly ModelMessage[];
|
|
50
50
|
readonly session: HarnessSession;
|
|
51
51
|
}): HarnessSession;
|
|
52
|
+
/** Rejects an ambiguous action batch before any result or side effect can bind by call id. */
|
|
53
|
+
export declare function assertUniqueRuntimeActionCallIds(actions: readonly RuntimeActionRequest[]): void;
|
|
52
54
|
/**
|
|
53
55
|
* Resolves one pending runtime-action batch back into model history.
|
|
54
56
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";
|
|
1
|
+
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function readSubagentResultOutcome(e){return e.origin===`child`?e.outcome:void 0}function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){assertUniqueRuntimeActionCallIds(e.actions);let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function assertUniqueRuntimeActionCallIds(e){let t=new Set;for(let n of e){if(t.has(n.callId))throw Error(`Runtime action batch contains duplicate callId "${n.callId}".`);t.add(n.callId)}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results,state:e.session.state})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results.filter(t=>isResultBoundToRunningHandle(e.state,t))})}async function resolvePendingRuntimeActions(t){let o=getPendingRuntimeActionBatch(t.session.state);if(o===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let s=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(s===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of s){if(n.kind===`subagent-result`&&n.isError!==!0){let e=readBackgroundTaskReceipt(n),r={callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName};await t.emit({data:e===void 0?r:{...r,backgroundTask:e},type:`subagent.completed`})}await t.emit(createActionResultEvent({result:n,sequence:o.event.sequence,stepIndex:o.event.stepIndex,turnId:o.event.turnId}))}let c=t.session;for(let e of s){if(e.kind!==`subagent-result`||e.origin!==`child`||readBackgroundTaskReceipt(e)!==void 0)continue;let t=findRunningAgentHandle(c.state,{callId:e.callId});if(t===void 0)continue;let i=readSubagentResultOutcome(e);if(i===void 0)continue;i.kind===`terminal`&&`continuationToken`in t.address&&(c=clearProxyInputRequestsForChild(c,t.address.continuationToken));let a=settleAgentTurn(c,{operationId:t.operation.id,outcome:i});a.kind===`settled`&&(c=a.session)}let l={...c.state};delete l[PENDING_RUNTIME_ACTION_BATCH_KEY],c={...c,state:Object.keys(l).length>0?l:void 0};for(let e of s){if(e.kind!==`subagent-result`)continue;let t=readSubagentResultOutcome(e);t!==void 0&&(c=setTurnUsageState(c,accumulateSessionUsage({previous:getTurnUsageState(c.state),usage:t.usageDelta})))}let u=s.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),d=[...c.history,...o.responseMessages];return u.length>0&&d.push({content:u,role:`tool`}),{messages:d,outcome:`resolved`,session:c}}function readBackgroundTaskReceipt(e){return`backgroundTask`in e?e.backgroundTask:void 0}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.frameworkAction===`load-skill`?{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`load-skill`}:t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null||typeof e==`string`&&e.trim()===``)return{};try{return parseJsonObject(typeof e==`string`?parseJsonStringInput(e):e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function parseJsonStringInput(e){return JSON.parse(e)}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{assertUniqueRuntimeActionCallIds,clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,resolvePendingRuntimeActions,resolveToolCallInputObject,setPendingRuntimeActionBatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{appendPendingInputBatch}from"#harness/input-requests.js";import{
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{appendPendingInputBatch}from"#harness/input-requests.js";import{bumpSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";import{SessionLimitDeclinedError}from"#harness/turn-cancellation.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:bumpSessionRuntimeTokenLimits(e.session)};if(!(e.config.mode===`conversation`||e.session.continuationToken!==``)){let t=getSessionTokenLimitViolation(e.session);return{result:t===null?{next:{done:!0,output:``},session:e.session}:await failSessionTokenLimit({...e,violation:t}),session:e.session}}throw new SessionLimitDeclinedError}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return t.limit>0&&n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let a=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,violation:t.violation}),o=t.emissionState,s=appendPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:[a],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[a],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.config.mode===`conversation`&&(o=await emitTurnEpilogue(t.emit,o,t.config.mode)),{next:null,session:setHarnessEmissionState(s,o)}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let n=getSessionTokenUsage(e.session),r=formatSessionTokenLimitMessage(e.violation.kind),i={inputTokens:n.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:n.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:i,message:r,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`||void 0,output:e.config.mode===`task`?r:``},session:e.session}}export{applySessionLimitContinuation,enforceSessionTokenLimit};
|