eve 0.58.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +1 -0
- package/dist/src/channel/session.d.ts +2 -0
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +8 -1
- package/dist/src/chunks/{use-eve-agent-X0asmJg-.js → use-eve-agent-Dmc6sX4d.js} +558 -233
- package/dist/src/chunks/{use-eve-agent-CxWcZCsU.js → use-eve-agent-jSR8P4nK.js} +565 -235
- package/dist/src/cli/dev/tui/runner.d.ts +4 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/client/eve-agent-projection.d.ts +10 -0
- package/dist/src/client/eve-agent-projection.js +1 -0
- package/dist/src/client/eve-agent-store-helpers.d.ts +6 -2
- package/dist/src/client/eve-agent-store-helpers.js +2 -2
- package/dist/src/client/eve-agent-store-state.d.ts +54 -1
- package/dist/src/client/eve-agent-store.d.ts +12 -82
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-response.d.ts +5 -1
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/ndjson.d.ts +1 -0
- package/dist/src/client/ndjson.js +2 -2
- package/dist/src/client/open-stream.d.ts +4 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-event-stream.d.ts +30 -0
- package/dist/src/client/session-event-stream.js +1 -0
- package/dist/src/client/session-utils.d.ts +2 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.d.ts +14 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +8 -2
- package/dist/src/client/sessions.js +1 -1
- package/dist/src/client/types.d.ts +7 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -3
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +88 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/index.d.ts +1 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +41 -1
- package/dist/src/compiled/@vercel/sandbox/constants.d.ts +3 -3
- package/dist/src/compiled/@vercel/{sandbox-drives → sandbox}/drive.d.ts +13 -2
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -2
- package/dist/src/compiled/@vercel/sandbox/index.js +15 -9
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +40 -5
- package/dist/src/compiled/_chunks/node/auth-DDrvYko5.js +2 -0
- package/dist/src/compiled/_chunks/node/version-C__MqbLM.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +14 -14
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/evals/context.d.ts +1 -1
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/define-eval.d.ts +1 -1
- package/dist/src/evals/define-eval.js +1 -1
- package/dist/src/evals/index.js +1 -1
- package/dist/src/evals/judge.d.ts +1 -1
- package/dist/src/evals/runner/execute-task.d.ts +1 -1
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/session-manager.d.ts +27 -0
- package/dist/src/evals/session-manager.js +1 -0
- package/dist/src/evals/session.d.ts +8 -28
- package/dist/src/evals/session.js +2 -1
- package/dist/src/evals/target.d.ts +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/evals/types.d.ts +19 -15
- package/dist/src/eve-channel/create-request.d.ts +24 -0
- package/dist/src/eve-channel/create-request.js +1 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.d.ts +3 -12
- package/dist/src/eve-channel/request.js +2 -2
- package/dist/src/eve-channel/types.d.ts +4 -2
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +3 -3
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-sdk-types.d.ts +1 -4
- package/dist/src/execution/sandbox/bindings/vercel.d.ts +1 -2
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/program.d.ts +2 -0
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/session-inbox/protocol.js +1 -1
- package/dist/src/execution/tools/connection-search.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/experimental/evaluate/auto-model.js +2 -2
- package/dist/src/experimental/evaluate/evaluate.d.ts +7 -0
- package/dist/src/experimental/evaluate/evaluate.js +1 -0
- package/dist/src/harness/compaction.d.ts +3 -3
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/request-envelope.d.ts +11 -0
- package/dist/src/harness/request-envelope.js +1 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/instrumentation/prepare-trace-context.d.ts +2 -1
- package/dist/src/instrumentation/prepare-trace-context.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +4 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +2 -0
- package/dist/src/internal/model-auth/transport.d.ts +3 -1
- package/dist/src/internal/model-auth/transport.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.js +1 -1
- package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +1 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.d.ts +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/public/experimental/evaluate/index.d.ts +1 -0
- package/dist/src/public/experimental/evaluate/index.js +1 -1
- package/dist/src/public/models/anthropic/index.js +1 -1
- package/dist/src/public/sandbox/vercel-sandbox.d.ts +1 -1
- package/dist/src/public/sandbox/vercel.d.ts +1 -1
- package/dist/src/public/sandbox/vercel.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/react/use-eve-agent.d.ts +4 -0
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/setup/flows/model-login-connection.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/subagents/handle-dispatch.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +4 -0
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +2 -0
- package/dist/src/tools/definition.js +1 -1
- package/dist/src/tools/durable-callbacks.d.ts +8 -2
- package/dist/src/tools/durable-callbacks.js +1 -1
- package/dist/src/tools/durable-schema.d.ts +16 -0
- package/dist/src/tools/durable-schema.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +4 -0
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +1 -0
- package/docs/channels/eve.mdx +20 -10
- package/docs/concepts/context-control.md +4 -0
- package/docs/concepts/sessions-runs-and-streaming.md +18 -3
- package/docs/evals/assertions.mdx +6 -6
- package/docs/evals/cases.mdx +59 -23
- package/docs/evals/judge.mdx +10 -8
- package/docs/evals/overview.mdx +6 -6
- package/docs/evals/reporters.mdx +1 -1
- package/docs/evals/targets.mdx +5 -0
- package/docs/guides/client/messages.mdx +5 -5
- package/docs/guides/client/overview.mdx +15 -1
- package/docs/guides/dynamic-capabilities.md +22 -0
- package/docs/guides/evaluate.md +58 -4
- package/docs/guides/frontend/overview.mdx +54 -5
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +13 -8
- package/docs/guides/frontend/use-eve-agent-vue.mdx +13 -8
- package/docs/reference/typescript-api.md +38 -36
- package/package.json +2 -3
- package/dist/src/compiled/@vercel/sandbox-drives/LICENSE +0 -201
- package/dist/src/compiled/@vercel/sandbox-drives/_async-retry.d.ts +0 -8
- package/dist/src/compiled/@vercel/sandbox-drives/_workflow-serde.d.ts +0 -5
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/api-client.d.ts +0 -1815
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/api-error.d.ts +0 -29
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/base-client.d.ts +0 -39
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/file-writer.d.ts +0 -66
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/index.d.ts +0 -2
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/validators.d.ts +0 -932
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/with-retry.d.ts +0 -10
- package/dist/src/compiled/@vercel/sandbox-drives/auth/error.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/auth/file.d.ts +0 -18
- package/dist/src/compiled/@vercel/sandbox-drives/auth/index.d.ts +0 -6
- package/dist/src/compiled/@vercel/sandbox-drives/auth/oauth.d.ts +0 -111
- package/dist/src/compiled/@vercel/sandbox-drives/auth/poll-for-token.d.ts +0 -28
- package/dist/src/compiled/@vercel/sandbox-drives/auth/project.d.ts +0 -40
- package/dist/src/compiled/@vercel/sandbox-drives/command.d.ts +0 -292
- package/dist/src/compiled/@vercel/sandbox-drives/constants.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/execution-context.d.ts +0 -116
- package/dist/src/compiled/@vercel/sandbox-drives/filesystem.d.ts +0 -258
- package/dist/src/compiled/@vercel/sandbox-drives/index.d.ts +0 -14
- package/dist/src/compiled/@vercel/sandbox-drives/index.js +0 -9
- package/dist/src/compiled/@vercel/sandbox-drives/network-policy.d.ts +0 -169
- package/dist/src/compiled/@vercel/sandbox-drives/proxy.d.ts +0 -55
- package/dist/src/compiled/@vercel/sandbox-drives/sandbox-user.d.ts +0 -211
- package/dist/src/compiled/@vercel/sandbox-drives/sandbox.d.ts +0 -1287
- package/dist/src/compiled/@vercel/sandbox-drives/session.d.ts +0 -435
- package/dist/src/compiled/@vercel/sandbox-drives/snapshot.d.ts +0 -238
- package/dist/src/compiled/@vercel/sandbox-drives/utils/get-credentials.d.ts +0 -21
- package/dist/src/compiled/@vercel/sandbox-drives/utils/paginator.d.ts +0 -16
- package/dist/src/compiled/@vercel/sandbox-drives/utils/resolveSignal.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/utils/sandbox-snapshot.d.ts +0 -11
- package/dist/src/compiled/@vercel/sandbox-drives/utils/types.d.ts +0 -11
- package/dist/src/compiled/_chunks/node/auth-8aQozzfi.js +0 -2
- package/dist/src/compiled/_chunks/node/auth-Bvv0xGTY.js +0 -2
- package/dist/src/compiled/_chunks/node/esm-Fqlolk7e.js +0 -7
- package/dist/src/compiled/_chunks/node/version-BC6t2Txc.js +0 -1
- package/dist/src/compiled/_chunks/node/version-DSQqVZ5T.js +0 -1
- package/dist/src/compiled/_chunks/node/xdg-app-paths-F-QHrdza.js +0 -1
package/dist/src/evals/target.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveDevDispatchSchedulePath}from"#protocol/routes.js";import{toErrorMessage}from"#shared/errors.js";import"#client/client.js";import{stripNpmPackageScope}from"#shared/package-name.js";import{EvalSessionManager}from"#evals/session.js";import{setTimeout}from"node:timers/promises";async function resolveEvalTargetHandle(e){await waitForTargetHealth(e.client,e.url);let t=await e.client.info();if(assertAgentInfoShape(t,e.url),e.expectedAgentName!==void 0&&!matchesExpectedAgentName(e.expectedAgentName,t.agent.name))throw Error(`Expected eval target ${JSON.stringify(e.expectedAgentName)} at ${e.url}, but ${JSON.stringify(t.agent.name)} is responding there.`);return createEvalTargetHandle({capabilities:capabilitiesFromInfo(t),client:e.client,kind:e.kind,url:e.url})}function createEvalTargetHandle(e){return createHandle({capabilities:e.capabilities,client:e.client,kind:e.kind,sessions:void 0,url:e.url})}function scopeEvalTargetHandle(e,t){return createHandle({capabilities:e.capabilities,client:void 0,delegate:e,kind:e.kind,sessions:t.sessions,url:e.url})}function createHandle(e){let t=e.delegate,n=e.client,fetchTarget=async(e,r)=>{if(t!==void 0)return await t.fetch(e,r);if(n===void 0)throw Error(`Eval target cannot fetch without a client.`);return await n.fetch(e,r)};return{capabilities:e.capabilities,kind:e.kind,url:e.url,async attachSession(r,i){if(e.sessions!==void 0)return await e.sessions.attachSession(r,i);if(t!==void 0)return await t.attachSession(r,i);if(n===void 0)throw Error(`Eval target cannot attach sessions without a client.`);return await new EvalSessionManager({client:n}).attachSession(r,i)},watchTurn(r,i){if(e.sessions!==void 0)return e.sessions.watchTurn(r,i);if(t!==void 0)return t.watchTurn(r,i);if(n===void 0)throw Error(`Eval target cannot watch sessions without a client.`);return new EvalSessionManager({client:n}).watchTurn(r,i)},async dispatchSchedule(t){if(!e.capabilities.devRoutes)throw Error(`target.dispatchSchedule() requires a target with dev routes enabled.`);let n=await fetchTarget(createEveDevDispatchSchedulePath(t),{method:`POST`});if(!n.ok){let e=await readResponseBodySafely(n);throw Error(`Schedule dispatch failed: ${n.status} ${n.statusText}`+(e.length>0?`, ${e}`:``))}return parseScheduleDispatchResult(await n.json())},async fetch(e,t){return await fetchTarget(e,t)}}}function capabilitiesFromInfo(e){return{devRoutes:e.capabilities?.devRoutes??e.mode===`development`}}function matchesExpectedAgentName(e,t){return t===e||t===stripNpmPackageScope(e)}async function waitForTargetHealth(e,t){let n=Date.now()+6e4,r;for(;Date.now()<n;)try{await e.health();return}catch(e){r=toErrorMessage(e),await setTimeout(250)}throw Error(`Timed out waiting for eval target health at ${t}.`+(r===void 0?``:` Last error: ${r}`))}function assertAgentInfoShape(e,t){if(e.kind!==`eve-agent-info`||e.version!==4)throw Error(`Eval target ${t} returned an unrecognized /eve/v1/info payload.`)}function parseScheduleDispatchResult(e){if(typeof e!=`object`||!e||!(`scheduleId`in e)||typeof e.scheduleId!=`string`||!(`sessionIds`in e)||!Array.isArray(e.sessionIds)||e.sessionIds.some(e=>typeof e!=`string`))throw Error(`Schedule dispatch returned an unexpected response shape: ${JSON.stringify(e)}`);return{scheduleId:e.scheduleId,sessionIds:[...e.sessionIds]}}async function readResponseBodySafely(e){try{return(await e.text()).trim()}catch{return``}}export{createEvalTargetHandle,resolveEvalTargetHandle,scopeEvalTargetHandle};
|
|
1
|
+
import{createEveDevDispatchSchedulePath}from"#protocol/routes.js";import{toErrorMessage}from"#shared/errors.js";import"#client/client.js";import{stripNpmPackageScope}from"#shared/package-name.js";import{EvalSessionManager}from"#evals/session-manager.js";import{setTimeout}from"node:timers/promises";async function resolveEvalTargetHandle(e){await waitForTargetHealth(e.client,e.url);let t=await e.client.info();if(assertAgentInfoShape(t,e.url),e.expectedAgentName!==void 0&&!matchesExpectedAgentName(e.expectedAgentName,t.agent.name))throw Error(`Expected eval target ${JSON.stringify(e.expectedAgentName)} at ${e.url}, but ${JSON.stringify(t.agent.name)} is responding there.`);return createEvalTargetHandle({capabilities:capabilitiesFromInfo(t),client:e.client,kind:e.kind,url:e.url})}function createEvalTargetHandle(e){return createHandle({capabilities:e.capabilities,client:e.client,kind:e.kind,sessions:void 0,url:e.url})}function scopeEvalTargetHandle(e,t){return createHandle({capabilities:e.capabilities,client:void 0,delegate:e,kind:e.kind,sessions:t.sessions,url:e.url})}function createHandle(e){let t=e.delegate,n=e.client,fetchTarget=async(e,r)=>{if(t!==void 0)return await t.fetch(e,r);if(n===void 0)throw Error(`Eval target cannot fetch without a client.`);return await n.fetch(e,r)};return{capabilities:e.capabilities,kind:e.kind,url:e.url,async attachSession(r,i){if(e.sessions!==void 0)return await e.sessions.attachSession(r,i);if(t!==void 0)return await t.attachSession(r,i);if(n===void 0)throw Error(`Eval target cannot attach sessions without a client.`);return await new EvalSessionManager({client:n}).attachSession(r,i)},watchTurn(r,i){if(e.sessions!==void 0)return e.sessions.watchTurn(r,i);if(t!==void 0)return t.watchTurn(r,i);if(n===void 0)throw Error(`Eval target cannot watch sessions without a client.`);return new EvalSessionManager({client:n}).watchTurn(r,i)},async dispatchSchedule(t){if(!e.capabilities.devRoutes)throw Error(`target.dispatchSchedule() requires a target with dev routes enabled.`);let n=await fetchTarget(createEveDevDispatchSchedulePath(t),{method:`POST`});if(!n.ok){let e=await readResponseBodySafely(n);throw Error(`Schedule dispatch failed: ${n.status} ${n.statusText}`+(e.length>0?`, ${e}`:``))}return parseScheduleDispatchResult(await n.json())},async fetch(e,t){return await fetchTarget(e,t)}}}function capabilitiesFromInfo(e){return{devRoutes:e.capabilities?.devRoutes??e.mode===`development`}}function matchesExpectedAgentName(e,t){return t===e||t===stripNpmPackageScope(e)}async function waitForTargetHealth(e,t){let n=Date.now()+6e4,r;for(;Date.now()<n;)try{await e.health();return}catch(e){r=toErrorMessage(e),await setTimeout(250)}throw Error(`Timed out waiting for eval target health at ${t}.`+(r===void 0?``:` Last error: ${r}`))}function assertAgentInfoShape(e,t){if(e.kind!==`eve-agent-info`||e.version!==4)throw Error(`Eval target ${t} returned an unrecognized /eve/v1/info payload.`)}function parseScheduleDispatchResult(e){if(typeof e!=`object`||!e||!(`scheduleId`in e)||typeof e.scheduleId!=`string`||!(`sessionIds`in e)||!Array.isArray(e.sessionIds)||e.sessionIds.some(e=>typeof e!=`string`))throw Error(`Schedule dispatch returned an unexpected response shape: ${JSON.stringify(e)}`);return{scheduleId:e.scheduleId,sessionIds:[...e.sessionIds]}}async function readResponseBodySafely(e){try{return(await e.text()).trim()}catch{return``}}export{createEvalTargetHandle,resolveEvalTargetHandle,scopeEvalTargetHandle};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { LanguageModel } from "ai";
|
|
2
2
|
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
|
|
3
3
|
import type { RuntimeIdentity, RuntimeTraceContext, MessageStreamEvent } from "#protocol/message.js";
|
|
4
|
-
import type { CancelSessionResult, ClientSessionState, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
4
|
+
import type { CancelSessionResult, ClientSessionState, CreateSessionOptions, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
5
5
|
import type { InputRequest, InputResponse } from "#shared/input.js";
|
|
6
6
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
7
7
|
import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";
|
|
@@ -240,7 +240,7 @@ export interface EveEvalLiveTurn {
|
|
|
240
240
|
/** Wait until the live stream emits one typed event matching `options`. */
|
|
241
241
|
waitForEvent<TType extends MessageStreamEvent["type"]>(type: TType, options?: EveEvalWaitForEventOptions<TType>): Promise<EveEvalStreamEvent<TType>>;
|
|
242
242
|
}
|
|
243
|
-
/** Operations and state
|
|
243
|
+
/** Operations and state belonging to one accepted session. */
|
|
244
244
|
export interface EveEvalSessionDriver {
|
|
245
245
|
/** All events observed on this session so far. */
|
|
246
246
|
readonly events: readonly MessageStreamEvent[];
|
|
@@ -252,9 +252,9 @@ export interface EveEvalSessionDriver {
|
|
|
252
252
|
/** Input requests left pending by the last parked turn. */
|
|
253
253
|
readonly pendingInputRequests: readonly InputRequest[];
|
|
254
254
|
/** Serializable cursor for resuming this session. */
|
|
255
|
-
readonly state: ClientSessionState
|
|
256
|
-
/**
|
|
257
|
-
readonly sessionId: string
|
|
255
|
+
readonly state: ClientSessionState;
|
|
256
|
+
/** Durable session id, available when the session is returned. */
|
|
257
|
+
readonly sessionId: string;
|
|
258
258
|
/** Request cooperative cancellation of this session's active turn. */
|
|
259
259
|
cancel(): Promise<CancelSessionResult>;
|
|
260
260
|
/** Require exactly one pending input request matching `filter`, or abort dependent control flow. */
|
|
@@ -272,7 +272,7 @@ export interface EveEvalSessionDriver {
|
|
|
272
272
|
/** Send one text turn with a local file attached as a data URL. */
|
|
273
273
|
sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;
|
|
274
274
|
}
|
|
275
|
-
/**
|
|
275
|
+
/** One accepted session, exposed by `t.session()`, turns, and target attachment helpers. */
|
|
276
276
|
export interface EveEvalSession extends EveEvalSessionDriver, EveEvalAssertions, EveEvalOutputAssertions {
|
|
277
277
|
}
|
|
278
278
|
/**
|
|
@@ -283,6 +283,8 @@ export interface EveEvalTurn extends EveEvalAssertions, EveEvalOutputAssertions
|
|
|
283
283
|
readonly events: readonly MessageStreamEvent[];
|
|
284
284
|
readonly inputRequests: readonly InputRequest[];
|
|
285
285
|
readonly message: string | undefined;
|
|
286
|
+
/** Session that owns this turn; use it for follow-up messages. */
|
|
287
|
+
readonly session: EveEvalSession;
|
|
286
288
|
readonly sessionId: string;
|
|
287
289
|
readonly status: "completed" | "failed" | "waiting";
|
|
288
290
|
readonly toolCalls: readonly EveEvalToolCall[];
|
|
@@ -304,7 +306,7 @@ export interface EveEvalJudgeConfig {
|
|
|
304
306
|
* Per-call options for `t.judge.autoevals.*` assertions.
|
|
305
307
|
*/
|
|
306
308
|
export interface JudgeOpts {
|
|
307
|
-
/** Value to grade. Defaults to the
|
|
309
|
+
/** Value to grade. Defaults to the most recently settled turn’s assistant message. */
|
|
308
310
|
readonly on?: unknown;
|
|
309
311
|
/** Judge model for this call only; overrides the eval/config judge model. */
|
|
310
312
|
readonly model?: LanguageModel;
|
|
@@ -330,26 +332,28 @@ export interface JudgeContext {
|
|
|
330
332
|
readonly autoevals: AutoevalsJudges;
|
|
331
333
|
}
|
|
332
334
|
/**
|
|
333
|
-
* The
|
|
334
|
-
*
|
|
335
|
-
* and value-level assertion vocabulary, and exposes `judge` for LLM-as-judge.
|
|
335
|
+
* The context passed to `test(t)`. Creates independent sessions and carries
|
|
336
|
+
* run-level assertions, value-level assertions, and model-backed judges.
|
|
336
337
|
*
|
|
337
338
|
* Scoped assertions (`succeeded`, `calledTool`, …) record an entry evaluated
|
|
338
339
|
* after the test body; `check`, `require`, and `judge` evaluate explicit values.
|
|
339
340
|
*/
|
|
340
|
-
export interface EveEvalContext extends
|
|
341
|
+
export interface EveEvalContext extends EveEvalAssertions {
|
|
341
342
|
/** Eval timeout signal. */
|
|
342
343
|
readonly signal: AbortSignal;
|
|
343
344
|
/** Current target under test. */
|
|
344
345
|
readonly target: EveEvalTargetHandle;
|
|
345
|
-
/** The primary session's last assistant message, or null. */
|
|
346
|
-
readonly reply: string | null;
|
|
347
346
|
/** Structured eval log hook. */
|
|
348
347
|
log(message: string): void;
|
|
349
348
|
/** Pause the eval task, defaulting to 1 second, while respecting the eval timeout signal. */
|
|
350
349
|
sleep(ms?: number): Promise<void>;
|
|
351
|
-
/**
|
|
352
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Create a new session without starting a turn or reading events. Resolves on
|
|
352
|
+
* acceptance with a definite session id and cursor. Every call creates a session.
|
|
353
|
+
*/
|
|
354
|
+
session(options?: CreateSessionOptions): Promise<EveEvalSession>;
|
|
355
|
+
/** Create a new session with its first message and wait for the turn to settle. */
|
|
356
|
+
send(message: SendTurnInput["message"], options?: SendTurnOptions): Promise<EveEvalTurn>;
|
|
353
357
|
/** Apply a value-level assertion (from `eve/evals/expect`) to a value. */
|
|
354
358
|
check(value: unknown, assertion: Assertion): AssertionHandle;
|
|
355
359
|
/** Record an immediate gate and abort dependent control flow when it fails. */
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { UserContent } from "ai";
|
|
2
|
+
import type { ActivityObserverConfig, SessionCallback, SessionCapabilities } from "#channel/types.js";
|
|
3
|
+
import type { JsonObject } from "#shared/json.js";
|
|
4
|
+
import type { RunMode } from "#shared/run-mode.js";
|
|
5
|
+
export interface ParsedCreateBody {
|
|
6
|
+
activityObserver?: ActivityObserverConfig;
|
|
7
|
+
callback?: SessionCallback;
|
|
8
|
+
capabilities?: SessionCapabilities;
|
|
9
|
+
message?: string | UserContent;
|
|
10
|
+
mode?: RunMode;
|
|
11
|
+
context?: readonly string[];
|
|
12
|
+
operationId?: string;
|
|
13
|
+
outputSchema?: JsonObject;
|
|
14
|
+
}
|
|
15
|
+
/** Enforces the fields that only make sense when creation also starts a turn. */
|
|
16
|
+
export declare function validateMessageFreeCreate(input: {
|
|
17
|
+
readonly activityObserver: ActivityObserverConfig | undefined;
|
|
18
|
+
readonly callback: SessionCallback | undefined;
|
|
19
|
+
readonly hasClientContext: boolean;
|
|
20
|
+
readonly hasMessageField: boolean;
|
|
21
|
+
readonly message: string | UserContent | undefined;
|
|
22
|
+
readonly mode: RunMode | undefined;
|
|
23
|
+
readonly outputSchema: JsonObject | undefined;
|
|
24
|
+
}): Response | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function validateMessageFreeCreate(e){if(e.hasMessageField&&e.message===void 0)return Response.json({error:`Expected 'message' to be non-empty when provided.`,ok:!1},{status:400});if(e.message===void 0){if(e.mode===`task`)return Response.json({error:`Task sessions require a non-empty 'message'.`,ok:!1},{status:400});if(e.hasClientContext||e.callback!==void 0||e.activityObserver!==void 0||e.outputSchema!==void 0)return Response.json({error:`Creating a session without a message does not accept 'clientContext', 'callback', 'activityObserver', or 'outputSchema'.`,ok:!1},{status:400})}}export{validateMessageFreeCreate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i)}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({activityObserver:c.activityObserver,audienceAuth:i,auth:v.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:b.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.auth}let p;try{let e=r(o),t=attachClientContext({activityObserver:l.activityObserver,auth:f,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy},l.context);p=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return p.status===`session_not_active`?Response.json({code:`session_not_active`,error:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409}):Response.json({ok:!0,sessionId:p.sessionId,status:`accepted`,deliveryId:p.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:p.sessionId},status:202})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
|
|
1
|
+
import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseOptionalJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i)}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=c.message===void 0?{auth:s.auth}:await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({activityObserver:c.activityObserver,audienceAuth:i,auth:v.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:b.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({activityObserver:l.activityObserver,auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
|
|
@@ -1,20 +1,10 @@
|
|
|
1
1
|
import type { UserContent } from "ai";
|
|
2
|
-
import type { ActivityObserverConfig, SessionAuthContext, SessionCallback,
|
|
2
|
+
import type { ActivityObserverConfig, SessionAuthContext, SessionCallback, TurnPolicy } from "#channel/types.js";
|
|
3
3
|
import type { Session } from "#channel/session.js";
|
|
4
4
|
import { type UploadPolicy } from "#public/channels/upload-policy.js";
|
|
5
5
|
import { type ValidatedInputResponse } from "#shared/input.js";
|
|
6
6
|
import { type JsonObject } from "#shared/json.js";
|
|
7
|
-
import type
|
|
8
|
-
interface ParsedCreateBody {
|
|
9
|
-
activityObserver?: ActivityObserverConfig;
|
|
10
|
-
callback?: SessionCallback;
|
|
11
|
-
capabilities?: SessionCapabilities;
|
|
12
|
-
message: string | UserContent;
|
|
13
|
-
mode?: RunMode;
|
|
14
|
-
context?: readonly string[];
|
|
15
|
-
operationId?: string;
|
|
16
|
-
outputSchema?: JsonObject;
|
|
17
|
-
}
|
|
7
|
+
import { type ParsedCreateBody } from "#eve-channel/create-request.js";
|
|
18
8
|
/** Replay-stable identity for one authenticated create operation. */
|
|
19
9
|
export declare function deriveOperationContinuationToken(input: {
|
|
20
10
|
readonly auth: SessionAuthContext;
|
|
@@ -42,6 +32,7 @@ export declare function parseResetBody(req: Request): Promise<{
|
|
|
42
32
|
readonly reason?: string;
|
|
43
33
|
} | Response>;
|
|
44
34
|
export declare function parseSessionControlBody(req: Request): Promise<Record<string, unknown> | Response>;
|
|
35
|
+
export declare function parseOptionalJsonRequest(req: Request): Promise<Record<string, unknown> | Response>;
|
|
45
36
|
export declare function rejectSessionContinuationToken(payload: Record<string, unknown>): Response | null;
|
|
46
37
|
export declare function requireSessionId(params: Readonly<Record<string, string>>): string | Response;
|
|
47
38
|
export declare function createSessionStreamResponse(request: Request, session: Session): Promise<Response>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{parseSessionCallback}from"#channel/session-callback.js";import{parseActivityObserverField,validateActivityObserverBinding}from"#eve-channel/activity-observer-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){if(e.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseCapabilitiesField(e.capabilities);if(i instanceof Response)return i;let a=parseActivityObserverField(e.activityObserver);if(a instanceof Response)return a;if(a!==void 0){let e=validateActivityObserverBinding(a,r);if(e!==void 0)return e}let o=parseModeField(e.mode);if(o instanceof Response)return o;let s=parseOutputSchemaField(e.outputSchema);if(s instanceof Response)return s;if(t===void 0)return Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400});let c=e.operationId;if(c!==void 0&&(typeof c!=`string`||!c))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let l={activityObserver:a,callback:r,capabilities:i,message:t,mode:o,context:n,outputSchema:s};return typeof c==`string`&&(l.operationId=c),l}function parseSessionMessageBody(e){let t=rejectSessionContinuationToken(e);if(t!==null)return t;let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseActivityObserverField(e.activityObserver);if(i instanceof Response)return i;if(i!==void 0){let e=validateActivityObserverBinding(i,r);if(e!==void 0)return e}let a=parseInputResponses$1(e.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(e.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(e.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(e.turnPolicy);return c instanceof Response?c:n===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):n!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{activityObserver:i,callback:r,message:n,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId,i=t.taskId,a=t.tasks;if(r!==void 0&&(typeof r!=`string`||r.length===0))return Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400});if(a!==void 0&&typeof a!=`boolean`)return Response.json({error:`Expected 'tasks' to be a boolean.`,ok:!1},{status:400});if(i!==void 0&&(typeof i!=`string`||i.length===0))return Response.json({error:`Expected 'taskId' to be a non-empty string.`,ok:!1},{status:400});let o={};return typeof i==`string`&&(o.taskId=i),typeof a==`boolean`&&(o.tasks=a),typeof r==`string`&&(o.turnId=r),o}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=r?await t.getStreamTailIndex():void 0,a=await t.getEventStream({startIndex:n}),o=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,s=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i!==void 0&&s.set(EVE_STREAM_TAIL_INDEX_HEADER,String(i)),new Response(serializeAsNdjson(a,e.signal,streamEventLimit(n,i),o!==void 0),{headers:s})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseTurnPolicyField(e){if(e!==void 0)return e===`queue`||e===`steer`?e:Response.json({error:`Expected 'turnPolicy' to be either 'queue' or 'steer'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
1
|
+
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{parseSessionCallback}from"#channel/session-callback.js";import{parseActivityObserverField,validateActivityObserverBinding}from"#eve-channel/activity-observer-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){if(e.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseCapabilitiesField(e.capabilities);if(i instanceof Response)return i;let a=parseActivityObserverField(e.activityObserver);if(a instanceof Response)return a;if(a!==void 0){let e=validateActivityObserverBinding(a,r);if(e!==void 0)return e}let o=parseModeField(e.mode);if(o instanceof Response)return o;let s=parseOutputSchemaField(e.outputSchema);if(s instanceof Response)return s;let c=validateMessageFreeCreate({activityObserver:a,callback:r,hasClientContext:e.clientContext!==void 0,hasMessageField:`message`in e,message:t,mode:o,outputSchema:s});if(c!==void 0)return c;let l=e.operationId;if(l!==void 0&&(typeof l!=`string`||!l))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let u={activityObserver:a,callback:r,capabilities:i,mode:o,context:n,outputSchema:s};return t!==void 0&&(u.message=t),typeof l==`string`&&(u.operationId=l),u}function parseSessionMessageBody(e){let t=rejectSessionContinuationToken(e);if(t!==null)return t;let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseActivityObserverField(e.activityObserver);if(i instanceof Response)return i;if(i!==void 0){let e=validateActivityObserverBinding(i,r);if(e!==void 0)return e}let a=parseInputResponses$1(e.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(e.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(e.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(e.turnPolicy);return c instanceof Response?c:n===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):n!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{activityObserver:i,callback:r,message:n,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId,i=t.taskId,a=t.tasks;if(r!==void 0&&(typeof r!=`string`||r.length===0))return Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400});if(a!==void 0&&typeof a!=`boolean`)return Response.json({error:`Expected 'tasks' to be a boolean.`,ok:!1},{status:400});if(i!==void 0&&(typeof i!=`string`||i.length===0))return Response.json({error:`Expected 'taskId' to be a non-empty string.`,ok:!1},{status:400});let o={};return typeof i==`string`&&(o.taskId=i),typeof a==`boolean`&&(o.tasks=a),typeof r==`string`&&(o.turnId=r),o}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=r?await t.getStreamTailIndex():void 0,a=await t.getEventStream({startIndex:n}),o=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,s=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i!==void 0&&s.set(EVE_STREAM_TAIL_INDEX_HEADER,String(i)),new Response(serializeAsNdjson(a,e.signal,streamEventLimit(n,i),o!==void 0),{headers:s})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseTurnPolicyField(e){if(e!==void 0)return e===`queue`||e===`steer`?e:Response.json({error:`Expected 'turnPolicy' to be either 'queue' or 'steer'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
2
2
|
${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
|
|
3
3
|
`)),scheduleHeartbeat(e)}catch{clearTimers()}},1e4)},startLease=e=>{scheduleHeartbeat(e),s=setTimeout(()=>{clearTimers();try{e.enqueue(i.encode(`${JSON.stringify(EVE_STREAM_LEASE_ENDED_CONTROL)}\n`)),e.terminate()}catch{}},6e4)},c=new TransformStream({start(e){e.enqueue(i.encode(`
|
|
4
|
-
`)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
|
|
4
|
+
`)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
|
|
@@ -56,7 +56,7 @@ export interface EveMessageContext {
|
|
|
56
56
|
export type EveMessageResult = {
|
|
57
57
|
readonly auth: SessionAuthContext | null;
|
|
58
58
|
readonly context?: readonly string[];
|
|
59
|
-
/**
|
|
59
|
+
/** Sets the title when creating a workflow or sending its first message after prewarming. */
|
|
60
60
|
readonly title?: string;
|
|
61
61
|
};
|
|
62
62
|
/** Synchronous or asynchronous `onMessage` result. */
|
|
@@ -125,7 +125,9 @@ export interface EveChannelInput {
|
|
|
125
125
|
readonly turnPolicy?: TurnPolicy;
|
|
126
126
|
/**
|
|
127
127
|
* Pre-dispatch hook for inbound eve HTTP messages. Runs after route auth and body
|
|
128
|
-
* parsing, before runtime dispatch.
|
|
128
|
+
* parsing, before runtime dispatch. Message-free creation skips this hook and
|
|
129
|
+
* parks before session initialization. The first message supplies auth and context
|
|
130
|
+
* for initialization and its first turn.
|
|
129
131
|
*/
|
|
130
132
|
readonly onMessage?: (ctx: EveMessageContext, message: string | UserContent) => EveMessageResultOrPromise;
|
|
131
133
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.59.0//executeWorkflowProgram`;export{executeWorkflowProgram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{completeLegacyDriverStep}from"./completion-step.js";import{interruptLegacySessionStep}from"./interrupt-step.js";import{prepareLegacySessionStep}from"./prepare-step.js";import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";async function turnWorkflow(e){"use workflow";let t=await prepareLegacySessionStep(e),{sessionId:n}=t.sessionState,r=createSessionInbox(n);try{await r.claimSessionHook(sessionCommandHookToken(n))}catch(e){if(isHookConflictError(e))return;throw e}let{mode:i,sessionWritable:a}=t.input,o;try{await r.claimSessionHooks(sessionHookTokens(t)),o=await interruptLegacySessionStep(t)}catch(e){return await r.dispose(),await failSession({error:e,mode:i,serializedContext:t.serializedContext,sessionId:n,sessionState:t.sessionState,sessionWritable:a})}await runPreparedSession({anchor:{kind:`self`,notify:e=>completeLegacyDriverStep({completionToken:t.input.completionToken,result:e,serializedContext:t.serializedContext,sessionState:t.sessionState,sessionWritable:a})},caller:void 0,capabilities:t.input.capabilities,deploymentId:t.deploymentId,initialInput:t.input.delivery===void 0?void 0:{...t.input.delivery,caller:void 0},mode:i,retention:t.input.retention,serializedContext:o.serializedContext,sessionId:n,sessionState:o.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:a},r)}turnWorkflow.workflowId=`workflow//eve//turnWorkflow`;export{turnWorkflow};
|
|
1
|
+
import{completeLegacyDriverStep}from"./completion-step.js";import{interruptLegacySessionStep}from"./interrupt-step.js";import{prepareLegacySessionStep}from"./prepare-step.js";import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";async function turnWorkflow(e){"use workflow";let t=await prepareLegacySessionStep(e),{sessionId:n}=t.sessionState,r=createSessionInbox(n);try{await r.claimSessionHook(sessionCommandHookToken(n))}catch(e){if(isHookConflictError(e))return;throw e}let{mode:i,sessionWritable:a}=t.input,o;try{await r.claimSessionHooks(sessionHookTokens(t)),o=await interruptLegacySessionStep(t)}catch(e){return await r.dispose(),await failSession({error:e,mode:i,serializedContext:t.serializedContext,sessionId:n,sessionState:t.sessionState,sessionWritable:a})}await runPreparedSession({anchor:{kind:`self`,notify:e=>completeLegacyDriverStep({completionToken:t.input.completionToken,result:e,serializedContext:t.serializedContext,sessionState:t.sessionState,sessionWritable:a})},caller:void 0,capabilities:t.input.capabilities,deploymentId:t.deploymentId,initialInput:t.input.delivery===void 0?void 0:{...t.input.delivery,caller:void 0},awaitFirstMessage:!1,mode:i,retention:t.input.retention,serializedContext:o.serializedContext,sessionId:n,sessionState:o.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:a},r)}turnWorkflow.workflowId=`workflow//eve//turnWorkflow`;export{turnWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConversationContextKey}from"#shared/conversation-context.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ActivityObserverKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicSubagentAgentConfigKey,InitiatorAuthKey,ModeKey,ParentSessionKey,ParentTraceContextKey,ScheduleIdKey,SessionCallbackKey,SessionTitleKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveInstrumentationEnvironment}from"#internal/application/dev-environment.js";import{readConversationId}from"#tracing/conversation-context.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{buildConversationContext}from"#channel/conversation-context.js";function buildRunContext(e){let{bundle:t,run:n}=e,r=new ContextContainer,i=n.auth,a=readConversationId(n.conversationId);if(a!==void 0&&r.set(ConversationIdKey,a),r.set(BundleKey,t),setChannelContext(r,n.adapter,{channelName:n.channelName}),r.set(ConversationContextKey,buildConversationContext(n,resolveInstrumentationEnvironment())),n.parent===void 0){let e=deriveSessionTitle(n.title??n.input.message);e!==void 0&&r.set(SessionTitleKey,e)}if(n.channelMetadata!==void 0){let e=r.get(ChannelInstrumentationKey);r.set(ChannelInstrumentationKey,{channelType:e?.channelType??n.channelMetadata.channelType,kind:e?.kind??n.channelMetadata.kind,metadata:n.channelMetadata.metadata})}n.continuationToken!==void 0&&(r.set(ContinuationTokenKey,n.continuationToken),r.set(ContinuationHookTokensKey,[n.continuationToken])),r.set(ModeKey,n.mode),r.set(AuthKey,i),r.set(InitiatorAuthKey,n.initiatorAuth??i),e.dynamicSubagentAgentConfig!==void 0&&r.set(DynamicSubagentAgentConfigKey,e.dynamicSubagentAgentConfig),n.capabilities!==void 0&&r.set(CapabilitiesKey,n.capabilities),n.requestId!==void 0&&r.set(ChannelRequestIdKey,n.requestId);let o=contextStorage.getStore()?.get(ScheduleIdKey);return o!==void 0&&r.set(ScheduleIdKey,o),n.delivery!==void 0&&r.set(ChannelDeliveryKey,n.delivery),n.callback!==void 0&&r.set(SessionCallbackKey,n.callback),n.activityObserver!==void 0&&r.set(ActivityObserverKey,n.activityObserver),n.parent!==void 0&&r.set(ParentSessionKey,n.parent),n.parentTraceContext!==void 0&&r.set(ParentTraceContextKey,n.parentTraceContext),r}export{buildRunContext};
|
|
1
|
+
import{ConversationContextKey}from"#shared/conversation-context.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ActivityObserverKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicSubagentAgentConfigKey,InitiatorAuthKey,ModeKey,ParentSessionKey,ParentTraceContextKey,ScheduleIdKey,SessionCallbackKey,SessionTitleKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveInstrumentationEnvironment}from"#internal/application/dev-environment.js";import{readConversationId}from"#tracing/conversation-context.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{buildConversationContext}from"#channel/conversation-context.js";function buildRunContext(e){let{bundle:t,run:n}=e,r=new ContextContainer,i=n.auth,a=readConversationId(n.conversationId);if(a!==void 0&&r.set(ConversationIdKey,a),r.set(BundleKey,t),setChannelContext(r,n.adapter,{channelName:n.channelName}),r.set(ConversationContextKey,buildConversationContext(n,resolveInstrumentationEnvironment())),n.parent===void 0){let e=deriveSessionTitle(n.title??n.input.message);e!==void 0&&r.set(SessionTitleKey,e)}if(n.channelMetadata!==void 0){let e=r.get(ChannelInstrumentationKey);r.set(ChannelInstrumentationKey,{channelType:e?.channelType??n.channelMetadata.channelType,kind:e?.kind??n.channelMetadata.kind,metadata:n.channelMetadata.metadata})}n.continuationToken!==void 0&&(r.set(ContinuationTokenKey,n.continuationToken),r.set(ContinuationHookTokensKey,[n.continuationToken])),r.set(ModeKey,n.mode),r.set(AuthKey,i),(n.initiatorAuth!==void 0||n.input.message!==void 0)&&r.set(InitiatorAuthKey,n.initiatorAuth??i),e.dynamicSubagentAgentConfig!==void 0&&r.set(DynamicSubagentAgentConfigKey,e.dynamicSubagentAgentConfig),n.capabilities!==void 0&&r.set(CapabilitiesKey,n.capabilities),n.requestId!==void 0&&r.set(ChannelRequestIdKey,n.requestId);let o=contextStorage.getStore()?.get(ScheduleIdKey);return o!==void 0&&r.set(ScheduleIdKey,o),n.delivery!==void 0&&r.set(ChannelDeliveryKey,n.delivery),n.callback!==void 0&&r.set(SessionCallbackKey,n.callback),n.activityObserver!==void 0&&r.set(ActivityObserverKey,n.activityObserver),n.parent!==void 0&&r.set(ParentSessionKey,n.parent),n.parentTraceContext!==void 0&&r.set(ParentTraceContextKey,n.parentTraceContext),r}export{buildRunContext};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type { VercelCreateOptions,
|
|
1
|
+
import type { VercelCreateOptions, VercelModule, VercelSandbox } from "#execution/sandbox/bindings/vercel-sdk-types.js";
|
|
2
2
|
export declare function deleteVercelSandbox(input: {
|
|
3
3
|
readonly createOptions: VercelCreateOptions;
|
|
4
|
-
readonly loadDeleteSandboxModule: () => Promise<VercelDeleteModule>;
|
|
5
4
|
readonly sandbox: VercelSandbox;
|
|
5
|
+
readonly sandboxModule: VercelModule;
|
|
6
6
|
readonly signal?: AbortSignal;
|
|
7
7
|
}): Promise<void>;
|
|
8
8
|
export declare function deleteUnusableVercelSandbox(input: {
|
|
9
9
|
readonly createOptions: VercelCreateOptions;
|
|
10
|
-
readonly loadDeleteSandboxModule: () => Promise<VercelDeleteModule>;
|
|
11
10
|
readonly sandbox: VercelSandbox;
|
|
11
|
+
readonly sandboxModule: VercelModule;
|
|
12
12
|
}): Promise<void>;
|
|
13
13
|
export declare function stopVercelSandbox(sandbox: VercelSandbox): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getVercelSandboxCredentials,getVercelSandboxFetch}from"#execution/sandbox/bindings/vercel-credentials.js";async function deleteVercelSandbox(e){await stopVercelSandbox(e.sandbox),await deleteVercelSandboxRecord(e)}async function deleteUnusableVercelSandbox(e){await deleteVercelSandboxRecord(e)}async function deleteVercelSandboxRecord(e){let t=await resolveVercelSandboxCredentials(e.createOptions);await(await
|
|
1
|
+
import{getVercelSandboxCredentials,getVercelSandboxFetch}from"#execution/sandbox/bindings/vercel-credentials.js";async function deleteVercelSandbox(e){await stopVercelSandbox(e.sandbox),await deleteVercelSandboxRecord(e)}async function deleteUnusableVercelSandbox(e){await deleteVercelSandboxRecord(e)}async function deleteVercelSandboxRecord(e){let t=await resolveVercelSandboxCredentials(e.createOptions);await(await e.sandboxModule.Sandbox.get({...t,fetch:getVercelSandboxFetch(e.createOptions),name:e.sandbox.name,resume:!1,signal:e.signal})).delete({deleteOrphanSnapshots:!0,signal:e.signal})}async function stopVercelSandbox(e){(e.status===`running`||e.status===`pending`)&&await e.stop()}async function resolveVercelSandboxCredentials(e){try{return await getVercelSandboxCredentials(e)}catch{return{}}}export{deleteUnusableVercelSandbox,deleteVercelSandbox,stopVercelSandbox};
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import type * as Vercel from "#compiled/@vercel/sandbox
|
|
2
|
-
import type * as VercelStable from "#compiled/@vercel/sandbox/index.js";
|
|
1
|
+
import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
|
|
3
2
|
export type VercelCreateOptions = NonNullable<Parameters<typeof Vercel.Sandbox.create>[0]>;
|
|
4
3
|
export type VercelGetOptions = Parameters<typeof Vercel.Sandbox.get>[0];
|
|
5
4
|
export type VercelModule = typeof Vercel;
|
|
6
5
|
export type VercelSandbox = Vercel.Sandbox;
|
|
7
|
-
export type VercelDeleteGetOptions = Parameters<typeof VercelStable.Sandbox.get>[0];
|
|
8
|
-
export type VercelDeleteModule = typeof VercelStable;
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
|
|
2
2
|
import type { VercelSandboxBootstrapUseOptions, VercelSandboxSessionCreateContext, VercelSandboxSessionCreateOptions, VercelSandboxSessionUseOptions } from "#public/sandbox/vercel-sandbox.js";
|
|
3
3
|
import { type CreateVercelSandbox } from "#execution/sandbox/bindings/vercel-create-sdk.js";
|
|
4
|
-
import type { VercelCreateOptions,
|
|
4
|
+
import type { VercelCreateOptions, VercelModule } from "#execution/sandbox/bindings/vercel-sdk-types.js";
|
|
5
5
|
export interface CreateVercelSandboxInput {
|
|
6
6
|
readonly createSandbox?: CreateVercelSandbox;
|
|
7
7
|
readonly createOptions?: VercelCreateOptions;
|
|
8
|
-
readonly loadDeleteSandboxModule?: () => Promise<VercelDeleteModule>;
|
|
9
8
|
readonly loadSandboxModule?: () => Promise<VercelModule>;
|
|
10
9
|
readonly resolveSessionCreateOptions?: (context: VercelSandboxSessionCreateContext) => Promise<VercelSandboxSessionCreateOptions> | VercelSandboxSessionCreateOptions;
|
|
11
10
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{resolveSandboxModelPath}from"#shared/skill-paths.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{streamToBuffer}from"#execution/sandbox/stream-utils.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{adaptMultiplexedCommandToSandboxProcess}from"#execution/sandbox/multiplexed-command.js";import{applyInitialVercelNetworkPolicy,createVercelNetworkPolicySetter,ensureVercelSandboxBaseRuntime,withBaseSetupNetworkPolicy}from"#execution/sandbox/bindings/vercel-base-runtime.js";import{createVercelEveImageSandbox}from"#execution/sandbox/bindings/vercel-create-sdk.js";import{ensureVercelSandboxTags,errorMessage,resolveVercelSandboxTags}from"#execution/sandbox/bindings/vercel-options.js";import{isVercelSandboxMissingError,isVercelSnapshotUnavailableError}from"#execution/sandbox/bindings/vercel-errors.js";import{getNamedVercelSandbox}from"#execution/sandbox/bindings/vercel-lookup.js";import{deleteUnusableVercelSandbox,deleteVercelSandbox,stopVercelSandbox}from"#execution/sandbox/bindings/vercel-lifecycle.js";import{normalizeVercelReadStream}from"#execution/sandbox/bindings/vercel-read-stream.js";function createVercelSandbox(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox
|
|
1
|
+
import{resolveSandboxModelPath}from"#shared/skill-paths.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{streamToBuffer}from"#execution/sandbox/stream-utils.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{adaptMultiplexedCommandToSandboxProcess}from"#execution/sandbox/multiplexed-command.js";import{applyInitialVercelNetworkPolicy,createVercelNetworkPolicySetter,ensureVercelSandboxBaseRuntime,withBaseSetupNetworkPolicy}from"#execution/sandbox/bindings/vercel-base-runtime.js";import{createVercelEveImageSandbox}from"#execution/sandbox/bindings/vercel-create-sdk.js";import{ensureVercelSandboxTags,errorMessage,resolveVercelSandboxTags}from"#execution/sandbox/bindings/vercel-options.js";import{isVercelSandboxMissingError,isVercelSnapshotUnavailableError}from"#execution/sandbox/bindings/vercel-errors.js";import{getNamedVercelSandbox}from"#execution/sandbox/bindings/vercel-lookup.js";import{deleteUnusableVercelSandbox,deleteVercelSandbox,stopVercelSandbox}from"#execution/sandbox/bindings/vercel-lifecycle.js";import{normalizeVercelReadStream}from"#execution/sandbox/bindings/vercel-read-stream.js";function createVercelSandbox(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:DEFAULT_SANDBOX_TIMEOUT_MS,...e.createOptions},r=e.createSandbox??createVercelEveImageSandbox,i=new Map;return{name:`vercel`,async create(a){let o=resolveVercelSandboxTags(n.tags,a.tags),s=a.templateKey===null?null:await readTemplateForCreate({createOptions:n,loadSandboxModule:t,prewarmedTemplates:i,templateKey:a.templateKey}),c=await t(),l={createOptions:n,createSandbox:r,existingMetadata:a.existingMetadata,resolveSessionCreateOptions:e.resolveSessionCreateOptions,sandboxModule:c,sessionId:a.tags?.sessionId??a.sessionKey,sessionKey:a.sessionKey,snapshotId:s?.snapshotId,tags:o},u;try{u=await ensureSession(l)}catch(e){throw s!==null&&isVercelSnapshotUnavailableError(e)?(i.delete(s.templateKey),await(await getNamedVercelSandbox({createOptions:n,sandboxModule:c,sandboxName:s.sandboxName}))?.delete(),new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:s.templateKey})):Error(`Failed to create sandbox session "${a.sessionKey}": ${errorMessage(e)}`,{cause:e})}try{u=await ensureUsableSession({input:l,session:u}),s===null&&u.created&&await applyInitialVercelNetworkPolicy(u.sandbox,n.networkPolicy)}catch(e){throw Error(`Failed to initialize sandbox session "${a.sessionKey}": ${errorMessage(e)}`,{cause:e})}return createHandle({createOptions:n,sandbox:u.sandbox,sandboxModule:c,sessionKey:a.sessionKey})},async prewarm(e){let a;try{a=await ensureTemplateWithUnavailableRetry({bootstrap:e.bootstrap,createOptions:n,createSandbox:r,loadSandboxModule:t,log:e.log,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${errorMessage(t)}`,{cause:t})}return i.set(e.templateKey,a.template),{reused:a.reused}}}}async function ensureTemplateWithUnavailableRetry(e){try{return await ensureTemplate(e)}catch(t){if(!isVercelSnapshotUnavailableError(t)&&!isVercelSandboxMissingError(t))throw t;return e.log?.(`cached template disappeared; rebuilding sandbox template`),await ensureTemplate(e)}}async function readTemplate(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await e.loadSandboxModule(),r=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:n,sandboxName:e.templateKey});if(r===null||typeof r.currentSnapshotId!=`string`)throw new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:e.templateKey}}async function readTemplateForCreate(e){try{return await readTemplate(e)}catch(t){throw SandboxTemplateNotProvisionedError.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${errorMessage(t)}`,{cause:t})}}async function ensureTemplate(e){let t=await e.loadSandboxModule(),n=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:t,sandboxName:e.templateKey}),r=resolveVercelSandboxTags(e.createOptions.tags,e.tags),i=extractAuthorSnapshotId(e.createOptions);if(n!==null&&isUnprovisionedTerminalTemplateSandbox(n,i)&&(await n.delete(),n=null),n===null?n=await e.createSandbox({sandboxModule:t,createOptions:withBaseSetupNetworkPolicy({...e.createOptions,name:e.templateKey,persistent:!0,tags:r})}):await ensureVercelSandboxTags(n,r),typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==i)return{reused:!0,template:{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}};e.log?.(`preparing base runtime inside sandbox`),await ensureVercelSandboxBaseRuntime(n),await applyInitialVercelNetworkPolicy(n,e.createOptions.networkPolicy);let a=buildSandboxSession(createVercelInternalSandboxSession(n,e.templateKey),createVercelNetworkPolicySetter(n));await writeVercelSandboxSeedFiles({sandbox:n,seedFiles:e.seedFiles,session:a}),e.bootstrap!==void 0&&(e.log?.(`running sandbox bootstrap`),await e.bootstrap({use:async t=>(t!==void 0&&await n.update(t),createLoggingSandboxSession({log:e.log,session:a}))}));let o=await n.snapshot();return{reused:!1,template:{sandboxName:n.name,snapshotId:o.snapshotId,templateKey:e.templateKey}}}async function ensureUsableSession(e){try{return await ensureVercelSandboxBaseRuntime(e.session.sandbox),e.session}catch(t){if(e.session.created||!isVercelSnapshotUnavailableError(t))throw t}await deleteUnusableVercelSandbox({createOptions:e.input.createOptions,sandbox:e.session.sandbox,sandboxModule:e.input.sandboxModule});let t=await ensureSession({...e.input,existingMetadata:void 0});return await ensureVercelSandboxBaseRuntime(t.sandbox),t}async function ensureSession(e){let t=getVercelSandboxName(e.existingMetadata)??e.sessionKey,n=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:e.sandboxModule,sandboxName:t});if(n!==null)return await ensureVercelSandboxTags(n,e.tags),{created:!1,sandbox:n};let r=createSessionCreateParams(e,t,await e.resolveSessionCreateOptions?.({session:{id:e.sessionId}}));return e.tags!==void 0&&(r.tags=e.tags),{created:!0,sandbox:await e.createSandbox({createOptions:r,sandboxModule:e.sandboxModule})}}function createSessionCreateParams(e,t,n={}){let r={...e.createOptions,...n};if(e.snapshotId===void 0)return withBaseSetupNetworkPolicy({...r,name:t,persistent:!0});let{image:i,runtime:a,source:o,...s}=r;return{...s,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}}}function createHandle(e){let{sandbox:t,sessionKey:n}=e;return{session:buildSandboxSession(createVercelInternalSandboxSession(t,n),createVercelNetworkPolicySetter(t)),useSessionFn:async e=>(e!==void 0&&await t.update(e),buildSandboxSession(createVercelInternalSandboxSession(t,n),createVercelNetworkPolicySetter(t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:t.name},sessionKey:n}},async delete(n){await deleteVercelSandbox({createOptions:e.createOptions,sandbox:t,sandboxModule:e.sandboxModule,signal:n?.abortSignal})},async stop(){await stopVercelSandbox(t)},async shutdown(){try{await stopVercelSandbox(t)}catch{}}}}function createVercelInternalSandboxSession(e,t){return{id:t,resolvePath:resolveVercelSandboxPath,async spawn(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??WORKSPACE_ROOT,detached:!0,env:t.env,signal:t.abortSignal});return adaptMultiplexedCommandToSandboxProcess({command:n,getOutput:e=>e.stream})},async readFile(t){return normalizeVercelReadStream(await e.readFile({path:t.path}))},async writeFile(t){let n=await streamToBuffer(t.content),r=await resolveVercelWritePath(e,t.path,t.abortSignal);await e.writeFiles([{content:n,path:r}],{signal:t.abortSignal})},async removePath(t){await e.fs.rm(t.path,{force:t.force,recursive:t.recursive,signal:t.abortSignal})}}}async function writeVercelSandboxSeedFiles(e){if(e.seedFiles.length===0)return;let t=await Promise.all(e.seedFiles.map(async t=>({content:typeof t.content==`string`?Buffer.from(t.content):t.content,path:await resolveSandboxModelPath({path:t.path,sandbox:e.session})})));await e.sandbox.writeFiles(t)}function resolveVercelSandboxPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}async function resolveVercelWritePath(e,t,n){let r=await e.runCommand({args:[`-m`,`--`,t],cmd:`realpath`,signal:n}),i=(await r.stdout()).trim();if(r.exitCode!==0||!i.startsWith(`/`)||i.includes(`
|
|
2
2
|
`))throw Error(`Failed to resolve Vercel Sandbox write path: ${t}`);return i}function isUnprovisionedTerminalTemplateSandbox(e,t){let n=e.currentSnapshotId;return typeof n==`string`&&n.length>0&&n!==t?!1:e.status===`aborted`||e.status===`failed`||e.status===`stopped`}function extractAuthorSnapshotId(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function getVercelSandboxName(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}const DEFAULT_SANDBOX_TIMEOUT_MS=18e5;export{createVercelSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{SESSION_INBOX_CONTEXT_KEY,sessionCommandHookToken}from"#execution/session-inbox/address.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{DEFAULT_SESSION_TIMEOUT_MS,sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleContinuationConflictStep}from"#execution/continuation-conflict-step.js";import{signalSessionOwnerActivationStep,validateSessionCheckpointStep}from"#execution/session/handoff-steps.js";async function workflowEntry(e){"use workflow";let t=e.kind===`initial`?await bootInitialOwner(e,getWorkflowMetadata().workflowRunId):await bootHandoffOwner(e);return t===void 0?{output:``}:{output:(await runPreparedSession(t.session,t.inbox)).output}}function stampSessionIdentity(e,t){return{...e,"eve.sessionId":t,[SESSION_INBOX_CONTEXT_KEY]:{sessionId:t}}}async function bootInitialOwner(e,t){let n=stampSessionIdentity(e.serializedContext,t),r=getWritable(),i=n[`eve.mode`],a=createSessionInbox(t),{workflowStartedAt:o}=getWorkflowMetadata(),s=e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS,c=n[`eve.continuationToken`]||``,l=n[`eve.bundle`];try{let[u,d,f]=await Promise.allSettled([createSessionStep({compiledArtifactsSource:l.source,continuationToken:c,dynamicSubagentAgentConfig:n[`eve.dynamicSubagentAgentConfig`],inheritedLimits:e.limits,nodeId:l.nodeId,outputSchema:e.input.outputSchema,rootSessionId:readRootSessionId(n),sessionId:t,taskId:e.taskId}),a.claimSessionHook(sessionCommandHookToken(t)),c===``?Promise.resolve():a.claimSessionHook(c)]);if(u.status===`rejected`)throw u.reason;if(d.status===`rejected`)throw d.reason;if(f.status===`rejected`){if(!isHookConflictError(f.reason))throw f.reason;(e.activityCollectorRunId!==void 0||e.continuationConflictCommand!==void 0)&&await settleContinuationConflictStep({activityCollectorRunId:e.activityCollectorRunId,command:e.continuationConflictCommand,continuationToken:c}),await a.dispose();return}return{inbox:a,session:{anchor:{kind:`self`},caller:hasDelegatedCallerContext(n)?await resolveInitialTurnCallerStep({serializedContext:n}):void 0,capabilities:n[`eve.capabilities`],deploymentId:e.ownerDeploymentId,initialInput:createInitialDelivery(e,n),mode:i,retention:e.retention,serializedContext:n,sessionId:t,sessionState:u.value.state,sessionTimeoutMs:s,sessionTimeoutDeadline:sessionTimeoutDeadline(s,o.getTime()),sessionWritable:r}}}catch(e){return await a.dispose(),await failSession({error:e,mode:i,serializedContext:n,sessionId:t,sessionState:void 0,sessionWritable:r})}}async function bootHandoffOwner(e){let{checkpoint:t,sessionId:n}=e,r=stampSessionIdentity(t.serializedContext,n),i=createSessionInbox(n);try{await validateSessionCheckpointStep({checkpoint:t}),await i.claimSessionHooks(sessionHookTokens({serializedContext:r,sessionState:t.sessionState})),await signalSessionOwnerActivationStep({activation:{kind:`active`},token:e.activationToken})}catch(t){let n=await i.release();await signalSessionOwnerActivationStep({activation:{error:normalizeSerializableError(t),kind:`failed`,payloads:n},token:e.activationToken});return}return{inbox:i,session:{anchor:{kind:`successor`},caller:e.delivery.caller,capabilities:t.capabilities,deploymentId:e.ownerDeploymentId,initialInput:e.delivery,mode:t.mode,retention:t.retention,serializedContext:r,sessionId:n,sessionState:t.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:e.sessionWritable}}}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`}function createInitialDelivery(e,t){return{deliveryMetadata:t[`eve.channelDelivery`]===void 0?void 0:[{...t[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[attachClientContext({message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema},readClientContext(e.input))],requestId:readChannelRequestId(t)}}workflowEntry.workflowId=`workflow//eve//workflowEntry`;export{workflowEntry};
|
|
1
|
+
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{SESSION_INBOX_CONTEXT_KEY,sessionCommandHookToken}from"#execution/session-inbox/address.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{DEFAULT_SESSION_TIMEOUT_MS,sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleContinuationConflictStep}from"#execution/continuation-conflict-step.js";import{signalSessionOwnerActivationStep,validateSessionCheckpointStep}from"#execution/session/handoff-steps.js";async function workflowEntry(e){"use workflow";let t=e.kind===`initial`?await bootInitialOwner(e,getWorkflowMetadata().workflowRunId):await bootHandoffOwner(e);return t===void 0?{output:``}:{output:(await runPreparedSession(t.session,t.inbox)).output}}function stampSessionIdentity(e,t){return{...e,"eve.sessionId":t,[SESSION_INBOX_CONTEXT_KEY]:{sessionId:t}}}async function bootInitialOwner(e,t){let n=stampSessionIdentity(e.serializedContext,t),r=getWritable(),i=n[`eve.mode`],a=createSessionInbox(t),{workflowStartedAt:o}=getWorkflowMetadata(),s=e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS,c=n[`eve.continuationToken`]||``,l=n[`eve.bundle`];try{if(e.input.message===void 0&&i!==`conversation`)throw Error(`A message-free session must use conversation mode.`);let[u,d,f]=await Promise.allSettled([createSessionStep({compiledArtifactsSource:l.source,continuationToken:c,dynamicSubagentAgentConfig:n[`eve.dynamicSubagentAgentConfig`],inheritedLimits:e.limits,nodeId:l.nodeId,outputSchema:e.input.outputSchema,rootSessionId:readRootSessionId(n),sessionId:t,taskId:e.taskId}),a.claimSessionHook(sessionCommandHookToken(t)),c===``?Promise.resolve():a.claimSessionHook(c)]);if(u.status===`rejected`)throw u.reason;if(d.status===`rejected`)throw d.reason;if(f.status===`rejected`){if(!isHookConflictError(f.reason))throw f.reason;(e.activityCollectorRunId!==void 0||e.continuationConflictCommand!==void 0)&&await settleContinuationConflictStep({activityCollectorRunId:e.activityCollectorRunId,command:e.continuationConflictCommand,continuationToken:c}),await a.dispose();return}return{inbox:a,session:{anchor:{kind:`self`},caller:hasDelegatedCallerContext(n)?await resolveInitialTurnCallerStep({serializedContext:n}):void 0,capabilities:n[`eve.capabilities`],deploymentId:e.ownerDeploymentId,initialInput:createInitialDelivery(e,n),awaitFirstMessage:e.input.message===void 0,mode:i,retention:e.retention,serializedContext:n,sessionId:t,sessionState:u.value.state,sessionTimeoutMs:s,sessionTimeoutDeadline:sessionTimeoutDeadline(s,o.getTime()),sessionWritable:r}}}catch(e){return await a.dispose(),await failSession({error:e,mode:i,serializedContext:n,sessionId:t,sessionState:void 0,sessionWritable:r})}}async function bootHandoffOwner(e){let{checkpoint:t,sessionId:n}=e,r=stampSessionIdentity(t.serializedContext,n),i=createSessionInbox(n);try{await validateSessionCheckpointStep({checkpoint:t}),await i.claimSessionHooks(sessionHookTokens({serializedContext:r,sessionState:t.sessionState})),await signalSessionOwnerActivationStep({activation:{kind:`active`},token:e.activationToken})}catch(t){let n=await i.release();await signalSessionOwnerActivationStep({activation:{error:normalizeSerializableError(t),kind:`failed`,payloads:n},token:e.activationToken});return}return{inbox:i,session:{anchor:{kind:`successor`},caller:e.delivery.caller,capabilities:t.capabilities,deploymentId:e.ownerDeploymentId,initialInput:e.delivery,awaitFirstMessage:!1,mode:t.mode,retention:t.retention,serializedContext:r,sessionId:n,sessionState:t.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:e.sessionWritable}}}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`}function createInitialDelivery(e,t){if(e.input.message!==void 0)return{deliveryMetadata:t[`eve.channelDelivery`]===void 0?void 0:[{...t[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[attachClientContext({message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema},readClientContext(e.input))],requestId:readChannelRequestId(t)}}workflowEntry.workflowId=`workflow//eve//workflowEntry`;export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resumeHook}from"#internal/workflow/runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e),n=getSessionTaskIndex(t),r=getAgentHandleStore(t);if([`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>t?.[e]!==void 0))return!1;for(let e of[`eve.runtime.pendingInputBatches`,`eve.runtime.workflowToolRuns`]){let n=t?.[e];if(n!==void 0&&(!Array.isArray(n)||n.length>0))return!1}let i=t?.[`eve.runtime.proxyInputRequests`];return i!==void 0&&(!isObject(i)||Object.keys(i).length>0)?!1:(r
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resumeHook}from"#internal/workflow/runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e),n=getSessionTaskIndex(t),r=getAgentHandleStore(t);if([`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>t?.[e]!==void 0))return!1;for(let e of[`eve.runtime.pendingInputBatches`,`eve.runtime.workflowToolRuns`]){let n=t?.[e];if(n!==void 0&&(!Array.isArray(n)||n.length>0))return!1}let i=t?.[`eve.runtime.proxyInputRequests`];return i!==void 0&&(!isObject(i)||Object.keys(i).length>0)?!1:(r===void 0||r.handles.every(e=>e.phase===`parked`||e.phase===`available`))&&n.every(e=>e.terminalView!==void 0)}async function isSessionIdleForHandoffStep(e){"use step";return isSessionStateIdleForHandoff(e.sessionState)}async function validateSessionCheckpointStep(e){"use step";let{checkpoint:t}=e;if(t.version!==SESSION_CHECKPOINT_VERSION)throw Error(`Unsupported session checkpoint version ${JSON.stringify(t.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Start a new session on this deployment.`);let n=t.sessionTimeoutMs;if(n!==!1&&(typeof n!=`number`||!Number.isFinite(n)||n<0))throw Error(`Session checkpoint contains an invalid timeout duration.`);if((await deserializeContext(t.serializedContext)).require(BundleKey),!isSessionStateIdleForHandoff(t.sessionState))throw Error(`Session checkpoint contains pending work and cannot be handed off.`)}async function signalSessionOwnerActivationStep(e){"use step";await resumeHook(e.token,e.activation)}async function signalSessionAnchorStep(e){"use step";await resumeHook(e.token,e.result)}export{isSessionIdleForHandoffStep,isSessionStateIdleForHandoff,signalSessionAnchorStep,signalSessionOwnerActivationStep,validateSessionCheckpointStep};
|
|
@@ -22,6 +22,8 @@ export interface SessionBoot {
|
|
|
22
22
|
readonly capabilities?: SessionCapabilities;
|
|
23
23
|
readonly deploymentId: string;
|
|
24
24
|
readonly initialInput: DeliverHookPayload | undefined;
|
|
25
|
+
/** Parks on the inbox before any session-scoped lifecycle work. */
|
|
26
|
+
readonly awaitFirstMessage: boolean;
|
|
25
27
|
readonly mode: RunMode;
|
|
26
28
|
readonly retention?: AgentWorkflowRetentionDefinition;
|
|
27
29
|
readonly serializedContext: Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,mode:e.mode,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0};try{let o;try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,mode:e.mode,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async t=>{for(;;){let r=await nextTurnDelivery({cursor:n,deferDeliveries:e.mode===`task`&&t.size>0,expectedAttemptIds:t,inbox:i,queue:o});if(r.kind!==`workflow`)return r;await s.handleWorkflowMessage(r.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t}
|
|
1
|
+
import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,mode:e.mode,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0};try{let o;try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,mode:e.mode,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async t=>{for(;;){let r=await nextTurnDelivery({cursor:n,deferDeliveries:e.mode===`task`&&t.size>0,expectedAttemptIds:t,inbox:i,queue:o});if(r.kind!==`workflow`)return r;await s.handleWorkflowMessage(r.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity(new Set);switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:case`authorization-resume`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,r]=await Promise.allSettled([runInitialAction(),c?.start()]);if(r.status===`rejected`)throw r.reason;if(t.status===`rejected`)throw t.reason;let i=t.value;if(i.kind!==`action`)return i;let o=i.action;for(;;){if(o.kind===`done`)return{kind:`terminal`,outcome:{action:o,kind:`done`}};if(o.cancelled===!0){let t={caller:a.caller,sessionId:e.sessionId},n=await settleCancelledTurn();await notifyCancelledTaskCallerStep(n.usage===void 0?t:{...t,usage:n.usage})}else o.settled!==void 0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:o.settled}),a.caller=void 0);let t=await nextParkedActivity(new Set(o.authorizationAttemptIds??[]));switch(t.kind){case`authorization-resume`:o=await runTurn({delivery:{kind:`deliver`,payloads:t.payloads}});continue;case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:o=await runTurn({control:t.kind});continue;case`cancel-turn`:await cancelDescendantTurnsStep({serializedContext:n.serializedContext,sessionState:n.sessionState}),await settleCancelledTurn(),o={...o,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(t);if(e.kind!==`action`)return e;o=e.action;continue}}}}finally{await c?.dispose()}}export{failSession,runPreparedSession};
|