eve 0.52.3 → 0.52.5
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 +27 -0
- package/dist/src/cli/commands/init-agent-workspace.d.ts +2 -0
- package/dist/src/cli/commands/init-agent-workspace.js +1 -1
- package/dist/src/cli/commands/init-install.d.ts +8 -0
- package/dist/src/cli/commands/init-install.js +1 -0
- package/dist/src/cli/commands/init.d.ts +3 -4
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/registry-add-command.d.ts +3 -0
- package/dist/src/cli/commands/registry-add-command.js +1 -0
- package/dist/src/cli/commands/registry-metadata.d.ts +4 -1
- package/dist/src/cli/commands/registry-metadata.js +1 -1
- package/dist/src/cli/commands/registry.d.ts +1 -2
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/run.js +2 -2
- package/dist/src/cli/telemetry/index.d.ts +3 -0
- package/dist/src/cli/telemetry/index.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -2
- package/dist/src/compiled/@workflow/world-local/index.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +4 -4
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/dynamic-model-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +11 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/mock-model.js +1 -1
- package/dist/src/evals/reporters/index.d.ts +1 -0
- package/dist/src/evals/reporters/index.js +1 -1
- package/dist/src/evals/runner/reporters/datadog.d.ts +137 -0
- package/dist/src/evals/runner/reporters/datadog.js +3 -0
- package/dist/src/evals/runner/run-evals.d.ts +1 -1
- package/dist/src/evals/runner/run-evals.js +1 -1
- package/dist/src/execution/activity-cohort.d.ts +20 -0
- package/dist/src/execution/activity-cohort.js +1 -0
- package/dist/src/execution/authorization-callback-match.d.ts +1 -0
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-options.d.ts +10 -0
- package/dist/src/execution/sandbox/bindings/vercel-options.js +1 -0
- package/dist/src/execution/sandbox/bindings/vercel.js +2 -1
- package/dist/src/execution/sandbox/shell-quote.d.ts +1 -12
- package/dist/src/execution/sandbox/shell-quote.js +1 -1
- package/dist/src/execution/session-activity-projection.d.ts +2 -0
- package/dist/src/execution/session-activity-projection.js +1 -1
- package/dist/src/execution/session-command-inbox.js +1 -1
- package/dist/src/execution/skills/instructions.js +1 -1
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tool-auth.d.ts +4 -32
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/tools/connection-search.js +2 -2
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.d.ts +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/workflow/ask.d.ts +3 -2
- package/dist/src/execution/tools/workflow/ask.js +1 -1
- package/dist/src/execution/tools/workflow/authorization-completion.d.ts +3 -0
- package/dist/src/execution/tools/workflow/authorization-completion.js +1 -0
- package/dist/src/execution/tools/workflow/body.d.ts +2 -0
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/step-context.d.ts +31 -0
- package/dist/src/execution/tools/workflow/step-context.js +1 -0
- package/dist/src/execution/tools/workflow/step-execution.d.ts +3 -0
- package/dist/src/execution/tools/workflow/step-execution.js +1 -0
- package/dist/src/execution/tools/workflow/step.d.ts +3 -0
- package/dist/src/execution/tools/workflow/step.js +1 -0
- package/dist/src/execution/turn-workflow-tool-run.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +7 -0
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.d.ts +2 -0
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/approval-delivery-coordinator.js +1 -1
- package/dist/src/harness/authorization.d.ts +6 -2
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/current-messages.d.ts +8 -2
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/hitl/approval-input-requests.js +1 -1
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/pending-input-batches.d.ts +4 -0
- package/dist/src/harness/pending-input-batches.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-client-context.d.ts +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/mock-model-identity.d.ts +2 -0
- package/dist/src/internal/mock-model-identity.js +1 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/vercel/build-command.d.ts +2 -1
- package/dist/src/internal/vercel/build-command.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +3 -5
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -3
- package/dist/src/public/channels/github/checkout.js +1 -1
- package/dist/src/public/channels/slack/activity.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/runtime/authorization-context.d.ts +14 -0
- package/dist/src/runtime/authorization-context.js +1 -0
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +18 -2
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/sandbox/keys.js +1 -1
- package/dist/src/sandbox/backends/default.d.ts +2 -0
- package/dist/src/sandbox/backends/default.js +1 -1
- package/dist/src/self-modification/agent.d.ts +5 -2
- package/dist/src/self-modification/agent.js +1 -1
- package/dist/src/self-modification/config.d.ts +52 -0
- package/dist/src/self-modification/config.js +1 -0
- package/dist/src/self-modification/credentials.d.ts +18 -0
- package/dist/src/self-modification/credentials.js +1 -0
- package/dist/src/self-modification/extension/eve-add.d.ts +7 -2
- package/dist/src/self-modification/extension/eve-add.js +1 -1
- package/dist/src/self-modification/extension/extension.d.ts +46 -1
- package/dist/src/self-modification/extension/extension.js +1 -1
- package/dist/src/self-modification/extension/instructions.js +23 -9
- package/dist/src/self-modification/extension/production-registry-add.d.ts +42 -0
- package/dist/src/self-modification/extension/production-registry-add.js +1 -0
- package/dist/src/self-modification/extension/tools/edit_file.js +1 -1
- package/dist/src/self-modification/extension/tools/publish.d.ts +7 -0
- package/dist/src/self-modification/extension/tools/publish.js +1 -0
- package/dist/src/self-modification/extension/tools/registry_add.d.ts +39 -7
- package/dist/src/self-modification/extension/tools/registry_add.js +1 -1
- package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -0
- package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
- package/dist/src/self-modification/filesystem.js +1 -1
- package/dist/src/self-modification/git-workspace.d.ts +31 -0
- package/dist/src/self-modification/git-workspace.js +1 -0
- package/dist/src/self-modification/git.d.ts +6 -0
- package/dist/src/self-modification/git.js +1 -0
- package/dist/src/self-modification/github-publisher.d.ts +27 -0
- package/dist/src/self-modification/github-publisher.js +2 -0
- package/dist/src/self-modification/identifiers.d.ts +4 -0
- package/dist/src/self-modification/identifiers.js +1 -0
- package/dist/src/self-modification/mode.d.ts +4 -0
- package/dist/src/self-modification/mode.js +1 -0
- package/dist/src/self-modification/network-policy.d.ts +1 -0
- package/dist/src/self-modification/network-policy.js +1 -0
- package/dist/src/self-modification/proposal.d.ts +39 -0
- package/dist/src/self-modification/proposal.js +2 -0
- package/dist/src/self-modification/sandbox.d.ts +25 -1
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/self-modification/setup.d.ts +34 -0
- package/dist/src/self-modification/setup.js +22 -0
- package/dist/src/self-modification/workspace-lock.d.ts +2 -0
- package/dist/src/self-modification/workspace-lock.js +1 -0
- package/dist/src/setup/integrations/registry.js +1 -1
- package/dist/src/setup/integrations/runner.js +1 -1
- package/dist/src/setup/integrations/self-modification/setup.d.ts +29 -0
- package/dist/src/setup/integrations/self-modification/setup.js +1 -0
- package/dist/src/setup/integrations/types.d.ts +2 -0
- package/dist/src/setup/integrations/types.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/empty-delivery.js +1 -1
- package/dist/src/shared/git.d.ts +16 -0
- package/dist/src/shared/git.js +1 -0
- package/dist/src/shared/shell-quote.d.ts +2 -0
- package/dist/src/shared/shell-quote.js +1 -0
- package/dist/src/shared/vercel-services.js +1 -1
- package/dist/src/tasks/delivery-context.d.ts +2 -2
- package/dist/src/tasks/delivery-context.js +2 -18
- package/dist/src/tasks/delivery-policy.js +1 -1
- package/dist/src/tasks/session-index.d.ts +1 -1
- package/dist/src/tasks/session-index.js +1 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +10 -0
- package/dist/src/tasks/session-task-cohorts.js +1 -0
- package/dist/src/tools/durable-callbacks.d.ts +18 -1
- package/dist/src/tools/durable-callbacks.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +5 -2
- package/docs/channels/overview.mdx +2 -0
- package/docs/channels/slack.mdx +2 -0
- package/docs/concepts/sessions-runs-and-streaming.md +2 -0
- package/docs/evals/reporters.mdx +20 -1
- package/docs/evals/running.mdx +3 -1
- package/docs/guides/dynamic-capabilities.md +36 -1
- package/docs/guides/instrumentation.md +3 -2
- package/docs/instructions.mdx +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/reference/telemetry.md +1 -1
- package/docs/reference/typescript-api.md +36 -35
- package/docs/sandbox.mdx +2 -0
- package/docs/subagents/index.mdx +10 -0
- package/docs/tools/overview.mdx +4 -2
- package/docs/tools/workflows.mdx +61 -2
- package/package.json +17 -1
- package/dist/src/self-modification/extension/source-lock.d.ts +0 -2
- package/dist/src/self-modification/extension/source-lock.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{toError}from"#shared/errors.js";import{defineTool}from"#tools/definition.js";import{stampDurableDynamicToolCallbacks}from"#tools/durable-callbacks.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{
|
|
2
|
-
`));a.sort((e,t)=>t.score-e.score);let d=a.slice(0,r).map(e=>e.item);if(d.length>0){let e=[...d,...o],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of d)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return s.map(e=>o.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:i}=readDiscoveredToolClosure(e),a=loadContext().get(ConnectionRegistryKey);if(a===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{toError}from"#shared/errors.js";import{defineTool}from"#tools/definition.js";import{stampDurableDynamicToolCallbacks}from"#tools/durable-callbacks.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{getAuthorizationResults,requestAuthorization}from"#harness/authorization.js";import{createAuthorizationExecution}from"#runtime/connections/scoped-authorization.js";import{isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(r!==void 0&&supportsInteractiveAuthorization(r))return{scope:n.connectionName,instanceId:n.instanceId,connection:{url:n.url??``},authorization:r}}async function completePendingAuthorizations(e,t,n){assertPendingConnectionAuthorizationInstances(e);for(let r of t){if(!getAuthorizationResults().some(e=>e.name===r.connectionName))continue;let t=await resolveInteractiveAuth(e,r.connectionName);t!==void 0&&await n.complete(t)}}async function executeConnectionSearch(e){let t=loadContext(),n=t.get(ConnectionRegistryKey);if(n===void 0)return[];let r=e.limit??10,i=tokenize(e.keywords),a=[],o=[],s=e.connection!==void 0&&e.connection!==``?n.getConnections().filter(t=>t.connectionName===e.connection):n.getConnections();if(e.connection&&s.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${n.getConnectionNames().join(`, `)}.`);let c=createAuthorizationExecution();await completePendingAuthorizations(n,s,c);let l=[];for(let e of s){let t;try{t=await n.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){let r=await resolveInteractiveAuth(n,e.connectionName);if(r!==void 0)try{let e=await c.handleError(t,r);l.push(...e.challenges)}catch(t){let n=toError(t);logger.warn(`connection authorization failed`,{connection:e.connectionName,error:n}),o.push({connection:e.connectionName,description:e.description,error:isConnectionAuthorizationFailedError(n)?n.message:`Failed to start authorization for "${e.connectionName}": ${n.message}`});continue}o.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),o.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),o.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(i,n);t>0&&a.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(l.length>0)return requestAuthorization(l);let u=o.filter(e=>e.error!==void 0);if(s.length>0&&u.length===s.length)throw Error(u.map(e=>e.error).join(`
|
|
2
|
+
`));a.sort((e,t)=>t.score-e.score);let d=a.slice(0,r).map(e=>e.item);if(d.length>0){let e=[...d,...o],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of d)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return s.map(e=>o.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:i}=readDiscoveredToolClosure(e),a=loadContext().get(ConnectionRegistryKey);if(a===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);assertPendingConnectionAuthorizationInstances(a);let o=await resolveInteractiveAuth(a,r),s=createAuthorizationExecution();o!==void 0&&await s.complete(o);try{return await a.getClient(r).executeTool(i,t,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){return await s.handleError(e,o)}}function assertPendingConnectionAuthorizationInstances(e){let t=new Map(e.getConnections().map(e=>[e.connectionName,e]));for(let e of getAuthorizationResults())if(e.instanceId!==void 0&&t.get(e.name)?.instanceId!==e.instanceId)throw Error(`Authorization for "${e.name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`)}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return r===void 0?`not-applicable`:await resolveApprovalPolicy(r)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),i=r===void 0||typeof r==`function`?void 0:r.response;return i===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await i(t)}async function resolveConnectionSearchDynamicTools(){let e=loadContext().get(ConnectionRegistryKey);if(!e||e.getConnections().length===0)return null;let t=e.getConnections().map(e=>e.connectionName),n=new Set(t),r=(loadContext().get(ConnectionSearchResultsKey)??[]).filter(e=>n.has(e.connection)),i={},a=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${t.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(a,{execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),i.connection_search=a;for(let t of r){let n=t.connection,r=t.tool,a=e.getConnectionApproval(n),o={connectionName:n,toolName:r},s=defineTool({description:t.description,inputSchema:t.inputSchema??{type:`object`},approval:a,outputSchema:t.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(o,e,t)}});stampDurableDynamicToolCallbacks(s,{execute:{callback:executeDiscoveredConnectionTool,closure:o},...a===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:o}},...a===void 0||typeof a==`function`||a.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:o}}}),i[qualifiedConnectionToolName(n,r)]=s}return i}export{resolveConnectionSearchDynamicTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.52.
|
|
1
|
+
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.52.5//executeSleepTool`;export{executeSleepTool};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
2
|
import { type TaskAuthorizationEventDelivery } from "#tasks/types.js";
|
|
3
|
-
/**
|
|
3
|
+
/** Accepts authorization events from the workflow task itself or an agent it owns. */
|
|
4
4
|
export declare function acceptTaskAuthorizationEventStep(input: {
|
|
5
5
|
readonly delivery: TaskAuthorizationEventDelivery;
|
|
6
6
|
readonly sessionState: DurableSessionState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus}from"#tasks/types.js";async function acceptTaskAuthorizationEventStep(e){"use step";let{hookPayload:t,taskId:n}=e.delivery,r=await readDurableSession(e.sessionState),i=findSessionTaskEntry(r.state,n);if(i===void 0)return!1;let a=getAgentHandleStore(r.state)?.handles??[],o=a.find(e=>e.phase===`claimed`&&e.ownerId===n&&e.identity.name===t.subagentName&&e.address.sessionId===t.childSessionId),s=a.filter(e=>e.phase===`reserved`&&e.ownerId===n&&e.identity.name===t.subagentName);if(o===void 0&&s.length!==1)return!1;let c=await readLatestTaskView({taskRunId:i.taskRunId});return c!==void 0&&!isTerminalTaskStatus(c.status)}export{acceptTaskAuthorizationEventStep};
|
|
1
|
+
import{readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus}from"#tasks/types.js";async function acceptTaskAuthorizationEventStep(e){"use step";let{hookPayload:t,taskId:n}=e.delivery,r=await readDurableSession(e.sessionState),i=findSessionTaskEntry(r.state,n);if(i===void 0)return!1;if(i.metadata.kind===`tool`&&i.taskRunId===t.childSessionId&&i.metadata.name===t.subagentName&&i.createdByTurnId===t.event.data.turnId){let e=await readLatestTaskView({taskRunId:i.taskRunId});return e!==void 0&&(t.event.type===`authorization.completed`||!isTerminalTaskStatus(e.status))}let a=getAgentHandleStore(r.state)?.handles??[],o=a.find(e=>e.phase===`claimed`&&e.ownerId===n&&e.identity.name===t.subagentName&&e.address.sessionId===t.childSessionId),s=a.filter(e=>e.phase===`reserved`&&e.ownerId===n&&e.identity.name===t.subagentName);if(o===void 0&&s.length!==1)return!1;let c=await readLatestTaskView({taskRunId:i.taskRunId});return c!==void 0&&!isTerminalTaskStatus(c.status)}export{acceptTaskAuthorizationEventStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{createHook}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{createHook}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{readWorkflowToolRunAdmission,readWorkflowToolRunOwner,readWorkflowToolRunRef}from"#execution/tools/workflow/ask.js";const AGENT_INVOCATION_IDS=Symbol.for(`eve.workflow-tool-run.agent-invocation-ids`);async function agent(e,t){return validateAgentInput(t,!0),readWorkflowToolRunRef(e),await invokeAgent(e,{agentId:t.agentId,message:t.message,outputSchema:t.outputSchema,target:t.target},{invocationId:`${e.callId}:${t.key}`})}async function invokeAgent(e,t,n){validateAgentInput(t,!1);let r=readWorkflowToolRunRef(e),i=readWorkflowToolRunOwner(e),a=readWorkflowToolRunAdmission(e);if(claimInvocationId(e,n.invocationId),a!==void 0){let e=await a;if(e.status===`rejected`)throw Error(e.reason)}let o=createHook();try{await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:o.token,request:{input:t,invocationId:n.invocationId,kind:`agent-invoke`}});let a=o[Symbol.asyncIterator]();for(;;){let t=await nextAgentReply(a,e.abortSignal);if(t.done)break;let s=t.value;if(s.kind===`runtime-action-result`){let e=s.results.find(e=>e.kind===`subagent-result`&&e.callId===n.invocationId);if(e!==void 0){if(e.origin===`child`&&await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:o.token,request:{kind:`agent-settled`,result:e}}),n.returnResult===!0&&r.execution===`blocking`)return e;if(e.isError===!0)throw e.output;return e.output}continue}if(s.kind===`subagent-input-request`){await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:s.childSessionInbox?.sessionId===s.childSessionId?sessionCommandHookToken(s.childSessionInbox.sessionId):s.childContinuationToken,request:{kind:`input-batch`,requests:s.event.requests},requestCoordinates:{sequence:s.event.sequence,stepIndex:s.event.stepIndex,turnId:s.event.turnId}});continue}if(s.kind===`task-update`){await resumeHookStep(i.inbox,{kind:`report`,from:r,update:s.message});continue}await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:o.token,request:{event:s,kind:`authorization-request`}})}}finally{try{await disposeHook(o)}catch{}}throw Error(`Agent "${t.target}" closed without a result.`)}async function nextAgentReply(e,t){if(t===void 0)return await e.next();if(t.aborted)throw t.reason;let n,r=new Promise((e,t)=>{n=t}),abort=()=>n?.(t.reason);t.addEventListener(`abort`,abort,{once:!0});try{return await Promise.race([e.next(),r])}finally{t.removeEventListener(`abort`,abort)}}function validateAgentInput(e,t){if(t&&(typeof e.key!=`string`||e.key.trim()===``))throw TypeError("agent() requires a non-empty `key`.");if(typeof e.target!=`string`||e.target.trim()===``)throw TypeError("agent() requires a non-empty `target`.");if(typeof e.message!=`string`||e.message.trim()===``)throw TypeError("agent() requires a non-empty `message`.")}function claimInvocationId(e,t){let n=e,r=n[AGENT_INVOCATION_IDS]??new Set;if(r.has(t)){let e=t.lastIndexOf(`:`),n=e<0?t:t.slice(e+1);throw TypeError(`agent() invocation key "${n}" was already used in this run; keys must be unique per run.`)}r.add(t),n[AGENT_INVOCATION_IDS]===void 0&&Object.defineProperty(n,AGENT_INVOCATION_IDS,{enumerable:!1,value:r})}export{agent,invokeAgent,validateAgentInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSubagentCalledEvent}from"#protocol/message.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{projectToDurableSession}from"#execution/session.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{clearProxyInputRequestsForChild,clearProxyInputRequestsForTask}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{abandonAgentInvocationOwners,applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createSubagentReceiptIdentity}from"#execution/tools/subagent/receipt-identity.js";import{createAgentErrorResult,dispatchToClaimedAgentAddress}from"#subagents/handle-dispatch.js";import{createAgentContinuationBundle}from"#subagents/continuation-bundle.js";import{startSubagent}from"#execution/tools/subagent/start.js";import{prepareOwnerAgentInvocation}from"#execution/tools/subagent/invoke-preparation.js";async function dispatchAgentInvocation(e){let t=await readDurableSession(e.sessionState),n=getAgentHandleStore(t.state)?.handles??[],r=await prepareOwnerAgentInvocation({invocation:e.request.input,invocationId:e.request.invocationId,knownAgentIds:n.map(e=>e.identity.id),serializedContext:e.serializedContext,sessionState:e.sessionState}),i=r.plan[0];if(i===void 0)throw Error(`Agent invocation produced no executable plan entry.`);let a=r.session,currentAgentHandles=()=>getAgentHandleStore(a.state)?.handles??[],sessionState=()=>replaceDurableSessionSnapshot({session:projectToDurableSession(a),state:e.sessionState}),applyHandleCommand=e=>{let t=applyTaskAgentHandleCommand(a,e);return a=t.session,t.result};if(i.kind===`reject`)return{kind:`failed`,result:i.result,sessionState:sessionState()};let o,s;if(i.kind===`resume`){let t=currentAgentHandles().filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId&&t.callId===i.action.callId&&t.identity.id===i.agentId);if(t.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple claims for "${i.action.callId}".`);let n=t[0];if(n===void 0){let t=deriveAgentOperationId({callId:i.action.callId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId}),a=applyHandleCommand({agentId:i.agentId,callId:i.action.callId,expectedTarget:i.action.kind===`remote-agent-call`?`remote`:`local`,invokedName:i.action.kind===`remote-agent-call`?i.action.remoteAgentName:i.action.subagentName,kind:`claim`,operationId:t,ownerId:e.ownerId});if(n=readClaimedHandle(a),n===void 0)return{kind:`failed`,result:createTaskClaimError(i.action,i.agentId,a),sessionState:sessionState()}}let c=createAgentContinuationBundle({action:i.action,bundle:r.bundle,dynamicRemoteAgent:i.dynamicRemoteAgent});o=await dispatchToClaimedAgentAddress({action:i.action,auth:r.auth,bundle:c,currentSession:a,parentToken:e.replyTo,handle:n,taskId:e.taskId}),o.kind===`error`&&o.deliveryPermanent===!0&&applyHandleCommand({agentId:i.agentId,kind:`remove`,ownerId:e.ownerId}),s=n.identity.id}else{let t=i.target.action,n=currentAgentHandles().filter(n=>n.phase===`reserved`&&n.ownerId===e.ownerId&&n.callId===t.callId&&n.identity.name===t.name&&n.identity.nodeId===t.nodeId),c=n.length===1?{identity:n[0].identity,operation:{id:n[0].operationId}}:createSubagentReceiptIdentity({callId:t.callId,subagentName:t.kind===`remote-agent-call`?t.remoteAgentName:t.subagentName,nodeId:t.nodeId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId});if(n.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple reservations for "${t.callId}".`);if(n.length===0&&applyHandleCommand({identity:c.identity,callId:t.callId,kind:`reserve`,operationId:c.operation.id,ownerId:e.ownerId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${c.operation.id}".`);if(o=await startSubagent({auth:r.auth,batchEvent:r.batch.event,bundle:r.bundle,callbackBaseUrl:e.callbackBaseUrl,capabilities:r.capabilities,channelMetadata:r.channelMetadata,currentSession:a,fanoutSize:r.fanoutSize,initiatorAuth:r.initiatorAuth,localDevRequest:r.localDevRequest,parentContinuationToken:e.replyTo,parentTraceContext:r.parentTraceContext,sandboxSessionId:r.sandboxSessionId,serializedContext:r.serializedContext,session:a,taskId:e.taskId,target:i.target}),s=c.identity.id,o.kind===`error`)applyHandleCommand({agentId:s,kind:`remove`,ownerId:e.ownerId});else if(readClaimedHandle(applyHandleCommand({address:o.address,kind:`confirm`,operationId:c.operation.id,ownerId:e.ownerId}))===void 0)throw Error(`Agent handle store could not confirm start operation "${c.operation.id}".`)}if(o.kind===`error`)return{kind:`failed`,result:o.result,sessionState:sessionState()};let c=i.kind===`resume`?i.action:i.target.action,l=i.kind===`resume`?i.dynamicRemoteAgent:i.target.kind===`remote`?i.target.dynamicRemoteAgent:void 0,u=createSubagentCalledEvent({agentId:s,callId:o.callId,childSessionId:o.address.sessionId,name:o.name,remote:o.address.kind===`agent/remote`?{resolverId:l===void 0?c.nodeId:l.credentialsStepId,url:o.address.url}:void 0,sequence:r.batch.event.sequence,sessionId:r.session.sessionId,toolName:o.toolName,turnId:r.batch.event.turnId,workflowId:workflowEntryReference.workflowId});return e.emit!==void 0&&await e.emit(u),{kind:`dispatched`,agentId:s,event:u,sessionState:sessionState()}}async function dispatchTaskAgentInvocationStep(e){"use step";if(e.taskId!==void 0){let t=await readDurableSession(e.sessionState),n=findSessionTaskEntry(t.state,e.taskId);if(n===void 0)return{kind:`not-admitted`,sessionState:e.sessionState};let r=await readLatestTaskView({taskRunId:n.taskRunId});if(r===void 0||isTerminalTaskStatus(r.status))return{kind:`not-admitted`,sessionState:e.sessionState}}return await dispatchAgentInvocation({...e,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url)})}async function settleTaskAgentInvocationStep(e){"use step";let t=await readDurableSession(e.sessionState),n=getAgentHandleStore(t.state)?.handles??[],r=n.filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId),i=r.find(t=>t.phase===`claimed`&&t.callId===e.result.callId)??(r.length===1?r[0]:void 0);if(i?.phase!==`claimed`)return{sessionState:e.sessionState};let a=e.result.outcome.kind===`terminal`?n.filter(e=>e!==i):n.map(t=>t===i?e.result.outcome.result.kind===`cancelled`?{address:i.address,identity:i.identity,lastStatus:`(cancelled)`,phase:`parked`}:{address:i.address,identity:i.identity,phase:`available`}:t),o=writeHandles(t,a);return e.result.outcome.kind===`terminal`&&(o=e.taskId===void 0?`continuationToken`in i.address?clearProxyInputRequestsForChild(o,i.address.continuationToken):o:clearProxyInputRequestsForTask(o,e.taskId)),e.accumulateUsage!==!1&&(o=setTurnUsageState(o,accumulateSessionUsage({previous:getTurnUsageState(o.state),usage:e.result.outcome.usageDelta}))),{sessionState:replaceDurableSessionSnapshot({session:o,state:e.sessionState})}}async function releaseAgentInvocationOwnerStep(e){"use step";let t=await readDurableSession(e.sessionState),n=e.cancelled?abandonAgentInvocationOwners(t,new Set([e.ownerId])):applyTaskAgentHandleCommand(t,{kind:`release-owner`,ownerId:e.ownerId}).session;return{sessionState:n===t?e.sessionState:replaceDurableSessionSnapshot({session:n,state:e.sessionState})}}function readClaimedHandle(e){let t=e.kind===`ready`?e.handle:void 0;return t?.phase===`claimed`?t:void 0}function createTaskClaimError(e,t,n){return n.kind===`mismatch`?createAgentErrorResult({action:e,code:AGENT_MISMATCH,message:`Agent "${t}" no longer matches this subagent definition. Start a new agent instead.`}):n.kind===`busy`?createAgentErrorResult({action:e,code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:t,agentName:n.handle.identity.name,ownerId:`ownerId`in n.handle?n.handle.ownerId:void 0})}):createAgentErrorResult({action:e,code:AGENT_UNREACHABLE,message:`Agent with id "${t}" is no longer reachable.`})}export{dispatchAgentInvocation,dispatchTaskAgentInvocationStep,releaseAgentInvocationOwnerStep,settleTaskAgentInvocationStep};
|
|
1
|
+
import{createSubagentCalledEvent}from"#protocol/message.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{projectToDurableSession}from"#execution/session.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{clearProxyInputRequestsForChild,clearProxyInputRequestsForTask}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{abandonAgentInvocationOwners,applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createSubagentReceiptIdentity}from"#execution/tools/subagent/receipt-identity.js";import{createAgentErrorResult,dispatchToClaimedAgentAddress}from"#subagents/handle-dispatch.js";import{createAgentContinuationBundle}from"#subagents/continuation-bundle.js";import{startSubagent}from"#execution/tools/subagent/start.js";import{prepareOwnerAgentInvocation}from"#execution/tools/subagent/invoke-preparation.js";async function dispatchAgentInvocation(e){let t=await readDurableSession(e.sessionState),n=getAgentHandleStore(t.state)?.handles??[],r=await prepareOwnerAgentInvocation({invocation:e.request.input,invocationId:e.request.invocationId,knownAgentIds:n.map(e=>e.identity.id),serializedContext:e.serializedContext,sessionState:e.sessionState}),i=r.plan[0];if(i===void 0)throw Error(`Agent invocation produced no executable plan entry.`);let a=r.session,currentAgentHandles=()=>getAgentHandleStore(a.state)?.handles??[],sessionState=()=>replaceDurableSessionSnapshot({session:projectToDurableSession(a),state:e.sessionState}),applyHandleCommand=e=>{let t=applyTaskAgentHandleCommand(a,e);return a=t.session,t.result};if(i.kind===`reject`)return{kind:`failed`,result:i.result,sessionState:sessionState()};let o,s;if(i.kind===`resume`){let t=currentAgentHandles().filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId&&t.callId===i.action.callId&&t.identity.id===i.agentId);if(t.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple claims for "${i.action.callId}".`);let n=t[0];if(n===void 0){let t=deriveAgentOperationId({callId:i.action.callId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId}),a=applyHandleCommand({agentId:i.agentId,callId:i.action.callId,expectedTarget:i.action.kind===`remote-agent-call`?`remote`:`local`,invokedName:i.action.kind===`remote-agent-call`?i.action.remoteAgentName:i.action.subagentName,kind:`claim`,operationId:t,ownerId:e.ownerId});if(n=readClaimedHandle(a),n===void 0)return{kind:`failed`,result:createTaskClaimError(i.action,i.agentId,a),sessionState:sessionState()}}let c=createAgentContinuationBundle({action:i.action,bundle:r.bundle,dynamicRemoteAgent:i.dynamicRemoteAgent});o=await dispatchToClaimedAgentAddress({action:i.action,auth:r.auth,bundle:c,currentSession:a,parentToken:e.replyTo,handle:n,taskId:e.taskId}),o.kind===`error`&&o.deliveryPermanent===!0&&applyHandleCommand({agentId:i.agentId,kind:`remove`,ownerId:e.ownerId}),s=n.identity.id}else{let t=i.target.action,n=currentAgentHandles().filter(n=>n.phase===`reserved`&&n.ownerId===e.ownerId&&n.callId===t.callId&&n.identity.name===t.name&&n.identity.nodeId===t.nodeId),c=n.length===1?{identity:n[0].identity,operation:{id:n[0].operationId}}:createSubagentReceiptIdentity({callId:t.callId,subagentName:t.kind===`remote-agent-call`?t.remoteAgentName:t.subagentName,nodeId:t.nodeId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId});if(n.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple reservations for "${t.callId}".`);if(n.length===0&&applyHandleCommand({identity:c.identity,callId:t.callId,kind:`reserve`,operationId:c.operation.id,ownerId:e.ownerId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${c.operation.id}".`);if(o=await startSubagent({auth:r.auth,batchEvent:r.batch.event,bundle:r.bundle,callbackBaseUrl:e.callbackBaseUrl,capabilities:r.capabilities,channelMetadata:r.channelMetadata,currentSession:a,fanoutSize:r.fanoutSize,initiatorAuth:r.initiatorAuth,localDevRequest:r.localDevRequest,parentContinuationToken:e.replyTo,activityObserver:r.activityObserver,parentTraceContext:r.parentTraceContext,sandboxSessionId:r.sandboxSessionId,serializedContext:r.serializedContext,session:a,taskId:e.taskId,target:i.target}),s=c.identity.id,o.kind===`error`)applyHandleCommand({agentId:s,kind:`remove`,ownerId:e.ownerId});else if(readClaimedHandle(applyHandleCommand({address:o.address,kind:`confirm`,operationId:c.operation.id,ownerId:e.ownerId}))===void 0)throw Error(`Agent handle store could not confirm start operation "${c.operation.id}".`)}if(o.kind===`error`)return{kind:`failed`,result:o.result,sessionState:sessionState()};let c=i.kind===`resume`?i.action:i.target.action,l=i.kind===`resume`?i.dynamicRemoteAgent:i.target.kind===`remote`?i.target.dynamicRemoteAgent:void 0,u=createSubagentCalledEvent({agentId:s,callId:o.callId,childSessionId:o.address.sessionId,name:o.name,remote:o.address.kind===`agent/remote`?{resolverId:l===void 0?c.nodeId:l.credentialsStepId,url:o.address.url}:void 0,sequence:r.batch.event.sequence,sessionId:r.session.sessionId,toolName:o.toolName,turnId:r.batch.event.turnId,workflowId:workflowEntryReference.workflowId});return e.emit!==void 0&&await e.emit(u),{kind:`dispatched`,agentId:s,event:u,sessionState:sessionState()}}async function dispatchTaskAgentInvocationStep(e){"use step";if(e.taskId!==void 0){let t=await readDurableSession(e.sessionState),n=findSessionTaskEntry(t.state,e.taskId);if(n===void 0)return{kind:`not-admitted`,sessionState:e.sessionState};let r=await readLatestTaskView({taskRunId:n.taskRunId});if(r===void 0||isTerminalTaskStatus(r.status))return{kind:`not-admitted`,sessionState:e.sessionState}}return await dispatchAgentInvocation({...e,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url)})}async function settleTaskAgentInvocationStep(e){"use step";let t=await readDurableSession(e.sessionState),n=getAgentHandleStore(t.state)?.handles??[],r=n.filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId),i=r.find(t=>t.phase===`claimed`&&t.callId===e.result.callId)??(r.length===1?r[0]:void 0);if(i?.phase!==`claimed`)return{sessionState:e.sessionState};let a=e.result.outcome.kind===`terminal`?n.filter(e=>e!==i):n.map(t=>t===i?e.result.outcome.result.kind===`cancelled`?{address:i.address,identity:i.identity,lastStatus:`(cancelled)`,phase:`parked`}:{address:i.address,identity:i.identity,phase:`available`}:t),o=writeHandles(t,a);return e.result.outcome.kind===`terminal`&&(o=e.taskId===void 0?`continuationToken`in i.address?clearProxyInputRequestsForChild(o,i.address.continuationToken):o:clearProxyInputRequestsForTask(o,e.taskId)),e.accumulateUsage!==!1&&(o=setTurnUsageState(o,accumulateSessionUsage({previous:getTurnUsageState(o.state),usage:e.result.outcome.usageDelta}))),{sessionState:replaceDurableSessionSnapshot({session:o,state:e.sessionState})}}async function releaseAgentInvocationOwnerStep(e){"use step";let t=await readDurableSession(e.sessionState),n=e.cancelled?abandonAgentInvocationOwners(t,new Set([e.ownerId])):applyTaskAgentHandleCommand(t,{kind:`release-owner`,ownerId:e.ownerId}).session;return{sessionState:n===t?e.sessionState:replaceDurableSessionSnapshot({session:n,state:e.sessionState})}}function readClaimedHandle(e){let t=e.kind===`ready`?e.handle:void 0;return t?.phase===`claimed`?t:void 0}function createTaskClaimError(e,t,n){return n.kind===`mismatch`?createAgentErrorResult({action:e,code:AGENT_MISMATCH,message:`Agent "${t}" no longer matches this subagent definition. Start a new agent instead.`}):n.kind===`busy`?createAgentErrorResult({action:e,code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:t,agentName:n.handle.identity.name,ownerId:`ownerId`in n.handle?n.handle.ownerId:void 0})}):createAgentErrorResult({action:e,code:AGENT_UNREACHABLE,message:`Agent with id "${t}" is no longer reachable.`})}export{dispatchAgentInvocation,dispatchTaskAgentInvocationStep,releaseAgentInvocationOwnerStep,settleTaskAgentInvocationStep};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type Hook } from "#compiled/@workflow/core/index.js";
|
|
2
2
|
import type { WorkflowToolRunOwner, WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
|
|
3
3
|
import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
|
|
4
|
-
interface WorkflowToolRunContext {
|
|
4
|
+
export interface WorkflowToolRunContext {
|
|
5
|
+
readonly authorizationSupported?: boolean;
|
|
5
6
|
/** Compatibility for already-started two-run background workflows. */
|
|
6
7
|
readonly admission?: Promise<{
|
|
7
8
|
readonly status: "accepted";
|
|
@@ -13,9 +14,9 @@ interface WorkflowToolRunContext {
|
|
|
13
14
|
readonly owner: WorkflowToolRunOwner;
|
|
14
15
|
}
|
|
15
16
|
export declare function attachWorkflowToolRunContext(ctx: ToolContext, context: WorkflowToolRunContext): void;
|
|
17
|
+
export declare function findWorkflowToolRunContext(value: unknown): WorkflowToolRunContext | undefined;
|
|
16
18
|
export declare function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef;
|
|
17
19
|
export declare function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwner;
|
|
18
20
|
export declare function readWorkflowToolRunAdmission(ctx: ToolContext): WorkflowToolRunContext["admission"];
|
|
19
21
|
/** Returns an answer hook which may be awaited or raced with another workflow operation. */
|
|
20
22
|
export declare function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse>;
|
|
21
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";import{createHook}from"#compiled/@workflow/core/index.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function readWorkflowToolRunRef(e){return readWorkflowToolRunContext(e,`agent`).from}function readWorkflowToolRunOwner(e){return readWorkflowToolRunContext(e,`agent`).owner}function readWorkflowToolRunAdmission(e){return readWorkflowToolRunContext(e,`agent`).admission}function ask(e,t){let n=readWorkflowToolRunContext(e,`ask`),r=createHook();return resumeHookStep(n.owner.inbox,{kind:`request`,from:n.from,replyTo:r.token,request:{kind:`ask`,request:t}}),r}export{ask,attachWorkflowToolRunContext,readWorkflowToolRunAdmission,readWorkflowToolRunOwner,readWorkflowToolRunRef};
|
|
1
|
+
import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";import{createHook}from"#compiled/@workflow/core/index.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function findWorkflowToolRunContext(e){return typeof e==`object`&&e?e[WORKFLOW_TOOL_RUN_CONTEXT]:void 0}function readWorkflowToolRunRef(e){return readWorkflowToolRunContext(e,`agent`).from}function readWorkflowToolRunOwner(e){return readWorkflowToolRunContext(e,`agent`).owner}function readWorkflowToolRunAdmission(e){return readWorkflowToolRunContext(e,`agent`).admission}function ask(e,t){let n=readWorkflowToolRunContext(e,`ask`),r=createHook();return resumeHookStep(n.owner.inbox,{kind:`request`,from:n.from,replyTo:r.token,request:{kind:`ask`,request:t}}),r}export{ask,attachWorkflowToolRunContext,findWorkflowToolRunContext,readWorkflowToolRunAdmission,readWorkflowToolRunOwner,readWorkflowToolRunRef};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getStepMetadata,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{getRun}from"#internal/workflow/runtime.js";import{consumeAuthorizationResult,getAuthorizationResults}from"#harness/authorization.js";import{completeScopedAuthorization}from"#runtime/connections/scoped-authorization.js";async function completeWorkflowStepAuthorization(e){let t=getAuthorizationResults().find(t=>t.name===e.scope&&t.instanceId===e.instanceId);if(t===void 0)return!1;let{stepId:n,attempt:r}=getStepMetadata(),i=`eve.authorization.${n}.${t.attemptId}`;if(r>1){let t=getRun(getWorkflowMetadata().workflowRunId).getReadable({namespace:i});try{if(await t.getTailIndex()>=0)return consumeAuthorizationResult(e.scope,e.instanceId),!0}finally{await t.cancel().catch(()=>{})}}if(!await completeScopedAuthorization(e))return!1;let a=getWritable({namespace:i}).getWriter();try{await a.write(!0)}finally{a.releaseLock()}return!0}export{completeWorkflowStepAuthorization};
|
|
@@ -2,6 +2,8 @@ import type { SessionContext } from "#context/session-context.js";
|
|
|
2
2
|
import { type WorkflowToolRunOutcome, type WorkflowToolRunOwner, type WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
|
|
3
3
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
4
4
|
export interface WorkflowBodyDefinition {
|
|
5
|
+
/** Advertised by the parent driver; absent on runs started before this capability. */
|
|
6
|
+
readonly authorizationSupported?: boolean;
|
|
5
7
|
readonly callId: string;
|
|
6
8
|
readonly executeInput?: JsonValue;
|
|
7
9
|
readonly input: JsonObject;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{
|
|
1
|
+
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{createTaskMessage}from"#tools/task.js";import{ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{agent}from"#execution/tools/subagent/invoke-agent.js";import"#execution/tools/workflow/messages.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{readRegisteredWorkflow}from"#execution/workflow-registry.js";async function executeWorkflowBody(e,t){let n=createWorkflowBodyRef(e),r=createWorkflowBodyContext(e,t);attachWorkflowToolRunContext(r,{from:n,owner:e.owner,authorizationSupported:e.execution===`blocking`||e.authorizationSupported===!0});let i=0;try{let t=resolveWorkflowToolExecute(e),a=e.execution===`background`?createWorkflowTaskExec(e):void 0,o=t(e.executeInput??e.input,r,a),s;if(!isAsyncIterable(o))s=await o;else{let t=o[Symbol.asyncIterator](),r,a=await t.next();for(;a.done!==!0;){r=a.value;let o={from:n,update:a.value};await resumeHookStep(e.owner.inbox,{kind:`report`,...o}),i+=1,a=await t.next()}s=a.value??(e.execution===`blocking`?r:void 0)??null}return{outcome:{output:s,status:`completed`},reportCount:i}}catch(e){return t.aborted?{outcome:{reason:t.reason instanceof Error?t.reason.message:String(t.reason??``),status:`cancelled`},reportCount:i}:{outcome:{error:normalizeSerializableError(e),status:`failed`},reportCount:i}}}function createWorkflowBodyRef(e){return{callId:e.callId,execution:e.execution,input:e.input,resultKind:e.resultKind,runId:e.runId??getWorkflowMetadata().workflowRunId,sequence:e.session.turn.sequence,stepIndex:e.stepIndex,toolName:e.toolName,turnId:e.session.turn.id}}function resolveWorkflowToolExecute(e){let t=readRegisteredWorkflow(e.workflowId);if(typeof t!=`function`)throw Error(`Tool "${e.toolName}" is not registered as a workflow in this deployment (${e.workflowId}). The tool was renamed or removed after this run started.`);return t}function createWorkflowBodyContext(e,t){let unavailable=(t,n)=>{throw Error(`ctx.${t} is not available inside a workflow tool; ${n}. Tool "${e.toolName}" runs as a durable workflow body, which only replays deterministic code.`)},n={agent:e=>agent(n,e),ask:e=>ask(n,e),abortSignal:t,callId:e.callId,getSandbox:()=>unavailable(`getSandbox()`,`the session sandbox belongs to the turn`),getSkill:()=>unavailable(`getSkill()`,`skills are read through the session sandbox`),getToken:()=>unavailable(`getToken()`,`pass ctx directly to a "use step" helper to resolve credentials`),requireAuth:()=>unavailable(`requireAuth()`,`pass ctx directly to a "use step" helper to request authorization`),session:e.session,toolName:e.toolName};return n}function createWorkflowTaskExec(e){if(e.taskId===void 0)throw Error(`Background workflow tool "${e.toolName}" has no task id.`);return{binding:{taskId:e.taskId,token:e.taskId},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:void 0,task:void 0,taskId:e.taskId}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}export{createWorkflowBodyRef,executeWorkflowBody};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { SessionContext } from "#context/session-context.js";
|
|
2
|
+
import type { AuthorizationResult, AuthorizationSignal } from "#harness/authorization.js";
|
|
3
|
+
export type WorkflowStepAuthorizationResult = AuthorizationResult & {
|
|
4
|
+
readonly attemptId: string;
|
|
5
|
+
readonly name: string;
|
|
6
|
+
};
|
|
7
|
+
export interface WorkflowStepContext {
|
|
8
|
+
readonly authorizationSupported: boolean;
|
|
9
|
+
readonly callId: string;
|
|
10
|
+
readonly toolName: string;
|
|
11
|
+
readonly session: SessionContext["session"];
|
|
12
|
+
readonly abortSignal: AbortSignal;
|
|
13
|
+
readonly baseUrl: string;
|
|
14
|
+
readonly token: string;
|
|
15
|
+
readonly authorizationResults: readonly WorkflowStepAuthorizationResult[];
|
|
16
|
+
}
|
|
17
|
+
export type WorkflowStepResult = {
|
|
18
|
+
readonly authorized: readonly string[];
|
|
19
|
+
} & ({
|
|
20
|
+
readonly kind: "result";
|
|
21
|
+
readonly output: unknown;
|
|
22
|
+
} | {
|
|
23
|
+
readonly kind: "authorization-required";
|
|
24
|
+
readonly signal: AuthorizationSignal;
|
|
25
|
+
});
|
|
26
|
+
/** Compiler-owned envelope; contextIndexes marks arguments replaced with step-local context. */
|
|
27
|
+
export interface WorkflowStepInvocation {
|
|
28
|
+
readonly args: readonly unknown[];
|
|
29
|
+
readonly context: WorkflowStepContext;
|
|
30
|
+
readonly contextIndexes: readonly number[];
|
|
31
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type WorkflowStepInvocation } from "#execution/tools/workflow/step-context.js";
|
|
2
|
+
/** Keeps token capabilities and bearer values inside the executing step. */
|
|
3
|
+
export declare function withWorkflowStepAuthorization(execute: (...args: never[]) => unknown): (this: unknown, invocation: WorkflowStepInvocation) => Promise<unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SessionIdKey,SessionKey}from"#context/keys.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError}from"#connections/errors.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;return i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults),contextStorage.run(i,async()=>{let a=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization}),unavailable=()=>{throw new ConnectionAuthorizationFailedError(r.toolName,{message:`Background workflow tool "${r.toolName}" cannot use ctx.getToken or ctx.requireAuth in this session because its driver predates workflow-task authorization. Start a new session and try again.`,reason:`workflow_task_authorization_unsupported`,retryable:!1})},o={...buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}}),getToken:r.authorizationSupported?a.getToken:unavailable,requireAuth:r.authorizationSupported?a.requireAuth:unavailable},s;try{s=await a.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?o:e)))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}let c=i.get(PendingAuthorizationResultKey)??[],l=r.authorizationResults.filter(e=>!c.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(s)?{kind:`authorization-required`,signal:s,authorized:l}:{kind:`result`,output:s,authorized:l}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}export{withWorkflowStepAuthorization};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { WorkflowStepInvocation } from "#execution/tools/workflow/step-context.js";
|
|
2
|
+
/** Wraps a step proxy only when the caller explicitly passes its workflow tool context. */
|
|
3
|
+
export declare function workflowToolStep(original: (...args: unknown[]) => Promise<unknown>, execute: (invocation: WorkflowStepInvocation) => Promise<unknown>): (...args: unknown[]) => Promise<unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAuthorizationCompletedEvent,createAuthorizationRequiredEvent}from"#protocol/message.js";import{createHook,getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{findWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";function workflowToolStep(e,t){return new Proxy(e,{apply(e,n,r){let i=findWorkflowContextArgument(r);return i===void 0?Reflect.apply(e,n,r):executeAuthorizedStep(t,n,r,i)}})}function findWorkflowContextArgument(e){for(let t of e){let e=findWorkflowToolRunContext(t);if(e!==void 0)return{ctx:t,run:e}}}async function executeAuthorizedStep(e,t,n,r){let{ctx:i,run:a}=r,o=[],s=new Map;for(;;){let r=createHook();try{let c;try{c=await invokeAuthorizedStep({args:n,authorizationResults:o,callbackToken:r.token,ctx:i,execute:e,receiver:t,run:a})}catch(e){throw i.abortSignal.aborted||await reportPendingAsFailed(a,i.abortSignal,s),e}if(await reconcileCompletedAuthorizations(a,i.abortSignal,s,o,c.authorized),c.kind===`result`)return await reportPendingAsFailed(a,i.abortSignal,s),c.output;await collectAuthorizationCallbacks({authorizationResults:o,callback:r,challenges:c.signal.challenges,ctx:i,pending:s,run:a})}finally{await disposeHook(r)}}}async function invokeAuthorizedStep(e){let{args:t,authorizationResults:n,callbackToken:r,ctx:i,execute:a,receiver:o,run:s}=e,c={authorizationSupported:s.authorizationSupported===!0,callId:i.callId,toolName:i.toolName,session:i.session,abortSignal:i.abortSignal,baseUrl:getWorkflowMetadata().url,token:r,authorizationResults:n},l={args:t.map(e=>e===i?null:e),context:c,contextIndexes:t.flatMap((e,t)=>e===i?[t]:[])};return await a.call(o,l)}async function reconcileCompletedAuthorizations(e,t,n,r,i){let a=new Set(i);for(let r of a){let i=n.get(r);i!==void 0&&await reportAuthorization(e,t,i,`authorized`),n.delete(r)}for(let e=r.length-1;e>=0;e--){let t=r[e];t!==void 0&&a.has(t.attemptId)&&r.splice(e,1)}}async function collectAuthorizationCallbacks(e){let{authorizationResults:t,callback:n,challenges:r,ctx:i,pending:a,run:o}=e;for(let e of r){let r=requireAttemptId(e);a.set(r.attemptId,r),await reportAuthorization(o,i.abortSignal,r);try{let e=await waitForCallback(n,r,i.abortSignal);t.push({name:r.name,instanceId:r.instanceId,attemptId:r.attemptId,hookUrl:r.hookUrl,principal:r.principal,resume:r.resume,callback:e})}catch(e){throw i.abortSignal.aborted||await reportAuthorization(o,i.abortSignal,r,`failed`),e}}}function requireAttemptId(e){if(e.attemptId===void 0)throw Error(`Workflow authorization challenge "${e.name}" has no attempt id.`);return e}async function reportPendingAsFailed(e,t,n){for(let r of n.values())await reportAuthorization(e,t,r,`failed`)}async function reportAuthorization(e,t,n,r){let i={attemptId:n.attemptId,name:n.name,sequence:e.from.sequence,stepIndex:e.from.stepIndex,turnId:e.from.turnId,authorization:n.challenge},a=r===void 0?createAuthorizationRequiredEvent({...i,description:`Sign in to ${n.name} to continue.`,webhookUrl:n.hookUrl}):createAuthorizationCompletedEvent({...i,outcome:r}),o=createHook();try{await withAbort(resumeHookStep(e.owner.inbox,{kind:`request`,from:e.from,replyTo:o.token,request:{kind:`authorization-request`,event:{kind:`subagent-authorization-event`,callId:e.from.callId,childSessionId:e.from.runId,subagentName:e.from.toolName,event:a}}}),t),await withAbort(o,t)}finally{await disposeHook(o)}}async function waitForCallback(e,t,n){let r=e[Symbol.asyncIterator]();for(;;){let e=await withAbort(r.next(),n);if(e.done)throw Error(`Authorization callback closed before sign-in completed.`);let i=readCallback(e.value,t);if(i!==void 0)return i}}async function withAbort(e,t){let abort,n=new Promise((e,n)=>{abort=()=>n(t.reason??Error(`Workflow authorization cancelled.`)),t.addEventListener(`abort`,abort,{once:!0}),t.aborted&&abort()});try{return await Promise.race([e,n])}finally{t.removeEventListener(`abort`,abort)}}function readCallback(e,t){if(typeof e==`object`&&e&&`payloads`in e&&Array.isArray(e.payloads))for(let n of e.payloads){let e=n?.authorizationCallback;if(e?.attemptId!==t.attemptId||e?.connectionName!==t.name)continue;let r=e.callback;if(!(typeof r?.method!=`string`||typeof r.params!=`object`||r.params===null||Array.isArray(r.params))&&Object.values(r.params).every(e=>typeof e==`string`)&&(r.body===void 0||typeof r.body==`string`))return r}}export{workflowToolStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{findWorkflowToolRun,isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{cancelAgentInvocationOwnerStep}from"#execution/tools/subagent/task-cancel.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";import{
|
|
1
|
+
import{findWorkflowToolRun,isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{cancelAgentInvocationOwnerStep}from"#execution/tools/subagent/task-cancel.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{workflowToolRunOutcomeToSubagentResult,workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload}from"#execution/tools/workflow/owner-inbox.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{releaseAgentInvocationOwnerStep}from"#execution/tools/subagent/invoke-step.js";import{emitWorkflowToolRunReportStep}from"#execution/tools/workflow/emit-workflow-tool-run-report-step.js";async function handleWorkflowToolRunMessage(e){let{message:t}=e;switch(t.kind){case`outcome`:return await handleWorkflowToolRunOutcome({...e,message:t});case`request`:await handleWorkflowToolRunRequest({...e,message:t});return;case`report`:await emitWorkflowToolRunReportStep({from:t.from,parentWritable:e.cursor.parentWritable,update:t.update});return}}async function handleWorkflowToolRunOutcome(e){let{cursor:t,message:n}=e,r=findWorkflowToolRun(t.sessionState.snapshot?.session.state,n.from.callId);if(r?.runId!==n.from.runId)return;let i=r.resultKind===`subagent`?await settleSubagentOutcome(e):workflowToolRunOutcomeToToolResult(n);await cancelAgentInvocationOwnerStep({ownerId:n.from.runId,serializedContext:t.serializedContext,sessionState:t.sessionState});let a=await releaseAgentInvocationOwnerStep({cancelled:n.result.status===`cancelled`,ownerId:n.from.runId,sessionState:t.sessionState});await t.adopt({serializedContext:t.serializedContext,sessionState:a.sessionState});let o=t.sessionState.snapshot?.session.state;return(i.kind===`subagent-result`?i.callId===n.from.callId&&isInboxSubagentResultFromRecordedWorkflowToolRun(o,i):isInboxToolResultFromRecordedWorkflowToolRun(o,i))?i:void 0}async function settleSubagentOutcome(e){let{cursor:t,message:n}=e,r=workflowToolRunOutcomeToSubagentResult(n);return r.origin===`child`&&await t.adopt(await applyTaskAgentRequest({accumulateUsage:!1,ownerId:n.from.runId,replyTo:n.from.runId,request:{kind:`agent-settled`,result:r}},requestContext(e))),r}async function handleWorkflowToolRunRequest(e){let{cursor:t,message:n}=e;if(n.request.kind===`agent-invoke`||n.request.kind===`agent-settled`){if(findWorkflowToolRun(t.sessionState.snapshot?.session.state,n.from.callId)?.runId!==n.from.runId){n.request.kind===`agent-invoke`&&await resumeHookStep(n.replyTo,{kind:`runtime-action-result`,results:[{callId:n.request.invocationId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`AGENT_INVOCATION_NOT_ADMITTED`,message:`The workflow tool run no longer owns this agent invocation.`},subagentName:n.request.input.target}]});return}await t.adopt(await applyTaskAgentRequest({accumulateUsage:n.from.resultKind!==`subagent`,ownerId:n.from.runId,replyTo:n.replyTo,request:n.request},requestContext(e)));return}if(n.request.kind===`authorization-request`){await t.adopt(await runProxySubagentEventStep({hookPayload:n.request.event,parentWritable:t.parentWritable,serializedContext:t.serializedContext,sessionState:t.sessionState})),n.request.event.childSessionId===n.from.runId&&await resumeHookStep(n.replyTo,null,{ifPresent:!0});return}await t.adopt(await runProxySubagentEventStep({...n.requestCoordinates===void 0?{answerHook:{runId:n.from.runId}}:{},hookPayload:workflowToolRunRequestToInputRequestPayload(n),parentWritable:t.parentWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))}function requestContext(e){return{callbackBaseUrl:resolveWorkflowCallbackBaseUrl(e.callbackMetadataUrl),parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}}export{handleWorkflowToolRunMessage};
|
|
@@ -5,6 +5,13 @@ export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[numbe
|
|
|
5
5
|
export declare const SESSION_INBOX_WIRE_VERSION: 1 | 2 | 3 | 4 | 5 | 6;
|
|
6
6
|
/** Hook metadata field advertising the consumer's inbox wire capability. */
|
|
7
7
|
export declare const SESSION_INBOX_WIRE_VERSION_METADATA_KEY = "sessionInboxWireVersion";
|
|
8
|
+
/**
|
|
9
|
+
* Hook metadata field advertising that the driver displays authorization
|
|
10
|
+
* events raised by a workflow task itself. Drivers pinned before this marker
|
|
11
|
+
* drop those events, so producers fail fast instead of waiting on a callback
|
|
12
|
+
* no channel will render.
|
|
13
|
+
*/
|
|
14
|
+
export declare const WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY = "workflowTaskAuthorization";
|
|
8
15
|
export declare const SESSION_INBOX_CONTEXT_KEY = "eve.sessionInbox";
|
|
9
16
|
/** Immutable inbox coordinates advertised by the receiving session's driver. */
|
|
10
17
|
export interface SessionInboxAddress {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const SESSION_INBOX_WIRE_VERSIONS=[1,2,3,4,5,6],SESSION_INBOX_WIRE_VERSION=SESSION_INBOX_WIRE_VERSIONS[SESSION_INBOX_WIRE_VERSIONS.length-1],SESSION_INBOX_WIRE_VERSION_METADATA_KEY=`sessionInboxWireVersion`,SESSION_INBOX_CONTEXT_KEY=`eve.sessionInbox`;function isSessionInboxAddress(e){return typeof e!=`object`||!e?!1:`sessionId`in e&&typeof e.sessionId==`string`&&e.sessionId.length>0&&!e.sessionId.includes(`:`)&&`version`in e&&typeof e.version==`number`&&Number.isSafeInteger(e.version)&&e.version>0}function isSessionInboxWireVersion(e){return SESSION_INBOX_WIRE_VERSIONS.some(t=>t===e)}var SessionInboxWireError=class extends Error{constructor(e){super(e),this.name=`SessionInboxWireError`}};export{SESSION_INBOX_CONTEXT_KEY,SESSION_INBOX_WIRE_VERSION,SESSION_INBOX_WIRE_VERSIONS,SESSION_INBOX_WIRE_VERSION_METADATA_KEY,SessionInboxWireError,isSessionInboxAddress,isSessionInboxWireVersion};
|
|
1
|
+
const SESSION_INBOX_WIRE_VERSIONS=[1,2,3,4,5,6],SESSION_INBOX_WIRE_VERSION=SESSION_INBOX_WIRE_VERSIONS[SESSION_INBOX_WIRE_VERSIONS.length-1],SESSION_INBOX_WIRE_VERSION_METADATA_KEY=`sessionInboxWireVersion`,WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY=`workflowTaskAuthorization`,SESSION_INBOX_CONTEXT_KEY=`eve.sessionInbox`;function isSessionInboxAddress(e){return typeof e!=`object`||!e?!1:`sessionId`in e&&typeof e.sessionId==`string`&&e.sessionId.length>0&&!e.sessionId.includes(`:`)&&`version`in e&&typeof e.version==`number`&&Number.isSafeInteger(e.version)&&e.version>0}function isSessionInboxWireVersion(e){return SESSION_INBOX_WIRE_VERSIONS.some(t=>t===e)}var SessionInboxWireError=class extends Error{constructor(e){super(e),this.name=`SessionInboxWireError`}};export{SESSION_INBOX_CONTEXT_KEY,SESSION_INBOX_WIRE_VERSION,SESSION_INBOX_WIRE_VERSIONS,SESSION_INBOX_WIRE_VERSION_METADATA_KEY,SessionInboxWireError,WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY,isSessionInboxAddress,isSessionInboxWireVersion};
|
|
@@ -5,6 +5,8 @@ type ResumedSessionInboxHook = Awaited<ReturnType<typeof resumeHook>>;
|
|
|
5
5
|
/** Resolves the consumer contract, encodes for it, and resumes that exact hook. */
|
|
6
6
|
export declare function resumeSessionInbox(address: string | SessionInboxAddress, command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload): Promise<ResumedSessionInboxHook>;
|
|
7
7
|
type SessionInboxHook = Awaited<ReturnType<typeof getHookByToken>>;
|
|
8
|
+
/** Whether the session's pinned driver displays authorization events raised by workflow tasks. */
|
|
9
|
+
export declare function sessionDriverSupportsWorkflowTaskAuthorization(sessionId: string): Promise<boolean>;
|
|
8
10
|
/** Selects the encoder understood by a persisted hook's consumer deployment. */
|
|
9
11
|
export declare function resolveSessionInboxWireTarget(hook: SessionInboxHook): Promise<SessionInboxWireTarget>;
|
|
10
12
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSessionCommandHookToken,sessionCommandHookToken}from"#execution/session-command-token.js";import{isObject}from"#shared/guards.js";import{SESSION_INBOX_WIRE_VERSION_METADATA_KEY,SessionInboxWireError,isSessionInboxAddress,isSessionInboxWireVersion}from"#execution/wire/session-inbox-contract.js";import{getHookByToken,getRawHookByToken,resumeHook}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{sessionInboxWire}from"#execution/wire/session-inbox-encoder.js";async function resumeSessionInbox(e,t){if(typeof e!=`string`){if(!isSessionInboxAddress(e))throw new SessionInboxWireError(`Session inbox target has an invalid address.`);if(!isSessionInboxWireVersion(e.version))throw new SessionInboxWireError(`Session inbox target declares unsupported wire version ${JSON.stringify(e.version)}.`);return await resumeHook(sessionCommandHookToken(e.sessionId),sessionInboxWire.encode(t,{version:e.version}))}let n=e;if(isStableInboxFastPathCompatible(n,t))return await resumeHook(n,sessionInboxWire.encode(t,{variant:`send`,version:0}));let r=await getHookByToken(n),i=await resolveSessionInboxWireTarget(r);return await resumeHook(r,sessionInboxWire.encode(t,i))}function isStableInboxFastPathCompatible(e,t){return!isSessionCommandHookToken(e)||t.kind===`cancel`&&t.tasks===!0?!1:!(`caller`in t&&t.caller?.activityObserver!==void 0)}async function resolveSessionInboxWireTarget(e){let t=isObject(e.metadata)?e.metadata:void 0;if(t!==void 0&&SESSION_INBOX_WIRE_VERSION_METADATA_KEY in t){let e=t[SESSION_INBOX_WIRE_VERSION_METADATA_KEY];if(isSessionInboxWireVersion(e))return{version:e};throw new SessionInboxWireError(`Session inbox target declares unsupported wire version ${JSON.stringify(e)}.`)}let n=sessionCommandHookToken(e.runId);if(e.token===n)return{variant:`send`,version:0};try{let t=await getRawHookByToken(n);if(t.runId!==e.runId)throw new SessionInboxWireError(`Stable session inbox ${JSON.stringify(n)} belongs to run ${JSON.stringify(t.runId)}, expected ${JSON.stringify(e.runId)}.`);return{variant:`send`,version:0}}catch(e){if(HookNotFoundError.is(e))return{variant:`deliver`,version:0};throw e}}export{resolveSessionInboxWireTarget,resumeSessionInbox};
|
|
1
|
+
import{isSessionCommandHookToken,sessionCommandHookToken}from"#execution/session-command-token.js";import{isObject}from"#shared/guards.js";import{SESSION_INBOX_WIRE_VERSION_METADATA_KEY,SessionInboxWireError,WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY,isSessionInboxAddress,isSessionInboxWireVersion}from"#execution/wire/session-inbox-contract.js";import{getHookByToken,getRawHookByToken,resumeHook}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{sessionInboxWire}from"#execution/wire/session-inbox-encoder.js";async function resumeSessionInbox(e,t){if(typeof e!=`string`){if(!isSessionInboxAddress(e))throw new SessionInboxWireError(`Session inbox target has an invalid address.`);if(!isSessionInboxWireVersion(e.version))throw new SessionInboxWireError(`Session inbox target declares unsupported wire version ${JSON.stringify(e.version)}.`);return await resumeHook(sessionCommandHookToken(e.sessionId),sessionInboxWire.encode(t,{version:e.version}))}let n=e;if(isStableInboxFastPathCompatible(n,t))return await resumeHook(n,sessionInboxWire.encode(t,{variant:`send`,version:0}));let r=await getHookByToken(n),i=await resolveSessionInboxWireTarget(r);return await resumeHook(r,sessionInboxWire.encode(t,i))}function isStableInboxFastPathCompatible(e,t){return!isSessionCommandHookToken(e)||t.kind===`cancel`&&t.tasks===!0?!1:!(`caller`in t&&t.caller?.activityObserver!==void 0)}async function sessionDriverSupportsWorkflowTaskAuthorization(e){let t=await getHookByToken(sessionCommandHookToken(e));return isObject(t.metadata)&&t.metadata[WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY]===!0}async function resolveSessionInboxWireTarget(e){let t=isObject(e.metadata)?e.metadata:void 0;if(t!==void 0&&SESSION_INBOX_WIRE_VERSION_METADATA_KEY in t){let e=t[SESSION_INBOX_WIRE_VERSION_METADATA_KEY];if(isSessionInboxWireVersion(e))return{version:e};throw new SessionInboxWireError(`Session inbox target declares unsupported wire version ${JSON.stringify(e)}.`)}let n=sessionCommandHookToken(e.runId);if(e.token===n)return{variant:`send`,version:0};try{let t=await getRawHookByToken(n);if(t.runId!==e.runId)throw new SessionInboxWireError(`Stable session inbox ${JSON.stringify(n)} belongs to run ${JSON.stringify(t.runId)}, expected ${JSON.stringify(e.runId)}.`);return{variant:`send`,version:0}}catch(e){if(HookNotFoundError.is(e))return{variant:`deliver`,version:0};throw e}}export{resolveSessionInboxWireTarget,resumeSessionInbox,sessionDriverSupportsWorkflowTaskAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowTaskCallIds,isWorkflowTaskInterrupt}from"#harness/workflow-task-state.js";import{TASK_UPDATE_SESSION_INSTRUCTION}from"#tools/framework/task-update.js";import{deferMismatchedInlineTurnStep}from"#execution/accepted-delivery-deployment.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";let t=deferMismatchedInlineTurnStep(e);if(t!==void 0)return t;let n=e,r=await readDurableSession(n.sessionState),i=await deserializeContext(n.serializedContext);e.input?.kind===`deliver`&&(i.set(TurnTaskDeliveryKey,`none`),i.delete(TurnTaskStateKey));let a=i.require(ChannelKey),o=i.require(BundleKey),s=resolveEffectiveAgentRuntime(o,i),c=r.taskId!==void 0&&s.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`task-update`);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(r.state),u;if(l&&n.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.input.payloads);if(n={...n,input:{...n.input,payloads:t}},e.length>0){let a=e.map(e=>e.result);i.set(PendingAuthorizationResultKey,a),r={...r,state:clearPendingAuthorization(r.state,a.map(e=>e.attemptId??e.name))},u=e,t.length===0&&(n={...n,input:void 0})}}n.input?.kind===`deliver`&&n.input.auth!==void 0&&i.set(AuthKey,n.input.auth??null);let d=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.thresholdPercent},durable:r,turnAgent:s.turnAgent}),f=createExecutionHistoryView(d),p=bindSessionInstrumentation({agentName:s.turnAgent.id,ctx:i,rootSessionId:d.rootSessionId??d.sessionId,sessionId:d.sessionId}),m=getHarnessEmissionState(d.state);e.input?.kind===`deliver`&&e.input.payloads.some(e=>e.message!==void 0)?i.set(TurnDeliveryIdsKey,e.input.deliveryMetadata?.map(e=>e.deliveryId)??[]):!m.sessionStarted&&i.get(ChannelDeliveryKey)!==void 0&&i.set(TurnDeliveryIdsKey,[i.require(ChannelDeliveryKey).deliveryId]),e.input?.kind===`deliver`&&await contextStorage.run(i,()=>p?.instrumentChannelDelivery({agentName:o.turnAgent.id,ctx:i,delivery:e.input,rootSessionId:d.rootSessionId??d.sessionId,sequence:m.sequence,sessionId:d.sessionId,turnId:activeTurnId(m)}));let failChannelDeliveries=async e=>{await contextStorage.run(i,()=>p?.instrumentChannelDelivery({ctx:i,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await p?.flush()},h=buildAdapterContext(a,i),g;if(n.input?.kind===`deliver`){let e=[];try{for(let t of n.input.payloads){let n=a.deliver?await a.deliver(t,h):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else n.input?.kind===`runtime-action-result`&&(n.input.acceptedAtMsByCallId!==void 0&&i.set(RuntimeActionSettlementTimesKey,n.input.acceptedAtMsByCallId),g={runtimeActionResults:n.input.results});if(g!==void 0&&e.input?.kind===`deliver`&&e.input.taskDeliveryId!==void 0){let t=resolveTaskDeliveryContext({state:r.state,taskDeliveryId:e.input.taskDeliveryId});t!==void 0&&(i.set(TurnTaskDeliveryKey,t.phase),g={...g,context:[...g.context??[],t.context]})}if(i.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:r.state,turnId:activeTurnId(m)});e!==void 0&&(i.set(TurnTaskDeliveryKey,e.phase),i.set(TurnTaskStateKey,e.context))}if(n.input?.kind===`deliver`){let e={...a,state:{...h.state}};setChannelContext(i,e)}if(n.input?.kind===`deliver`&&g===void 0){await contextStorage.run(i,()=>p?.instrumentChannelDelivery({ctx:i,includeTurn:!1,outcome:`completed`})),await p?.flush();let e=reconcileSessionContinuationToken(i,d),t=serializeContext(i),r=e===d?n.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r}}let _=o.hookRegistry,v=bindDynamicConnections(i,o.resolvedAgent),y=o.resolvedAgent.dynamicInstructionsResolvers??[],b=o.resolvedAgent.dynamicSkillResolvers??[],x=o.subagentRegistry.dynamicResolvers??[],S=o.resolvedAgent.dynamicToolResolvers??[],C={...o.graph.root,turnAgent:s.turnAgent},w=buildRuntimeIdentity(C);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(o.compiledArtifactsSource);if(!m.sessionStarted)i.set(SessionDynamicSubagentRuntimeRevisionKey,t),i.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:i,resolvers:x,event:e,messages:f.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:i,resolvers:S,event:e,messages:f.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:i,event:createTurnStartedEvent({sequence:m.sequence,turnId:activeTurnId(m)}),messages:f.initial.messages,resolvers:S})}}catch(e){throw await failChannelDeliveries(e),e}let T=n.parentWritable.getWriter(),emit=async e=>{let t=await callAdapterEventHandler(a,e,h);setChannelContext(i,{...a,state:{...h.state}});let n=stampMessageStreamEvent(t,i.get(TurnDeliveryIdsKey));return await T.write(encodeMessageStreamEvent(n)),n},handleEvent=async(e,t)=>{let r=await forwardTaskEventToSessionCallback(i,e)?stampMessageStreamEvent(e,i.get(TurnDeliveryIdsKey)):await emit(e),a=await dispatchMemoryLifecycleEvent({abortSignal:n.abortSignal,appRoot:C.agent?.metadata?.appRoot??``,ctx:i,event:e,memories:C.agent?.memories??[],messages:t,nodeId:o.nodeId??`__root__`});observeSessionActivity({ctx:i,event:r,sessionId:d.sessionId}),await dispatchStreamEventHooks({ctx:i,registry:_,event:r}),r.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:i,dynamicModel:s.turnAgent.dynamicModel,event:r,messages:a,scope:{moduleMap:o.moduleMap,nodeId:o.nodeId}}),await v.dispatch(r),await dispatchDynamicSubagentEvent({ctx:i,resolvers:x,event:r,messages:a}),await dispatchDynamicToolEvent({ctx:i,resolvers:S,event:r,messages:a}),await dispatchDynamicSkillEvent({ctx:i,resolvers:b,event:r,messages:a}),await dispatchDynamicInstructionEvent({ctx:i,resolvers:y,event:r,messages:a})},E=i.require(ModeKey),D;try{throwIfTurnAborted(n.abortSignal),D=await runBackgroundStep(i,d,async e=>{i.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:s.turnAgent.outputSchema,input:g,mode:E,session:e});if(await v.rehydrate(m,w,isHarnessBetweenTurns(t)),u){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(i,f.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:p});try{e=await emitTurnPreamble(handleEvent,{},e,w,r)}finally{n=drainDynamicInstructionUserMessages(i),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of u){let r=l?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let r=i.get(CapabilitiesKey);return(async(e,t)=>{let i=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:s.thresholdPercent},session:e,systemPromptAdditions:c?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:s.turnAgent}),a=i;return createExecutionNodeStep({abortSignal:n.abortSignal,capabilities:r,clearOnly:n.input?.kind===`clear`,compactOnly:n.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:f.projector,historyView:f.prepare(a),instrumentation:p,mode:E,modelResolutionScope:{moduleMap:o.moduleMap,nodeId:o.nodeId},node:C,workflowMaxSubagents:i.workflowMaxSubagents})(a,t)})(t,g)})}catch(e){if(!isTurnCancellation(e)&&n.abortSignal?.aborted!==!0)throw await failChannelDeliveries(e),e;T.releaseLock();let t=serializeContext(i),r=readRetainedBackgroundToolResult(i),a=await contextStorage.run(i,()=>preserveCancelledTurnMessage(r?.backgroundTaskSession??d,g));return{action:`cancelled`,...r===void 0?{}:{backgroundTaskState:createDurableSessionState({session:a}),backgroundTasks:r.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection({...n.serializedContext,[TurnDeliveryIdsKey.name]:t[TurnDeliveryIdsKey.name]},t),t),t),sessionState:createDurableSessionState({session:a})}}let O=reconcileSessionContinuationToken(i,D.session),k=serializeContext(i);D={...D,session:O};let A=createDurableSessionState({session:D.session}),j=D.backgroundTasks===void 0||D.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:D.backgroundTaskSession}),backgroundTasks:D.backgroundTasks};if(D.next!==null&&typeof D.next==`object`&&`done`in D.next){if(E===`task`&&hasPendingInputBatch(D.session.state))throw T.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await T.close();let e=getTurnUsageState(D.session.state)?.session;return{action:`done`,...j,output:D.next.output,isError:D.next.isError,serializedContext:k,sessionState:A,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(D.session).delta}}if(D.next===null){T.releaseLock();let e=getPendingWorkflowInterrupt(D.session.state);if(e!==void 0&&isWorkflowTaskInterrupt(e.interrupt))return{action:`dispatch-workflow-tasks`,...j,pendingTaskCallIds:getWorkflowTaskCallIds(e.interrupt),serializedContext:k,sessionState:A};let t=derivePendingState(D.session);if(D.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(D.session);return{action:`park`,...j,...t,serializedContext:k,sessionState:createDurableSessionState({session:n}),settled:{output:D.settledTurn.output,isError:D.settledTurn.isError,usage:e}}}return{action:`park`,...j,...t,serializedContext:k,sessionState:A}}return T.releaseLock(),{action:`continue`,...j,serializedContext:k,sessionState:A}}export{turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowTaskCallIds,isWorkflowTaskInterrupt}from"#harness/workflow-task-state.js";import{TASK_UPDATE_SESSION_INSTRUCTION}from"#tools/framework/task-update.js";import{deferMismatchedInlineTurnStep}from"#execution/accepted-delivery-deployment.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";import*as activityCohort from"#execution/activity-cohort.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";let t=deferMismatchedInlineTurnStep(e);if(t!==void 0)return t;let n=e,r=await readDurableSession(n.sessionState),i=await deserializeContext(n.serializedContext);e.input?.kind===`deliver`&&i.set(TurnTaskDeliveryKey,`none`);let a=i.require(ChannelKey),o=i.require(BundleKey),s=resolveEffectiveAgentRuntime(o,i),c=r.taskId!==void 0&&s.turnAgent.tools.some(e=>e.kind===`authored-tool`&&e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`task-update`);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(r.state),u;if(l&&n.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.input.payloads);if(n={...n,input:{...n.input,payloads:t}},e.length>0){let a=activityCohort.restoreAuthorizationActivity({ctx:i,matches:e,pending:l}),o=e.map(e=>e.result);i.set(PendingAuthorizationResultKey,o),r={...r,state:clearPendingAuthorization(r.state,a)},u=e,t.length===0&&(n={...n,input:void 0})}}n.input?.kind===`deliver`&&n.input.auth!==void 0&&i.set(AuthKey,n.input.auth??null);let d=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.thresholdPercent},durable:r,turnAgent:s.turnAgent}),f=createExecutionHistoryView(d),p=bindSessionInstrumentation({agentName:s.turnAgent.id,ctx:i,rootSessionId:d.rootSessionId??d.sessionId,sessionId:d.sessionId}),m=getHarnessEmissionState(d.state);e.input?.kind===`deliver`&&e.input.payloads.some(e=>e.message!==void 0)?i.set(TurnDeliveryIdsKey,e.input.deliveryMetadata?.map(e=>e.deliveryId)??[]):!m.sessionStarted&&i.get(ChannelDeliveryKey)!==void 0&&i.set(TurnDeliveryIdsKey,[i.require(ChannelDeliveryKey).deliveryId]),e.input?.kind===`deliver`&&await contextStorage.run(i,()=>p?.instrumentChannelDelivery({agentName:o.turnAgent.id,ctx:i,delivery:e.input,rootSessionId:d.rootSessionId??d.sessionId,sequence:m.sequence,sessionId:d.sessionId,turnId:activeTurnId(m)}));let failChannelDeliveries=async e=>{await contextStorage.run(i,()=>p?.instrumentChannelDelivery({ctx:i,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await p?.flush()},h=buildAdapterContext(a,i),g;if(n.input?.kind===`deliver`){let e=[];try{for(let t of n.input.payloads){let n=a.deliver?await a.deliver(t,h):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else n.input?.kind===`runtime-action-result`&&(n.input.acceptedAtMsByCallId!==void 0&&i.set(RuntimeActionSettlementTimesKey,n.input.acceptedAtMsByCallId),g={runtimeActionResults:n.input.results});let _;if(g!==void 0&&e.input?.kind===`deliver`&&e.input.taskDeliveryId!==void 0){let t=resolveTaskDeliveryContext({state:r.state,taskDeliveryId:e.input.taskDeliveryId});t!==void 0&&(i.set(TurnTaskDeliveryKey,t.phase),_=t.rootTurnId,g={...g,context:[...g.context??[],t.context]})}activityCohort.updateActivityRootForDelivery({activeTurnId:activeTurnId(m),ctx:i,delivery:e.input?.kind===`deliver`?e.input:void 0,sessionState:r.state,taskRootTurnId:_});let v=i.get(TurnTaskDeliveryKey);if(v===`none`||v===`initiating`){let e=resolveInitiatingTaskContext({state:r.state,turnId:activeTurnId(m)});e!==void 0&&i.set(TurnTaskDeliveryKey,e.phase)}if(n.input?.kind===`deliver`){let e={...a,state:{...h.state}};setChannelContext(i,e)}if(n.input?.kind===`deliver`&&g===void 0){await contextStorage.run(i,()=>p?.instrumentChannelDelivery({ctx:i,includeTurn:!1,outcome:`completed`})),await p?.flush();let e=reconcileSessionContinuationToken(i,d),t=serializeContext(i),r=e===d?n.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:r}}let y=o.hookRegistry,b=bindDynamicConnections(i,o.resolvedAgent),x=o.resolvedAgent.dynamicInstructionsResolvers??[],S=o.resolvedAgent.dynamicSkillResolvers??[],C=o.subagentRegistry.dynamicResolvers??[],w=o.resolvedAgent.dynamicToolResolvers??[],T={...o.graph.root,turnAgent:s.turnAgent},E=buildRuntimeIdentity(T);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(o.compiledArtifactsSource);if(!m.sessionStarted)i.set(SessionDynamicSubagentRuntimeRevisionKey,t),i.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:E});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:i,resolvers:C,event:e,messages:f.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:i,resolvers:w,event:e,messages:f.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:i,event:createTurnStartedEvent({sequence:m.sequence,turnId:activeTurnId(m)}),messages:f.initial.messages,resolvers:w})}}catch(e){throw await failChannelDeliveries(e),e}let D=n.parentWritable.getWriter(),emit=async e=>{let t=await callAdapterEventHandler(a,e,h);setChannelContext(i,{...a,state:{...h.state}});let n=stampMessageStreamEvent(t,i.get(TurnDeliveryIdsKey));return await D.write(encodeMessageStreamEvent(n)),n},handleEvent=async(e,t)=>{activityCohort.updateActivityBlockers(i,e);let r=await forwardTaskEventToSessionCallback(i,e)?stampMessageStreamEvent(e,i.get(TurnDeliveryIdsKey)):await emit(e),a=await dispatchMemoryLifecycleEvent({abortSignal:n.abortSignal,appRoot:T.agent?.metadata?.appRoot??``,ctx:i,event:e,memories:T.agent?.memories??[],messages:t,nodeId:o.nodeId??`__root__`});observeSessionActivity({ctx:i,event:r,sessionId:d.sessionId}),await dispatchStreamEventHooks({ctx:i,registry:y,event:r}),r.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:i,dynamicModel:s.turnAgent.dynamicModel,event:r,messages:a,scope:{moduleMap:o.moduleMap,nodeId:o.nodeId}}),await b.dispatch(r),await dispatchDynamicSubagentEvent({ctx:i,resolvers:C,event:r,messages:a}),await dispatchDynamicToolEvent({ctx:i,resolvers:w,event:r,messages:a}),await dispatchDynamicSkillEvent({ctx:i,resolvers:S,event:r,messages:a}),await dispatchDynamicInstructionEvent({ctx:i,resolvers:x,event:r,messages:a})},O=i.require(ModeKey),k;try{throwIfTurnAborted(n.abortSignal),k=await runBackgroundStep(i,d,async e=>{i.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:s.turnAgent.outputSchema,input:g,mode:O,session:e});if(await b.rehydrate(m,E,isHarnessBetweenTurns(t)),u){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(i,f.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:p});try{e=await emitTurnPreamble(handleEvent,{},e,E,r)}finally{n=drainDynamicInstructionUserMessages(i),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of u){let r=l?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let r=i.get(CapabilitiesKey);return(async(e,t)=>{let i=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:s.thresholdPercent},session:e,systemPromptAdditions:c?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:s.turnAgent}),a=i;return createExecutionNodeStep({abortSignal:n.abortSignal,capabilities:r,clearOnly:n.input?.kind===`clear`,compactOnly:n.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:f.projector,historyView:f.prepare(a),instrumentation:p,mode:O,modelResolutionScope:{moduleMap:o.moduleMap,nodeId:o.nodeId},node:T,workflowMaxSubagents:i.workflowMaxSubagents})(a,t)})(t,g)})}catch(e){if(!isTurnCancellation(e)&&n.abortSignal?.aborted!==!0)throw await failChannelDeliveries(e),e;D.releaseLock();let t=serializeContext(i),r=readRetainedBackgroundToolResult(i),a=await contextStorage.run(i,()=>preserveCancelledTurnMessage(r?.backgroundTaskSession??d,g));return{action:`cancelled`,...r===void 0?{}:{backgroundTaskState:createDurableSessionState({session:a}),backgroundTasks:r.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection({...n.serializedContext,[TurnDeliveryIdsKey.name]:t[TurnDeliveryIdsKey.name]},t),t),t),sessionState:createDurableSessionState({session:a})}}let A=reconcileSessionContinuationToken(i,k.session),j=serializeContext(i);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=k.backgroundTasks===void 0||k.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:k.backgroundTaskSession}),backgroundTasks:k.backgroundTasks};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){if(O===`task`&&hasPendingInputBatch(k.session.state))throw D.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,...N,output:k.next.output,isError:k.next.isError,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowTaskInterrupt(e.interrupt))return{action:`dispatch-workflow-tasks`,...N,pendingTaskCallIds:getWorkflowTaskCallIds(e.interrupt),serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...N,...t,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...N,...t,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...N,serializedContext:j,sessionState:M}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.js";import{resolveTextToResponses}from"#channel/resolve-text.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{buildApprovalResponseAuth,handleApprovalResponsePolicyError}from"#execution/tool-auth.js";import{clearPendingAuthorization,getAuthorizationResult,getPendingAuthorization,isAuthorizationSignal}from"#harness/authorization.js";import{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,settleAllowedCandidate,settleDirectApprovalResponse}from"#harness/approval-candidates.js";import{isApprovalRequest}from"#harness/input-request-class.js";
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.js";import{resolveTextToResponses}from"#channel/resolve-text.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{buildApprovalResponseAuth,handleApprovalResponsePolicyError}from"#execution/tool-auth.js";import{getPendingInputBatches}from"#harness/pending-input-batches.js";import{clearPendingAuthorization,getAuthorizationResult,getPendingAuthorization,isAuthorizationSignal}from"#harness/authorization.js";import{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,settleAllowedCandidate,settleDirectApprovalResponse}from"#harness/approval-candidates.js";import{isApprovalRequest}from"#harness/input-request-class.js";const UNAUTHENTICATED_APPROVAL_FEEDBACK=`Authentication is required to respond to this approval.`;function shouldPrepareApprovalPolicyTools(e){let t=getPendingInputBatches(e.session.state),n=[...(e.stepInput?.attributedInputResponses??[]).map(({response:e})=>e),...e.stepInput?.inputResponses??[]];if(t.some(e=>e.requests.some(e=>isApprovalRequest(e)&&n.some(t=>t.requestId===e.requestId))))return!1;let r=e.now??Date.now();return getApprovalAuditState(e.session.state).activeCandidates.some(e=>e.expiresAt>r&&(e.status===`pending`||(e.authorizationChallenges?.some(e=>getAuthorizationResult(e.name)!==void 0)??!1)))}function shouldPrepareApprovalReplayTools(e){if(shouldPrepareApprovalPolicyTools(e))return!0;let t=getPendingInputBatches(e.session.state),n=[...(e.stepInput?.attributedInputResponses??[]).map(({response:e})=>e),...e.stepInput?.inputResponses??[]],r=t.length===1?t[0]:void 0;r!==void 0&&typeof e.stepInput?.message==`string`&&!n.some(e=>r.requests.some(t=>t.requestId===e.requestId))&&n.push(...resolveTextToResponses(e.stepInput.message,r.requests.filter(e=>!r.responseAuthRequiredRequestIds?.includes(e.requestId))));let i=new Set(n.filter(e=>e.optionId===`approve`).map(e=>e.requestId));return t.some(e=>e.requests.some(e=>isApprovalRequest(e)&&i.has(e.requestId)))}async function coordinateApprovalDelivery(e){let t=e.now??Date.now(),n=getApprovalAuditState(e.session.state).activeCandidates.filter(e=>e.expiresAt<=t).flatMap(e=>e.authorizationChallenges?.map(e=>e.name)??[]),r=expireApprovalCandidates({now:t,state:e.session.state}),i={...e.session,state:clearPendingAuthorization(r,n)},a=getApprovalAuditState(i.state),o=getPendingInputBatches(i.state),s=new Set(o.flatMap(e=>e.requests.map(e=>e.requestId))),c=a.settlements.filter(e=>s.has(e.requestId)),l=new Set(a.settlements.map(e=>e.requestId)),u=hasResponseForRequest(e.stepInput,l),d=u?removeConsumedResponses(e.stepInput,l):e.stepInput;if(u&&c.length===0&&!hasMeaningfulInput(d))return deliveryResult(i,d,`park`);if(o.length===0)return deliveryResult(i,d);let f=d,p=new Set(o.flatMap(e=>e.responseAuthRequiredRequestIds??[])),m=o.flatMap(e=>e.requests),h=new Map(m.map(e=>[e.requestId,e])),g=[],_=[],v=new Set,y=!1,b=getApprovalAuditState(i.state).activeCandidates,x=[...f?.attributedInputResponses??[],...(f?.inputResponses??[]).map(e=>({auth:void 0,response:e}))];for(let{auth:e,response:n}of x){let r=h.get(n.requestId);if(r===void 0||!isApprovalRequest(r))continue;if(!p.has(n.requestId)){let r=contextStorage.getStore(),a=e===void 0?r?.get(AuthKey)??r?.get(SessionKey)?.auth.current??null:e;if(a!==null&&(n.optionId===`approve`||n.optionId===`cancel`)){let e=settleDirectApprovalResponse({actor:a,outcome:n.optionId===`approve`?`allowed`:`cancelled`,requestId:n.requestId,settledAt:t,state:i.state});i={...i,state:e.state},y||=e.changed}continue}if(v.add(n.requestId),n.optionId===`cancel`){let r=e===void 0?buildCallbackContext().session.auth.current:e;if(r===null){_.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let a=settleDirectApprovalResponse({actor:r,outcome:`cancelled`,requestId:n.requestId,settledAt:t,state:i.state});i={...i,state:a.state},y||=a.changed;continue}if(n.optionId!==`approve`)continue;let a=e===void 0?buildCallbackContext().session.auth.current:e;if(a===null){_.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let o=createApprovalCandidate({candidateIdPrefix:approvalCandidateIdPrefix(r.requestId,a),createdAt:t,expiresAt:t+6e5,requestId:r.requestId,responder:a,state:i.state});i={...i,state:o.state},y||=o.changed}let S=removeConsumedResponses(f,v);if(v.size>0)return deliveryResult(i,S,y?`continue-coordination`:`continue`,[],_);if(y)return deliveryResult(i,S,`continue`,[],_);let C=new Set(getPendingAuthorization(i.state)?.challenges.map(e=>e.name)??[]);for(let n of b){if(n.status===`authorization-required`){let e=n.authorizationChallenges??[];if(!e.some(e=>getAuthorizationResult(e.name)!==void 0)){g.push(...e.filter(e=>!C.has(e.name)));continue}}let r=h.get(n.requestId);if(r===void 0||getActiveApprovalCandidate(i.state,n.candidateId)===void 0)continue;let a=await authorizeCandidate({candidateId:n.candidateId,now:t,request:r,responder:n.responder,session:i,tools:e.tools});i=a.session,y||=a.didCommit,g.push(...a.challenges);let o=getApprovalAuditState(i.state).settlements.find(e=>e.requestId===n.requestId);o!==void 0&&c.push(o)}let w=appendSettledResponses(S,c);return c.length>0?deliveryResult(i,w,`continue`):y?deliveryResult(i,w,`continue-coordination`):deliveryResult(i,w,g.length>0?`authorization-required`:`continue`,g)}async function authorizeCandidate(e){let t={...e.session,state:expireApprovalCandidates({now:e.now,state:e.session.state})};if(getActiveApprovalCandidate(t.state,e.candidateId)===void 0)return{challenges:[],didCommit:!1,session:t};let n=e.tools.get(e.request.action.toolName)?.approval,r=n!==void 0&&typeof n!=`function`?n.response:void 0;if(r===void 0)return failCandidate({...e,reason:`Approval authorization is temporarily unavailable. Please try again.`,session:t});try{let n=buildCallbackContext(),i=await withAuthorizerTimeout(r({auth:buildApprovalResponseAuth({responder:e.responder,scope:e.candidateId}),request:{callId:e.request.action.callId,requestId:e.request.requestId,toolInput:e.request.action.input,toolName:e.request.action.toolName},response:{decision:`approve`},responder:e.responder,session:{id:n.session.id,initiator:n.session.auth.initiator,parent:n.session.parent,turn:n.session.turn}}));if(i.status===`rejected`)return t={...t,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:i.reason,state:t.state,status:`rejected`})},{challenges:[],didCommit:!0,session:t};if(i.status!==`allowed`)return failCandidate({...e,session:t});let a=settleAllowedCandidate({candidateId:e.candidateId,settledAt:e.now,state:t.state});return{challenges:[],didCommit:a.changed,session:{...t,state:a.state}}}catch(n){let r=await handleApprovalResponsePolicyError(n).catch(()=>void 0);if(isAuthorizationSignal(r)){let n=r.challenges.map(e=>Date.parse(e.challenge.expiresAt??``)).filter(Number.isFinite).sort((e,t)=>e-t)[0];return t={...t,state:markApprovalCandidateAuthorizationRequired({authorizationChallenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),candidateId:e.candidateId,expiresAt:n,state:t.state})},{challenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),didCommit:!0,session:t}}return failCandidate({...e,session:t})}}function failCandidate(e){let t=e.reason??`We couldn’t verify your approval. Please try again.`;return{challenges:[],didCommit:!0,session:{...e.session,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:t,state:e.session.state,status:`failed`})}}}function hasResponseForRequest(e,t){return e?.attributedInputResponses?.some(({response:e})=>t.has(e.requestId))===!0||e?.inputResponses?.some(e=>t.has(e.requestId))===!0}function hasMeaningfulInput(e){return e?.message!==void 0||(e?.attributedInputResponses?.length??0)>0||(e?.inputResponses?.length??0)>0||(e?.runtimeActionResults?.length??0)>0}function appendSettledResponses(e,t){return t.length===0?e:{...e,inputResponses:[...e?.inputResponses??[],...t.map(e=>({optionId:e.outcome===`allowed`?`approve`:`cancel`,requestId:e.requestId}))]}}function removeConsumedResponses(e,t){if(e===void 0)return;let n=(e.attributedInputResponses??[]).filter(({response:e})=>!t.has(e.requestId)),r=[...(e.inputResponses??[]).filter(e=>!t.has(e.requestId)),...n.map(({response:e})=>e)];return{...e,attributedInputResponses:void 0,inputResponses:r}}function deliveryResult(e,t,n=`continue`,r=[],i=[]){return{challenges:r,feedback:i,kind:n,session:e,stepInput:t}}function approvalCandidateIdPrefix(e,t){let n=[t.authenticator,t.issuer??``,t.principalType,t.principalId].join(`:`);return`${encodeCandidateIdPart(e)}.${encodeCandidateIdPart(n)}`}function encodeCandidateIdPart(e){return Array.from(e,e=>e.codePointAt(0).toString(36)).join(`-`)}async function withAuthorizerTimeout(e){let t;try{return await Promise.race([Promise.resolve(e),new Promise((e,n)=>{t=setTimeout(()=>n(Error(`Approval response authorizer timed out.`)),1e4)})])}finally{t!==void 0&&clearTimeout(t)}}export{coordinateApprovalDelivery,shouldPrepareApprovalPolicyTools,shouldPrepareApprovalReplayTools};
|
|
@@ -112,11 +112,12 @@ export declare function consumeAuthorizationResult(name: string, instanceId?: st
|
|
|
112
112
|
* Builds a callback URL for external systems. `name` and `attemptId` identify
|
|
113
113
|
* the exact challenge in the URL path.
|
|
114
114
|
*
|
|
115
|
-
*
|
|
115
|
+
* By default the URL embeds the session's authorization hook token (`${sessionId}:auth`).
|
|
116
|
+
* A runtime with its own continuation supplies that hook through AuthorizationHookKey.
|
|
116
117
|
* It is independent of the continuation token, so channel re-keying mid-turn
|
|
117
118
|
* does not invalidate the callback URL.
|
|
118
119
|
*
|
|
119
|
-
* Returns `undefined` if
|
|
120
|
+
* Returns `undefined` if no callback address is available.
|
|
120
121
|
*/
|
|
121
122
|
export declare function getHookUrl(name: string, attemptId: string): string | undefined;
|
|
122
123
|
/** Mints the identity and callback URL for one interactive authorization attempt. */
|
|
@@ -158,7 +159,10 @@ export declare const PendingAuthorizationResultKey: ContextKey<readonly NamedAut
|
|
|
158
159
|
* metadata.
|
|
159
160
|
*/
|
|
160
161
|
export declare const CallbackBaseUrlKey: ContextKey<string>;
|
|
162
|
+
/** Hook token of a runtime that owns its callback instead of using the session hook. */
|
|
163
|
+
export declare const AuthorizationHookKey: ContextKey<string>;
|
|
161
164
|
export interface PendingAuthorizationState {
|
|
165
|
+
readonly activityRootTurnIds?: Readonly<Record<string, string>>;
|
|
162
166
|
readonly challenges: readonly AuthorizationChallenge[];
|
|
163
167
|
}
|
|
164
168
|
export declare function setPendingAuthorization(sessionState: Record<string, unknown> | undefined, value: PendingAuthorizationState): Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{loadContext}from"#context/container.js";import{SessionIdKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(t&&t.length!==0)return e===void 0?t[0]:t.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,t){let n=loadContext(),r=n.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(n=>n.name===e&&n.instanceId===t);if(i===-1&&t!==void 0&&r.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return n.delete(PendingAuthorizationResultKey),o.length>0&&n.set(PendingAuthorizationResultKey,o),a}function getHookUrl(e,t){let n=loadContext(),r=n.get(SessionIdKey),i=n.get(CallbackBaseUrlKey)
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{contextStorage,loadContext}from"#context/container.js";import{ActivityRootTurnIdKey,SessionIdKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(t&&t.length!==0)return e===void 0?t[0]:t.find(t=>t.name===e)}function getAuthorizationResults(){return loadContext().get(PendingAuthorizationResultKey)??[]}function consumeAuthorizationResult(e,t){let n=loadContext(),r=n.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(n=>n.name===e&&n.instanceId===t);if(i===-1&&t!==void 0&&r.some(t=>t.name===e&&t.instanceId!==void 0))throw Error(`Authorization for "${e}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return n.delete(PendingAuthorizationResultKey),o.length>0&&n.set(PendingAuthorizationResultKey,o),a}function getHookUrl(e,t){let n=loadContext(),r=n.get(SessionIdKey),i=n.get(CallbackBaseUrlKey),a=n.get(AuthorizationHookKey)??(r?authHookToken(r):void 0);if(a&&i)return createWorkflowCallbackUrl(i,createEveConnectionCallbackRoutePath(e,t,a))}function createAuthorizationAttempt(e){let t=createUlid(),n=getHookUrl(e,t);return n===void 0?void 0:{attemptId:t,hookUrl:n}}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),AuthorizationHookKey=new ContextKey(`eve.authorizationHook`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){let n=resolveActiveAuthorizationChallenges(t.challenges),r=getPendingAuthorization(e),i=r?.challenges??[],a=getSupersededAuthorizationChallenges(e,n),o=contextStorage.getStore()?.get(ActivityRootTurnIdKey),s={...r?.activityRootTurnIds};for(let e of a)delete s[authorizationAttemptKey(e)];if(o!==void 0)for(let e of n)s[authorizationAttemptKey(e)]=o;return{...e,[PENDING_AUTHORIZATION_KEY]:{...Object.keys(s).length===0?{}:{activityRootTurnIds:s},challenges:[...i.filter(e=>!a.includes(e)),...n]}}}function resolveActiveAuthorizationChallenges(e){return e.filter((t,n)=>!e.slice(n+1).some(e=>t.name===e.name&&samePrincipal(t.principal,e.principal)))}function getSupersededAuthorizationChallenges(e,t){return(getPendingAuthorization(e)?.challenges??[]).filter(e=>t.some(t=>e.name===t.name&&samePrincipal(e.principal,t.principal)))}function samePrincipal(e,t){return e===void 0||t===void 0?e===t:e.type===`app`||t.type===`app`?e.type===t.type:e.id===t.id&&e.issuer===t.issuer}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(authorizationAttemptKey(e)));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:pendingAuthorizationValue(n,i)}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function pendingAuthorizationValue(e,t){let n=Object.fromEntries(t.flatMap(t=>{let n=authorizationAttemptKey(t),r=e.activityRootTurnIds?.[n];return r===void 0?[]:[[n,r]]}));return{...Object.keys(n).length===0?{}:{activityRootTurnIds:n},challenges:t}}function authorizationAttemptKey(e){return e.attemptId??e.candidateId??e.name}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(typeof t==`object`&&t)return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getAuthorizationResults,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,resolveActiveAuthorizationChallenges,setPendingAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{generateText}from"ai";import{COMPACTION_CHECKPOINT_MARKER,COMPACTION_PROMPT_ENVELOPE,COMPACTION_RESUMPTION_MESSAGE,TODO_COMPACTION_PRESERVATION_LABEL,TRANSCRIPT_PAYLOAD_LIMIT,createCompactionPrompt,sliceUtf16Safe,stubContentOutputFileParts}from"#harness/compaction-prompt.js";import{estimateTokens}from"#harness/token-estimate.js";const COMPACTION_PROMPT_OVERHEAD_TOKENS=estimateTokens([{content:COMPACTION_PROMPT_ENVELOPE.system,role:`system`},{content:COMPACTION_PROMPT_ENVELOPE.prompt,role:`user`}]);function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return e.length>0&&getInputTokenCount(e,t)+COMPACTION_PROMPT_OVERHEAD_TOKENS>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}const COMPACTION_HEURISTICS=[toolResultCapHeuristic];function toolResultCapHeuristic(e){let t=withResumptionGuard([...e.previousCheckpoint===void 0?[]:[{content:COMPACTION_CHECKPOINT_MARKER,role:`user`},{content:e.previousCheckpoint,role:`assistant`}],...capToolResults(e.older),...e.recent],e.conversation);return evaluateThreshold(t,e.config,`should-compact`,e.tokenEstimateAdjustment).type===`within-limit`?{messages:t,type:`within-limit`}:{type:`insufficient`}}function evaluateThreshold(e,t,n,r=0){let i=n===`should-compact`?COMPACTION_PROMPT_OVERHEAD_TOKENS:0,a=estimateTokens(e)+i+r;return{estimatedTokens:a,type:a<=t.threshold?`within-limit`:`over-limit`}}async function compactMessages(e,t,n,r,i,a,o,s=!1){let{conversation:c,previousCheckpoint:l}=extractPreviousCheckpoint(e),u=selectRecentWindowSize(c,s?{...n,recentWindowSize:1}:n);if(!s){let{older:t,recent:r}=splitMessagesForCompaction(c,u);if(t.length===0&&l===void 0)return keepNonToolResultMessages(r);let i=Math.max(0,getInputTokenCount(e,n)-estimateTokens(e));for(let e of COMPACTION_HEURISTICS){let a=e({config:n,conversation:c,older:t,previousCheckpoint:l,recent:r,tokenEstimateAdjustment:i});if(a.type===`within-limit`)return a.messages}}for(;;){let{older:e,recent:s}=splitMessagesForCompaction(c,u),d=createCompactionPrompt({messages:e,previousCheckpoint:l,transcriptBudgetTokens:n.threshold}),f=await generateText({abortSignal:o,headers:a,model:t,prompt:d.prompt,providerOptions:r,system:d.system,telemetry:i?{...i,functionId:`eve.compaction`}:void 0,temperature:0});if(f.text.trim().length===0)throw Error(`The compaction model returned an empty summary. Finish reason: ${f.finishReason}.`);let p=[{content:COMPACTION_CHECKPOINT_MARKER,role:`user`},{content:f.text,role:`assistant`}],m=withResumptionGuard([...p,...s],c);if(evaluateThreshold(m,n,`estimate`).type===`within-limit`)return m;let h=withResumptionGuard([...p,...keepNonToolResultMessages(s)],c);if(evaluateThreshold(h,n,`estimate`).type===`within-limit`||u===0)return h;--u}}function capToolResults(e){return e.map(e=>{if(e.role!==`tool`||typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-result`)return e;let n=stubContentOutputFileParts(e.output),r=JSON.stringify(n)??``;return r.length<=TRANSCRIPT_PAYLOAD_LIMIT?n===e.output?e:(t=!0,{...e,output:n}):(t=!0,{...e,output:{type:`text`,value:`[Truncated by eve: tool result reduced during context compaction. Re-run the tool if you need the full output.]\n\n${sliceUtf16Safe(r,TRANSCRIPT_PAYLOAD_LIMIT)}`}})});return t?{...e,content:n}:e})}function withResumptionGuard(e,t){let
|
|
1
|
+
import{generateText}from"ai";import{COMPACTION_CHECKPOINT_MARKER,COMPACTION_PROMPT_ENVELOPE,COMPACTION_RESUMPTION_MESSAGE,TODO_COMPACTION_PRESERVATION_LABEL,TRANSCRIPT_PAYLOAD_LIMIT,createCompactionPrompt,sliceUtf16Safe,stubContentOutputFileParts}from"#harness/compaction-prompt.js";import{estimateTokens}from"#harness/token-estimate.js";const COMPACTION_PROMPT_OVERHEAD_TOKENS=estimateTokens([{content:COMPACTION_PROMPT_ENVELOPE.system,role:`system`},{content:COMPACTION_PROMPT_ENVELOPE.prompt,role:`user`}]);function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return e.length>0&&getInputTokenCount(e,t)+COMPACTION_PROMPT_OVERHEAD_TOKENS>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}const COMPACTION_HEURISTICS=[toolResultCapHeuristic];function toolResultCapHeuristic(e){let t=withResumptionGuard([...e.previousCheckpoint===void 0?[]:[{content:COMPACTION_CHECKPOINT_MARKER,role:`user`},{content:e.previousCheckpoint,role:`assistant`}],...capToolResults(e.older),...e.recent],e.conversation,e.config.threshold);return evaluateThreshold(t,e.config,`should-compact`,e.tokenEstimateAdjustment).type===`within-limit`?{messages:t,type:`within-limit`}:{type:`insufficient`}}function evaluateThreshold(e,t,n,r=0){let i=n===`should-compact`?COMPACTION_PROMPT_OVERHEAD_TOKENS:0,a=estimateTokens(e)+i+r;return{estimatedTokens:a,type:a<=t.threshold?`within-limit`:`over-limit`}}async function compactMessages(e,t,n,r,i,a,o,s=!1){let{conversation:c,previousCheckpoint:l}=extractPreviousCheckpoint(e),u=selectRecentWindowSize(c,s?{...n,recentWindowSize:1}:n);if(!s){let{older:t,recent:r}=splitMessagesForCompaction(c,u);if(t.length===0&&l===void 0)return keepNonToolResultMessages(r);let i=Math.max(0,getInputTokenCount(e,n)-estimateTokens(e));for(let e of COMPACTION_HEURISTICS){let a=e({config:n,conversation:c,older:t,previousCheckpoint:l,recent:r,tokenEstimateAdjustment:i});if(a.type===`within-limit`)return a.messages}}for(;;){let{older:e,recent:s}=splitMessagesForCompaction(c,u),d=createCompactionPrompt({messages:e,previousCheckpoint:l,transcriptBudgetTokens:n.threshold}),f=await generateText({abortSignal:o,headers:a,model:t,prompt:d.prompt,providerOptions:r,system:d.system,telemetry:i?{...i,functionId:`eve.compaction`}:void 0,temperature:0});if(f.text.trim().length===0)throw Error(`The compaction model returned an empty summary. Finish reason: ${f.finishReason}.`);let p=[{content:COMPACTION_CHECKPOINT_MARKER,role:`user`},{content:f.text,role:`assistant`}],m=withResumptionGuard([...p,...s],c,n.threshold);if(evaluateThreshold(m,n,`estimate`).type===`within-limit`)return m;let h=withResumptionGuard([...p,...keepNonToolResultMessages(s)],c,n.threshold);if(evaluateThreshold(h,n,`estimate`).type===`within-limit`||u===0)return h;--u}}function capToolResults(e){return e.map(e=>{if(e.role!==`tool`||typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-result`)return e;let n=stubContentOutputFileParts(e.output),r=JSON.stringify(n)??``;return r.length<=TRANSCRIPT_PAYLOAD_LIMIT?n===e.output?e:(t=!0,{...e,output:n}):(t=!0,{...e,output:{type:`text`,value:`[Truncated by eve: tool result reduced during context compaction. Re-run the tool if you need the full output.]\n\n${sliceUtf16Safe(r,TRANSCRIPT_PAYLOAD_LIMIT)}`}})});return t?{...e,content:n}:e})}function withResumptionGuard(e,t,n){let r=e.at(-1)?.role,i=findLastRealUserMessage(t),a=i!==void 0&&e.some(e=>e.role===`user`&&e.content===i.content);return r!==void 0&&r!==`assistant`?r===`tool`&&i!==void 0&&!a&&estimateTokens([i])<=n?[...e,i]:e:[...e,i!==void 0&&!a?i:{content:COMPACTION_RESUMPTION_MESSAGE,role:`user`}]}function findLastRealUserMessage(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`&&typeof n.content==`string`&&!(n.content===COMPACTION_RESUMPTION_MESSAGE||n.content===COMPACTION_CHECKPOINT_MARKER||n.content.startsWith(TODO_COMPACTION_PRESERVATION_LABEL)))return n}}function extractPreviousCheckpoint(e){let t=e[0],n=e[1];return t?.role!==`user`||t.content!==COMPACTION_CHECKPOINT_MARKER||n?.role!==`assistant`?{conversation:[...e],previousCheckpoint:void 0}:{conversation:e.slice(2),previousCheckpoint:assistantMessageText(n)}}function keepNonToolResultMessages(e){let t=[];for(let n of e)if(n.role!==`tool`){if(n.role===`assistant`){let e=assistantMessageText(n);e.length>0&&t.push({content:e,role:`assistant`});continue}t.push(n)}return t}function assistantMessageText(e){return typeof e.content==`string`?e.content.trim():e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim()}function selectRecentWindowSize(e,t){let n=Math.min(t.recentWindowSize,Math.max(e.length-1,0)),r=resolveCompactionSummaryReserve(t),i=0,a=0;for(let o=e.length-1;o>=0&&i<n;--o){let n=e[o];if(n===void 0)continue;let s=estimateTokens([n]);if(a+s+r>t.threshold)break;a+=s,i+=1}return i}function resolveCompactionSummaryReserve(e){return Math.min(2048,Math.max(64,Math.floor(e.threshold/4)))}function splitMessagesForCompaction(e,t){if(t<=0)return{older:[...e],recent:[]};let n=e.length-t;for(;n<e.length&&e[n]?.role===`tool`;)n+=1;return{older:e.slice(0,n),recent:e.slice(n)}}export{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact};
|
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import type { ModelMessage, SystemModelMessage } from "ai";
|
|
2
|
+
import type { HistoryState } from "#context/keys.js";
|
|
2
3
|
interface AddCurrentMessageOptions {
|
|
3
4
|
readonly cacheFriendly?: boolean;
|
|
4
5
|
}
|
|
5
6
|
interface CurrentMessagesOptions {
|
|
7
|
+
readonly historyState?: HistoryState;
|
|
6
8
|
readonly currentTurnMessages?: readonly ModelMessage[];
|
|
9
|
+
readonly projectedMessages?: readonly ModelMessage[];
|
|
7
10
|
}
|
|
8
|
-
/**
|
|
11
|
+
/** Builds the model view and durable history for one step. */
|
|
9
12
|
export declare function createCurrentMessages(history: readonly ModelMessage[], options?: CurrentMessagesOptions): {
|
|
13
|
+
readonly history: readonly ModelMessage[];
|
|
14
|
+
readonly historyState: HistoryState;
|
|
10
15
|
readonly nonSystemMessages: readonly ModelMessage[];
|
|
11
16
|
readonly systemMessages: readonly SystemModelMessage[];
|
|
12
|
-
add(
|
|
17
|
+
add(message: string, options?: AddCurrentMessageOptions): void;
|
|
18
|
+
addAnnouncements(announcements: HistoryState): void;
|
|
13
19
|
addSystem(messages: SystemModelMessage | readonly SystemModelMessage[]): void;
|
|
14
20
|
};
|
|
15
21
|
/** True when the history ends with a tool message carrying a tool-approval-response. */
|