eve 0.47.7 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/src/channel/delivery-metadata.d.ts +1 -0
- package/dist/src/channel/delivery-metadata.js +1 -1
- package/dist/src/channel/types.d.ts +10 -8
- package/dist/src/chunks/{use-eve-agent-Dg5S44kG.js → use-eve-agent-BZnOzAVd.js} +25 -5
- package/dist/src/chunks/{use-eve-agent-B5zw1dwj.js → use-eve-agent-Bgp6INfi.js} +25 -5
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/integration-connect.d.ts +2 -1
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/register-integration-commands.d.ts +3 -1
- package/dist/src/cli/commands/register-integration-commands.js +1 -1
- package/dist/src/cli/dev/command-options.d.ts +2 -0
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/blocks.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.d.ts +17 -0
- package/dist/src/cli/dev/tui/registry-result-message.js +3 -0
- package/dist/src/cli/dev/tui/runner.d.ts +11 -4
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +9 -3
- package/dist/src/cli/dev/tui/setup-commands.js +2 -3
- package/dist/src/cli/dev/tui/setup-flow.d.ts +15 -5
- package/dist/src/cli/dev/tui/setup-panel.d.ts +6 -1
- package/dist/src/cli/dev/tui/setup-panel.js +4 -4
- package/dist/src/cli/dev/tui/setup-selection-input.d.ts +1 -0
- package/dist/src/cli/dev/tui/setup-selection-input.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/cli/dev/tui/tui.d.ts +3 -4
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/run.js +2 -2
- package/dist/src/client/agent-info-schema.d.ts +1 -0
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/open-stream.d.ts +1 -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 +2 -1
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +6 -0
- package/dist/src/compiled/@workflow/builders/LICENSE.md +201 -0
- package/dist/src/compiled/@workflow/builders/index.d.ts +62 -0
- package/dist/src/compiled/@workflow/builders/index.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +2 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/context/keys.d.ts +3 -8
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +7 -7
- package/dist/src/execution/accepted-delivery-deployment.d.ts +7 -0
- package/dist/src/execution/accepted-delivery-deployment.js +1 -0
- package/dist/src/execution/cancel-descendant-turns-step.d.ts +4 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/delegation-tool.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +7 -2
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-turn-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.d.ts +2 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.js +1 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +25 -3
- package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/finalize-terminal-session.d.ts +17 -0
- package/dist/src/execution/finalize-terminal-session.js +1 -0
- package/dist/src/execution/inline-turn.d.ts +29 -0
- package/dist/src/execution/inline-turn.js +1 -0
- package/dist/src/execution/next-driver-action.d.ts +4 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/pending-turn-state.d.ts +1 -0
- package/dist/src/execution/pending-turn-state.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +2 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/session-command-token.d.ts +2 -0
- package/dist/src/execution/session-command-token.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/stable-workflow-names.d.ts +12 -0
- package/dist/src/execution/stable-workflow-names.js +1 -0
- package/dist/src/execution/subagent-event-proxy-step.d.ts +3 -0
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +2 -1
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/subagent-start-remote.d.ts +2 -0
- package/dist/src/execution/subagent-start-remote.js +1 -1
- package/dist/src/execution/tasks/child/steps.d.ts +2 -0
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.js +1 -1
- package/dist/src/execution/terminal-session-event.d.ts +13 -0
- package/dist/src/execution/terminal-session-event.js +1 -0
- package/dist/src/execution/terminal-session-failure-step.d.ts +1 -0
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/tool-run/answer.d.ts +3 -0
- package/dist/src/execution/tool-run/answer.js +1 -0
- package/dist/src/execution/tool-run/background.d.ts +14 -0
- package/dist/src/execution/tool-run/background.js +1 -0
- package/dist/src/execution/tool-run/cancel.d.ts +7 -0
- package/dist/src/execution/tool-run/cancel.js +1 -0
- package/dist/src/execution/tool-run/dispatch.d.ts +24 -0
- package/dist/src/execution/tool-run/dispatch.js +1 -0
- package/dist/src/execution/tool-run/emit-run-report-step.d.ts +7 -0
- package/dist/src/execution/tool-run/emit-run-report-step.js +1 -0
- package/dist/src/execution/tool-run/messages.d.ts +70 -0
- package/dist/src/execution/tool-run/messages.js +1 -0
- package/dist/src/execution/tool-run/owner-channels.d.ts +29 -0
- package/dist/src/execution/tool-run/owner-channels.js +1 -0
- package/dist/src/execution/tool-run/owner-inbox.d.ts +11 -0
- package/dist/src/execution/tool-run/owner-inbox.js +1 -0
- package/dist/src/execution/tool-run/owner.d.ts +13 -0
- package/dist/src/execution/tool-run/owner.js +1 -0
- package/dist/src/execution/tool-run/resume-hook-step.d.ts +4 -0
- package/dist/src/execution/tool-run/resume-hook-step.js +1 -0
- package/dist/src/execution/tool-run/run-control.d.ts +18 -0
- package/dist/src/execution/tool-run/run-control.js +1 -0
- package/dist/src/execution/tool-run/start.d.ts +11 -0
- package/dist/src/execution/tool-run/start.js +1 -0
- package/dist/src/execution/tool-run/types.d.ts +21 -0
- package/dist/src/execution/tool-run/types.js +1 -0
- package/dist/src/execution/tool-run/workflow.d.ts +9 -0
- package/dist/src/execution/tool-run/workflow.js +1 -0
- package/dist/src/execution/tools/subagent/local.js +1 -1
- package/dist/src/execution/turn-cancellation-control.d.ts +2 -0
- package/dist/src/execution/turn-cancellation-control.js +1 -1
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +4 -2
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
- package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v1.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.d.ts +0 -2
- package/dist/src/execution/wire/session-inbox-wire.v2-migration.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v2.migration.d.ts +3 -0
- package/dist/src/execution/wire/session-inbox-wire.v2.migration.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.d.ts +480 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.js +1 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.migration.d.ts +3 -0
- package/dist/src/execution/wire/session-inbox-wire.v3.migration.js +1 -0
- package/dist/src/execution/workflow-entry-finalization.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-registry.d.ts +5 -0
- package/dist/src/execution/workflow-registry.js +1 -0
- package/dist/src/execution/workflow-runtime.d.ts +9 -11
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/execution/workflow-webhook-route.d.ts +4 -0
- package/dist/src/execution/workflow-webhook-route.js +1 -0
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +10 -0
- 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/tool-runs.d.ts +21 -0
- package/dist/src/harness/tool-runs.js +1 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/instrumentation/content-policy.d.ts +3 -1
- package/dist/src/instrumentation/content-policy.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +2 -2
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/attachments/errors.d.ts +3 -0
- package/dist/src/internal/authored-module-loader.d.ts +7 -1
- package/dist/src/internal/authored-module-loader.js +3 -3
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/authored-runtime-modules.d.ts +2 -0
- package/dist/src/internal/authored-runtime-modules.js +1 -1
- package/dist/src/internal/nitro/development-generation.d.ts +2 -0
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.d.ts +17 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.d.ts +19 -0
- package/dist/src/internal/workflow-bundle/authored-workflow-modules.js +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +17 -2
- package/dist/src/internal/workflow-bundle/builder-support.js +4 -3
- package/dist/src/internal/workflow-bundle/builder.d.ts +2 -2
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.d.ts +2 -0
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +3 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +6 -2
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +3 -0
- package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.d.ts +7 -0
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.js +1 -0
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +15 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -4
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/baggage.d.ts +6 -0
- package/dist/src/protocol/baggage.js +1 -0
- package/dist/src/public/channels/slack/attachments.js +1 -1
- package/dist/src/public/channels/teams/attachments.d.ts +2 -2
- package/dist/src/public/channels/teams/attachments.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/attachments.js +1 -1
- package/dist/src/public/definitions/remote-agent.d.ts +6 -3
- package/dist/src/public/workflow/index.d.ts +3 -0
- package/dist/src/public/workflow/index.js +1 -0
- package/dist/src/public/workflow-modules.d.js +1 -0
- package/dist/src/public/workflow-modules.d.ts +11 -0
- package/dist/src/runtime/actions/keys.js +1 -1
- package/dist/src/runtime/tools/registry.js +1 -1
- package/dist/src/setup/connection-connector.d.ts +4 -2
- package/dist/src/setup/connection-connector.js +2 -2
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/flows/provider.d.ts +5 -0
- package/dist/src/setup/flows/provider.js +4 -4
- package/dist/src/setup/flows/registry-session.d.ts +24 -7
- package/dist/src/setup/flows/registry-session.js +1 -1
- package/dist/src/setup/flows/registry.d.ts +35 -29
- package/dist/src/setup/flows/registry.js +2 -1
- package/dist/src/setup/integrations/web/setup.d.ts +0 -2
- package/dist/src/setup/integrations/web/setup.js +1 -1
- package/dist/src/setup/prompter.d.ts +24 -4
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/shared/dispatch-action.d.ts +6 -0
- package/dist/src/shared/forwarded-trace-policy.d.ts +28 -0
- package/dist/src/shared/forwarded-trace-policy.js +1 -0
- package/dist/src/shared/instrumentation-decision.d.ts +3 -0
- package/dist/src/shared/instrumentation-decision.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/behavior.d.ts +6 -0
- package/dist/src/tools/definition.d.ts +39 -3
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.d.ts +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/otel-declaration.d.ts +5 -3
- package/dist/src/tracing/otel-registration.d.ts +1 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +2 -0
- package/docs/channels/eve.mdx +5 -1
- package/docs/channels/teams.mdx +6 -1
- package/docs/concepts/sessions-runs-and-streaming.md +4 -2
- package/docs/guides/auth-and-route-protection.md +5 -1
- package/docs/guides/client/messages.mdx +6 -0
- package/docs/guides/dev-tui.md +30 -18
- package/docs/guides/remote-agents.md +25 -0
- package/docs/reference/cli.md +2 -2
- package/docs/tools/meta.json +1 -1
- package/docs/tools/overview.mdx +7 -0
- package/docs/tools/workflows.mdx +288 -0
- package/package.json +12 -1
- package/dist/src/internal/authored-directive-prologue.d.ts +0 -4
- package/dist/src/internal/authored-directive-prologue.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[],s;for(let i of n){let n=t.get(i.requestId);if(n===void 0||e.allowRoute?.(i.requestId,n)===!1){a.push(i);continue}n.kind===`session-limit`&&i.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let c=n.taskId===void 0?n.childContinuationToken:`${n.childContinuationToken}\0${n.childResponseUrl??`local`}\0${n.taskId}`,l=r.get(c);l===void 0?r.set(c,{childContinuationToken:n.childContinuationToken,parentRequestIds:[i.requestId],responses:[toChildInputResponse(i,n)],routes:[n],...n.childResponseUrl!==void 0&&{childResponseUrl:n.childResponseUrl},...n.taskId!==void 0&&{taskId:n.taskId}}):(l.parentRequestIds.push(i.requestId),l.responses.push(toChildInputResponse(i,n)),l.routes.push(n))}let c=[...r.values()].map(({
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[],s;for(let i of n){let n=t.get(i.requestId);if(n===void 0||e.allowRoute?.(i.requestId,n)===!1){a.push(i);continue}n.kind===`session-limit`&&i.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let c=n.taskId===void 0?n.childContinuationToken:`${n.childContinuationToken}\0${n.childResponseUrl??`local`}\0${n.taskId}`,l=r.get(c);l===void 0?r.set(c,{childContinuationToken:n.childContinuationToken,parentRequestIds:[i.requestId],responses:[toChildInputResponse(i,n)],routes:[n],...n.answerHook!==void 0&&{answerHook:n.answerHook},...n.childResponseUrl!==void 0&&{childResponseUrl:n.childResponseUrl},...n.taskId!==void 0&&{taskId:n.taskId}}):(l.parentRequestIds.push(i.requestId),l.responses.push(toChildInputResponse(i,n)),l.routes.push(n))}let c=[...r.values()].map(({answerHook:e,childContinuationToken:n,childResponseUrl:r,parentRequestIds:i,responses:a,routes:o,taskId:s})=>{let c=new Set(i),l=new Set(c);for(let e of o)if(e.batch!==void 0&&batchResolves({batch:e.batch,childContinuationToken:n,entries:t,responseIds:c}))for(let t of e.batch.requestIds)l.add(t);return{childContinuationToken:n,payload:{inputResponses:a},retireRequestIds:[...l],...e!==void 0&&{answerHook:e},...r!==void 0&&{childResponseUrl:r},...s!==void 0&&{taskId:s}}}),l={};for(let[t,n]of Object.entries(e.payload))t===`inputResponses`||n===void 0||(l[t]=n);return a.length>0&&(l.inputResponses=a),{forChildren:c,forSelf:Object.keys(l).length>0?l:void 0,parentAction:s}}function batchResolves(e){return e.batch.approvalRequestIds.length===0||e.batch.approvalRequestIds.every(t=>{let n=e.entries.get(t);return n===void 0||!sameBatch(n,e)||e.responseIds.has(t)})}function sameBatch(e,t){return e.childContinuationToken===t.childContinuationToken&&e.batch?.requestIds.length===t.batch.requestIds.length&&e.batch.requestIds.every((e,n)=>e===t.batch.requestIds[n])}function toChildInputResponse(e,t){return t.childRequestId===void 0?e:{...e,requestId:t.childRequestId}}export{emitProxiedInputRequest,routeDeliverPayload};
|
|
@@ -2,6 +2,7 @@ import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-di
|
|
|
2
2
|
import { resolveRemoteAgentForAction, startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";
|
|
3
3
|
import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
|
|
4
4
|
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
5
|
+
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
5
6
|
/** Starts one remote subagent after dispatch planning has selected its target. */
|
|
6
7
|
export declare function startRemoteSubagent(input: {
|
|
7
8
|
readonly action: RuntimeRemoteAgentCallActionRequest;
|
|
@@ -12,6 +13,7 @@ export declare function startRemoteSubagent(input: {
|
|
|
12
13
|
};
|
|
13
14
|
readonly bundle: CompiledBundle;
|
|
14
15
|
readonly callbackBaseUrl: string | undefined;
|
|
16
|
+
readonly originAudience: ChannelAudience;
|
|
15
17
|
readonly currentSession: RuntimeSession;
|
|
16
18
|
readonly dynamicRemoteAgent?: NonNullable<Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]>;
|
|
17
19
|
readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{confirmAgentStarted,confirmTaskAgentAddress,prepareAgentStart,rejectAgentEffect}from"#harness/handles/transitions.js";import{createRemoteAgentStartFailureResult}from"#execution/dispatch-action-failures.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";const log=createLogger(`execution.subagent-start-remote`);async function startRemoteSubagent(e){let{action:r}=e,i=deriveChildActivityObserverConfig({activityObserver:e.activityObserver,callId:r.callId,kind:`remote-agent`,name:r.remoteAgentName,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),a,o;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);a=e.callbackBaseUrl,o=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:r,error:n}),session:e.currentSession}}let{identity:s,operation:c}=mintStartOperation({callId:r.callId,name:r.remoteAgentName,nodeId:r.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),l={resolverId:e.dynamicRemoteAgent===void 0?r.nodeId:e.dynamicRemoteAgent.credentialsStepId},u=prepareAgentStart(e.currentSession,{identity:s,operation:c,target:{callbackBaseUrl:a,credentialResolver:l,kind:`agent/remote`,url:o.url}});try{let t=await startRemoteAgentSession({action:r,auth:e.auth,callbackBaseUrl:a,callbackToken:e.parentContinuationToken,initiatorAuth:e.initiatorAuth,operationId:c.id,parentTraceContext:e.parentTraceContext,activityObserver:i,remote:o,session:e.session}),n={callbackBaseUrl:a,credentialResolver:l,kind:`agent/remote`,sessionId:t.sessionId,url:o.url};return{address:n,callId:r.callId,kind:`called`,name:r.name,session:e.taskOwned?confirmTaskAgentAddress(u,{address:n,operationId:c.id}):confirmAgentStarted(u,{address:n,operationId:c.id}),toolName:r.remoteAgentName}}catch(e){return logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:r,error:e}),session:rejectAgentEffect(u,{disposition:`dead`,operationId:c.id})}}}export{startRemoteSubagent};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{confirmAgentStarted,confirmTaskAgentAddress,prepareAgentStart,rejectAgentEffect}from"#harness/handles/transitions.js";import{createRemoteAgentStartFailureResult}from"#execution/dispatch-action-failures.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";const log=createLogger(`execution.subagent-start-remote`);async function startRemoteSubagent(e){let{action:r}=e,i=deriveChildActivityObserverConfig({activityObserver:e.activityObserver,callId:r.callId,kind:`remote-agent`,name:r.remoteAgentName,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),a,o;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);a=e.callbackBaseUrl,o=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:r,error:n}),session:e.currentSession}}let{identity:s,operation:c}=mintStartOperation({callId:r.callId,name:r.remoteAgentName,nodeId:r.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),l={resolverId:e.dynamicRemoteAgent===void 0?r.nodeId:e.dynamicRemoteAgent.credentialsStepId},u=prepareAgentStart(e.currentSession,{identity:s,operation:c,target:{callbackBaseUrl:a,credentialResolver:l,kind:`agent/remote`,url:o.url}});try{let t=await startRemoteAgentSession({action:r,auth:e.auth,callbackBaseUrl:a,callbackToken:e.parentContinuationToken,originAudience:e.originAudience,initiatorAuth:e.initiatorAuth,operationId:c.id,parentTraceContext:e.parentTraceContext,activityObserver:i,remote:o,session:e.session}),n={callbackBaseUrl:a,credentialResolver:l,kind:`agent/remote`,sessionId:t.sessionId,url:o.url};return{address:n,callId:r.callId,kind:`called`,name:r.name,session:e.taskOwned?confirmTaskAgentAddress(u,{address:n,operationId:c.id}):confirmAgentStarted(u,{address:n,operationId:c.id}),toolName:r.remoteAgentName}}catch(e){return logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:r,error:e}),session:rejectAgentEffect(u,{disposition:`dead`,operationId:c.id})}}}export{startRemoteSubagent};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ActivityObserverConfig } from "#channel/types.js";
|
|
2
|
+
import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
|
|
2
3
|
import type { ActivityEventV1 } from "#protocol/activity.js";
|
|
3
4
|
import { type TaskInboundAnswerInput, type TaskInboundAuthorizationEvent, type TaskInboundInputRequest, type TaskInboundUpdate, type TaskView } from "#tasks/types.js";
|
|
4
5
|
/**
|
|
@@ -56,6 +57,7 @@ export declare function wakeTaskInputRequestParentStep(input: {
|
|
|
56
57
|
*/
|
|
57
58
|
export declare function deliverTaskInputResponsesStep(input: {
|
|
58
59
|
readonly answer: TaskInboundAnswerInput;
|
|
60
|
+
readonly answerHook?: AnswerHookRoute;
|
|
59
61
|
readonly requestIds: readonly string[];
|
|
60
62
|
}): Promise<"delivered" | "unreachable">;
|
|
61
63
|
export declare function formatTaskNotification(view: TaskView): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{getWritable}from"#compiled/@workflow/core/index.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{submitActivity}from"#execution/submit-activity.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";import{TASK_VIEW_STREAM_NAMESPACE,isTerminalTaskStatus,taskAuthorizationRequestId}from"#tasks/types.js";const log=createLogger(`execution.tasks.run`);async function appendTaskViewStep(e){"use step";let n=getWritable({namespace:TASK_VIEW_STREAM_NAMESPACE}).getWriter();try{await n.write(e.view)}finally{n.releaseLock()}submitActivity({events:projectTaskActivitySettlement({activityObserver:e.activityObserver,settledAt:new Date().toISOString(),view:e.view}),sink:e.activityObserver?.sink})}function projectTaskActivitySettlement(e){let t=e.activityObserver?.workIdentity,n=e.view.status;return t===void 0||n!==`completed`&&n!==`failed`&&n!==`cancelled`?[]:[{eventId:`${t.id}:settled:${n}`,kind:`work.settled`,outcome:n,settledAt:e.settledAt,workId:t.id}]}async function wakeTaskAuthorizationParentStep(e){"use step";let t={callId:e.request.callId,childSessionId:e.request.childSessionId,event:e.request.event,kind:`subagent-authorization-event`,subagentName:e.request.subagentName},r=e.request.event.data,i={task:{authorizationEvents:[{hookPayload:t,taskId:e.taskId}]}};e.request.event.type===`authorization.required`&&(i.message=`Background task ${e.taskId} needs authorization.`);let a={kind:`send`,payload:i,taskDeliveryId:`${e.taskId}:authorization:${e.request.event.type}:${r.turnId}:${r.stepIndex}:${r.sequence}:${taskAuthorizationRequestId(e.request.event)}`};try{await resumeSessionInbox(e.token,a)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskParentStep(e){"use step";let t={message:formatTaskNotification(e.view)};isTerminalTaskStatus(e.view.status)&&(t.task={views:[e.view]});let r={kind:`send`,payload:t,taskDeliveryId:`${e.view.taskId}:ready:${e.view.status}`};try{await resumeSessionInbox(e.token,r)}catch(t){if(isTaskWorkflowTargetGone(t)){log.warn(`task wake target is gone; the parent session already ended`,{status:e.view.status,taskId:e.view.taskId});return}throw t}}async function wakeTaskUpdateParentStep(e){"use step";let t={kind:`send`,payload:{message:`Background task ${e.view.taskId} (${e.view.metadata.name}) update: ${e.update.message}`},taskDeliveryId:`${e.view.taskId}:update:${e.update.updateEpoch}:${e.update.updateIndex}:${e.update.callId}`};try{await resumeSessionInbox(e.token,t)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskInputRequestParentStep(e){"use step";let t={kind:`send`,payload:{task:{inputRequests:[{hookPayload:e.request,taskId:e.taskId}]}},taskDeliveryId:`${e.taskId}:input:${e.request.event.turnId}:${e.request.event.stepIndex}:${e.request.event.sequence}`};try{await resumeSessionInbox(e.token,t)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function deliverTaskInputResponsesStep(e){"use step";let t=new Set(e.requestIds),
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{getWritable}from"#compiled/@workflow/core/index.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{resumeToolRunAnswers}from"#execution/tool-run/answer.js";import{submitActivity}from"#execution/submit-activity.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";import{TASK_VIEW_STREAM_NAMESPACE,isTerminalTaskStatus,taskAuthorizationRequestId}from"#tasks/types.js";const log=createLogger(`execution.tasks.run`);async function appendTaskViewStep(e){"use step";let n=getWritable({namespace:TASK_VIEW_STREAM_NAMESPACE}).getWriter();try{await n.write(e.view)}finally{n.releaseLock()}submitActivity({events:projectTaskActivitySettlement({activityObserver:e.activityObserver,settledAt:new Date().toISOString(),view:e.view}),sink:e.activityObserver?.sink})}function projectTaskActivitySettlement(e){let t=e.activityObserver?.workIdentity,n=e.view.status;return t===void 0||n!==`completed`&&n!==`failed`&&n!==`cancelled`?[]:[{eventId:`${t.id}:settled:${n}`,kind:`work.settled`,outcome:n,settledAt:e.settledAt,workId:t.id}]}async function wakeTaskAuthorizationParentStep(e){"use step";let t={callId:e.request.callId,childSessionId:e.request.childSessionId,event:e.request.event,kind:`subagent-authorization-event`,subagentName:e.request.subagentName},r=e.request.event.data,i={task:{authorizationEvents:[{hookPayload:t,taskId:e.taskId}]}};e.request.event.type===`authorization.required`&&(i.message=`Background task ${e.taskId} needs authorization.`);let a={kind:`send`,payload:i,taskDeliveryId:`${e.taskId}:authorization:${e.request.event.type}:${r.turnId}:${r.stepIndex}:${r.sequence}:${taskAuthorizationRequestId(e.request.event)}`};try{await resumeSessionInbox(e.token,a)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskParentStep(e){"use step";let t={message:formatTaskNotification(e.view)};isTerminalTaskStatus(e.view.status)&&(t.task={views:[e.view]});let r={kind:`send`,payload:t,taskDeliveryId:`${e.view.taskId}:ready:${e.view.status}`};try{await resumeSessionInbox(e.token,r)}catch(t){if(isTaskWorkflowTargetGone(t)){log.warn(`task wake target is gone; the parent session already ended`,{status:e.view.status,taskId:e.view.taskId});return}throw t}}async function wakeTaskUpdateParentStep(e){"use step";let t={kind:`send`,payload:{message:`Background task ${e.view.taskId} (${e.view.metadata.name}) update: ${e.update.message}`},taskDeliveryId:`${e.view.taskId}:update:${e.update.updateEpoch}:${e.update.updateIndex}:${e.update.callId}`};try{await resumeSessionInbox(e.token,t)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskInputRequestParentStep(e){"use step";let t={kind:`send`,payload:{task:{inputRequests:[{hookPayload:e.request,taskId:e.taskId}]}},taskDeliveryId:`${e.taskId}:input:${e.request.event.turnId}:${e.request.event.stepIndex}:${e.request.event.sequence}`};try{await resumeSessionInbox(e.token,t)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function deliverTaskInputResponsesStep(e){"use step";let t=new Set(e.requestIds),i={auth:e.answer.auth,kind:`send`,payload:{inputResponses:e.answer.inputResponses.filter(e=>t.has(e.requestId))},taskDeliveryId:`${e.answer.taskId}:${[...e.requestIds].sort().join(`,`)}`};try{if(e.answer.childResponseUrl!==void 0){let t=await fetch(e.answer.childResponseUrl,{body:JSON.stringify({inputResponses:i.payload.inputResponses}),headers:{"content-type":`application/json`},method:`POST`,redirect:`error`});if(t.status===404)return`unreachable`;if(!t.ok)throw Error(`Remote task input delivery failed with HTTP ${t.status}.`)}else e.answerHook===void 0?await resumeSessionInbox(e.answer.childContinuationToken,i):await resumeToolRunAnswers(e.answer.childContinuationToken,i.payload.inputResponses);return`delivered`}catch(t){if(isTaskWorkflowTargetGone(t))return log.warn(`task input answer target is gone; the child turn already ended`,{taskId:e.answer.taskId}),`unreachable`;throw t}}function formatTaskNotification(e){let t=`Background task ${e.taskId} (${e.metadata.name})`;return e.status===`input_required`?`${t} needs input.`:e.status===`completed`?`${t} is completed.\n\nResult:\n${formatTaskOutput(e.lastOutput.data)}`:e.status===`failed`?`${t} failed.\n\nError:\n${formatTaskOutput(e.lastOutput.data)}`:`${t} is cancelled.`}function formatTaskOutput(e){return typeof e==`string`?e:JSON.stringify(e)??`null`}export{appendTaskViewStep,deliverTaskInputResponsesStep,formatTaskNotification,projectTaskActivitySettlement,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,wakeTaskUpdateParentStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{isReadyTaskStatus,isTerminalTaskStatus,readTaskInputRequestId,readTaskUsage}from"#tasks/types.js";import{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,wakeTaskUpdateParentStep}from"#execution/tasks/child/steps.js";import{applyTaskTransition}from"#tasks/transitions.js";import{translateTaskInboundPayload}from"#tasks/wire.js";function isTaskRunFinished(e,t){return!isTerminalTaskStatus(e.status)||!t?!1:e.status!==`cancelled`||e.executor?.lifecycle===`terminal`}async function taskRunWorkflow(
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{isReadyTaskStatus,isTerminalTaskStatus,readTaskInputRequestId,readTaskUsage}from"#tasks/types.js";import{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,wakeTaskUpdateParentStep}from"#execution/tasks/child/steps.js";import{applyTaskTransition}from"#tasks/transitions.js";import{translateTaskInboundPayload}from"#tasks/wire.js";import{createChannelReader,raceChannelReads}from"#execution/tool-run/owner-channels.js";import{openRunOwnerChannels}from"#execution/tool-run/owner.js";import{runOutcomeToTaskCommand,runReportToTaskUpdate,runRequestToInputRequestPayload}from"#execution/tool-run/owner-inbox.js";function isTaskRunFinished(e,t){return!isTerminalTaskStatus(e.status)||!t?!1:e.status!==`cancelled`||e.executor?.lifecycle===`terminal`}async function taskRunWorkflow(a){"use workflow";let o=createHook({token:a.taskInboxToken}),l=createChannelReader(`commands`,o),u=a.initialView.metadata.kind===`tool`?openRunOwnerChannels(a.taskInboxToken):void 0,d=u===void 0?[l]:[...u.readers,l],f=!1;try{try{await claimHookOwnership(o),f=!0}catch(e){if(isHookConflictError(e))return;throw e}let e=a.initialView,n,s=[],c=[],l=!1,u=0,p=new Map;for(await appendTaskViewStep({activityObserver:a.activityObserver,view:e});!isTaskRunFinished(e,l);){let t=await raceChannelReads(d);if(t.next.done===!0)return;t.channel===`request`&&p.set(t.next.value.answerToken,{runId:t.next.value.from.runId});let r=t.channel===`report`?runReportToTaskUpdate(t.next.value,e.taskId,u++):t.channel===`request`?runRequestToInputRequestPayload(t.next.value):t.channel===`outcome`?{command:runOutcomeToTaskCommand(t.next.value),kind:`task-command`}:t.next.value,o=r.kind===`subagent-authorization-event`?{...r,kind:`authorization-event`}:r;if(o.kind===`authorization-event`&&(o.event.type===`approval.candidate`||o.event.type===`approval.settled`))continue;let f=o.kind===`task-command`&&o.command.kind===`ready`,m=o.kind===`task-command`&&o.command.kind===`reject-dispatch`;if((f||m)&&(l=!0),o.kind===`subagent-input-request`&&(n=o),o.kind===`authorization-event`&&s.push(o),o.kind===`task-update`){l&&!isTerminalTaskStatus(e.status)?await wakeTaskUpdateParentStep({token:a.parentContinuationToken,update:o,view:e}):c.push(o);continue}let h=e.status===`cancelled`&&o.kind===`runtime-action-result`,g=o.kind===`input-response`,_;if(h)_={kind:`settle-executor`,usage:readTaskUsage(o.results[0]?.outcome?.usageDelta)};else if(g){if(e.status!==`input_required`)continue;_=await resolveAnsweredCommand(e,o,p.get(o.childContinuationToken))}else _=translateTaskInboundPayload(o);if(_===void 0)continue;if(f&&isTerminalTaskStatus(e.status)){for(let t of c)await wakeTaskUpdateParentStep({token:a.parentContinuationToken,update:t,view:e});c=[],await wakeTaskParentStep({token:a.parentContinuationToken,view:e});continue}let v=applyTaskTransition(e,_);if(v.action!==`accepted`)continue;let y=!isTerminalTaskStatus(e.status)&&isTerminalTaskStatus(v.view.status),b=!isReadyTaskStatus(e.status)&&isReadyTaskStatus(v.view.status);e=v.view,await appendTaskViewStep({activityObserver:a.activityObserver,view:e});let x=l&&!y?s:[];for(let t of x)await wakeTaskAuthorizationParentStep({request:t,taskId:e.taskId,token:a.parentContinuationToken});if(l&&c.length>0&&!isTerminalTaskStatus(e.status)){for(let t of c)await wakeTaskUpdateParentStep({token:a.parentContinuationToken,update:t,view:e});c=[]}(y||x.length>0)&&(s=[]),n!==void 0&&l&&e.status===`input_required`?(await wakeTaskInputRequestParentStep({request:n,taskId:e.taskId,token:a.parentContinuationToken}),n=void 0):!m&&x.length===0&&l&&(y||b&&n===void 0)&&await wakeTaskParentStep({token:a.parentContinuationToken,view:e}),e.status!==`input_required`&&(n=void 0)}}finally{f&&(await u?.dispose(),await disposeHook(o))}}async function resolveAnsweredCommand(e,t,n){if(t.taskId!==e.taskId)return;let r=new Set(e.inputRequests.flatMap(e=>{let t=readTaskInputRequestId(e);return t===void 0?[]:[t]})),i=t.inputResponses.map(e=>e.requestId).filter(e=>r.has(e));return i.length===0?void 0:await deliverTaskInputResponsesStep({answer:t,answerHook:n,requestIds:i})===`delivered`?{kind:`answered`,requestIds:i}:void 0}export{taskRunWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDurableSessionState}from"#execution/durable-session-store.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{emitSubagentCalled,prepareRuntimeActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{beginDelegatedTask,settleDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{checkTaskContinuationAvailability,describeTaskDispatch,persistContinuationTaskInParentSession,settleTaskDispatchError}from"#execution/tasks/parent/continuation-dispatch.js";async function dispatchTaskStep(r){"use step";let i=await prepareRuntimeActionDispatch({serializedContext:r.serializedContext,sessionState:r.sessionState,taskControls:!0});if(i===void 0)return{results:[],sessionState:r.sessionState,pendingTasks:[]};let{batch:a,bundle:o,session:s}=i,c=r.parentWritable.getWriter(),l=s,u=[],d=[];try{for(let e of i.plan){if(e.kind===`reject`){u.push(e.result);continue}if(e.kind===`task-control`){let t=await executeTaskControlAction({action:e.action,adapter:i.adapter,bundle:o,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,serializedContext:i.serializedContext,session:l});l=t.session,t.pendingTask!==void 0&&d.push(t.pendingTask),u.push(t.result);continue}if(e.kind===`resume`){let t=await checkTaskContinuationAvailability({action:e.action,agentId:e.agentId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l});if(t!==void 0){u.push(t);continue}}let n=e.kind===`resume`?e.action:e.target.action,f=await beginDelegatedTask({...describeTaskDispatch({action:n,agentId:e.kind===`resume`?e.agentId:void 0,parentSessionId:s.sessionId,parentTurnId:a.event.turnId,session:l}),activityObserver:i.activityObserver===void 0?void 0:deriveChildActivityObserverConfig({activityObserver:i.activityObserver,callId:n.callId,kind:`task`,name:e.kind===`resume`?e.action.name:e.target.action.name,parentSessionId:s.sessionId,parentTurnId:a.event.turnId}),parentSessionId:s.sessionId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l}),p;e.kind===`resume`&&(p=await persistContinuationTaskInParentSession({action:e.action,agentId:e.agentId,delegated:f,session:l}),l=p?.session??l);let m;switch(e.kind){case`resume`:m=await dispatchToTaskAgentAddress({action:e.action,activityObserver:i.activityObserver===void 0?void 0:deriveChildActivityObserverConfig({activityObserver:i.activityObserver,callId:e.action.callId,kind:`task`,name:e.action.name,parentSessionId:s.sessionId,parentTurnId:a.event.turnId}),agentId:e.agentId,auth:i.auth,bundle:createAgentContinuationBundle({action:e.action,bundle:o,dynamicRemoteAgent:e.dynamicRemoteAgent}),currentSession:l,parentToken:f.taskInboxToken});break;case`start`:m=await startSubagent({auth:i.auth,batchEvent:a.event,bundle:o,callbackBaseUrl:r.callbackBaseUrl,capabilities:i.capabilities,channelMetadata:i.channelMetadata,currentSession:l,fanoutSize:i.fanoutSize,initiatorAuth:i.initiatorAuth,localDevRequest:i.localDevRequest,parentContinuationToken:f.taskInboxToken,parentTraceContext:i.parentTraceContext,activityObserver:i.activityObserver,sandboxSessionId:i.sandboxSessionId,serializedContext:i.serializedContext,session:s,taskOwned:!0,target:e.target});break}if(l=m.session,m.kind===`error`){u.push(await settleTaskDispatchError({delegated:f,outcome:m,persisted:p})),p!==void 0&&d.push(f);continue}if(p!==void 0)u.push(p.receipt);else{let e=await settleDelegatedDispatch({callId:m.callId,session:l,subagentName:m.toolName,task:f});l=e.session,u.push(e.receipt)}d.push(f),await emitSubagentCalled({adapter:i.adapter,adapterCtx:i.adapterCtx,batchEvent:a.event,entry:e,outcome:m,sessionId:s.sessionId,writer:c})}}finally{c.releaseLock()}return{results:u,sessionState:l===s?r.sessionState:createDurableSessionState({session:l}),pendingTasks:d}}export{dispatchTaskStep};
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{startWorkflowTool}from"#execution/tool-run/dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{emitSubagentCalled,prepareRuntimeActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{beginDelegatedTask,settleDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{checkTaskContinuationAvailability,describeTaskDispatch,persistContinuationTaskInParentSession,settleTaskDispatchError}from"#execution/tasks/parent/continuation-dispatch.js";async function dispatchTaskStep(r){"use step";let i=await prepareRuntimeActionDispatch({serializedContext:r.serializedContext,sessionState:r.sessionState,taskControls:!0});if(i===void 0)return{results:[],sessionState:r.sessionState,pendingTasks:[]};let{batch:a,bundle:o,session:s}=i,c=r.parentWritable.getWriter(),l=s,u=[],d=[];try{for(let e of i.plan){if(e.kind===`reject`){u.push(e.result);continue}if(e.kind===`workflow-tool`){let t=await startWorkflowTool({action:e.action,batchEvent:a.event,ownerInboxToken:r.parentContinuationToken,prepared:i,session:l});l=t.session,t.result!==void 0&&u.push(t.result);continue}if(e.kind===`task-control`){let t=await executeTaskControlAction({action:e.action,adapter:i.adapter,bundle:o,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,serializedContext:i.serializedContext,session:l});l=t.session,t.pendingTask!==void 0&&d.push(t.pendingTask),u.push(t.result);continue}if(e.kind===`resume`){let t=await checkTaskContinuationAvailability({action:e.action,agentId:e.agentId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l});if(t!==void 0){u.push(t);continue}}let n=e.kind===`resume`?e.action:e.target.action,f=await beginDelegatedTask({...describeTaskDispatch({action:n,agentId:e.kind===`resume`?e.agentId:void 0,parentSessionId:s.sessionId,parentTurnId:a.event.turnId,session:l}),activityObserver:i.activityObserver===void 0?void 0:deriveChildActivityObserverConfig({activityObserver:i.activityObserver,callId:n.callId,kind:`task`,name:e.kind===`resume`?e.action.name:e.target.action.name,parentSessionId:s.sessionId,parentTurnId:a.event.turnId}),parentSessionId:s.sessionId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l}),p;e.kind===`resume`&&(p=await persistContinuationTaskInParentSession({action:e.action,agentId:e.agentId,delegated:f,session:l}),l=p?.session??l);let m;switch(e.kind){case`resume`:m=await dispatchToTaskAgentAddress({action:e.action,activityObserver:i.activityObserver===void 0?void 0:deriveChildActivityObserverConfig({activityObserver:i.activityObserver,callId:e.action.callId,kind:`task`,name:e.action.name,parentSessionId:s.sessionId,parentTurnId:a.event.turnId}),agentId:e.agentId,auth:i.auth,bundle:createAgentContinuationBundle({action:e.action,bundle:o,dynamicRemoteAgent:e.dynamicRemoteAgent}),currentSession:l,parentToken:f.taskInboxToken});break;case`start`:m=await startSubagent({auth:i.auth,batchEvent:a.event,bundle:o,callbackBaseUrl:r.callbackBaseUrl,capabilities:i.capabilities,channelMetadata:i.channelMetadata,currentSession:l,fanoutSize:i.fanoutSize,initiatorAuth:i.initiatorAuth,localDevRequest:i.localDevRequest,parentContinuationToken:f.taskInboxToken,parentTraceContext:i.parentTraceContext,activityObserver:i.activityObserver,sandboxSessionId:i.sandboxSessionId,serializedContext:i.serializedContext,session:s,taskOwned:!0,target:e.target});break}if(l=m.session,m.kind===`error`){u.push(await settleTaskDispatchError({delegated:f,outcome:m,persisted:p})),p!==void 0&&d.push(f);continue}if(p!==void 0)u.push(p.receipt);else{let e=await settleDelegatedDispatch({callId:m.callId,session:l,subagentName:m.toolName,task:f});l=e.session,u.push(e.receipt)}d.push(f),await emitSubagentCalled({adapter:i.adapter,adapterCtx:i.adapterCtx,batchEvent:a.event,entry:e,outcome:m,sessionId:s.sessionId,writer:c})}}finally{c.releaseLock()}return{results:u,sessionState:l===s?r.sessionState:createDurableSessionState({session:l}),pendingTasks:d}}export{dispatchTaskStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders}from"#execution/remote-agent-dispatch.js";import{deserializeContext}from"#context/serialize.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{sendTaskCommand}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus,readSubagentExecutor,readSubagentTaskMetadata}from"#tasks/types.js";import{createTaskControlError,createTaskViewsResult,createUnknownTasksError,findTaskAgentAddress,lookupTaskEntries,readTaskView}from"#execution/tasks/parent/control-shared.js";import{executeTaskUpdate}from"#execution/tasks/child/update.js";const log=createLogger(`execution.tasks.dispatch`);function isTaskControlAction(e){return e.target.kind===`task-cancel`||e.target.kind===`task-update`}async function executeTaskControlAction(e){let{action:t,session:n}=e;if(t.target.kind===`task-update`)return{result:await executeTaskUpdate({action:t,adapter:e.adapter,updateIndex:e.parentStepIndex??0,updateEpoch:e.parentTurnId,serializedContext:e.serializedContext}),session:n};let r=readTaskIds(t.input);if(r===void 0||r.length===0)return{result:createTaskControlError(t,"Provide a non-empty `taskIds` array."),session:n};let i=lookupTaskEntries(n,r);if(i.kind===`unknown`)return{result:createUnknownTasksError(t,i.unknown),session:n};let a=i.entries,o=[];for(let t of a)o.push(await cancelOwnedTask({bundle:e.bundle,entry:t,serializedContext:e.serializedContext,session:n}));return{result:createTaskViewsResult(t,o),session:n}}async function cancelOwnedTask(e){let{entry:t}=e,n=await sendTaskCommand({command:{kind:`cancel`},taskInboxToken:t.taskInboxToken}),r=await readTaskView(t);for(let e=0;e<10&&!isTerminalTaskStatus(r.status);e+=1)await new Promise(e=>setTimeout(e,250)),r=await readTaskView(t);if(!isTerminalTaskStatus(r.status))throw Error(`Task "${t.taskId}" did not commit cancellation before timeout.`);let i=r;return i.status===`cancelled`&&n===`delivered`&&await propagateTaskCancel({bundle:e.bundle,serializedContext:e.serializedContext,session:e.session,view:i}),i}async function propagateTaskCancel(e){let t=readSubagentTaskMetadata(e.view);if(
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders}from"#execution/remote-agent-dispatch.js";import{deserializeContext}from"#context/serialize.js";import{cancelToolRun}from"#execution/tool-run/cancel.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{readWorkflowToolExecutor}from"#execution/tool-run/background.js";import{sendTaskCommand}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus,readSubagentExecutor,readSubagentTaskMetadata}from"#tasks/types.js";import{createTaskControlError,createTaskViewsResult,createUnknownTasksError,findTaskAgentAddress,lookupTaskEntries,readTaskView}from"#execution/tasks/parent/control-shared.js";import{executeTaskUpdate}from"#execution/tasks/child/update.js";const log=createLogger(`execution.tasks.dispatch`);function isTaskControlAction(e){return e.target.kind===`task-cancel`||e.target.kind===`task-update`}async function executeTaskControlAction(e){let{action:t,session:n}=e;if(t.target.kind===`task-update`)return{result:await executeTaskUpdate({action:t,adapter:e.adapter,updateIndex:e.parentStepIndex??0,updateEpoch:e.parentTurnId,serializedContext:e.serializedContext}),session:n};let r=readTaskIds(t.input);if(r===void 0||r.length===0)return{result:createTaskControlError(t,"Provide a non-empty `taskIds` array."),session:n};let i=lookupTaskEntries(n,r);if(i.kind===`unknown`)return{result:createUnknownTasksError(t,i.unknown),session:n};let a=i.entries,o=[];for(let t of a)o.push(await cancelOwnedTask({bundle:e.bundle,entry:t,serializedContext:e.serializedContext,session:n}));return{result:createTaskViewsResult(t,o),session:n}}async function cancelOwnedTask(e){let{entry:t}=e,n=await sendTaskCommand({command:{kind:`cancel`},taskInboxToken:t.taskInboxToken}),r=await readTaskView(t);for(let e=0;e<10&&!isTerminalTaskStatus(r.status);e+=1)await new Promise(e=>setTimeout(e,250)),r=await readTaskView(t);if(!isTerminalTaskStatus(r.status))throw Error(`Task "${t.taskId}" did not commit cancellation before timeout.`);let i=r;return i.status===`cancelled`&&n===`delivered`&&await propagateTaskCancel({bundle:e.bundle,serializedContext:e.serializedContext,entry:t,session:e.session,view:i}),i}async function propagateTaskCancel(e){let t=readWorkflowToolExecutor(e.view.executor?.binding);if(t!==void 0){await cancelToolRun(t,`Task ${e.entry.taskId} was cancelled.`),await sendTaskCommand({command:{kind:`settle-executor`},taskInboxToken:e.entry.taskInboxToken});return}let n=readSubagentTaskMetadata(e.view);if(n===void 0)return;let r=readSubagentExecutor(e.view.executor)??findTaskAgentAddress(e.session,n.agentId);r!==void 0&&(e.view.executor?.childSessionId!==void 0&&e.view.executor.childSessionId!==r.address.sessionId||await propagateSubagentExecutorCancel({bundle:e.bundle,childTurnId:e.view.executor?.childTurnId,executor:r,serializedContext:e.serializedContext,taskId:e.view.taskId}))}async function propagateSubagentExecutorCancel(e){let{address:s,identity:c}=e.executor,l=s.sessionId,u=e.childTurnId;try{if(s.kind===`agent/remote`){if(e.bundle===void 0)throw Error(`No compiled bundle is available to resolve the remote agent.`);let t=s.credentialResolver,n;if(t===void 0&&e.serializedContext!==void 0){let t=getDynamicSubagentSelection(await deserializeContext(e.serializedContext),c.nodeId);n=t?.kind===`remote`?t.remoteAgent:void 0}let d=t===void 0?resolveRemoteAgentForAction({dynamicRemoteAgent:n,nodeId:c.nodeId,remoteAgentName:c.name,registry:e.bundle.subagentRegistry.subagentsByNodeId}):{name:c.name,url:s.url},f=t===void 0&&d.url!==s.url,p=f?{}:t?.resolverId===void 0?t===void 0?void 0:{}:await resolveRemoteAgentStreamHeaders({bundle:e.bundle,name:c.name,resolverId:t.resolverId,url:s.url}),m=f?{name:c.name,url:s.url}:{...d,url:s.url},h={remote:m,sessionId:l,taskId:e.taskId};if(p!==void 0&&(h.headers=p),u!==void 0&&(h.turnId=u),(await cancelRemoteAgentTurn(h)).status===`no_active_turn`){let t={remote:m,sessionId:l,taskId:e.taskId};p!==void 0&&(t.headers=p),await cancelRemoteAgentTurn(t)}return}let t={sessionId:l,taskId:e.taskId};u!==void 0&&(t.turnId=u),(await requestWorkflowTurnCancellation(t)).status===`no_active_turn`&&await requestWorkflowTurnCancellation({sessionId:l,taskId:e.taskId})}catch(n){logError(log,`task cancel propagation failed; the child may run to completion`,n,{childSessionId:l,taskId:e.taskId})}}function readTaskIds(e){let t=e.taskIds;if(Array.isArray(t))return t.filter(e=>typeof e==`string`&&e.trim()!==``)}export{cancelOwnedTask,executeTaskControlAction,isTaskControlAction,propagateSubagentExecutorCancel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{isInputRequest}from"#shared/input.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{removeTaskAgentAddressFromState}from"#harness/handles/transitions.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{readDurableSession}from"#execution/durable-session-store.js";import{createTaskInputRequestId,toProxyInputRequestEntries,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{cacheTerminalTaskView,findSessionTaskEntry}from"#tasks/session-index.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";import{isTerminalTaskStatus,readSubagentTaskMetadata}from"#tasks/types.js";async function recordTaskInputRequestStep(
|
|
1
|
+
import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{isInputRequest}from"#shared/input.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{removeTaskAgentAddressFromState}from"#harness/handles/transitions.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{readDurableSession}from"#execution/durable-session-store.js";import{createTaskInputRequestId,toProxyInputRequestEntries,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{readWorkflowToolExecutor}from"#execution/tool-run/background.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{cacheTerminalTaskView,findSessionTaskEntry}from"#tasks/session-index.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";import{isTerminalTaskStatus,readSubagentTaskMetadata}from"#tasks/types.js";async function recordTaskInputRequestStep(n){"use step";let r=await readDurableSession(n.sessionState),a=findSessionTaskEntry(r.state,n.taskId);if(a===void 0)return{accepted:!1,sessionState:n.sessionState};let c=await readLatestTaskView({taskRunId:a.taskRunId}),l=n.hookPayload.event.requests.map(e=>e.requestId),u=c?.inputRequests?.map(e=>typeof e==`object`&&e&&!Array.isArray(e)?Reflect.get(e,`requestId`):void 0)??[];if(c?.status!==`input_required`||!n.hookPayload.event.requests.every(isInputRequest)||new Set(l).size!==l.length||l.length!==u.length||l.some((e,t)=>e!==u[t]))return{accepted:!1,sessionState:n.sessionState};let d=readWorkflowToolExecutor(c.executor?.binding);if(d!==void 0&&d.runId!==n.hookPayload.childSessionId)return{accepted:!1,sessionState:n.sessionState};let f=d===void 0?findAddressedTaskHandle(r.state,a):void 0;if(d===void 0){let e=readSubagentTaskMetadata(a),t=readSubagentTaskMetadata(c);if(f===void 0||f.address.sessionId!==n.hookPayload.childSessionId||t?.mode!==(f.address.kind===`agent/remote`?`remote`:`local`)||t.agentId!==e?.agentId||c.executor?.childSessionId!==n.hookPayload.childSessionId)return{accepted:!1,sessionState:n.sessionState}}let p=namespaceTaskInputRequests(n.hookPayload,n.taskId),m=toProxyInputRequestEntries(p,n.taskId).map(([e,t],r)=>{let i=n.hookPayload.event.requests[r].requestId;return[e,{...t,childRequestId:i}]});if(f?.address.kind===`agent/remote`){let t=createRemoteTaskInputCallbackUrl(f.address.url,createEveTaskInputRoutePath(createTaskInputCapabilityToken(n.hookPayload.childContinuationToken)));m=m.map(([e,n])=>[e,{...n,childResponseUrl:t}])}let h=upsertProxyInputRequestState({entries:m,forChildContinuationToken:n.hookPayload.childContinuationToken,state:r.state});return{accepted:!0,hookPayload:p,sessionState:{...n.sessionState,hasProxyInputRequests:!0,snapshot:{session:{...r,state:h},version:n.sessionState.version}}}}function findAddressedTaskHandle(e,t){let r=readSubagentTaskMetadata(t)?.agentId;if(r!==void 0)return(getAgentHandleStore(e)?.handles??[]).find(e=>e.phase===`addressed`&&e.identity.id===r)}function namespaceTaskInputRequests(e,t){return{...e,event:{...e.event,requests:e.event.requests.map(e=>({...e,requestId:createTaskInputRequestId(t,e.requestId)}))}}}async function acceptTaskAuthorizationEventStep(e){"use step";let t=await readDurableSession(e.sessionState),r=findSessionTaskEntry(t.state,e.taskId);if(r===void 0)return!1;let i=readSubagentTaskMetadata(r);if(i===void 0)return!1;let a=(getAgentHandleStore(t.state)?.handles??[]).find(e=>e.phase===`addressed`&&e.identity.id===i.agentId);if(a?.phase!==`addressed`||a.address.sessionId!==e.hookPayload.childSessionId)return!1;let o=await readLatestTaskView({taskRunId:r.taskRunId}),s=o===void 0?void 0:readSubagentTaskMetadata(o);return o!==void 0&&!isTerminalTaskStatus(o.status)&&o.executor?.childSessionId===e.hookPayload.childSessionId&&s?.agentId===i.agentId}async function recordTerminalTaskViewsStep(e){"use step";let t=await readDurableSession(e.sessionState),n=t.state;for(let t of e.views)if(n=cacheTerminalTaskView(n,t),t.executor?.lifecycle===`terminal`){let e=readSubagentTaskMetadata(t);e!==void 0&&(n=removeTaskAgentAddressFromState(n,e.agentId))}return n===t.state?e.sessionState:{...e.sessionState,snapshot:{session:{...t,state:n},version:e.sessionState.version}}}export{acceptTaskAuthorizationEventStep,recordTaskInputRequestStep,recordTerminalTaskViewsStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveCallbackRoutePath}from"#protocol/routes.js";import{loadContext}from"#context/container.js";import{parseJsonValue}from"#shared/json.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{recordTaskAgentAddress}from"#harness/handles/transitions.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{runStep}from"#context/run-step.js";import{propagateSubagentExecutorCancel}from"#execution/tasks/parent/dispatch.js";import{activeTurnId}from"#harness/active-turn-id.js";import{CallbackBaseUrlKey,isAuthorizationSignal}from"#harness/authorization.js";import{sendTaskCommand,sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{recordSessionTask}from"#tasks/session-index.js";import{readSubagentExecutor}from"#tasks/types.js";import{beginBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{
|
|
1
|
+
import{createEveCallbackRoutePath}from"#protocol/routes.js";import{loadContext}from"#context/container.js";import{parseJsonValue}from"#shared/json.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{recordTaskAgentAddress}from"#harness/handles/transitions.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{cancelToolRun}from"#execution/tool-run/cancel.js";import{runStep}from"#context/run-step.js";import{propagateSubagentExecutorCancel}from"#execution/tasks/parent/dispatch.js";import{activeTurnId}from"#harness/active-turn-id.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{readWorkflowToolExecutor}from"#execution/tool-run/background.js";import{CallbackBaseUrlKey,isAuthorizationSignal}from"#harness/authorization.js";import{sendTaskCommand,sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{recordSessionTask}from"#tasks/session-index.js";import{readSubagentExecutor}from"#tasks/types.js";import{beginBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskDelegated,isTaskDelegated}from"#tools/task.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t,e.get(BundleKey))}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{bundle;executions=new Map;records=[];retained=!1;initialSession;constructor(e,t){this.bundle=t,this.initialSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await compensateBackgroundToolExecution(t,Error(`Background tool execution did not delegate or complete its task.`),this.bundle),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await compensateBackgroundToolExecution(n,e,this.bundle),t.length!==0){if(isTurnCancellation(e)){this.retained=!0;return}await compensateBackgroundToolExecution(t,e,this.bundle)}}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records){if(!e.settled||e.task===void 0)continue;let n=readSubagentExecutor(e.task.executor);n!==void 0&&(t=recordTaskAgentAddress(t,n)),t=recordSessionTask(t,e.task)}return t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(r){let a={settled:!1};this.records.push(a);let o=getHarnessEmissionState(this.initialSession.state),s=await beginBackgroundTask({callId:r.options.toolCallId,metadata:{kind:`tool`,name:r.definition.name},parentSessionId:this.initialSession.sessionId,parentStepIndex:o.stepIndex,parentTurnId:activeTurnId(o),session:this.initialSession});a.task=s;let c=loadContext().get(CallbackBaseUrlKey),l={taskId:s.taskId,token:s.taskInboxToken,...c===void 0?{}:{url:createWorkflowCallbackUrl(c,createEveCallbackRoutePath(s.taskInboxToken))}},u={batch:r.batch.calls,binding:l,delegated:({executor:e,receipt:t})=>createTaskDelegated({binding:l,executor:e,receipt:t}),send:createTaskSender(s,r.options.toolCallId),session:this.initialSession,task:s},d=r.definition.execute(r.toolInput,r.options,u);if(isAsyncIterable(d))throw Error(`Background tools cannot return AsyncIterable output.`);let f=await d;return isAuthorizationSignal(f)?f:isTaskDelegated(f)?(await deliverTaskCommand(s,{executor:f.executor,kind:`bind`}),a.task={...s,executor:f.executor},a.settled=!0,f.receipt):(await deliverTaskCommand(s,{data:parseJsonValue(f),kind:`complete`}),a.settled=!0,f)}};function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function createTaskSender(e,t){let n=0;return async r=>{if(r.kind!==`update`){await deliverTaskCommand(e,r);return}if(await sendTaskInboundPayload({payload:{callId:t,kind:`task-update`,message:r.message,updateEpoch:e.taskId,updateIndex:n++},taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${r.kind}".`)}}async function compensateBackgroundToolExecution(e,t,n){let r=[];for(let i of e.toReversed()){if(i.task===void 0)continue;try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:i.task})}catch(e){r.push(e)}let e=readSubagentExecutor(i.task.executor);e!==void 0&&await propagateSubagentExecutorCancel({bundle:n,executor:e,taskId:i.task.taskId});let a=readWorkflowToolExecutor(i.task.executor);a!==void 0&&await cancelToolRun(a,`The step that started the tool failed.`)}if(r.length>0)throw AggregateError([t,...r],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createSessionCompletedEvent}from"#protocol/message.js";import{emitTerminalSessionEvent}from"#execution/terminal-session-event.js";async function emitTerminalSessionCompletionStep(e){"use step";await emitTerminalSessionEvent({...e,event:createSessionCompletedEvent()})}export{emitTerminalSessionCompletionStep};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
2
|
+
type TerminalSessionEvent = Extract<UnstampedMessageStreamEvent, {
|
|
3
|
+
type: "session.completed" | "session.failed";
|
|
4
|
+
}>;
|
|
5
|
+
/** Delivers one out-of-turn terminal event through the native instrumentation lifecycle. */
|
|
6
|
+
export declare function emitTerminalSessionEvent(input: {
|
|
7
|
+
readonly errorId?: string;
|
|
8
|
+
readonly event: TerminalSessionEvent;
|
|
9
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
10
|
+
readonly serializedContext: Record<string, unknown>;
|
|
11
|
+
readonly turnId?: string;
|
|
12
|
+
}): Promise<void>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{ParentSessionKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionEvent(e){let i=e.serializedContext[`eve.sessionId`]??``,a;try{a=await deserializeContext(e.serializedContext)}catch(t){log.error(`failed to restore context for terminal ${e.event.type} event`,{error:t,errorId:e.errorId,sessionId:i})}let handleEvent=async n=>{if(a!==void 0){let r=a.get(ChannelKey);if(r!==void 0)try{await callAdapterEventHandler(r,n,buildAdapterContext(r,a))}catch(t){log.error(`adapter failed to handle terminal ${n.type} event`,{error:t,errorId:e.errorId,sessionId:i})}}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(stampMessageStreamEvent(n)))}finally{t.releaseLock()}}catch(t){log.error(`failed to write terminal ${n.type} event to durable stream`,{error:t,errorId:e.errorId,sessionId:i})}},o;if(a!==void 0)try{o=bindSessionInstrumentation({agentName:a.require(BundleKey).turnAgent.id,ctx:a,rootSessionId:a.get(ParentSessionKey)?.rootSessionId??i,sessionId:i})}catch(t){log.error(`failed to bind instrumentation for terminal ${e.event.type} event`,{error:t,errorId:e.errorId,sessionId:i})}let s=o?.createHandleEvent({handleEvent,turnId:e.turnId})??handleEvent;try{a===void 0?await s(e.event):await contextStorage.run(a,()=>s(e.event))}catch(t){log.error(`instrumentation failed to handle terminal ${e.event.type} event`,{error:t,errorId:e.errorId,sessionId:i})}finally{try{await o?.flush()}catch(t){log.error(`failed to flush instrumentation after terminal ${e.event.type} event`,{error:t,errorId:e.errorId,sessionId:i})}}}export{emitTerminalSessionEvent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{createSessionFailedEvent}from"#protocol/message.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{emitTerminalSessionEvent}from"#execution/terminal-session-event.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let t=formatError(e.error),n=summarizeKnownError(e.error),r=t;if(n!==null){let e={...t,message:n.message,name:n.name,semanticErrorId:n.id};r=n.hint===void 0?e:{...e,hint:n.hint}}let i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i}),await emitTerminalSessionEvent({errorId:typeof r.errorId==`string`?r.errorId:void 0,event:createSessionFailedEvent({code:i,details:r,message:a,sessionId:o}),parentWritable:e.parentWritable,serializedContext:e.serializedContext,turnId:e.turnId})}export{emitTerminalSessionFailureStep};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { InputResponse } from "#shared/input.js";
|
|
2
|
+
/** Resumed with the bare response, not a session-inbox delivery, so the body can race the hook. */
|
|
3
|
+
export declare function resumeToolRunAnswers(answerToken: string, responses: readonly InputResponse[] | undefined): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resumeHook}from"#internal/workflow/runtime.js";async function resumeToolRunAnswers(e,t){for(let n of t??[])await resumeHook(e,{optionId:n.optionId,text:n.text})}export{resumeToolRunAnswers};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type ToolRunAddress } from "#execution/tool-run/types.js";
|
|
2
|
+
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
|
|
3
|
+
import { type JsonObject } from "#shared/json.js";
|
|
4
|
+
import type { TaskExecutorBinding } from "#tools/task.js";
|
|
5
|
+
/** Harness `execute` for a background workflow tool: starts the run as the task's executor. */
|
|
6
|
+
export declare function createWorkflowToolBackgroundExecute(input: {
|
|
7
|
+
readonly toolName: string;
|
|
8
|
+
readonly workflowId: string;
|
|
9
|
+
}): NonNullable<HarnessToolDefinition["execute"]>;
|
|
10
|
+
export declare function createWorkflowToolExecutorBinding(data: ToolRunAddress): TaskExecutorBinding;
|
|
11
|
+
/** Reads the tool run recorded on a task's executor binding, if that is what runs it. */
|
|
12
|
+
export declare function readWorkflowToolExecutor(binding: TaskExecutorBinding | undefined): ToolRunAddress | undefined;
|
|
13
|
+
/** The input crosses the run's serialization boundary; a schema may emit a `Date`, which cannot. */
|
|
14
|
+
export declare function parseWorkflowToolInput(toolInput: unknown, toolName: string): JsonObject;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseJsonObject}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveRunOwner}from"#execution/tool-run/messages.js";import{startToolRun}from"#execution/tool-run/start.js";import{WORKFLOW_TOOL_EXECUTOR_KIND}from"#execution/tool-run/types.js";function createWorkflowToolBackgroundExecute(e){return async(r,i,a)=>{if(a===void 0)throw Error(`Background tool "${e.toolName}" requires a task runtime.`);let o=await startToolRun({callId:i.toolCallId,input:parseWorkflowToolInput(r,e.toolName),owner:deriveRunOwner(a.task.taskInboxToken),session:buildCallbackContext().session,stepIndex:getHarnessEmissionState(a.session.state).stepIndex,toolName:e.toolName,workflowId:e.workflowId});return a.delegated({executor:createWorkflowToolExecutorBinding(o),receipt:{}})}}function createWorkflowToolExecutorBinding(e){return{data:{hookToken:e.hookToken,runId:e.runId},kind:WORKFLOW_TOOL_EXECUTOR_KIND}}function readWorkflowToolExecutor(e){if(e?.kind!==WORKFLOW_TOOL_EXECUTOR_KIND)return;let{hookToken:t,runId:n}=e.data;return typeof t==`string`&&typeof n==`string`?{hookToken:t,runId:n}:void 0}function parseWorkflowToolInput(t,n){try{return parseJsonObject(t)}catch(e){throw TypeError(`Tool "${n}" is a workflow, so its parsed input must be a JSON object.`,{cause:e})}}export{createWorkflowToolBackgroundExecute,createWorkflowToolExecutorBinding,parseWorkflowToolInput,readWorkflowToolExecutor};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ToolRunAddress } from "#execution/tool-run/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Asks the run to cancel itself; cancels it outright only if the message cannot
|
|
4
|
+
* be delivered. Failures are logged, not thrown: the caller has already
|
|
5
|
+
* committed the cancellation the run was serving.
|
|
6
|
+
*/
|
|
7
|
+
export declare function cancelToolRun(run: ToolRunAddress, reason: string): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{cancelRun,getWorld,resumeHook}from"#internal/workflow/runtime.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";const log=createLogger(`execution.tool-run`);async function cancelToolRun(e,n){let r={kind:`cancel`,reason:n};try{await resumeHook(e.hookToken,r);return}catch(t){if(isTaskWorkflowTargetGone(t))return;logError(log,`failed to signal a workflow tool run to cancel; cancelling it outright`,t,{runId:e.runId})}try{await cancelRun(await getWorld(),e.runId,{cancelReason:n})}catch(t){if(isTaskWorkflowTargetGone(t))return;logError(log,`failed to cancel workflow tool run; it may run to completion`,t,{runId:e.runId})}}export{cancelToolRun};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { PreparedRuntimeActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
|
|
2
|
+
import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
|
|
3
|
+
import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
|
|
4
|
+
import type { PendingDispatchAction, PendingWorkflowToolAction } from "#shared/dispatch-action.js";
|
|
5
|
+
export declare function isWorkflowToolAction(action: PendingDispatchAction): action is PendingWorkflowToolAction;
|
|
6
|
+
/**
|
|
7
|
+
* Starts the run and records it on the session so the turn can bind its
|
|
8
|
+
* result, route its requests, and cancel it. A start failure settles the call
|
|
9
|
+
* with an error and records nothing, so nothing is left to cancel.
|
|
10
|
+
*/
|
|
11
|
+
export declare function startWorkflowTool(input: {
|
|
12
|
+
readonly action: PendingWorkflowToolAction;
|
|
13
|
+
readonly batchEvent: {
|
|
14
|
+
readonly sequence: number;
|
|
15
|
+
readonly stepIndex: number;
|
|
16
|
+
readonly turnId: string;
|
|
17
|
+
};
|
|
18
|
+
readonly ownerInboxToken: string | undefined;
|
|
19
|
+
readonly prepared: Pick<PreparedRuntimeActionDispatch, "auth" | "initiatorAuth" | "parentSession">;
|
|
20
|
+
readonly session: RuntimeSession;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
readonly result?: RuntimeToolResultActionResult;
|
|
23
|
+
readonly session: RuntimeSession;
|
|
24
|
+
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{toError}from"#shared/errors.js";import{recordToolRun}from"#harness/tool-runs.js";import{deriveRunOwner}from"#execution/tool-run/messages.js";import{startToolRun}from"#execution/tool-run/start.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";const log=createLogger(`execution.tool-run`);function isWorkflowToolAction(e){return e.target.kind===`workflow-tool-call`}async function startWorkflowTool(e){let{action:n,batchEvent:r,prepared:i,session:a}=e;if(e.ownerInboxToken===void 0)throw Error(`Workflow tool "${n.toolName}" was dispatched without the turn inbox its run reports to.`);try{let t=await startToolRun({callId:n.callId,input:n.input,owner:deriveRunOwner(e.ownerInboxToken),session:{auth:{current:i.auth,initiator:i.initiatorAuth},id:a.sessionId,parent:i.parentSession,turn:{id:r.turnId,sequence:r.sequence}},stepIndex:r.stepIndex,toolName:n.toolName,workflowId:n.target.workflowId});return{session:recordToolRun(a,{callId:n.callId,hookToken:t.hookToken,runId:t.runId,toolName:n.toolName})}}catch(e){return logError(log,`workflow tool run failed to start`,e,{callId:n.callId,toolName:n.toolName}),{result:createRuntimeToolResultFromValue({callId:n.callId,isError:!0,output:toError(e),toolName:n.toolName}),session:a}}}export{isWorkflowToolAction,startWorkflowTool};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { RunRef } from "#execution/tool-run/messages.js";
|
|
2
|
+
import type { JsonValue } from "#shared/json.js";
|
|
3
|
+
export declare function emitRunReportStep(input: {
|
|
4
|
+
readonly from: RunRef;
|
|
5
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
6
|
+
readonly update: JsonValue;
|
|
7
|
+
}): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createActionPartialEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";async function emitRunReportStep(e){"use step";let t=createActionPartialEvent({result:createRuntimeToolResultFromValue({callId:e.from.callId,output:e.update,toolName:e.from.toolName}),sequence:e.from.sequence,stepIndex:e.from.stepIndex,turnId:e.from.turnId}),n=e.parentWritable.getWriter();try{await n.write(encodeMessageStreamEvent(stampMessageStreamEvent(t)))}finally{n.releaseLock()}}export{emitRunReportStep};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type Hook } from "#compiled/@workflow/core/index.js";
|
|
2
|
+
import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
|
|
3
|
+
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
4
|
+
export interface ToolRunOwner {
|
|
5
|
+
readonly outcome: string;
|
|
6
|
+
readonly report: string;
|
|
7
|
+
readonly request: string;
|
|
8
|
+
}
|
|
9
|
+
/** Identifies the sending run to an owner that shares its channels across many runs. */
|
|
10
|
+
export interface RunRef {
|
|
11
|
+
readonly callId: string;
|
|
12
|
+
/** The tool's parsed input, shown as the request's action when the run asks. */
|
|
13
|
+
readonly input: JsonObject;
|
|
14
|
+
readonly runId: string;
|
|
15
|
+
/** Stream coordinates of the model call that made the tool call. */
|
|
16
|
+
readonly sequence: number;
|
|
17
|
+
readonly stepIndex: number;
|
|
18
|
+
readonly toolName: string;
|
|
19
|
+
readonly turnId: string;
|
|
20
|
+
}
|
|
21
|
+
export type RunOutcome = {
|
|
22
|
+
readonly status: "completed";
|
|
23
|
+
readonly output: JsonValue;
|
|
24
|
+
} | {
|
|
25
|
+
readonly status: "failed";
|
|
26
|
+
readonly error: unknown;
|
|
27
|
+
} | {
|
|
28
|
+
readonly status: "cancelled";
|
|
29
|
+
readonly reason?: string;
|
|
30
|
+
};
|
|
31
|
+
/** Progress sent up from a run; the owner streams it as a turn partial or a task update. */
|
|
32
|
+
export interface RunReport {
|
|
33
|
+
readonly from: RunRef;
|
|
34
|
+
readonly update: JsonValue;
|
|
35
|
+
}
|
|
36
|
+
/** A question sent up from a run; the owner puts it to the human and resumes `answerToken` with the reply. */
|
|
37
|
+
export interface RunRequestMessage {
|
|
38
|
+
readonly answerToken: string;
|
|
39
|
+
readonly from: RunRef;
|
|
40
|
+
readonly request: ToolInputRequest;
|
|
41
|
+
}
|
|
42
|
+
/** The end of a run, sent up once; the owner settles the tool call or the task with it. */
|
|
43
|
+
export interface RunOutcomeMessage {
|
|
44
|
+
readonly from: RunRef;
|
|
45
|
+
readonly result: RunOutcome;
|
|
46
|
+
}
|
|
47
|
+
export declare const reportHook: import("#compiled/@workflow/core/index.js").TypedHook<RunReport, RunReport>;
|
|
48
|
+
export declare const requestHook: import("#compiled/@workflow/core/index.js").TypedHook<RunRequestMessage, RunRequestMessage>;
|
|
49
|
+
export declare const outcomeHook: import("#compiled/@workflow/core/index.js").TypedHook<RunOutcomeMessage, RunOutcomeMessage>;
|
|
50
|
+
/** Derived from the owner's inbox token so owner and run agree without exchanging tokens. */
|
|
51
|
+
export declare function deriveRunOwner(inboxToken: string): ToolRunOwner;
|
|
52
|
+
export type RunControlMessage = {
|
|
53
|
+
readonly kind: "cancel";
|
|
54
|
+
readonly reason: string;
|
|
55
|
+
};
|
|
56
|
+
export declare function isRunControlMessage(value: unknown): value is RunControlMessage;
|
|
57
|
+
interface RunContext {
|
|
58
|
+
answerSeq: number;
|
|
59
|
+
readonly from: RunRef;
|
|
60
|
+
readonly owner: ToolRunOwner;
|
|
61
|
+
}
|
|
62
|
+
export declare function attachRunContext(ctx: ToolContext, context: Omit<RunContext, "answerSeq">): void;
|
|
63
|
+
/**
|
|
64
|
+
* Asks the human on the session's channel and returns the hook the answer
|
|
65
|
+
* resumes, as `createHook` would: await it for the answer, or race it against
|
|
66
|
+
* a `sleep` for a deadline. Synchronous because a `Hook` is thenable: an async
|
|
67
|
+
* `ask` would resolve to the answer, never the hook.
|
|
68
|
+
*/
|
|
69
|
+
export declare function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse>;
|
|
70
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHook,defineHook}from"#compiled/@workflow/core/index.js";import{toolRunAnswerToken}from"#harness/tool-runs.js";import{resumeHookStep}from"#execution/tool-run/resume-hook-step.js";const reportHook=defineHook(),requestHook=defineHook(),outcomeHook=defineHook();function deriveRunOwner(e){return{outcome:`${e}:outcome`,report:`${e}:report`,request:`${e}:request`}}function isRunControlMessage(e){if(typeof e!=`object`||!e)return!1;let{kind:t,reason:n}=e;return t===`cancel`&&typeof n==`string`}const RUN_CONTEXT=Symbol.for(`eve.tool-run.context`);function attachRunContext(e,t){Object.defineProperty(e,RUN_CONTEXT,{enumerable:!1,value:{...t,answerSeq:0}})}function readRunContext(e){let t=e[RUN_CONTEXT];if(t===void 0)throw Error(`ask() must be called with the context of a workflow tool body ("use workflow").`);return t}function ask(t,r){let i=readRunContext(t),a=createHook({token:toolRunAnswerToken(i.from.runId,i.answerSeq++)}),o={answerToken:a.token,from:i.from,request:r};return resumeHookStep(i.owner.request,o),a}export{ask,attachRunContext,deriveRunOwner,isRunControlMessage,outcomeHook,reportHook,requestHook};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Races reads across several hooks. A read that lands while no race is waiting
|
|
3
|
+
* is kept until one claims it: the owner awaits steps between races, and a
|
|
4
|
+
* resume arriving then must not be dropped or re-issued. Claims follow array
|
|
5
|
+
* order because separate hooks carry no order between them.
|
|
6
|
+
*/
|
|
7
|
+
export interface ChannelReader<C extends string, T> {
|
|
8
|
+
readonly channel: C;
|
|
9
|
+
readonly iterator: AsyncIterator<T>;
|
|
10
|
+
/** Reads that have landed and not yet been claimed, oldest first. */
|
|
11
|
+
readonly landed: IteratorResult<T>[];
|
|
12
|
+
failure?: {
|
|
13
|
+
readonly error: unknown;
|
|
14
|
+
};
|
|
15
|
+
pending?: Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export declare function createChannelReader<C extends string, T>(channel: C, iterable: AsyncIterable<T>): ChannelReader<C, T>;
|
|
18
|
+
export type ChannelRead<R extends readonly ChannelReader<string, unknown>[]> = {
|
|
19
|
+
[I in keyof R]: R[I] extends ChannelReader<infer C, infer T> ? {
|
|
20
|
+
readonly channel: C;
|
|
21
|
+
readonly next: IteratorResult<T>;
|
|
22
|
+
} : never;
|
|
23
|
+
}[number];
|
|
24
|
+
/**
|
|
25
|
+
* Channel reads wake the loop with `undefined` after buffering their result;
|
|
26
|
+
* a cancel wins the race outright.
|
|
27
|
+
*/
|
|
28
|
+
export declare function raceChannelReads<const R extends readonly ChannelReader<string, unknown>[]>(readers: R): Promise<ChannelRead<R>>;
|
|
29
|
+
export declare function raceChannelReads<const R extends readonly ChannelReader<string, unknown>[]>(readers: R, cancelled: Promise<"cancel"> | undefined): Promise<ChannelRead<R> | "cancel">;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function createChannelReader(e,t){return{channel:e,iterator:t[Symbol.asyncIterator](),landed:[]}}async function raceChannelReads(e,t){for(;;){for(let t of e){if(t.failure!==void 0)throw t.failure.error;let e=t.landed.shift();if(e!==void 0)return{channel:t.channel,next:e}}let n=[];for(let t of e)t.pending??=t.iterator.next().then(e=>{t.landed.push(e),t.pending=void 0},e=>{t.failure={error:e},t.pending=void 0}),n.push(t.pending);if(t!==void 0&&n.push(t),await Promise.race(n)===`cancel`)return`cancel`}}export{createChannelReader,raceChannelReads};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
|
|
2
|
+
import type { RunOutcomeMessage, RunReport, RunRequestMessage } from "#execution/tool-run/messages.js";
|
|
3
|
+
import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
|
|
4
|
+
import type { TaskCommand, TaskInboundUpdate } from "#tasks/types.js";
|
|
5
|
+
/** A cancelled run settles the call as an error so the owner never waits on it. */
|
|
6
|
+
export declare function runOutcomeToToolResult(message: RunOutcomeMessage): RuntimeToolResultActionResult;
|
|
7
|
+
/** The answer hook token is both the request id and the route, so one resume reaches the body. */
|
|
8
|
+
export declare function runRequestToInputRequestPayload(message: RunRequestMessage): SubagentInputRequestHookPayload;
|
|
9
|
+
export declare function runReportToTaskUpdate(message: RunReport, taskId: string, updateIndex: number): TaskInboundUpdate;
|
|
10
|
+
/** A cancelled run only settles the executor: the task itself was already cancelled. */
|
|
11
|
+
export declare function runOutcomeToTaskCommand(message: RunOutcomeMessage): TaskCommand;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function runOutcomeToToolResult(e){let{from:t,result:n}=e;if(n.status===`completed`)return{callId:t.callId,kind:`tool-result`,output:n.output,toolName:t.toolName};let r=n.status===`failed`?errorMessage(n.error):n.reason??`The tool run was cancelled.`;return{callId:t.callId,isError:!0,kind:`tool-result`,output:r,toolName:t.toolName}}function errorMessage(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return String(e)}function runRequestToInputRequestPayload(e){let{answerToken:t,from:n,request:r}=e;return{callId:n.callId,childContinuationToken:t,childSessionId:n.runId,event:{requests:[toInputRequest(r,n,t)],sequence:n.sequence,stepIndex:n.stepIndex,turnId:n.turnId},kind:`subagent-input-request`,subagentName:n.toolName}}function toInputRequest(e,t,n){if(typeof e.prompt!=`string`||e.prompt.length===0)throw TypeError("A tool run request needs a non-empty `prompt`.");let r={action:{callId:t.callId,input:t.input,kind:`tool-call`,toolName:t.toolName},kind:`question`,prompt:e.prompt,requestId:n};return e.allowFreeform!==void 0&&(r.allowFreeform=e.allowFreeform),e.display!==void 0&&(r.display=e.display),e.options!==void 0&&(r.options=[...e.options]),r}function runReportToTaskUpdate(e,t,n){return{callId:e.from.callId,kind:`task-update`,message:typeof e.update==`string`?e.update:JSON.stringify(e.update),updateEpoch:t,updateIndex:n}}function runOutcomeToTaskCommand(e){let{result:t}=e;return t.status===`completed`?{data:t.output,kind:`complete`,lifecycle:`terminal`}:t.status===`failed`?{data:errorMessage(t.error),kind:`fail`,lifecycle:`terminal`}:{kind:`settle-executor`}}export{runOutcomeToTaskCommand,runOutcomeToToolResult,runReportToTaskUpdate,runRequestToInputRequestPayload};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type RunOutcomeMessage, type RunReport, type RunRequestMessage } from "#execution/tool-run/messages.js";
|
|
2
|
+
import { type ChannelReader } from "#execution/tool-run/owner-channels.js";
|
|
3
|
+
/** In read priority: what a run said before its outcome lands first. */
|
|
4
|
+
export type RunOwnerReaders = readonly [
|
|
5
|
+
ChannelReader<"report", RunReport>,
|
|
6
|
+
ChannelReader<"request", RunRequestMessage>,
|
|
7
|
+
ChannelReader<"outcome", RunOutcomeMessage>
|
|
8
|
+
];
|
|
9
|
+
export interface RunOwnerChannels {
|
|
10
|
+
readonly readers: RunOwnerReaders;
|
|
11
|
+
dispose(): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export declare function openRunOwnerChannels(inboxToken: string): RunOwnerChannels;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{disposeHook}from"#execution/hook-ownership.js";import{createChannelReader}from"#execution/tool-run/owner-channels.js";import{deriveRunOwner,outcomeHook,reportHook,requestHook}from"#execution/tool-run/messages.js";function openRunOwnerChannels(e){let t=deriveRunOwner(e),n=reportHook.create({token:t.report}),r=requestHook.create({token:t.request}),i=outcomeHook.create({token:t.outcome});return{readers:[createChannelReader(`report`,n),createChannelReader(`request`,r),createChannelReader(`outcome`,i)],async dispose(){await Promise.all([disposeHook(n),disposeHook(r),disposeHook(i)])}}}export{openRunOwnerChannels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resumeHook}from"#internal/workflow/runtime.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";async function resumeHookStep(t,n,r){"use step";try{await resumeHook(t,n)}catch(e){if(r?.ifPresent===!0&&isTaskWorkflowTargetGone(e))return;throw e}}export{resumeHookStep};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Hook } from "#compiled/@workflow/core/index.js";
|
|
2
|
+
import { type RunControlMessage } from "#execution/tool-run/messages.js";
|
|
3
|
+
/**
|
|
4
|
+
* The run's control inbox. An unawaited hook read is not scheduled under
|
|
5
|
+
* replay, so `cancelled` must be raced for a cancel to be observed at all.
|
|
6
|
+
*/
|
|
7
|
+
export interface RunControlInbox {
|
|
8
|
+
readonly hook: Hook<RunControlMessage>;
|
|
9
|
+
readonly signal: AbortSignal;
|
|
10
|
+
/** Rejects with {@link RunCancelledError} when a cancel message arrives; never resolves. */
|
|
11
|
+
readonly cancelled: Promise<never>;
|
|
12
|
+
reason(): string | undefined;
|
|
13
|
+
}
|
|
14
|
+
/** Opens without claiming, so a losing duplicate start never trips the signal. */
|
|
15
|
+
export declare function openRunControlInbox(hookToken: string): RunControlInbox;
|
|
16
|
+
export declare class RunCancelledError extends Error {
|
|
17
|
+
constructor(reason: string);
|
|
18
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{isRunControlMessage}from"#execution/tool-run/messages.js";function openRunControlInbox(t){let n=createHook({token:t}),r=n[Symbol.asyncIterator](),i=new AbortController,a,o=consumeCancel(r,e=>{a=e,i.abort(new RunCancelledError(e))});return o.catch(()=>{}),{cancelled:o,hook:n,reason:()=>a,signal:i.signal}}async function consumeCancel(e,n){for(;;){let r;try{r=await e.next()}catch{return await new Promise(()=>{})}if(r.done===!0)return await new Promise(()=>{});if(isRunControlMessage(r.value))throw n(r.value.reason),new RunCancelledError(r.value.reason)}}var RunCancelledError=class extends Error{constructor(e){super(e),this.name=`RunCancelledError`}};export{RunCancelledError,openRunControlInbox};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
|
|
2
|
+
export declare function deriveToolRunHookToken(input: {
|
|
3
|
+
readonly callId: string;
|
|
4
|
+
readonly parentSessionId: string;
|
|
5
|
+
readonly parentTurnId: string;
|
|
6
|
+
}): string;
|
|
7
|
+
/** Resolves once the run owns its hook. Call from inside a `"use step"` body. */
|
|
8
|
+
export declare function startToolRun(input: Omit<ToolRunWorkflowInput, "hookToken">): Promise<{
|
|
9
|
+
readonly hookToken: string;
|
|
10
|
+
readonly runId: string;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{startWorkflowPreferLatest,toolRunWorkflowReference,waitForCommandHookOwner}from"#execution/workflow-runtime.js";import{deriveAgentOperationId}from"#harness/handles/operation-id.js";function deriveToolRunHookToken(e){return`eve:tool-run:${deriveAgentOperationId(e)}`}async function startToolRun(t){let n=deriveToolRunHookToken({callId:t.callId,parentSessionId:t.session.id,parentTurnId:t.session.turn.id});return await startWorkflowPreferLatest(toolRunWorkflowReference,[{...t,hookToken:n}]),{hookToken:n,runId:(await waitForCommandHookOwner(n)).runId}}export{deriveToolRunHookToken,startToolRun};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SessionContext } from "#context/session-context.js";
|
|
2
|
+
import type { ToolRunOwner } from "#execution/tool-run/messages.js";
|
|
3
|
+
import type { JsonObject } from "#shared/json.js";
|
|
4
|
+
export type ToolRunSessionContext = SessionContext["session"];
|
|
5
|
+
export interface ToolRunWorkflowInput {
|
|
6
|
+
readonly callId: string;
|
|
7
|
+
/** Deterministic per call: a replayed start re-derives it, loses the claim, and exits. */
|
|
8
|
+
readonly hookToken: string;
|
|
9
|
+
readonly input: JsonObject;
|
|
10
|
+
readonly owner: ToolRunOwner;
|
|
11
|
+
readonly session: ToolRunSessionContext;
|
|
12
|
+
/** Harness step index of the model call that made this tool call. */
|
|
13
|
+
readonly stepIndex: number;
|
|
14
|
+
readonly toolName: string;
|
|
15
|
+
readonly workflowId: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ToolRunAddress {
|
|
18
|
+
readonly hookToken: string;
|
|
19
|
+
readonly runId: string;
|
|
20
|
+
}
|
|
21
|
+
export declare const WORKFLOW_TOOL_EXECUTOR_KIND = "workflow-tool";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const WORKFLOW_TOOL_EXECUTOR_KIND=`workflow-tool`;export{WORKFLOW_TOOL_EXECUTOR_KIND};
|