eve 0.79.0 → 0.79.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/dist/src/channel/pending-authorization.d.ts +10 -0
- package/dist/src/channel/pending-authorization.js +1 -0
- package/dist/src/chunks/{use-eve-agent-BSYe_Re7.js → use-eve-agent-Ch-Q-s12.js} +43 -13
- package/dist/src/chunks/{use-eve-agent-B8brxCk-.js → use-eve-agent-Vsl-S0yI.js} +43 -13
- package/dist/src/client/abort-signal.d.ts +2 -0
- package/dist/src/client/abort-signal.js +1 -0
- package/dist/src/client/conversation-client.d.ts +2 -0
- package/dist/src/client/conversation-client.js +1 -1
- package/dist/src/client/eve-agent-store-state.d.ts +9 -0
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/ndjson.js +1 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-turn-dispatch.js +1 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -2
- package/dist/src/compiled/@eve/tracing/adapters/serialization.d.ts +2 -2
- package/dist/src/compiled/@eve/tracing/core/types.d.ts +6 -1
- package/dist/src/compiled/@eve/tracing/index.js +1 -1
- package/dist/src/compiled/@eve/tracing/otel.js +1 -1
- package/dist/src/compiled/_chunks/workflow/mcp-Bwx_LQ4q.js +5 -0
- package/dist/src/compiler/extension-compatibility.d.ts +18 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/evals/runner/reporters/assertion-scores.d.ts +6 -4
- package/dist/src/evals/runner/reporters/assertion-scores.js +1 -1
- package/dist/src/evals/runner/reporters/braintrust.js +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/authorization-callback-match.d.ts +2 -2
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/forward-session-input.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +26 -5
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-create-sdk.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-credentials.d.ts +2 -0
- package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lookup.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.d.ts +3 -6
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session/active-turn.d.ts +2 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -1
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +13 -6
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.d.ts +5 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/tasks/steps.d.ts +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/tasks/task-id-input.js +1 -1
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/workflow/answer.d.ts +1 -1
- package/dist/src/execution/tools/workflow/apply-run-messages-step.d.ts +6 -2
- package/dist/src/execution/tools/workflow/apply-run-messages-step.js +1 -1
- package/dist/src/execution/tools/workflow/body.d.ts +10 -1
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/owner-inbox.js +1 -1
- package/dist/src/execution/tools/workflow/serve.js +1 -1
- package/dist/src/execution/tools/workflow/withdraw-step.d.ts +2 -2
- package/dist/src/execution/tools/workflow/withdraw-step.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +10 -1
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/harness/action-result-helpers.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/authorization.d.ts +3 -13
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/compaction/engine.js +3 -1
- package/dist/src/harness/compaction/prompt.d.ts +7 -0
- package/dist/src/harness/compaction/prompt.js +1 -1
- package/dist/src/harness/compaction/step.d.ts +1 -0
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +1 -1
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/approved-calls.d.ts +3 -0
- package/dist/src/harness/hitl/approved-calls.js +1 -1
- package/dist/src/harness/hitl/candidates.d.ts +13 -0
- package/dist/src/harness/hitl/candidates.js +1 -1
- package/dist/src/harness/hitl/coordinator.js +1 -1
- package/dist/src/harness/hitl/index.d.ts +2 -5
- package/dist/src/harness/hitl/index.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/{proxy-input-requests.d.ts → hitl/relays.d.ts} +3 -39
- package/dist/src/harness/hitl/relays.js +1 -0
- package/dist/src/harness/hitl/requests.d.ts +64 -0
- package/dist/src/harness/hitl/requests.js +1 -0
- package/dist/src/harness/hitl/sign-ins.d.ts +9 -0
- package/dist/src/harness/hitl/sign-ins.js +1 -0
- package/dist/src/harness/inline-tool-authorization.js +1 -1
- package/dist/src/harness/input-request-resolution.d.ts +2 -1
- package/dist/src/harness/input-request-resolution.js +1 -1
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/model.d.ts +3 -1
- package/dist/src/harness/model-call/model.js +1 -1
- package/dist/src/harness/session-machine/commit.d.ts +14 -3
- package/dist/src/harness/session-machine/commit.js +1 -1
- package/dist/src/harness/session-machine/transitions.d.ts +16 -0
- package/dist/src/harness/session-machine/transitions.js +1 -1
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +1 -0
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/internal/application/optional-package-import.d.ts +5 -0
- package/dist/src/internal/application/optional-package-import.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/source-identity.d.ts +6 -0
- package/dist/src/internal/authored-definition/source-identity.js +1 -1
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/helpers/markdown.js +1 -1
- package/dist/src/internal/nitro/host/start-production-server.js +2 -2
- package/dist/src/internal/workflow/is-inactive-workflow-run-error.d.ts +2 -0
- package/dist/src/internal/workflow/is-inactive-workflow-run-error.js +1 -1
- package/dist/src/protocol/baggage.d.ts +1 -0
- package/dist/src/protocol/baggage.js +1 -1
- package/dist/src/protocol/message.d.ts +2 -0
- package/dist/src/protocol/message.js +1 -1
- package/dist/src/public/channels/teams/authorization.d.ts +53 -0
- package/dist/src/public/channels/teams/authorization.js +1 -0
- package/dist/src/public/channels/teams/defaults.js +2 -2
- package/dist/src/public/channels/teams/hitl.d.ts +2 -1
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/authorization-callback.js +1 -1
- package/dist/src/public/definitions/connections/mcp.js +1 -1
- package/dist/src/public/definitions/connections/openapi.js +1 -1
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/server.d.ts +11 -2
- package/dist/src/public/next/server.js +1 -1
- package/dist/src/public/sandbox/vercel.d.ts +2 -0
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/public/tools/result.d.ts +10 -7
- package/dist/src/react/use-eve-agent.d.ts +6 -0
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/authorization-context.d.ts +5 -0
- package/dist/src/runtime/authorization-context.js +1 -1
- package/dist/src/runtime/connections/mcp-tracing.js +1 -1
- package/dist/src/runtime/connections/openapi-operations.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +6 -0
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +18 -10
- package/dist/src/shared/action-types.d.ts +1 -0
- package/dist/src/shared/action-types.js +1 -1
- package/dist/src/shared/git.js +1 -1
- package/dist/src/shared/instrumentation-content.d.ts +1 -1
- package/dist/src/shared/instrumentation-content.js +1 -1
- package/dist/src/shared/instrumentation-decision.d.ts +3 -0
- package/dist/src/shared/instrumentation-decision.js +1 -1
- package/dist/src/shared/skill-package.js +1 -1
- package/dist/src/shared/trace-policy.js +1 -1
- package/dist/src/subagents/adapter.js +1 -1
- package/dist/src/subagents/event-proxy-step.d.ts +1 -1
- package/dist/src/subagents/event-proxy-step.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +1 -1
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +6 -0
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +38 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/signature.d.ts +4 -2
- package/dist/src/tools/signature.js +1 -1
- package/dist/src/tracing/eve/agent-otel-provider.js +1 -1
- package/dist/src/tracing/eve/gateway.d.ts +2 -1
- package/dist/src/tracing/eve/gateway.js +1 -1
- package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
- package/dist/src/tracing/eve/otel-declaration.d.ts +9 -8
- package/dist/src/tracing/eve/policy.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +6 -0
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +48 -0
- package/docs/channels/eve.mdx +2 -0
- package/docs/channels/teams.mdx +6 -0
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/connections/overview.mdx +9 -6
- package/docs/guides/frontend/overview.mdx +10 -1
- package/docs/guides/hooks.md +6 -2
- package/docs/guides/instrumentation/instrumentation.mdx +2 -0
- package/docs/guides/instrumentation/otel.mdx +3 -0
- package/docs/reference/cli.md +1 -1
- package/docs/reference/typescript-api.md +7 -6
- package/docs/sandbox/vercel.mdx +9 -0
- package/docs/skills.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +21 -0
- package/package.json +1 -1
- package/dist/src/compiled/_chunks/workflow/mcp-CrGp4EC8.js +0 -5
- package/dist/src/harness/proxy-input-requests.js +0 -1
|
@@ -29,6 +29,8 @@ export declare class SessionInputQueue {
|
|
|
29
29
|
private readonly entries;
|
|
30
30
|
private nextSequence;
|
|
31
31
|
get pendingCount(): number;
|
|
32
|
+
/** The sequence the next admission receives; every earlier admission is below it. */
|
|
33
|
+
get nextAdmission(): number;
|
|
32
34
|
enqueueDelivery(delivery: DeliverHookPayload): DeliveryAdmission;
|
|
33
35
|
enqueueControl(control: SessionControl): void;
|
|
34
36
|
/** Keeps one payload per authorization attempt; a repeated callback for the same attempt is dropped. */
|
|
@@ -65,17 +67,22 @@ export interface SteeringTurn {
|
|
|
65
67
|
}
|
|
66
68
|
export interface SteeringOptions {
|
|
67
69
|
/**
|
|
68
|
-
* The turn waits on its own person for a sign-in or approval
|
|
69
|
-
*
|
|
70
|
-
* that cannot end
|
|
70
|
+
* The turn waits on its own person for a sign-in or approval, held since
|
|
71
|
+
* this admission sequence. Their later messages steer even with
|
|
72
|
+
* `turnPolicy: "queue"`: queued, they would wait for a turn that cannot end
|
|
73
|
+
* until they act. Earlier ones were sent before the request existed, so
|
|
74
|
+
* they stay queued and never answer it.
|
|
71
75
|
*/
|
|
72
|
-
readonly
|
|
76
|
+
readonly heldSince?: number;
|
|
73
77
|
}
|
|
74
78
|
/**
|
|
75
79
|
* Only the turn's own principal steers it; another principal's message waits
|
|
76
80
|
* for the turn to end. A delivery without auth acts as the session's current
|
|
77
|
-
* identity, which is the turn's.
|
|
81
|
+
* identity, which is the turn's. `heldOnPerson` lets a queued message steer a
|
|
82
|
+
* turn that waits on its person.
|
|
78
83
|
*/
|
|
79
|
-
export declare function isSteeringDelivery(delivery: DeliverHookPayload, turn: SteeringTurn, options?:
|
|
84
|
+
export declare function isSteeringDelivery(delivery: DeliverHookPayload, turn: SteeringTurn, options?: {
|
|
85
|
+
readonly heldOnPerson?: boolean;
|
|
86
|
+
}): boolean;
|
|
80
87
|
/** A steering delivery with a message for the model, not only answers to requests. */
|
|
81
88
|
export declare function isSteeringMessage(delivery: DeliverHookPayload, turn: SteeringTurn): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{coalesceDeliveries}from"#harness/messages.js";import{ANONYMOUS_PRINCIPAL,principalOf}from"#execution/session/principal.js";var SessionInputQueue=class{entries=[];nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e){let t={delivery:e,sequence:this.nextSequence++};return this.entries.push({...t,kind:`delivery`}),t}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}takeAuthorizations(e){let t=this.entries.filter(t=>t.kind===`authorization`&&e.has(t.attemptId));if(!(t.length===0||new Set(t.map(e=>e.attemptId)).size<e.size))return this.retain(e=>!t.includes(e)),t.map(e=>e.payload)}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}takeSteering(e,t,n){let r=this.entries.filter(r=>r.kind===`delivery`&&e.has(r.sequence)&&isSteeringDelivery(r.delivery,t,n));if(r.length!==0)return this.retain(e=>e.kind!==`delivery`||!r.includes(e)),{delivery:combine(r),handoffEligible:!1,kind:`turn`,sequences:r.map(({sequence:e})=>e)}}takeNext(e){this.retain(e=>e.kind!==`authorization`);let t=this.entries.shift();if(t===void 0)return;if(t.kind===`control`)return{control:t.control,kind:`control`};let n=[t,...this.takeFollowingDeliveriesFrom(t)],r=n.map(({sequence:e})=>e),i=combine(n);return{delivery:i,handoffEligible:r.length===1&&r[0]===e?.freshSequence&&i.caller===void 0&&this.entries.length===0,kind:`turn`,sequences:r}}takeFollowingDeliveriesFrom(e){let t=principalOf(e.delivery.auth),n=[],r=e.delivery.caller?.callId;for(;;){let e=this.entries[0];if(e?.kind!==`delivery`||t===ANONYMOUS_PRINCIPAL||principalOf(e.delivery.auth)!==t||r!==void 0&&e.delivery.caller!==void 0&&e.delivery.caller.callId!==r)break;n.push(e),this.entries.shift(),r??=e.delivery.caller?.callId}return n}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isSteeringDelivery(e,t,n){return(n?.heldOnPerson===!0||(e.turnPolicy??`steer`)===`steer`)&&(e.caller===void 0||e.caller.callId===t.callerCallId)&&(e.auth===void 0||principalOf(e.auth)===t.principal)}function isSteeringMessage(e,t){return isSteeringDelivery(e,t)&&e.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0)}function combine(e){return e.length===1?e[0].delivery:coalesceDeliveries(e.map(({delivery:e})=>e))}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}export{SessionInputQueue,isSteeringDelivery,isSteeringMessage};
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{ANONYMOUS_PRINCIPAL,principalOf}from"#execution/session/principal.js";var SessionInputQueue=class{entries=[];nextSequence=0;get pendingCount(){return this.entries.length}get nextAdmission(){return this.nextSequence}enqueueDelivery(e){let t={delivery:e,sequence:this.nextSequence++};return this.entries.push({...t,kind:`delivery`}),t}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}takeAuthorizations(e){let t=this.entries.filter(t=>t.kind===`authorization`&&e.has(t.attemptId));if(!(t.length===0||new Set(t.map(e=>e.attemptId)).size<e.size))return this.retain(e=>!t.includes(e)),t.map(e=>e.payload)}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}takeSteering(e,t,n){let r=this.entries.filter(r=>r.kind===`delivery`&&e.has(r.sequence)&&isSteeringDelivery(r.delivery,t,{heldOnPerson:n?.heldSince!==void 0&&r.sequence>=n.heldSince}));if(r.length!==0)return this.retain(e=>e.kind!==`delivery`||!r.includes(e)),{delivery:combine(r),handoffEligible:!1,kind:`turn`,sequences:r.map(({sequence:e})=>e)}}takeNext(e){this.retain(e=>e.kind!==`authorization`);let t=this.entries.shift();if(t===void 0)return;if(t.kind===`control`)return{control:t.control,kind:`control`};let n=[t,...this.takeFollowingDeliveriesFrom(t)],r=n.map(({sequence:e})=>e),i=combine(n);return{delivery:i,handoffEligible:r.length===1&&r[0]===e?.freshSequence&&i.caller===void 0&&this.entries.length===0,kind:`turn`,sequences:r}}takeFollowingDeliveriesFrom(e){let t=principalOf(e.delivery.auth),n=[],r=e.delivery.caller?.callId;for(;;){let e=this.entries[0];if(e?.kind!==`delivery`||t===ANONYMOUS_PRINCIPAL||principalOf(e.delivery.auth)!==t||r!==void 0&&e.delivery.caller!==void 0&&e.delivery.caller.callId!==r)break;n.push(e),this.entries.shift(),r??=e.delivery.caller?.callId}return n}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isSteeringDelivery(e,t,n){return(n?.heldOnPerson===!0||(e.turnPolicy??`steer`)===`steer`)&&(e.caller===void 0||e.caller.callId===t.callerCallId)&&(e.auth===void 0||principalOf(e.auth)===t.principal)}function isSteeringMessage(e,t){return isSteeringDelivery(e,t)&&e.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0)}function combine(e){return e.length===1?e[0].delivery:coalesceDeliveries(e.map(({delivery:e})=>e))}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}export{SessionInputQueue,isSteeringDelivery,isSteeringMessage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{openSignIns}from"#protocol/session-projection.js";import{runtimeWait}from"#harness/session-machine/view.js";import{
|
|
1
|
+
import{openSignIns}from"#protocol/session-projection.js";import{runtimeWait}from"#harness/session-machine/view.js";import{readHitlState}from"#harness/hitl/index.js";import{sessionView}from"#harness/session-machine/commit.js";import{ownOpenRequestIds}from"#harness/session-machine/transitions.js";function derivePendingState(e,t){let{signIns:n}=readHitlState(e.state),r={authorizationAttemptIds:n.length===0?void 0:n.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),hasPendingAuthorization:openSignIns(t).length>0,hasPendingInputBatch:ownOpenRequestIds(sessionView(t,e.state)).size>0},i=runtimeWait(e.state);return i===void 0?r:{...r,hasRunsToDispatch:i.tasks.length>0,pendingCoordinationCallIds:i.callIds,pendingTaskToolCalls:i.taskToolCalls}}export{derivePendingState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{currentProjection,enterSessionProjection,saveSessionProjection}from"#harness/session-machine/current.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,OccurrenceIdKey,ParentSessionKey,ScheduleIdKey,ScheduleInstanceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,isBetweenTurns,turnPosition}from"#harness/session-machine/view.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{runStep}from"#context/run-step.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import*as agentTraceState from"#tracing/eve/agent-trace-context-store.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{dropClosedRecords}from"#harness/session-machine/commit.js";import{sessionStartedForResolvers,turnStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{recoverDynamicConnectionRehydration}from"#execution/dynamic-connection-recovery.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t={};try{return await runSessionStepBody(e,t)}finally{await t.title}}async function runSessionStepBody(e,t){let n=e.input?.delivery,r=n,i=e.input?.runtimeResults,a=readDurableSession(e.sessionState);for(let e of i?.delegatedUsage??[])a=countRunUsage(a,e);let o=await deserializeContext(e.serializedContext);enterSessionProjection(o,a.state);let s=o.require(ChannelKey),c=o.require(BundleKey),l=resolveEffectiveAgentRuntime(c,o);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let u=getPendingAuthorization(a.state),d;if(u&&r!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,r.payloads);if(r={...r,payloads:t},e.length>0){let n=e.map(e=>e.result.attemptId),i=e.map(e=>e.result);o.set(PendingAuthorizationResultKey,i),a={...a,state:clearPendingAuthorization(a.state,n)},d=e,t.length===0&&(r=void 0)}}r?.payloads.some(e=>e.message!==void 0)&&(o.delete(ScheduleIdKey),o.delete(ScheduleInstanceKey),o.delete(OccurrenceIdKey),r.schedule!==void 0&&(o.set(ScheduleIdKey,r.schedule.definition),r.schedule.instance!==void 0&&o.set(ScheduleInstanceKey,r.schedule.instance),r.schedule.occurrenceId!==void 0&&o.set(OccurrenceIdKey,r.schedule.occurrenceId)));let f=o.get(AuthKey),p=o.has(InitiatorAuthKey);r?.auth!==void 0&&(o.set(AuthKey,r.auth??null),o.has(InitiatorAuthKey)||o.set(InitiatorAuthKey,r.auth??null));let m=r===void 0?d?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;m!==void 0&&o.set(AuthKey,m);let h={...hydrateDurableSession({compactionOverrides:{thresholdPercent:l.thresholdPercent},durable:a,turnAgent:l.turnAgent}),history:validateHarnessModelMessages(e.history)},g=createExecutionHistoryView(h),_=bindSessionInstrumentation({agentName:l.turnAgent.id,ctx:o,rootSessionId:h.rootSessionId??h.sessionId,sessionId:h.sessionId}),v=turnPosition(currentProjection(o)),y=isBetweenTurns(currentProjection(o));if(!v.sessionStarted&&!o.has(SessionTitleKey)&&!o.has(ParentSessionKey)){let e=n?.payloads.find(e=>e.message!==void 0)?.message,r=deriveSessionTitle(n?.title??e);r!==void 0&&(o.set(SessionTitleKey,r),t.title=setEveAttributes({"$eve.title":r}))}n!==void 0&&(await contextStorage.run(o,()=>_?.preparePreamble({sequence:v.sequence,sessionStarted:v.sessionStarted})),await contextStorage.run(o,()=>_?.instrumentChannelDelivery({agentName:c.turnAgent.id,ctx:o,delivery:n,rootSessionId:h.rootSessionId??h.sessionId,sequence:v.sequence,sessionId:h.sessionId,turnId:activeTurnId(v)})));let failChannelDeliveries=async e=>{await contextStorage.run(o,()=>_?.instrumentChannelDelivery({ctx:o,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await _?.flush()},b=openSessionEventPublisher({ctx:o,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:x}=b.dispatcher,S=new AbortController,C=e.abortSignal===void 0?S.signal:AbortSignal.any([e.abortSignal,S.signal]);try{let u=bindDynamicConnections(o,c.resolvedAgent),m={...c.graph.root,turnAgent:l.turnAgent},w=!1,T=createTurnEventHandler({abortSignal:C,bundle:c,canCancelTurn:e.input?.control===void 0,hookCancellation:S,ctx:o,dynamicConnections:u,effectiveAgent:l,effectiveNode:m,instrumentation:_,publisher:b}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(w=!0),await T(e,t)},E=r!==void 0&&!y?structuredClone(x.state):void 0,D;if(r!==void 0){let e=[];try{for(let t of r.payloads){let n=s.deliver?await s.deliver(t,x):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}D=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let O=r?.auth===void 0?void 0:attributeAnswers({responder:r.auth,state:a.state,stepInput:D});if(O!==void 0&&(D=O,f===void 0?o.delete(AuthKey):o.set(AuthKey,f),p||o.delete(InitiatorAuthKey)),r!==void 0&&D===void 0&&!y)f===void 0?o.delete(AuthKey):o.set(AuthKey,f),x.state=E;else if(n?.payloads.some(e=>e.message!==void 0)){let e=n.deliveryMetadata?.map(e=>e.deliveryId)??[];o.set(TurnDeliveryIdsKey,v.turnId?[...new Set([...o.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!v.sessionStarted&&o.get(ChannelDeliveryKey)!==void 0&&o.set(TurnDeliveryIdsKey,[o.require(ChannelDeliveryKey).deliveryId]);if(i!==void 0&&(i.acceptedAtMsByCallId!==void 0&&o.set(RuntimeActionSettlementTimesKey,i.acceptedAtMsByCallId),D={...D,runtimeActionResults:i.results}),n!==void 0){let e={...s,state:{...x.state}};setChannelContext(o,e)}if(r!==void 0&&D===void 0&&y){await contextStorage.run(o,()=>_?.instrumentChannelDelivery({ctx:o,includeTurn:!1,outcome:`completed`})),await _?.flush();let t=saveSessionProjection(reconcileSessionContinuationToken(o,h),o),n=serializeContext(o),r=t===h?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t,currentProjection(o)),serializedContext:n,...r}}let k=c.subagentRegistry.dynamicResolvers??[],A=c.resolvedAgent.dynamicToolResolvers??[],j=buildRuntimeIdentity(m);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(c.compiledArtifactsSource),n=v.sessionStarted;if(o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null),!n)o.set(SessionDynamicSubagentRuntimeRevisionKey,t),o.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=sessionStartedForResolvers(j);await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:o,resolvers:k,event:e,messages:g.initial.messages,runtimeRevision:t}),contextStorage.run(o,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:o,resolvers:A,event:e,messages:g.initial.messages,runtimeRevision:t}))]),y||await rebindMissingCompiledDynamicToolCallbacks({ctx:o,event:turnStartedForResolvers({sequence:v.sequence,turnId:activeTurnId(v)}),messages:g.initial.messages,resolvers:A})}}catch(e){throw await failChannelDeliveries(e),e}let M=c.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,N=o.get(CapabilitiesKey),runHarnessStep=async(n,r,i)=>{let a=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:l.thresholdPercent},session:n,turnAgent:l.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:C,capabilities:N,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>u.dispatch(turnStartedForResolvers(e)),signInCompletions:i,historyProjector:g.projector,historyView:g.prepare(a),instrumentation:_,modelResolutionScope:{moduleMap:c.moduleMap,nodeId:c.nodeId},node:m,titleAttributeWrite:t.title})(a,r)},P,F;try{throwIfTurnAborted(C),F=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:D,initialSession:h,modelCallsPerStep:M,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(o,t,async t=>{o.setVirtualContext(HandleEventKey,handleEvent),o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null);let r=e&&D?.outputSchema!==void 0?{...t,outputSchema:D.outputSchema}:t,i=turnPosition(currentProjection(o));try{await u.rehydrate(i,j,isBetweenTurns(currentProjection(o))?void 0:{sequence:i.sequence,turnId:activeTurnId(i)})}catch(e){let t=await recoverDynamicConnectionRehydration({emit:handleEvent,error:e,projection:currentProjection(o),session:r});if(t!==void 0)return t;throw e}let a=e&&d!==void 0?d.map(({challenge:e})=>e):void 0;return runHarnessStep(r,n,a)});r.settledTurn===void 0&&throwIfTurnAborted(C);let i={...r,session:saveSessionProjection(r.session,o)};return P={result:i,serializedContext:serializeContext(o)},i}})}catch(t){if(!isTurnCancellation(t)&&!C.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:P,ctx:o,initialSession:h,stepInput:D})}let I=saveSessionProjection(dropClosedRecords(reconcileSessionContinuationToken(o,F.session),currentProjection(o)),o);agentTraceState.pruneAgentTraceState(o,I.sessionId,I.state);let L=serializeContext(o);F={...F,session:I};let R=resolveSessionStepResult(F,L);return R.action===`done`&&await b.writer.close(),w?{...R,compacted:!0}:R}finally{b.writer.release()}}export{turnStep};
|
|
1
|
+
import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{currentProjection,enterSessionProjection,saveSessionProjection}from"#harness/session-machine/current.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,OccurrenceIdKey,ParentSessionKey,ScheduleIdKey,ScheduleInstanceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,isBetweenTurns,storedProjection,turnPosition}from"#harness/session-machine/view.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{runStep}from"#context/run-step.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{readHitlState}from"#harness/hitl/index.js";import*as agentTraceState from"#tracing/eve/agent-trace-context-store.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey}from"#harness/authorization.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{dropClosedRecords,saveTransition,sessionView}from"#harness/session-machine/commit.js";import{matchSignIns}from"#harness/session-machine/transitions.js";import{sessionStartedForResolvers,turnStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{recoverDynamicConnectionRehydration}from"#execution/dynamic-connection-recovery.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t={};try{return await runSessionStepBody(e,t)}finally{await t.title}}async function runSessionStepBody(e,t){let n=e.input?.delivery,r=n,i=e.input?.runtimeResults,a=readDurableSession(e.sessionState);for(let e of i?.delegatedUsage??[])a=countRunUsage(a,e);let o=await deserializeContext(e.serializedContext);enterSessionProjection(o,a.state);let s=o.require(ChannelKey),c=o.require(BundleKey),l=resolveEffectiveAgentRuntime(c,o);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let{signIns:u}=readHitlState(a.state),d;if(u.length>0&&r!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,r.payloads);if(r={...r,payloads:t},e.length>0){let n=e.map(e=>e.result.attemptId),i=e.map(e=>e.result);o.set(PendingAuthorizationResultKey,i);let s=sessionView(storedProjection(a.state),a.state),c=matchSignIns(s,{attemptIds:n});if(c.events.length!==0)throw Error(`matchSignIns must not emit events.`);a=saveTransition(a,c),d=e,t.length===0&&(r=void 0)}}r?.payloads.some(e=>e.message!==void 0)&&(o.delete(ScheduleIdKey),o.delete(ScheduleInstanceKey),o.delete(OccurrenceIdKey),r.schedule!==void 0&&(o.set(ScheduleIdKey,r.schedule.definition),r.schedule.instance!==void 0&&o.set(ScheduleInstanceKey,r.schedule.instance),r.schedule.occurrenceId!==void 0&&o.set(OccurrenceIdKey,r.schedule.occurrenceId)));let f=o.get(AuthKey),p=o.has(InitiatorAuthKey);r?.auth!==void 0&&(o.set(AuthKey,r.auth??null),o.has(InitiatorAuthKey)||o.set(InitiatorAuthKey,r.auth??null));let m=r===void 0?d?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;m!==void 0&&o.set(AuthKey,m);let h={...hydrateDurableSession({compactionOverrides:{thresholdPercent:l.thresholdPercent},durable:a,turnAgent:l.turnAgent}),history:validateHarnessModelMessages(e.history)},g=createExecutionHistoryView(h),_=bindSessionInstrumentation({agentName:l.turnAgent.id,ctx:o,rootSessionId:h.rootSessionId??h.sessionId,sessionId:h.sessionId}),v=turnPosition(currentProjection(o)),y=isBetweenTurns(currentProjection(o));if(!v.sessionStarted&&!o.has(SessionTitleKey)&&!o.has(ParentSessionKey)){let e=n?.payloads.find(e=>e.message!==void 0)?.message,r=deriveSessionTitle(n?.title??e);r!==void 0&&(o.set(SessionTitleKey,r),t.title=setEveAttributes({"$eve.title":r}))}n!==void 0&&(await contextStorage.run(o,()=>_?.preparePreamble({sequence:v.sequence,sessionStarted:v.sessionStarted})),await contextStorage.run(o,()=>_?.instrumentChannelDelivery({agentName:c.turnAgent.id,ctx:o,delivery:n,rootSessionId:h.rootSessionId??h.sessionId,sequence:v.sequence,sessionId:h.sessionId,turnId:activeTurnId(v)})));let failChannelDeliveries=async e=>{await contextStorage.run(o,()=>_?.instrumentChannelDelivery({ctx:o,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await _?.flush()},b=openSessionEventPublisher({ctx:o,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:x}=b.dispatcher,S=new AbortController,C=e.abortSignal===void 0?S.signal:AbortSignal.any([e.abortSignal,S.signal]);try{let u=bindDynamicConnections(o,c.resolvedAgent),m={...c.graph.root,turnAgent:l.turnAgent},w=!1,T=createTurnEventHandler({abortSignal:C,bundle:c,canCancelTurn:e.input?.control===void 0,hookCancellation:S,ctx:o,dynamicConnections:u,effectiveAgent:l,effectiveNode:m,instrumentation:_,publisher:b}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(w=!0),await T(e,t)},E=r!==void 0&&!y?structuredClone(x.state):void 0,D;if(r!==void 0){let e=[];try{for(let t of r.payloads){let n=s.deliver?await s.deliver(t,x):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}D=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let O=r?.auth===void 0?void 0:attributeAnswers({responder:r.auth,state:a.state,stepInput:D});if(O!==void 0&&(D=O,f===void 0?o.delete(AuthKey):o.set(AuthKey,f),p||o.delete(InitiatorAuthKey)),r!==void 0&&D===void 0&&!y)f===void 0?o.delete(AuthKey):o.set(AuthKey,f),x.state=E;else if(n?.payloads.some(e=>e.message!==void 0)){let e=n.deliveryMetadata?.map(e=>e.deliveryId)??[];o.set(TurnDeliveryIdsKey,v.turnId?[...new Set([...o.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!v.sessionStarted&&o.get(ChannelDeliveryKey)!==void 0&&o.set(TurnDeliveryIdsKey,[o.require(ChannelDeliveryKey).deliveryId]);if(i!==void 0&&(i.acceptedAtMsByCallId!==void 0&&o.set(RuntimeActionSettlementTimesKey,i.acceptedAtMsByCallId),D={...D,runtimeActionResults:i.results}),n!==void 0){let e={...s,state:{...x.state}};setChannelContext(o,e)}if(r!==void 0&&D===void 0&&y){await contextStorage.run(o,()=>_?.instrumentChannelDelivery({ctx:o,includeTurn:!1,outcome:`completed`})),await _?.flush();let t=saveSessionProjection(reconcileSessionContinuationToken(o,h),o),n=serializeContext(o),r=t===h?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t,currentProjection(o)),serializedContext:n,...r}}let k=c.subagentRegistry.dynamicResolvers??[],A=c.resolvedAgent.dynamicToolResolvers??[],j=buildRuntimeIdentity(m);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(c.compiledArtifactsSource),n=v.sessionStarted;if(o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null),!n)o.set(SessionDynamicSubagentRuntimeRevisionKey,t),o.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=sessionStartedForResolvers(j);await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:o,resolvers:k,event:e,messages:g.initial.messages,runtimeRevision:t}),contextStorage.run(o,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:o,resolvers:A,event:e,messages:g.initial.messages,runtimeRevision:t}))]),y||await rebindMissingCompiledDynamicToolCallbacks({ctx:o,event:turnStartedForResolvers({sequence:v.sequence,turnId:activeTurnId(v)}),messages:g.initial.messages,resolvers:A})}}catch(e){throw await failChannelDeliveries(e),e}let M=c.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,N=o.get(CapabilitiesKey),runHarnessStep=async(n,r,i)=>{let a=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:l.thresholdPercent},session:n,turnAgent:l.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:C,capabilities:N,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>u.dispatch(turnStartedForResolvers(e)),signInCompletions:i,historyProjector:g.projector,historyView:g.prepare(a),instrumentation:_,modelResolutionScope:{moduleMap:c.moduleMap,nodeId:c.nodeId},node:m,titleAttributeWrite:t.title})(a,r)},P,F;try{throwIfTurnAborted(C),F=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:D,initialSession:h,modelCallsPerStep:M,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(o,t,async t=>{o.setVirtualContext(HandleEventKey,handleEvent),o.setVirtualContext(StaticModelReferenceKey,l.turnAgent.model??null);let r=e&&D?.outputSchema!==void 0?{...t,outputSchema:D.outputSchema}:t,i=turnPosition(currentProjection(o));try{await u.rehydrate(i,j,isBetweenTurns(currentProjection(o))?void 0:{sequence:i.sequence,turnId:activeTurnId(i)})}catch(e){let t=await recoverDynamicConnectionRehydration({emit:handleEvent,error:e,projection:currentProjection(o),session:r});if(t!==void 0)return t;throw e}let a=e&&d!==void 0?d.map(({challenge:e})=>e):void 0;return runHarnessStep(r,n,a)});r.settledTurn===void 0&&throwIfTurnAborted(C);let i={...r,session:saveSessionProjection(r.session,o)};return P={result:i,serializedContext:serializeContext(o)},i}})}catch(t){if(!isTurnCancellation(t)&&!C.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:P,ctx:o,initialSession:h,stepInput:D})}let I=saveSessionProjection(dropClosedRecords(reconcileSessionContinuationToken(o,F.session),currentProjection(o)),o);agentTraceState.pruneAgentTraceState(o,I.sessionId,I.state);let L=serializeContext(o);F={...F,session:I};let R=resolveSessionStepResult(F,L);return R.action===`done`&&await b.writer.close(),w?{...R,compacted:!0}:R}finally{b.writer.release()}}export{turnStep};
|
|
@@ -40,6 +40,7 @@ export declare class SessionExecution {
|
|
|
40
40
|
* stream is closed, and finalizing the session terminates the children.
|
|
41
41
|
*/
|
|
42
42
|
private handleBoundaryMessages;
|
|
43
|
+
/** Hooks on the messages' events may cancel `turn`, the turn that is running. */
|
|
43
44
|
private applyRunMessages;
|
|
44
45
|
private runTurnSteps;
|
|
45
46
|
/**
|
|
@@ -71,7 +72,10 @@ export declare class SessionExecution {
|
|
|
71
72
|
* The turn waits on a sign-in or tool approval it raised. It wakes with the
|
|
72
73
|
* delivery its next step reads: the sign-in callback, an approval answer
|
|
73
74
|
* from any responder, or a message from the turn's own person, which steers
|
|
74
|
-
* the turn and cancels the request. Anyone else's message queues behind it
|
|
75
|
+
* the turn and cancels the request. Anyone else's message queues behind it,
|
|
76
|
+
* as does a queued message admitted before the step that raised the request
|
|
77
|
+
* (`heldSince`): it was sent before the request existed, so it must not
|
|
78
|
+
* answer it.
|
|
75
79
|
*/
|
|
76
80
|
private waitForHeldRequest;
|
|
77
81
|
private waitForRuntimeActionResults;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{taskWaitResult}from"#execution/tasks/table.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,getBlockingWorkflowToolRuns,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{handleWorkflowToolRunMessage,isAppliedRunMessage,takeLeadingAppliedRunMessages}from"#execution/session-workflow-tool-run.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{answerTaskCancel,cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{taskToolResult}from"#execution/tasks/calls.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{applyRunMessagesStep}from"#execution/tools/workflow/apply-run-messages-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{ActiveTurn}from"#execution/session/active-turn.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{startTaskToolCallsStep,traceTaskToolCallStep}from"#execution/session/task-tool-tracing-step.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n;try{n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)},t.control)}catch(e){throw t.control?.dispose(),e}try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),{...t,...n.caller!==void 0&&{caller:n.caller},...n.compacted&&{compacted:!0}}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1){let
|
|
1
|
+
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{TASK_WAIT_TOOL_NAME}from"#protocol/task-tools.js";import{renderTaskWaitResult}from"#execution/tasks/render.js";import{taskWaitResult}from"#execution/tasks/table.js";import{sleep}from"#compiled/@workflow/core/index.js";import{findBlockingWorkflowToolRun,getBlockingWorkflowToolRuns,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{handleWorkflowToolRunMessage,isAppliedRunMessage,takeLeadingAppliedRunMessages}from"#execution/session-workflow-tool-run.js";import{resolveTurnPrincipal}from"#execution/session/principal.js";import{answerTaskCancel,cancelWorkingTasks,sessionTaskTable}from"#execution/tasks/session.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{taskToolResult}from"#execution/tasks/calls.js";import{publishTurnWaitingStep}from"#execution/session/turn-waiting-step.js";import{applyRunMessagesStep}from"#execution/tools/workflow/apply-run-messages-step.js";import{interruptWorkflowToolRun}from"#execution/tools/workflow/interrupt.js";import{turnStep}from"#execution/session/turn-step.js";import{ActiveTurn}from"#execution/session/active-turn.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{startTaskToolCallsStep,traceTaskToolCallStep}from"#execution/session/task-tool-tracing-step.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e,t={}){let n;try{n=new ActiveTurn(this.input,{caller:t.caller,principal:resolveTurnPrincipal(e,this.input.cursor.serializedContext)},t.control)}catch(e){throw t.control?.dispose(),e}try{let t=await this.runTurnSteps(n,e);return await this.handleBoundaryMessages(n.takeBoundaryMessages(),t.kind===`done`),t.kind===`park`&&t.settled!==void 0&&await cancelWorkingTasks(this.input.cursor,`turn_ended`),{...t,...n.caller!==void 0&&{caller:n.caller},...n.compacted&&{compacted:!0}}}finally{n.dispose()}}async handleBoundaryMessages(e,t=!1,n){let r=[];for(let i of e)isAppliedRunMessage(i)?(!t||i.kind!==`agent-started`)&&r.push(i):(await this.applyRunMessages(r,n),r=[],await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:i}));await this.applyRunMessages(r,n)}async applyRunMessages(e,t){if(e.length===0)return;let{cancelled:n}=await this.input.cursor.advance(n=>applyRunMessagesStep({...n,canCancelTurn:t!==void 0,messages:e}));n&&t?.abort()}async runTurnSteps(e,t){let n=t,r=e.caller;for(;;){let{cursor:t}=this.input,i=r;r=void 0;let a=await t.advanceWithHistory(t=>turnStep({...t,abortSignal:e.signal,caller:i,input:n,steeringSignal:e.steeringSignal}));a.compacted===!0&&(e.compacted=!0);let o=a.action===`park`?a.pendingCoordinationCallIds:void 0,s=a.action===`park`&&a.settled!==void 0,c=this.input.queue.nextAdmission;await e.admitBoundary();let l=a.action===`done`;if(await this.handleBoundaryMessages(e.takeBoundaryMessages(),l,l?void 0:e),a.action===`cancelled`||!s&&e.signal.aborted&&o===void 0)return await this.finishCancelledTurn(e);if(a.action===`done`)return{isError:a.isError,kind:`done`,output:a.output??``,usage:a.usage,usageDelta:a.usageDelta};if(a.action===`held`&&a.hold===`request`){if(a.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error(`This session cannot request human input, so it cannot wait for a tool approval or question. Configure unattended tools with an approval policy that does not require human input.`);let t=await this.waitForHeldRequest(e,a,c);if(t===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:t};continue}if(a.action===`held`){if(await this.waitForHeldTurn(e)===`cancelled`)return await this.finishCancelledTurn(e);let t=await e.takeSteering();n=t===void 0?void 0:{delivery:t};continue}if(o!==void 0&&a.action===`park`){let t=a.hasRunsToDispatch===!1?[]:await this.dispatchRuns(),r=t.length===0?void 0:Date.now(),i=await this.waitForRuntimeActionResults({initialAcceptedAtMs:r,initialResults:t,taskToolCalls:a.pendingTaskToolCalls??[],pendingCallIds:o,turn:e});if(i===`cancelled`)return await this.finishCancelledTurn(e);n={delivery:await e.takeSteering(),runtimeResults:i};continue}if(a.action===`park`)return{kind:`park`,settled:a.settled};let u=await e.takeSteering();n=u===void 0?void 0:{delivery:u}}}async dispatchRuns(){return(await this.input.cursor.advance(e=>dispatchCoordinationStep({action:`park`,workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},...e}))).results}async handleWorkflowMessage(e,t){if(isAppliedRunMessage(e)){let n=t?.takeAppliedRunMessages()??takeLeadingAppliedRunMessages(this.input.inbox);await this.applyRunMessages([e,...n],t);return}return await handleWorkflowToolRunMessage({cursor:this.input.cursor,message:e})}async cancelTurnWork(){let{cursor:e}=this.input;mayWaitOnWorkflowToolRuns(e.sessionState)&&await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),await cancelWorkingTasks(e,`turn_cancelled`)}async finishCancelledTurn(e){return await this.handleBoundaryMessages(e.takeBoundaryMessages(`agent-started`)),await this.cancelTurnWork(),{cancelled:!0,kind:`park`}}async waitForHeldTurn(e){let t=!1;for(;;){let n={interrupted:t,timedOut:!1};if(taskWaitResult(sessionTaskTable(this.input.cursor),n)!==void 0)return`woke`;let r=await e.nextRuntimeEvent([]);if(r===`cancelled`)return r;switch(r.kind){case`steering`:t=!0;continue;case`workflow`:await this.handleWorkflowMessage(r.message,e);continue;case`input`:case`runtime-action-result`:case`timeout`:continue}}}async waitForHeldRequest(e,t,n){let r=new Set(t.authorizationAttemptIds),i=new Set(t.inputRequestIds);for(;;){let t=this.input.queue.takeAuthorizations(r);if(t!==void 0)return{kind:`deliver`,payloads:t};let a=await e.takeInputResponses(i);if(a!==void 0)return a;let o=await e.takeSteering({heldSince:n});if(o!==void 0)return o;let s=await e.nextRuntimeEvent([]);if(s===`cancelled`)return s;s.kind===`workflow`&&await this.handleWorkflowMessage(s.message,e)}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=!1,r=new Map,i=new Map;if(e.initialAcceptedAtMs!==void 0)for(let n of t)r.set(n.callId,e.initialAcceptedAtMs);let accept=e=>{t.push(e),r.set(e.callId,Date.now())},a=await this.answerTaskToolCalls(e.taskToolCalls,accept);try{for(;;){a=await this.resolveTaskWaits(a,n,accept);let o=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(o!==void 0){let e=o.flatMap(e=>{let t=i.get(e.callId);return t===void 0?[]:[t]});return{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(e.callId)])),...e.length>0&&{delegatedUsage:e},results:o}}let s=a.flatMap(e=>e.timer===void 0?[]:[e.timer]),c=await e.turn.nextRuntimeEvent(s);if(c===`cancelled`)return c;if(c.kind===`timeout`){for(let e of a)e.callId===c.callId&&(e.timedOut=!0);continue}if(c.kind===`input`)continue;if(c.kind===`steering`){n||await this.interruptWaitedWorkflowCalls(e.pendingCallIds,t),n=!0;continue}if(c.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,n=c.results.filter(t=>t.kind===`tool-result`&&isInboxToolResultFromRecordedWorkflowToolRun(e,t));if(n.length>0){let e=Date.now();t.push(...n);for(let t of n)r.set(t.callId,e)}continue}let l=await this.handleWorkflowMessage(c.message,e.turn);l!==void 0&&(accept(l),c.message.kind===`outcome`&&c.message.usage!==void 0&&i.set(l.callId,c.message.usage))}}finally{for(let e of a)await this.traceTaskWait(e,void 0,!0)}}async resolveTaskWaits(e,t,n){let r=sessionTaskTable(this.input.cursor),i=[];for(let a of e){let e=taskWaitResult(r,{interrupted:t,timedOut:a.timedOut});if(e===void 0){i.push(a);continue}let o=renderTaskWaitResult(e,Date.now()-a.startedAtMs);await this.traceTaskWait(a,o,t),n(taskToolResult(a.callId,TASK_WAIT_TOOL_NAME,o))}return i}async answerTaskToolCalls(e,t){let n=[],r=e.length===0?0:await startTaskToolCallsStep();for(let i of e)if(i.kind===TASK_WAIT_TOOL_NAME)n.push(startTaskWait(i,r));else{let e;try{e=await answerTaskCancel(this.input.cursor,i)}catch(e){throw await this.input.cursor.advance(e=>traceTaskToolCallStep(e,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},failed:!0})),e}await this.input.cursor.advance(t=>traceTaskToolCallStep(t,{callId:i.callId,toolName:i.kind,startedAtMs:r,completedAtMs:Date.now(),input:{taskId:i.taskId},output:e.output})),t(e)}let i=await this.resolveTaskWaits(n,!1,t);return i.length>0&&await this.input.cursor.advance(publishTurnWaitingStep),i}async traceTaskWait(e,t,n=!1){await this.input.cursor.advance(r=>traceTaskToolCallStep(r,{callId:e.callId,toolName:TASK_WAIT_TOOL_NAME,startedAtMs:e.startedAtMs,completedAtMs:Date.now(),input:e.input,output:t,failed:n}))}async interruptWaitedWorkflowCalls(e,t){let n=this.input.cursor.sessionState.snapshot.session.state,r=new Set(t.map(e=>e.callId)),i=e.filter(e=>!r.has(e)).flatMap(e=>{let t=findBlockingWorkflowToolRun(n,e);return t===void 0?[]:[t.address]});await Promise.all(i.map(e=>interruptWorkflowToolRun(e)))}};function startTaskWait(e,t){let{callId:n,timeoutMs:r}=e,i=r===void 0?void 0:sleep(r).then(()=>n);return{callId:n,startedAtMs:t,input:r===void 0?{}:{timeoutSeconds:r/1e3},timedOut:r===0,timer:i}}function mayWaitOnWorkflowToolRuns(e){try{return getBlockingWorkflowToolRuns(e.snapshot?.session?.state).length>0}catch{return!0}}export{SessionExecution,hasDelegatedCallerContext};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type TaskRunCommands } from "#execution/tasks/table.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { PublishedSessionEvents, SessionStepState } from "#execution/publish-session-events.js";
|
|
3
3
|
import { type SessionStateTransition } from "#execution/session/state-delta.js";
|
|
4
4
|
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
|
|
5
5
|
import type { TaskCancelReason } from "#protocol/message.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resumeHook}from"#internal/workflow/runtime.js";import{cancelTask,findTask,finishTaskRun,markTaskRunStarted,readTaskTable,recordTaskRunUsage,settleRemainingTaskCalls,settleTaskCalls,writeTaskTable}from"#execution/tasks/table.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{readHitlState}from"#harness/hitl/index.js";import{commitSessionStep}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{finishRun,settleTask}from"#harness/session-machine/transitions.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{workflowToolRunFailureOutput}from"#execution/tools/workflow/owner-inbox.js";import{ignoreGoneTarget}from"#execution/tasks/workflow-target.js";async function applyTaskRunMessage(e){let{message:t}=e,n=t.from.taskId,r=readDurableSession(e.sessionState);if(n===void 0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let i=readTaskTable(r.state),a=[],o=[];switch(t.kind){case`started`:{let e=markTaskRunStarted(i,n,t.from.runId);i=e.table,e.held!==void 0&&await sendTaskRunCommands(e.held);break}case`reply`:{({session:r,table:i}=countTaskRunUsage(r,i,n,t));let e={output:t.output,status:`completed`},o=findTask(i,n),s=settleTaskCalls(i,{callIds:t.callIds,outcome:e,taskId:n});i=s.table,a.push(...taskSettled(o,s.settled,e));break}case`usage`:({session:r,table:i}=countTaskRunUsage(r,i,n,t));break;case`outcome`:{({session:r,table:i}=countTaskRunUsage(r,i,n,t));let e=toOutcome(t),s=findTask(i,n),c=settleRemainingTaskCalls(i,n,e);a.push(...taskSettled(s,c.settled,e)),i=finishTaskRun(c.table,n,t.from.runId);let l=runRequestIds(r,t.from.runId);o.push(e=>finishRun(e,{requestIds:l,taskId:n}));break}}return await commitTaskDecisions(e,saveTable(e.sessionState,r,i),{settles:a,withdraws:o})}async function cancelTasksStep(e){"use step";return await withSessionStateDelta(e,cancelTasks)}async function cancelTasks(e){let t=readDurableSession(e.sessionState),n=readTaskTable(t.state),r=[],i=[],a={reason:e.reason,status:`cancelled`};for(let o of e.taskIds){let e=findTask(n,o),s=cancelTask(n,o);if(n=s.table,r.push(...taskSettled(e,s.settled,a)),s.send!==void 0){if(e?.resumable===!1){let e=runRequestIds(t,s.send.run.runId);i.push(t=>finishRun(t,{requestIds:e,taskId:o}))}await sendTaskRunCommands(s.send)}}return await commitTaskDecisions(e,saveTable(e.sessionState,t,n),{settles:r,withdraws:i})}async function commitTaskDecisions(e,t,n){let r=await commitSessionStep({...e,sessionState:t},e=>n.withdraws.map(t=>t(e)),{origin:`relayed`});return await commitSessionStep({...e,...r},e=>n.settles.map(t=>t(e)),{origin:`own`})}function taskSettled(e,t,n){return e===void 0?[]:[r=>settleTask(r,{calls:t,outcome:n,task:e})]}async function sendTaskRunCommands(e){for(let t of e.commands)await ignoreGoneTarget(resumeHook(e.run.hookToken,toControlMessage(t)))}function toControlMessage(e){switch(e.kind){case`cancel`:return{kind:`cancel`,reason:`The task was cancelled.`};case`call`:return{call:e.call,kind:`call`}}}function toOutcome(e){switch(e.result.status){case`completed`:return{output:e.result.output,status:`completed`};case`failed`:return{error:failureMessage(e),status:`failed`};case`cancelled`:return{status:`cancelled`}}}function failureMessage(e){let t=workflowToolRunFailureOutput(e);if(typeof t==`string`)return t;let n=typeof t==`object`&&t?Reflect.get(t,`message`):void 0;return typeof n==`string`?n:JSON.stringify(t)}function countTaskRunUsage(e,t,n,r){let i=findTask(t,n)?.run;return r.usage===void 0||i?.runId!==r.from.runId?{session:e,table:t}:{session:countRunUsage(e,r.usage,i.usage),table:recordTaskRunUsage(t,n,r.usage)}}function runRequestIds(e,t){return[...readHitlState(e.state).relays].filter(([,e])=>e.runId===t).map(([e])=>e)}function saveTable(e,t,n){return replaceDurableSessionSnapshot({session:writeTaskTable(t,n),state:e})}export{applyTaskRunMessage,cancelTasksStep,sendTaskRunCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{displayTitle}from"#shared/display-name.js";import{firstSentence}from"#shared/presentation-text.js";import{isToolSchema,withOptionalStringProperty}from"#tools/schema.js";import{AGENT_SERVE_TOOL_DESCRIPTION,SERVE_TOOL_DESCRIPTION,TASK_ID_INPUT_DESCRIPTION}from"#execution/tasks/render.js";import{AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentTool}from"#execution/tasks/tool-entry-point.js";const TASK_ID_INPUT=`taskId`;function withTaskIdSchema(e){return withOptionalStringProperty(e,{description:TASK_ID_INPUT_DESCRIPTION,name:TASK_ID_INPUT})}function withTaskIdInput(e){let t=e.inputSchema;if(!isToolSchema(t))throw Error(`Tool "${e.name}" has no input schema eve can add taskId to.`);let n=isAgentTool(e),r={...e,description:appendSentence(e.description,n?AGENT_SERVE_TOOL_DESCRIPTION:SERVE_TOOL_DESCRIPTION),inputSchema:withTaskIdSchema(t)};return!n||e.label?.start!==void 0?r:{...r,label:{...e.label,start:t=>agentCallLabel(e.name,t)}}}function agentCallLabel(e,t){let n=typeof t==`object`&&t?t.message:void 0,r=typeof n==`string`?firstSentence(n):void 0;return r===void 0?displayTitle(e):e===AGENT_TOOL_NAME?r:`${displayTitle(e)}: ${r}`}function splitTaskIdInput(e){let{[TASK_ID_INPUT]:t,...n}=e;return typeof t
|
|
1
|
+
import{displayTitle}from"#shared/display-name.js";import{firstSentence}from"#shared/presentation-text.js";import{isToolSchema,withOptionalStringProperty}from"#tools/schema.js";import{AGENT_SERVE_TOOL_DESCRIPTION,SERVE_TOOL_DESCRIPTION,TASK_ID_INPUT_DESCRIPTION}from"#execution/tasks/render.js";import{AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentTool}from"#execution/tasks/tool-entry-point.js";const TASK_ID_INPUT=`taskId`;function withTaskIdSchema(e){return withOptionalStringProperty(e,{description:TASK_ID_INPUT_DESCRIPTION,name:TASK_ID_INPUT})}function withTaskIdInput(e){let t=e.inputSchema;if(!isToolSchema(t))throw Error(`Tool "${e.name}" has no input schema eve can add taskId to.`);let n=isAgentTool(e),r={...e,description:appendSentence(e.description,n?AGENT_SERVE_TOOL_DESCRIPTION:SERVE_TOOL_DESCRIPTION),inputSchema:withTaskIdSchema(t)};return!n||e.label?.start!==void 0?r:{...r,label:{...e.label,start:t=>agentCallLabel(e.name,t)}}}function agentCallLabel(e,t){let n=typeof t==`object`&&t?t.message:void 0,r=typeof n==`string`?firstSentence(n):void 0;return r===void 0?displayTitle(e):e===AGENT_TOOL_NAME?r:`${displayTitle(e)}: ${r}`}function splitTaskIdInput(e){let{[TASK_ID_INPUT]:t,...n}=e;return typeof t!=`string`||t===``?{input:n}:{input:n,taskId:t}}function appendSentence(e,t){let n=e.trimEnd();return n===``?t:`${n} ${t}`}export{TASK_ID_INPUT,splitTaskIdInput,withTaskIdInput,withTaskIdSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{handleAuthorizationError}from"#runtime/connections/scoped-authorization.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";function createToolExecuteWithAuth(e){return(t,n)=>{let r=createAuthorizationContext({scope:e.scope}),i={...buildBaseToolContext({options:n,toolName:e.scope}),messages:n.messages,getToken:r.getToken,requireAuth:r.requireAuth};return r.run(()=>e.execute(t,i))}}function buildApprovalResponseAuth(e){let t=createAuthorizationContext({scope:e.scope,boundResponder:e.responder});return{getToken:(n,r)=>t.getToken(n,namespaceApprovalAuthOptions(e.scope,r)),requireAuth:(n,r)=>t.requireAuth(n,namespaceApprovalAuthOptions(e.scope,r))}}function namespaceApprovalAuthOptions(e,t){return t?.authKey===void 0?t:{...t,authKey:`${e}:${t.authKey}`}}async function handleApprovalResponsePolicyError(e){return await handleAuthorizationError(e)}export{buildApprovalResponseAuth,createToolExecuteWithAuth,handleApprovalResponsePolicyError};
|
|
1
|
+
import{handleAuthorizationError}from"#runtime/connections/scoped-authorization.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";function createToolExecuteWithAuth(e){return(t,n)=>{let r=createAuthorizationContext({scope:e.scope}),i={...buildBaseToolContext({options:n,toolName:e.scope}),messages:n.messages,getToken:r.getToken,requireAuth:r.requireAuth,...n.approval!==void 0&&{approval:approvalOf(n.approval.responder,r)}};return r.run(()=>e.execute(t,i))}}function approvalOf(e,t){return{responder:{...e,getToken:(n,r)=>t.getResponderToken(e,n,r)}}}function buildApprovalResponseAuth(e){let t=createAuthorizationContext({scope:e.scope,boundResponder:e.responder});return{getToken:(n,r)=>t.getToken(n,namespaceApprovalAuthOptions(e.scope,r)),requireAuth:(n,r)=>t.requireAuth(n,namespaceApprovalAuthOptions(e.scope,r))}}function namespaceApprovalAuthOptions(e,t){return t?.authKey===void 0?t:{...t,authKey:`${e}:${t.authKey}`}}async function handleApprovalResponsePolicyError(e){return await handleAuthorizationError(e)}export{buildApprovalResponseAuth,createToolExecuteWithAuth,handleApprovalResponsePolicyError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.79.
|
|
1
|
+
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{message:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.79.2//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
-
import type { WorkflowAskRoute } from "#harness/
|
|
2
|
+
import type { WorkflowAskRoute } from "#harness/hitl/relays.js";
|
|
3
3
|
import type { InputResponse } from "#shared/input.js";
|
|
4
4
|
import type { ToolInputResponseResponder } from "#tools/definition.js";
|
|
5
5
|
export declare function toToolInputResponseResponder(auth: SessionAuthContext | null | undefined): ToolInputResponseResponder | undefined;
|
|
@@ -13,8 +13,12 @@ export type AppliedRunMessage = Extract<WorkflowToolRunMessage, {
|
|
|
13
13
|
/**
|
|
14
14
|
* Applies run messages in the order they arrived, in one step however many
|
|
15
15
|
* there are: a fan-out's starts, reports, and replies would otherwise cost a
|
|
16
|
-
* step each.
|
|
16
|
+
* step each. Set `canCancelTurn` while a turn runs: a hook's `ctx.cancel()`
|
|
17
|
+
* on a report then returns `cancelled` for the turn to stop.
|
|
17
18
|
*/
|
|
18
19
|
export declare function applyRunMessagesStep(input: SessionStepState & {
|
|
20
|
+
readonly canCancelTurn?: boolean;
|
|
19
21
|
readonly messages: readonly AppliedRunMessage[];
|
|
20
|
-
}): Promise<SessionStateTransition
|
|
22
|
+
}): Promise<SessionStateTransition & {
|
|
23
|
+
readonly cancelled: boolean;
|
|
24
|
+
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionPartialEvent,createAgentStartedEvent}from"#protocol/message.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{applyTaskRunMessage}from"#execution/tasks/steps.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";function workflowToolRunReportEvent(e,t){return createActionPartialEvent({result:createRuntimeToolResultFromValue({callId:e.callId,output:t,toolName:e.toolName}),sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId})}function agentStartedEvent(e,{from:t,session:n}){return createAgentStartedEvent({callId:t.callId,name:n.name,parentSessionId:e,remote:n.kind===`remote`?{url:n.url,...n.resolverId!==void 0&&{resolverId:n.resolverId}}:void 0,sessionId:n.sessionId,...t.taskId!==void 0&&{taskId:t.taskId},turnId:t.turnId})}async function applyRunMessagesStep(e){"use step";return await withSessionStateDelta(e,async({messages:
|
|
1
|
+
import{createActionPartialEvent,createAgentStartedEvent}from"#protocol/message.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{applyTaskRunMessage}from"#execution/tasks/steps.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";function workflowToolRunReportEvent(e,t){return createActionPartialEvent({result:createRuntimeToolResultFromValue({callId:e.callId,output:t,toolName:e.toolName}),sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId})}function agentStartedEvent(e,{from:t,session:n}){return createAgentStartedEvent({callId:t.callId,name:n.name,parentSessionId:e,remote:n.kind===`remote`?{url:n.url,...n.resolverId!==void 0&&{resolverId:n.resolverId}}:void 0,sessionId:n.sessionId,...t.taskId!==void 0&&{taskId:t.taskId},turnId:t.turnId})}async function applyRunMessagesStep(e){"use step";return await withSessionStateDelta(e,async({canCancelTurn:e,messages:t,...n})=>{let r=n,i=!1,a=[],publish=async()=>{if(a.length===0)return;let t=await publishSessionEvents(r,a,{canCancelTurn:e});r={...r,serializedContext:t.serializedContext,sessionState:t.sessionState},i||=t.cancelled,a=[]};for(let e of t)e.kind===`agent-started`?a.push(agentStartedEvent(r.sessionState.sessionId,e)):e.kind===`report`?a.push(workflowToolRunReportEvent(e.from,e.update)):(await publish(),r={...r,...await applyTaskRunMessage({...r,message:e})});return await publish(),{cancelled:i,serializedContext:r.serializedContext,sessionState:r.sessionState}})}export{applyRunMessagesStep};
|
|
@@ -6,7 +6,7 @@ import { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";
|
|
|
6
6
|
import type { WorkflowBodyCommand, WorkflowToolRunOutcome, WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
|
|
7
7
|
import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";
|
|
8
8
|
import type { WorkflowToolRunEntry } from "#shared/action-types.js";
|
|
9
|
-
import type
|
|
9
|
+
import { type JsonObject, type JsonValue } from "#shared/json.js";
|
|
10
10
|
import type { ToolContext } from "#tools/definition.js";
|
|
11
11
|
export interface WorkflowBodyDefinition {
|
|
12
12
|
/** Everything the run needs to open `ctx.agent` sessions for its caller, and `ctx.agents`. */
|
|
@@ -52,6 +52,15 @@ export interface StartedWorkflowBody {
|
|
|
52
52
|
}
|
|
53
53
|
/** Starts the body of an `execute` or `task` call, which serves the call the run started with. */
|
|
54
54
|
export declare function startCallBody(input: WorkflowBodyInput): StartedWorkflowBody;
|
|
55
|
+
/**
|
|
56
|
+
* An authored result as the run's JSON outcome, parsed the way a local tool's
|
|
57
|
+
* result is: undefined properties are omitted, a missing result is `null`,
|
|
58
|
+
* and a value JSON can't carry throws, failing the run.
|
|
59
|
+
*/
|
|
60
|
+
export declare function toWorkflowOutput(call: {
|
|
61
|
+
readonly callId: string;
|
|
62
|
+
readonly toolName: string;
|
|
63
|
+
}, output: unknown): JsonValue;
|
|
55
64
|
/** A body's failure, or its cancellation when the run stopped. */
|
|
56
65
|
export declare function toFailedOutcome(error: unknown, runSignal: AbortSignal): WorkflowToolRunOutcome;
|
|
57
66
|
export declare function createWorkflowBodyRef(input: WorkflowBodyDefinition & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callToolStubStep}from"#execution/tool-stubs/steps.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{findStubTarget,stubCallId}from"#tool-stubs/target.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{createRunUsageTally}from"#execution/agent-sessions/usage.js";import{toolStubOutput}from"#tool-stubs/output.js";import{createAgentSessions}from"#execution/agent-sessions/session.js";import{WorkflowToolRunAsks,ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{readRegisteredWorkflow}from"#execution/workflow-registry.js";const INTERRUPTED_OUTPUT={interrupted:!0};var WorkflowCallSignals=class{body=new AbortController;run=new AbortController;asks;constructor(e){this.asks=e}get abortSignal(){return this.body.signal}get runSignal(){return this.run.signal}get interrupted(){return this.body.signal.aborted&&!this.run.signal.aborted}get unwinding(){return this.run.signal.aborted}apply(e){switch(e.kind){case`cancel`:case`end`:this.asks.cancelAll(),this.run.abort(new WorkflowToolRunCancelledError(e.reason)),this.body.abort(this.run.signal.reason);return;case`interrupt`:this.body.abort(new WorkflowToolRunInterruptedError);return;case`call`:return}}};function startCallBody(e){let t=createWorkflowBodyRef(e),n=new WorkflowToolRunAsks(t.runId),r=new WorkflowCallSignals(n),i={agentContext:e.agentContext,asks:n,auth:e.session.auth,control:e.hookToken,from:t,owner:e.owner},a=createRunUsageTally(),o=createAgentSessions(i,a),s=createCallContext(e,r,o.open);return attachWorkflowToolRunContext(s,i),{asks:n,close:o.close,control:r,outcome:executeCallBody(e,s,r,t),usage:a}}async function executeCallBody(e,t,n,r){try{let n=findStubTarget(e.agentContext.toolStubs,e.toolName);if(n!==void 0){let t=await callToolStubStep(n.scope,{callId:stubCallId(e.session.id,e.session.turn.id,e.callId),tool:n.tool,input:e.input});if(t.kind===`error`)throw Error(t.error);if(t.kind===`stub`)return{output:toolStubOutput(t.outcome),status:`completed`}}let i=resolveWorkflowEntryPoint(e)(e.executeInput??e.input,t),a;if(!isAsyncIterable(i))a=await i;else{let t=i[Symbol.asyncIterator](),n,o=await t.next();for(;o.done!==!0;)n=o.value,await e.owner.send({from:r,kind:`report`,update:o.value}),o=await t.next();a=o.value??n
|
|
1
|
+
import{parseJsonValue}from"#shared/json.js";import{callToolStubStep}from"#execution/tool-stubs/steps.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{findStubTarget,stubCallId}from"#tool-stubs/target.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{createRunUsageTally}from"#execution/agent-sessions/usage.js";import{toolStubOutput}from"#tool-stubs/output.js";import{createAgentSessions}from"#execution/agent-sessions/session.js";import{WorkflowToolRunAsks,ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{readRegisteredWorkflow}from"#execution/workflow-registry.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";const INTERRUPTED_OUTPUT={interrupted:!0};var WorkflowCallSignals=class{body=new AbortController;run=new AbortController;asks;constructor(e){this.asks=e}get abortSignal(){return this.body.signal}get runSignal(){return this.run.signal}get interrupted(){return this.body.signal.aborted&&!this.run.signal.aborted}get unwinding(){return this.run.signal.aborted}apply(e){switch(e.kind){case`cancel`:case`end`:this.asks.cancelAll(),this.run.abort(new WorkflowToolRunCancelledError(e.reason)),this.body.abort(this.run.signal.reason);return;case`interrupt`:this.body.abort(new WorkflowToolRunInterruptedError);return;case`call`:return}}};function startCallBody(e){let t=createWorkflowBodyRef(e),n=new WorkflowToolRunAsks(t.runId),r=new WorkflowCallSignals(n),i={agentContext:e.agentContext,asks:n,auth:e.session.auth,control:e.hookToken,from:t,owner:e.owner},a=createRunUsageTally(),o=createAgentSessions(i,a),s=createCallContext(e,r,o.open);return attachWorkflowToolRunContext(s,i),{asks:n,close:o.close,control:r,outcome:executeCallBody(e,s,r,t),usage:a}}async function executeCallBody(e,t,n,r){try{let n=findStubTarget(e.agentContext.toolStubs,e.toolName);if(n!==void 0){let t=await callToolStubStep(n.scope,{callId:stubCallId(e.session.id,e.session.turn.id,e.callId),tool:n.tool,input:e.input});if(t.kind===`error`)throw Error(t.error);if(t.kind===`stub`)return{output:toolStubOutput(t.outcome),status:`completed`}}let i=resolveWorkflowEntryPoint(e)(e.executeInput??e.input,t),a;if(!isAsyncIterable(i))a=await i;else{let t=i[Symbol.asyncIterator](),n,o=await t.next();for(;o.done!==!0;)n=o.value,await e.owner.send({from:r,kind:`report`,update:o.value}),o=await t.next();a=o.value??n}return{output:toWorkflowOutput(e,a),status:`completed`}}catch(e){return n.interrupted?{output:INTERRUPTED_OUTPUT,status:`completed`}:toFailedOutcome(e,n.runSignal)}}function toWorkflowOutput(e,t){return withToolOutputSerializationError({boundary:`execute`,toolCallId:e.callId,toolName:e.toolName},()=>parseJsonValue(t??null))}function toFailedOutcome(e,t){if(t.aborted){let{reason:e}=t;return{reason:e instanceof Error?e.message:String(e??``),status:`cancelled`}}return{error:normalizeSerializableError(e),status:`failed`}}function createWorkflowBodyRef(e){let t={callId:e.callId,input:e.input,runId:e.runId??getWorkflowMetadata().workflowRunId,sequence:e.session.turn.sequence,stepIndex:e.stepIndex,toolName:e.toolName,turnId:e.session.turn.id};return e.entry.entryPoint===`execute`?t:{...t,taskId:e.entry.taskId}}function resolveWorkflowEntryPoint(e){let t=readRegisteredWorkflow(e.workflowId);if(typeof t!=`function`)throw Error(`Tool "${e.toolName}" is not registered as a workflow in this deployment (${e.workflowId}). The tool was renamed or removed after this run started.`);return t}function createSharedContext(e,t,n){let unavailable=(t,n)=>{throw Error(`ctx.${t} is not available inside a workflow tool; ${n}. Tool "${e.toolName}" runs as a durable workflow body, which only replays deterministic code.`)};return{agent:t,ask:n,getSandbox:()=>unavailable(`getSandbox()`,`the session sandbox belongs to the turn`),getToken:()=>unavailable(`getToken()`,`pass ctx directly to a "use step" helper to resolve credentials`),requireAuth:()=>unavailable(`requireAuth()`,`pass ctx directly to a "use step" helper to request authorization`),toolName:e.toolName}}function createAgentsView(e){return Object.freeze(Object.fromEntries(Object.entries(e.agents).map(([e,t])=>[e,Object.freeze({...t})])))}function createCallContext(e,t,n){let r={...createSharedContext(e,n,(e,t)=>ask(r,e,t)),abortSignal:t.abortSignal,agents:createAgentsView(e.agentContext),callId:e.callId,session:e.session};return r}function isAsyncIterable(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var WorkflowToolRunCancelledError=class extends Error{constructor(e){super(e),this.name=`WorkflowToolRunCancelledError`}},WorkflowToolRunInterruptedError=class extends Error{constructor(){super(`A new message arrived while the turn waited on this call.`),this.name=`WorkflowToolRunInterruptedError`}};export{WorkflowToolRunCancelledError,WorkflowToolRunInterruptedError,createAgentsView,createSharedContext,createWorkflowBodyRef,resolveWorkflowEntryPoint,startCallBody,toFailedOutcome,toWorkflowOutput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseJsonValue}from"#shared/json.js";function workflowToolRunOutcomeToToolResult(e){let{from:t,result:n}=e;return n.status===`completed`?{callId:t.callId,kind:`tool-result`,output:n.output,toolName:t.toolName}:{callId:t.callId,isError:!0,kind:`tool-result`,output:
|
|
1
|
+
import{parseJsonValue}from"#shared/json.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";function workflowToolRunOutcomeToToolResult(e){let{from:t,result:n}=e;return n.status===`completed`?{callId:t.callId,kind:`tool-result`,output:n.output,toolName:t.toolName}:n.status===`failed`?{callId:t.callId,errorName:rebuildSerializableError(n.error).name,isError:!0,kind:`tool-result`,output:workflowToolRunFailureOutput(e),toolName:t.toolName}:{callId:t.callId,isError:!0,kind:`tool-result`,output:n.reason??`The workflow tool run was cancelled.`,toolName:t.toolName}}function workflowToolRunFailureOutput(e){if(e.result.status!==`failed`)throw TypeError(`Expected a failed workflow outcome.`);let t=parseJsonValueOrUndefined(e.result.error);return t!==void 0&&typeof t==`object`&&t&&!Array.isArray(t)&&typeof Reflect.get(t,`code`)==`string`?t:errorMessage(e.result.error)}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 parseJsonValueOrUndefined(e){try{return parseJsonValue(e)}catch{return}}function workflowToolRunRequestToInputRequestPayload(e){let{from:t,replyTo:n,requestCoordinates:r}=e;return{callId:t.callId,childContinuationToken:n,childSessionId:t.runId,childSessionInbox:e.childSessionInbox,remote:e.remote,inputSource:e.inputSource,event:{requests:workflowToolRunInputRequests(e),sequence:r?.sequence??t.sequence,stepIndex:r?.stepIndex??t.stepIndex,taskId:t.taskId,turnId:r?.turnId??t.turnId},kind:`subagent-input-request`,subagentName:t.toolName}}function workflowToolRunInputRequests(e){return e.request.kind===`input-batch`?e.request.requests:[normalizeInputRequest(e.request,e.from,e.replyTo)]}function normalizeInputRequest(e,t,n){switch(e.kind){case`authorization-request`:throw TypeError(`A workflow authorization event cannot be normalized as human input.`);case`ask`:return normalizeAskRequest(e.request,t,n);default:return e}}function normalizeAskRequest(e,t,n){if(typeof e.prompt!=`string`||e.prompt.length===0)throw TypeError("A workflow 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}export{workflowToolRunFailureOutput,workflowToolRunInputRequests,workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callToolStubStep}from"#execution/tool-stubs/steps.js";import{findStubTarget,stubCallId}from"#tool-stubs/target.js";import{createRunUsageTally}from"#execution/agent-sessions/usage.js";import{toolStubOutput}from"#tool-stubs/output.js";import{createAgentSessions}from"#execution/agent-sessions/session.js";import{WorkflowToolRunAsks,ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{WorkflowToolRunCancelledError,createAgentsView,createSharedContext,createWorkflowBodyRef,resolveWorkflowEntryPoint,toFailedOutcome}from"#execution/tools/workflow/body.js";var WorkflowServeCalls=class{asks;run=new AbortController;first;runRef;runSession;owner;usage=createRunUsageTally(()=>this.sendUncarriedUsage());carriedUsage;toolName;seenCallIds;firstReceived=!1;arrived=[];waiting;latest;pendingReceive;stretch;unwindingCancel=!1;endedBy;replies=Promise.resolve();constructor(e){this.runRef=createWorkflowBodyRef(e),this.asks=new WorkflowToolRunAsks(this.runRef.runId),this.runSession=e.session,this.owner=e.owner,this.toolName=e.toolName,this.seenCallIds=new Set([e.callId]),this.first=this.serve({agentContext:e.agentContext,auth:e.session.auth,callId:this.runRef.callId,executeInput:e.executeInput,input:this.runRef.input,sequence:this.runRef.sequence,stepIndex:this.runRef.stepIndex,turnId:this.runRef.turnId}),this.waiting=[this.first],this.latest=this.first}get runSignal(){return this.run.signal}get unwinding(){return this.run.signal.aborted||this.unwindingCancel}get currentSignal(){return this.stretch?.signal??this.run.signal}get current(){return this.latest}apply(e){switch(e.kind){case`call`:this.accept(e.call);return;case`cancel`:this.cancel(new WorkflowToolRunCancelledError(e.reason));return;case`end`:this.end(new WorkflowToolRunCancelledError(e.reason));return;case`interrupt`:return}}receive(){if(!this.firstReceived)return this.firstReceived=!0,Promise.resolve(this.first.call);if(this.unwindingCancel=!1,this.pendingReceive!==void 0)return this.pendingReceive.promise;if(this.endedBy!==void 0)return Promise.reject(this.endedBy);let e=this.arrived.shift();return e===void 0?(this.pendingReceive=createPendingReceive(),this.pendingReceive.promise):(this.take(e),Promise.resolve(e.call))}reply(e){let t=this.waiting;if(t.length===0)return;this.waiting=[],this.arrived.length===0&&(this.stretch=void 0),this.asks.withdrawAll();let n=this.replies;this.replies=n.then(()=>this.deliverReply(t,e))}assertWaiting(){if(!(this.waiting.length>0))throw Error(`ctx.ask() needs a call waiting for a result, but tool "${this.toolName}" already replied to every call it received.`)}async flush(){await this.asks.flush(),await this.replies}sendUncarriedUsage(){if(this.waiting.length>0||this.endedBy!==void 0)return;let{from:e}=this.latest;this.replies=this.replies.then(async()=>{let t=this.usage.total();t===void 0||isSameUsage(t,this.carriedUsage)||(this.carriedUsage=t,await this.owner.send({from:e,kind:`usage`,usage:t}))})}accept(e){if(this.endedBy!==void 0||this.seenCallIds.has(e.callId))return;this.seenCallIds.add(e.callId);let t=this.serve(e),n=this.pendingReceive;if(n===void 0){this.arrived.push(t);return}this.pendingReceive=void 0,this.take(t),n.resolve(t.call)}take(e){this.waiting.push(e),this.latest=e}cancel(e){this.pendingReceive===void 0&&(this.unwindingCancel=!0),this.stretch?.abort(e),this.stretch=void 0,this.waiting=[],this.arrived=[]}end(e){this.asks.cancelAll(),this.endedBy=e,this.run.abort(e),this.stretch?.abort(e);let t=this.pendingReceive;this.pendingReceive=void 0,t?.reject(e)}serve(e){return this.stretch??=new AbortController,{agentContext:e.agentContext,agents:createAgentsView(e.agentContext),call:{abortSignal:this.stretch.signal,callId:e.callId,input:e.executeInput??e.input},from:{...this.runRef,callId:e.callId,input:e.input,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},session:{...this.runSession,auth:e.auth,turn:{id:e.turnId,sequence:e.sequence}}}}async deliverReply(e,t){let n=e.at(-1);if(n===void 0)return;let r=e.map(e=>e.from.callId),i=this.usage.total();this.carriedUsage=i,await this.owner.send({callIds:r,from:n.from,kind:`reply`,output:t,...i!==void 0&&{usage:i}})}};function isSameUsage(e,t){return t!==void 0&&e.inputTokens===t.inputTokens&&e.outputTokens===t.outputTokens&&e.cacheReadTokens===t.cacheReadTokens&&e.cacheWriteTokens===t.cacheWriteTokens&&e.costUsd===t.costUsd}function startServeBody(e){let t=new WorkflowServeCalls(e),n={get agentContext(){return t.current.agentContext},asks:t.asks,get auth(){return t.current.session.auth},control:e.hookToken,get from(){return t.current.from},owner:e.owner},r=createAgentSessions(n,t.usage),i=createServeContext(e,t,r.open);return attachWorkflowToolRunContext(i,n),{asks:t.asks,close:r.close,control:t,outcome:executeServeBody(e,t,i),usage:t.usage}}async function executeServeBody(e,t,n){let r;try{let i=findStubTarget(e.agentContext.toolStubs,e.toolName),receive=()=>t.receive()
|
|
1
|
+
import{callToolStubStep}from"#execution/tool-stubs/steps.js";import{findStubTarget,stubCallId}from"#tool-stubs/target.js";import{createRunUsageTally}from"#execution/agent-sessions/usage.js";import{toolStubOutput}from"#tool-stubs/output.js";import{createAgentSessions}from"#execution/agent-sessions/session.js";import{WorkflowToolRunAsks,ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{WorkflowToolRunCancelledError,createAgentsView,createSharedContext,createWorkflowBodyRef,resolveWorkflowEntryPoint,toFailedOutcome,toWorkflowOutput}from"#execution/tools/workflow/body.js";var WorkflowServeCalls=class{asks;run=new AbortController;first;runRef;runSession;owner;usage=createRunUsageTally(()=>this.sendUncarriedUsage());carriedUsage;toolName;seenCallIds;firstReceived=!1;arrived=[];waiting;latest;pendingReceive;stretch;unwindingCancel=!1;endedBy;replies=Promise.resolve();constructor(e){this.runRef=createWorkflowBodyRef(e),this.asks=new WorkflowToolRunAsks(this.runRef.runId),this.runSession=e.session,this.owner=e.owner,this.toolName=e.toolName,this.seenCallIds=new Set([e.callId]),this.first=this.serve({agentContext:e.agentContext,auth:e.session.auth,callId:this.runRef.callId,executeInput:e.executeInput,input:this.runRef.input,sequence:this.runRef.sequence,stepIndex:this.runRef.stepIndex,turnId:this.runRef.turnId}),this.waiting=[this.first],this.latest=this.first}get runSignal(){return this.run.signal}get unwinding(){return this.run.signal.aborted||this.unwindingCancel}get currentSignal(){return this.stretch?.signal??this.run.signal}get current(){return this.latest}apply(e){switch(e.kind){case`call`:this.accept(e.call);return;case`cancel`:this.cancel(new WorkflowToolRunCancelledError(e.reason));return;case`end`:this.end(new WorkflowToolRunCancelledError(e.reason));return;case`interrupt`:return}}receive(){if(!this.firstReceived)return this.firstReceived=!0,Promise.resolve(this.first.call);if(this.unwindingCancel=!1,this.pendingReceive!==void 0)return this.pendingReceive.promise;if(this.endedBy!==void 0)return Promise.reject(this.endedBy);let e=this.arrived.shift();return e===void 0?(this.pendingReceive=createPendingReceive(),this.pendingReceive.promise):(this.take(e),Promise.resolve(e.call))}reply(e){let t=this.waiting;if(t.length===0)return;this.waiting=[],this.arrived.length===0&&(this.stretch=void 0),this.asks.withdrawAll();let n=this.replies;this.replies=n.then(()=>this.deliverReply(t,e))}assertWaiting(){if(!(this.waiting.length>0))throw Error(`ctx.ask() needs a call waiting for a result, but tool "${this.toolName}" already replied to every call it received.`)}async flush(){await this.asks.flush(),await this.replies}sendUncarriedUsage(){if(this.waiting.length>0||this.endedBy!==void 0)return;let{from:e}=this.latest;this.replies=this.replies.then(async()=>{let t=this.usage.total();t===void 0||isSameUsage(t,this.carriedUsage)||(this.carriedUsage=t,await this.owner.send({from:e,kind:`usage`,usage:t}))})}accept(e){if(this.endedBy!==void 0||this.seenCallIds.has(e.callId))return;this.seenCallIds.add(e.callId);let t=this.serve(e),n=this.pendingReceive;if(n===void 0){this.arrived.push(t);return}this.pendingReceive=void 0,this.take(t),n.resolve(t.call)}take(e){this.waiting.push(e),this.latest=e}cancel(e){this.pendingReceive===void 0&&(this.unwindingCancel=!0),this.stretch?.abort(e),this.stretch=void 0,this.waiting=[],this.arrived=[]}end(e){this.asks.cancelAll(),this.endedBy=e,this.run.abort(e),this.stretch?.abort(e);let t=this.pendingReceive;this.pendingReceive=void 0,t?.reject(e)}serve(e){return this.stretch??=new AbortController,{agentContext:e.agentContext,agents:createAgentsView(e.agentContext),call:{abortSignal:this.stretch.signal,callId:e.callId,input:e.executeInput??e.input},from:{...this.runRef,callId:e.callId,input:e.input,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},session:{...this.runSession,auth:e.auth,turn:{id:e.turnId,sequence:e.sequence}}}}async deliverReply(e,t){let n=e.at(-1);if(n===void 0)return;let r=e.map(e=>e.from.callId),i=this.usage.total();this.carriedUsage=i,await this.owner.send({callIds:r,from:n.from,kind:`reply`,output:t,...i!==void 0&&{usage:i}})}};function isSameUsage(e,t){return t!==void 0&&e.inputTokens===t.inputTokens&&e.outputTokens===t.outputTokens&&e.cacheReadTokens===t.cacheReadTokens&&e.cacheWriteTokens===t.cacheWriteTokens&&e.costUsd===t.costUsd}function startServeBody(e){let t=new WorkflowServeCalls(e),n={get agentContext(){return t.current.agentContext},asks:t.asks,get auth(){return t.current.session.auth},control:e.hookToken,get from(){return t.current.from},owner:e.owner},r=createAgentSessions(n,t.usage),i=createServeContext(e,t,r.open);return attachWorkflowToolRunContext(i,n),{asks:t.asks,close:r.close,control:t,outcome:executeServeBody(e,t,i),usage:t.usage}}async function executeServeBody(e,t,n){let r;try{let i=findStubTarget(e.agentContext.toolStubs,e.toolName),receive=()=>t.receive(),a=i===void 0?await resolveWorkflowEntryPoint(e)(receive,n):await serveStub(i.scope,i.tool,receive,n);r={output:toWorkflowOutput(e,a),status:`completed`}}catch(e){r=toFailedOutcome(e,t.runSignal)}return await t.flush(),r}function createServeContext(e,t,n){let r={...createSharedContext(e,n,(e,n)=>(t.assertWaiting(),ask(r,e,n))),get abortSignal(){return t.currentSignal},get agents(){return t.current.agents},get callId(){return t.current.from.callId},get session(){return t.current.session},reply:n=>t.reply(toWorkflowOutput({callId:r.callId,toolName:e.toolName},n))};return r}function createPendingReceive(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),reject:t,resolve:e}}async function serveStub(e,t,n,r){for(;;){let i=await n();if(i.abortSignal.aborted)continue;let a=await callToolStubStep(e,{callId:stubCallId(r.session.id,r.session.turn.id,i.callId),input:i.input,tool:t,persistent:!0});if(a.kind!==`stub`)throw Error(a.kind===`error`?a.error:`Persistent stub configuration changed.`);r.reply(toolStubOutput(a.outcome))}}export{startServeBody};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { PublishedSessionEvents, SessionStepState } from "#execution/publish-session-events.js";
|
|
2
2
|
import { type SessionStateTransition } from "#execution/session/state-delta.js";
|
|
3
|
-
import {
|
|
3
|
+
import type { ProxyInputRequest } from "#harness/hitl/relays.js";
|
|
4
4
|
/**
|
|
5
5
|
* Decides a run's request to withdraw a question. A question the session
|
|
6
6
|
* still offers is withdrawn, so channels stop offering it. One it no longer
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resumeHook}from"#internal/workflow/runtime.js";import{readDurableSession}from"#execution/durable-session-store.js";import{readHitlState}from"#harness/hitl/index.js";import{commitSessionStep}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{finishRun}from"#harness/session-machine/transitions.js";import{ignoreGoneTarget}from"#execution/tasks/workflow-target.js";async function withdrawWorkflowToolRunQuestionStep(e){"use step";return await withSessionStateDelta(e,withdrawWorkflowToolRunQuestion)}async function withdrawWorkflowToolRunQuestion(e){let t={kind:`withdrawn`,requestId:e.requestId};return await ignoreGoneTarget(resumeHook(e.control,t)),await relayWithdrawnRequests(e,(t,n)=>t===e.requestId&&n.workflowAsk!==void 0&&n.runId===e.runId)}async function withdrawFinishedRunQuestionsStep(e){"use step";return await withSessionStateDelta(e,e=>relayWithdrawnRequests(e,(t,n)=>n.runId===e.runId))}async function relayWithdrawnRequests(e,t){let{state:n}=readDurableSession(e.sessionState),r=[...readHitlState(n).relays].filter(([e,n])=>t(e,n)).map(([e])=>e);return await commitSessionStep(e,e=>[finishRun(e,{requestIds:r})],{origin:`relayed`})}export{relayWithdrawnRequests,withdrawFinishedRunQuestionsStep,withdrawWorkflowToolRunQuestionStep};
|
|
@@ -21,10 +21,19 @@ export declare function resolveVercelProductionCallbackBaseUrl(): string | null;
|
|
|
21
21
|
*/
|
|
22
22
|
export declare function resolveWorkflowCallbackBaseUrl(metadataUrl: string): string;
|
|
23
23
|
/**
|
|
24
|
-
* Builds a framework-owned callback URL
|
|
24
|
+
* Builds a framework-owned callback URL that a browser or third party sees,
|
|
25
|
+
* such as the connection sign-in redirect handed to an IdP.
|
|
25
26
|
*
|
|
26
27
|
* `callbackPath` is appended to the full base URL rather than resolved
|
|
27
28
|
* against it: the base may carry a public route prefix path, which
|
|
28
29
|
* `new URL(path, base)` would drop for absolute paths.
|
|
29
30
|
*/
|
|
31
|
+
export declare function createBrowserCallbackUrl(baseUrl: string, callbackPath: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* Builds a framework-owned callback URL for server-to-server delivery.
|
|
34
|
+
*
|
|
35
|
+
* Unlike {@link createBrowserCallbackUrl}, it carries the deployment's
|
|
36
|
+
* Protection Bypass for Automation secret so the caller can reach a
|
|
37
|
+
* protected deployment.
|
|
38
|
+
*/
|
|
30
39
|
export declare function createWorkflowCallbackUrl(baseUrl: string, callbackPath: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{joinEveRoutePath}from"#shared/eve-route-path.js";import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function resolveWorkflowCallbackBaseUrl(e){let t=process.env.WORKFLOW_LOCAL_BASE_URL?.trim()||void 0,n=(resolveVercelProductionCallbackBaseUrl()??t??e).replace(/\/$/,``),r=normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]);return r===void 0?n:`${n}${r}`}function
|
|
1
|
+
import{joinEveRoutePath}from"#shared/eve-route-path.js";import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function resolveWorkflowCallbackBaseUrl(e){let t=process.env.WORKFLOW_LOCAL_BASE_URL?.trim()||void 0,n=(resolveVercelProductionCallbackBaseUrl()??t??e).replace(/\/$/,``),r=normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]);return r===void 0?n:`${n}${r}`}function createBrowserCallbackUrl(e,t){let n=new URL(t,`http://eve.local`),r=new URL(e);return r.pathname=joinEveRoutePath(r.pathname,n.pathname),r.search=n.search,r.toString()}function createWorkflowCallbackUrl(e,t){let n=new URL(createBrowserCallbackUrl(e,t)),r=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return r&&n.searchParams.set(`x-vercel-protection-bypass`,r),n.toString()}export{createBrowserCallbackUrl,createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl,resolveWorkflowCallbackBaseUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{skillTarget}from"#shared/action-request-name.js";import{toError}from"#shared/errors.js";import{SKILL_ENTRY_NAME}from"#protocol/catalog-tools.js";import{parseJsonValue}from"#shared/json.js";import{authorizationPendingAsJsonObject,isAuthorizationPendingModelOutput,isAuthorizationSignal}from"#harness/authorization.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";function toJsonValue(e){return isAuthorizationSignal(e)?parseJsonValue(authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})):isAuthorizationPendingModelOutput(e)?parseJsonValue(authorizationPendingAsJsonObject(e)):parseJsonValue(e===void 0?null:e)}function createRuntimeToolResultFromValue(e){let t={callId:e.callId,kind:`tool-result`,output:toolResultOutputToJsonValue({output:{type:e.isError===!0?`error-json`:`json`,value:
|
|
1
|
+
import{skillTarget}from"#shared/action-request-name.js";import{toError}from"#shared/errors.js";import{SKILL_ENTRY_NAME}from"#protocol/catalog-tools.js";import{parseJsonValue}from"#shared/json.js";import{authorizationPendingAsJsonObject,isAuthorizationPendingModelOutput,isAuthorizationSignal}from"#harness/authorization.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";function toJsonValue(e){return isAuthorizationSignal(e)?parseJsonValue(authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})):isAuthorizationPendingModelOutput(e)?parseJsonValue(authorizationPendingAsJsonObject(e)):parseJsonValue(e===void 0?null:e)}function createRuntimeToolResultFromValue(e){let t=e.isError===!0&&e.output instanceof Error?e.output:void 0,n={callId:e.callId,kind:`tool-result`,output:toolResultOutputToJsonValue({output:{type:e.isError===!0?`error-json`:`json`,value:t===void 0?e.output:t.message},toolCallId:e.callId,toolName:e.toolName}),toolName:e.toolName};return e.isError===!0?t===void 0?{...n,isError:!0}:{...n,errorName:t.name,isError:!0}:n}function createRuntimeToolResultFromStepResult(e){return createRuntimeToolResultFromValue({callId:e.toolCallId,output:e.output,toolName:e.toolName})}function createRuntimeToolResultFromToolError(e){return createRuntimeToolResultFromValue({callId:e.toolCallId,isError:!0,output:toError(e.error),toolName:e.toolName})}function toActionResult(e,t){let n=e.toolName===SKILL_ENTRY_NAME?skillTarget(t):void 0;return n===void 0?e:{callId:e.callId,isError:e.isError,kind:`load-skill-result`,name:n,output:e.output}}function createToolResultMessagePartFromToolError(e){return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:{type:`error-text`,value:toError(e.error).message}}}function createRuntimeToolResultFromMessagePart(e,t){return createRuntimeToolResultFromValue({callId:e.toolCallId,output:toolResultOutputToJsonValue({output:e.output,toolCallId:e.toolCallId,toolName:t}),toolName:t,isError:isToolResultError(e.output)})}function toolResultOutputToJsonValue(e){return withToolOutputSerializationError({boundary:`action.result`,toolCallId:e.toolCallId,toolName:e.toolName},()=>{switch(e.output.type){case`text`:case`error-text`:return e.output.value;case`json`:case`error-json`:return toJsonValue(e.output.value);case`execution-denied`:return{code:`TOOL_EXECUTION_DENIED`,message:e.output.reason??`Tool execution was denied.`};case`content`:return toJsonValue(e.output.value)}})}function isToolResultError(e){return e.type===`error-json`||e.type===`error-text`||e.type===`execution-denied`}export{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createRuntimeToolResultFromValue,createToolResultMessagePartFromToolError,isToolResultError,toActionResult};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{contextStorage,loadContext}from"#context/container.js";import{SandboxKey}from"#context/keys.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{basename,dirname,extname}from"node:path";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createFrameworkUserMessage}from"#harness/messages.js";import{DEFAULT_UPLOAD_POLICY,isMediaTypeAllowed}from"#public/channels/upload-policy.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{readMediaMetadata,verifyMediaType}from"#internal/attachments/media-metadata.js";import{decodeSandboxRef,encodeSandboxRef,inlinesSandboxRefAsBytes,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";import{isUnresolvedFileData,readFileData}from"#internal/attachments/data.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{createPublicDownloads}from"#internal/attachments/public-link.js";const ATTACHMENTS_ROOT=`/workspace/.eve/attachments`,log=createLogger(`harness.attachment-staging`),UNSAFE_FILENAME_CHARS=/[^\w.-]+/g,MEDIA_TYPE_EXTENSIONS={"application/pdf":`.pdf`,"image/gif":`.gif`,"image/jpeg":`.jpg`,"image/png":`.png`,"image/webp":`.webp`};async function stageAttachmentsForAdapter(e,t,n){if(typeof e==`string`)return e;let r=reconstitueFilePartUrls(e),i=n.ctx.get(ChannelKey)?.uploadPolicy,a=createPublicDownloads(maxBytesOf(i??DEFAULT_UPLOAD_POLICY));return Promise.all(r.map(async e=>e.type===`file`?stageFilePart(e,t,n,a,i):e))}async function stageAttachmentsToSandbox(e){if(typeof e==`string`||!Array.isArray(e)||!hasFileParts(e))return e;let t=loadContext(),n=await t.get(SandboxKey)?.get()??null;if(n===null)return e.map(e=>e.type===`file`&&!isSandboxRefUrl(e.data)&&readFileData(e.data).kind!==`reference`?attachmentNote(e,`could not be stored: no sandbox is available.`):e);let r=t.get(ChannelKey);return stageAttachmentsForAdapter(e,n,r?buildAdapterContext(r,t):{ctx:t,state:{},session:buildSessionHandle(t)})}async function stageToolResultMedia(e){if(!e.some(hasInlineToolResultFile))return[...e];let t=await contextStorage.getStore()?.get(SandboxKey)?.get()??null;return Promise.all(e.map(async e=>{if(e.role!==`tool`||!hasInlineToolResultFile(e))return e;let n=await Promise.all(e.content.map(async e=>e.type===`tool-result`?{...e,output:await stageToolOutputFiles(e.output,t)}:e));return{...e,content:n}}))}async function hydrateSandboxAttachments(e){let t=replaceUnresolvedFileParts(e);if(!messagesContainSandboxRef(t))return t;let n=loadContext().get(SandboxKey);if(n===void 0)throw Error(`Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. Hydration must run inside a step scope with the framework sandbox provider installed.`);let r=await n.get();if(r===null)throw Error(`Cannot hydrate sandbox-ref FilePart: SandboxKey is bound but no active sandbox session is available.`);return Promise.all(t.map(async e=>{if(!messageContainsSandboxRef(e))return e;let t=await hydrateMessageContent(e.content,r);return{...e,content:t}}))}function replaceUnresolvedFileParts(e){let t=!1,n=e.map(e=>{if(e.role!==`user`||!Array.isArray(e.content)||!e.content.some(isUnresolvedFilePart))return e;t=!0;let n=e.content.map(e=>isUnresolvedFilePart(e)?attachmentNote(e,`could not be retrieved.`):e);return{...e,content:n}});return t?n:e}function isUnresolvedFilePart(e){return e.type===`file`&&!isSandboxRefUrl(e.data)&&isUnresolvedFileData(e.data)}function hasFileParts(e){for(let t of e)if(t.type===`file`)return!0;return!1}function messagesContainSandboxRef(e){for(let t of e)if(messageContainsSandboxRef(t))return!0;return!1}function messageContainsSandboxRef(e){let t=e.content;if(!Array.isArray(t))return!1;for(let e of t)if(isSandboxRefFilePart(e)||e.type===`tool-result`&&contentOutputParts(e.output).some(isToolOutputRefFile))return!0;return!1}function contentOutputParts(e){return e.type===`content`?e.value:[]}function hasInlineToolResultFile(e){return e.role===`tool`&&e.content.some(e=>e.type===`tool-result`&&contentOutputParts(e.output).some(isInlineToolOutputFile))}function isInlineToolOutputFile(e){return e.type===`file`&&e.data.type===`data`}function isToolOutputRefFile(e){return e.type===`file`&&e.data.type===`url`&&isSandboxRefUrl(e.data.url)}async function stageToolOutputFiles(e,t){if(e.type!==`content`||!e.value.some(isInlineToolOutputFile))return e;let n=await Promise.all(e.value.map(async e=>{if(!isInlineToolOutputFile(e)||e.data.type!==`data`)return e;let n=readFileData(e.data.data);if(n.kind===`link`)return e;if(t===null||n.kind!==`bytes`)return{text:`Returned file ${e.filename??`file`} (${e.mediaType}) could not be stored.`,type:`text`};let r=await writeSandboxRef(n.bytes,e.mediaType,e.filename,t);return{...e,data:{type:`url`,url:encodeSandboxRef(r)},mediaType:r.mediaType}}));return{...e,value:n}}function isSandboxRefFilePart(e){return typeof e==`object`&&!!e&&e.type===`file`&&isSandboxRefUrl(e.data)}async function hydrateMessageContent(e,t){return Array.isArray(e)?(await Promise.all(e.map(async e=>{if(isSandboxRefFilePart(e)){let n=decodeSandboxRef(e.data),r=renderSandboxRefAsTextPart(n);if(!inlinesSandboxRefAsBytes(n))return[r];let i=await readSandboxRefBytes(n,t);return i===null?[renderMissingSandboxRef(n)]:[r,{...e,data:i,mediaType:n.mediaType}]}if(e.type===`tool-result`){let n=e;return[{...n,output:await hydrateToolOutput(n.output,t)}]}return[e]}))).flat():e}async function hydrateToolOutput(e,t){if(e.type!==`content`||!e.value.some(isToolOutputRefFile))return e;let n=await Promise.all(e.value.map(async e=>{if(!isToolOutputRefFile(e)||e.data.type!==`url`)return[e];let n=decodeSandboxRef(e.data.url),r=renderSandboxRefAsTextPart(n);if(!inlinesSandboxRefAsBytes(n))return[r];let i=await readSandboxRefBytes(n,t);return i===null?[renderMissingSandboxRef(n)]:[r,{...e,data:{data:Buffer.from(i).toString(`base64`),type:`data`}}]}));return{...e,value:n.flat()}}async function readSandboxRefBytes(e,t){let n=await t.readBinaryFile({path:e.path});return n===null?(log.warn(`sandbox-ref attachment bytes missing on hydration — degrading to text reference`,{mediaType:e.mediaType,path:e.path,size:e.size}),null):n.byteLength!==e.size||sha256Prefix(n)!==basename(dirname(e.path))?(log.warn(`sandbox-ref attachment bytes changed since staging — degrading to text reference`,{mediaType:e.mediaType,path:e.path,size:e.size}),null):n}function renderMissingSandboxRef(e){return{text:`FileNotFound: Current snapshot may be newer and does not contain ${e.path}.`,type:`text`}}function moveToolResultFilesToUserMessages(e){let t=[],n=[];for(let r of e){if(r.role!==`tool`&&n.length>0&&(t.push(createReturnedFilesMessage(n)),n=[]),r.role!==`tool`){t.push(r);continue}let e=r.content.map(e=>{if(e.type!==`tool-result`||e.output.type!==`content`)return e;let t=e.output.value.map(e=>{if(e.type!==`file`)return e;let t={data:e.data,mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),n.push(t),{text:`Attached file ${e.filename??`file`} (${e.mediaType}) follows this tool result.`,type:`text`}});return{...e,output:{...e.output,value:t}}});t.push({...r,content:e})}return n.length>0&&t.push(createReturnedFilesMessage(n)),t}function createReturnedFilesMessage(e){return createFrameworkUserMessage(`context.state`,[{text:`Files returned by the preceding tool results:`,type:`text`},...e])}function renderSandboxRefAsTextPart(e){return{text:`Attached file ${e.path} (${e.mediaType})`,type:`text`}}async function stageFilePart(e,t,n,r,i){if(isSandboxRefUrl(e.data))return e;let a=readFileData(e.data);if(a.kind===`bytes`)return stageResolvedBytes(e,{bytes:a.bytes},t,i);if(a.kind===`reference`)return e;if(a.kind===`unreadable`)return log.warn(`attachment data is not bytes, base64, or a URL — degrading to text part`,{filename:e.filename,mediaType:e.mediaType}),attachmentNote(e,`could not be read.`);let o;try{o=await resolveLink(a.url,n,r)}catch(t){if(!(t instanceof EveAttachmentError))throw t;return log.warn(`attachment resolver failed — degrading to text part`,{adapterKind:t.adapterKind,error:t.cause,filename:e.filename,kind:t.kind}),attachmentNote(e,`could not be retrieved: ${t.message}`)}return stageResolvedBytes(e,o,t,i)}function attachmentNote(e,t){return{text:`Attachment ${e.filename?.trim()||`file`} ${t}`,type:`text`}}async function stageResolvedBytes(e,t,n,r){let i=verifyMediaType(t.bytes,t.mediaType??e.mediaType??`application/octet-stream`);if(r!==void 0){let n=maxBytesOf(r);if(t.bytes.byteLength>n)return attachmentNote(e,`was not accepted: it is ${t.bytes.byteLength} bytes, over this channel's ${n}-byte upload limit.`);if(!isMediaTypeAllowed(i,r))return attachmentNote(e,`was not accepted: this channel doesn't accept ${i} files.`)}let a=await writeSandboxRef(t.bytes,i,t.filename??e.filename,n);return{...e,data:encodeSandboxRef(a),filename:a.path,mediaType:a.mediaType}}async function writeSandboxRef(e,t,n,r){let i=verifyMediaType(e,t),a=sha256Prefix(e),o=`${ATTACHMENTS_ROOT}/${a}/${safeFilename(n,a,i)}`;return await r.writeBinaryFile({content:e,path:o}),{...readMediaMetadata(e,i),path:r.resolvePath(o)}}async function resolveLink(e,t,n){let r=t.ctx.get(ChannelKey),i=r===void 0?`none`:getAdapterKind(r);if(r?.fetchFile!==void 0){let n;try{n=await r.fetchFile(e.href,t)}catch(e){throw e instanceof EveAttachmentError?new EveAttachmentError({adapterKind:i,cause:e.cause,kind:e.kind,message:e.message}):new EveAttachmentError({adapterKind:i,cause:e,kind:`resolver-threw`,message:`Attachment retrieval failed in the "${i}" channel.`})}if(n!==null)return Buffer.isBuffer(n)?{bytes:n}:n}return n(e,i)}function reconstitueFilePartUrls(e){let t=!1,n=e.map(e=>e.type===`file`&&isSerializedUrlFilePart(e.data)?(t=!0,{...e,data:deserializeUrlFilePart(e.data)}):e);return t?n:e}function sha256Prefix(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,16)}function safeFilename(e,t,n){let r=e===void 0?``:basename(e).replace(UNSAFE_FILENAME_CHARS,`_`),i=r.length>0?r:`file-${t}`,a=MEDIA_TYPE_EXTENSIONS[n];return a===void 0||extname(i)!==``?i:`${i}${a}`}export{ATTACHMENTS_ROOT,hydrateSandboxAttachments,moveToolResultFilesToUserMessages,stageAttachmentsForAdapter,stageAttachmentsToSandbox,stageToolResultMedia};
|
|
1
|
+
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{contextStorage,loadContext}from"#context/container.js";import{SandboxKey}from"#context/keys.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{basename,dirname,extname}from"node:path";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createFrameworkUserMessage}from"#harness/messages.js";import{DEFAULT_UPLOAD_POLICY,isMediaTypeAllowed}from"#public/channels/upload-policy.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{readMediaMetadata,verifyMediaType}from"#internal/attachments/media-metadata.js";import{decodeSandboxRef,encodeSandboxRef,inlinesSandboxRefAsBytes,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";import{isUnresolvedFileData,readFileData}from"#internal/attachments/data.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{createPublicDownloads}from"#internal/attachments/public-link.js";const ATTACHMENTS_ROOT=`/workspace/.eve/attachments`,log=createLogger(`harness.attachment-staging`),UNSAFE_FILENAME_CHARS=/[^\w.-]+/g,MEDIA_TYPE_EXTENSIONS={"application/pdf":`.pdf`,"image/gif":`.gif`,"image/jpeg":`.jpg`,"image/png":`.png`,"image/webp":`.webp`};async function stageAttachmentsForAdapter(e,t,n){if(typeof e==`string`)return e;let r=reconstitueFilePartUrls(e),i=n.ctx.get(ChannelKey)?.uploadPolicy,a=createPublicDownloads(maxBytesOf(i??DEFAULT_UPLOAD_POLICY));return Promise.all(r.map(async e=>e.type===`file`?stageFilePart(e,t,n,a,i):e))}async function stageAttachmentsToSandbox(e){if(typeof e==`string`||!Array.isArray(e)||!hasFileParts(e))return e;let t=loadContext(),n=await activeSandbox(t.get(SandboxKey));if(n===null)return e.map(e=>e.type===`file`&&!isSandboxRefUrl(e.data)&&readFileData(e.data).kind!==`reference`?attachmentNote(e,`could not be stored: no sandbox is available.`):e);let r=t.get(ChannelKey);return stageAttachmentsForAdapter(e,n,r?buildAdapterContext(r,t):{ctx:t,state:{},session:buildSessionHandle(t)})}async function stageToolResultMedia(e){if(!e.some(hasInlineToolResultFile))return[...e];let t=await activeSandbox(contextStorage.getStore()?.get(SandboxKey));return Promise.all(e.map(async e=>{if(e.role!==`tool`||!hasInlineToolResultFile(e))return e;let n=await Promise.all(e.content.map(async e=>e.type===`tool-result`?{...e,output:await stageToolOutputFiles(e.output,t)}:e));return{...e,content:n}}))}async function hydrateSandboxAttachments(e){let t=replaceUnresolvedFileParts(e);if(!messagesContainSandboxRef(t))return t;let n=loadContext().get(SandboxKey);if(n===void 0)throw Error(`Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. Hydration must run inside a step scope with the framework sandbox provider installed.`);let r=await activeSandbox(n);return Promise.all(t.map(async e=>{if(!messageContainsSandboxRef(e))return e;let t=await hydrateMessageContent(e.content,r);return{...e,content:t}}))}async function activeSandbox(e){if(e===void 0)return null;try{return await e.get()}catch(e){return log.warn(`session sandbox unavailable, degrading attachments to text`,{error:e}),null}}function replaceUnresolvedFileParts(e){let t=!1,n=e.map(e=>{if(e.role!==`user`||!Array.isArray(e.content)||!e.content.some(isUnresolvedFilePart))return e;t=!0;let n=e.content.map(e=>isUnresolvedFilePart(e)?attachmentNote(e,`could not be retrieved.`):e);return{...e,content:n}});return t?n:e}function isUnresolvedFilePart(e){return e.type===`file`&&!isSandboxRefUrl(e.data)&&isUnresolvedFileData(e.data)}function hasFileParts(e){for(let t of e)if(t.type===`file`)return!0;return!1}function messagesContainSandboxRef(e){for(let t of e)if(messageContainsSandboxRef(t))return!0;return!1}function messageContainsSandboxRef(e){let t=e.content;if(!Array.isArray(t))return!1;for(let e of t)if(isSandboxRefFilePart(e)||e.type===`tool-result`&&contentOutputParts(e.output).some(isToolOutputRefFile))return!0;return!1}function contentOutputParts(e){return e.type===`content`?e.value:[]}function hasInlineToolResultFile(e){return e.role===`tool`&&e.content.some(e=>e.type===`tool-result`&&contentOutputParts(e.output).some(isInlineToolOutputFile))}function isInlineToolOutputFile(e){return e.type===`file`&&e.data.type===`data`}function isToolOutputRefFile(e){return e.type===`file`&&e.data.type===`url`&&isSandboxRefUrl(e.data.url)}async function stageToolOutputFiles(e,t){if(e.type!==`content`||!e.value.some(isInlineToolOutputFile))return e;let n=await Promise.all(e.value.map(async e=>{if(!isInlineToolOutputFile(e)||e.data.type!==`data`)return e;let n=readFileData(e.data.data);if(n.kind===`link`)return e;if(t===null||n.kind!==`bytes`)return{text:`Returned file ${e.filename??`file`} (${e.mediaType}) could not be stored.`,type:`text`};let r=await writeSandboxRef(n.bytes,e.mediaType,e.filename,t);return{...e,data:{type:`url`,url:encodeSandboxRef(r)},mediaType:r.mediaType}}));return{...e,value:n}}function isSandboxRefFilePart(e){return typeof e==`object`&&!!e&&e.type===`file`&&isSandboxRefUrl(e.data)}async function hydrateMessageContent(e,t){return Array.isArray(e)?(await Promise.all(e.map(async e=>{if(isSandboxRefFilePart(e)){let n=decodeSandboxRef(e.data),r=renderSandboxRefAsTextPart(n);if(!inlinesSandboxRefAsBytes(n))return[r];let i=await readSandboxRefBytes(n,t);return i===null?[renderMissingSandboxRef(n)]:[r,{...e,data:i,mediaType:n.mediaType}]}if(e.type===`tool-result`){let n=e;return[{...n,output:await hydrateToolOutput(n.output,t)}]}return[e]}))).flat():e}async function hydrateToolOutput(e,t){if(e.type!==`content`||!e.value.some(isToolOutputRefFile))return e;let n=await Promise.all(e.value.map(async e=>{if(!isToolOutputRefFile(e)||e.data.type!==`url`)return[e];let n=decodeSandboxRef(e.data.url),r=renderSandboxRefAsTextPart(n);if(!inlinesSandboxRefAsBytes(n))return[r];let i=await readSandboxRefBytes(n,t);return i===null?[renderMissingSandboxRef(n)]:[r,{...e,data:{data:Buffer.from(i).toString(`base64`),type:`data`}}]}));return{...e,value:n.flat()}}async function readSandboxRefBytes(e,t){if(t===null)return null;let n=await t.readBinaryFile({path:e.path});return n===null?(log.warn(`sandbox-ref attachment bytes missing on hydration — degrading to text reference`,{mediaType:e.mediaType,path:e.path,size:e.size}),null):n.byteLength!==e.size||sha256Prefix(n)!==basename(dirname(e.path))?(log.warn(`sandbox-ref attachment bytes changed since staging — degrading to text reference`,{mediaType:e.mediaType,path:e.path,size:e.size}),null):n}function renderMissingSandboxRef(e){return{text:`FileNotFound: Current snapshot may be newer and does not contain ${e.path}.`,type:`text`}}function moveToolResultFilesToUserMessages(e){let t=[],n=[];for(let r of e){if(r.role!==`tool`&&n.length>0&&(t.push(createReturnedFilesMessage(n)),n=[]),r.role!==`tool`){t.push(r);continue}let e=r.content.map(e=>{if(e.type!==`tool-result`||e.output.type!==`content`)return e;let t=e.output.value.map(e=>{if(e.type!==`file`)return e;let t={data:e.data,mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),n.push(t),{text:`Attached file ${e.filename??`file`} (${e.mediaType}) follows this tool result.`,type:`text`}});return{...e,output:{...e.output,value:t}}});t.push({...r,content:e})}return n.length>0&&t.push(createReturnedFilesMessage(n)),t}function createReturnedFilesMessage(e){return createFrameworkUserMessage(`context.state`,[{text:`Files returned by the preceding tool results:`,type:`text`},...e])}function renderSandboxRefAsTextPart(e){return{text:`Attached file ${e.path} (${e.mediaType})`,type:`text`}}async function stageFilePart(e,t,n,r,i){if(isSandboxRefUrl(e.data))return e;let a=readFileData(e.data);if(a.kind===`bytes`)return stageResolvedBytes(e,{bytes:a.bytes},t,i);if(a.kind===`reference`)return e;if(a.kind===`unreadable`)return log.warn(`attachment data is not bytes, base64, or a URL — degrading to text part`,{filename:e.filename,mediaType:e.mediaType}),attachmentNote(e,`could not be read.`);let o;try{o=await resolveLink(a.url,n,r)}catch(t){if(!(t instanceof EveAttachmentError))throw t;return log.warn(`attachment resolver failed — degrading to text part`,{adapterKind:t.adapterKind,error:t.cause,filename:e.filename,kind:t.kind}),attachmentNote(e,`could not be retrieved: ${t.message}`)}return stageResolvedBytes(e,o,t,i)}function attachmentNote(e,t){return{text:`Attachment ${e.filename?.trim()||`file`} ${t}`,type:`text`}}async function stageResolvedBytes(e,t,n,r){let i=verifyMediaType(t.bytes,t.mediaType??e.mediaType??`application/octet-stream`);if(r!==void 0){let n=maxBytesOf(r);if(t.bytes.byteLength>n)return attachmentNote(e,`was not accepted: it is ${t.bytes.byteLength} bytes, over this channel's ${n}-byte upload limit.`);if(!isMediaTypeAllowed(i,r))return attachmentNote(e,`was not accepted: this channel doesn't accept ${i} files.`)}let a=await writeSandboxRef(t.bytes,i,t.filename??e.filename,n);return{...e,data:encodeSandboxRef(a),filename:a.path,mediaType:a.mediaType}}async function writeSandboxRef(e,t,n,r){let i=verifyMediaType(e,t),a=sha256Prefix(e),o=`${ATTACHMENTS_ROOT}/${a}/${safeFilename(n,a,i)}`;return await r.writeBinaryFile({content:e,path:o}),{...readMediaMetadata(e,i),path:r.resolvePath(o)}}async function resolveLink(e,t,n){let r=t.ctx.get(ChannelKey),i=r===void 0?`none`:getAdapterKind(r);if(r?.fetchFile!==void 0){let n;try{n=await r.fetchFile(e.href,t)}catch(e){throw e instanceof EveAttachmentError?new EveAttachmentError({adapterKind:i,cause:e.cause,kind:e.kind,message:e.message}):new EveAttachmentError({adapterKind:i,cause:e,kind:`resolver-threw`,message:`Attachment retrieval failed in the "${i}" channel.`})}if(n!==null)return Buffer.isBuffer(n)?{bytes:n}:n}return n(e,i)}function reconstitueFilePartUrls(e){let t=!1,n=e.map(e=>e.type===`file`&&isSerializedUrlFilePart(e.data)?(t=!0,{...e,data:deserializeUrlFilePart(e.data)}):e);return t?n:e}function sha256Prefix(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,16)}function safeFilename(e,t,n){let r=e===void 0?``:basename(e).replace(UNSAFE_FILENAME_CHARS,`_`),i=r.length>0?r:`file-${t}`,a=MEDIA_TYPE_EXTENSIONS[n];return a===void 0||extname(i)!==``?i:`${i}${a}`}export{ATTACHMENTS_ROOT,hydrateSandboxAttachments,moveToolResultFilesToUserMessages,stageAttachmentsForAdapter,stageAttachmentsToSandbox,stageToolResultMedia};
|
|
@@ -91,6 +91,9 @@ export declare function consumeAuthorizationResult(name: string, instanceId?: st
|
|
|
91
91
|
* It is independent of the continuation token, so channel aliasing mid-turn
|
|
92
92
|
* does not invalidate the callback URL.
|
|
93
93
|
*
|
|
94
|
+
* The URL reaches the user's browser and the IdP, so it never carries the
|
|
95
|
+
* deployment's protection bypass secret.
|
|
96
|
+
*
|
|
94
97
|
* Returns `undefined` if no callback address is available.
|
|
95
98
|
*/
|
|
96
99
|
export declare function getHookUrl(name: string, attemptId: string): string | undefined;
|
|
@@ -135,17 +138,4 @@ export declare const PendingAuthorizationResultKey: ContextKey<readonly NamedAut
|
|
|
135
138
|
export declare const CallbackBaseUrlKey: ContextKey<string>;
|
|
136
139
|
/** Hook token of a runtime that owns its callback instead of using the session hook. */
|
|
137
140
|
export declare const AuthorizationHookKey: ContextKey<string>;
|
|
138
|
-
export interface PendingAuthorizationState {
|
|
139
|
-
readonly challenges: readonly AuthorizationChallenge[];
|
|
140
|
-
}
|
|
141
|
-
export declare function setPendingAuthorization(sessionState: Record<string, unknown> | undefined, value: PendingAuthorizationState): Record<string, unknown>;
|
|
142
|
-
/** The pending sign-ins once `challenges` are asked for: each replaces the attempt it supersedes. */
|
|
143
|
-
export declare function withSignIns(previous: readonly AuthorizationChallenge[], challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
144
|
-
/** Keeps the last challenge for each sign-in and principal. */
|
|
145
|
-
export declare function resolveActiveAuthorizationChallenges(challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
146
|
-
/** The attempts in `previous` that `replacements` replace: the same sign-in and principal. */
|
|
147
|
-
export declare function supersededChallenges(previous: readonly AuthorizationChallenge[], replacements: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
148
|
-
export declare function clearPendingAuthorization(sessionState: Record<string, unknown> | undefined, attemptIds?: readonly string[]): Record<string, unknown> | undefined;
|
|
149
|
-
export declare function getPendingAuthorization(sessionState: Record<string, unknown> | undefined): PendingAuthorizationState | undefined;
|
|
150
|
-
export declare function hasPendingAuthorization(sessionState: Record<string, unknown> | undefined): boolean;
|
|
151
141
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{ContextKey}from"#context/key.js";import{
|
|
1
|
+
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{ContextKey}from"#context/key.js";import{createBrowserCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(t&&t.length!==0)return e===void 0?t[0]:t.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,t){let n=loadContext(),r=n.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(n=>n.name===e&&n.instanceId===t);if(i===-1&&t!==void 0&&r.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return n.delete(PendingAuthorizationResultKey),o.length>0&&n.set(PendingAuthorizationResultKey,o),a}function getHookUrl(e,t){let n=loadContext(),r=n.get(SessionIdKey),i=n.get(CallbackBaseUrlKey),a=n.get(AuthorizationHookKey)??(r?authHookToken(r):void 0);if(a&&i)return createBrowserCallbackUrl(i,createEveConnectionCallbackRoutePath(e,t,a))}function createAuthorizationAttempt(e){let t=createUlid(),n=getHookUrl(e,t);return n===void 0?void 0:{attemptId:t,hookUrl:n}}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return sessionInboxHookToken(sessionCommandHookToken(e))}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),AuthorizationHookKey=new ContextKey(`eve.authorizationHook`);export{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getAuthorizationResults,getHookUrl,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,requestAuthorization};
|