eve 0.66.0 → 0.66.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/channel/forwarded-principal.d.ts +26 -6
- package/dist/src/channel/forwarded-principal.js +1 -1
- package/dist/src/chunks/{use-eve-agent-BUeSjwIk.js → use-eve-agent-Di1u2zKu.js} +24 -4
- package/dist/src/chunks/{use-eve-agent-ydPlURM4.js → use-eve-agent-PbSMyJ6e.js} +24 -4
- package/dist/src/cli/commands/extension-build.js +1 -1
- package/dist/src/cli/commands/registry-project.d.ts +2 -1
- package/dist/src/cli/commands/registry-project.js +2 -2
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/commands/trace-detail.d.ts +5 -25
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/commands/trace.js +2 -2
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.d.ts +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +2 -2
- package/dist/src/cli/dev/tui/setup-commands.d.ts +3 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.d.ts +14 -0
- package/dist/src/cli/dev/tui/setup-panel.js +4 -4
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +2 -10
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +10 -10
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/open-stream.d.ts +3 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +16 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/evals/session.d.ts +3 -2
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +8 -2
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +12 -4
- package/dist/src/execution/cancel-indexed-session-tasks-step.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/route-child-delivery.js +2 -2
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +12 -10
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/next-input.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step-result.d.ts +3 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step-types.d.ts +7 -2
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/ask-question-workflow.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-preparation.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.d.ts +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-tag-state.d.ts +2 -2
- package/dist/src/harness/workflow-tool-runs.d.ts +33 -5
- package/dist/src/harness/workflow-tool-runs.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.js +1 -1
- package/dist/src/internal/nitro/host/extension-build-lock.d.ts +9 -0
- package/dist/src/internal/nitro/host/extension-build-lock.js +1 -0
- package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -4
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +2 -2
- package/dist/src/internal/nitro/host/workspace-extensions.d.ts +31 -0
- package/dist/src/internal/nitro/host/workspace-extensions.js +1 -0
- package/dist/src/public/next/index.d.ts +10 -7
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/server.d.ts +3 -0
- package/dist/src/public/next/server.js +2 -2
- package/dist/src/self-modification/extension/local-only.d.ts +5 -0
- package/dist/src/self-modification/extension/local-only.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/instructions.js +6 -6
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.d.ts +10 -0
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.js +19 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.d.ts +128 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.d.ts +80 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/registry_add.js +1 -1
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.d.ts +53 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.js +1 -0
- package/dist/src/self-modification/extension/trace-inspection.d.ts +15 -0
- package/dist/src/self-modification/extension/trace-inspection.js +1 -0
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/setup/ask.d.ts +2 -0
- package/dist/src/setup/ask.js +1 -1
- package/dist/src/setup/cli/option-row.d.ts +3 -1
- package/dist/src/setup/cli/option-row.js +1 -1
- package/dist/src/setup/flows/model-login.d.ts +4 -0
- package/dist/src/setup/flows/model-login.js +1 -1
- package/dist/src/setup/integrations/web/setup.d.ts +15 -10
- package/dist/src/setup/integrations/web/setup.js +30 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +7 -3
- package/dist/src/setup/scaffold/create/web-template.js +39 -20
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/subagents/parent-notification.d.ts +1 -1
- package/dist/src/subagents/remote-dispatch.d.ts +1 -0
- package/dist/src/subagents/remote-dispatch.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/delivery-context.js +2 -2
- package/dist/src/tasks/notification.d.ts +6 -0
- package/dist/src/tasks/notification.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/local-trace-analysis.d.ts +51 -0
- package/dist/src/tracing/local-trace-analysis.js +1 -0
- package/dist/src/tracing/local-trace-discovery-index.d.ts +15 -0
- package/dist/src/tracing/local-trace-discovery-index.js +1 -0
- package/dist/src/tracing/local-trace-operations.d.ts +13 -0
- package/dist/src/tracing/local-trace-operations.js +1 -0
- package/dist/src/tracing/local-trace-query.d.ts +17 -0
- package/dist/src/tracing/local-trace-query.js +1 -0
- package/dist/src/tracing/local-trace-span-processor.js +1 -1
- package/dist/src/tracing/local-trace-summary.d.ts +31 -0
- package/dist/src/tracing/local-trace-summary.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/project-structure.mdx +2 -4
- package/docs/concepts/sessions-runs-and-streaming.md +2 -2
- package/docs/evals/cases.mdx +1 -0
- package/docs/extensions.md +3 -1
- package/docs/guides/auth-and-route-protection.md +33 -1
- package/docs/guides/client/streaming.mdx +26 -0
- package/docs/guides/deployment/vercel.mdx +3 -5
- package/docs/guides/frontend/nextjs.mdx +20 -7
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/remote-agents.md +3 -1
- package/docs/install-integrations.mdx +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/subagents/index.mdx +8 -2
- package/package.json +1 -1
- package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +0 -18
- package/dist/src/internal/nitro/host/dev-workspace-extensions.js +0 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +0 -7
- package/dist/src/tasks/session-task-cohorts.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{remoteHost}from"./target.js";import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{TerminalRenderer}from"./terminal-renderer.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{appendUserAgentProduct}from"#internal/user-agent.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function inlineArgumentSuggestions(e){return async t=>{if(t===`model`){let{gatewayModelCapabilities:e}=await import(`#setup/boxes/model-capabilities.js`),{fetchGatewayCatalog:t,modelOptionsFromCatalog:n}=await import(`#setup/boxes/select-model.js`),r=await t().catch(()=>void 0);return n(r).map(t=>{let n=e(r,t.value)?.reasoningLevels;return{value:t.value,label:t.value,hint:t.hint,...n===void 0||n.length===0?{}:{next:[{value:`default`,label:`default`},...n.map(e=>({value:e,label:e}))]}}})}let{browseRegistryCatalog:n}=await import(`#cli/commands/registry.js`);return(await n(e)).items.map(e=>({value:e.address,label:e.name,hint:e.description??e.address}))}}async function startDevelopmentTuiStartup(e){let t=await createDevDiagnostics(e.appRoot).catch(()=>void 0),n=new TerminalRenderer({...e,diagnostics:t,argumentSuggestions:inlineArgumentSuggestions(e.appRoot),onExitRequest:e.onExitRequest});return n.beginStartupDraft({initialDraft:e.initialInput,title:e.name??`eve`}),{diagnostics:t,renderer:n,finish:()=>n.finishStartupDraft(),async shutdown(){n.shutdown(),await t?.close()}}}function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}function withTuiUserAgent(e){let t=new Headers(e);return appendUserAgentProduct(t,`eve-tui/${resolveInstalledPackageInfo().version}`),Object.fromEntries(t.entries())}async function runDevelopmentTui(e){let{target:t,headers:n,initialInput:r,onboard:i,onOnboardingStep:a,onOnboardingTerminal:o,onBootProgress:s,lifecycle:c,startup:l,withExclusiveTerminal:u,...d}=e,f=prepareDevelopmentTarget(t),{serverUrl:p}=t,m={headers:withTuiUserAgent(n)},h=new Client(f.kind===`local`?resolveLocalDevelopmentClientOptions({...m,interactiveClient:!0,serverUrl:p,token:()=>resolveLinkedDevelopmentOidcToken(f.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...m,serverUrl:p,credentials:f.remote.credentials})),g={...d,client:h,serverUrl:p,promptCommandHandler:createPromptCommandHandler({target:t}),availablePromptCommands:promptCommandsFor(t.kind),...t.kind===`local`?{argumentSuggestions:inlineArgumentSuggestions(t.workspaceRoot)}:{},formatTransportError:e=>isVercelAuthChallenge(e)?formatRemoteAuthChallengeMessage(p):toErrorMessage(e)};f.kind===`local`?(g.appRoot=f.target.workspaceRoot,g.probeMcpConnection=probeMcpConnection):g.remote=f.remote,r!==void 0&&(g.initialInput=r),l!==void 0&&(g.renderer=l.renderer,g.startup=l),i!==void 0&&(g.onboard=i),a!==void 0&&(g.onOnboardingStep=a),o!==void 0&&(g.onOnboardingTerminal=o),s!==void 0&&(g.onBootProgress=s),c!==void 0&&(g.lifecycle=c),u!==void 0&&(g.withExclusiveTerminal=u);let _=l?.diagnostics??(f.kind===`local`?await createDevDiagnostics(f.target.workspaceRoot).catch(()=>void 0):void 0);_!==void 0&&(g.diagnostics=_);try{await new EveTUIRunner(g).run()}finally{await _?.close()}}export{runDevelopmentTui,startDevelopmentTuiStartup};
|
|
1
|
+
import{remoteHost}from"./target.js";import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{TerminalRenderer}from"./terminal-renderer.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{appendUserAgentProduct}from"#internal/user-agent.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function inlineArgumentSuggestions(e){return async t=>{if(t===`login`)return[{value:`vercel`,label:`Vercel account`},{value:`chatgpt`,label:`ChatGPT account`},{value:`vercel-api-key`,label:`API key (Vercel AI Gateway)`},{value:`openai-api-key`,label:`API key (OpenAI)`},{value:`anthropic-api-key`,label:`API key (Anthropic)`}];if(t===`model`){let{gatewayModelCapabilities:e}=await import(`#setup/boxes/model-capabilities.js`),{fetchGatewayCatalog:t,modelOptionsFromCatalog:n}=await import(`#setup/boxes/select-model.js`),r=await t().catch(()=>void 0);return n(r).map(t=>{let n=e(r,t.value)?.reasoningLevels;return{value:t.value,label:t.value,hint:t.hint,...n===void 0||n.length===0?{}:{next:[{value:`default`,label:`default`},...n.map(e=>({value:e,label:e}))]}}})}let{browseRegistryCatalog:n}=await import(`#cli/commands/registry.js`);return(await n(e)).items.map(e=>({value:e.address,label:e.name,hint:e.description??e.address}))}}async function startDevelopmentTuiStartup(e){let t=await createDevDiagnostics(e.appRoot).catch(()=>void 0),n=new TerminalRenderer({...e,diagnostics:t,argumentSuggestions:inlineArgumentSuggestions(e.appRoot),onExitRequest:e.onExitRequest});return n.beginStartupDraft({initialDraft:e.initialInput,title:e.name??`eve`}),{diagnostics:t,renderer:n,finish:()=>n.finishStartupDraft(),async shutdown(){n.shutdown(),await t?.close()}}}function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}function withTuiUserAgent(e){let t=new Headers(e);return appendUserAgentProduct(t,`eve-tui/${resolveInstalledPackageInfo().version}`),Object.fromEntries(t.entries())}async function runDevelopmentTui(e){let{target:t,headers:n,initialInput:r,onboard:i,onOnboardingStep:a,onOnboardingTerminal:o,onBootProgress:s,lifecycle:c,startup:l,withExclusiveTerminal:u,...d}=e,f=prepareDevelopmentTarget(t),{serverUrl:p}=t,m={headers:withTuiUserAgent(n)},h=new Client(f.kind===`local`?resolveLocalDevelopmentClientOptions({...m,interactiveClient:!0,serverUrl:p,token:()=>resolveLinkedDevelopmentOidcToken(f.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...m,serverUrl:p,credentials:f.remote.credentials})),g={...d,client:h,serverUrl:p,promptCommandHandler:createPromptCommandHandler({target:t}),availablePromptCommands:promptCommandsFor(t.kind),...t.kind===`local`?{argumentSuggestions:inlineArgumentSuggestions(t.workspaceRoot)}:{},formatTransportError:e=>isVercelAuthChallenge(e)?formatRemoteAuthChallengeMessage(p):toErrorMessage(e)};f.kind===`local`?(g.appRoot=f.target.workspaceRoot,g.probeMcpConnection=probeMcpConnection):g.remote=f.remote,r!==void 0&&(g.initialInput=r),l!==void 0&&(g.renderer=l.renderer,g.startup=l),i!==void 0&&(g.onboard=i),a!==void 0&&(g.onOnboardingStep=a),o!==void 0&&(g.onOnboardingTerminal=o),s!==void 0&&(g.onBootProgress=s),c!==void 0&&(g.lifecycle=c),u!==void 0&&(g.withExclusiveTerminal=u);let _=l?.diagnostics??(f.kind===`local`?await createDevDiagnostics(f.target.workspaceRoot).catch(()=>void 0):void 0);_!==void 0&&(g.diagnostics=_);try{await new EveTUIRunner(g).run()}finally{await _?.close()}}export{runDevelopmentTui,startDevelopmentTuiStartup};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{code;status;body;headers;constructor(e,t,n){let r=t||`Server returned ${e}.`,
|
|
1
|
+
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{code;status;body;headers;constructor(e,t,n){let r=Object.freeze(Object.fromEntries(new Headers(n).entries())),i=r[`content-type`]?.toLowerCase(),a=t||`Server returned ${e}.`,o;try{let e=JSON.parse(t);isObject(e)&&(typeof e.error==`string`&&(a=e.error),typeof e.code==`string`&&(o=e.code))}catch{i?.includes(`text/html`)&&(a=`Server returned ${e} with an HTML response. Check the eve route and development server configuration.`)}super(a),this.name=`ClientError`,this.code=o,this.status=e,this.body=t,this.headers=r}};export{ClientError};
|
|
@@ -26,7 +26,8 @@ interface FollowStreamInput {
|
|
|
26
26
|
readonly streamReadIdleTimeoutMs?: number;
|
|
27
27
|
readonly resolveHeaders: () => Promise<Headers>;
|
|
28
28
|
readonly redirect?: ClientRedirectPolicy;
|
|
29
|
-
|
|
29
|
+
/** eve stream route path, such as a session stream or a parent-origin subagent stream. */
|
|
30
|
+
readonly path: string;
|
|
30
31
|
readonly signal?: AbortSignal;
|
|
31
32
|
readonly startIndex: number;
|
|
32
33
|
/** Follow the live stream after the durable tail (default). `false` bounds the read at the tail. */
|
|
@@ -37,7 +38,7 @@ interface OpenStreamInput extends FollowStreamInput {
|
|
|
37
38
|
readonly requestTailIndex?: boolean;
|
|
38
39
|
}
|
|
39
40
|
/**
|
|
40
|
-
* Follows
|
|
41
|
+
* Follows one durable event stream route from an absolute cursor,
|
|
41
42
|
* transparently reconnecting whenever the transport ends.
|
|
42
43
|
*
|
|
43
44
|
* Transport endings reconnect from the advanced cursor. Progress resets the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{readMessageStreamVersion}from"#client/stream-version.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e,t=!1){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let n=e;return{retryableErrorStatuses:n?.retryableErrorStatuses?new Set(n.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(n?.streamIdleReconnectPolicy,{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:t?1/0:DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy.maxAttempts}),streamOpenReconnectPolicy:resolveRetryPolicy(n?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let resolvePolicy=()=>resolveStreamReconnectPolicy(e.resolveReconnectPolicy===void 0?e.streamReconnectPolicy:e.resolveReconnectPolicy(),e.keepAlive),t=resolvePolicy(),n=t.streamIdleReconnectPolicy,r=e.startIndex,i=n.baseDelayMs,a=0,o=!0,s,c=!1;for(;;){t=resolvePolicy(),n=t.streamIdleReconnectPolicy;let l;try{l=await openStreamBody({...e,retryPolicy:t,startIndex:r,requestTailIndex:(e.follow===!1||e.onCaughtUp!==void 0)&&s===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if((e.follow===!1||e.onCaughtUp!==void 0)&&s===void 0&&(s=l.tailIndex,s===void 0))throw l.close(),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(!c&&s!==void 0&&r>s&&(c=!0,e.onCaughtUp?.()),e.follow===!1&&s!==void 0&&r>s){l.close();return}let u=!1,d=!1;try{for await(let t of readNdjsonStream(l.body,{signal:e.signal,controlVersion:l.controlVersion,idleTimeoutMs:e.streamReadIdleTimeoutMs??15e3,onLeaseEnded:()=>{d=!0},streamVersion:l.streamVersion}))if(r+=1,u=!0,i=n.baseDelayMs,a=0,yield t,!c&&s!==void 0&&r>s&&(c=!0,e.onCaughtUp?.()),e.follow===!1&&s!==void 0&&r>s)return}catch(e){if(!isStreamDisconnectError(e))throw e}finally{l.close()}if(n=resolvePolicy().streamIdleReconnectPolicy,e.signal?.aborted||e.startIndex<0||n.maxAttempts===0)return;if(!d){if(!u&&!o&&(a+=1)>=n.maxAttempts||(o=!1,await sleep(i,e.signal),e.signal?.aborted))return;i=Math.min(i*2,n.maxDelayMs)}}}async function openStreamBody(e){let t=e.retryPolicy??resolveStreamReconnectPolicy(e.streamReconnectPolicy,e.keepAlive),n=t.streamOpenReconnectPolicy,r,i,a,o=n.baseDelayMs,s=e.startIndex>=0&&t.streamIdleReconnectPolicy.maxAttempts>0?EVE_STREAM_CONTROL_VERSION:void 0,c={};s!==void 0&&(c[EVE_STREAM_CONTROL_VERSION_QUERY]=s),e.startIndex!==0&&(c.startIndex=String(e.startIndex)),e.requestTailIndex===!0&&(c.includeTailIndex=`1`);for(let l=0;l<n.maxAttempts;l+=1){e.signal?.throwIfAborted();let u=createClientUrl(e.host,e.path,Object.keys(c).length>0?c:void 0),d=await e.resolveHeaders();e.signal?.throwIfAborted();let f=new AbortController,p=e.signal?AbortSignal.any([e.signal,f.signal]):f.signal,m;try{m=await fetch(u,{cache:`no-store`,headers:d,redirect:e.redirect,signal:p})}catch(t){if(e.signal?.aborted||!isStreamDisconnectError(t)||l===n.maxAttempts-1)throw t;await sleep(o,e.signal),o=Math.min(o*2,n.maxDelayMs);continue}if(m.ok){if(!m.body)throw new ClientError(m.status,`Response body is null.`,m.headers);let e=!1;return{body:m.body,close:()=>{e||(e=!0,m.body?.cancel().catch(()=>{}),f.abort())},controlVersion:s,streamVersion:readMessageStreamVersion(m.headers),tailIndex:parseTailIndexHeader(m.headers)}}if(r=m.status,i=await m.text(),a=m.headers,!t.retryableErrorStatuses.has(m.status))throw new ClientError(m.status,i,m.headers);l<n.maxAttempts-1&&(await sleep(o,e.signal),o=Math.min(o*2,n.maxDelayMs))}throw new ClientError(r??0,i??`Failed to open message stream.`,a)}function parseTailIndexHeader(e){let t=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(t===null||!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody,sleep};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
1
|
+
import type { MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
|
|
2
2
|
import { MessageResponse } from "#client/message-response.js";
|
|
3
3
|
import type { InputResponse } from "#shared/input.js";
|
|
4
4
|
import type { CancelSessionResult, ClearResult, ClientSessionState, CompactResult, ClientRedirectPolicy, CreateSessionOptions, RespondTurnOptions, ResetResult, SendTurnInput, SendTurnOptions, SessionSnapshot, StreamOptions } from "#client/types.js";
|
|
@@ -57,6 +57,21 @@ export declare class ClientSession {
|
|
|
57
57
|
}): Promise<ResetResult>;
|
|
58
58
|
/** Opens this session's durable event stream from its stored cursor. */
|
|
59
59
|
stream(options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
60
|
+
/**
|
|
61
|
+
* Follows one delegated child's durable event stream through this parent session.
|
|
62
|
+
*
|
|
63
|
+
* Pass a `subagent.called` event from this session. The client reads its
|
|
64
|
+
* `childStreamPath` with this session's host and credentials: a local child's
|
|
65
|
+
* own stream route, or the parent-origin proxy for a remote child, which the
|
|
66
|
+
* parent deployment authenticates to the remote agent. Reading the child never
|
|
67
|
+
* advances this session's cursor. The child cursor starts at `0`; pass
|
|
68
|
+
* `startIndex` to resume. Stop at a child turn boundary with
|
|
69
|
+
* `isCurrentTurnBoundaryEvent`.
|
|
70
|
+
*
|
|
71
|
+
* @throws {Error} When `called` belongs to a different session or has no
|
|
72
|
+
* `childStreamPath` because an older eve version recorded it.
|
|
73
|
+
*/
|
|
74
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
60
75
|
[followSession](options: FollowSessionOptions): AsyncIterable<MessageStreamEvent>;
|
|
61
76
|
}
|
|
62
77
|
/** @internal Follow continuously while the frontend owns the session. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),deliveryId:r,sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),
|
|
1
|
+
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath,createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}streamSubagent(e,t){if(e.data.sessionId!==this.#t.sessionId)throw Error(`streamSubagent() requires a subagent.called event from session ${this.#t.sessionId}, but it came from session ${e.data.sessionId}.`);if(typeof e.data.childStreamPath!=`string`)throw Error(`streamSubagent() requires a subagent.called event with childStreamPath, but call ${e.data.callId} has none. The event was recorded by an older eve version.`);let n=t?.startIndex??0;if(t?.follow===!1&&n<0)throw Error(`streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return followStreamIterable({follow:t?.follow,host:this.#e.host,path:e.data.childStreamPath,redirect:this.#e.redirect,resolveHeaders:()=>this.#e.resolveHeaders(),signal:t?.signal,startIndex:n,streamReconnectPolicy:t?.streamReconnectPolicy})}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),deliveryId:r,sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),path:createEveSessionStreamRoutePath(this.#t.sessionId),redirect:this.#e.redirect,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy,resolveReconnectPolicy:e.resolveReconnectPolicy})}};function followClientSession(e,t){return e[followSession](t)}async function postSessionSend(e,t,n){let r=Date.now()+2e4,i=250;for(;;){try{return await postTurn(e,t,n,!1)}catch(e){if(!isSessionNotReady(e))throw e;let t=r-Date.now();if(t<=0)throw e;await sleep(Math.min(i,t),n.signal)}n.signal?.throwIfAborted(),i=Math.min(i*2,2e3)}}async function postCreateSession(e,t){let n=await e.resolveHeaders(t.headers),r=await fetch(createClientUrl(e.host,EVE_SESSION_ROUTE_PATH),{headers:n,method:`POST`,redirect:e.redirect,signal:t.signal??null});if(!r.ok){let e=await r.text();throw new ClientError(r.status,e,r.headers)}return r}function isSessionNotReady(e){return e instanceof ClientError&&e.status===409&&e.code===`session_not_ready`}async function postTurn(e,t,n,r){let i=createMessageBody(n,r);if(i===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let a=await e.resolveHeaders(n.headers);a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(i),headers:a,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!o.ok){let e=await o.text();throw new ClientError(o.status,e,o.headers)}return o}async function readAcceptedMessage(e,t){let n=await e.json(),r=(typeof n.sessionId==`string`?n.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!r)throw Error(`Message route did not return a session id.`);return{sessionId:r,deliveryId:typeof n.deliveryId==`string`&&n.deliveryId.length>0?n.deliveryId:void 0}}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.message!==void 0&&e.taskDeliveryPolicy!==void 0&&(n.taskDeliveryPolicy=e.taskDeliveryPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession,followClientSession};
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"zod": "4.5.4",
|
|
57
57
|
"zod-validation-error": "5.0.0"
|
|
58
58
|
},
|
|
59
|
-
"scriptHash": "
|
|
59
|
+
"scriptHash": "ad64a50e997fe5d72b036c7d4bc8e622f93260a3d5db09a5aa71eb63aac169fe",
|
|
60
60
|
"toolVersions": {
|
|
61
61
|
"rolldown": "1.2.9",
|
|
62
62
|
"typescript": "7.0.2"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ClientSession } from "#client/session.js";
|
|
2
|
-
import type { CancelSessionResult, ClientSessionState, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
3
|
-
import type { MessageStreamEvent, RuntimeTraceContext, TurnFailureStreamEvent } from "#protocol/message.js";
|
|
2
|
+
import type { CancelSessionResult, ClientSessionState, SendTurnInput, SendTurnOptions, StreamOptions } from "#client/types.js";
|
|
3
|
+
import type { MessageStreamEvent, RuntimeTraceContext, SubagentCalledStreamEvent, TurnFailureStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { InputRequest, InputResponse } from "#shared/input.js";
|
|
5
5
|
import { AssertionCollector } from "#evals/assertions/collector.js";
|
|
6
6
|
import type { EveEvalAssertions, EveEvalLiveTurn, EveEvalOutputAssertions, EveEvalSession, EveEvalSessionResult, EveEvalTurn } from "#evals/types.js";
|
|
@@ -39,6 +39,7 @@ export declare class EvalSessionDriver implements EveEvalSession {
|
|
|
39
39
|
get sessionId(): string;
|
|
40
40
|
get state(): ClientSessionState;
|
|
41
41
|
cancel(): Promise<CancelSessionResult>;
|
|
42
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
42
43
|
/** @internal */
|
|
43
44
|
cleanup(signal: AbortSignal): Promise<void>;
|
|
44
45
|
requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
1
|
+
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}streamSubagent(e,t={}){return this.#e.streamSubagent(e,{...t,signal:t.signal??this.#r})}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
`)),this.#g(n,e)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#o,sessionId:e,state:this.#e.state,traceContexts:[...this.#c]}}#m(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#l.has(r)||(this.#l.add(r),this.#c.push(n),!this.#d&&(this.#d=!0,this.#s?.({primary:this.#o,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#h(e){this.#a.push(...e.events),this.#f=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#i,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,session:this,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#u=n,this.#t(this),n}#g(e,t){let n=summarizeTurnEvents(t);return this.#h({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#_(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],output:outputOf(this.#u),status:this.#u?.status??`completed`}}#v(e,t){throw this.#i.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let r=!1;for await(let n of e)if(this.#t.push(n),t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),isCurrentTurnBoundaryEvent(n)){r=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}if(!r)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;session;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.session=e.session,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}export{EvalSessionDriver,EveEvalTurnFailedError};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Experimental_EvaluationModel as EvaluationModel } from "ai";
|
|
2
2
|
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
|
|
3
|
-
import type { RuntimeIdentity, RuntimeTraceContext, MessageStreamEvent } from "#protocol/message.js";
|
|
4
|
-
import type { CancelSessionResult, ClientSessionState, CreateSessionOptions, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
3
|
+
import type { RuntimeIdentity, RuntimeTraceContext, MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
|
|
4
|
+
import type { CancelSessionResult, ClientSessionState, CreateSessionOptions, SendTurnInput, SendTurnOptions, StreamOptions } 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 { TaskStatus } from "#tasks/types.js";
|
|
@@ -274,6 +274,12 @@ export interface EveEvalSessionDriver {
|
|
|
274
274
|
start(message: string, options?: SendTurnOptions): Promise<EveEvalLiveTurn>;
|
|
275
275
|
/** Send one text turn with a local file attached as a data URL. */
|
|
276
276
|
sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;
|
|
277
|
+
/**
|
|
278
|
+
* Follow one delegated child's stream through this parent session, with the
|
|
279
|
+
* eval client's credentials. Local children use their own stream route; remote
|
|
280
|
+
* children use the parent-origin proxy.
|
|
281
|
+
*/
|
|
282
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
277
283
|
}
|
|
278
284
|
/** One accepted session, exposed by `t.session()`, turns, and target attachment helpers. */
|
|
279
285
|
export interface EveEvalSession extends EveEvalSessionDriver, EveEvalAssertions, EveEvalOutputAssertions {
|
|
@@ -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,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({taskDeliveryPolicy:c.taskDeliveryPolicy,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({taskDeliveryPolicy:l.taskDeliveryPolicy,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
|
+
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({taskDeliveryPolicy:c.taskDeliveryPolicy,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({taskDeliveryPolicy:l.taskDeliveryPolicy,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};
|
|
@@ -5,6 +5,7 @@ import type { AuthFn } from "#public/channels/auth.js";
|
|
|
5
5
|
import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
|
|
6
6
|
import type { AudienceContext, Channel, ChannelContinuationOps, ChannelEvents, ChannelMethod } from "#public/definitions/channel.js";
|
|
7
7
|
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
8
|
+
export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
|
|
8
9
|
/**
|
|
9
10
|
* Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
|
|
10
11
|
* has no platform-specific state, so handlers receive optional continuation routing here and the
|
|
@@ -93,12 +94,19 @@ export interface EveChannelInput {
|
|
|
93
94
|
* The trusted-forwarders policy: which transport-authenticated callers may
|
|
94
95
|
* assert a forwarded principal, callback-marked public trace audience, or
|
|
95
96
|
* remote parent lineage. The predicate receives the *verified* route-auth
|
|
96
|
-
* principal of the forwarder
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* permissive predicate lets any authenticated forwarder assert any principal,
|
|
97
|
+
* principal of the forwarder and must match it precisely (for example
|
|
98
|
+
* `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
|
|
99
|
+
* A permissive predicate lets any authenticated forwarder assert any principal,
|
|
100
100
|
* public trace audience, or remote lineage.
|
|
101
101
|
*
|
|
102
|
+
* The second argument carries what the forwarder asserts. `assertion.principal`
|
|
103
|
+
* holds the stamped `current` and `initiator` contexts the forwarder asserts,
|
|
104
|
+
* so a receiver can limit a forwarder to the identities it may speak for, such as
|
|
105
|
+
* one authenticator and issuer. `initiator` takes effect only on session
|
|
106
|
+
* creation; on continuation it is the asserted value, not the session's pinned
|
|
107
|
+
* initiator. `assertion.principal` is absent when the predicate decides remote
|
|
108
|
+
* parent lineage for a request that forwards no principal.
|
|
109
|
+
*
|
|
102
110
|
* When a trusted forwarder's assertion is accepted on session creation, the
|
|
103
111
|
* forwarded principal replaces `session.auth.current` and
|
|
104
112
|
* `session.auth.initiator`. On continuation, only `session.auth.current`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession}from"#execution/session.js";import{cancelOwnedTask}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";const log=createLogger(`execution.cancel-indexed-session-tasks`);async function cancelAllIndexedSessionTasksStep(e){"use step";let t;try{t=readDurableSession(e.sessionState)}catch(t){return logError(log,`failed to read the session for indexed task cancellation`,t,{parentSessionId:e.sessionState.sessionId}),{sessionState:e.sessionState}}let n,r;try{n=getBackgroundTasks(t.state),r=n.query({state:`working`})}catch(n){return logError(log,`failed to read the task index`,n,{parentSessionId:t.sessionId}),{sessionState:e.sessionState}}let i=[];try{i=n.query({state:`cancelled`})}catch(e){logError(log,`failed to read cancelled task outcomes`,e,{parentSessionId:t.sessionId})}let a=[...r,...i].map(e=>e.run);if(a.length===0)return{sessionState:e.sessionState};if(e.serializedContext===void 0)throw Error(`Indexed task cancellation requires serialized runtime context.`);let o=await deserializeContext(e.serializedContext),s=o.require(BundleKey),c=resolveEffectiveAgentRuntime(s,o),l=hydrateDurableSession({durable:t,turnAgent:c.turnAgent}),u=[];for(let n of a)try{let t=await cancelOwnedTask({cancelOwnedWork:cancelBackgroundAgentTask,entry:n,serializedContext:e.serializedContext,session:l});u.push(t)}catch(e){logError(log,`failed to cancel indexed task`,e,{parentSessionId:t.sessionId,taskId:n.task.taskId})}return await recordTerminalTaskViewsStep({serializedContext:e.serializedContext,sessionState:e.sessionState,views:u})}export{cancelAllIndexedSessionTasksStep};
|
|
@@ -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.66.
|
|
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.66.1//executeWorkflowProgram`;export{executeWorkflowProgram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputResolvedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{getPendingCoordinationBatch}from"#harness/coordination.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createInputResolvedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{getPendingCoordinationBatch}from"#harness/coordination.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{createTaskInputRequestId,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{resumeWorkflowToolRunAnswers,resumeWorkflowToolRunDismissal}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";let t=readDurableSession(e.sessionState),n=e.delivery,r=new Map,i=new Map,a,o=n.caller===void 0&&n.taskDeliveryId===void 0,s=new Set;for(let[e,c]of n.payloads.entries()){let l=routeDeliverPayload({allowRoute:(e,n)=>!s.has(e)&&(n.taskId===void 0||getBackgroundTasks(t.state).get(n.taskId)!==void 0),payload:c,resolveMessage:o,state:t.state});a??=l.parentAction,l.forSelf!==void 0&&r.set(e,l.forSelf);for(let[t,r]of l.forChildren.entries()){if(r.answerHook!==void 0)for(let e of r.retireRequestIds)s.add(e);let a=[r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.childResponseUrl??``,r.taskId??``].join(`\0`),o=i.get(a)??{answerHook:r.answerHook,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,childResponseUrl:r.childResponseUrl,dismissedRequestIds:[],metadata:[],payloads:[],retireRequestIds:[],sourcePayloadIndexes:[],taskId:r.taskId},c=o.payloads.length;if(o.payloads.push(r.payload),o.dismissedRequestIds.push(...r.dismissedRequestIds??[]),o.retireRequestIds.push(...r.retireRequestIds),o.sourcePayloadIndexes.push(e),l.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&o.metadata.push({...t,payloadIndex:c});i.set(a,o)}}let c=!1;for(let a of i.values()){let i=a.taskId;if(i!==void 0){let e=getBackgroundTasks(t.state).get(i)?.run;if(e===void 0){mergeStrandedResponses(r,a,i);continue}if(await sendTaskInboundPayload({taskInboxToken:e.address.hookToken,payload:{auth:n.auth,childContinuationToken:a.childContinuationToken,childSessionInbox:a.childSessionInbox,childResponseUrl:a.childResponseUrl,inputResponses:coalesceDeliverPayloads(a.payloads).inputResponses??[],kind:`input-response`,taskId:i}})===`unreachable`){mergeStrandedResponses(r,a,i);continue}t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}if(a.answerHook!==void 0){let n=coalesceDeliverPayloads(a.payloads).inputResponses??[];await resumeWorkflowToolRunAnswers(a.childContinuationToken,n),a.dismissedRequestIds.length>0&&await resumeWorkflowToolRunDismissal(a.childContinuationToken),a.answerHook.question!==void 0&&await emitQuestionResolutions({dismissedRequestIds:a.dismissedRequestIds,responses:n,sessionState:t.state,sessionWritable:e.sessionWritable}),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}let o={...n,deliveryMetadata:a.metadata.length===0?void 0:a.metadata,payloads:a.payloads};await resumeSessionInbox(a.childSessionInbox??a.childContinuationToken,o),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0}let l={serializedContext:e.serializedContext??{},sessionState:c?replaceDurableSessionSnapshot({session:t,state:e.sessionState}):e.sessionState};if(a!==void 0)return{...l,...a};let u=[...r].sort(([e],[t])=>e-t),d=u.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),f=u.length===0?void 0:{...n,deliveryMetadata:d.length===0?void 0:d,payloads:u.map(([,e])=>e)};return{...l,kind:`continue`,remainder:f}}async function emitQuestionResolutions(e){let t=getPendingCoordinationBatch(e.sessionState)?.event;if(t===void 0)return;let n=[...e.responses.map(e=>({kind:`question`,outcome:`answered`,requestId:e.requestId,response:e})),...e.dismissedRequestIds.map(e=>({kind:`question`,outcome:`ignored`,requestId:e}))];if(n.length===0)return;let r=e.sessionWritable.getWriter();try{await r.write(encodeMessageStreamEvent(stampMessageStreamEvent(createInputResolvedEvent({resolutions:n,...t}))))}finally{r.releaseLock()}}function mergeStrandedResponses(e,t,n){for(let[r,i]of t.payloads.entries()){let a=t.sourcePayloadIndexes[r];if(a===void 0)continue;let o=(i.inputResponses??[]).map(e=>({...e,requestId:createTaskInputRequestId(n,e.requestId)}));if(o.length===0)continue;let s=e.get(a);e.set(a,{...s,inputResponses:[...s?.inputResponses??[],...o]})}}export{routeProxiedDeliverStep};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{recordTaskInputRequestStep,recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{emitSubagentEventStep}from"#execution/tools/subagent/emit-event-step.js";import{formatTaskNotification}from"#tasks/notification.js";import{routeProxiedDeliverStep}from"#execution/proxied-deliver-step.js";import{emitRecordedTaskInputRequestStep,runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{acceptTaskAuthorizationEventStep}from"#execution/tools/subagent/accept-event-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.delivery.payloads),n=e.serializedContext,r=e.sessionState,i=new Map,a=new Set((t.task?.views??[]).map(e=>e.taskId));for(let i of t.task?.inputRequests??[]){if(a.has(i.taskId))continue;let t=await recordTaskInputRequestStep({request:i,sessionState:r});if(r=t.sessionState,!t.accepted)continue;let o=await emitRecordedTaskInputRequestStep({sessionWritable:e.sessionWritable,request:t.request,serializedContext:n,sessionState:r});n=o.serializedContext,r=o.sessionState}for(let i of t.task?.agentRequests??[]){if(i.request.kind===`agent-invoke`&&a.has(i.taskId))continue;let t=await applyTaskAgentRequest({...i,ownerId:i.taskId},{sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}for(let i of t.task?.authorizationEvents??[]){if(i.hookPayload.event.type===`authorization.required`&&a.has(i.taskId)||!await acceptTaskAuthorizationEventStep({delivery:i,sessionState:r}))continue;let t=await runProxySubagentEventStep({hookPayload:i.hookPayload,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}if((t.task?.views?.length??0)>0){let a=await recordTerminalTaskViewsStep({serializedContext:n,sessionState:r,views:t.task?.views??[]});n=a.serializedContext,r=a.sessionState;for(let e of a.views)i.set(e.taskId,e);for(let t of a.subagentCompletions){let i=await emitSubagentEventStep({event:t,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=i.serializedContext,r=i.sessionState}}let o=[],
|
|
1
|
+
import{recordTaskInputRequestStep,recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{emitSubagentEventStep}from"#execution/tools/subagent/emit-event-step.js";import{formatTaskNotification,hasRecordedTaskOutcome}from"#tasks/notification.js";import{routeProxiedDeliverStep}from"#execution/proxied-deliver-step.js";import{emitRecordedTaskInputRequestStep,runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{acceptTaskAuthorizationEventStep}from"#execution/tools/subagent/accept-event-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.delivery.payloads),n=e.serializedContext,r=e.sessionState,i=new Map,a=new Set((t.task?.views??[]).map(e=>e.taskId));for(let i of t.task?.inputRequests??[]){if(a.has(i.taskId))continue;let t=await recordTaskInputRequestStep({request:i,sessionState:r});if(r=t.sessionState,!t.accepted)continue;let o=await emitRecordedTaskInputRequestStep({sessionWritable:e.sessionWritable,request:t.request,serializedContext:n,sessionState:r});n=o.serializedContext,r=o.sessionState}for(let i of t.task?.agentRequests??[]){if(i.request.kind===`agent-invoke`&&a.has(i.taskId))continue;let t=await applyTaskAgentRequest({...i,ownerId:i.taskId},{sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}for(let i of t.task?.authorizationEvents??[]){if(i.hookPayload.event.type===`authorization.required`&&a.has(i.taskId)||!await acceptTaskAuthorizationEventStep({delivery:i,sessionState:r}))continue;let t=await runProxySubagentEventStep({hookPayload:i.hookPayload,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}if((t.task?.views?.length??0)>0){let a=await recordTerminalTaskViewsStep({serializedContext:n,sessionState:r,views:t.task?.views??[]});n=a.serializedContext,r=a.sessionState;for(let e of a.views)i.set(e.taskId,e);for(let t of a.subagentCompletions){let i=await emitSubagentEventStep({event:t,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=i.serializedContext,r=i.sessionState}}let o=e.sessionState.snapshot.session.state;if(t.task!==void 0&&hasRecordedTaskOutcome(e.delivery,o))return{kind:`continue`,remainder:void 0,serializedContext:n,sessionState:r};let s=[],c=[];for(let[t,n]of e.delivery.payloads.entries()){let r={...n};if(delete r.task,r.message!==void 0&&n.task?.views!==void 0){let e=n.task.views.flatMap(({taskId:e})=>{let t=i.get(e);return t===void 0?[]:[formatTaskNotification(t)]});e.length===0?delete r.message:r.message=e.join(`
|
|
2
2
|
|
|
3
|
-
`)}if(Object.keys(r).length===0)continue;let a=
|
|
3
|
+
`)}if(Object.keys(r).length===0)continue;let a=s.length;s.push(r);for(let n of e.delivery.deliveryMetadata??[])n.payloadIndex===t&&c.push({...n,payloadIndex:a})}let l=s.length===0?void 0:{...e.delivery,deliveryMetadata:c.length===0?void 0:c,payloads:s};return l===void 0?{kind:`continue`,remainder:void 0,serializedContext:n,sessionState:r}:r.hasProxyInputRequests?await routeProxiedDeliverStep({delivery:l,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r}):{kind:`continue`,remainder:l,serializedContext:n,sessionState:r}}export{routeDeliverToChildren};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isWorkflowMessage}from"#execution/session-inbox/inbox.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{cancelAllIndexedSessionTasksStep}from"#execution/cancel-indexed-session-tasks-step.js";import{SessionInboxPayloadError,decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{reportDroppedWirePayloadStep}from"#execution/report-dropped-wire-payload-step.js";import{findRunningAgentHandle}from"#subagents/handles/query.js";async function admitSessionInboxPayload(e,t){if(e.kind===`runtime-action-result`)return{kind:`runtime-action-result`,payload:e};if(isWorkflowMessage(e))return{kind:`workflow`,message:e};if(e.kind===`authorization-callback`)return t.queue.enqueueAuthorization(e.payloads),{kind:`consumed`};if(e.kind===`subagent-input-request`||e.kind===`subagent-authorization-event`){let n=findRunningAgentHandle(t.cursor.sessionState.snapshot.session.state,{callId:e.callId});return n?.identity.name===e.subagentName&&n.address.sessionId===e.childSessionId&&await t.cursor.apply(await runProxySubagentEventStep({hookPayload:e,sessionWritable:t.cursor.sessionWritable,serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState})),{kind:`consumed`}}let n;try{n=decodeSessionInboxPayload(e)}catch(e){if(!(e instanceof SessionInboxPayloadError))throw e;return await reportDroppedWirePayloadStep({detail:e.message,family:`session-inbox`}),{kind:`consumed`}}switch(n.kind){case`deliver`:{let e=t.queue.enqueueDelivery(n);return e===void 0?{kind:`consumed`}:{admission:e,kind:`delivery`}}case`clear`:case`compact`:return t.queue.enqueueControl(n.kind),{kind:`consumed`};case`session-timeout`:return n.ownerRunId===getWorkflowMetadata().workflowRunId&&t.queue.enqueueControl(`expired`),{kind:`consumed`};case`reset`:return t.queue.enqueueControl(`reset`),{command:{kind:`cancel`},kind:`cancel`};case`cancel`:return{command:n,kind:`cancel`}}}async function applySessionCancellation(e,t){if(e.tasks===!0){let e=await cancelAllIndexedSessionTasksStep({serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState});await t.cursor.apply(e)}e.taskId!==void 0&&t.queue.cancelTask(e.taskId)}export{admitSessionInboxPayload,applySessionCancellation};
|
|
1
|
+
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isWorkflowMessage}from"#execution/session-inbox/inbox.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{cancelAllIndexedSessionTasksStep}from"#execution/cancel-indexed-session-tasks-step.js";import{SessionInboxPayloadError,decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{reportDroppedWirePayloadStep}from"#execution/report-dropped-wire-payload-step.js";import{findRunningAgentHandle}from"#subagents/handles/query.js";async function admitSessionInboxPayload(e,t){if(e.kind===`runtime-action-result`)return{kind:`runtime-action-result`,payload:e};if(isWorkflowMessage(e))return{kind:`workflow`,message:e};if(e.kind===`authorization-callback`)return t.queue.enqueueAuthorization(e.payloads),{kind:`consumed`};if(e.kind===`subagent-input-request`||e.kind===`subagent-authorization-event`){let n=findRunningAgentHandle(t.cursor.sessionState.snapshot.session.state,{callId:e.callId});return n?.identity.name===e.subagentName&&n.address.sessionId===e.childSessionId&&await t.cursor.apply(await runProxySubagentEventStep({hookPayload:e,sessionWritable:t.cursor.sessionWritable,serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState})),{kind:`consumed`}}let n;try{n=decodeSessionInboxPayload(e)}catch(e){if(!(e instanceof SessionInboxPayloadError))throw e;return await reportDroppedWirePayloadStep({detail:e.message,family:`session-inbox`}),{kind:`consumed`}}switch(n.kind){case`deliver`:{let e=t.queue.enqueueDelivery(n,t.cursor.sessionState.snapshot.session.state);return e===void 0?{kind:`consumed`}:{admission:e,kind:`delivery`}}case`clear`:case`compact`:return t.queue.enqueueControl(n.kind),{kind:`consumed`};case`session-timeout`:return n.ownerRunId===getWorkflowMetadata().workflowRunId&&t.queue.enqueueControl(`expired`),{kind:`consumed`};case`reset`:return t.queue.enqueueControl(`reset`),{command:{kind:`cancel`},kind:`cancel`};case`cancel`:return{command:n,kind:`cancel`}}}async function applySessionCancellation(e,t){if(e.tasks===!0){let e=await cancelAllIndexedSessionTasksStep({serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState});await t.cursor.apply(e),t.queue.discardStaleNotifications(t.cursor.sessionState.snapshot.session.state)}e.taskId!==void 0&&t.queue.cancelTask(e.taskId)}export{admitSessionInboxPayload,applySessionCancellation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyDelegatedParentStep,notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#subagents/callback-step.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#subagents/parent-result.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&await terminateChildSessionsStep({serializedContext:n,sessionState:r}),e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId});let i=settledResult(e);if(t.mode===`task`)await fireSessionCallbackStep({error:i.isError?i.output:void 0,output:i.isError?void 0:i.output,serializedContext:n,status:i.isError?`failed`:`completed`,usage:i.sessionUsage}),await notifyDelegatedParentStep({result:i.isError?createDelegatedSubagentErrorResult(n,i.output):createDelegatedSubagentSuccessResult(n,i.output),serializedContext:n,usage:i.sessionUsage});else if(t.caller!==void 0){let e={output:i.output,usage:i.turnUsage};i.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:i.isError,output:i.output}}function settledResult(e){switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return{isError:!1,output:``};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error)}}}export{finalizeSession};
|
|
1
|
+
import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyDelegatedParentStep,notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{getSessionTokenUsage,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{fireSessionCallbackStep}from"#subagents/callback-step.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#subagents/parent-result.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&await terminateChildSessionsStep({serializedContext:n,sessionState:r}),e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId});let i=settledResult(e,t);if(t.mode===`task`)await fireSessionCallbackStep({error:i.isError?i.output:void 0,output:i.isError?void 0:i.output,serializedContext:n,status:i.isError?`failed`:`completed`,usage:i.sessionUsage}),await notifyDelegatedParentStep({result:i.isError?createDelegatedSubagentErrorResult(n,i.output):createDelegatedSubagentSuccessResult(n,i.output),serializedContext:n,usage:i.sessionUsage});else if(t.caller!==void 0){let e={output:i.output,usage:i.turnUsage};i.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:i.isError,output:i.output,usage:i.sessionUsage,usageDelta:i.turnUsage}}function settledResult(e,t){let n=t.cursor.sessionState?.snapshot.session,r=n===void 0||t.caller===void 0?{}:{sessionUsage:toUsage(getSessionTokenUsage(n)),turnUsage:takeSessionUsageDelta(n).delta};switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return t.caller===void 0?{isError:!1,output:``}:{isError:!0,output:`The session ended before the delegated task completed.`,...r};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error),...r}}}export{finalizeSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.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{
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.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{getBackgroundTasks,getBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getResolvedRuntimeAgentNode}from"#runtime/graph.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e),n=getBackgroundTasks(t).query(),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;let i=t?.[`eve.runtime.pendingInputBatches`];if(i!==void 0&&(!Array.isArray(i)||i.length>0))return!1;let a=t?.[`eve.runtime.proxyInputRequests`];return a!==void 0&&(!isObject(a)||Object.keys(a).length>0)?!1:(r===void 0||r.handles.every(e=>e.phase===`parked`||e.phase===`available`))&&getBlockingWorkflowToolRuns(t).length===0&&n.every(e=>e.status!==`working`)}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.`);let r=(await deserializeContext(t.serializedContext)).require(BundleKey),i=readDurableSession(t.sessionState).sandboxState?.session;if(i!=null){let e=getResolvedRuntimeAgentNode(r.graph,r.nodeId).sandboxRegistry.sandbox.inheritance?.definition??getResolvedRuntimeAgentNode(r.graph,r.nodeId).sandboxRegistry.sandbox.definition;if(e.kind!==`independent`)throw Error(`Session checkpoint sandbox has no resolved provider.`);let t=getSandboxEnvironmentRuntime(e.environment);if(i.providerName!==t.providerName||i.stateProtocolVersion!==t.stateProtocolVersion)throw Error(`Session checkpoint sandbox provider state is incompatible.`)}if(!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};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
+
import type { SessionStateMap } from "#harness/types.js";
|
|
1
2
|
import type { TaskDeliveryPolicy, DeliverHookPayload, DeliverPayload } from "#channel/types.js";
|
|
2
|
-
import type { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";
|
|
3
3
|
export type SessionControl = "clear" | "compact" | "expired" | "reset";
|
|
4
|
-
type TaskCohorts = ReturnType<typeof getSessionTaskCohorts>;
|
|
5
4
|
export interface DeliveryAdmission {
|
|
6
5
|
readonly delivery: DeliverHookPayload;
|
|
7
6
|
readonly sequence: number;
|
|
@@ -29,8 +28,7 @@ export type SessionInputSelection = TurnSelection | {
|
|
|
29
28
|
* Ordered, admitted session input, plus the idempotency and cancellation
|
|
30
29
|
* facts for task deliveries this owner has seen. Entries are private; callers
|
|
31
30
|
* receive typed admission and selection values. Everything here is rebuilt
|
|
32
|
-
* deterministically on replay
|
|
33
|
-
* handoff requires every indexed task to be terminal.
|
|
31
|
+
* deterministically on replay. Indexed task outcomes live in session state.
|
|
34
32
|
*/
|
|
35
33
|
export declare class SessionInputQueue {
|
|
36
34
|
private readonly entries;
|
|
@@ -38,8 +36,8 @@ export declare class SessionInputQueue {
|
|
|
38
36
|
private readonly seenTaskDeliveryIds;
|
|
39
37
|
private nextSequence;
|
|
40
38
|
get pendingCount(): number;
|
|
41
|
-
/**
|
|
42
|
-
enqueueDelivery(delivery: DeliverHookPayload): DeliveryAdmission | undefined;
|
|
39
|
+
/** Drops notifications the model must not see; lifecycle envelopes are always admitted. */
|
|
40
|
+
enqueueDelivery(delivery: DeliverHookPayload, state?: SessionStateMap): DeliveryAdmission | undefined;
|
|
43
41
|
/** A caller's own task id counts as seen so its echo is not admitted twice. */
|
|
44
42
|
rememberTask(taskId: string): void;
|
|
45
43
|
isTaskCancelled(taskId: string): boolean;
|
|
@@ -50,10 +48,12 @@ export declare class SessionInputQueue {
|
|
|
50
48
|
/** Task lifecycle effects must be applied even while their cohort report is held. */
|
|
51
49
|
taskDeliveries(): readonly DeliveryAdmission[];
|
|
52
50
|
replaceDelivery(sequence: number, delivery: DeliverHookPayload | undefined): void;
|
|
53
|
-
/**
|
|
51
|
+
/** Revokes model wakeups for a cancelled task; its lifecycle envelopes still reach routing. */
|
|
54
52
|
cancelTask(taskId: string): void;
|
|
53
|
+
/** After cancellation records outcomes, queued notifications for those tasks are stale. */
|
|
54
|
+
discardStaleNotifications(state: SessionStateMap | undefined): void;
|
|
55
55
|
takeSteering(admitted: ReadonlySet<number>, callerCallId: string | undefined): TurnSelection | undefined;
|
|
56
|
-
takeNext(
|
|
56
|
+
takeNext(state: SessionStateMap | undefined, options?: {
|
|
57
57
|
readonly deferDeliveries?: boolean;
|
|
58
58
|
readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
|
|
59
59
|
/**
|
|
@@ -68,8 +68,10 @@ export declare class SessionInputQueue {
|
|
|
68
68
|
}): SessionInputSelection | undefined;
|
|
69
69
|
private nextActionableIndex;
|
|
70
70
|
private takeSelectionAt;
|
|
71
|
-
private
|
|
71
|
+
private isCancelledDelivery;
|
|
72
|
+
/** A cancelled task's notification never reaches the model. */
|
|
73
|
+
private isCancelledNotification;
|
|
74
|
+
private discardDeliveries;
|
|
72
75
|
private retain;
|
|
73
76
|
}
|
|
74
77
|
export declare function isSteeringDelivery(delivery: DeliverHookPayload, callerCallId: string | undefined): boolean;
|
|
75
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e){let
|
|
1
|
+
import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{hasRecordedTaskOutcome,taskIdOfDelivery}from"#tasks/notification.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e,t){if(isStaleNotification(e,t))return;let n=taskDeliveryId(e);if(n!==void 0){let t=terminalTaskId(e),r=t===void 0?n:`${t}:ready`;if(this.seenTaskDeliveryIds.has(r)||this.isCancelledNotification(e))return;this.seenTaskDeliveryIds.add(r)}let r={delivery:e,sequence:this.nextSequence++};return this.entries.push({...r,kind:`delivery`}),r}rememberTask(e){this.seenTaskDeliveryIds.add(e)}isTaskCancelled(e){return this.cancelledTaskIds.has(e)}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}taskDeliveries(){return this.entries.filter(e=>e.kind===`delivery`&&!isNotificationOnly(e.delivery))}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0||this.isCancelledNotification(t)){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}cancelTask(e){this.cancelledTaskIds.add(e),this.discardDeliveries(e=>this.isCancelledNotification(e))}discardStaleNotifications(e){this.discardDeliveries(t=>isStaleNotification(t,e))}takeSteering(e,t){let n=this.entries.filter(n=>n.kind===`delivery`&&e.has(n.sequence)&&isSteeringDelivery(n.delivery,t));if(n.length!==0)return this.retain(e=>e.kind!==`delivery`||!n.includes(e)),{delivery:combine(n),handoffEligible:!1,kind:`turn`,sequences:n.map(({sequence:e})=>e)}}takeNext(e,t){let n=t?.expectedAttemptIds??new Set;if(this.retain(e=>e.kind!==`authorization`||n.has(e.attemptId)),n.size>0){let e=new Map(this.entries.flatMap(e=>e.kind===`authorization`?[[e.attemptId,e.payload]]:[]));if([...n].every(t=>e.has(t)))return this.retain(e=>e.kind!==`authorization`),{kind:`authorization-resume`,payloads:[...n].map(t=>e.get(t))}}let r=getBackgroundTasks(e),i=new Set(r.query({state:`working`}).filter(({taskId:e})=>!this.seenTaskDeliveryIds.has(`${e}:ready`)&&!this.cancelledTaskIds.has(e)).map(e=>e.cohortId)),a=this.nextActionableIndex(r,i,t?.deferDeliveries===!0,t?.taskDeliveryPolicy??`cohort`);if(!(a<0))return this.takeSelectionAt(a,r,t?.freshSequence)}nextActionableIndex(e,t,n,r){return this.entries.findIndex(i=>{if(i.kind===`control`)return!0;if(i.kind===`authorization`||n||this.isCancelledDelivery(i.delivery))return!1;let a=terminalCohort(i.delivery,e);return r===`auto`||a===void 0||!t.has(a)})}takeSelectionAt(e,t,n){let r=this.entries[e];if(r.kind!==`delivery`)return this.entries.splice(e,1),r.kind===`control`?{control:r.control,kind:`control`}:{kind:`authorization-resume`,payloads:[r.payload]};let i=terminalCohort(r.delivery,t);if(i!==void 0){let r=this.entries.findLastIndex(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===i),a=this.entries.findIndex((n,i)=>i>e&&i<r&&(n.kind!==`delivery`||!this.isCancelledDelivery(n.delivery)&&terminalCohort(n.delivery,t)===void 0));if(a>=0)return this.takeSelectionAt(a,t,n)}let a=this.entries.splice(e,1)[0];if(a.kind!==`delivery`)throw Error(`Selected a non-delivery entry as a turn.`);let o=[a],s=terminalCohort(a.delivery,t);if(s!==void 0){let e=this.entries.filter(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===s);o.push(...e),this.retain(t=>t.kind!==`delivery`||!e.includes(t))}else{let t=a.delivery.auth!=null&&a.delivery.auth.principalType!==`anonymous`,n=a.delivery.caller;for(;this.entries.length>e;){let r=this.entries[e];if(r?.kind!==`delivery`||a.delivery.taskDeliveryId!==void 0||r.delivery.taskDeliveryId!==void 0||!t||!jsonValuesEqual(a.delivery.auth,r.delivery.auth)||n!==void 0&&r.delivery.caller!==void 0)break;o.push(this.entries.splice(e,1)[0]),n??=r.delivery.caller}}let c=o.map(({sequence:e})=>e),l=combine(o);return{delivery:l,handoffEligible:c.length===1&&c[0]===n&&l.caller===void 0&&taskDeliveryId(l)===void 0&&this.entries.length===0,kind:`turn`,sequences:c}}isCancelledDelivery(e){let t=taskDeliveryId(e);return t!==void 0&&this.cancelledTaskIds.has(taskIdOfDelivery(t))}isCancelledNotification(e){return isNotificationOnly(e)&&this.isCancelledDelivery(e)}discardDeliveries(e){this.retain(t=>t.kind!==`delivery`||!e(t.delivery))}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isNotificationOnly(e){return e.payloads.every(e=>e.task===void 0)}function isStaleNotification(e,t){return isNotificationOnly(e)&&hasRecordedTaskOutcome(e,t)}function isSteeringDelivery(e,t){return e.taskDeliveryId===void 0&&(e.turnPolicy??`steer`)===`steer`&&(e.caller===void 0||e.caller.callId===t)}function combine(e){if(e.length===1)return e[0].delivery;let t=e.map(({delivery:e})=>e),n=t.flatMap(e=>e.taskDeliveryIds??(e.taskDeliveryId===void 0?[]:[e.taskDeliveryId]));return{...coalesceDeliveries(t),taskDeliveryIds:n.length>0?n:void 0}}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}function taskDeliveryId(e){return e.taskDeliveryId??e.caller?.taskId}function terminalCohort(e,t){let n=terminalTaskId(e);return n===void 0?void 0:t.get(n)?.cohortId}function terminalTaskId(e){if(e.caller===void 0)for(let t of[`completed`,`failed`,`cancelled`]){let n=`:ready:${t}`;if(e.taskDeliveryId?.endsWith(n))return e.taskDeliveryId.slice(0,-n.length)}}export{SessionInputQueue,isSteeringDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";
|
|
1
|
+
import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){for(let{delivery:e,sequence:t}of r.taskDeliveries()){let i=await routeDeliverToChildren({delivery:e,sessionWritable:n.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});if(await n.apply(i),r.replaceDelivery(t,i.kind===`cancel-turn`?void 0:i.remainder),i.kind===`cancel-turn`)return i}let a=r.takeNext(n.sessionState.snapshot.session.state,{deferDeliveries:e.deferDeliveries,taskDeliveryPolicy:n.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME]===`auto`?`auto`:`cohort`,expectedAttemptIds:e.expectedAttemptIds,freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`authorization-resume`)return a;if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);switch(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind){case`workflow`:return{kind:`workflow`,message:c.message};case`cancel`:await applySessionCancellation(c.command,e)}}}export{nextTurnDelivery};
|
|
@@ -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},o;try{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,o)}}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,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;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
|
|
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},o;try{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,o)}}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,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;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?.notifyCaller===!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};
|