eve 0.15.0 → 0.15.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 +16 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/status-line.d.ts +6 -3
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/cli/dev/tui/vercel-status.d.ts +2 -2
- package/dist/src/cli/dev/tui/vercel-status.js +1 -1
- package/dist/src/cli/run.d.ts +2 -2
- package/dist/src/cli/run.js +2 -2
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/deliver-payloads.d.ts +3 -0
- package/dist/src/execution/deliver-payloads.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +2 -0
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +1 -0
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +7 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
- package/dist/src/execution/forward-turn-delivery-step.d.ts +6 -0
- package/dist/src/execution/forward-turn-delivery-step.js +1 -0
- package/dist/src/execution/hook-ownership.d.ts +6 -0
- package/dist/src/execution/hook-ownership.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +1 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/route-child-delivery.d.ts +18 -0
- package/dist/src/execution/route-child-delivery.js +1 -0
- package/dist/src/execution/session-delivery-hook.d.ts +20 -0
- package/dist/src/execution/session-delivery-hook.js +1 -0
- package/dist/src/execution/subagent-tool.d.ts +2 -0
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/execution/turn-control-protocol.d.ts +36 -0
- package/dist/src/execution/turn-control-protocol.js +1 -0
- package/dist/src/execution/turn-control-receiver.d.ts +35 -0
- package/dist/src/execution/turn-control-receiver.js +1 -0
- package/dist/src/execution/turn-dispatch.d.ts +17 -0
- package/dist/src/execution/turn-dispatch.js +1 -0
- package/dist/src/execution/turn-execution-cursor.d.ts +48 -0
- package/dist/src/execution/turn-execution-cursor.js +1 -0
- package/dist/src/execution/turn-workflow.d.ts +1 -27
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +8 -0
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.d.ts +6 -4
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +4 -22
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/dev-server-state.d.ts +20 -0
- package/dist/src/internal/nitro/host/dev-server-state.js +1 -0
- package/dist/src/internal/nitro/host/start-development-server.d.ts +12 -5
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/internal/nitro/host/types.d.ts +25 -3
- package/dist/src/internal/nitro/host.d.ts +2 -2
- package/dist/src/internal/nitro/host.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/eve-server-health.d.ts +5 -0
- package/dist/src/shared/eve-server-health.js +1 -0
- package/dist/src/shared/network-address.d.ts +12 -0
- package/dist/src/shared/network-address.js +1 -1
- package/dist/src/shared/result.d.ts +12 -0
- package/dist/src/shared/result.js +1 -0
- package/docs/connections/overview.mdx +11 -11
- package/docs/guides/dev-tui.md +1 -1
- package/docs/meta.json +1 -0
- package/docs/patterns/dynamic-scheduling.md +257 -0
- package/docs/patterns/meta.json +9 -0
- package/docs/patterns/multi-tenant-approvals.md +191 -0
- package/docs/patterns/multi-tenant-auth.md +177 -0
- package/docs/patterns/multi-tenant-memory.md +188 -0
- package/docs/reference/cli.md +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
|
+
/**
|
|
4
|
+
* Coalesces inbound deliver payloads and routes any descendant-bound input
|
|
5
|
+
* responses down to the owning child, returning the parent-local remainder
|
|
6
|
+
* (or `undefined` when the whole payload routed away).
|
|
7
|
+
*
|
|
8
|
+
* Short-circuits via `hasProxyInputRequests` so the common no-active-descendant
|
|
9
|
+
* path skips a durable step boundary. Lives in its own non-step module so both
|
|
10
|
+
* the driver and the active turn can share it (a `"use step"` module cannot
|
|
11
|
+
* re-export plain helpers into a workflow body).
|
|
12
|
+
*/
|
|
13
|
+
export declare function routeDeliverToChildren(input: {
|
|
14
|
+
readonly auth?: SessionAuthContext | null;
|
|
15
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
16
|
+
readonly payloads: readonly DeliverPayload[];
|
|
17
|
+
readonly sessionState: DurableSessionState;
|
|
18
|
+
}): Promise<DeliverPayload | undefined>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeProxiedDeliverStep}from"#execution/workflow-steps.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}export{routeDeliverToChildren};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
|
|
2
|
+
/** Reads and rekeys the public delivery hook for one session driver. */
|
|
3
|
+
export interface SessionDeliveryHook {
|
|
4
|
+
consumeNext(): void;
|
|
5
|
+
next(): Promise<IteratorResult<HookPayload>>;
|
|
6
|
+
rekey(token: string): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/** Adds workflow-entry lifecycle ownership to a session delivery hook. */
|
|
9
|
+
export interface SessionDeliveryHookHandle extends SessionDeliveryHook {
|
|
10
|
+
dispose(): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Creates the public delivery hook used by `workflowEntry`.
|
|
14
|
+
*
|
|
15
|
+
* Retired hooks are disposed immediately, but their already-armed reads stay
|
|
16
|
+
* in the logical hook's delivery race. A delivery that committed before disposal can
|
|
17
|
+
* therefore still resolve on replay; a later delivery loses the storage race
|
|
18
|
+
* to `hook_disposed` and receives `HookNotFoundError` from the Workflow SDK.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createSessionDeliveryHook(bufferedDeliveries: DeliverHookPayload[]): SessionDeliveryHookHandle;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook}from"#execution/hook-ownership.js";function createSessionDeliveryHook(r){let i,a=[],o=[],s=0,c=null,l,u,enqueue=e=>{o.push(e),o.sort((e,t)=>e.order-t.order),u?.(),u=void 0},arm=e=>{e.closed||e.pending||(e.pending=!0,e.resolved=void 0,(e.retired?Promise.resolve(e.hook).then(e=>({done:!1,value:e})):e.iterator.next()).then(t=>{let n={order:s++,result:t,state:e};e.resolved=n,e.enabled&&enqueue(n)},()=>{}))},enable=e=>{e.enabled=!0,e.resolved!==void 0&&enqueue(e.resolved)},drainReady=async()=>{if(c===null)for(await Promise.resolve();o.length>0;){let e=o.shift();e.state.pending=!1,e.state.resolved=void 0,e.result.done?e.state.closed=!0:e.result.value.kind===`deliver`&&r.push(e.result.value),arm(e.state),await Promise.resolve()}};return{consumeNext(){if(l===void 0)throw Error(`Cannot consume a public delivery before it resolves.`);l.state.pending=!1,l.state.resolved=void 0,l.result.done&&(l.state.closed=!0),l=void 0,c=null},async dispose(){i!==void 0&&(await disposeHook(i.hook),i=void 0)},next(){if(i===void 0)throw Error(`Cannot wait for deliveries before a continuation token is available.`);if(c!==null)return c;arm(i);for(let e of a)arm(e);return i.closed&&a.every(e=>e.closed)?(l={order:s++,result:{done:!0,value:void 0},state:i},c=Promise.resolve(l.result),c):(c=(async()=>{for(;o.length===0;)await new Promise(e=>{u=e});let e=o.shift();return l=e,e.result})(),c)},async rekey(r){if(!r||i?.hook.token===r)return;let o=createHook({token:r}),s={closed:!1,enabled:!1,hook:o,iterator:o[Symbol.asyncIterator](),pending:!1,retired:!1};if(i===void 0){await claimHookOwnership(s.hook),enable(s),i=s;return}let c=i;arm(c),arm(s),await claimHookOwnership(s.hook),enable(s),await drainReady();try{await disposeHook(c.hook)}catch(e){i=void 0;try{await disposeHook(s.hook)}catch{}throw e}c.retired=!0,a.push(c),i=s,await drainReady()}}}export{createSessionDeliveryHook};
|
|
@@ -34,6 +34,8 @@ export declare function buildSubagentRunInput(input: {
|
|
|
34
34
|
readonly capabilities?: SessionCapabilities;
|
|
35
35
|
readonly channelMetadata?: ChannelInstrumentationProjection;
|
|
36
36
|
readonly initiatorAuth: SessionAuthContext | null;
|
|
37
|
+
/** Hook token owned by the workflow currently waiting for this child. */
|
|
38
|
+
readonly parentContinuationToken?: string;
|
|
37
39
|
readonly session: HarnessSession;
|
|
38
40
|
}): SubagentRunInputBuild;
|
|
39
41
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{formatSubagentInvocation}from"#execution/subagent-invocation.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l}=n,u=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),d=l.rootSessionId??l.sessionId;return{childContinuationToken:u,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:u,initiatorAuth:c,input:{message:formatSubagentCallInputMessage(r),outputSchema:r.input.outputSchema},mode:`task`,parent:{callId:r.callId,rootSessionId:d,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}}}}}function formatSubagentCallInputMessage(e){let{message:t}=e.input;return formatSubagentInvocation({description:e.description,message:t,name:e.subagentName}).message}export{buildSubagentRunInput};
|
|
1
|
+
import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{formatSubagentInvocation}from"#execution/subagent-invocation.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l}=n,u=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),d=l.rootSessionId??l.sessionId;return{childContinuationToken:u,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:u,initiatorAuth:c,input:{message:formatSubagentCallInputMessage(r),outputSchema:r.input.outputSchema},mode:`task`,parent:{callId:r.callId,rootSessionId:d,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}}}}}function formatSubagentCallInputMessage(e){let{message:t}=e.input;return formatSubagentInvocation({description:e.description,message:t,name:e.subagentName}).message}export{buildSubagentRunInput};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
|
|
2
|
+
import type { NextDriverAction } from "#execution/next-driver-action.js";
|
|
3
|
+
/** Payloads delivered to the private inbox owned by one active turn. */
|
|
4
|
+
export type TurnInboxPayload = Exclude<HookPayload, DeliverHookPayload> | {
|
|
5
|
+
readonly delivery: DeliverHookPayload;
|
|
6
|
+
readonly kind: "driver-delivery";
|
|
7
|
+
readonly requestId: string;
|
|
8
|
+
};
|
|
9
|
+
/** Control payloads emitted from an active turn to its session driver. */
|
|
10
|
+
export type TurnControlPayload = {
|
|
11
|
+
readonly action: NextDriverAction;
|
|
12
|
+
readonly bufferedDeliveries?: readonly DeliverHookPayload[];
|
|
13
|
+
readonly kind: "turn-result";
|
|
14
|
+
} | {
|
|
15
|
+
readonly kind: "turn-error";
|
|
16
|
+
readonly error: unknown;
|
|
17
|
+
} | {
|
|
18
|
+
readonly continuationToken: string;
|
|
19
|
+
readonly kind: "turn-continuation-token";
|
|
20
|
+
} | {
|
|
21
|
+
readonly continuationToken: string;
|
|
22
|
+
readonly inboxToken: string;
|
|
23
|
+
readonly kind: "turn-delivery-request";
|
|
24
|
+
readonly requestId: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: "turn-delivery-accepted";
|
|
27
|
+
readonly requestId: string;
|
|
28
|
+
} | {
|
|
29
|
+
readonly kind: "turn-delivery-cancelled";
|
|
30
|
+
readonly requestId: string;
|
|
31
|
+
};
|
|
32
|
+
/** Sends one lifecycle payload to the session driver's control hook. */
|
|
33
|
+
export declare function sendTurnControlStep(input: {
|
|
34
|
+
readonly controlToken: string;
|
|
35
|
+
readonly payload: TurnControlPayload;
|
|
36
|
+
}): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resumeHook}from"#internal/workflow/runtime.js";async function sendTurnControlStep(e){"use step";await resumeHook(e.controlToken,e.payload)}export{sendTurnControlStep};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DeliverHookPayload } from "#channel/types.js";
|
|
2
|
+
import type { NextDriverAction } from "#execution/next-driver-action.js";
|
|
3
|
+
import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
|
|
4
|
+
/** Owns one turn's driver-side control hook and public-delivery relay state. */
|
|
5
|
+
export declare class TurnControlReceiver {
|
|
6
|
+
private readonly bufferedDeliveries;
|
|
7
|
+
private readonly control;
|
|
8
|
+
private readonly controlIterator;
|
|
9
|
+
private readonly deliveryHook;
|
|
10
|
+
private pendingControl;
|
|
11
|
+
constructor(input: {
|
|
12
|
+
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
13
|
+
readonly deliveryHook: SessionDeliveryHook;
|
|
14
|
+
readonly token: string;
|
|
15
|
+
});
|
|
16
|
+
/** Token passed to the turn workflow so it can publish control messages. */
|
|
17
|
+
get token(): string;
|
|
18
|
+
/** Releases the turn control hook and its iterator. */
|
|
19
|
+
dispose(): Promise<void>;
|
|
20
|
+
/** Services control messages until the active turn returns its terminal driver action. */
|
|
21
|
+
waitForAction(): Promise<NextDriverAction>;
|
|
22
|
+
private bufferTurnDeliveries;
|
|
23
|
+
private consumeControl;
|
|
24
|
+
private getControlPromise;
|
|
25
|
+
private nextControl;
|
|
26
|
+
private readTerminalControl;
|
|
27
|
+
private serviceDeliveryRequest;
|
|
28
|
+
/**
|
|
29
|
+
* Waits for the active turn to resolve a forwarded delivery. The turn either
|
|
30
|
+
* accepts it (consumed) or releases it on cancellation or termination, in
|
|
31
|
+
* which case the delivery returns to the buffer ahead of the turn's own
|
|
32
|
+
* remainders so the next parent turn still observes it in arrival order.
|
|
33
|
+
*/
|
|
34
|
+
private awaitForwardedDelivery;
|
|
35
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{forwardTurnDeliveryStep}from"#execution/forward-turn-delivery-step.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";var TurnControlReceiver=class{bufferedDeliveries;control;controlIterator;deliveryHook;pendingControl=null;constructor(t){this.bufferedDeliveries=t.bufferedDeliveries,this.control=createHook({token:t.token}),this.controlIterator=this.control[Symbol.asyncIterator](),this.deliveryHook=t.deliveryHook}get token(){return this.control.token}async dispose(){await closeHookIterator(this.controlIterator),await disposeHook(this.control)}async waitForAction(){for(;;){let e=await this.nextControl(`Turn control hook closed before delivering a result.`),t=this.readTerminalControl(e);if(t!==void 0)return t;if(e.kind===`turn-delivery-request`){let t=await this.serviceDeliveryRequest(e);if(t!==void 0)return t}}}bufferTurnDeliveries(e){e.bufferedDeliveries!==void 0&&this.bufferedDeliveries.unshift(...e.bufferedDeliveries)}consumeControl(){this.pendingControl=null}getControlPromise(){return this.pendingControl??=this.controlIterator.next(),this.pendingControl}async nextControl(e){for(;;){let t=await this.getControlPromise();if(this.consumeControl(),t.done)throw Error(e);let n=t.value;if(n.kind===`turn-error`)throw rebuildSerializableError(n.error);if(n.kind===`turn-continuation-token`){await this.deliveryHook.rekey(n.continuationToken);continue}return n}}readTerminalControl(e){if(e.kind===`turn-error`)throw rebuildSerializableError(e.error);if(e.kind===`turn-result`)return this.bufferTurnDeliveries(e),e.action}async serviceDeliveryRequest(e){await this.deliveryHook.rekey(e.continuationToken);let t=this.bufferedDeliveries.shift();for(;t===void 0;){let n=await Promise.race([this.getControlPromise().then(e=>({kind:`control`,value:e})),this.deliveryHook.next().then(e=>({kind:`delivery`,value:e}))]);if(n.kind===`control`){if(this.consumeControl(),n.value.done)throw Error(`Turn control hook closed during a delivery request.`);if(n.value.value.kind===`turn-continuation-token`){await this.deliveryHook.rekey(n.value.value.continuationToken);continue}let t=this.readTerminalControl(n.value.value);if(t!==void 0)return t;if(n.value.value.kind===`turn-delivery-cancelled`&&n.value.value.requestId===e.requestId)return;continue}if(n.value.done)throw Error(`Session delivery hook closed during a turn delivery request.`);this.deliveryHook.consumeNext(),n.value.value.kind===`deliver`&&(t=n.value.value)}try{await forwardTurnDeliveryStep({inboxToken:e.inboxToken,payload:{delivery:t,kind:`driver-delivery`,requestId:e.requestId}})}catch(e){if(!(e instanceof Error&&e.name===`HookNotFoundError`))throw e}return await this.awaitForwardedDelivery(e.requestId,t)}async awaitForwardedDelivery(e,t){for(;;){let n=await this.nextControl(`Turn control hook closed before resolving a forwarded delivery.`);if(n.kind===`turn-delivery-accepted`){if(n.requestId===e)return;continue}if(n.kind===`turn-delivery-cancelled`&&n.requestId===e){this.bufferedDeliveries.unshift(t);return}n.kind===`turn-result`&&this.bufferedDeliveries.unshift(t);let r=this.readTerminalControl(n);if(r!==void 0)return r}}};export{TurnControlReceiver};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";
|
|
2
|
+
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
|
+
import type { NextDriverAction } from "#execution/next-driver-action.js";
|
|
4
|
+
import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
|
|
5
|
+
import type { RunMode } from "#shared/run-mode.js";
|
|
6
|
+
/** Dispatches one turn and services its private-inbox control protocol until it terminates. */
|
|
7
|
+
export declare function dispatchAndAwaitTurn(input: {
|
|
8
|
+
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
9
|
+
readonly capabilities?: SessionCapabilities;
|
|
10
|
+
readonly controlToken: string;
|
|
11
|
+
readonly delivery: HookPayload;
|
|
12
|
+
readonly deliveryHook: SessionDeliveryHook;
|
|
13
|
+
readonly mode: RunMode;
|
|
14
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
15
|
+
readonly serializedContext: Record<string, unknown>;
|
|
16
|
+
readonly sessionState: DurableSessionState;
|
|
17
|
+
}): Promise<NextDriverAction>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dispatchTurnStep}from"#execution/workflow-steps.js";import{TurnControlReceiver}from"#execution/turn-control-receiver.js";async function dispatchAndAwaitTurn(e){let t=new TurnControlReceiver({bufferedDeliveries:e.bufferedDeliveries,deliveryHook:e.deliveryHook,token:e.controlToken});try{return await dispatchTurnStep({capabilities:e.capabilities,completionToken:t.token,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),await t.waitForAction()}finally{await t.dispose()}}export{dispatchAndAwaitTurn};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
|
|
2
|
+
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
|
|
3
|
+
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
4
|
+
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
5
|
+
interface TurnTransition {
|
|
6
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
7
|
+
readonly sessionState: DurableSessionState;
|
|
8
|
+
}
|
|
9
|
+
type TurnTerminalAction = {
|
|
10
|
+
readonly isError?: boolean;
|
|
11
|
+
readonly kind: "done";
|
|
12
|
+
readonly output: unknown;
|
|
13
|
+
} | {
|
|
14
|
+
readonly authorizationNames?: readonly string[];
|
|
15
|
+
readonly kind: "park";
|
|
16
|
+
};
|
|
17
|
+
/** Owns the mutable durable state cursor for one active turn workflow. */
|
|
18
|
+
export declare class TurnExecutionCursor {
|
|
19
|
+
readonly controlToken: string;
|
|
20
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
21
|
+
private currentSerializedContext;
|
|
22
|
+
private currentSessionState;
|
|
23
|
+
private lastReportedContinuationToken;
|
|
24
|
+
constructor(input: {
|
|
25
|
+
readonly controlToken: string;
|
|
26
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
27
|
+
readonly serializedContext: Record<string, unknown>;
|
|
28
|
+
readonly sessionState: DurableSessionState;
|
|
29
|
+
});
|
|
30
|
+
/** Latest serialized runtime context adopted by the active turn. */
|
|
31
|
+
get serializedContext(): Record<string, unknown>;
|
|
32
|
+
/** Latest durable session state adopted by the active turn. */
|
|
33
|
+
get sessionState(): DurableSessionState;
|
|
34
|
+
/** Adopts a state transition and reports any continuation-token change once. */
|
|
35
|
+
adopt(transition: TurnTransition): Promise<void>;
|
|
36
|
+
/** Builds the next atomic turn-step input from the cursor's current state. */
|
|
37
|
+
createStepInput(input: HookPayload | undefined): TurnStepInput;
|
|
38
|
+
/**
|
|
39
|
+
* Adopts a terminal turn transition and publishes it as the turn result.
|
|
40
|
+
* The result already carries the final session state, so no separate
|
|
41
|
+
* continuation-token update is sent.
|
|
42
|
+
*/
|
|
43
|
+
finish(transition: TurnTransition, action: TurnTerminalAction, bufferedDeliveries: readonly DeliverHookPayload[]): Promise<void>;
|
|
44
|
+
/** Sends one control payload to the session driver. */
|
|
45
|
+
send(payload: TurnControlPayload): Promise<void>;
|
|
46
|
+
private setState;
|
|
47
|
+
}
|
|
48
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sendTurnControlStep}from"#execution/turn-control-protocol.js";var TurnExecutionCursor=class{controlToken;parentWritable;currentSerializedContext;currentSessionState;lastReportedContinuationToken;constructor(e){this.controlToken=e.controlToken,this.currentSerializedContext=e.serializedContext,this.currentSessionState=e.sessionState,this.lastReportedContinuationToken=e.sessionState.continuationToken,this.parentWritable=e.parentWritable}get serializedContext(){return this.currentSerializedContext}get sessionState(){return this.currentSessionState}async adopt(e){this.setState(e);let t=e.sessionState.continuationToken;t===``||t===this.lastReportedContinuationToken||(this.lastReportedContinuationToken=t,await this.send({continuationToken:t,kind:`turn-continuation-token`}))}createStepInput(e){return{input:e,parentWritable:this.parentWritable,serializedContext:this.currentSerializedContext,sessionState:this.currentSessionState}}async finish(e,t,n){this.setState(e),await this.send({action:{...t,serializedContext:this.currentSerializedContext,sessionState:this.currentSessionState},bufferedDeliveries:n.length===0?void 0:[...n],kind:`turn-result`})}async send(t){await sendTurnControlStep({controlToken:this.controlToken,payload:t})}setState(e){this.currentSerializedContext=e.serializedContext??this.currentSerializedContext,this.currentSessionState=e.sessionState}};export{TurnExecutionCursor};
|
|
@@ -1,30 +1,4 @@
|
|
|
1
|
-
import type { NextDriverAction } from "#execution/next-driver-action.js";
|
|
2
1
|
import { type TurnWorkflowInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
3
|
-
/**
|
|
4
|
-
* Hook payload the turn child workflow delivers to the parent driver
|
|
5
|
-
* on completion. `turn-result` wraps a {@link NextDriverAction} the
|
|
6
|
-
* driver dispatches on; `turn-error` carries a normalized error the
|
|
7
|
-
* driver rethrows.
|
|
8
|
-
*/
|
|
9
|
-
export type TurnCompletionPayload = {
|
|
10
|
-
readonly kind: "turn-result";
|
|
11
|
-
readonly action: NextDriverAction;
|
|
12
|
-
} | {
|
|
13
|
-
readonly kind: "turn-error";
|
|
14
|
-
readonly error: unknown;
|
|
15
|
-
};
|
|
16
2
|
export type { TurnWorkflowInput };
|
|
17
|
-
/**
|
|
18
|
-
* Short-lived workflow that owns one runtime turn for the driver.
|
|
19
|
-
*
|
|
20
|
-
* `parentWritable` is threaded in from the driver run so event writes
|
|
21
|
-
* land on the driver's stream. Resolves the turn into a
|
|
22
|
-
* {@link NextDriverAction} and reports it back through
|
|
23
|
-
* {@link notifyDriverStep}.
|
|
24
|
-
*/
|
|
3
|
+
/** Runs one complete logical turn, including child-agent waits when supported. */
|
|
25
4
|
export declare function turnWorkflow(rawInput: unknown): Promise<void>;
|
|
26
|
-
/** Resumes the driver's one-shot completion hook with the turn result. */
|
|
27
|
-
export declare function notifyDriverStep(input: {
|
|
28
|
-
readonly completionToken: string;
|
|
29
|
-
readonly payload: TurnCompletionPayload;
|
|
30
|
-
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resolveRuntimeActionResultsForKeys}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{runProxyInputRequestStep,turnStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,closeHookIterator,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let t=migrateTurnWorkflowInput(e);return t.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(t):runLegacyTurnWorkflow(t)}async function runTurnOwnedWorkflow(e){let r=createHook({token:`${e.completionToken}:inbox`}),c=r[Symbol.asyncIterator](),l=new TurnExecutionCursor({controlToken:e.completionToken,parentWritable:e.stepInput.parentWritable,serializedContext:e.stepInput.serializedContext,sessionState:e.stepInput.sessionState}),u=0,nextDeliveryRequestId=()=>`${r.token}:delivery:${String(u++)}`,d=[],f=e.stepInput.input,p=!1;try{try{await claimHookOwnership(r),p=!0}catch(e){if(isHookConflictError(e))return;throw e}for(;;){let a=await turnStep(l.createStepInput(f));if(a.action===`done`){await l.finish(a,{kind:`done`,output:a.output??``,isError:a.isError},d);return}let s=a.action===`dispatch-workflow-runtime-actions`||a.action===`park`?a.pendingRuntimeActionKeys:void 0;if(s!==void 0){await l.adopt(a);let e=await(a.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:r.token,parentWritable:l.parentWritable,serializedContext:l.serializedContext,sessionState:l.sessionState});await l.adopt(e),f={kind:`runtime-action-result`,results:await waitForRuntimeActionResults({bufferedDeliveries:d,cursor:l,inboxToken:r.token,initialResults:e.results,iterator:c,nextDeliveryRequestId,pendingActionKeys:s})};continue}if(a.action===`park`){if(!(a.hasPendingAuthorization||a.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await l.finish(a,{authorizationNames:a.authorizationNames,kind:`park`},d);return}await l.adopt(a),f=void 0}}catch(e){throw await l.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{await closeHookIterator(c),p&&await disposeHook(r)}}async function waitForRuntimeActionResults(t){let n,i=[...t.initialResults];for(;;){let a=resolveRuntimeActionResultsForKeys({pendingKeys:t.pendingActionKeys,results:i});if(a!==void 0)return n!==void 0&&await t.cursor.send({kind:`turn-delivery-cancelled`,requestId:n}),a;t.cursor.sessionState.hasProxyInputRequests&&n===void 0&&(n=t.nextDeliveryRequestId(),await t.cursor.send({continuationToken:t.cursor.sessionState.continuationToken,inboxToken:t.inboxToken,kind:`turn-delivery-request`,requestId:n}));let o=await t.iterator.next();if(o.done)throw Error(`Turn inbox closed before runtime actions completed.`);let s=o.value;if(s.kind===`runtime-action-result`){i.push(...s.results);continue}if(s.kind===`subagent-input-request`){let e=await runProxyInputRequestStep({hookPayload:s,parentWritable:t.cursor.parentWritable,serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState});await t.cursor.adopt(e);continue}if(s.kind===`driver-delivery`&&s.requestId===n){await t.cursor.send({kind:`turn-delivery-accepted`,requestId:s.requestId}),n=void 0;let e=await routeDeliverToChildren({auth:s.delivery.auth,parentWritable:t.cursor.parentWritable,payloads:s.delivery.payloads,sessionState:t.cursor.sessionState});e!==void 0&&t.bufferedDeliveries.push({...s.delivery,payloads:[e]})}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationNames:n.authorizationNames}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
|
|
@@ -6,6 +6,14 @@
|
|
|
6
6
|
* agent.
|
|
7
7
|
*/
|
|
8
8
|
export declare function resolveVercelProductionCallbackBaseUrl(): string | null;
|
|
9
|
+
/**
|
|
10
|
+
* Resolves the origin used for framework-owned workflow callbacks.
|
|
11
|
+
*
|
|
12
|
+
* Workflow metadata falls back to port 3000 when its optional local port
|
|
13
|
+
* discovery is unavailable. eve already configures the local world with the
|
|
14
|
+
* active dev-server origin, so prefer that value before the metadata fallback.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveWorkflowCallbackBaseUrl(metadataUrl: string): string;
|
|
9
17
|
/**
|
|
10
18
|
* Builds a framework-owned callback URL from a resolved callback origin.
|
|
11
19
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function createWorkflowCallbackUrl(e,t){let n=new URL(t,e),r=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return r&&n.searchParams.set(`x-vercel-protection-bypass`,r),n.toString()}export{createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl};
|
|
1
|
+
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;return(resolveVercelProductionCallbackBaseUrl()??t??e).replace(/\/$/,``)}function createWorkflowCallbackUrl(e,t){let n=new URL(t,e),r=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return r&&n.searchParams.set(`x-vercel-protection-bypass`,r),n.toString()}export{createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl,resolveWorkflowCallbackBaseUrl};
|
|
@@ -18,9 +18,11 @@ export interface WorkflowEntryResult {
|
|
|
18
18
|
* on a child stream and resume the parked parent with a
|
|
19
19
|
* `subagent-result` on completion.
|
|
20
20
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
21
|
+
* Owns the public delivery hook and the session lifecycle; each turn-owned
|
|
22
|
+
* turn resolves its own runtime actions in-line and reports back only
|
|
23
|
+
* `done`/`park` via the closed-contract {@link NextDriverAction}. The
|
|
24
|
+
* only session-shape flag the driver reads (besides identity) is
|
|
25
|
+
* `hasProxyInputRequests`, the documented short-circuit for hook-payload
|
|
26
|
+
* routing to any descendant still active when the parent parks.
|
|
25
27
|
*/
|
|
26
28
|
export declare function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowEntryResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{emitTerminalSessionFailureStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{coalesceDeliveries}from"#harness/messages.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionDeliveryHook}from"#execution/session-delivery-hook.js";async function workflowEntry(t){"use workflow";let{workflowRunId:i}=getWorkflowMetadata(),a=t.serializedContext[`eve.continuationToken`]||``,s=t.serializedContext[`eve.mode`],c=t.serializedContext[`eve.capabilities`],u=t.serializedContext[`eve.bundle`];t.serializedContext[`eve.sessionId`]=i;let d=getWritable();try{let e=readRootSessionId(t.serializedContext),{state:n}=await createSessionStep({compiledArtifactsSource:u.source,continuationToken:a,nodeId:u.nodeId,outputSchema:t.input.outputSchema,rootSessionId:e,sessionId:i});return await runDriverLoop({capabilities:c,driverWritable:d,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,context:t.input.context,outputSchema:t.input.outputSchema}],requestId:readChannelRequestId(t.serializedContext)},mode:s,serializedContext:t.serializedContext,sessionState:n})}catch(n){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(n),parentWritable:d,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(n),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,n),serializedContext:t.serializedContext}),n}}async function runDriverLoop(e){let n=createHook({token:`${e.sessionState.sessionId}:auth`}),r=n[Symbol.asyncIterator](),o=0,nextTurnControlToken=()=>`${e.sessionState.sessionId}:turn-control:${String(o++)}`,c=[],l=createSessionDeliveryHook(c);try{e.sessionState.continuationToken&&await l.rekey(e.sessionState.continuationToken);let t=await dispatchAndAwaitTurn({bufferedDeliveries:c,capabilities:e.capabilities,controlToken:nextTurnControlToken(),delivery:e.initialInput,deliveryHook:l,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});for(;;){if(t.kind===`done`)return await finalizeDone({action:t,driverWritable:e.driverWritable});if(t.kind!==`park`)throw Error(`Driver received unexpected turn action "${t.kind}".`);if(!t.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");if(await l.rekey(t.sessionState.continuationToken),t.authorizationNames&&t.authorizationNames.length>0){let n=t.authorizationNames.length,i=[];for(;i.length<n;){let e=await r.next();if(e.done)break;e.value.kind===`deliver`&&i.push(...e.value.payloads)}t=await dispatchAndAwaitTurn({bufferedDeliveries:c,capabilities:e.capabilities,controlToken:nextTurnControlToken(),delivery:{kind:`deliver`,payloads:i},deliveryHook:l,mode:e.mode,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState});continue}let n=await waitForNextDeliver({bufferedDeliveries:c,deliveryHook:l});if(n===null)return{output:``};let i=await routeDeliverToChildren({auth:n.auth,parentWritable:e.driverWritable,payloads:n.payloads,sessionState:t.sessionState});i!==void 0&&(t=await dispatchAndAwaitTurn({bufferedDeliveries:c,capabilities:e.capabilities,controlToken:nextTurnControlToken(),delivery:{auth:n.auth,kind:`deliver`,payloads:[i],requestId:n.requestId},deliveryHook:l,mode:e.mode,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))}}finally{await l.dispose(),await closeHookIterator(r),await disposeHook(n)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.deliveryHook.next();if(e.deliveryHook.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.deliveryHook.next());if(t===NO_READY_MESSAGE||(e.deliveryHook.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e,o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";async function turnStep(e){"use step";let t=e,o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
@@ -61,29 +61,11 @@ export declare function recordPendingSubagentChildToken(input: {
|
|
|
61
61
|
readonly childContinuationToken: string;
|
|
62
62
|
readonly session: HarnessSession;
|
|
63
63
|
}): HarnessSession;
|
|
64
|
-
/**
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
* coupling to a concrete `HookPayload` shape.
|
|
68
|
-
*/
|
|
69
|
-
type RuntimeActionAccumulatorItem<TDeliver> = {
|
|
70
|
-
readonly kind: "deliver";
|
|
71
|
-
readonly value: TDeliver;
|
|
72
|
-
} | {
|
|
73
|
-
readonly kind: "runtime-action-result";
|
|
64
|
+
/** Returns results in pending-key order once every requested action has completed. */
|
|
65
|
+
export declare function resolveRuntimeActionResultsForKeys(input: {
|
|
66
|
+
readonly pendingKeys: readonly string[];
|
|
74
67
|
readonly results: readonly RuntimeActionResult[];
|
|
75
|
-
};
|
|
76
|
-
/**
|
|
77
|
-
* Accumulates runtime-action results until every pending key has a
|
|
78
|
-
* matching result. The caller passes the ordered key list so the
|
|
79
|
-
* workflow runtime can drive the loop without hydrating a session.
|
|
80
|
-
*/
|
|
81
|
-
export declare function accumulateRuntimeActionResults<TDeliver>(input: {
|
|
82
|
-
readonly bufferedDeliveries: TDeliver[];
|
|
83
|
-
readonly getNext: () => Promise<RuntimeActionAccumulatorItem<TDeliver> | null>;
|
|
84
|
-
readonly initialResults?: readonly RuntimeActionResult[];
|
|
85
|
-
readonly pendingActionKeys: readonly string[] | undefined;
|
|
86
|
-
}): Promise<RuntimeActionResult[] | null>;
|
|
68
|
+
}): RuntimeActionResult[] | undefined;
|
|
87
69
|
/**
|
|
88
70
|
* Resolves one pending runtime-action batch back into model history.
|
|
89
71
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function recordPendingSubagentChildToken(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t===void 0)return e.session;let n={...e.session.state};return n[PENDING_RUNTIME_ACTION_BATCH_KEY]={...t,childContinuationTokens:{...t.childContinuationTokens,[e.callId]:e.childContinuationToken}},{...e.session,state:n}}
|
|
1
|
+
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function recordPendingSubagentChildToken(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t===void 0)return e.session;let n={...e.session.state};return n[PENDING_RUNTIME_ACTION_BATCH_KEY]={...t,childContinuationTokens:{...t.childContinuationTokens,[e.callId]:e.childContinuationToken}},{...e.session,state:n}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results})}function resolveRuntimeActionResultsForKeys(e){let t=new Set(e.pendingKeys),n=new Map;for(let r of e.results){let e=getRuntimeActionResultKey(r);t.has(e)&&n.set(e,r)}let r=[];for(let t of e.pendingKeys){let e=n.get(t);if(e===void 0)return;r.push(e)}return r}async function resolvePendingRuntimeActions(t){let r=getPendingRuntimeActionBatch(t.session.state);if(r===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let i=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(i===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of i)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:r.event.sequence,stepIndex:r.event.stepIndex,turnId:r.event.turnId}));let a={...t.session.state};delete a[PENDING_RUNTIME_ACTION_BATCH_KEY];let o={...t.session,state:Object.keys(a).length>0?a:void 0},s=r.childContinuationTokens;if(s!==void 0)for(let e of i){if(e.kind!==`subagent-result`)continue;let t=s[e.callId];t!==void 0&&(o=clearProxyInputRequestsForChild(o,t))}let c=i.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),l=[...o.history,...r.responseMessages];return c.length>0&&l.push({content:c,role:`tool`}),{messages:l,outcome:`resolved`,session:o}}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null)return{};try{return parseJsonObject(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,recordPendingSubagentChildToken,resolvePendingRuntimeActions,resolveRuntimeActionResultsForKeys,resolveToolCallInputObject,setPendingRuntimeActionBatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.15.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.15.2`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The last ready development-server URL for one app root.
|
|
3
|
+
*
|
|
4
|
+
* The record lets a second interactive `eve dev` attach to the same server.
|
|
5
|
+
* It is not a lock: a stale or malformed record simply causes the caller to
|
|
6
|
+
* start a new server and overwrite it once that server is ready.
|
|
7
|
+
*/
|
|
8
|
+
export declare class DevelopmentServerState {
|
|
9
|
+
#private;
|
|
10
|
+
readonly appRoot: string;
|
|
11
|
+
constructor(project: {
|
|
12
|
+
readonly appRoot: string;
|
|
13
|
+
});
|
|
14
|
+
/** Returns the recorded URL, if the record exists and is valid. */
|
|
15
|
+
read(): Promise<string | undefined>;
|
|
16
|
+
/** Records a server after it is ready to accept clients. */
|
|
17
|
+
write(url: string): Promise<void>;
|
|
18
|
+
/** Clears the record after the listening server has stopped. */
|
|
19
|
+
remove(): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{httpServerUrlSchema}from"#shared/network-address.js";import{join}from"node:path";import{mkdir,readFile,rm,writeFile}from"node:fs/promises";const developmentServerStateSchema=z.object({url:httpServerUrlSchema}).strict();var DevelopmentServerState=class{appRoot;#e;#t;constructor(e){this.appRoot=e.appRoot,this.#e=join(this.appRoot,`.eve`),this.#t=join(this.#e,`dev-server-state.v1.json`)}async read(){let e;try{e=await readFile(this.#t,`utf8`)}catch(e){if(isErrnoException(e,`ENOENT`))return;throw e}try{let t=developmentServerStateSchema.safeParse(JSON.parse(e));return t.success?t.data.url:void 0}catch{return}}async write(e){let t=developmentServerStateSchema.parse({url:e});await mkdir(this.#e,{recursive:!0}),await writeFile(this.#t,`${JSON.stringify(t)}\n`,`utf8`)}async remove(){await rm(this.#t,{force:!0})}};function isErrnoException(e,t){return e instanceof Error&&`code`in e&&e.code===t}export{DevelopmentServerState};
|
|
@@ -1,16 +1,23 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DevelopmentServer, DevelopmentServerOptions, StartedDevelopmentServer } from "#internal/nitro/host/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Rewrites a server URL whose hostname is a wildcard listen address into a
|
|
4
4
|
* loopback URL on the same address family.
|
|
5
5
|
*/
|
|
6
6
|
export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* Creates a development server for an eve application. Call `start()` to boot an
|
|
9
|
+
* owned Nitro server or attach to a running owner, and `close()` to tear down a
|
|
10
|
+
* server this instance started. `close()` waits for an in-progress `start()`,
|
|
11
|
+
* resolves after failed-start cleanup, and is a no-op when it attached to an
|
|
12
|
+
* existing owner or was never started.
|
|
9
13
|
*
|
|
10
|
-
* Authored schedules are never registered with Nitro's cron scheduler in
|
|
11
|
-
*
|
|
14
|
+
* Authored schedules are never registered with Nitro's cron scheduler in dev
|
|
15
|
+
* mode. To fire one authored schedule on demand, `POST` the dev-only
|
|
12
16
|
* `/eve/v1/dev/schedules/:scheduleId` route — the handler returns
|
|
13
17
|
* `{ scheduleId, sessionIds }` so callers can subscribe to the existing
|
|
14
18
|
* per-session stream route.
|
|
15
19
|
*/
|
|
16
|
-
export declare function
|
|
20
|
+
export declare function createDevelopmentServer(rootDir: string, options?: DevelopmentServerOptions & {
|
|
21
|
+
existing?: "reject";
|
|
22
|
+
}): DevelopmentServer<StartedDevelopmentServer>;
|
|
23
|
+
export declare function createDevelopmentServer(rootDir: string, options?: DevelopmentServerOptions): DevelopmentServer;
|