eve 0.12.3 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/cli/commands/deploy.js +1 -1
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/link.d.ts +2 -2
- package/dist/src/cli/commands/link.js +1 -1
- package/dist/src/cli/dev/tui/setup-flow.d.ts +5 -0
- package/dist/src/cli/dev/tui/setup-panel.d.ts +4 -1
- package/dist/src/cli/dev/tui/setup-panel.js +1 -1
- package/dist/src/cli/dev/tui/setup-selection-input.d.ts +2 -1
- package/dist/src/cli/dev/tui/setup-selection-input.js +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +2 -2
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +3 -2
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/session.d.ts +4 -10
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/tool-auth.d.ts +16 -39
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/public/channels/github/api.d.ts +5 -0
- package/dist/src/public/channels/github/api.js +1 -1
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/pr-context.d.ts +10 -0
- package/dist/src/public/channels/github/pr-context.js +2 -2
- package/dist/src/public/definitions/tool.d.ts +3 -48
- package/dist/src/public/definitions/tool.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/types.d.ts +0 -10
- package/dist/src/setup/boxes/link-project.d.ts +8 -14
- package/dist/src/setup/boxes/link-project.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.d.ts +2 -1
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/cli/select-component.d.ts +7 -1
- package/dist/src/setup/cli/select-component.js +1 -1
- package/dist/src/setup/cli/select-option-codec.d.ts +1 -0
- package/dist/src/setup/cli/select-option-codec.js +1 -1
- package/dist/src/setup/cli/select-state.d.ts +14 -1
- package/dist/src/setup/cli/select-state.js +1 -1
- package/dist/src/setup/flows/model.d.ts +2 -2
- package/dist/src/setup/index.d.ts +1 -1
- package/dist/src/setup/package-manager.d.ts +2 -1
- package/dist/src/setup/package-manager.js +1 -1
- package/dist/src/setup/primitives/pm/index.d.ts +1 -1
- package/dist/src/setup/primitives/pm/pnpm.d.ts +11 -1
- package/dist/src/setup/primitives/pm/pnpm.js +5 -2
- package/dist/src/setup/primitives/pm/types.d.ts +10 -1
- package/dist/src/setup/project-resolution.d.ts +9 -6
- package/dist/src/setup/project-resolution.js +1 -1
- package/dist/src/setup/prompter.d.ts +13 -0
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.d.ts +8 -0
- package/dist/src/setup/scaffold/create/project.js +8 -7
- package/dist/src/setup/scaffold/update/channels.d.ts +8 -0
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/package-json.d.ts +3 -0
- package/dist/src/setup/scaffold/update/package-json.js +1 -1
- package/dist/src/setup/scaffold/workspace-glob.d.ts +5 -0
- package/dist/src/setup/scaffold/workspace-glob.js +1 -0
- package/dist/src/setup/scaffold/workspace-root.d.ts +29 -0
- package/dist/src/setup/scaffold/workspace-root.js +1 -0
- package/dist/src/setup/state.d.ts +7 -2
- package/dist/src/setup/vercel-api-failure.d.ts +9 -0
- package/dist/src/setup/vercel-api-failure.js +1 -0
- package/dist/src/setup/vercel-deployment.js +1 -1
- package/dist/src/setup/vercel-project-api.d.ts +25 -0
- package/dist/src/setup/vercel-project-api.js +1 -0
- package/dist/src/setup/vercel-project.d.ts +9 -51
- package/dist/src/setup/vercel-project.js +1 -1
- package/docs/concepts/execution-model-and-durability.md +2 -0
- package/docs/guides/auth-and-route-protection.md +2 -4
- package/docs/guides/dev-tui.md +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/reference/typescript-api.md +0 -2
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e;await setEveAttributes(buildTurnAttributes({parentSessionId:t.sessionState.sessionId,rootSessionId:readRootSessionId(t.serializedContext)??t.sessionState.sessionId}));let o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let h=getPendingAuthorization(o.state),g;if(h&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=h.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),g=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let _=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,m),n=serializeContext(l),r=e===m?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(g){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of g)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},refreshSystemPrompt:shouldRefreshSystemPromptFromTurnAgent(p.compiledArtifactsSource),session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingCodeModeInterrupt(T.session.state);return e!==void 0&&isCodeModeRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-code-mode-runtime-actions`,pendingRuntimeActionKeys:[getRuntimeActionKeyFromInterrupt(e.interrupt)],serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function shouldRefreshSystemPromptFromTurnAgent(e){return e.kind===`disk`&&e.moduleMapLoaderPath!==void 0}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state}),{resumeHook:r}=await import(`#compiled/@workflow/core/runtime.js`);process.env.WORKFLOW_QUEUE_NAMESPACE=`eve`;for(let t of n.forChildren)await r(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e;await setEveAttributes(buildTurnAttributes({parentSessionId:t.sessionState.sessionId,rootSessionId:readRootSessionId(t.serializedContext)??t.sessionState.sessionId}));let o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let h=getPendingAuthorization(o.state),g;if(h&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=h.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),g=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let _=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,m),n=serializeContext(l),r=e===m?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(g){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of g)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingCodeModeInterrupt(T.session.state);return e!==void 0&&isCodeModeRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-code-mode-runtime-actions`,pendingRuntimeActionKeys:[getRuntimeActionKeyFromInterrupt(e.interrupt)],serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state}),{resumeHook:r}=await import(`#compiled/@workflow/core/runtime.js`);process.env.WORKFLOW_QUEUE_NAMESPACE=`eve`;for(let t of n.forChildren)await r(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.13.1`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.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 isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}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 r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}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 resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.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{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME}from"#shared/code-mode.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames,getFrameworkToolDefinitions}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";function buildAgentInfoResponse(e,t){let r=e.agent,i=buildToolInfo(r);return{agent:{agentRoot:r.metadata.agentRoot,appRoot:r.metadata.appRoot,configSource:r.config.source?toSource(r.config.source):void 0,description:r.config.description,model:{contextWindowTokens:r.config.model.contextWindowTokens,id:r.config.model.id,providerOptions:r.config.model.providerOptions,source:r.config.model.source?toSource(r.config.model.source):void 0},name:r.config.name,outputSchema:r.config.outputSchema},capabilities:{devRoutes:t.mode===`development`},channels:buildChannelInfo(r),connections:r.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:e.approval!==void 0,hasAuthorization:e.authorization!==void 0,hasHeaders:e.headers!==void 0,protocol:e.protocol,toolFilter:e.tools,url:e.url})),diagnostics:{discoveryErrors:r.metadata.diagnosticsSummary.errors,discoveryWarnings:r.metadata.diagnosticsSummary.warnings},hooks:r.hooks.map(e=>({...toSource(e),eventNames:Object.keys(e.events).sort(),slug:e.slug})),instructions:{dynamic:r.dynamicInstructionsResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:r.instructions?{...toSource(r.instructions),markdown:r.instructions.markdown,name:r.instructions.name}:null},kind:`eve-agent-info`,mode:t.mode,sandbox:renderSandbox(r.sandbox),schedules:e.schedules.map(renderSchedule),skills:{static:r.skills.map(renderSkill),dynamic:r.dynamicSkillResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:e.manifest.subagents.map(renderSubagent),total:e.manifest.subagents.length},tools:i,version:1,workflow:{enabled:r.workflowEnabled,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:r.workspaceResourceRoot,rootEntries:[...r.workspaceSpec.rootEntries]}}}function buildChannelInfo(e){let t=new Set(e.channels.map(e=>e.name)),n=new Set(e.disabledFrameworkChannels),a=getAllFrameworkChannelNames(),o=getFrameworkChannelDefinitions(),s=o.filter(e=>!t.has(e.name)&&!n.has(e.name)),c=e.channels.map(e=>renderChannel(e,{origin:`authored`})),l=o.map(e=>{let r=t.has(e.name),i=n.has(e.name),a=i?`disabled`:r?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:i,replacedByAuthoredChannel:r,status:a}});return{authored:c,available:[...s.map(e=>renderChannel(e,{origin:`framework`})),...c],disabledFramework:[...e.disabledFrameworkChannels],framework:l.filter(e=>a.has(e.name))}}function buildToolInfo(r){let i=new Set(r.tools.map(e=>e.name)),c=new Set(r.disabledFrameworkTools),l=getAllFrameworkToolNames(),u=getFrameworkToolDefinitions({hasConnections:r.connections.length>0}),d=r.connections.length>0?[createConnectionSearchResolver()]:[],f=u.filter(e=>!i.has(e.name)&&!c.has(e.name)),p=r.tools.map(e=>renderTool(e,{origin:`authored`,replacesFrameworkTool:l.has(e.name)})),m=u.map(e=>{let t=i.has(e.name),n=c.has(e.name),r=n?`disabled`:t?`replaced`:`active`;return{...renderTool(e,{origin:`framework`,replacesFrameworkTool:!1}),disabledByAuthor:n,replacedByAuthoredTool:t,status:r}});return{available:[...f.map(e=>renderTool(e,{origin:`framework`,replacesFrameworkTool:!1})),...p],authored:p,disabledFramework:[...r.disabledFrameworkTools],dynamic:[...d.map(e=>renderDynamicResolver(e,{origin:`framework`})),...r.dynamicToolResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:m,reserved:[CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]}}function renderChannel(e,t){return{...toSource(e),adapterKind:e.adapter?.kind,method:e.method,name:e.name,origin:t.origin,urlPath:e.urlPath}}function renderTool(e,t){return{...toSource(e),description:e.description,hasAuth
|
|
1
|
+
import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME}from"#shared/code-mode.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames,getFrameworkToolDefinitions}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";function buildAgentInfoResponse(e,t){let r=e.agent,i=buildToolInfo(r);return{agent:{agentRoot:r.metadata.agentRoot,appRoot:r.metadata.appRoot,configSource:r.config.source?toSource(r.config.source):void 0,description:r.config.description,model:{contextWindowTokens:r.config.model.contextWindowTokens,id:r.config.model.id,providerOptions:r.config.model.providerOptions,source:r.config.model.source?toSource(r.config.model.source):void 0},name:r.config.name,outputSchema:r.config.outputSchema},capabilities:{devRoutes:t.mode===`development`},channels:buildChannelInfo(r),connections:r.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:e.approval!==void 0,hasAuthorization:e.authorization!==void 0,hasHeaders:e.headers!==void 0,protocol:e.protocol,toolFilter:e.tools,url:e.url})),diagnostics:{discoveryErrors:r.metadata.diagnosticsSummary.errors,discoveryWarnings:r.metadata.diagnosticsSummary.warnings},hooks:r.hooks.map(e=>({...toSource(e),eventNames:Object.keys(e.events).sort(),slug:e.slug})),instructions:{dynamic:r.dynamicInstructionsResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:r.instructions?{...toSource(r.instructions),markdown:r.instructions.markdown,name:r.instructions.name}:null},kind:`eve-agent-info`,mode:t.mode,sandbox:renderSandbox(r.sandbox),schedules:e.schedules.map(renderSchedule),skills:{static:r.skills.map(renderSkill),dynamic:r.dynamicSkillResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:e.manifest.subagents.map(renderSubagent),total:e.manifest.subagents.length},tools:i,version:1,workflow:{enabled:r.workflowEnabled,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:r.workspaceResourceRoot,rootEntries:[...r.workspaceSpec.rootEntries]}}}function buildChannelInfo(e){let t=new Set(e.channels.map(e=>e.name)),n=new Set(e.disabledFrameworkChannels),a=getAllFrameworkChannelNames(),o=getFrameworkChannelDefinitions(),s=o.filter(e=>!t.has(e.name)&&!n.has(e.name)),c=e.channels.map(e=>renderChannel(e,{origin:`authored`})),l=o.map(e=>{let r=t.has(e.name),i=n.has(e.name),a=i?`disabled`:r?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:i,replacedByAuthoredChannel:r,status:a}});return{authored:c,available:[...s.map(e=>renderChannel(e,{origin:`framework`})),...c],disabledFramework:[...e.disabledFrameworkChannels],framework:l.filter(e=>a.has(e.name))}}function buildToolInfo(r){let i=new Set(r.tools.map(e=>e.name)),c=new Set(r.disabledFrameworkTools),l=getAllFrameworkToolNames(),u=getFrameworkToolDefinitions({hasConnections:r.connections.length>0}),d=r.connections.length>0?[createConnectionSearchResolver()]:[],f=u.filter(e=>!i.has(e.name)&&!c.has(e.name)),p=r.tools.map(e=>renderTool(e,{origin:`authored`,replacesFrameworkTool:l.has(e.name)})),m=u.map(e=>{let t=i.has(e.name),n=c.has(e.name),r=n?`disabled`:t?`replaced`:`active`;return{...renderTool(e,{origin:`framework`,replacesFrameworkTool:!1}),disabledByAuthor:n,replacedByAuthoredTool:t,status:r}});return{available:[...f.map(e=>renderTool(e,{origin:`framework`,replacesFrameworkTool:!1})),...p],authored:p,disabledFramework:[...r.disabledFrameworkTools],dynamic:[...d.map(e=>renderDynamicResolver(e,{origin:`framework`})),...r.dynamicToolResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:m,reserved:[CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]}}function renderChannel(e,t){return{...toSource(e),adapterKind:e.adapter?.kind,method:e.method,name:e.name,origin:t.origin,urlPath:e.urlPath}}function renderTool(e,t){return{...toSource(e),description:e.description,hasAuth:!1,hasExecute:e.execute!==void 0,hasModelOutputProjection:e.toModelOutput!==void 0,hasOutputSchema:e.outputSchema!==void 0&&e.outputSchema!==null,inputSchema:e.inputSchema,name:e.name,origin:t.origin,outputSchema:e.outputSchema,replacesFrameworkTool:t.replacesFrameworkTool,requiresApproval:e.needsApproval!==void 0}}function renderSkill(e){return{...toSource(e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}}function renderSchedule(e){return{...toSource(e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name}}function renderSandbox(e){return e===null?null:{...toSource(e),backendKind:resolveBackendKind(e.backend),description:e.description,hasBootstrap:e.bootstrap!==void 0,hasOnSession:e.onSession!==void 0,revalidationKey:e.revalidationKey,sourceHash:e.sourceHash}}function renderSubagent(e){return{...toSource(e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,rootPath:e.rootPath,summary:{channels:e.agent.channels.length,connections:e.agent.connections.length,hooks:e.agent.hooks.length,instructions:e.agent.instructions!==void 0,schedules:e.agent.schedules.length,skills:e.agent.skills.length,tools:e.agent.tools.length}}}function renderDynamicResolver(e,t){return{...toSource(e),eventNames:[...e.eventNames],origin:t.origin,slug:e.slug}}function toSource(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:e.sourceKind}}function resolveBackendKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`?t:void 0}export{buildAgentInfoResponse,renderChannel,renderDynamicResolver,renderSchedule,renderSubagent,renderTool,toSource};
|
|
@@ -161,6 +161,11 @@ export declare function listGitHubPullRequestFiles(input: GitHubResourceInput &
|
|
|
161
161
|
readonly perPage?: number;
|
|
162
162
|
readonly pullRequestNumber: number;
|
|
163
163
|
}): Promise<readonly GitHubPullRequestFile[]>;
|
|
164
|
+
/** Lists files changed between two commits (three-dot compare). */
|
|
165
|
+
export declare function listGitHubCompareFiles(input: GitHubResourceInput & {
|
|
166
|
+
readonly baseSha: string;
|
|
167
|
+
readonly headSha: string;
|
|
168
|
+
}): Promise<readonly GitHubPullRequestFile[]>;
|
|
164
169
|
/** Creates a reaction on a GitHub issue or review comment. */
|
|
165
170
|
export declare function createGitHubReaction(input: GitHubResourceInput & {
|
|
166
171
|
readonly commentId: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{resolveGitHubInstallationToken}from"#public/channels/github/auth.js";var GitHubApiError=class extends Error{body;method;path;status;constructor(e){super(`GitHub ${e.method} ${e.path} failed with HTTP ${e.status}.`),this.name=`GitHubApiError`,this.body=e.body,this.method=e.method,this.path=e.path,this.status=e.status}};async function callGitHubApi(e){let r=e.api?.fetch??fetch,i=e.options?.auth!==!1,a={accept:`application/vnd.github+json`,"x-github-api-version":`2022-11-28`,...e.options?.headers};e.body!==void 0&&(a[`content-type`]=`application/json; charset=utf-8`),i&&(a.authorization=`Bearer ${await resolveGitHubInstallationToken({api:e.api,credentials:e.credentials,installationId:e.options?.installationId??e.installationId})}`);let o=await r(`${e.api?.apiBaseUrl??`https://api.github.com`}${e.path}`,{body:e.body===void 0?void 0:JSON.stringify(parseJsonObject(e.body)),headers:a,method:e.method}),s=await parseResponseBody(o);if(!o.ok)throw new GitHubApiError({body:s,method:e.method,path:e.path,status:o.status});return{body:s,ok:o.ok,status:o.status}}async function createGitHubIssueComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/issues/${e.issueNumber}/comments`})).body)}async function updateGitHubIssueComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`PATCH`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/issues/comments/${e.commentId}`})).body)}async function createGitHubReviewCommentReply(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/comments/${e.commentId}/replies`})).body)}async function updateGitHubPullRequestReviewComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`PATCH`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/comments/${e.commentId}`})).body)}function createGitHubPullRequestReview(e){return callGitHubApi({api:e.api,body:e.body,credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/reviews`})}async function createGitHubPullRequestReviewComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:e.body,credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/comments`})).body)}async function getGitHubPullRequest(e){return toPullRequestDetails((await callGitHubApi({api:e.api,credentials:e.credentials,installationId:e.installationId,method:`GET`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}`})).body)}async function listGitHubPullRequestFiles(e){let t=e.perPage===void 0?``:`?per_page=${Math.min(e.perPage,100)}`;return(await callGitHubApi({api:e.api,credentials:e.credentials,installationId:e.installationId,method:`GET`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/files${t}`})).body.map(toPullRequestFile)}function createGitHubReaction(e){let t=e.subject===`issue_comment`?`issues/comments`:`pulls/comments`;return callGitHubApi({api:e.api,body:{content:e.content},credentials:e.credentials,installationId:e.installationId,method:`POST`,options:{headers:{accept:`application/vnd.github+json`}},path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/${t}/${e.commentId}/reactions`})}async function getGitHubRepository(t){let n=await callGitHubApi({api:t.api,credentials:t.credentials,installationId:t.installationId,method:`GET`,options:{auth:t.auth??t.installationId!==void 0},path:`/repos/${encodePath(t.owner)}/${encodePath(t.repo)}`}),r=isObject(n.body)?n.body:{},i=typeof r.id==`number`?r.id:0;return{defaultBranch:typeof r.default_branch==`string`?r.default_branch:void 0,id:i}}function normalizeCommentBody(e){return{body:typeof e==`string`?e:e.body}}function toPostedComment(t){let n=isObject(t)?t:{};return{htmlUrl:typeof n.html_url==`string`?n.html_url:void 0,id:typeof n.id==`number`?n.id:0,raw:t,url:typeof n.url==`string`?n.url:void 0}}function toPullRequestFile(t){let n=isObject(t)?t:{};return{additions:typeof n.additions==`number`?n.additions:void 0,changes:typeof n.changes==`number`?n.changes:void 0,deletions:typeof n.deletions==`number`?n.deletions:void 0,filename:typeof n.filename==`string`?n.filename:``,patch:typeof n.patch==`string`?n.patch:void 0,status:typeof n.status==`string`?n.status:void 0}}function toPullRequestDetails(t){let n=isObject(t)?t:{},r=toPullRequestRefDetails(n.base);return{additions:typeof n.additions==`number`?n.additions:void 0,author:toPullRequestUser(n.user),base:r,body:typeof n.body==`string`&&n.body.length>0?n.body:void 0,changedFiles:typeof n.changed_files==`number`?n.changed_files:void 0,defaultBranch:readDefaultBranch(n.base),deletions:typeof n.deletions==`number`?n.deletions:void 0,draft:n.draft===!0,head:toPullRequestRefDetails(n.head),htmlUrl:typeof n.html_url==`string`?n.html_url:void 0,mergeable:typeof n.mergeable==`boolean`||n.mergeable===null?n.mergeable:void 0,number:typeof n.number==`number`?n.number:0,raw:t,state:typeof n.state==`string`?n.state:void 0,title:typeof n.title==`string`?n.title:``}}function toPullRequestRefDetails(t){let n=isObject(t)?t:{},r=isObject(n.repo)?n.repo:{};return{ref:typeof n.ref==`string`?n.ref:void 0,repoFullName:typeof r.full_name==`string`?r.full_name:void 0,sha:typeof n.sha==`string`?n.sha:void 0}}function toPullRequestUser(t){if(!(!isObject(t)||typeof t.login!=`string`))return{id:typeof t.id==`number`?t.id:0,login:t.login,type:typeof t.type==`string`?t.type:`User`}}function readDefaultBranch(t){let n=isObject(t)?t:{},r=isObject(n.repo)?n.repo:{};return typeof r.default_branch==`string`?r.default_branch:void 0}async function parseResponseBody(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}function encodePath(e){return encodeURIComponent(e)}export{GitHubApiError,callGitHubApi,createGitHubIssueComment,createGitHubPullRequestReview,createGitHubPullRequestReviewComment,createGitHubReaction,createGitHubReviewCommentReply,getGitHubPullRequest,getGitHubRepository,listGitHubPullRequestFiles,updateGitHubIssueComment,updateGitHubPullRequestReviewComment};
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{resolveGitHubInstallationToken}from"#public/channels/github/auth.js";var GitHubApiError=class extends Error{body;method;path;status;constructor(e){super(`GitHub ${e.method} ${e.path} failed with HTTP ${e.status}.`),this.name=`GitHubApiError`,this.body=e.body,this.method=e.method,this.path=e.path,this.status=e.status}};async function callGitHubApi(e){let r=e.api?.fetch??fetch,i=e.options?.auth!==!1,a={accept:`application/vnd.github+json`,"x-github-api-version":`2022-11-28`,...e.options?.headers};e.body!==void 0&&(a[`content-type`]=`application/json; charset=utf-8`),i&&(a.authorization=`Bearer ${await resolveGitHubInstallationToken({api:e.api,credentials:e.credentials,installationId:e.options?.installationId??e.installationId})}`);let o=await r(`${e.api?.apiBaseUrl??`https://api.github.com`}${e.path}`,{body:e.body===void 0?void 0:JSON.stringify(parseJsonObject(e.body)),headers:a,method:e.method}),s=await parseResponseBody(o);if(!o.ok)throw new GitHubApiError({body:s,method:e.method,path:e.path,status:o.status});return{body:s,ok:o.ok,status:o.status}}async function createGitHubIssueComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/issues/${e.issueNumber}/comments`})).body)}async function updateGitHubIssueComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`PATCH`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/issues/comments/${e.commentId}`})).body)}async function createGitHubReviewCommentReply(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/comments/${e.commentId}/replies`})).body)}async function updateGitHubPullRequestReviewComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:normalizeCommentBody(e.body),credentials:e.credentials,installationId:e.installationId,method:`PATCH`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/comments/${e.commentId}`})).body)}function createGitHubPullRequestReview(e){return callGitHubApi({api:e.api,body:e.body,credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/reviews`})}async function createGitHubPullRequestReviewComment(e){return toPostedComment((await callGitHubApi({api:e.api,body:e.body,credentials:e.credentials,installationId:e.installationId,method:`POST`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/comments`})).body)}async function getGitHubPullRequest(e){return toPullRequestDetails((await callGitHubApi({api:e.api,credentials:e.credentials,installationId:e.installationId,method:`GET`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}`})).body)}async function listGitHubPullRequestFiles(e){let t=e.perPage===void 0?``:`?per_page=${Math.min(e.perPage,100)}`;return(await callGitHubApi({api:e.api,credentials:e.credentials,installationId:e.installationId,method:`GET`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/pulls/${e.pullRequestNumber}/files${t}`})).body.map(toPullRequestFile)}async function listGitHubCompareFiles(e){return((await callGitHubApi({api:e.api,credentials:e.credentials,installationId:e.installationId,method:`GET`,path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/compare/${e.baseSha}...${e.headSha}`})).body.files??[]).map(toPullRequestFile)}function createGitHubReaction(e){let t=e.subject===`issue_comment`?`issues/comments`:`pulls/comments`;return callGitHubApi({api:e.api,body:{content:e.content},credentials:e.credentials,installationId:e.installationId,method:`POST`,options:{headers:{accept:`application/vnd.github+json`}},path:`/repos/${encodePath(e.owner)}/${encodePath(e.repo)}/${t}/${e.commentId}/reactions`})}async function getGitHubRepository(t){let n=await callGitHubApi({api:t.api,credentials:t.credentials,installationId:t.installationId,method:`GET`,options:{auth:t.auth??t.installationId!==void 0},path:`/repos/${encodePath(t.owner)}/${encodePath(t.repo)}`}),r=isObject(n.body)?n.body:{},i=typeof r.id==`number`?r.id:0;return{defaultBranch:typeof r.default_branch==`string`?r.default_branch:void 0,id:i}}function normalizeCommentBody(e){return{body:typeof e==`string`?e:e.body}}function toPostedComment(t){let n=isObject(t)?t:{};return{htmlUrl:typeof n.html_url==`string`?n.html_url:void 0,id:typeof n.id==`number`?n.id:0,raw:t,url:typeof n.url==`string`?n.url:void 0}}function toPullRequestFile(t){let n=isObject(t)?t:{};return{additions:typeof n.additions==`number`?n.additions:void 0,changes:typeof n.changes==`number`?n.changes:void 0,deletions:typeof n.deletions==`number`?n.deletions:void 0,filename:typeof n.filename==`string`?n.filename:``,patch:typeof n.patch==`string`?n.patch:void 0,status:typeof n.status==`string`?n.status:void 0}}function toPullRequestDetails(t){let n=isObject(t)?t:{},r=toPullRequestRefDetails(n.base);return{additions:typeof n.additions==`number`?n.additions:void 0,author:toPullRequestUser(n.user),base:r,body:typeof n.body==`string`&&n.body.length>0?n.body:void 0,changedFiles:typeof n.changed_files==`number`?n.changed_files:void 0,defaultBranch:readDefaultBranch(n.base),deletions:typeof n.deletions==`number`?n.deletions:void 0,draft:n.draft===!0,head:toPullRequestRefDetails(n.head),htmlUrl:typeof n.html_url==`string`?n.html_url:void 0,mergeable:typeof n.mergeable==`boolean`||n.mergeable===null?n.mergeable:void 0,number:typeof n.number==`number`?n.number:0,raw:t,state:typeof n.state==`string`?n.state:void 0,title:typeof n.title==`string`?n.title:``}}function toPullRequestRefDetails(t){let n=isObject(t)?t:{},r=isObject(n.repo)?n.repo:{};return{ref:typeof n.ref==`string`?n.ref:void 0,repoFullName:typeof r.full_name==`string`?r.full_name:void 0,sha:typeof n.sha==`string`?n.sha:void 0}}function toPullRequestUser(t){if(!(!isObject(t)||typeof t.login!=`string`))return{id:typeof t.id==`number`?t.id:0,login:t.login,type:typeof t.type==`string`?t.type:`User`}}function readDefaultBranch(t){let n=isObject(t)?t:{},r=isObject(n.repo)?n.repo:{};return typeof r.default_branch==`string`?r.default_branch:void 0}async function parseResponseBody(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}function encodePath(e){return encodeURIComponent(e)}export{GitHubApiError,callGitHubApi,createGitHubIssueComment,createGitHubPullRequestReview,createGitHubPullRequestReviewComment,createGitHubReaction,createGitHubReviewCommentReply,getGitHubPullRequest,getGitHubRepository,listGitHubCompareFiles,listGitHubPullRequestFiles,updateGitHubIssueComment,updateGitHubPullRequestReviewComment};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{extractGitHubCommentTrigger,formatGitHubContextBlock,prependGitHubContext}from"#public/channels/github/inbound.js";import{buildGitHubBinding}from"#public/channels/github/binding.js";import{buildGitHubPullRequestContext,mergeGitHubContext}from"#public/channels/github/pr-context.js";import{continuationTokenFromState,stateFromIssueCommentEvent,stateFromIssueEvent,stateFromPullRequestEvent,stateFromPullRequestReviewCommentEvent}from"#public/channels/github/state.js";const log=createLogger(`github.dispatch`);async function dispatchIssueComment(e){if(isIgnoredInboundComment(e.event.comment.body,e.event.comment.author,e.botName))return;let t=buildInboundContext(e.config,e.event);await dispatchCommentTurn({body:e.event.comment.body,botName:e.botName,commentUrl:e.event.comment.htmlUrl,event:e.event,handlerResult:()=>e.handler(t,toGitHubComment(e.event.comment)),config:e.config,send:e.send,state:stateFromIssueCommentEvent(e.event)})}async function dispatchPullRequestReviewComment(e){if(isIgnoredInboundComment(e.event.comment.body,e.event.comment.author,e.botName))return;let t=buildInboundContext(e.config,e.event);await dispatchCommentTurn({body:e.event.comment.body,botName:e.botName,commentUrl:e.event.comment.htmlUrl,event:e.event,handlerResult:()=>e.handler(t,toGitHubComment(e.event.comment)),config:e.config,send:e.send,state:stateFromPullRequestReviewCommentEvent(e.event)})}async function dispatchIssue(e){let t=buildInboundContext(e.config,e.event);await dispatchWebhookEventTurn({config:e.config,event:e.event,handlerResult:()=>e.handler(t,e.event.issue),message:formatIssueEventMessage(e.event),send:e.send,state:stateFromIssueEvent(e.event)})}async function dispatchPullRequest(e){let t=buildInboundContext(e.config,e.event);await dispatchWebhookEventTurn({config:e.config,event:e.event,handlerResult:()=>e.handler(t,e.event.pullRequest),message:formatPullRequestEventMessage(e.event),send:e.send,state:stateFromPullRequestEvent(e.event)})}async function dispatchWebhookEventTurn(e){let t=await runInboundHandler({event:e.event,handlerResult:e.handlerResult});t!=null&&await sendGitHubTurn({auth:t.auth,event:e.event,message:e.message,context:mergeGitHubContext({github:await buildPullRequestContext(e.config,e.state,e.event.delivery.id),hook:t.context}),send:e.send,state:e.state})}async function dispatchCommentTurn(e){let t=await runInboundHandler({event:e.event,handlerResult:e.handlerResult});if(t==null)return;let r=extractGitHubCommentTrigger({body:e.body,botName:e.botName})?.message??e.body.trim();await sendGitHubTurn({auth:t.auth,commentUrl:e.commentUrl,event:e.event,message:r,context:mergeGitHubContext({github:await buildPullRequestContext(e.config,e.state,e.event.delivery.id),hook:t.context}),send:e.send,state:e.state})}async function runInboundHandler(e){try{return await e.handlerResult()}catch(n){logError(log,`GitHub inbound handler failed`,n,{deliveryId:e.event.delivery.id});return}}async function sendGitHubTurn(e){let n=formatGitHubContextBlock({deliveryId:e.event.delivery.id,commentUrl:e.commentUrl,headSha:e.state.headSha,issueNumber:e.state.issueNumber,pullRequestNumber:e.state.pullRequestNumber,repository:e.event.repository,sender:e.event.sender}),i=prependGitHubContext(e.message,n);try{await e.send({message:i,context:e.context},{auth:e.auth,continuationToken:continuationTokenFromState(e.state),state:e.state})}catch(n){logError(log,e.logMessage??`GitHub delivery failed`,n,{deliveryId:e.event.delivery.id})}}async function buildPullRequestContext(e,n,r){try{return await buildGitHubPullRequestContext({api:e.api,config:e.pullRequestContext,credentials:e.credentials,installationId:n.installationId??void 0,owner:n.owner,pullRequestNumber:n.pullRequestNumber,repo:n.repo})}catch(e){logError(log,`GitHub pull-request context failed — swallowed`,e,{deliveryId:r});return}}function buildInboundContext(e,t){let n=buildGitHubBinding({config:e,state:t.kind===`issue_comment`?stateFromIssueCommentEvent(t):t.kind===`issues`?stateFromIssueEvent(t):t.kind===`pull_request`?stateFromPullRequestEvent(t):stateFromPullRequestReviewCommentEvent(t)});return{conversation:t.conversation,delivery:t.delivery,github:n.github,repository:t.repository,sender:t.sender,thread:n.thread}}function toGitHubComment(e){return{author:e.author,body:e.body,htmlUrl:e.htmlUrl,id:e.id,raw:e.raw,url:e.url}}function formatIssueEventMessage(e){let t=readString(e.issue.raw.title);return`Issue ${e.issue.action}: #${e.issue.issueNumber}${t?` ${t}`:``}`}function formatPullRequestEventMessage(e){let t=readString(e.pullRequest.raw.title);return`Pull request ${e.pullRequest.action}: #${e.pullRequest.pullRequestNumber}${t?` ${t}`:``}`}function isIgnoredInboundComment(e,t,n){if(e.includes(`<!-- eve:github:`)||t?.type===`Bot`)return!0;let r=n?`${n}[bot]`.toLowerCase():``;return r.length>0&&t?.login.toLowerCase()===r}function readString(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}export{dispatchIssue,dispatchIssueComment,dispatchPullRequest,dispatchPullRequestReviewComment};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{extractGitHubCommentTrigger,formatGitHubContextBlock,prependGitHubContext}from"#public/channels/github/inbound.js";import{buildGitHubBinding}from"#public/channels/github/binding.js";import{buildGitHubPullRequestContext,mergeGitHubContext}from"#public/channels/github/pr-context.js";import{continuationTokenFromState,stateFromIssueCommentEvent,stateFromIssueEvent,stateFromPullRequestEvent,stateFromPullRequestReviewCommentEvent}from"#public/channels/github/state.js";const log=createLogger(`github.dispatch`);async function dispatchIssueComment(e){if(isIgnoredInboundComment(e.event.comment.body,e.event.comment.author,e.botName))return;let t=buildInboundContext(e.config,e.event);await dispatchCommentTurn({body:e.event.comment.body,botName:e.botName,commentUrl:e.event.comment.htmlUrl,event:e.event,handlerResult:()=>e.handler(t,toGitHubComment(e.event.comment)),config:e.config,send:e.send,state:stateFromIssueCommentEvent(e.event)})}async function dispatchPullRequestReviewComment(e){if(isIgnoredInboundComment(e.event.comment.body,e.event.comment.author,e.botName))return;let t=buildInboundContext(e.config,e.event);await dispatchCommentTurn({body:e.event.comment.body,botName:e.botName,commentUrl:e.event.comment.htmlUrl,event:e.event,handlerResult:()=>e.handler(t,toGitHubComment(e.event.comment)),config:e.config,send:e.send,state:stateFromPullRequestReviewCommentEvent(e.event)})}async function dispatchIssue(e){let t=buildInboundContext(e.config,e.event);await dispatchWebhookEventTurn({config:e.config,event:e.event,handlerResult:()=>e.handler(t,e.event.issue),message:formatIssueEventMessage(e.event),send:e.send,state:stateFromIssueEvent(e.event)})}async function dispatchPullRequest(e){let t=buildInboundContext(e.config,e.event);await dispatchWebhookEventTurn({config:e.config,event:e.event,handlerResult:()=>e.handler(t,e.event.pullRequest),message:formatPullRequestEventMessage(e.event),send:e.send,state:stateFromPullRequestEvent(e.event)})}async function dispatchWebhookEventTurn(e){let t=await runInboundHandler({event:e.event,handlerResult:e.handlerResult});t!=null&&await sendGitHubTurn({auth:t.auth,event:e.event,message:e.message,context:mergeGitHubContext({github:await buildPullRequestContext(e.config,e.state,e.event.delivery.id),hook:t.context}),send:e.send,state:e.state})}async function dispatchCommentTurn(e){let t=await runInboundHandler({event:e.event,handlerResult:e.handlerResult});if(t==null)return;let r=extractGitHubCommentTrigger({body:e.body,botName:e.botName})?.message??e.body.trim();await sendGitHubTurn({auth:t.auth,commentUrl:e.commentUrl,event:e.event,message:r,context:mergeGitHubContext({github:await buildPullRequestContext(e.config,e.state,e.event.delivery.id),hook:t.context}),send:e.send,state:e.state})}async function runInboundHandler(e){try{return await e.handlerResult()}catch(n){logError(log,`GitHub inbound handler failed`,n,{deliveryId:e.event.delivery.id});return}}async function sendGitHubTurn(e){let n=formatGitHubContextBlock({deliveryId:e.event.delivery.id,commentUrl:e.commentUrl,headSha:e.state.headSha,issueNumber:e.state.issueNumber,pullRequestNumber:e.state.pullRequestNumber,repository:e.event.repository,sender:e.event.sender}),i=prependGitHubContext(e.message,n);try{await e.send({message:i,context:e.context},{auth:e.auth,continuationToken:continuationTokenFromState(e.state),state:e.state})}catch(n){logError(log,e.logMessage??`GitHub delivery failed`,n,{deliveryId:e.event.delivery.id})}}async function buildPullRequestContext(e,n,r){try{return await buildGitHubPullRequestContext({api:e.api,baseSha:n.baseSha,config:e.pullRequestContext,credentials:e.credentials,headSha:n.headSha,installationId:n.installationId??void 0,owner:n.owner,pullRequestNumber:n.pullRequestNumber,repo:n.repo})}catch(e){logError(log,`GitHub pull-request context failed — swallowed`,e,{deliveryId:r});return}}function buildInboundContext(e,t){let n=buildGitHubBinding({config:e,state:t.kind===`issue_comment`?stateFromIssueCommentEvent(t):t.kind===`issues`?stateFromIssueEvent(t):t.kind===`pull_request`?stateFromPullRequestEvent(t):stateFromPullRequestReviewCommentEvent(t)});return{conversation:t.conversation,delivery:t.delivery,github:n.github,repository:t.repository,sender:t.sender,thread:n.thread}}function toGitHubComment(e){return{author:e.author,body:e.body,htmlUrl:e.htmlUrl,id:e.id,raw:e.raw,url:e.url}}function formatIssueEventMessage(e){let t=readString(e.issue.raw.title);return`Issue ${e.issue.action}: #${e.issue.issueNumber}${t?` ${t}`:``}`}function formatPullRequestEventMessage(e){let t=readString(e.pullRequest.raw.title);return`Pull request ${e.pullRequest.action}: #${e.pullRequest.pullRequestNumber}${t?` ${t}`:``}`}function isIgnoredInboundComment(e,t,n){if(e.includes(`<!-- eve:github:`)||t?.type===`Bot`)return!0;let r=n?`${n}[bot]`.toLowerCase():``;return r.length>0&&t?.login.toLowerCase()===r}function readString(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}export{dispatchIssue,dispatchIssueComment,dispatchPullRequest,dispatchPullRequestReviewComment};
|
|
@@ -22,8 +22,18 @@ export interface GitHubPullRequestContextConfig {
|
|
|
22
22
|
/** Input for building one-shot model context for a pull request. */
|
|
23
23
|
export interface GitHubPullRequestContextInput {
|
|
24
24
|
readonly api?: GitHubApiOptions;
|
|
25
|
+
/**
|
|
26
|
+
* When set with {@link headSha}, file patches load via the compare API for
|
|
27
|
+
* this exact base/head pair instead of `/pulls/{number}/files` (current head).
|
|
28
|
+
*/
|
|
29
|
+
readonly baseSha?: string | null;
|
|
25
30
|
readonly config?: GitHubPullRequestContextConfig;
|
|
26
31
|
readonly credentials?: GitHubChannelCredentials;
|
|
32
|
+
/**
|
|
33
|
+
* Webhook-resolved head SHA for this turn. When set, metadata and diffs pin to
|
|
34
|
+
* this commit so injected context matches sandbox checkout.
|
|
35
|
+
*/
|
|
36
|
+
readonly headSha?: string | null;
|
|
27
37
|
readonly installationId?: number;
|
|
28
38
|
readonly owner: string;
|
|
29
39
|
readonly pullRequestNumber: number | null;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{getGitHubPullRequest,listGitHubPullRequestFiles}from"#public/channels/github/api.js";const MAX_PATCH_BYTES=2e4,GITHUB_DEFAULT_EXCLUDED_DIFF_FILES=[`**/pnpm-lock.yaml`,`**/package-lock.json`,`**/npm-shrinkwrap.json`,`**/yarn.lock`,`**/bun.lockb`,`**/Cargo.lock`,`**/go.sum`,`**/poetry.lock`,`**/Pipfile.lock`,`**/uv.lock`,`**/composer.lock`,`**/Gemfile.lock`,`**/*.min.js`,`**/*.min.css`,`**/*.map`,`**/*.snap`];async function buildGitHubPullRequestContext(
|
|
1
|
+
import{getGitHubPullRequest,listGitHubCompareFiles,listGitHubPullRequestFiles}from"#public/channels/github/api.js";const MAX_PATCH_BYTES=2e4,GITHUB_DEFAULT_EXCLUDED_DIFF_FILES=[`**/pnpm-lock.yaml`,`**/package-lock.json`,`**/npm-shrinkwrap.json`,`**/yarn.lock`,`**/bun.lockb`,`**/Cargo.lock`,`**/go.sum`,`**/poetry.lock`,`**/Pipfile.lock`,`**/uv.lock`,`**/composer.lock`,`**/Gemfile.lock`,`**/*.min.js`,`**/*.min.css`,`**/*.map`,`**/*.snap`];async function buildGitHubPullRequestContext(r){if(r.pullRequestNumber===null)return;let a=withPinnedPullRequestShas(await getGitHubPullRequest({api:r.api,credentials:r.credentials,installationId:r.installationId,owner:r.owner,pullRequestNumber:r.pullRequestNumber,repo:r.repo}),r),o=renderPullRequestMetadata(a),s=readNonEmptySha(r.baseSha)??readNonEmptySha(a.base.sha),c=readNonEmptySha(r.headSha)??readNonEmptySha(a.head.sha),l=readNonEmptySha(r.headSha)!==void 0&&c!==void 0&&s!==void 0?(await listGitHubCompareFiles({api:r.api,baseSha:s,credentials:r.credentials,headSha:c,installationId:r.installationId,owner:r.owner,repo:r.repo})).slice(0,50):await listGitHubPullRequestFiles({api:r.api,credentials:r.credentials,installationId:r.installationId,owner:r.owner,perPage:50,pullRequestNumber:r.pullRequestNumber,repo:r.repo}),u=[...GITHUB_DEFAULT_EXCLUDED_DIFF_FILES,...r.config?.excludedFiles??[]];return o.push(``,...renderPullRequestFiles(l,u)),[[`GitHub pull request context for the current turn. `,`Use this as background for the user's GitHub comment.`,``,o.join(`
|
|
2
2
|
`)].join(`
|
|
3
|
-
`)]}function mergeGitHubContext(e){let t=e.github??[],n=e.hook??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function renderPullRequestMetadata(e){return[`<github_pull_request>`,`number: ${e.number}`,`title: ${e.title}`,`state: ${e.state??`unknown`}`,`draft: ${e.draft?`true`:`false`}`,...e.author?.login?[`author: ${e.author.login}`]:[],...e.htmlUrl?[`url: ${e.htmlUrl}`]:[],...e.base.ref?[`base_ref: ${e.base.ref}`]:[],...e.base.sha?[`base_sha: ${e.base.sha}`]:[],...e.head.ref?[`head_ref: ${e.head.ref}`]:[],...e.head.sha?[`head_sha: ${e.head.sha}`]:[],...e.mergeable===null||e.mergeable===void 0?[]:[`mergeable: ${e.mergeable?`true`:`false`}`],...e.changedFiles===void 0?[]:[`changed_files: ${e.changedFiles}`],...e.additions===void 0?[]:[`additions: ${e.additions}`],...e.deletions===void 0?[]:[`deletions: ${e.deletions}`],...e.body?[``,`body:`,indent(truncateText(e.body,4e3))]:[],`</github_pull_request>`]}function renderPullRequestFiles(e,t){if(e.length===0)return[`<github_pull_request_files>`,`none`,`</github_pull_request_files>`];let
|
|
3
|
+
`)]}function mergeGitHubContext(e){let t=e.github??[],n=e.hook??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function withPinnedPullRequestShas(e,t){let n=readNonEmptySha(t.headSha),r=readNonEmptySha(t.baseSha);return n===void 0&&r===void 0?e:{...e,base:{...e.base,sha:r??e.base.sha},head:{...e.head,sha:n??e.head.sha}}}function readNonEmptySha(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function renderPullRequestMetadata(e){return[`<github_pull_request>`,`number: ${e.number}`,`title: ${e.title}`,`state: ${e.state??`unknown`}`,`draft: ${e.draft?`true`:`false`}`,...e.author?.login?[`author: ${e.author.login}`]:[],...e.htmlUrl?[`url: ${e.htmlUrl}`]:[],...e.base.ref?[`base_ref: ${e.base.ref}`]:[],...e.base.sha?[`base_sha: ${e.base.sha}`]:[],...e.head.ref?[`head_ref: ${e.head.ref}`]:[],...e.head.sha?[`head_sha: ${e.head.sha}`]:[],...e.mergeable===null||e.mergeable===void 0?[]:[`mergeable: ${e.mergeable?`true`:`false`}`],...e.changedFiles===void 0?[]:[`changed_files: ${e.changedFiles}`],...e.additions===void 0?[]:[`additions: ${e.additions}`],...e.deletions===void 0?[]:[`deletions: ${e.deletions}`],...e.body?[``,`body:`,indent(truncateText(e.body,4e3))]:[],`</github_pull_request>`]}function renderPullRequestFiles(e,t){if(e.length===0)return[`<github_pull_request_files>`,`none`,`</github_pull_request_files>`];let n=[`<github_pull_request_files>`],i=MAX_PATCH_BYTES,a=!1;for(let r of e){if(n.push(renderFileSummary(r)),fileMatchesAnyGlob(r.filename,t)){n.push(` patch omitted (excluded)`);continue}if(r.patch===void 0)continue;if(i<=0){a=!0;continue}let e=truncateByBytes(r.patch,i);n.push(`patch:`,indent(e.text)),i-=e.bytes,e.truncated&&(a=!0,i=0)}return a&&n.push(``,`patches_truncated: true`,`max_patch_bytes: ${MAX_PATCH_BYTES}`),n.push(`</github_pull_request_files>`),n}function renderFileSummary(e){let t=[e.status??`modified`,e.additions===void 0?void 0:`+${e.additions}`,e.deletions===void 0?void 0:`-${e.deletions}`].filter(e=>e!==void 0);return`- ${e.filename}${t.length>0?` (${t.join(`, `)})`:``}`}function fileMatchesAnyGlob(e,t){return t.some(t=>globToRegExp(t).test(e))}function globToRegExp(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e.charAt(n);r===`*`?e[n+1]===`*`?(t+=`.*`,n+=1,e[n+1]===`/`&&(n+=1)):t+=`[^/]*`:`\\^$.|?+()[]{}`.includes(r)?t+=`\\${r}`:t+=r}return RegExp(`^${t}$`,`u`)}function truncateByBytes(e,t){let n=new TextEncoder().encode(e);return n.byteLength<=t?{bytes:n.byteLength,text:e,truncated:!1}:{bytes:t,text:`${new TextDecoder().decode(n.slice(0,t))}\n[truncated]`,truncated:!0}}function truncateText(e,t){return e.length<=t?e:`${e.slice(0,t)}\n[truncated]`}function indent(e){return e.split(`
|
|
4
4
|
`).map(e=>` ${e}`).join(`
|
|
5
5
|
`)}export{GITHUB_DEFAULT_EXCLUDED_DIFF_FILES,buildGitHubPullRequestContext,fileMatchesAnyGlob,mergeGitHubContext};
|
|
@@ -21,8 +21,9 @@ export interface NeedsApprovalContext<TInput = Record<string, unknown>> {
|
|
|
21
21
|
}
|
|
22
22
|
export type { ToolModelOutput } from "#shared/tool-definition.js";
|
|
23
23
|
/**
|
|
24
|
-
* Authorization
|
|
25
|
-
*
|
|
24
|
+
* Authorization provider passed to {@link ToolContext.getToken} or
|
|
25
|
+
* {@link ToolContext.requireAuth}. Accepts the same shapes as a connection's
|
|
26
|
+
* `auth`:
|
|
26
27
|
* - a `getToken`-only object (static API keys, pre-provisioned JWTs);
|
|
27
28
|
* `principalType` may be omitted and defaults to `"app"`.
|
|
28
29
|
* - a full interactive OAuth definition (e.g. `connect("okta/myagent")` from
|
|
@@ -62,42 +63,14 @@ export interface ToolAuthOptions {
|
|
|
62
63
|
*
|
|
63
64
|
* Extends {@link SessionContext} with token accessors. Passing a provider
|
|
64
65
|
* resolves that provider inline, which lets one tool use multiple credentials.
|
|
65
|
-
* For backwards compatibility, calling the accessors without a provider uses
|
|
66
|
-
* the tool's deprecated top-level `auth` field and throws when no `auth` exists.
|
|
67
66
|
*/
|
|
68
67
|
export type ToolContext = SessionContext & {
|
|
69
|
-
/**
|
|
70
|
-
* Resolves the bearer token for this tool's declared `auth`,
|
|
71
|
-
* consulting the per-step token cache before invoking the authored
|
|
72
|
-
* `getToken`. For interactive strategies a cache miss throws
|
|
73
|
-
* `ConnectionAuthorizationRequiredError`; the runtime catches it,
|
|
74
|
-
* suspends the turn on a framework-owned callback URL, shows a
|
|
75
|
-
* "Sign in" affordance, and re-runs the tool after the OAuth
|
|
76
|
-
* callback completes.
|
|
77
|
-
*
|
|
78
|
-
* Throws when the tool does not declare an `auth` strategy.
|
|
79
|
-
*
|
|
80
|
-
* @deprecated Prefer `ctx.getToken(provider)` so auth dependencies live at
|
|
81
|
-
* the call site and compose when a tool needs multiple credentials.
|
|
82
|
-
*/
|
|
83
|
-
getToken(): Promise<TokenResult>;
|
|
84
68
|
/**
|
|
85
69
|
* Resolves the bearer token for an inline provider. This accepts the same
|
|
86
70
|
* auth shapes as a connection's `auth` field, including `connect("...")`
|
|
87
71
|
* from `@vercel/connect/eve`.
|
|
88
72
|
*/
|
|
89
73
|
getToken(provider: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;
|
|
90
|
-
/**
|
|
91
|
-
* Signals that the caller must complete this tool's authorization flow.
|
|
92
|
-
* Throws `ConnectionAuthorizationRequiredError`, which the runtime converts
|
|
93
|
-
* into a consent prompt (for interactive strategies) and re-runs the tool
|
|
94
|
-
* after sign-in. Use it after a downstream request rejects a token returned
|
|
95
|
-
* by the deprecated no-argument {@link getToken}.
|
|
96
|
-
*
|
|
97
|
-
* @deprecated Prefer `ctx.requireAuth(provider)` so auth dependencies live at
|
|
98
|
-
* the call site and compose when a tool needs multiple credentials.
|
|
99
|
-
*/
|
|
100
|
-
requireAuth(): never;
|
|
101
74
|
/**
|
|
102
75
|
* Signals that the caller must complete authorization for an inline
|
|
103
76
|
* provider before proceeding. Use this after a downstream `401` rejects a
|
|
@@ -114,16 +87,6 @@ export type ToolContext = SessionContext & {
|
|
|
114
87
|
*/
|
|
115
88
|
export type ToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefinition<TInput, TOutput> & {
|
|
116
89
|
execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput;
|
|
117
|
-
/**
|
|
118
|
-
* Optional authorization strategy used by the deprecated no-argument
|
|
119
|
-
* {@link ToolContext.getToken} / {@link ToolContext.requireAuth} accessors.
|
|
120
|
-
*
|
|
121
|
-
* @deprecated Prefer passing a provider at the call site:
|
|
122
|
-
* `ctx.getToken(connect("..."))` or `ctx.requireAuth(connect("..."))`.
|
|
123
|
-
* Inline providers use the same auth shapes and compose when a tool needs
|
|
124
|
-
* multiple credentials.
|
|
125
|
-
*/
|
|
126
|
-
auth?: ToolAuthDefinition;
|
|
127
90
|
/**
|
|
128
91
|
* Optional per-tool approval gate. The return value determines whether
|
|
129
92
|
* user approval is required before executing this tool.
|
|
@@ -160,8 +123,6 @@ export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unk
|
|
|
160
123
|
execute(input: StandardJSONSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema>;
|
|
161
124
|
needsApproval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, unknown>["needsApproval"];
|
|
162
125
|
toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
|
|
163
|
-
/** @deprecated Prefer inline providers via `ctx.getToken(provider)`. */
|
|
164
|
-
auth?: ToolAuthDefinition;
|
|
165
126
|
}): ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
|
|
166
127
|
export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutput>(definition: {
|
|
167
128
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
@@ -170,8 +131,6 @@ export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown,
|
|
|
170
131
|
execute(input: StandardJSONSchemaV1.InferOutput<TSchema>, ctx: ToolContext): Promise<TOutput> | TOutput;
|
|
171
132
|
needsApproval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, unknown>["needsApproval"];
|
|
172
133
|
toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
|
|
173
|
-
/** @deprecated Prefer inline providers via `ctx.getToken(provider)`. */
|
|
174
|
-
auth?: ToolAuthDefinition;
|
|
175
134
|
}): ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, TOutput>;
|
|
176
135
|
export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>>(definition: {
|
|
177
136
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
@@ -180,8 +139,6 @@ export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<un
|
|
|
180
139
|
execute(input: Record<string, unknown>, ctx: ToolContext): Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema>;
|
|
181
140
|
needsApproval?: ToolDefinition<Record<string, unknown>, unknown>["needsApproval"];
|
|
182
141
|
toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
|
|
183
|
-
/** @deprecated Prefer inline providers via `ctx.getToken(provider)`. */
|
|
184
|
-
auth?: ToolAuthDefinition;
|
|
185
142
|
}): ToolDefinition<Record<string, unknown>, StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
|
|
186
143
|
export declare function defineTool<TOutput>(definition: {
|
|
187
144
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
@@ -190,8 +147,6 @@ export declare function defineTool<TOutput>(definition: {
|
|
|
190
147
|
execute(input: Record<string, unknown>, ctx: ToolContext): Promise<TOutput> | TOutput;
|
|
191
148
|
needsApproval?: ToolDefinition<Record<string, unknown>, unknown>["needsApproval"];
|
|
192
149
|
toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
|
|
193
|
-
/** @deprecated Prefer inline providers via `ctx.getToken(provider)`. */
|
|
194
|
-
auth?: ToolAuthDefinition;
|
|
195
150
|
}): ToolDefinition<Record<string, unknown>, TOutput>;
|
|
196
151
|
export declare function defineTool<TInput = unknown, TOutput = unknown>(definition: ToolDefinition<TInput, TOutput>): ToolDefinition<TInput, TOutput>;
|
|
197
152
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DYNAMIC_SENTINEL_KIND,TOOL_BRAND}from"#shared/dynamic-tool-definition.js";import{
|
|
1
|
+
import{DYNAMIC_SENTINEL_KIND,TOOL_BRAND}from"#shared/dynamic-tool-definition.js";import{stampDefinitionKey}from"#public/tool-result-narrowing.js";function defineTool(e){if(e.auth!==void 0)throw Error(`defineTool: The "auth" field is no longer supported. Pass auth providers inline to ctx.getToken(provider) or ctx.requireAuth(provider).`);return Object.assign(e,{[TOOL_BRAND]:!0}),stampDefinitionKey(e,`tool:${e.description}`),e}function defineDynamic(t){let n={kind:DYNAMIC_SENTINEL_KIND,events:t.events};return stampDefinitionKey(n,`dynamic:${Object.keys(t.events).join(`,`)}`),n}const DISABLED_TOOL_SENTINEL_KIND=`eve:disabled-tool`;function disableTool(){return{kind:DISABLED_TOOL_SENTINEL_KIND}}function isDisabledToolSentinel(e){return typeof e==`object`&&!!e&&e.kind===DISABLED_TOOL_SENTINEL_KIND}const ENABLE_WORKFLOW_TOOL_SENTINEL_KIND=`eve:enable-workflow-tool`,ExperimentalWorkflow=Object.freeze({kind:ENABLE_WORKFLOW_TOOL_SENTINEL_KIND});function isEnableWorkflowToolSentinel(e){return typeof e==`object`&&!!e&&e.kind===ENABLE_WORKFLOW_TOOL_SENTINEL_KIND}export{ExperimentalWorkflow,defineDynamic,defineTool,disableTool,isDisabledToolSentinel,isEnableWorkflowToolSentinel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{
|
|
1
|
+
import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{registerDefinitionSource,stampDefinitionKey}from"#public/tool-result-narrowing.js";async function resolveToolDefinition(i,a,o){try{let n=expectObjectRecord(await loadResolvedModuleExport({definition:i,kindLabel:`tool`,moduleMap:a,nodeId:o}),describe(i,`to return an object`)),r={kind:`tool`,logicalPath:i.logicalPath,name:i.name},s=`tool-source:${i.sourceId}`;stampDefinitionKey(n,s),registerDefinitionSource(s,r),registerDefinitionSource(`tool:${n.description}`,r);let c=expectFunction(n.execute,describe(i,`to provide an execute function`));return{description:i.description,execute:c,exportName:i.exportName,inputSchema:i.inputSchema,logicalPath:i.logicalPath,name:i.name,outputSchema:i.outputSchema,sourceId:i.sourceId,sourceKind:`module`,...extractOptionalHooks(n,i)}}catch(e){throw e instanceof ResolveAgentError?e:new ResolveAgentError(`Failed to attach the tool execute function from "${i.logicalPath}": ${toErrorMessage(e)}`,{logicalPath:i.logicalPath,sourceId:i.sourceId})}}function extractOptionalHooks(t,n){let r={};return t.needsApproval!==void 0&&(r.needsApproval=expectFunction(t.needsApproval,describe(n,`to provide a needsApproval function`))),t.toModelOutput!==void 0&&(r.toModelOutput=expectFunction(t.toModelOutput,describe(n,`to provide a toModelOutput function`))),t.inputSchema!==void 0&&isFlexibleSchema(t.inputSchema)&&(r.inputStandardSchema=t.inputSchema),t.outputSchema!==void 0&&isFlexibleSchema(t.outputSchema)&&(r.outputStandardSchema=t.outputSchema),r}function describe(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function isFlexibleSchema(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}export{resolveToolDefinition};
|
|
@@ -154,16 +154,6 @@ export type ResolvedToolDefinition = Readonly<Optional<InternalToolDefinitionWit
|
|
|
154
154
|
* handlers and the stream. See {@link ToolModelOutput}.
|
|
155
155
|
*/
|
|
156
156
|
readonly toModelOutput?: (output: unknown) => ToolModelOutput | Promise<ToolModelOutput>;
|
|
157
|
-
/**
|
|
158
|
-
* Optional authorization strategy reattached from the authored
|
|
159
|
-
* module at resolve time. Carries live `getToken` /
|
|
160
|
-
* `startAuthorization` / `completeAuthorization` callbacks, so it
|
|
161
|
-
* cannot survive compilation and must be read off the resolved
|
|
162
|
-
* module like {@link execute}. When present, the execution layer
|
|
163
|
-
* builds token accessors onto the tool context and drives the
|
|
164
|
-
* interactive consent flow scoped to this tool's {@link name}.
|
|
165
|
-
*/
|
|
166
|
-
readonly auth?: AuthorizationDefinition;
|
|
167
157
|
};
|
|
168
158
|
/**
|
|
169
159
|
* Runtime-owned authored hook definition resolved from a compiled module
|
|
@@ -2,12 +2,11 @@ import { detectProjectResolution, type ProjectResolution } from "../project-reso
|
|
|
2
2
|
import type { Prompter } from "../prompter.js";
|
|
3
3
|
import { type SetupState } from "../state.js";
|
|
4
4
|
import type { SetupBox } from "../step.js";
|
|
5
|
-
import { linkProject,
|
|
5
|
+
import { linkProject, unresolvedProject } from "../vercel-project.js";
|
|
6
6
|
/** Injected for tests; defaults to the real Vercel project helpers. */
|
|
7
7
|
export interface LinkProjectDeps {
|
|
8
8
|
linkProject: typeof linkProject;
|
|
9
9
|
detectProjectResolution: typeof detectProjectResolution;
|
|
10
|
-
resolveProjectByNameOrId: typeof resolveProjectByNameOrId;
|
|
11
10
|
unresolvedProject: typeof unresolvedProject;
|
|
12
11
|
}
|
|
13
12
|
export interface LinkProjectOptions {
|
|
@@ -16,18 +15,13 @@ export interface LinkProjectOptions {
|
|
|
16
15
|
deps?: LinkProjectDeps;
|
|
17
16
|
}
|
|
18
17
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* resolve-provisioning box, so `perform` owns all the work.
|
|
18
|
+
* Executes the resolved Vercel project plan after scaffolding, once the project
|
|
19
|
+
* directory exists. Gather prompts for nothing — every decision was made in the
|
|
20
|
+
* resolve-provisioning box.
|
|
23
21
|
*
|
|
24
|
-
* The plan is authoritative
|
|
25
|
-
* a stale or mismatched `.vercel` link can
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* in `state.project`, which every later box reads.
|
|
29
|
-
*
|
|
30
|
-
* Named `linkVercelProject` because the setup island also exports the
|
|
31
|
-
* `linkProject` executor helper this box drives.
|
|
22
|
+
* The plan is authoritative: the box always re-links to the planned project so
|
|
23
|
+
* a stale or mismatched `.vercel` link can't silently win. Re-linking the same
|
|
24
|
+
* identity is idempotent. The resolution read back from the link metadata lands
|
|
25
|
+
* in `state.project`.
|
|
32
26
|
*/
|
|
33
27
|
export declare function linkVercelProject(options: LinkProjectOptions): SetupBox<SetupState, null, ProjectResolution>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProjectResolution,mergeProjectResolution}from"../project-resolution.js";import{requireProjectPath}from"../state.js";import{linkProject,
|
|
1
|
+
import{detectProjectResolution,mergeProjectResolution}from"../project-resolution.js";import{requireProjectPath}from"../state.js";import{linkProject,unresolvedProject}from"../vercel-project.js";import{createPromptCommandOutput}from"#setup/cli/index.js";function linkVercelProject(a){let o=a.deps??{linkProject,detectProjectResolution,unresolvedProject};return{id:`link-project`,shouldRun(e){return e.vercelProject.kind!==`none`},async gather(){return null},async perform({state:e,signal:t}){let r=e.vercelProject;if(r.kind===`none`)return o.unresolvedProject();let i=requireProjectPath(e),s=createPromptCommandOutput(a.prompter.log),c=await o.linkProject(a.prompter,i,r,s,{signal:t});if(t?.throwIfAborted(),!c)throw Error("Vercel project provisioning did not complete. Run `vercel link` manually, or re-run and choose not to deploy to Vercel.");let l=await o.detectProjectResolution(i,{signal:t});if(l.kind===`unresolved`)throw Error(`Linked the directory, but could not resolve the Vercel project from its link metadata.`);if(l.projectId!==c.projectId)throw Error(`The linked project does not match the selected project: expected ${c.projectId}, found ${l.projectId}.`);return l},apply(e,n){return{...e,project:mergeProjectResolution(e.project,n)}}}}export{linkVercelProject};
|
|
@@ -4,7 +4,7 @@ import { detectProjectResolution, type ProjectResolution } from "../project-reso
|
|
|
4
4
|
import type { Prompter } from "../prompter.js";
|
|
5
5
|
import type { ProvisioningMode, ResolvedAiGateway, ResolvedVercelProject, SetupState, WiringMode } from "../state.js";
|
|
6
6
|
import type { SetupBox } from "../step.js";
|
|
7
|
-
import { assertNewProjectNameAvailable, isVercelAuthenticated, pickNewProjectName, pickProject, pickTeam, requireAuth, resolveTeam, validateTeam } from "../vercel-project.js";
|
|
7
|
+
import { assertNewProjectNameAvailable, isVercelAuthenticated, pickNewProjectName, pickProject, pickTeam, requireAuth, resolveProjectByNameOrId, resolveTeam, validateTeam } from "../vercel-project.js";
|
|
8
8
|
/** Injected for tests; defaults to the real Vercel project and fs helpers. */
|
|
9
9
|
export interface ResolveProvisioningDeps {
|
|
10
10
|
requireAuth: typeof requireAuth;
|
|
@@ -17,6 +17,7 @@ export interface ResolveProvisioningDeps {
|
|
|
17
17
|
pickProject: typeof pickProject;
|
|
18
18
|
pickNewProjectName: typeof pickNewProjectName;
|
|
19
19
|
assertNewProjectNameAvailable: typeof assertNewProjectNameAvailable;
|
|
20
|
+
resolveProjectByNameOrId: typeof resolveProjectByNameOrId;
|
|
20
21
|
}
|
|
21
22
|
export interface ResolveProvisioningOptions {
|
|
22
23
|
/** Resolves the provisioning-tree questions; the composed stack decides how. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{select,text}from"../ask.js";import{detectProjectResolution,isProjectResolved,mergeProjectResolution}from"../project-resolution.js";import{withSpinner}from"../with-spinner.js";import{assertNewProjectNameAvailable,isVercelAuthenticated,pickNewProjectName,pickProject,pickTeam,requireAuth,resolveTeam,validateTeam}from"../vercel-project.js";import{pathExists}from"../path-exists.js";import{join,resolve}from"node:path";import{byokProviderEnvVar}from"#setup/scaffold/index.js";import{whimsyFor}from"#setup/cli/index.js";function vercelDemands(e){return{slack:e.channelSelection.includes(`slack`),connectSlugs:e.connectionSelection.filter(e=>e.entry.auth?.kind===`connect`).map(e=>e.slug)}}function connectClause(e){let t=e.length===1?`authenticates`:`authenticate`;return`${e.join(`, `)} ${t} through Vercel Connect`}function vercelRequirements(e){let t=[];return e.slack&&t.push(`Slack needs a public URL`),e.connectSlugs.length>0&&t.push(connectClause(e.connectSlugs)),t}function resolveProvisioning(l){let u=l.deps??{requireAuth,isVercelAuthenticated,detectProjectResolution,pathExists,validateTeam,resolveTeam,pickTeam,pickProject,pickNewProjectName,assertNewProjectNameAvailable},parent=()=>resolve(l.targetDirectory??process.cwd());async function detectAdoptableLink(e,t){if(e.projectPath.kind!==`resolved`)return;let n=e.projectPath.path;if(await u.pathExists(join(n,`.vercel`,`project.json`)))return withSpinner(l.prompter,whimsyFor(`project-detect`),async()=>{let e=await u.detectProjectResolution(n,{signal:t});if(!(!isProjectResolved(e)||!await u.isVercelAuthenticated(n,{signal:t})))return e})}async function plansFromFlags(e,t,n,r){if(t.skipVercel)return n.apiKey===void 0?{vercelProject:{kind:`none`},aiGateway:{kind:`byop`},modelWiring:`self`}:{vercelProject:{kind:`none`},aiGateway:{kind:`byok`,apiGatewayKey:n.apiKey},modelWiring:`gateway`};if(t.team===void 0||t.team.length===0)throw Error(`Headless Vercel provisioning requires --team <slug> or --scope <slug> so the current CLI scope is not applied silently.`);await u.requireAuth(parent(),void 0,{signal:r}),await u.validateTeam(l.prompter,parent(),t.team,{signal:r});let i=await u.resolveTeam(parent(),t.team,{signal:r}),a=n.apiKey===void 0?{kind:`inherit`}:{kind:`byok`,apiGatewayKey:n.apiKey},o
|
|
1
|
+
import{select,text}from"../ask.js";import{detectProjectResolution,isProjectResolved,mergeProjectResolution}from"../project-resolution.js";import{withSpinner}from"../with-spinner.js";import{assertNewProjectNameAvailable,isVercelAuthenticated,pickNewProjectName,pickProject,pickTeam,requireAuth,resolveProjectByNameOrId,resolveTeam,validateTeam}from"../vercel-project.js";import{pathExists}from"../path-exists.js";import{join,resolve}from"node:path";import{byokProviderEnvVar}from"#setup/scaffold/index.js";import{whimsyFor}from"#setup/cli/index.js";function vercelDemands(e){return{slack:e.channelSelection.includes(`slack`),connectSlugs:e.connectionSelection.filter(e=>e.entry.auth?.kind===`connect`).map(e=>e.slug)}}function connectClause(e){let t=e.length===1?`authenticates`:`authenticate`;return`${e.join(`, `)} ${t} through Vercel Connect`}function vercelRequirements(e){let t=[];return e.slack&&t.push(`Slack needs a public URL`),e.connectSlugs.length>0&&t.push(connectClause(e.connectSlugs)),t}function resolveProvisioning(l){let u=l.deps??{requireAuth,isVercelAuthenticated,detectProjectResolution,pathExists,validateTeam,resolveTeam,pickTeam,pickProject,pickNewProjectName,assertNewProjectNameAvailable,resolveProjectByNameOrId},parent=()=>resolve(l.targetDirectory??process.cwd());async function detectAdoptableLink(e,t){if(e.projectPath.kind!==`resolved`)return;let n=e.projectPath.path;if(await u.pathExists(join(n,`.vercel`,`project.json`)))return withSpinner(l.prompter,whimsyFor(`project-detect`),async()=>{let e=await u.detectProjectResolution(n,{signal:t});if(!(!isProjectResolved(e)||!await u.isVercelAuthenticated(n,{signal:t})))return e})}async function plansFromFlags(e,t,n,r){if(t.skipVercel)return n.apiKey===void 0?{vercelProject:{kind:`none`},aiGateway:{kind:`byop`},modelWiring:`self`}:{vercelProject:{kind:`none`},aiGateway:{kind:`byok`,apiGatewayKey:n.apiKey},modelWiring:`gateway`};if(t.team===void 0||t.team.length===0)throw Error(`Headless Vercel provisioning requires --team <slug> or --scope <slug> so the current CLI scope is not applied silently.`);await u.requireAuth(parent(),void 0,{signal:r}),await u.validateTeam(l.prompter,parent(),t.team,{signal:r});let i=await u.resolveTeam(parent(),t.team,{signal:r}),a=n.apiKey===void 0?{kind:`inherit`}:{kind:`byok`,apiGatewayKey:n.apiKey},o;if(t.project===void 0)o={kind:`new`,project:e,team:i};else{let e=await u.resolveProjectByNameOrId(parent(),i,t.project,{signal:r});if(e===null)throw Error(`Vercel project "${t.project}" was not found in ${i}.`);o={kind:`existing`,project:e,team:i}}return o.kind===`new`&&await u.assertNewProjectNameAvailable(parent(),i,o.project,{signal:r}),{vercelProject:o,aiGateway:a,modelWiring:`gateway`}}async function promptPlans(n,r){let i=l.prompter,a=n.agentName,o=l.adoptExistingLink===!1?void 0:await detectAdoptableLink(n,r);if(o!==void 0)return i.log.info(`This directory is already linked to a Vercel project, so your agent will run there — the AI Gateway authenticates through your Vercel login.`),{vercelProject:{kind:`none`},aiGateway:{kind:`inherit`},modelWiring:`gateway`,project:o};let s=vercelRequirements(vercelDemands(n)),c=!0;if(s.length>0?i.log.info(`${s.join(` and `)}, so your agent will run on Vercel.`):c=await l.asker.ask(select({key:`deploy`,message:`Where should your agent run?`,options:[{id:`vercel`,value:!0,label:`On Vercel`,hint:`AI Gateway, Durable Workflow, Sandbox, and more`},{id:`local`,value:!1,label:`Locally for now`,hint:`run with eve dev, deploy any time later`}],recommended:!0,required:!0})),c){await u.requireAuth(parent(),i,{signal:r});let t=await u.pickTeam(i,parent(),void 0,{signal:r}),n=[{value:`new`,label:`Create a new project`,hint:`Named ${a}`},{value:`link`,label:`Link an existing project`}],o=l.projectSelection!==`existing-only`&&l.prompter.selectEditable?await l.prompter.selectEditable({message:`Vercel project`,options:n,initialValue:`new`,editable:{value:`new`,defaultValue:a,formatHint:e=>`Named ${e}`,validate:e=>e.trim().length===0?`Project name cannot be empty.`:void 0}}):void 0;if((l.projectSelection===`existing-only`?`link`:o?.value??await l.asker.ask(select({key:`vercel-project`,message:`Vercel project`,options:[{id:`new`,value:`new`,label:`Create a new project`,hint:`Named ${a}`},{id:`link`,value:`link`,label:`Link an existing project`}],recommended:`new`,required:!0})))===`new`){let e=o?.kind===`edited`?o.text:a;return{vercelProject:{kind:`new`,project:await u.pickNewProjectName(i,parent(),t,e,{signal:r}),team:t},aiGateway:{kind:`inherit`},modelWiring:`gateway`}}return{vercelProject:await u.pickProject(i,parent(),t,{allowCreateWhenEmpty:l.projectSelection!==`existing-only`,signal:r}),aiGateway:{kind:`inherit`},modelWiring:`gateway`}}return await l.asker.ask(select({key:`credential`,message:`How should your agent reach the model?`,options:[{id:`api-key`,value:`api-key`,label:`Use my own AI Gateway API key`,hint:`AI_GATEWAY_API_KEY`},{id:`local`,value:`local`,label:`Use my own provider API key`,hint:byokProviderEnvVar(n.modelId)}],recommended:`api-key`,required:!0}))===`api-key`?{vercelProject:{kind:`none`},aiGateway:{kind:`byok`,apiGatewayKey:await l.asker.ask(text({key:`gateway-api-key`,message:`Enter your AI_GATEWAY_API_KEY`,sensitive:!0,validate:e=>e.trim().length===0?`API key cannot be empty.`:null,required:!0}))},modelWiring:`gateway`}:{vercelProject:{kind:`none`},aiGateway:{kind:`byop`},modelWiring:`self`}}return{id:`resolve-provisioning`,async gather({state:e,signal:t}){if(l.mode.headless){let n=await plansFromFlags(e.agentName,l.mode.project,l.mode.aiGateway,t);if(n.vercelProject.kind===`none`){let t=vercelDemands(e);if(t.slack)throw Error(`Slack requires a Vercel project. Remove --skip-vercel to add Slack.`);if(t.connectSlugs.length>0)throw Error(`${connectClause(t.connectSlugs)}, which needs a Vercel project. Remove --skip-vercel to add ${t.connectSlugs.length===1?`it`:`them`}.`)}return n}return promptPlans(e,t)},async perform({input:e}){return e},apply(e,t){return{...e,vercelProject:t.vercelProject,aiGateway:t.aiGateway,modelWiring:t.modelWiring,project:t.project===void 0?e.project:mergeProjectResolution(e.project,t.project)}}}}export{resolveProvisioning};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Prompt } from "@clack/core";
|
|
2
2
|
import { type PromptOption, type PromptValue } from "./prompt-ui.js";
|
|
3
|
-
import { type SelectState } from "./select-state.js";
|
|
3
|
+
import { type SearchActionOption, type SelectState } from "./select-state.js";
|
|
4
4
|
/**
|
|
5
5
|
* A prompt's live status note (e.g. a two-stage quit guard), read on each
|
|
6
6
|
* render. Returns `undefined` when there is nothing to show. Wired in by
|
|
@@ -20,6 +20,7 @@ export declare class SelectComponent extends Prompt<string | string[]> {
|
|
|
20
20
|
readonly options: PromptOption<string>[];
|
|
21
21
|
readonly multiple: boolean;
|
|
22
22
|
readonly search: boolean;
|
|
23
|
+
readonly searchAction: SearchActionOption | undefined;
|
|
23
24
|
readonly required: boolean;
|
|
24
25
|
filter: string;
|
|
25
26
|
optionCursor: number;
|
|
@@ -28,6 +29,7 @@ export declare class SelectComponent extends Prompt<string | string[]> {
|
|
|
28
29
|
options: PromptOption<string>[];
|
|
29
30
|
multiple: boolean;
|
|
30
31
|
search: boolean;
|
|
32
|
+
searchAction?: SearchActionOption;
|
|
31
33
|
required: boolean;
|
|
32
34
|
initial: SelectState;
|
|
33
35
|
render: (this: Omit<SelectComponent, "prompt">) => string | undefined;
|
|
@@ -74,6 +76,10 @@ export declare function runSelectComponent<T extends PromptValue>(input: {
|
|
|
74
76
|
options: readonly PromptOption<T>[];
|
|
75
77
|
multiple: boolean;
|
|
76
78
|
search: boolean;
|
|
79
|
+
searchAction?: {
|
|
80
|
+
label(query: string): string;
|
|
81
|
+
value(query: string): T;
|
|
82
|
+
};
|
|
77
83
|
required: boolean;
|
|
78
84
|
placeholder?: string;
|
|
79
85
|
defaultValue?: T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{m,q}from"../../node_modules/.pnpm/@clack_core@1.3.1/node_modules/@clack/core/dist/index.js";import{renderMultiselectPrompt,renderSearchableSelect,renderSelectPrompt}from"./prompt-ui.js";import{createSelectOptionCodec}from"./select-option-codec.js";import{filterOptions,initialSelectState,orderedSelection,reduceSelect,selectValueAtCursor,submitRowIndex}from"./select-state.js";var import_picocolors=__toESM(require_picocolors(),1);function toPromptState(e){return e}var SelectComponent=class extends m{options;multiple;search;required;filter=``;optionCursor=0;selectedSet=new Set;constructor(e){super({render:e.render,validate:()=>this.submitError()},!1),this.options=e.options,this.multiple=e.multiple,this.search=e.search,this.required=e.required,this.filter=e.initial.filter,this.optionCursor=e.initial.cursor,this.selectedSet=e.initial.selected,this.refreshValue(),this.on(`key`,(e,t)=>{if(this.multiple&&t?.name===`space`){this.apply({type:`toggle`});return}if(this.search){if(t?.name===`backspace`||e===``||e===`\b`){this.apply({type:`backspace`});return}e!==void 0&&e.length===1&&e>=` `&&e!==``&&this.apply({type:`char`,char:e})}}),this.on(`cursor`,e=>{e===`up`||e===`left`?this.apply({type:`up`}):(e===`down`||e===`right`)&&this.apply({type:`down`})})}visibleOptions(){return filterOptions(this.options,this.filter)}onSubmitRow(){return this.multiple&&this.optionCursor===submitRowIndex(this.visibleOptions())}submitLabel(){if(this.required)return`Submit`;let e=new Set(this.options.filter(e=>e.locked).map(e=>e.value));return[...this.selectedSet].some(t=>!e.has(t))?`Submit`:`Skip`}_shouldSubmit(){return this.multiple?this.onSubmitRow()?!0:(this.apply({type:`toggle`}),!1):this.visibleOptions()[this.optionCursor]?.completed!==!0}selectedValues(){if(this.multiple)return orderedSelection(this.options,this.selectedSet);let e=selectValueAtCursor(this.visibleOptions(),this.optionCursor);return e===void 0?[]:[e]}submitDisplay(){if(this.multiple){let e=this.options.filter(e=>this.selectedSet.has(e.value)).map(e=>e.label);return e.length>0?e.join(`, `):import_picocolors.default.dim(`(none selected)`)}let e=selectValueAtCursor(this.visibleOptions(),this.optionCursor);return e===void 0?``:this.labelForValue(e)}labelForValue(e){return this.options.find(t=>t.value===e)?.label??e}submitError(){return this.multiple?this.required&&this.selectedSet.size===0?`Select at least one option, then press enter.`:void 0:selectValueAtCursor(this.visibleOptions(),this.optionCursor)===void 0?`Type to match an option, then press enter.`:void 0}apply(e){let t=reduceSelect({filter:this.filter,cursor:this.optionCursor,selected:this.selectedSet},e,{options:this.options,submitRow:this.multiple});this.filter=t.filter,this.optionCursor=t.cursor,this.selectedSet=t.selected,this.refreshValue()}refreshValue(){this.value=this.multiple?orderedSelection(this.options,this.selectedSet):selectValueAtCursor(this.visibleOptions(),this.optionCursor)}};function renderSelectComponent(e,t,n,r){let s=toPromptState(e.state);return e.search?renderSearchableSelect({colors:import_picocolors.default,state:s,leadingRail:n,message:t.message,multiple:e.multiple,filter:e.filter,placeholder:t.placeholder,options:e.visibleOptions(),cursor:e.optionCursor,selectedValues:e.selectedValues(),submitDisplay:e.submitDisplay(),footerNote:r,error:e.error,submitLabel:e.submitLabel()}):e.multiple?renderMultiselectPrompt({colors:import_picocolors.default,cursor:e.optionCursor,error:e.error,footerNote:r,leadingRail:n,message:t.message,options:e.options,selectedValues:e.selectedValues(),state:s,submitLabel:e.submitLabel()}):renderSelectPrompt({colors:import_picocolors.default,cursor:e.optionCursor,footerNote:r,leadingRail:n,message:t.message,options:e.options,state:s})}async function runSelectComponent(e){let t=createSelectOptionCodec(e.options),n=initialSelectState({options:t.options,defaultValue:e.defaultValue===void 0?void 0:t.encode(e.defaultValue),initialValues:e.initialValues?.map(e=>t.encode(e)),submitRow:e.multiple}),i,a,o=new SelectComponent({options:t.options,multiple:e.multiple,search:e.search,required:e.required,initial:n,render(){return i?renderSelectComponent(i,{message:e.message,placeholder:e.placeholder},e.leadingRail,a?.note()):``}});i=o,a=e.attachGuard?.(o);let c=await o.prompt();if(q(c))return c;if(c===void 0)throw Error(`Select prompt returned no value.`);
|
|
1
|
+
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{m,q}from"../../node_modules/.pnpm/@clack_core@1.3.1/node_modules/@clack/core/dist/index.js";import{renderMultiselectPrompt,renderSearchableSelect,renderSelectPrompt}from"./prompt-ui.js";import{createSelectOptionCodec}from"./select-option-codec.js";import{filterOptions,initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor,submitRowIndex}from"./select-state.js";var import_picocolors=__toESM(require_picocolors(),1);function toPromptState(e){return e}var SelectComponent=class extends m{options;multiple;search;searchAction;required;filter=``;optionCursor=0;selectedSet=new Set;constructor(e){super({render:e.render,validate:()=>this.submitError()},!1),this.options=e.options,this.multiple=e.multiple,this.search=e.search,this.searchAction=e.searchAction,this.required=e.required,this.filter=e.initial.filter,this.optionCursor=e.initial.cursor,this.selectedSet=e.initial.selected,this.refreshValue(),this.on(`key`,(e,t)=>{if(this.multiple&&t?.name===`space`){this.apply({type:`toggle`});return}if(this.search){if(t?.name===`backspace`||e===``||e===`\b`){this.apply({type:`backspace`});return}e!==void 0&&e.length===1&&e>=` `&&e!==``&&this.apply({type:`char`,char:e})}}),this.on(`cursor`,e=>{e===`up`||e===`left`?this.apply({type:`up`}):(e===`down`||e===`right`)&&this.apply({type:`down`})})}visibleOptions(){return filterOptions(this.options,this.filter,this.searchAction)}onSubmitRow(){return this.multiple&&this.optionCursor===submitRowIndex(this.visibleOptions())}submitLabel(){if(this.required)return`Submit`;let e=new Set(this.options.filter(e=>e.locked).map(e=>e.value));return[...this.selectedSet].some(t=>!e.has(t))?`Submit`:`Skip`}_shouldSubmit(){return this.multiple?this.onSubmitRow()?!0:(this.apply({type:`toggle`}),!1):this.visibleOptions()[this.optionCursor]?.completed!==!0}selectedValues(){if(this.multiple)return orderedSelection(this.options,this.selectedSet);let e=selectValueAtCursor(this.visibleOptions(),this.optionCursor);return e===void 0?[]:[e]}submitDisplay(){if(this.multiple){let e=this.options.filter(e=>this.selectedSet.has(e.value)).map(e=>e.label);return e.length>0?e.join(`, `):import_picocolors.default.dim(`(none selected)`)}let e=selectValueAtCursor(this.visibleOptions(),this.optionCursor);return e===void 0?``:this.labelForValue(e)}labelForValue(e){let t=searchActionQuery(e);return t!==void 0&&this.searchAction!==void 0?this.searchAction.label(t):this.options.find(t=>t.value===e)?.label??e}submitError(){return this.multiple?this.required&&this.selectedSet.size===0?`Select at least one option, then press enter.`:void 0:selectValueAtCursor(this.visibleOptions(),this.optionCursor)===void 0?`Type to match an option, then press enter.`:void 0}apply(e){let t=reduceSelect({filter:this.filter,cursor:this.optionCursor,selected:this.selectedSet},e,{options:this.options,searchAction:this.searchAction,submitRow:this.multiple});this.filter=t.filter,this.optionCursor=t.cursor,this.selectedSet=t.selected,this.refreshValue()}refreshValue(){this.value=this.multiple?orderedSelection(this.options,this.selectedSet):selectValueAtCursor(this.visibleOptions(),this.optionCursor)}};function renderSelectComponent(e,t,n,r){let s=toPromptState(e.state);return e.search?renderSearchableSelect({colors:import_picocolors.default,state:s,leadingRail:n,message:t.message,multiple:e.multiple,filter:e.filter,placeholder:t.placeholder,options:e.visibleOptions(),cursor:e.optionCursor,selectedValues:e.selectedValues(),submitDisplay:e.submitDisplay(),footerNote:r,error:e.error,submitLabel:e.submitLabel()}):e.multiple?renderMultiselectPrompt({colors:import_picocolors.default,cursor:e.optionCursor,error:e.error,footerNote:r,leadingRail:n,message:t.message,options:e.options,selectedValues:e.selectedValues(),state:s,submitLabel:e.submitLabel()}):renderSelectPrompt({colors:import_picocolors.default,cursor:e.optionCursor,footerNote:r,leadingRail:n,message:t.message,options:e.options,state:s})}async function runSelectComponent(e){let t=createSelectOptionCodec(e.options),n=initialSelectState({options:t.options,defaultValue:e.defaultValue===void 0?void 0:t.encode(e.defaultValue),initialValues:e.initialValues?.map(e=>t.encode(e)),submitRow:e.multiple}),i,a,o=new SelectComponent({options:t.options,multiple:e.multiple,search:e.search,searchAction:e.searchAction===void 0?void 0:{label:e.searchAction.label},required:e.required,initial:n,render(){return i?renderSelectComponent(i,{message:e.message,placeholder:e.placeholder},e.leadingRail,a?.note()):``}});i=o,a=e.attachGuard?.(o);let c=await o.prompt();if(q(c))return c;if(c===void 0)throw Error(`Select prompt returned no value.`);if(Array.isArray(c))return c.map(e=>t.decode(e));let l=searchActionQuery(c);return l!==void 0&&e.searchAction!==void 0?e.searchAction.value(l):t.decode(c)}export{SelectComponent,runSelectComponent};
|
|
@@ -2,6 +2,7 @@ import type { PromptOption, PromptValue } from "./prompt-ui.js";
|
|
|
2
2
|
export interface SelectOptionCodec<T extends PromptValue> {
|
|
3
3
|
readonly options: PromptOption<string>[];
|
|
4
4
|
encode(value: T): string;
|
|
5
|
+
encodeOptions(options: readonly PromptOption<T>[]): PromptOption<string>[];
|
|
5
6
|
decode(key: string): T;
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function createSelectOptionCodec(e){let t=new Map,n=new Map;return
|
|
1
|
+
function createSelectOptionCodec(e){let t=new Map,n=new Map,r=0,encodeOptions=e=>{let i=new Set;return e.map((e,a)=>{if(i.has(e.value))throw Error(`Select option values must be unique; duplicate at index ${a}.`);i.add(e.value);let o=n.get(e.value);return o===void 0&&(o=`option-${r}`,r+=1,n.set(e.value,o),t.set(o,e.value)),{...e,value:o}})};return{options:encodeOptions(e),encode(e){let t=n.get(e);if(t===void 0)throw Error(`Select initial value does not match an option.`);return t},encodeOptions,decode(e){let n=t.get(e);if(n===void 0)throw Error(`Select returned an unknown option key: ${e}`);return n}}}export{createSelectOptionCodec};
|