eve 0.30.7 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +5 -6
- package/dist/src/acp/adapter.d.ts +10 -4
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/channel/adapter-context.d.ts +1 -1
- package/dist/src/channel/adapter.d.ts +2 -4
- package/dist/src/channel/adapter.js +1 -1
- package/dist/src/channel/channel-address.d.ts +58 -0
- package/dist/src/channel/channel-address.js +1 -0
- package/dist/src/channel/channel-operations.d.ts +72 -0
- package/dist/src/channel/channel-operations.js +1 -0
- package/dist/src/channel/compiled-channel.d.ts +10 -6
- package/dist/src/channel/cross-channel-receive.d.ts +13 -25
- package/dist/src/channel/cross-channel-receive.js +2 -2
- package/dist/src/channel/receive-target.d.ts +1 -2
- package/dist/src/channel/routes.d.ts +21 -149
- package/dist/src/channel/schedule.d.ts +1 -1
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/channel/send-input.d.ts +6 -0
- package/dist/src/channel/send-input.js +1 -0
- package/dist/src/channel/session.d.ts +44 -30
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +8 -35
- package/dist/src/chunks/{use-eve-agent-k-XHfrJT.js → use-eve-agent-CF5D6jSV.js} +361 -367
- package/dist/src/chunks/{use-eve-agent-BXMIf5fR.js → use-eve-agent-DbYZLG0h.js} +364 -368
- package/dist/src/cli/commands/agent-prompt/build-and-verify.md +1 -2
- package/dist/src/cli/commands/channel-add-conflicts.js +1 -1
- package/dist/src/cli/commands/info.d.ts +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/commands/registry-metadata.d.ts +15 -0
- package/dist/src/cli/commands/registry-metadata.js +1 -0
- package/dist/src/cli/commands/registry-package.d.ts +46 -0
- package/dist/src/cli/commands/registry-package.js +1 -0
- package/dist/src/cli/commands/registry.d.ts +1 -1
- package/dist/src/cli/commands/registry.js +4 -4
- package/dist/src/cli/dev/tui/runner.d.ts +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +2 -2
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/invoke/invoke.d.ts +1 -1
- package/dist/src/cli/invoke/invoke.js +1 -1
- package/dist/src/cli/invoke/result.d.ts +0 -11
- package/dist/src/cli/invoke/result.js +1 -1
- package/dist/src/client/client-error.d.ts +2 -0
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/client.d.ts +7 -14
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/eve-agent-store.d.ts +4 -4
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +3 -2
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-reducer-types.d.ts +3 -0
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/message-response.d.ts +2 -7
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-controls.d.ts +29 -0
- package/dist/src/client/session-controls.js +1 -0
- package/dist/src/client/session-utils.d.ts +0 -20
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.d.ts +26 -90
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +20 -0
- package/dist/src/client/sessions.js +1 -0
- package/dist/src/client/types.d.ts +26 -47
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/evals/cli/eval-client.js +1 -1
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/session.d.ts +7 -6
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +9 -9
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +1 -3
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/runtime-errors.d.ts +1 -1
- package/dist/src/execution/session-command-token.d.ts +2 -0
- package/dist/src/execution/session-command-token.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/tool-auth.d.ts +1 -1
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/turn-control-receiver.d.ts +2 -2
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/cancelled-turn-emission.d.ts +1 -1
- package/dist/src/harness/cancelled-turn-emission.js +1 -1
- package/dist/src/harness/emission-state.d.ts +25 -0
- package/dist/src/harness/emission-state.js +1 -0
- package/dist/src/harness/emission.d.ts +5 -37
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/handles/prompt.d.ts +22 -3
- package/dist/src/harness/handles/prompt.js +1 -1
- package/dist/src/harness/handles/store.d.ts +0 -5
- package/dist/src/harness/handles/store.js +1 -1
- package/dist/src/harness/ordered-stream-emitter.d.ts +3 -2
- package/dist/src/harness/ordered-stream-emitter.js +1 -1
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/tools.d.ts +1 -1
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-local-roots.d.ts +15 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-local-roots.js +1 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.d.ts +14 -2
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
- package/dist/src/internal/nitro/host/dev-server-http.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.d.ts +2 -5
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +4 -3
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/cancel-turn.d.ts +9 -4
- package/dist/src/protocol/cancel-turn.js +1 -1
- package/dist/src/protocol/message.d.ts +27 -17
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/reset-session.d.ts +1 -1
- package/dist/src/protocol/routes.d.ts +27 -47
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +19 -21
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/discord/discordChannel.d.ts +5 -4
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/eve.d.ts +11 -10
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/github/dispatch.d.ts +8 -8
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +4 -3
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/pr-context.d.ts +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +4 -3
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/interactions.d.ts +3 -4
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/session-operations.d.ts +37 -0
- package/dist/src/public/channels/slack/session-operations.js +1 -0
- package/dist/src/public/channels/slack/slackChannel.d.ts +56 -74
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +4 -3
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +5 -4
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +4 -3
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/definitions/callback-context.d.ts +1 -2
- package/dist/src/public/definitions/channel.d.ts +22 -86
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +1 -0
- package/dist/src/public/definitions/remote-agent.js +1 -1
- package/dist/src/public/definitions/schedule.d.ts +16 -16
- package/dist/src/public/definitions/tool.d.ts +5 -5
- package/dist/src/public/schedules/index.d.ts +1 -1
- package/dist/src/react/use-eve-agent.d.ts +7 -4
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/agent/bootstrap-model-utils.d.ts +11 -0
- package/dist/src/runtime/agent/bootstrap-model-utils.js +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/subagents/dynamic-remote-agent-config.js +1 -1
- package/dist/src/runtime/types.d.ts +2 -2
- package/dist/src/services/inspect-application.d.ts +1 -1
- package/dist/src/services/inspect-application.js +1 -1
- package/dist/src/setup/channel-add-conflicts.js +1 -1
- package/dist/src/setup/integrations/linear/setup.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +29 -17
- package/dist/src/shared/async-iterable.d.ts +2 -0
- package/dist/src/shared/async-iterable.js +1 -0
- package/dist/src/shared/channel-definition.d.ts +7 -7
- package/dist/src/shared/schedule-definition.d.ts +2 -2
- package/dist/src/shared/tool-definition.d.ts +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +8 -5
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +8 -5
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +6 -6
- package/docs/channels/chat-sdk.mdx +5 -6
- package/docs/channels/custom.mdx +116 -144
- package/docs/channels/discord.mdx +1 -1
- package/docs/channels/eve.mdx +76 -30
- package/docs/channels/github.mdx +1 -1
- package/docs/channels/linear.mdx +10 -10
- package/docs/channels/overview.mdx +2 -2
- package/docs/channels/slack.mdx +46 -15
- package/docs/channels/telegram.mdx +1 -1
- package/docs/channels/twilio.mdx +1 -1
- package/docs/concepts/default-harness.md +11 -3
- package/docs/concepts/execution-model-and-durability.mdx +17 -5
- package/docs/concepts/sessions-runs-and-streaming.md +45 -16
- package/docs/evals/cases.mdx +3 -3
- package/docs/evals/targets.mdx +1 -1
- package/docs/guides/auth-and-route-protection.md +2 -1
- package/docs/guides/client/continuations.mdx +50 -77
- package/docs/guides/client/messages.mdx +29 -33
- package/docs/guides/client/output-schema.mdx +7 -14
- package/docs/guides/client/overview.mdx +40 -11
- package/docs/guides/client/streaming.mdx +18 -23
- package/docs/guides/frontend/nuxt.mdx +1 -1
- package/docs/guides/frontend/overview.mdx +40 -36
- package/docs/guides/frontend/sveltekit.mdx +1 -1
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +19 -23
- package/docs/guides/frontend/use-eve-agent-vue.mdx +21 -25
- package/docs/guides/hooks.md +1 -1
- package/docs/guides/instrumentation.md +1 -1
- package/docs/install-integrations.mdx +4 -2
- package/docs/patterns/dynamic-scheduling.md +16 -15
- package/docs/reference/cli.md +4 -1
- package/docs/schedules.mdx +10 -11
- package/docs/subagents.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tools/overview.mdx +26 -2
- package/docs/tutorial/ship-it.mdx +1 -1
- package/package.json +1 -1
- package/dist/src/channel/cancel.d.ts +0 -6
- package/dist/src/channel/cancel.js +0 -1
- package/dist/src/channel/clear-session.d.ts +0 -4
- package/dist/src/channel/clear-session.js +0 -1
- package/dist/src/channel/compact-session.d.ts +0 -4
- package/dist/src/channel/compact-session.js +0 -1
- package/dist/src/channel/reset-session.d.ts +0 -6
- package/dist/src/channel/reset-session.js +0 -1
- package/dist/src/channel/resolve-active-session.d.ts +0 -4
- package/dist/src/channel/resolve-active-session.js +0 -1
- package/dist/src/channel/send.d.ts +0 -6
- package/dist/src/channel/send.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,createEveSessionCancelRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{AgentHandleError}from"#protocol/agent-handle-error.js";const CreateSessionResponseSchema=z.object({ok:z.literal(!0),sessionId:z.string().min(1),status:z.literal(`accepted`)});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),i={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,persistentSession:e.persistentSessions,remote:e.remote}),mode:e.persistentSessions===!0?`conversation`:`task`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};n!==void 0&&(i.forwardedPrincipal=n);let a=await resolveRemoteAgentRequestHeaders(e.remote),o=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(i),headers:{"content-type":`application/json`,...a},method:`POST`});if(!o.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${o.status}.`);let s;try{s=await o.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let c=CreateSessionResponseSchema.safeParse(s);if(!c.success)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was invalid.`);return{sessionId:c.data.sessionId}}async function continueRemoteAgentSession(e){let t=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify({callback:e.callback,message:e.message,outputSchema:e.outputSchema}),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!t.ok){let n=await readRemoteAgentErrorCode(t),r=t.status===404||n===AgentHandleError.SessionNotResumable.code;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${r?` permanently`:``} with HTTP ${t.status}.`,{retryable:!r})}}var RemoteAgentContinueRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.status===`accepted`&&i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return i.data.status===`accepted`?{sessionId:i.data.sessionId,status:`accepted`}:{status:`no_active_turn`}}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let r=getStepRegistry().get(e.credentialsStepId);if(r===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let i=expectObjectRecord(r(),`Dynamic remote subagent credentials are invalid.`),a={};return i.auth!==void 0&&(a.auth=expectFunction(i.auth,`Dynamic remote subagent auth is invalid.`)),i.headers!==void 0&&(a.headers=resolveDynamicRemoteAgentHeaders(i.headers)),a}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionCancelRoutePath(t))}function createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionRoutePath(t))}function createRemoteAgentRouteUrl(e,t){return new URL(t.replace(/^\/+/,``),`${trimTrailingSlash(e)}/`).toString()}function isRetryableRemoteCancelStatus(e){return e===408||e===425||e===429||e>=500}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,persistentSession:e.persistentSession,type:`remote`}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{RemoteAgentContinueRequestError,cancelRemoteAgentTurn,continueRemoteAgentSession,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,resolveRemoteAgentForAction,startRemoteAgentSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicSubagentAgentConfigKey,InitiatorAuthKey,ModeKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SubagentDepthKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{setChannelContext}from"#execution/channel-context.js";function buildRunContext(t){let{bundle:n,run:r}=t,i=new ContextContainer,a=r.auth;if(i.set(BundleKey,n),setChannelContext(i,r.adapter,{channelName:r.channelName}),r.channelMetadata!==void 0){let e=i.get(ChannelInstrumentationKey);i.set(ChannelInstrumentationKey,{kind:e?.kind??r.channelMetadata.kind,metadata:r.channelMetadata.metadata})}return i.set(ContinuationTokenKey,r.continuationToken
|
|
1
|
+
import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicSubagentAgentConfigKey,InitiatorAuthKey,ModeKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SubagentDepthKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{setChannelContext}from"#execution/channel-context.js";function buildRunContext(t){let{bundle:n,run:r}=t,i=new ContextContainer,a=r.auth;if(i.set(BundleKey,n),setChannelContext(i,r.adapter,{channelName:r.channelName}),r.channelMetadata!==void 0){let e=i.get(ChannelInstrumentationKey);i.set(ChannelInstrumentationKey,{kind:e?.kind??r.channelMetadata.kind,metadata:r.channelMetadata.metadata})}return r.continuationToken!==void 0&&i.set(ContinuationTokenKey,r.continuationToken),i.set(ModeKey,r.mode),i.set(AuthKey,a),i.set(InitiatorAuthKey,r.initiatorAuth??a),t.dynamicSubagentAgentConfig!==void 0&&i.set(DynamicSubagentAgentConfigKey,t.dynamicSubagentAgentConfig),r.capabilities!==void 0&&i.set(CapabilitiesKey,r.capabilities),r.requestId!==void 0&&i.set(ChannelRequestIdKey,r.requestId),r.callback!==void 0&&i.set(SessionCallbackKey,r.callback),r.parent!==void 0&&i.set(ParentSessionKey,r.parent),r.parentTraceContext!==void 0&&i.set(ParentTraceContextKey,r.parentTraceContext),r.subagentDepth!==void 0&&i.set(SubagentDepthKey,r.subagentDepth),i}export{buildRunContext};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Thrown by a {@link Runtime}'s `deliver` when no in-flight session
|
|
3
3
|
* matches the continuation token. Callers using the resume-or-start
|
|
4
|
-
* pattern (e.g.
|
|
4
|
+
* pattern (e.g. a channel address send) treat this as the signal to start
|
|
5
5
|
* a fresh session.
|
|
6
6
|
*/
|
|
7
7
|
export declare class RuntimeNoActiveSessionError extends Error {
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
+
/** Returns whether a token belongs to eve's framework-reserved session command namespace. */
|
|
2
|
+
export declare function isReservedSessionCommandToken(token: string): boolean;
|
|
1
3
|
/** Derives the framework-reserved stable command inbox token for a session. */
|
|
2
4
|
export declare function sessionCommandHookToken(sessionId: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function sessionCommandHookToken(e){return
|
|
1
|
+
const SESSION_COMMAND_NAMESPACE=`eve:session`;function isReservedSessionCommandToken(e){return e.startsWith(`${SESSION_COMMAND_NAMESPACE}:`)}function sessionCommandHookToken(e){return`${SESSION_COMMAND_NAMESPACE}:${e}:inbox`}export{isReservedSessionCommandToken,sessionCommandHookToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation-native-events.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let t=a.parentWritable.getWriter();try{let n=await withContextScope(s,p,async n=>{let baseEmit=async n=>{let r=await callAdapterEventHandler(c,n,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await t.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.resolvedAgent.config.name,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation-native-events.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let t=a.parentWritable.getWriter();try{let n=await withContextScope(s,p,async n=>{let baseEmit=async n=>{let r=await callAdapterEventHandler(c,n,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await t.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.resolvedAgent.config.name,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m),session:n}});m=n.result,p=n.session}finally{await f?.forceFlush(),t.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(abandonRunningAgentTurns(p))))),m));return{serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})}}export{settleCancelledTurnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[],s;for(let e of n){let n=t.get(e.requestId);if(n===void 0){a.push(e);continue}n.kind===`session-limit`&&e.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let i=r.get(n.childContinuationToken);i===void 0?r.set(n.childContinuationToken,[e]):i.push(e)}let c=[...r.entries()].map(([e,t])=>({childContinuationToken:e,payload:{inputResponses:t}})),l={};for(let[t,n]of Object.entries(e.payload))t===`inputResponses`||n===void 0||(l[t]=n);return a.length>0&&(l.inputResponses=a),{forChildren:c,forSelf:Object.keys(l).length>0?l:void 0,parentAction:s}}export{emitProxiedInputRequest,routeDeliverPayload};
|
|
@@ -31,4 +31,4 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
|
31
31
|
export declare function createToolExecuteWithAuth(input: {
|
|
32
32
|
readonly scope: string;
|
|
33
33
|
readonly execute: (toolInput: unknown, ctx: unknown) => unknown;
|
|
34
|
-
}): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown>;
|
|
34
|
+
}): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown> | AsyncIterable<unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";function createToolExecuteWithAuth(e){let{scope:t,execute:n}=e;return
|
|
1
|
+
import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";import{isAsyncIterable}from"#shared/async-iterable.js";function createToolExecuteWithAuth(e){let{scope:t,execute:n}=e;return(e,r)=>{let i=buildToolContext({inlineAuthState:{},justAuthorizedScopes:new Set,options:r,scope:t});try{let t=n(e,i);return isAsyncIterable(t)?handleToolIterableErrors(t):Promise.resolve(t).catch(handleToolError)}catch(e){return handleToolError(e)}async function handleToolError(e){if(isToolAuthorizationRequiredError(e))return await handleAuthorizationRequests(e.requests);throw e}async function*handleToolIterableErrors(e){try{for await(let t of e)yield t}catch(e){yield await handleToolError(e)}}}}function buildToolContext(t){let{scope:n,justAuthorizedScopes:r,inlineAuthState:i}=t;return{...buildBaseToolContext({options:t.options,toolName:n}),async getToken(e,t){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({inlineAuthState:i,justAuthorizedScopes:r,options:t,provider:e,toolScope:n})},requireAuth(e,t){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({inlineAuthState:i,options:t,provider:e,toolScope:n});throw new ToolAuthorizationRequiredError([{justAuthorized:r.has(a.scope),scoped:a}])}}}async function resolveInlineToken(e){let{justAuthorizedScopes:t}=e,n=buildInlineScopedAuthorization(e);!t.has(n.scope)&&await completeScopedAuthorization(n)&&t.add(n.scope);try{return await resolveScopedToken(n)}catch(e){throw isConnectionAuthorizationRequiredError(e)?new ToolAuthorizationRequiredError([{cause:e,justAuthorized:t.has(n.scope),scoped:n}]):e}}async function handleAuthorizationRequests(e){let r=[],o;for(let i of e){let{scoped:e}=i;if(i.justAuthorized)throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});await evictScopedToken(e);let s=await startScopedAuthorization(e);if(s!==void 0){r.push(...s.challenges);continue}if(supportsInteractiveAuthorization(e.authorization))throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1});o??=i.cause instanceof Error?i.cause:new ConnectionAuthorizationRequiredError(e.scope)}if(r.length>0)return requestAuthorization(r);throw o??Error(`Tool authorization is required.`)}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,toolScope:e.toolScope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.toolScope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.toolScope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}var ToolAuthorizationRequiredError=class extends Error{requests;constructor(e){super(`Tool authorization required.`),this.name=`ToolAuthorizationRequiredError`,this.requests=e}};function isToolAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ToolAuthorizationRequiredError`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{createToolExecuteWithAuth};
|
|
@@ -32,8 +32,8 @@ export declare class TurnControlReceiver {
|
|
|
32
32
|
/**
|
|
33
33
|
* Waits for the active turn to resolve a forwarded delivery. The turn either
|
|
34
34
|
* accepts it (consumed) or releases it on cancellation or termination, in
|
|
35
|
-
* which case the delivery returns
|
|
36
|
-
*
|
|
35
|
+
* which case the delivery returns behind remainders from earlier deliveries
|
|
36
|
+
* accepted by the turn and ahead of deliveries that arrived later.
|
|
37
37
|
*/
|
|
38
38
|
private awaitForwardedDelivery;
|
|
39
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{turnStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";
|
|
1
|
+
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{turnStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let t=migrateTurnWorkflowInput(e);return t.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(t):runLegacyTurnWorkflow(t)}async function runTurnOwnedWorkflow(n){let o=createHook({token:`${n.completionToken}:inbox`}),c=o[Symbol.asyncIterator](),l=new TurnExecutionCursor({controlToken:n.completionToken,parentWritable:n.stepInput.parentWritable,serializedContext:n.stepInput.serializedContext,sessionState:n.stepInput.sessionState}),u=0,nextDeliveryRequestId=()=>`${o.token}:delivery:${String(u++)}`,d=[],f=n.stepInput.input,p=!1,m;try{try{await claimHookOwnership(o),p=!0}catch(e){if(isHookConflictError(e))return;throw e}for(n.driverCapabilities?.cancelledTurnSettle===!0&&(m=await createTurnCancellationControl({controlToken:n.completionToken,expectedTurnId:activeTurnId(n.stepInput.sessionState.emissionState)}));;){let i=await turnStep(l.createStepInput(f,m?.signal)),s=i.action===`dispatch-workflow-runtime-actions`||i.action===`park`?i.pendingRuntimeActionKeys:void 0;if(i.action===`cancelled`||m?.signal.aborted===!0&&s===void 0){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}if(i.sleepDurationMs!==void 0&&await waitForTurnSleep(i.sleepDurationMs,m)===`cancel`){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}if(i.action===`done`){await m?.dispose(),await l.finish(i,{kind:`done`,output:i.output??``,isError:i.isError,usage:i.usage,usageDelta:i.usageDelta},d);return}if(s!==void 0){await l.adopt(i);let n=await(i.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:o.token,parentWritable:l.parentWritable,serializedContext:l.serializedContext,sessionState:l.sessionState});await l.adopt(n);let r=await waitForRuntimeActionResults({bufferedDeliveries:d,cancellation:m,cursor:l,inboxToken:o.token,initialResults:n.results,iterator:c,nextDeliveryRequestId,pendingActionKeys:s});if(r===`cancelled`){f=void 0;continue}if(r===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}f={kind:`runtime-action-result`,results:r};continue}if(i.action===`park`){if(!(i.hasPendingAuthorization||i.hasPendingInputBatch&&n.capabilities?.requestInput===!0||n.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await m?.dispose(),await l.finish(i,{authorizationNames:i.authorizationNames,kind:`park`,settled:i.settled},d);return}await l.adopt(i),f=void 0}}catch(e){throw await l.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{m!==void 0&&await m.dispose(),p&&await disposeHook(o)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,r=[...e.initialResults];for(;;){let i=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:r});if(i!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),i;e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let a=e.iterator.next();a.catch(()=>{});let o=await(e.cancellation===void 0?a:Promise.race([a,e.cancellation.requested]));if(o===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(o.done)throw Error(`Turn inbox closed before runtime actions completed.`);let s=o.value;if(s.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state;r.push(...s.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e)));continue}if(s.kind===`subagent-input-request`||s.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:s,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(s.kind===`driver-delivery`&&s.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:s.requestId}),t=void 0;let r=await routeDeliverToChildren({auth:s.delivery.auth,parentWritable:e.cursor.parentWritable,payloads:s.delivery.payloads,sessionState:e.cursor.sessionState});if(r.kind===`cancel-turn`)return r.kind;r.remainder!==void 0&&e.bufferedDeliveries.push({...s.delivery,payloads:[r.remainder]})}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:n,workflowStartedAt:a}=getWorkflowMetadata(),s=e.serializedContext[`eve.continuationToken`]||``,m=e.serializedContext[`eve.mode`],h=e.serializedContext[`eve.capabilities`],g=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=n;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let r=readRootSessionId(e.serializedContext),i=readSerializedSubagentDepth(e.serializedContext),o=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:u}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:s,dynamicSubagentAgentConfig:o,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:r,sessionId:n,subagentDepth:i});v.lastSessionState=u,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let d=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:m,serializedContext:e.serializedContext,sessionState:u,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(a.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return d.kind===`result`?d.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:m,serializedContext:d.serializedContext,sessionState:d.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:_,serializedContext:e.serializedContext}),m===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:n,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let r=createHook({token:`${t.sessionState.sessionId}:auth`}),i=r[Symbol.asyncIterator](),o=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(o++)}`,c=[],l=[],u=createSessionCommandInbox(),f=sessionCommandHookToken(t.sessionState.sessionId);await u.claimStable(f);let p=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:f}),m,runTurn=async e=>{let n=await dispatchAndAwaitTurn({bufferedDeliveries:c,bufferedSessionControls:l,capabilities:t.capabilities,commandInbox:u,controlToken:nextTurnControlToken(),delivery:e.delivery,mode:t.mode,parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});return await m?.(),m=n.dispose,n.action};try{t.sessionState.continuationToken&&await u.rekeyContinuation(t.sessionState.continuationToken),await p?.start();let e=await runTurn({delivery:t.initialInput,serializedContext:t.serializedContext,sessionState:t.sessionState});for(t.crashCleanupState.lastSessionState=e.sessionState;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState},t.crashCleanupState.lastSessionState=e.sessionState}if(e.sessionState.continuationToken&&await u.rekeyContinuation(e.sessionState.continuationToken),e.authorizationNames&&e.authorizationNames.length>0){let n=e.authorizationNames.length,r=[];for(;r.length<n;){let e=await i.next();if(e.done)break;e.value.kind===`deliver`&&r.push(...e.value.payloads)}e=await runTurn({delivery:{kind:`deliver`,payloads:r},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:e.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextTurnDelivery({bufferedDeliveries:c,bufferedSessionControls:l,commandInbox:u,driverWritable:t.driverWritable,sessionState:e.sessionState});if(r.kind===`expired`)return{kind:`expired`,serializedContext:e.serializedContext,sessionState:e.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({sessionState:e.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({delivery:{kind:r.kind},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=e.sessionState;continue}r.deliver.caller!==void 0&&(t.crashCleanupState.caller=r.deliver.caller),e=await runTurn({delivery:{auth:r.deliver.auth,kind:`deliver`,payloads:[r.remainder],requestId:r.deliver.requestId},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState}}finally{await m?.(),await p?.dispose(),await u.dispose(),await disposeHook(r)}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:r?void 0:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:r?void 0:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f=l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId),i.continuationToken){let e=await waitForCommandHookOwner(i.continuationToken);if(e.runId!==p.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:i.continuationToken,ownerSessionId:e.runId,sessionId:p.runId})}let m,getEvents=()=>(m??=parseNdjsonStream(()=>getRun(p.runId).getReadable()),m);return{get events(){return getEvents()},sessionId:p.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeHook(e,n))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),{kind:`cancel`,turnId:e.turnId})}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
|
|
@@ -8,4 +8,4 @@ import type { HarnessEmissionState } from "#harness/emission.js";
|
|
|
8
8
|
* cancelled turn's preamble — the turn id is reconstructed via
|
|
9
9
|
* {@link activeTurnId} and `sessionStarted` is stamped `true`.
|
|
10
10
|
*/
|
|
11
|
-
export declare function emitCancelledTurn(emitFn: HarnessEmitFn, state: HarnessEmissionState
|
|
11
|
+
export declare function emitCancelledTurn(emitFn: HarnessEmitFn, state: HarnessEmissionState): Promise<HarnessEmissionState>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSessionWaitingEvent,createTurnCancelledEvent}from"#protocol/message.js";import{activeTurnId}from"#harness/active-turn-id.js";async function emitCancelledTurn(e,t
|
|
1
|
+
import{createSessionWaitingEvent,createTurnCancelledEvent}from"#protocol/message.js";import{activeTurnId}from"#harness/active-turn-id.js";async function emitCancelledTurn(e,t){return await e(createTurnCancelledEvent({sequence:t.sequence,turnId:activeTurnId(t)})),await e(createSessionWaitingEvent()),{sessionStarted:!0,sequence:t.sequence+1,stepIndex:0,turnId:``}}export{emitCancelledTurn};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Tracks emission lifecycle state across harness step invocations.
|
|
4
|
+
*
|
|
5
|
+
* Persisted on `session.state` so the state survives when the durable
|
|
6
|
+
* workflow runtime recreates the harness at each `"use step"` boundary.
|
|
7
|
+
*/
|
|
8
|
+
export interface HarnessEmissionState {
|
|
9
|
+
readonly sessionStarted: boolean;
|
|
10
|
+
readonly sequence: number;
|
|
11
|
+
readonly stepIndex: number;
|
|
12
|
+
readonly turnId: string;
|
|
13
|
+
}
|
|
14
|
+
/** Reads the emission state, returning defaults when absent. */
|
|
15
|
+
export declare function getHarnessEmissionState(state: SessionStateMap | undefined): HarnessEmissionState;
|
|
16
|
+
/**
|
|
17
|
+
* Returns `true` when the harness is between turns — either no turn has
|
|
18
|
+
* started yet or the previous turn has emitted its epilogue and reset.
|
|
19
|
+
*
|
|
20
|
+
* The empty `turnId` sentinel distinguishes a fresh delivery from an in-flight
|
|
21
|
+
* continuation. Callers should use this predicate instead of reading it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isHarnessBetweenTurns(session: HarnessSession): boolean;
|
|
24
|
+
/** Writes the emission state onto a new copy of the session. */
|
|
25
|
+
export declare function setHarnessEmissionState(session: HarnessSession, state: HarnessEmissionState): HarnessSession;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(n){return n?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(t,n){return{...t,state:{...t.state,[HARNESS_EMISSION_STATE_KEY]:n}}}export{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState};
|
|
@@ -8,41 +8,10 @@ type InlineToolResultPart = Extract<ToolResponsePart, {
|
|
|
8
8
|
import type { AssistantStepFinishReason, RuntimeIdentity } from "#protocol/message.js";
|
|
9
9
|
import type { RunMode } from "#shared/run-mode.js";
|
|
10
10
|
import type { JsonObject } from "#shared/json.js";
|
|
11
|
-
import type {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* Persisted on `session.state` so the state survives when the durable
|
|
16
|
-
* workflow runtime recreates the harness at each `"use step"` boundary.
|
|
17
|
-
*/
|
|
18
|
-
export interface HarnessEmissionState {
|
|
19
|
-
readonly sessionStarted: boolean;
|
|
20
|
-
readonly sequence: number;
|
|
21
|
-
readonly stepIndex: number;
|
|
22
|
-
readonly turnId: string;
|
|
23
|
-
}
|
|
24
|
-
/** Reads the emission state, returning defaults when absent. */
|
|
25
|
-
export declare function getHarnessEmissionState(state: SessionStateMap | undefined): HarnessEmissionState;
|
|
26
|
-
/**
|
|
27
|
-
* Returns `true` when the harness is **between turns** — either no turn
|
|
28
|
-
* has started yet (initial state) or the previous turn has emitted its
|
|
29
|
-
* epilogue (or recoverable failure cascade) and reset.
|
|
30
|
-
*
|
|
31
|
-
* Returns `false` while a turn is in progress, including during
|
|
32
|
-
* tool-loop continuations and runtime-action resumes within the same
|
|
33
|
-
* turn. Callers that gate per-turn work (eg. lifecycle hook dispatch)
|
|
34
|
-
* use this predicate to distinguish a fresh delivery from a
|
|
35
|
-
* continuation of an in-flight turn.
|
|
36
|
-
*
|
|
37
|
-
* Implemented over the empty-`turnId` sentinel that `emitTurnEpilogue`
|
|
38
|
-
* and `emitRecoverableFailedTurn` write — clients should never read
|
|
39
|
-
* `state.turnId` directly to make this distinction.
|
|
40
|
-
*/
|
|
41
|
-
export declare function isHarnessBetweenTurns(session: HarnessSession): boolean;
|
|
42
|
-
/**
|
|
43
|
-
* Writes the emission state onto a new copy of the session.
|
|
44
|
-
*/
|
|
45
|
-
export declare function setHarnessEmissionState(session: HarnessSession, state: HarnessEmissionState): HarnessSession;
|
|
11
|
+
import type { HarnessEmissionState } from "#harness/emission-state.js";
|
|
12
|
+
import type { HarnessEmitFn, HarnessToolMap, StepInput } from "#harness/types.js";
|
|
13
|
+
export { getHarnessEmissionState, isHarnessBetweenTurns, setHarnessEmissionState, } from "#harness/emission-state.js";
|
|
14
|
+
export type { HarnessEmissionState } from "#harness/emission-state.js";
|
|
46
15
|
/**
|
|
47
16
|
* Emits `session.started` (once), `turn.started`, and `message.received` at the
|
|
48
17
|
* beginning of a new turn. Returns updated emission state.
|
|
@@ -84,7 +53,7 @@ export declare function advanceStep(state: HarnessEmissionState): HarnessEmissio
|
|
|
84
53
|
* Emits `turn.completed` and either `session.waiting` or `session.completed`.
|
|
85
54
|
* Returns updated emission state with an incremented sequence.
|
|
86
55
|
*/
|
|
87
|
-
export declare function emitTurnEpilogue(emitFn: HarnessEmitFn, state: HarnessEmissionState, mode: RunMode
|
|
56
|
+
export declare function emitTurnEpilogue(emitFn: HarnessEmitFn, state: HarnessEmissionState, mode: RunMode): Promise<HarnessEmissionState>;
|
|
88
57
|
/**
|
|
89
58
|
* Maps an AI SDK finish reason string to the eve-owned
|
|
90
59
|
* {@link AssistantStepFinishReason} union. Unknown values become `"other"`.
|
|
@@ -116,4 +85,3 @@ interface StreamActionEmissionOptions {
|
|
|
116
85
|
* without a streamed call resumes a call from an earlier step.
|
|
117
86
|
*/
|
|
118
87
|
export declare function emitStreamContent(emitFn: HarnessEmitFn, state: HarnessEmissionState, fullStream: AsyncIterable<TextStreamPart<ToolSet>>, options?: StreamActionEmissionOptions): Promise<EmittedStreamContent>;
|
|
119
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";
|
|
1
|
+
import{createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(a,o,s,c,l){let u=``,d=``,f=`stop`,p,m=new Set,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=[],x=[],flushCurrentMessage=async()=>{d.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d=``)},emitActionRequest=async e=>{h.has(e.callId)||(d.trim().length>0&&await flushCurrentMessage(),h.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{if(_.has(e.toolCallId)||(_.add(e.toolCallId),h.has(e.toolCallId)))return;h.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){y.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(t.toolError));return}c.observe(t.request)},emitActionResult=async e=>{g.has(e.callId)||(g.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitActionPartial=async t=>{await a(createActionPartialEvent({result:t,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}))},emitToolCall=async e=>{if(isInvalidToolCall(e)){y.add(e.toolCallId);return}if(!(l===void 0||l.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:l.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});y.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of s)if(p===void 0)switch(e.type){case`reasoning-delta`:await c.flush(),u+=e.text,await a(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await c.flush(),u.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``),d+=e.text,await a(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let t=e;m.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await c.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0){t.providerExecuted!==!0&&await emitActionPartial(createRuntimeToolResultFromStepResult(t));break}if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await c.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(m.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;h.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId));break}if(await c.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){v.add(e.toolCallId),b.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await c.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):h.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),v.add(t.toolCallId),x.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:f=normalizeAssistantStepFinishReason(e.finishReason),await c.flush();break;case`error`:p=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await c.flush(),p!==void 0)throw p;return u.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),f!==`tool-calls`&&hasEmptyDeliverySentinel(d)?await a(createMessageCompletedEvent({finishReason:f,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):d.trim().length>0&&await a(createMessageCompletedEvent({finishReason:f,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:h,handledInlineToolResultCallIds:v,invalidInputToolCallIds:y,inlineAuthorizationResults:b,trailingInlineToolResultParts:x}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { ModelMessage } from "ai";
|
|
2
2
|
import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
|
|
3
|
+
/**
|
|
4
|
+
* Label prefixing every framework-injected agents announcement. Mock model
|
|
5
|
+
* adapters use it to treat announcements as transparent scaffolding rather
|
|
6
|
+
* than authored user input.
|
|
7
|
+
*/
|
|
8
|
+
export declare const AGENTS_SNIPPET_LABEL = "[Agents]";
|
|
3
9
|
/** Returns the resumable handles: the only phase the model may continue. */
|
|
4
10
|
export declare function projectParkedAgentHandles(store: AgentHandleStore): readonly Extract<AgentHandle, {
|
|
5
11
|
phase: "parked";
|
|
@@ -11,9 +17,22 @@ export declare function projectParkedAgentHandles(store: AgentHandleStore): read
|
|
|
11
17
|
*/
|
|
12
18
|
export declare function renderAgentsSnippet(store: AgentHandleStore): string;
|
|
13
19
|
/**
|
|
14
|
-
* Returns an append-only
|
|
15
|
-
* changed
|
|
16
|
-
*
|
|
20
|
+
* Returns an append-only announcement when the visible handle listing
|
|
21
|
+
* changed since the last one in history, or `undefined` when it is
|
|
22
|
+
* unchanged.
|
|
23
|
+
*
|
|
24
|
+
* The announcement is framework-injected `user`-role conversation content
|
|
25
|
+
* (the pattern system-reminder notes use in Claude Code and OpenCode), not
|
|
26
|
+
* an `assistant` or `system` entry:
|
|
27
|
+
*
|
|
28
|
+
* - `assistant` breaks providers that reject assistant-final requests
|
|
29
|
+
* (a settle resume carries no new user input, so the announcement would
|
|
30
|
+
* end the request) and invites the model to imitate the listing.
|
|
31
|
+
* - `system` busts the provider prompt cache for the entire conversation
|
|
32
|
+
* every time a child settles; append-only history preserves the prefix.
|
|
33
|
+
*
|
|
34
|
+
* The static agent-messaging prompt block declares the `[Agents]` label as
|
|
35
|
+
* eve-injected so the model does not attribute it to the user.
|
|
17
36
|
*/
|
|
18
37
|
export declare function resolveAgentsAnnouncement(input: {
|
|
19
38
|
readonly messages: readonly ModelMessage[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const AGENTS_SNIPPET_LABEL=`[Agents]`;function projectParkedAgentHandles(e){return e.handles.filter(e=>e.phase===`parked`)}function renderAgentsSnippet(t){let n=projectParkedAgentHandles(t).map(e=>`<agent id="${escapeXml(e.identity.id)}" name="${escapeXml(e.identity.name)}">${escapeXml(e.lastStatus===``?`(no status)`:e.lastStatus)}</agent>`);return[AGENTS_SNIPPET_LABEL,`<agents>`,...n,`</agents>`].join(`
|
|
2
|
-
`)}function resolveAgentsAnnouncement(
|
|
2
|
+
`)}function resolveAgentsAnnouncement(e){let t=e.messages.findLast(e=>e.role===`user`&&typeof e.content==`string`&&e.content.startsWith(`[Agents]`)),n=e.store??{handles:[]};if(t===void 0&&projectParkedAgentHandles(n).length===0)return;let r=renderAgentsSnippet(n);return t?.content===r?void 0:r}function escapeXml(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}export{AGENTS_SNIPPET_LABEL,projectParkedAgentHandles,renderAgentsSnippet,resolveAgentsAnnouncement};
|
|
@@ -68,11 +68,6 @@ export type AgentAddress = {
|
|
|
68
68
|
} | {
|
|
69
69
|
readonly kind: "agent/remote";
|
|
70
70
|
readonly sessionId: string;
|
|
71
|
-
/**
|
|
72
|
-
* Absent when the remote deployment predates continuation tokens; the
|
|
73
|
-
* child completes as a task-mode one-shot and can never be continued.
|
|
74
|
-
*/
|
|
75
|
-
readonly continuationToken?: string;
|
|
76
71
|
readonly url: string;
|
|
77
72
|
readonly callbackBaseUrl: string;
|
|
78
73
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_HANDLES_STATE_KEY}from"./state-key.js";import{z}from"#compiled/zod/index.js";const nonEmptyString=z.string().min(1),identitySchema=z.strictObject({id:nonEmptyString,name:nonEmptyString,nodeId:nonEmptyString}),startOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`start`),parentTurnId:nonEmptyString}),continueOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`continue`),parentTurnId:nonEmptyString,previousStatus:z.string().max(120)}),startTargetSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`)}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`)}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),url:z.url()})]),addressSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`),sessionId:nonEmptyString}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`),sessionId:nonEmptyString}),z.strictObject({callbackBaseUrl:z.url(),
|
|
1
|
+
import{AGENT_HANDLES_STATE_KEY}from"./state-key.js";import{z}from"#compiled/zod/index.js";const nonEmptyString=z.string().min(1),identitySchema=z.strictObject({id:nonEmptyString,name:nonEmptyString,nodeId:nonEmptyString}),startOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`start`),parentTurnId:nonEmptyString}),continueOperationSchema=z.strictObject({callId:nonEmptyString,id:nonEmptyString,kind:z.literal(`continue`),parentTurnId:nonEmptyString,previousStatus:z.string().max(120)}),startTargetSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`)}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`)}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),url:z.url()})]),addressSchema=z.discriminatedUnion(`kind`,[z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/local`),sessionId:nonEmptyString}),z.strictObject({continuationToken:nonEmptyString,kind:z.literal(`agent/self`),sessionId:nonEmptyString}),z.strictObject({callbackBaseUrl:z.url(),kind:z.literal(`agent/remote`),sessionId:nonEmptyString,url:z.url()})]),agentHandleSchema=z.discriminatedUnion(`phase`,[z.strictObject({identity:identitySchema,operation:startOperationSchema,phase:z.literal(`starting`),target:startTargetSchema}),z.strictObject({address:addressSchema,identity:identitySchema,operation:z.discriminatedUnion(`kind`,[startOperationSchema,continueOperationSchema]),phase:z.literal(`running`)}),z.strictObject({address:addressSchema,identity:identitySchema,lastStatus:z.string().max(120),phase:z.literal(`parked`)})]),agentHandleStoreSchema=z.strictObject({handles:z.array(agentHandleSchema)}).refine(e=>new Set(e.handles.map(e=>e.identity.id)).size===e.handles.length,{message:`Agent handle ids must be unique.`});function deriveAgentId(e,t){return`ag_${e}:${t.slice(0,12)}`}function formatAgentStatus(e){return(typeof e==`string`?e:JSON.stringify(e)??``).replaceAll(/\s+/g,` `).trim().slice(0,120)}function assertPersistableAgentHandleStore(e){let t=agentHandleStoreSchema.safeParse(e);if(!t.success)throw Error(`Refusing to persist a corrupt agent handle store: ${t.error.message}`);return t.data}function getAgentHandleStore(t){let n=t?.[AGENT_HANDLES_STATE_KEY];if(n===void 0)return;let r=agentHandleStoreSchema.safeParse(n);if(!r.success)throw Error(`Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${r.error.message}`);return r.data}export{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,deriveAgentId,formatAgentStatus,getAgentHandleStore};
|
|
@@ -6,8 +6,9 @@ interface OrderedStreamEmitter {
|
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
8
|
* Decouples model-stream consumption from the durable event sink while
|
|
9
|
-
* preserving FIFO dispatch. Adjacent append events
|
|
10
|
-
* write are folded together; every other event
|
|
9
|
+
* preserving FIFO dispatch. Adjacent append events and same-call tool partials
|
|
10
|
+
* waiting behind the active write are folded together; every other event
|
|
11
|
+
* remains an ordering barrier.
|
|
11
12
|
* Coalescing before the durable writer keeps one Workflow chunk per emitted
|
|
12
13
|
* event, so event-count reconnect cursors remain aligned with chunk indexes.
|
|
13
14
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const MAX_PENDING_DELTA_CHARACTERS=64*1024;function createOrderedStreamEmitter(t,n={}){let r=n.maxPendingEvents??64;if(!Number.isInteger(r)||r<1)throw RangeError(`maxPendingEvents must be a positive integer.`);let i=[],a=new Set,o=new Set,s=!1,c=0,l=0,u,d=!1,f=!1,p=new AbortController,throwIfFailed=()=>{if(d)throw u},settleIdleWaiters=()=>{for(let e of o)e();o.clear()},hasCapacity=()=>l<r&&c<MAX_PENDING_DELTA_CHARACTERS,settleCapacityWaiters=()=>{if(hasCapacity()){for(let e of a)e();a.clear()}},pump=async()=>{if(!(f||d)){for(f=!0;i.length>0;){let e=i.shift();if(e===void 0)break;c-=e.deltaCharacters,l-=e.sourceEvents,settleCapacityWaiters();try{await t(materializeEvent(e),e.messages)}catch(e){d||(u=e,d=!0,p.abort(e)),i.length=0,c=0,l=0,settleCapacityWaiters();break}}f=!1,settleIdleWaiters()}},waitForIdle=async()=>{if(!f&&i.length===0){throwIfFailed();return}await new Promise(e=>{o.add(e)}),throwIfFailed()},waitForCapacity=async()=>{hasCapacity()||(await new Promise(e=>{a.add(e)}),throwIfFailed())};return{async closeAndDrain(){s=!0,pump(),await waitForIdle()},async emit(t,n){if(throwIfFailed(),s)throw TypeError(`Cannot emit after the ordered stream emitter has closed.`);let a=i.length-1,o=i[a],u=appendDelta(t);o===void 0||!
|
|
1
|
+
const MAX_PENDING_DELTA_CHARACTERS=64*1024;function createOrderedStreamEmitter(t,n={}){let r=n.maxPendingEvents??64;if(!Number.isInteger(r)||r<1)throw RangeError(`maxPendingEvents must be a positive integer.`);let i=[],a=new Set,o=new Set,s=!1,c=0,l=0,u,d=!1,f=!1,p=new AbortController,throwIfFailed=()=>{if(d)throw u},settleIdleWaiters=()=>{for(let e of o)e();o.clear()},hasCapacity=()=>l<r&&c<MAX_PENDING_DELTA_CHARACTERS,settleCapacityWaiters=()=>{if(hasCapacity()){for(let e of a)e();a.clear()}},pump=async()=>{if(!(f||d)){for(f=!0;i.length>0;){let e=i.shift();if(e===void 0)break;c-=e.deltaCharacters,l-=e.sourceEvents,settleCapacityWaiters();try{await t(materializeEvent(e),e.messages)}catch(e){d||(u=e,d=!0,p.abort(e)),i.length=0,c=0,l=0,settleCapacityWaiters();break}}f=!1,settleIdleWaiters()}},waitForIdle=async()=>{if(!f&&i.length===0){throwIfFailed();return}await new Promise(e=>{o.add(e)}),throwIfFailed()},waitForCapacity=async()=>{hasCapacity()||(await new Promise(e=>{a.add(e)}),throwIfFailed())};return{async closeAndDrain(){s=!0,pump(),await waitForIdle()},async emit(t,n){if(throwIfFailed(),s)throw TypeError(`Cannot emit after the ordered stream emitter has closed.`);let a=i.length-1,o=i[a],u=appendDelta(t);o===void 0||!mergeAdjacentEmissions(o,t,n)?i.push({deltaCharacters:u?.length??0,event:t,messages:n,sourceEvents:1}):(o.deltaCharacters+=u?.length??0,o.sourceEvents+=1),c+=u?.length??0,l+=1,pump(),(l>=r||c>=MAX_PENDING_DELTA_CHARACTERS)&&await waitForCapacity(),throwIfFailed()},failureSignal:p.signal}}function mergeAdjacentEmissions(e,t,n){return e.event.type===`message.appended`&&t.type===`message.appended`?sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.messageDelta],e.deltaParts.push(t.data.messageDelta),e.event=t,e.messages=n,!0):!1:e.event.type===`reasoning.appended`&&t.type===`reasoning.appended`?sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.reasoningDelta],e.deltaParts.push(t.data.reasoningDelta),e.event=t,e.messages=n,!0):!1:e.event.type===`action.partial`&&t.type===`action.partial`&&e.event.data.result.callId===t.data.result.callId?(e.event=t,e.messages=n,!0):!1}function appendDelta(e){if(e.type===`message.appended`)return e.data.messageDelta;if(e.type===`reasoning.appended`)return e.data.reasoningDelta}function materializeEvent(e){return e.deltaParts===void 0?e.event:e.event.type===`message.appended`?{...e.event,data:{...e.event.data,messageDelta:e.deltaParts.join(``)}}:e.event.type===`reasoning.appended`?{...e.event,data:{...e.event.data,reasoningDelta:e.deltaParts.join(``)}}:e.event}function sameCoordinates(e,t){return e.data.sequence===t.data.sequence&&e.data.stepIndex===t.data.stepIndex&&e.data.turnId===t.data.turnId}export{createOrderedStreamEmitter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function readSubagentResultOutcome(e){return e.origin===`child`?e.outcome:void 0}function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results,state:e.session.state})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results.filter(t=>isResultBoundToRunningHandle(e.state,t))})}async function resolvePendingRuntimeActions(t){let i=getPendingRuntimeActionBatch(t.session.state);if(i===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let a=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(a===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of a)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:i.event.sequence,stepIndex:i.event.stepIndex,turnId:i.event.turnId}));let o=t.session;for(let e of a){if(e.kind!==`subagent-result`||e.origin!==`child`)continue;let t=findRunningAgentHandle(o.state,{callId:e.callId});if(t===void 0)continue;let i=readSubagentResultOutcome(e);if(i===void 0)continue;i.kind===`terminal
|
|
1
|
+
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{settleAgentTurn}from"#harness/handles/transitions.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{findRunningAgentHandle,isResultBoundToRunningHandle}from"#harness/handles/query.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function readSubagentResultOutcome(e){return e.origin===`child`?e.outcome:void 0}function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results,state:e.session.state})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results.filter(t=>isResultBoundToRunningHandle(e.state,t))})}async function resolvePendingRuntimeActions(t){let i=getPendingRuntimeActionBatch(t.session.state);if(i===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let a=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(a===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of a)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:i.event.sequence,stepIndex:i.event.stepIndex,turnId:i.event.turnId}));let o=t.session;for(let e of a){if(e.kind!==`subagent-result`||e.origin!==`child`)continue;let t=findRunningAgentHandle(o.state,{callId:e.callId});if(t===void 0)continue;let i=readSubagentResultOutcome(e);if(i===void 0)continue;i.kind===`terminal`&&`continuationToken`in t.address&&(o=clearProxyInputRequestsForChild(o,t.address.continuationToken));let a=settleAgentTurn(o,{operationId:t.operation.id,outcome:i});a.kind===`settled`&&(o=a.session)}let s={...o.state};delete s[PENDING_RUNTIME_ACTION_BATCH_KEY],o={...o,state:Object.keys(s).length>0?s:void 0};for(let e of a){if(e.kind!==`subagent-result`)continue;let t=readSubagentResultOutcome(e);t!==void 0&&(o=setTurnUsageState(o,accumulateSessionUsage({previous:getTurnUsageState(o.state),usage:t.usageDelta})))}let c=a.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),l=[...o.history,...i.responseMessages];return c.length>0&&l.push({content:c,role:`tool`}),{messages:l,outcome:`resolved`,session:o}}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null||typeof e==`string`&&e.trim()===``)return{};try{return parseJsonObject(typeof e==`string`?parseJsonStringInput(e):e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function parseJsonStringInput(e){return JSON.parse(e)}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,resolvePendingRuntimeActions,resolveToolCallInputObject,setPendingRuntimeActionBatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{setPendingInputBatch}from"#harness/input-requests.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";import{SessionLimitDeclinedError}from"#harness/turn-cancellation.js";import{bumpSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:bumpSessionRuntimeTokenLimits(e.session)};if(!(e.config.mode===`conversation`||e.session.continuationToken!==``)){let t=getSessionTokenLimitViolation(e.session);return{result:t===null?{next:{done:!0,output:``},session:e.session}:await failSessionTokenLimit({...e,violation:t}),session:e.session}}throw new SessionLimitDeclinedError}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return t.limit>0&&n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let a=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,violation:t.violation}),o=t.emissionState,s=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:[a],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[a],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.config.mode===`conversation`&&(o=await emitTurnEpilogue(t.emit,o,t.config.mode
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{setPendingInputBatch}from"#harness/input-requests.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";import{SessionLimitDeclinedError}from"#harness/turn-cancellation.js";import{bumpSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:bumpSessionRuntimeTokenLimits(e.session)};if(!(e.config.mode===`conversation`||e.session.continuationToken!==``)){let t=getSessionTokenLimitViolation(e.session);return{result:t===null?{next:{done:!0,output:``},session:e.session}:await failSessionTokenLimit({...e,violation:t}),session:e.session}}throw new SessionLimitDeclinedError}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return t.limit>0&&n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let a=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,violation:t.violation}),o=t.emissionState,s=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:[a],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[a],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.config.mode===`conversation`&&(o=await emitTurnEpilogue(t.emit,o,t.config.mode)),{next:null,session:setHarnessEmissionState(s,o)}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let n=getSessionTokenUsage(e.session),r=formatSessionTokenLimitMessage(e.violation.kind),i={inputTokens:n.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:n.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:i,message:r,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`||void 0,output:e.config.mode===`task`?r:``},session:e.session}}export{applySessionLimitContinuation,enforceSessionTokenLimit};
|