eve 0.52.3 → 0.52.4

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.
Files changed (138) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/src/cli/commands/registry-add-command.d.ts +3 -0
  3. package/dist/src/cli/commands/registry-add-command.js +1 -0
  4. package/dist/src/cli/commands/registry-metadata.d.ts +4 -1
  5. package/dist/src/cli/commands/registry-metadata.js +1 -1
  6. package/dist/src/cli/commands/registry.d.ts +1 -2
  7. package/dist/src/cli/commands/registry.js +1 -1
  8. package/dist/src/compiled/.vendor-stamp.json +1 -1
  9. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  10. package/dist/src/compiler/extension-compatibility.js +1 -1
  11. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  12. package/dist/src/evals/reporters/index.d.ts +1 -0
  13. package/dist/src/evals/reporters/index.js +1 -1
  14. package/dist/src/evals/runner/reporters/datadog.d.ts +137 -0
  15. package/dist/src/evals/runner/reporters/datadog.js +3 -0
  16. package/dist/src/execution/parked-delivery-wait.js +1 -1
  17. package/dist/src/execution/sandbox/bindings/vercel-options.d.ts +10 -0
  18. package/dist/src/execution/sandbox/bindings/vercel-options.js +1 -0
  19. package/dist/src/execution/sandbox/bindings/vercel.js +2 -1
  20. package/dist/src/execution/sandbox/shell-quote.d.ts +1 -12
  21. package/dist/src/execution/sandbox/shell-quote.js +1 -1
  22. package/dist/src/execution/session-command-inbox.js +1 -1
  23. package/dist/src/execution/tasks/child/workflow.js +1 -1
  24. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  25. package/dist/src/execution/tool-auth.d.ts +4 -32
  26. package/dist/src/execution/tool-auth.js +1 -1
  27. package/dist/src/execution/tools/connection-search.js +2 -2
  28. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  29. package/dist/src/execution/tools/subagent/accept-event-step.d.ts +1 -1
  30. package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
  31. package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
  32. package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
  33. package/dist/src/execution/tools/workflow/ask.d.ts +3 -2
  34. package/dist/src/execution/tools/workflow/ask.js +1 -1
  35. package/dist/src/execution/tools/workflow/authorization-completion.d.ts +3 -0
  36. package/dist/src/execution/tools/workflow/authorization-completion.js +1 -0
  37. package/dist/src/execution/tools/workflow/body.d.ts +2 -0
  38. package/dist/src/execution/tools/workflow/body.js +1 -1
  39. package/dist/src/execution/tools/workflow/step-context.d.ts +31 -0
  40. package/dist/src/execution/tools/workflow/step-context.js +1 -0
  41. package/dist/src/execution/tools/workflow/step-execution.d.ts +3 -0
  42. package/dist/src/execution/tools/workflow/step-execution.js +1 -0
  43. package/dist/src/execution/tools/workflow/step.d.ts +3 -0
  44. package/dist/src/execution/tools/workflow/step.js +1 -0
  45. package/dist/src/execution/turn-workflow-tool-run.js +1 -1
  46. package/dist/src/execution/wire/session-inbox-contract.d.ts +7 -0
  47. package/dist/src/execution/wire/session-inbox-contract.js +1 -1
  48. package/dist/src/execution/wire/session-inbox-resume.d.ts +2 -0
  49. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  50. package/dist/src/harness/authorization.d.ts +5 -2
  51. package/dist/src/harness/authorization.js +1 -1
  52. package/dist/src/internal/application/package.js +1 -1
  53. package/dist/src/internal/authored-definition/connection.js +1 -1
  54. package/dist/src/internal/authored-package-boundary.js +1 -1
  55. package/dist/src/internal/vercel/build-command.d.ts +2 -1
  56. package/dist/src/internal/vercel/build-command.js +1 -1
  57. package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
  58. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  59. package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +3 -5
  60. package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -3
  61. package/dist/src/public/channels/github/checkout.js +1 -1
  62. package/dist/src/public/channels/slack/activity.js +1 -1
  63. package/dist/src/runtime/authorization-context.d.ts +14 -0
  64. package/dist/src/runtime/authorization-context.js +1 -0
  65. package/dist/src/runtime/connections/mcp-client.js +1 -1
  66. package/dist/src/runtime/connections/scoped-authorization.d.ts +18 -2
  67. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  68. package/dist/src/runtime/resolve-connection.js +1 -1
  69. package/dist/src/runtime/sandbox/keys.js +1 -1
  70. package/dist/src/sandbox/backends/default.d.ts +2 -0
  71. package/dist/src/sandbox/backends/default.js +1 -1
  72. package/dist/src/self-modification/agent.d.ts +5 -2
  73. package/dist/src/self-modification/agent.js +1 -1
  74. package/dist/src/self-modification/config.d.ts +52 -0
  75. package/dist/src/self-modification/config.js +1 -0
  76. package/dist/src/self-modification/credentials.d.ts +18 -0
  77. package/dist/src/self-modification/credentials.js +1 -0
  78. package/dist/src/self-modification/extension/eve-add.d.ts +7 -2
  79. package/dist/src/self-modification/extension/eve-add.js +1 -1
  80. package/dist/src/self-modification/extension/extension.d.ts +46 -1
  81. package/dist/src/self-modification/extension/extension.js +1 -1
  82. package/dist/src/self-modification/extension/instructions.js +23 -9
  83. package/dist/src/self-modification/extension/production-registry-add.d.ts +42 -0
  84. package/dist/src/self-modification/extension/production-registry-add.js +1 -0
  85. package/dist/src/self-modification/extension/tools/edit_file.js +1 -1
  86. package/dist/src/self-modification/extension/tools/publish.d.ts +7 -0
  87. package/dist/src/self-modification/extension/tools/publish.js +1 -0
  88. package/dist/src/self-modification/extension/tools/registry_add.d.ts +39 -7
  89. package/dist/src/self-modification/extension/tools/registry_add.js +1 -1
  90. package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -0
  91. package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
  92. package/dist/src/self-modification/filesystem.js +1 -1
  93. package/dist/src/self-modification/git-workspace.d.ts +31 -0
  94. package/dist/src/self-modification/git-workspace.js +1 -0
  95. package/dist/src/self-modification/git.d.ts +6 -0
  96. package/dist/src/self-modification/git.js +1 -0
  97. package/dist/src/self-modification/github-publisher.d.ts +27 -0
  98. package/dist/src/self-modification/github-publisher.js +2 -0
  99. package/dist/src/self-modification/identifiers.d.ts +4 -0
  100. package/dist/src/self-modification/identifiers.js +1 -0
  101. package/dist/src/self-modification/mode.d.ts +4 -0
  102. package/dist/src/self-modification/mode.js +1 -0
  103. package/dist/src/self-modification/network-policy.d.ts +1 -0
  104. package/dist/src/self-modification/network-policy.js +1 -0
  105. package/dist/src/self-modification/proposal.d.ts +39 -0
  106. package/dist/src/self-modification/proposal.js +2 -0
  107. package/dist/src/self-modification/sandbox.d.ts +25 -1
  108. package/dist/src/self-modification/sandbox.js +1 -1
  109. package/dist/src/self-modification/setup.d.ts +34 -0
  110. package/dist/src/self-modification/setup.js +22 -0
  111. package/dist/src/self-modification/workspace-lock.d.ts +2 -0
  112. package/dist/src/self-modification/workspace-lock.js +1 -0
  113. package/dist/src/setup/integrations/registry.js +1 -1
  114. package/dist/src/setup/integrations/runner.js +1 -1
  115. package/dist/src/setup/integrations/self-modification/setup.d.ts +29 -0
  116. package/dist/src/setup/integrations/self-modification/setup.js +1 -0
  117. package/dist/src/setup/integrations/types.d.ts +2 -0
  118. package/dist/src/setup/integrations/types.js +1 -1
  119. package/dist/src/setup/scaffold/create/project.js +1 -1
  120. package/dist/src/shared/empty-delivery.js +1 -1
  121. package/dist/src/shared/git.d.ts +16 -0
  122. package/dist/src/shared/git.js +1 -0
  123. package/dist/src/shared/shell-quote.d.ts +2 -0
  124. package/dist/src/shared/shell-quote.js +1 -0
  125. package/dist/src/shared/vercel-services.js +1 -1
  126. package/dist/src/tasks/session-index.d.ts +1 -1
  127. package/dist/src/tasks/session-index.js +1 -1
  128. package/dist/src/tasks/session-task-cohorts.d.ts +10 -0
  129. package/dist/src/tasks/session-task-cohorts.js +1 -0
  130. package/dist/src/tools/workflow-definition.d.ts +5 -2
  131. package/docs/concepts/sessions-runs-and-streaming.md +2 -0
  132. package/docs/evals/reporters.mdx +20 -1
  133. package/docs/sandbox.mdx +2 -0
  134. package/docs/subagents/index.mdx +10 -0
  135. package/docs/tools/workflows.mdx +61 -2
  136. package/package.json +17 -1
  137. package/dist/src/self-modification/extension/source-lock.d.ts +0 -2
  138. package/dist/src/self-modification/extension/source-lock.js +0 -1
@@ -1 +1 @@
1
- import{sessionCommandHookToken}from"#execution/session-command-token.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{serializeContext}from"#context/serialize.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{cancelOwnedTask}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{findSessionTaskEntry,recordSessionTask}from"#tasks/session-index.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{sendTaskCommand,sendTaskInboundPayload,startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskMessage,isTaskMessage}from"#tools/task.js";import{beginBackgroundTask,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";const IN_PROCESS_WORKFLOW_EXECUTOR={data:{},kind:`workflow-task`};function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];steeringAgents=new Set;agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=recordSessionTask(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(e){let t={settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t}),a=i.task;t.task=a;let o={binding:{taskId:a.taskId,token:a.taskInboxToken},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:this.initialSession,task:a,taskId:a.taskId};if(e.definition.workflowId!==void 0)return t.settled=!0,{...i.receipt,status:`working`,taskId:a.taskId};let s=e.definition.execute(e.toolInput,e.options,o),c=isAsyncIterable(s)?await executeBackgroundIterable({callId:e.options.toolCallId,output:s,task:a}):await s;return isAuthorizationSignal(c)?c:(await deliverTaskCommand(a,{data:parseJsonValue(c),kind:`complete`}),t.settled=!0,{status:`working`,taskId:a.taskId})}async startTask(e){let t=e.input.definition.workflowId===void 0?void 0:{...e.input.definition,workflowId:e.input.definition.workflowId},n=t===void 0?void 0:parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t?.resultKind===`subagent`&&n!==void 0?projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}}):void 0;if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession};if(t===void 0)return{task:await beginBackgroundTask({activityObserver:o.activityObserver,callId:o.callId,metadata:o.metadata,parentSessionId:o.parentSessionId,parentStepIndex:o.parentStepIndex,parentTurnId:o.parentTurnId,session:o.session})};if(n===void 0)throw Error(`Background workflow tool "${e.input.definition.name}" has no input.`);let s=prepareBackgroundTask(o);if(t.resultKind===`subagent`&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:o.callId,kind:`reserve`,operationId:t.operation.id,ownerId:s.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.resultKind===`subagent`&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:o.callId,parentSessionId:o.parentSessionId,parentTurnId:r}),n=await this.claimAgentForSteering({agentId:i.metadata.agentId,callId:o.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:s.taskId},e.ctx);readClaimedHandle(n)?e.record.claim={operationId:t,taskId:s.taskId}:throwAgentClaimError(i.metadata.agentId,n)}await startTaskRun({activityObserver:o.activityObserver,initialView:{metadata:s.metadata,status:`working`,taskId:s.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:s.taskInboxToken,workflow:{callId:o.callId,executeInput:t.executeInput?.(n),input:n,resultKind:t.resultKind,session:buildCallbackContext().session,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,taskId:s.taskId,workflowId:t.workflowId}});let c=await waitForTaskCommandOwner({taskInboxToken:s.taskInboxToken}),l={...s,executor:IN_PROCESS_WORKFLOW_EXECUTOR,taskRunId:c.runId};return e.record.task=l,t.resultKind!==`subagent`||i===void 0?{task:l}:(i.identity,{receipt:i.receipt,task:l})}async claimAgentForSteering(e,t){let n=this.applyAgentHandleCommand(e);if(n.kind!==`busy`||n.handle.phase!==`claimed`)return n;let r=n.handle;if(this.steeringAgents.has(r.identity.id))return n;let i=findSessionTaskEntry(this.agentHandleSession.state,r.ownerId);if(i?.metadata.kind!==`subagent`||i.metadata.agentId!==r.identity.id||i.metadata.name!==r.identity.name)return n;this.steeringAgents.add(r.identity.id);try{return await cancelOwnedTask({cancelOwnedWork:cancelBackgroundAgentTask,entry:i,serializedContext:serializeContext(t),session:this.agentHandleSession}),this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.ownerId}),this.applyAgentHandleCommand(e)}finally{this.steeringAgents.delete(r.identity.id)}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};async function executeBackgroundIterable(e){let t=e.output[Symbol.asyncIterator](),n=0,r=await t.next();for(;!r.done;){let i=isTaskMessage(r.value)?{callId:e.callId,kind:`task-message`,message:r.value.message,messageEpoch:e.task.taskId,messageIndex:n++}:{callId:e.callId,kind:`task-update`,message:typeof r.value==`string`?r.value:JSON.stringify(r.value),updateEpoch:e.task.taskId,updateIndex:n++};if(await sendTaskInboundPayload({payload:i,taskInboxToken:e.task.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.task.taskId}" did not accept "${i.kind}".`);r=await t.next()}return r.value??null}function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
1
+ import{sessionCommandHookToken}from"#execution/session-command-token.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{serializeContext}from"#context/serialize.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{cancelOwnedTask}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{findSessionTaskEntry,recordSessionTask}from"#tasks/session-index.js";import{sessionDriverSupportsWorkflowTaskAuthorization}from"#execution/wire/session-inbox-resume.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{sendTaskCommand,sendTaskInboundPayload,startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskMessage,isTaskMessage}from"#tools/task.js";import{beginBackgroundTask,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";const IN_PROCESS_WORKFLOW_EXECUTOR={data:{},kind:`workflow-task`};function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];steeringAgents=new Set;agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=recordSessionTask(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(e){let t={settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t}),a=i.task;t.task=a;let o={binding:{taskId:a.taskId,token:a.taskInboxToken},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:this.initialSession,task:a,taskId:a.taskId};if(e.definition.workflowId!==void 0)return t.settled=!0,{...i.receipt,status:`working`,taskId:a.taskId};let s=e.definition.execute(e.toolInput,e.options,o),c=isAsyncIterable(s)?await executeBackgroundIterable({callId:e.options.toolCallId,output:s,task:a}):await s;return isAuthorizationSignal(c)?c:(await deliverTaskCommand(a,{data:parseJsonValue(c),kind:`complete`}),t.settled=!0,{status:`working`,taskId:a.taskId})}async startTask(e){let t=e.input.definition.workflowId===void 0?void 0:{...e.input.definition,workflowId:e.input.definition.workflowId},n=t===void 0?void 0:parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t?.resultKind===`subagent`&&n!==void 0?projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}}):void 0;if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession};if(t===void 0)return{task:await beginBackgroundTask({activityObserver:o.activityObserver,callId:o.callId,metadata:o.metadata,parentSessionId:o.parentSessionId,parentStepIndex:o.parentStepIndex,parentTurnId:o.parentTurnId,session:o.session})};if(n===void 0)throw Error(`Background workflow tool "${e.input.definition.name}" has no input.`);let s=prepareBackgroundTask(o);if(t.resultKind===`subagent`&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:o.callId,kind:`reserve`,operationId:t.operation.id,ownerId:s.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.resultKind===`subagent`&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:o.callId,parentSessionId:o.parentSessionId,parentTurnId:r}),n=await this.claimAgentForSteering({agentId:i.metadata.agentId,callId:o.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:s.taskId},e.ctx);readClaimedHandle(n)?e.record.claim={operationId:t,taskId:s.taskId}:throwAgentClaimError(i.metadata.agentId,n)}await startTaskRun({activityObserver:o.activityObserver,initialView:{metadata:s.metadata,status:`working`,taskId:s.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:s.taskInboxToken,workflow:{authorizationSupported:await sessionDriverSupportsWorkflowTaskAuthorization(this.initialSession.sessionId),callId:o.callId,executeInput:t.executeInput?.(n),input:n,resultKind:t.resultKind,session:buildCallbackContext().session,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,taskId:s.taskId,workflowId:t.workflowId}});let c=await waitForTaskCommandOwner({taskInboxToken:s.taskInboxToken}),l={...s,executor:IN_PROCESS_WORKFLOW_EXECUTOR,taskRunId:c.runId};return e.record.task=l,t.resultKind!==`subagent`||i===void 0?{task:l}:(i.identity,{receipt:i.receipt,task:l})}async claimAgentForSteering(e,t){let n=this.applyAgentHandleCommand(e);if(n.kind!==`busy`||n.handle.phase!==`claimed`)return n;let r=n.handle;if(this.steeringAgents.has(r.identity.id))return n;let i=findSessionTaskEntry(this.agentHandleSession.state,r.ownerId);if(i?.metadata.kind!==`subagent`||i.metadata.agentId!==r.identity.id||i.metadata.name!==r.identity.name)return n;this.steeringAgents.add(r.identity.id);try{return await cancelOwnedTask({cancelOwnedWork:cancelBackgroundAgentTask,entry:i,serializedContext:serializeContext(t),session:this.agentHandleSession}),this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.ownerId}),this.applyAgentHandleCommand(e)}finally{this.steeringAgents.delete(r.identity.id)}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};async function executeBackgroundIterable(e){let t=e.output[Symbol.asyncIterator](),n=0,r=await t.next();for(;!r.done;){let i=isTaskMessage(r.value)?{callId:e.callId,kind:`task-message`,message:r.value.message,messageEpoch:e.task.taskId,messageIndex:n++}:{callId:e.callId,kind:`task-update`,message:typeof r.value==`string`?r.value:JSON.stringify(r.value),updateEpoch:e.task.taskId,updateIndex:n++};if(await sendTaskInboundPayload({payload:i,taskInboxToken:e.task.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.task.taskId}" did not accept "${i.kind}".`);r=await t.next()}return r.value??null}function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
@@ -1,36 +1,7 @@
1
- /**
2
- * Tool-hosted authorization wiring for authored tools that resolve auth
3
- * providers inline with {@link ToolContext.getToken} and
4
- * {@link ToolContext.requireAuth}.
5
- *
6
- * Mirrors the connection authorization flow used by connection search but scopes the
7
- * per-step token cache and framework-owned callback URL by the tool's
8
- * path-derived name and provider key instead of a connection name. All the shared
9
- * machinery — principal resolution, cache reads/writes, the park/resume
10
- * webhook dance, and the loop guard — lives in
11
- * `runtime/connections/scoped-authorization.ts`; this module is the thin
12
- * execution-layer adapter that wraps one tool's `execute`.
13
- */
14
1
  import type { SessionAuthContext } from "#channel/types.js";
15
2
  import type { ApprovalResponseAuth } from "#approval/definition.js";
16
- import type { ToolContext } from "#tools/definition.js";
17
- import type { ToolExecuteOptions } from "#tools/definition.js";
3
+ import type { ToolContext, ToolExecuteOptions } from "#tools/definition.js";
18
4
  import type { TaskExec } from "#tools/task.js";
19
- /**
20
- * Wraps one authored tool's `execute` with a context that supports inline
21
- * provider auth (`ctx.getToken(connect("..."))`).
22
- *
23
- * On a thrown provider-scoped authorization request — implicit from
24
- * `ctx.getToken(provider)` or explicit via `ctx.requireAuth(provider)` — the
25
- * wrapper either fails terminally (token rejected immediately after sign-in)
26
- * or evicts the rejected token from the per-step cache and starts the
27
- * interactive flow, returning an `AuthorizationSignal` to park the turn.
28
- * Interactive strategies never rethrow the raw `Required` into the model: if
29
- * no callback URL can be minted, they fail with a classified
30
- * {@link ConnectionAuthorizationFailedError} instead. Non-interactive
31
- * strategies rethrow the original error because they have no consent flow to
32
- * park on.
33
- */
34
5
  type ToolExecuteWithAuthInput<TInput> = {
35
6
  readonly scope: string;
36
7
  } & ({
@@ -40,8 +11,9 @@ type ToolExecuteWithAuthInput<TInput> = {
40
11
  readonly execution?: never;
41
12
  readonly execute: (toolInput: TInput, ctx: ToolContext, task?: TaskExec) => unknown;
42
13
  });
43
- export declare function createToolExecuteWithAuth<TInput>(input: ToolExecuteWithAuthInput<TInput>): (toolInput: TInput, options: ToolExecuteOptions, task?: TaskExec) => Promise<unknown> | AsyncIterable<unknown>;
44
- /** Builds the narrow token capability used by approval response authorizers. */
14
+ /** Supplies the shared auth capability to one authored tool execution. */
15
+ export declare function createToolExecuteWithAuth<TInput>(input: ToolExecuteWithAuthInput<TInput>): (toolInput: TInput, options: ToolExecuteOptions, task?: TaskExec) => AsyncIterable<unknown> | Promise<unknown>;
16
+ /** Binds the same capability to the person responding to an approval. */
45
17
  export declare function buildApprovalResponseAuth(input: {
46
18
  readonly responder: SessionAuthContext;
47
19
  readonly scope: string;
@@ -1 +1 @@
1
- import{requestAuthorization}from"#harness/authorization.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";function createToolExecuteWithAuth(e){let{scope:t}=e;return(n,r,i)=>{let a=buildToolContext({inlineAuthState:{},justAuthorizedScopes:new Set,options:r,scope:t});try{let t;if(e.execution===`background`){if(i===void 0)throw Error(`Background tool execution requires a task runtime.`);t=e.execute(n,a,i)}else t=e.execute(n,a,i);return isAsyncIterable(t)?handleToolIterableErrors(t):Promise.resolve(t).catch(handleToolError)}catch(e){return handleToolError(e)}async function handleToolError(e){if(isToolAuthorizationRequiredError(e))return await handleAuthorizationRequests(e.requests);throw e}async function*handleToolIterableErrors(e){try{for await(let t of e)yield t}catch(e){yield await handleToolError(e)}}}}function buildApprovalResponseAuth(e){let t={},n=new Set;return{async getToken(r,i){if(r===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({boundResponder:e.responder,inlineAuthState:t,justAuthorizedScopes:n,options:namespaceApprovalAuthOptions(e.scope,i),provider:r,toolScope:e.scope})},requireAuth(r,i){if(r===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({boundResponder:e.responder,inlineAuthState:t,options:namespaceApprovalAuthOptions(e.scope,i),provider:r,toolScope:e.scope});throw new ToolAuthorizationRequiredError([{justAuthorized:n.has(a.scope),scoped:a}])}}}function namespaceApprovalAuthOptions(e,t){return t?.authKey===void 0?t:{...t,authKey:`${e}:${t.authKey}`}}async function handleApprovalResponsePolicyError(e){if(!isToolAuthorizationRequiredError(e))throw e;return await handleAuthorizationRequests(e.requests)}function buildToolContext(e){let{scope:t,justAuthorizedScopes:n,inlineAuthState:r}=e;return{...buildBaseToolContext({options:e.options,toolName:t}),async getToken(e,i){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({inlineAuthState:r,justAuthorizedScopes:n,options:i,provider:e,toolScope:t})},requireAuth(e,i){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({inlineAuthState:r,options:i,provider:e,toolScope:t});throw new ToolAuthorizationRequiredError([{justAuthorized:n.has(a.scope),scoped:a}])}}}async function resolveInlineToken(e){let{justAuthorizedScopes:t}=e,n=buildInlineScopedAuthorization(e);!t.has(n.scope)&&await completeScopedAuthorization(n)&&t.add(n.scope);try{return await resolveScopedToken(n)}catch(e){throw isConnectionAuthorizationRequiredError(e)?new ToolAuthorizationRequiredError([{cause:e,justAuthorized:t.has(n.scope),scoped:n}]):e}}async function handleAuthorizationRequests(e){let t=[],n;for(let r of e){let{scoped:e}=r;if(r.justAuthorized)throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});await evictScopedToken(e);let i=await startScopedAuthorization(e);if(i!==void 0){t.push(...i.challenges);continue}if(supportsInteractiveAuthorization(e.authorization))throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1});n??=r.cause instanceof Error?r.cause:new ConnectionAuthorizationRequiredError(e.scope)}if(t.length>0)return requestAuthorization(t);throw n??Error(`Tool authorization is required.`)}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,boundResponder:e.boundResponder,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,toolScope:e.toolScope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.toolScope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.toolScope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}var ToolAuthorizationRequiredError=class extends Error{requests;constructor(e){super(`Tool authorization required.`),this.name=`ToolAuthorizationRequiredError`,this.requests=e}};function isToolAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ToolAuthorizationRequiredError`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{buildApprovalResponseAuth,createToolExecuteWithAuth,handleApprovalResponsePolicyError};
1
+ import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{handleAuthorizationError}from"#runtime/connections/scoped-authorization.js";function createToolExecuteWithAuth(e){return(t,n,r)=>{let i=createAuthorizationContext({scope:e.scope}),a={...buildBaseToolContext({options:n,toolName:e.scope}),getToken:i.getToken,requireAuth:i.requireAuth};return i.run(()=>{if(e.execution===`background`){if(r===void 0)throw Error(`Background tool execution requires a task runtime.`);return e.execute(t,a,r)}return e.execute(t,a,r)})}}function buildApprovalResponseAuth(e){let t=createAuthorizationContext({scope:e.scope,boundResponder:e.responder});return{getToken:(n,r)=>t.getToken(n,namespaceApprovalAuthOptions(e.scope,r)),requireAuth:(n,r)=>t.requireAuth(n,namespaceApprovalAuthOptions(e.scope,r))}}function namespaceApprovalAuthOptions(e,t){return t?.authKey===void 0?t:{...t,authKey:`${e}:${t.authKey}`}}async function handleApprovalResponsePolicyError(e){return await handleAuthorizationError(e)}export{buildApprovalResponseAuth,createToolExecuteWithAuth,handleApprovalResponsePolicyError};
@@ -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{consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResults,requestAuthorization}from"#harness/authorization.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{connectionAuthorizationScope}from"#runtime/connections/instance-identity.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.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(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){assertPendingConnectionAuthorizationInstances(e);let n=loadContext(),r=new Set;for(let i of t){let t=consumeAuthorizationResult(i.connectionName,i.instanceId);if(!t)continue;let a=await resolveInteractiveAuth(e,i.connectionName);if(!a)continue;let o=t.principal??resolveConnectionPrincipal(i.connectionName,a),s=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:i.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,connectionAuthorizationScope(i),principalKey(o),s),r.add(i.connectionName)}return r}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=await completePendingAuthorizations(n,s),l=[];for(let e of s){let t;try{t=await n.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(c.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),o.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(n,e.connectionName);if(t){let n=createAuthorizationAttempt(e.connectionName);if(n){let r=resolveConnectionPrincipal(e.connectionName,t),i=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:n.hookUrl});try{let{challenge:a,resume:o}=await t.startAuthorization({callbackUrl:i,connection:{url:e.url??``},principal:r});l.push({attemptId:n.attemptId,name:e.connectionName,challenge:stampChallengeDisplayName(a,t),hookUrl:i,instanceId:e.instanceId,principal:r,resume:o})}catch(t){let n=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:n}),o.push({connection:e.connectionName,description:e.description,error:`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.`);let o=a.getConnections().find(e=>e.connectionName===r);assertPendingConnectionAuthorizationInstances(a);let s=await resolveInteractiveAuth(a,r),c=!1;if(s){let e=consumeAuthorizationResult(r,o?.instanceId);if(e){c=!0;let t=loadContext(),n=e.principal??resolveConnectionPrincipal(r,s),i=await s.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:o?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,o===void 0?r:connectionAuthorizationScope(o),principalKey(n),i)}}try{return await a.getClient(r).executeTool(i,t,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!s)throw e;if(c)throw new ConnectionAuthorizationFailedError(r,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${r}" rejected the token immediately after authorization.`});let t=createAuthorizationAttempt(r);if(!t)throw e;let n=resolveConnectionPrincipal(r,s),i=resolveAuthorizationCallbackUrl({authorization:s,callbackUrl:t.hookUrl}),{challenge:a,resume:l}=await s.startAuthorization({callbackUrl:i,connection:{url:o?.url??``},principal:n});return requestAuthorization([{attemptId:t.attemptId,name:r,challenge:stampChallengeDisplayName(a,s),hookUrl:i,instanceId:o?.instanceId,principal:n,resume:l}])}}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
+ 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.3//executeSleepTool`;export{executeSleepTool};
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.4//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
- /** Validates that a task child's authorization event came from an agent the task owns. */
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{readWorkflowToolRunAdmission,readWorkflowToolRunOwner,readWorkflowToolRunRef}from"#execution/tools/workflow/ask.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.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
+ 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,3 @@
1
+ import { type ScopedAuthorization } from "#runtime/connections/scoped-authorization.js";
2
+ /** Record successful completion before returning to authored code. */
3
+ export declare function completeWorkflowStepAuthorization(scoped: ScopedAuthorization): Promise<boolean>;
@@ -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{createTaskMessage}from"#tools/task.js";import{ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.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});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()`,`read credentials from the environment inside a "use step" helper`),requireAuth:()=>unavailable(`requireAuth()`,`a workflow body cannot park on 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};
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{workflowToolRunOutcomeToSubagentResult,workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload}from"#execution/tools/workflow/owner-inbox.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.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}));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};
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};
@@ -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
- * The URL embeds the session's authorization hook token (`${sessionId}:auth`).
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 the session context isn't available.
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,6 +159,8 @@ 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 {
162
165
  readonly challenges: readonly AuthorizationChallenge[];
163
166
  }
@@ -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);if(!r||!i)return;let a=authHookToken(r);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`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){let n=resolveActiveAuthorizationChallenges(t.challenges),r=getPendingAuthorization(e)?.challenges??[],i=getSupersededAuthorizationChallenges(e,n);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...r.filter(e=>!i.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(e.attemptId??e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}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{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getAuthorizationResults,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,resolveActiveAuthorizationChallenges,setPendingAuthorization};
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),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)?.challenges??[],i=getSupersededAuthorizationChallenges(e,n);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...r.filter(e=>!i.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(e.attemptId??e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}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{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.52.3`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(e){return createRequire(e).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),r=tryResolveDirectBuildLocation(n);if(r!==void 0)return r;let i=findNearestVerifiedPackageRoot(dirname(n));if(i!==void 0&&isSourceCheckout(i))return{packageBuildRoot:null,packageRoot:i};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let a=i===void 0?void 0:tryCreatePackageLocation(i);if(a!==void 0)return a;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(typeof t.name==`string`&&typeof t.version==`string`)return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.52.4`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(e){return createRequire(e).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),r=tryResolveDirectBuildLocation(n);if(r!==void 0)return r;let i=findNearestVerifiedPackageRoot(dirname(n));if(i!==void 0&&isSourceCheckout(i))return{packageBuildRoot:null,packageRoot:i};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let a=i===void 0?void 0:tryCreatePackageLocation(i);if(a!==void 0)return a;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(typeof t.name==`string`&&typeof t.version==`string`)return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};