eve 0.64.0 → 0.64.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 +12 -0
- package/dist/src/cli/commands/registry-pnpm-build-policy-flow.d.ts +1 -1
- package/dist/src/cli/commands/registry-pnpm-build-policy-flow.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +0 -1
- package/dist/src/cli/dev/tui/runner.js +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +0 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
- package/dist/src/execution/sandbox/development-lazy-prewarm.d.ts +7 -0
- package/dist/src/execution/sandbox/development-lazy-prewarm.js +1 -0
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/sandbox/prewarm.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/internal/application/compiled-artifacts.js +1 -1
- package/dist/src/internal/application/optional-package-install.d.ts +3 -0
- package/dist/src/internal/application/optional-package-install.js +2 -2
- package/dist/src/internal/application/output-publication-lock.d.ts +6 -0
- package/dist/src/internal/application/output-publication-lock.js +1 -1
- package/dist/src/internal/application/output-publication.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +1 -0
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-runtime-modules.d.ts +1 -0
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
- package/dist/src/internal/nitro/host/development-runtime-prune-plugin.d.ts +9 -0
- package/dist/src/internal/nitro/host/development-runtime-prune-plugin.js +2 -0
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/public/next/vercel-output-config.js +1 -1
- package/dist/src/runtime/cache-key.js +1 -1
- package/dist/src/runtime/sandbox/prepared-artifacts.js +1 -1
- package/dist/src/{cli/commands/registry-pnpm-build-policy.d.ts → setup/primitives/pm/pnpm-build-policy.d.ts} +4 -0
- package/dist/src/setup/primitives/pm/pnpm-build-policy.js +8 -0
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/sandbox-provider.d.ts +2 -0
- package/docs/channels/slack.mdx +1 -1
- package/docs/guides/deployment/vercel.mdx +0 -6
- package/docs/guides/instrumentation/instrumentation.mdx +1 -1
- package/docs/guides/instrumentation/migration.md +1 -6
- package/docs/guides/instrumentation/otel.mdx +15 -47
- package/docs/reference/typescript-api.md +2 -2
- package/docs/sandbox/index.mdx +3 -1
- package/docs/sandbox/just-bash.mdx +6 -0
- package/package.json +1 -1
- package/dist/src/cli/commands/registry-pnpm-build-policy.js +0 -6
- package/dist/src/execution/sandbox/development-prewarm.d.ts +0 -20
- package/dist/src/execution/sandbox/development-prewarm.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TaskDeliveryPolicyKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import*as activityCohort from"#execution/activity-cohort.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createSessionEventSink}from"#execution/session/event-sink.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{getBackgroundTaskDelivery,markBackgroundTaskStepInput,resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return runSessionStep(e)}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState),a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a),l=t?.taskDeliveryPolicy??a.get(TaskDeliveryPolicyKey)??`auto`;a.set(TaskDeliveryPolicyKey,l);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let u=getPendingAuthorization(i.state),d;if(u&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,n.payloads);if(n={...n,payloads:t},e.length>0){let r=activityCohort.restoreAuthorizationActivity({ctx:a,matches:e,pending:u}),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},d=e,t.length===0&&(n=void 0)}}let f=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=getBackgroundTaskDelivery(n),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=createSessionEventSink({abortSignal:e.abortSignal,adapter:o,bundle:s,ctx:a,effectiveAgent:c,instrumentation:g,isFirstTurn:_.sequence===0,sessionWritable:e.sessionWritable,sessionId:m.sessionId}),{adapterCtx:y,dynamicConnections:b,effectiveNode:x,handleEvent:S}=v;try{let C=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,w;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(p===void 0?n:markBackgroundTaskStepInput(n))}}catch(e){throw await failChannelDeliveries(e),e}w=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let T=n!==void 0&&w===void 0&&!isHarnessBetweenTurns(m);if(T)f===void 0?a.delete(AuthKey):a.set(AuthKey,f),y.state=C;else if(t!==void 0&&a.set(TurnTaskDeliveryKey,`none`),t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),w={...w,runtimeActionResults:r.results});let E;if(w!==void 0&&p!==void 0){let e=resolveTaskDeliveryContext({state:i.state,taskDeliveryIds:p.taskDeliveryIds??[p.taskDeliveryId],taskDeliveryPolicy:l});e!==void 0&&(a.set(TurnTaskDeliveryKey,e.phase),E=e.rootTurnId,w={...w,context:[...w.context??[],e.context]})}activityCohort.updateActivityRootForDelivery({activeTurnId:activeTurnId(_),ctx:a,delivery:T?void 0:t,sessionState:i.state,taskRootTurnId:E});let D=a.get(TurnTaskDeliveryKey);if(D===`none`||D===`initiating`){let e=resolveInitiatingTaskContext({state:i.state,turnId:activeTurnId(_)});e!==void 0&&a.set(TurnTaskDeliveryKey,e.phase)}if(t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&w===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let O=s.subagentRegistry.dynamicResolvers??[],k=s.resolvedAgent.dynamicToolResolvers??[],A=buildRuntimeIdentity(x);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:A});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:k,event:e,messages:h.initial.messages,runtimeRevision:t})]),await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:k})}}catch(e){throw await failChannelDeliveries(e),e}let j=a.require(ModeKey),M=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,N=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:N,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:S,historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,mode:j,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:x})(r,n)},P,F;try{throwIfTurnAborted(e.abortSignal),F=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:w,initialSession:m,modelCallsPerStep:M,runStep:async({firstCall:t,session:n,stepInput:r})=>{let i=await runBackgroundStep(a,n,async e=>{a.setVirtualContext(HandleEventKey,S),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let n=t?resolveEffectiveOutputSchema({agentOutputSchema:c.turnAgent.outputSchema,input:w,mode:j,session:e}):e;if(await b.rehydrate(getHarnessEmissionState(n.state),A,isHarnessBetweenTurns(n)),t&&d){let e=getHarnessEmissionState(n.state);if(isHarnessBetweenTurns(n)){let t=createTurnInputMessages(consumeDeferredStepInput({session:n,input:r}).input);prepareDynamicInstructionPreamble(a,h.messages(n)),prepareMemoryPreamble(a,{history:n.history,input:t,projector:h.projector,state:n.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(S,{},e,h.projector({messages:[...n.history,...t],state:n.state}),A,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);n={...n,history:validateHarnessModelMessages([...e?.history??n.history,...i]),state:e?.state??n.state}}n=setHarnessEmissionState(n,e)}for(let{authorization:t,result:n}of d){let r=u?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await S(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}return runHarnessStep(n,r)});return i.settledTurn===void 0&&throwIfTurnAborted(e.abortSignal),P={result:i,serializedContext:serializeContext(a)},i}})}catch(t){if(!isTurnCancellation(t)&&e.abortSignal?.aborted!==!0)throw await failChannelDeliveries(t),t;let n=readRetainedBackgroundToolResult(a);return g?.rememberBackgroundTasks(n?.backgroundTasks??[]),createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:P,ctx:a,initialSession:m,stepInput:w})}g?.rememberBackgroundTasks(F.backgroundTasks??[]);let I=reconcileSessionContinuationToken(a,F.session);agentTraceState.pruneAgentTraceState(a,I.sessionId,I.state);let L=serializeContext(a);F={...F,session:I};let R=resolveSessionStepResult(F,L,j,e.serializedContext);return R.action===`done`&&await v.close(),R}finally{v.release()}}export{turnStep};
|
|
1
|
+
import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TaskDeliveryPolicyKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import*as activityCohort from"#execution/activity-cohort.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createSessionEventSink}from"#execution/session/event-sink.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{getBackgroundTaskDelivery,markBackgroundTaskStepInput,resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return runSessionStep(e)}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState),a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a),l=t?.taskDeliveryPolicy??a.get(TaskDeliveryPolicyKey)??`auto`;a.set(TaskDeliveryPolicyKey,l);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let u=getPendingAuthorization(i.state),d;if(u&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,n.payloads);if(n={...n,payloads:t},e.length>0){let r=activityCohort.restoreAuthorizationActivity({ctx:a,matches:e,pending:u}),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},d=e,t.length===0&&(n=void 0)}}let f=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=getBackgroundTaskDelivery(n),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=createSessionEventSink({abortSignal:e.abortSignal,adapter:o,bundle:s,ctx:a,effectiveAgent:c,instrumentation:g,isFirstTurn:_.sequence===0,sessionWritable:e.sessionWritable,sessionId:m.sessionId}),{adapterCtx:y,dynamicConnections:b,effectiveNode:x,handleEvent:S}=v;try{let C=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,w;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(p===void 0?n:markBackgroundTaskStepInput(n))}}catch(e){throw await failChannelDeliveries(e),e}w=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let T=n!==void 0&&w===void 0&&!isHarnessBetweenTurns(m);if(T)f===void 0?a.delete(AuthKey):a.set(AuthKey,f),y.state=C;else if(t!==void 0&&a.set(TurnTaskDeliveryKey,`none`),t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),w={...w,runtimeActionResults:r.results});let E;if(w!==void 0&&p!==void 0){let e=resolveTaskDeliveryContext({state:i.state,taskDeliveryIds:p.taskDeliveryIds??[p.taskDeliveryId],taskDeliveryPolicy:l});e!==void 0&&(a.set(TurnTaskDeliveryKey,e.phase),E=e.rootTurnId,w={...w,context:[...w.context??[],e.context]})}activityCohort.updateActivityRootForDelivery({activeTurnId:activeTurnId(_),ctx:a,delivery:T?void 0:t,sessionState:i.state,taskRootTurnId:E});let D=a.get(TurnTaskDeliveryKey);if(D===`none`||D===`initiating`){let e=resolveInitiatingTaskContext({state:i.state,turnId:activeTurnId(_)});e!==void 0&&a.set(TurnTaskDeliveryKey,e.phase)}if(t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&w===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let O=s.subagentRegistry.dynamicResolvers??[],k=s.resolvedAgent.dynamicToolResolvers??[],A=buildRuntimeIdentity(x);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:A});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:k,event:e,messages:h.initial.messages,runtimeRevision:t}))]),await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:k})}}catch(e){throw await failChannelDeliveries(e),e}let j=a.require(ModeKey),M=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,N=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:N,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:S,historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,mode:j,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:x})(r,n)},P,F;try{throwIfTurnAborted(e.abortSignal),F=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:w,initialSession:m,modelCallsPerStep:M,runStep:async({firstCall:t,session:n,stepInput:r})=>{let i=await runBackgroundStep(a,n,async e=>{a.setVirtualContext(HandleEventKey,S),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let n=t?resolveEffectiveOutputSchema({agentOutputSchema:c.turnAgent.outputSchema,input:w,mode:j,session:e}):e;if(await b.rehydrate(getHarnessEmissionState(n.state),A,isHarnessBetweenTurns(n)),t&&d){let e=getHarnessEmissionState(n.state);if(isHarnessBetweenTurns(n)){let t=createTurnInputMessages(consumeDeferredStepInput({session:n,input:r}).input);prepareDynamicInstructionPreamble(a,h.messages(n)),prepareMemoryPreamble(a,{history:n.history,input:t,projector:h.projector,state:n.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(S,{},e,h.projector({messages:[...n.history,...t],state:n.state}),A,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);n={...n,history:validateHarnessModelMessages([...e?.history??n.history,...i]),state:e?.state??n.state}}n=setHarnessEmissionState(n,e)}for(let{authorization:t,result:n}of d){let r=u?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await S(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}return runHarnessStep(n,r)});return i.settledTurn===void 0&&throwIfTurnAborted(e.abortSignal),P={result:i,serializedContext:serializeContext(a)},i}})}catch(t){if(!isTurnCancellation(t)&&e.abortSignal?.aborted!==!0)throw await failChannelDeliveries(t),t;let n=readRetainedBackgroundToolResult(a);return g?.rememberBackgroundTasks(n?.backgroundTasks??[]),createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:P,ctx:a,initialSession:m,stepInput:w})}g?.rememberBackgroundTasks(F.backgroundTasks??[]);let I=reconcileSessionContinuationToken(a,F.session);agentTraceState.pruneAgentTraceState(a,I.sessionId,I.state);let L=serializeContext(a);F={...F,session:I};let R=resolveSessionStepResult(F,L,j,e.serializedContext);return R.action===`done`&&await v.close(),R}finally{v.release()}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.64.
|
|
1
|
+
import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.64.1//executeAgentRouterTool`;export{executeAgentRouterTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.64.
|
|
1
|
+
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.64.1//executeSleepTool`;export{executeSleepTool};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{buildPackageUserAgent}from"#internal/user-agent.js";import{sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import"#internal/instrumentation-layout.js";import{resolveWorkflowWorldImport}from"#internal/workflow/world-target.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-module-map.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),i=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),a=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(e.compileResult.paths.sandboxPreparedArtifactsPath,`utf8`))),o=await prepareAuthoredRuntimeModules({manifest:e.compileResult.manifest,moduleMapPath:e.compileResult.paths.moduleMapPath});await mkdir(e.outDir,{recursive:!0}),await writeFile(n,o.moduleMapCode),await writeFile(t,createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),metadata:e.compileResult.metadata,moduleMapImportPath:n,sandboxPreparedArtifacts:a})),await writeFile(i,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld}));let s={authoredWorkflowModules:o.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:i},c=await writePreparedInstrumentation({instrumentation:o.instrumentation,outDir:e.outDir});return await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:c})),s.instrumentationPluginPath=r,s.instrumentationLayout=generatedInstrumentationLayout(c),s.instrumentationSourcePaths=instrumentationSourcePathsOf(c),s}async function writePreparedInstrumentation(e){let writeOne=async(t,n)=>{let r=join(e.outDir,`compiled-artifacts-instrumentation-${t}.mjs`);return await writeFile(r,n),r},t={};for(let[n,r]of Object.entries(e.instrumentation.moduleCodeBySlot))t[n]=await writeOne(n,r);return{kind:`directory`,modulePathsBySlot:t}}function instrumentationSourcePathsOf(e){return Object.values(e.modulePathsBySlot)}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),i=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(i===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(r,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let a={authoredWorkflowModules:e.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:r};if(i.instrumentation!==void 0){let t=await copyMaterializedInstrumentation({instrumentation:i.instrumentation,outDir:e.outDir,runtimeAppRoot:e.runtimeAppRoot});await writeFile(n,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:t})),a.instrumentationPluginPath=n,a.instrumentationLayout=generatedInstrumentationLayout(t),a.instrumentationSourcePaths=instrumentationSourcePathsOf(t)}return a}function generatedInstrumentationLayout(e){return{kind:`directory`,slots:Object.keys(e.modulePathsBySlot)}}async function copyMaterializedInstrumentation(e){let t=join(e.runtimeAppRoot,`.eve`,`compile`),copyOne=async(n,r)=>{let i=join(e.outDir,`compiled-artifacts-instrumentation-${n}.mjs`);return await copyFile(join(t,r),i),i},n={};for(let[t,r]of Object.entries(e.instrumentation.modulePathsBySlot))n[t]=await copyOne(t,r);return{kind:`directory`,modulePathsBySlot:n}}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
|
|
1
|
+
import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{buildPackageUserAgent}from"#internal/user-agent.js";import{sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import"#internal/instrumentation-layout.js";import{resolveWorkflowWorldImport}from"#internal/workflow/world-target.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-module-map.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),i=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),a=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(e.compileResult.paths.sandboxPreparedArtifactsPath,`utf8`))),o=await prepareAuthoredRuntimeModules({appRoot:e.compileResult.project.appRoot,manifest:e.compileResult.manifest,moduleMapPath:e.compileResult.paths.moduleMapPath});await mkdir(e.outDir,{recursive:!0}),await writeFile(n,o.moduleMapCode),await writeFile(t,createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),metadata:e.compileResult.metadata,moduleMapImportPath:n,sandboxPreparedArtifacts:a})),await writeFile(i,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld}));let s={authoredWorkflowModules:o.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:i},c=await writePreparedInstrumentation({instrumentation:o.instrumentation,outDir:e.outDir});return await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:c})),s.instrumentationPluginPath=r,s.instrumentationLayout=generatedInstrumentationLayout(c),s.instrumentationSourcePaths=instrumentationSourcePathsOf(c),s}async function writePreparedInstrumentation(e){let writeOne=async(t,n)=>{let r=join(e.outDir,`compiled-artifacts-instrumentation-${t}.mjs`);return await writeFile(r,n),r},t={};for(let[n,r]of Object.entries(e.instrumentation.moduleCodeBySlot))t[n]=await writeOne(n,r);return{kind:`directory`,modulePathsBySlot:t}}function instrumentationSourcePathsOf(e){return Object.values(e.modulePathsBySlot)}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),i=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(i===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(r,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let a={authoredWorkflowModules:e.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:r};if(i.instrumentation!==void 0){let t=await copyMaterializedInstrumentation({instrumentation:i.instrumentation,outDir:e.outDir,runtimeAppRoot:e.runtimeAppRoot});await writeFile(n,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:t})),a.instrumentationPluginPath=n,a.instrumentationLayout=generatedInstrumentationLayout(t),a.instrumentationSourcePaths=instrumentationSourcePathsOf(t)}return a}function generatedInstrumentationLayout(e){return{kind:`directory`,slots:Object.keys(e.modulePathsBySlot)}}async function copyMaterializedInstrumentation(e){let t=join(e.runtimeAppRoot,`.eve`,`compile`),copyOne=async(n,r)=>{let i=join(e.outDir,`compiled-artifacts-instrumentation-${n}.mjs`);return await copyFile(join(t,r),i),i},n={};for(let[t,r]of Object.entries(e.instrumentation.modulePathsBySlot))n[t]=await copyOne(t,r);return{kind:`directory`,modulePathsBySlot:n}}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
|
|
2
2
|
`)}function createCompiledArtifactsBootstrapSource(e){let t=e.compileResult.manifest.config.name;return[`// Generated by eve. Do not edit by hand.`,`import moduleMap from ${stringifyEsmImportSpecifier(e.moduleMapImportPath)};`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(t)});`,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`const sandboxPreparedArtifacts = ${JSON.stringify(e.sandboxPreparedArtifacts,null,2)};`,``,`export { moduleMap };`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` sandboxPreparedArtifacts,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``].join(`
|
|
3
3
|
`)}function resolveWorkflowWorldWiring(e){if(e===`@workflow/world-local`){let t=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`)),n=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-delivery-timeouts.ts`));return{moduleImportSpecifier:resolvePackageCompiledFilePath(`src/compiled/${e}/index.js`),extraImportLines:`
|
|
4
4
|
import { applyLocalWorkflowWorldDeliveryTimeoutDefaults } from ${n};
|
|
@@ -16,6 +16,7 @@ export declare function detectProjectPackageManager(appRoot: string): ProjectPac
|
|
|
16
16
|
export declare function installPackageIntoProject(input: {
|
|
17
17
|
readonly appRoot: string;
|
|
18
18
|
readonly packageName: string;
|
|
19
|
+
readonly ignoredOptionalDependencies?: readonly string[];
|
|
19
20
|
}): Promise<void>;
|
|
20
21
|
/**
|
|
21
22
|
* Loads an optional engine package, auto-installing it into the
|
|
@@ -28,6 +29,8 @@ export declare function loadOptionalEnginePackage<T>(input: {
|
|
|
28
29
|
readonly autoInstall: boolean;
|
|
29
30
|
readonly importInstalledModule?: () => Promise<T>;
|
|
30
31
|
readonly importModule: () => Promise<T>;
|
|
32
|
+
readonly installPackageName?: string;
|
|
33
|
+
readonly ignoredOptionalDependencies?: readonly string[];
|
|
31
34
|
readonly missingMessage: string;
|
|
32
35
|
readonly packageName: string;
|
|
33
36
|
}): Promise<T>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir,readFile,rm,stat,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";import{existsSync}from"node:fs";import{spawn}from"node:child_process";import{pathToFileURL}from"node:url";import{EVE_DEV_ENV_FLAG,isEveDevEnvironment}from"#internal/application/dev-environment.js";import{Worker}from"node:worker_threads";function detectProjectPackageManager(e){let t=e;for(;;){if(existsSync(join(t,`pnpm-lock.yaml`))||existsSync(join(t,`pnpm-workspace.yaml`)))return`
|
|
1
|
+
import{mkdir,readFile,rm,stat,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{existsSync,realpathSync}from"node:fs";import{spawn}from"node:child_process";import{ensurePnpmOptionalDependencyDefaults}from"#setup/primitives/pm/pnpm-build-policy.js";import{pathToFileURL}from"node:url";import{EVE_DEV_ENV_FLAG,isEveDevEnvironment}from"#internal/application/dev-environment.js";import{Worker}from"node:worker_threads";function detectProjectPackageManager(e){return resolveProjectInstallation(e).packageManager}function resolveProjectInstallation(e){let t=resolve(e);try{t=realpathSync.native(t)}catch{}let n=t;for(;;){if(existsSync(join(t,`pnpm-lock.yaml`))||existsSync(join(t,`pnpm-workspace.yaml`)))return{root:t,packageManager:`pnpm`};if(existsSync(join(t,`yarn.lock`)))return{root:t,packageManager:`yarn`};if(existsSync(join(t,`bun.lock`))||existsSync(join(t,`bun.lockb`)))return{root:t,packageManager:`bun`};if(existsSync(join(t,`package-lock.json`)))return{root:t,packageManager:`npm`};let e=dirname(t);if(e===t)return{root:n,packageManager:`npm`};t=e}}const INSTALL_ARGUMENTS={bun:[`add`,`--dev`],npm:[`install`,`--save-dev`],pnpm:[`add`,`-D`],yarn:[`add`,`-D`]},OPTIONAL_PACKAGE_LOCK_TIMEOUT_MS=6e5,pendingOptionalPackageInstalls=new Map;async function installPackageIntoProject(e){let t=detectProjectPackageManager(e.appRoot);t===`pnpm`&&e.ignoredOptionalDependencies?.length&&await ensurePnpmOptionalDependencyDefaults(e.appRoot,e.ignoredOptionalDependencies);let n=[...INSTALL_ARGUMENTS[t],e.packageName];console.info(`[eve:dev] installing optional dependency "${e.packageName}" via \`${t} ${n.join(` `)}\`...`);let r=spawn(t,n,{cwd:e.appRoot,shell:shouldSpawnPackageManagerWithShell(),stdio:[`ignore`,`pipe`,`pipe`]}),i=[];r.stdout?.on(`data`,e=>i.push(e)),r.stderr?.on(`data`,e=>i.push(e));let a=await new Promise((e,t)=>{r.on(`error`,t),r.on(`close`,t=>e(t??1))});if(a!==0){let n=Buffer.concat(i).toString(`utf8`).trim();throw Error(`Failed to install "${e.packageName}" with ${t} (exit ${a}).`+(n.length>0?`\n${n.slice(-2e3)}`:``))}console.info(`[eve:dev] installed "${e.packageName}".`)}async function loadOptionalEnginePackage(e){try{return await e.importModule()}catch(t){if(!e.autoInstall||!isEveDevEnvironment())throw Error(e.missingMessage,{cause:t});let n=e.importInstalledModule??(async()=>await importInstalledEnginePackage({appRoot:e.appRoot,packageName:e.packageName})),r=e.importInstalledModule===void 0?async()=>await isInstalledEnginePackageLoadable(e):async()=>{try{return await n(),!0}catch{return!1}};try{await withOptionalPackageInstallLock(e,async()=>{await r()||await installPackageIntoProject({appRoot:e.appRoot,packageName:e.installPackageName??e.packageName,ignoredOptionalDependencies:e.ignoredOptionalDependencies})})}catch(t){throw Error(`${e.missingMessage} Automatic installation failed: ${toMessage(t)}`,{cause:t})}try{return await n()}catch(t){throw Error(`${e.missingMessage} Automatic installation completed, but "${e.packageName}" still could not be loaded from "${e.appRoot}". This usually means the package manager installed into a different workspace, node_modules is unavailable, or the Node/package-manager environment changed while eve dev was running. Last load error: ${toMessage(t)}`,{cause:t})}}}async function importInstalledEnginePackage(e){return await import(await resolveInstalledEnginePackageEntrypointHref(e))}async function isInstalledEnginePackageLoadable(e){try{return await importEntrypointInWorker(await resolveInstalledEnginePackageEntrypointHref(e)),!0}catch{return!1}}async function resolveInstalledEnginePackageEntrypointHref(e){let t=findInstalledPackageRoot(e),n=join(t,`package.json`),r=resolvePackageEntryPoint(JSON.parse(await readFile(n,`utf8`)));if(r.startsWith(`/`))throw Error(`Invalid absolute entrypoint for optional package "${e.packageName}".`);return pathToFileURL(join(t,r)).href}async function importEntrypointInWorker(e){let t=new Worker(`
|
|
2
2
|
const { parentPort, workerData } = require("node:worker_threads");
|
|
3
3
|
|
|
4
4
|
(async () => {
|
|
@@ -12,4 +12,4 @@ const { parentPort, workerData } = require("node:worker_threads");
|
|
|
12
12
|
});
|
|
13
13
|
}
|
|
14
14
|
})();
|
|
15
|
-
`,{eval:!0,workerData:{entrypointHref:e}});await new Promise((e,n)=>{let r=!1,settle=e=>{r||(r=!0,t.off(`error`,handleError),t.off(`exit`,handleExit),t.off(`message`,handleMessage),t.terminate().catch(()=>{}),e())},handleError=e=>settle(()=>n(e)),handleExit=e=>{e!==0&&settle(()=>n(Error(`Optional dependency worker exited before loading module (code ${e}).`)))},handleMessage=t=>{let r=t;settle(()=>{if(r.ok===!0){e();return}n(Error(typeof r.message==`string`?r.message:`Optional dependency worker failed to load module.`))})};t.once(`error`,handleError),t.once(`exit`,handleExit),t.once(`message`,handleMessage)})}function findInstalledPackageRoot(e){let t=e.packageName.split(`/`),n=[],r=e.appRoot;for(;;){let i=join(r,`node_modules`,...t);if(n.push(i),existsSync(join(i,`package.json`)))return i;let a=dirname(r);if(a===r)throw Error(`Could not find installed optional dependency "${e.packageName}". Checked: ${n.join(`, `)}`);r=a}}function resolvePackageEntryPoint(e){let t=readDotExport(e.exports);return t===void 0?typeof e.module==`string`&&e.module.length>0?e.module:typeof e.main==`string`&&e.main.length>0?e.main:`index.js`:t}function readDotExport(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e!=`object`||!e)return;let t=`.`in e?e[`.`]:e;if(typeof t==`string`&&t.length>0)return t;if(typeof t!=`object`||!t)return;let n=t;if(typeof n.import==`string`&&n.import.length>0)return n.import;if(typeof n.default==`string`&&n.default.length>0)return n.default}async function withOptionalPackageInstallLock(e,t){let n
|
|
15
|
+
`,{eval:!0,workerData:{entrypointHref:e}});await new Promise((e,n)=>{let r=!1,settle=e=>{r||(r=!0,t.off(`error`,handleError),t.off(`exit`,handleExit),t.off(`message`,handleMessage),t.terminate().catch(()=>{}),e())},handleError=e=>settle(()=>n(e)),handleExit=e=>{e!==0&&settle(()=>n(Error(`Optional dependency worker exited before loading module (code ${e}).`)))},handleMessage=t=>{let r=t;settle(()=>{if(r.ok===!0){e();return}n(Error(typeof r.message==`string`?r.message:`Optional dependency worker failed to load module.`))})};t.once(`error`,handleError),t.once(`exit`,handleExit),t.once(`message`,handleMessage)})}function findInstalledPackageRoot(e){let t=e.packageName.split(`/`),n=[],r=e.appRoot;for(;;){let i=join(r,`node_modules`,...t);if(n.push(i),existsSync(join(i,`package.json`)))return i;let a=dirname(r);if(a===r)throw Error(`Could not find installed optional dependency "${e.packageName}". Checked: ${n.join(`, `)}`);r=a}}function resolvePackageEntryPoint(e){let t=readDotExport(e.exports);return t===void 0?typeof e.module==`string`&&e.module.length>0?e.module:typeof e.main==`string`&&e.main.length>0?e.main:`index.js`:t}function readDotExport(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e!=`object`||!e)return;let t=`.`in e?e[`.`]:e;if(typeof t==`string`&&t.length>0)return t;if(typeof t!=`object`||!t)return;let n=t;if(typeof n.import==`string`&&n.import.length>0)return n.import;if(typeof n.default==`string`&&n.default.length>0)return n.default}async function withOptionalPackageInstallLock(e,t){let n=resolveProjectInstallation(e.appRoot).root,r=(pendingOptionalPackageInstalls.get(n)??Promise.resolve()).catch(()=>{}).then(()=>withOptionalPackageInstallFileLock(n,t));pendingOptionalPackageInstalls.set(n,r);try{await r}finally{pendingOptionalPackageInstalls.get(n)===r&&pendingOptionalPackageInstalls.delete(n)}}async function withOptionalPackageInstallFileLock(e,t){let n=join(e,`.eve`,`optional-package-install.lock`);await acquireLock(n);try{await t()}finally{await rm(n,{force:!0,recursive:!0}).catch(()=>{})}}async function acquireLock(e){let t=Date.now();for(;;){await mkdir(dirname(e),{recursive:!0});try{await mkdir(e),await writeFile(join(e,`owner.json`),`${JSON.stringify({createdAt:new Date().toISOString(),pid:process.pid})}\n`);return}catch(n){if(!isFileExistsError(n))throw n;await waitForExistingLock(e,t)}}}async function waitForExistingLock(e,t){let n=await stat(e).catch(e=>{if(isNotFoundError(e))return null;throw e});if(n!==null){if(Date.now()-n.mtimeMs>18e5){await rm(e,{force:!0,recursive:!0}).catch(()=>{});return}if(Date.now()-t>OPTIONAL_PACKAGE_LOCK_TIMEOUT_MS)throw Error(`Timed out waiting for optional package install lock "${e}" after ${OPTIONAL_PACKAGE_LOCK_TIMEOUT_MS}ms.`);await new Promise(e=>setTimeout(e,250))}}function shouldSpawnPackageManagerWithShell(e=process.platform){return e===`win32`}function isFileExistsError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`EEXIST`}function isNotFoundError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function toMessage(e){return e instanceof Error?e.message:String(e)}export{EVE_DEV_ENV_FLAG,detectProjectPackageManager,importInstalledEnginePackage,installPackageIntoProject,isEveDevEnvironment,loadOptionalEnginePackage};
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { type OutputPublicationJournal } from "#internal/application/output-publication-journal.js";
|
|
2
|
+
interface RecoveryLease {
|
|
3
|
+
complete(): Promise<void>;
|
|
4
|
+
release(): Promise<void>;
|
|
5
|
+
}
|
|
2
6
|
export declare function resolveOutputPublicationLockPath(appRoot: string): string;
|
|
3
7
|
/**
|
|
4
8
|
* Keeps a held lock's (or lease's) journal mtime fresh while its owner works.
|
|
@@ -8,3 +12,5 @@ export declare function resolveOutputPublicationLockPath(appRoot: string): strin
|
|
|
8
12
|
*/
|
|
9
13
|
export declare function startPublicationJournalHeartbeat(journalDirectoryPath: string): () => void;
|
|
10
14
|
export declare function acquireOutputPublicationLock(lockPath: string, journal: OutputPublicationJournal, onContention: () => Promise<void>): Promise<() => Promise<void>>;
|
|
15
|
+
export declare function acquireRecoveryLease(recoveryPath: string, token: string): Promise<RecoveryLease | undefined>;
|
|
16
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readdir,realpath,rm,stat,utimes}from"node:fs/promises";import{isErrnoCode}from"#shared/guards.js";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";import{watch}from"node:fs";import{pathExists}from"#shared/path-exists.js";import{removeOutputPublicationBackups,rollbackOutputPublication}from"#internal/application/output-publication-artifacts.js";import{readOutputPublicationJournal,readRecoveryLeaseJournal,resolveJournalFilePath,writeOutputPublicationJournal,writeRecoveryLeaseJournal}from"#internal/application/output-publication-journal.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";const PUBLICATION_LOCK_TIMEOUT_MS=6e4,INCOMPLETE_LOCK_STALE_MS=5e3;function resolveOutputPublicationLockPath(e){return join(resolve(e),`.eve`,`locks`,`output-publication.lock`)}function startPublicationJournalHeartbeat(e){let t=resolveJournalFilePath(e),n=setInterval(()=>{let e=new Date;utimes(t,e,e).catch(()=>void 0)},1e3);return n.unref(),()=>{clearInterval(n)}}async function acquireOutputPublicationLock(e,t,n){let r=Date.now()+PUBLICATION_LOCK_TIMEOUT_MS,i=`${e}.recovery`;for(await mkdir(dirname(e),{recursive:!0});;){if(await pathExists(i)){if(await n(),await recoverStalePublication(e,i,t))continue;await waitForPublicationLockChange(e,r);continue}try{if(await mkdir(e),await pathExists(i)){await rm(e,{force:!0,recursive:!0}),await waitForPublicationLockChange(e,r);continue}try{await writeOutputPublicationJournal(e,t)}catch(t){throw await rm(e,{force:!0,recursive:!0}),t}return async()=>{if((await readOutputPublicationJournal(e))?.token!==t.token)return;let n=`${e}.released-${t.token}`;try{await renameWithTransientBusyRetry(e,n)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(n,{force:!0,recursive:!0})}}catch(e){if(!isErrnoCode(e,`EEXIST`))throw e}await n(),!await recoverStalePublication(e,i,t)&&await waitForPublicationLockChange(e,r)}}async function recoverStalePublication(e,t,n){let r=await acquireRecoveryLease(t,n.token);if(r===void 0)return!1;let i=startPublicationJournalHeartbeat(join(t,`lease`)),a=!1;try{let r=await readOutputPublicationJournal(e);if(r!==void 0&&r.liveness===`active`&&isProcessAlive(r.pid)&&!await isJournalStale(e)||r===void 0&&!await isPathStale(e))return!1;if(await pathExists(e)){let r=join(t,`owner-${n.token}`);try{await renameWithTransientBusyRetry(e,r),a=!0}catch(e){if(!isErrnoCode(e,`ENOENT`))throw e}}let i=await readdir(t,{withFileTypes:!0});a=i.some(e=>e.isDirectory()&&e.name.startsWith(`owner-`));for(let e of i)e.isDirectory()&&e.name.startsWith(`owner-`)&&await finishInterruptedPublication(join(t,e.name));return a=!1,!0}finally{i(),a?await r.release():await r.complete()}}async function acquireRecoveryLease(e,t){let n=join(e,`lease`),r={pid:process.pid,token:t};for(await mkdir(e,{recursive:!0});;){try{await mkdir(n);try{await writeRecoveryLeaseJournal(n,r)}catch(e){throw await rm(n,{force:!0,recursive:!0}),e}return{async complete(){if((await readRecoveryLeaseJournal(n))?.token!==t)return;let r=`${e}.released-${t}`;try{await renameWithTransientBusyRetry(e,r)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(r,{force:!0,recursive:!0})},async release(){if((await readRecoveryLeaseJournal(n))?.token!==t)return;let e=`${n}.released-${t}`;try{await renameWithTransientBusyRetry(n,e)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(e,{force:!0,recursive:!0})}}}catch(e){if(isErrnoCode(e,`ENOENT`))return;if(!isErrnoCode(e,`EEXIST`))throw e}let i=await readRecoveryLeaseJournal(n);if(i!==void 0&&isProcessAlive(i.pid)&&!await isJournalStale(n)||i===void 0&&!await isPathStale(n))return;let a=`${n}.stale-${t}`;try{await renameWithTransientBusyRetry(n,a)}catch(e){if(isErrnoCode(e,`ENOENT`))continue;throw e}await rm(a,{force:!0,recursive:!0})}}async function finishInterruptedPublication(e){let t=await readOutputPublicationJournal(e);if(t===void 0||!hasTokenDerivedBackupPaths(t)){await rm(e,{force:!0,recursive:!0});return}t.phase===`committed`?await removeOutputPublicationBackups(t):await rollbackOutputPublication(t),await removePublicationScratchDirectory(t),await rm(e,{force:!0,recursive:!0})}function hasTokenDerivedBackupPaths(e){return e.outputBackupPath===`${e.finalOutputDir}.eve-backup-${e.token}`&&e.summaryBackupPath===`${e.finalSummaryPath}.eve-backup-${e.token}`}async function removePublicationScratchDirectory(e){let t=relative(e.scratchDir,e.stagedOutputDir);t===``||t.startsWith(`..`)||isAbsolute(t)||await rm(e.scratchDir,{force:!0,recursive:!0})}async function waitForPublicationLockChange(e,t){let n=t-Date.now();if(n<=0)throw Error(`Timed out waiting ${PUBLICATION_LOCK_TIMEOUT_MS}ms to publish completed build output.`);let r=await realpath(dirname(e)),i=basename(e),a=await readPublicationLockState(e);await new Promise((t,o)=>{let s=!1,c=setTimeout(settleResolve,Math.min(n,INCOMPLETE_LOCK_STALE_MS)),l=watch(r,(e,t)=>{e===`rename`&&(t===null||t.toString().startsWith(i))&&settleResolve()});function cleanup(){clearTimeout(c),l.close()}function settleResolve(){s||(s=!0,cleanup(),t())}function settleReject(e){s||(s=!0,cleanup(),o(e))}l.once(`error`,settleReject),Promise.all([readPublicationLockState(e),pathExists(e),pathExists(`${e}.recovery`)]).then(([e,t,n])=>{(!t&&!n||e!==a)&&settleResolve()},settleReject)})}async function readPublicationLockState(e){let t=`${e}.recovery`,[n,r,i,a]=await Promise.all([readOutputPublicationJournal(e),readRecoveryLeaseJournal(join(t,`lease`)),pathExists(e),pathExists(t)]);return JSON.stringify({lockExists:i,lockToken:n?.token,recoveryExists:a,recoveryToken:r?.token})}async function isPathStale(e){try{return Date.now()-(await stat(e)).mtimeMs>=INCOMPLETE_LOCK_STALE_MS}catch(e){if(isErrnoCode(e,`ENOENT`))return!0;throw e}}async function isJournalStale(e){try{let t=await stat(resolveJournalFilePath(e));return Date.now()-t.mtimeMs>=15e3}catch(e){if(isErrnoCode(e,`ENOENT`))return!0;throw e}}function isProcessAlive(e){try{return process.kill(e,0),!0}catch(e){return!isErrnoCode(e,`ESRCH`)}}export{acquireOutputPublicationLock,resolveOutputPublicationLockPath,startPublicationJournalHeartbeat};
|
|
1
|
+
import{mkdir,readdir,realpath,rm,stat,utimes}from"node:fs/promises";import{isErrnoCode}from"#shared/guards.js";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";import{watch}from"node:fs";import{pathExists}from"#shared/path-exists.js";import{removeOutputPublicationBackups,rollbackOutputPublication}from"#internal/application/output-publication-artifacts.js";import{readOutputPublicationJournal,readRecoveryLeaseJournal,resolveJournalFilePath,writeOutputPublicationJournal,writeRecoveryLeaseJournal}from"#internal/application/output-publication-journal.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";const PUBLICATION_LOCK_TIMEOUT_MS=6e4,INCOMPLETE_LOCK_STALE_MS=5e3;function resolveOutputPublicationLockPath(e){return join(resolve(e),`.eve`,`locks`,`output-publication.lock`)}function startPublicationJournalHeartbeat(e){let t=resolveJournalFilePath(e),n=setInterval(()=>{let e=new Date;utimes(t,e,e).catch(()=>void 0)},1e3);return n.unref(),()=>{clearInterval(n)}}async function acquireOutputPublicationLock(e,t,n){let r=Date.now()+PUBLICATION_LOCK_TIMEOUT_MS,i=`${e}.recovery`;for(await mkdir(dirname(e),{recursive:!0});;){if(await pathExists(i)){if(await n(),await recoverStalePublication(e,i,t))continue;await waitForPublicationLockChange(e,r);continue}try{if(await mkdir(e),await pathExists(i)){await rm(e,{force:!0,recursive:!0}),await waitForPublicationLockChange(e,r);continue}try{await writeOutputPublicationJournal(e,t)}catch(t){throw await rm(e,{force:!0,recursive:!0}),t}return async()=>{if((await readOutputPublicationJournal(e))?.token!==t.token)return;let n=`${e}.released-${t.token}`;try{await renameWithTransientBusyRetry(e,n)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(n,{force:!0,recursive:!0})}}catch(e){if(!isErrnoCode(e,`EEXIST`))throw e}await n(),!await recoverStalePublication(e,i,t)&&await waitForPublicationLockChange(e,r)}}async function recoverStalePublication(e,t,n){let r=await acquireRecoveryLease(t,n.token);if(r===void 0)return!1;let i=startPublicationJournalHeartbeat(join(t,`lease`)),a=!1;try{let r=await readOutputPublicationJournal(e);if(r!==void 0&&r.liveness===`active`&&isProcessAlive(r.pid)&&!await isJournalStale(e)||r===void 0&&!await isPathStale(e))return!1;if(await pathExists(e)){let r=join(t,`owner-${n.token}`);try{await renameWithTransientBusyRetry(e,r),a=!0}catch(e){if(!isErrnoCode(e,`ENOENT`))throw e}}let i=await readdir(t,{withFileTypes:!0});a=i.some(e=>e.isDirectory()&&e.name.startsWith(`owner-`));for(let e of i)e.isDirectory()&&e.name.startsWith(`owner-`)&&await finishInterruptedPublication(join(t,e.name));return a=!1,!0}finally{i(),a?await r.release():await r.complete()}}async function acquireRecoveryLease(e,t){let n=join(e,`lease`),r={pid:process.pid,token:t};for(await mkdir(e,{recursive:!0});;){try{await mkdir(n);try{await writeRecoveryLeaseJournal(n,r)}catch(e){throw await rm(n,{force:!0,recursive:!0}),e}return{async complete(){if((await readRecoveryLeaseJournal(n))?.token!==t)return;let r=`${e}.released-${t}`;try{await renameWithTransientBusyRetry(e,r)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(r,{force:!0,recursive:!0})},async release(){if((await readRecoveryLeaseJournal(n))?.token!==t)return;let e=`${n}.released-${t}`;try{await renameWithTransientBusyRetry(n,e)}catch(e){if(isErrnoCode(e,`ENOENT`))return;throw e}await rm(e,{force:!0,recursive:!0})}}}catch(e){if(isErrnoCode(e,`ENOENT`))return;if(!isErrnoCode(e,`EEXIST`))throw e}let i=await readRecoveryLeaseJournal(n);if(i!==void 0&&isProcessAlive(i.pid)&&!await isJournalStale(n)||i===void 0&&!await isPathStale(n))return;let a=`${n}.stale-${t}`;try{await renameWithTransientBusyRetry(n,a)}catch(e){if(isErrnoCode(e,`ENOENT`))continue;throw e}await rm(a,{force:!0,recursive:!0})}}async function finishInterruptedPublication(e){let t=await readOutputPublicationJournal(e);if(t===void 0||!hasTokenDerivedBackupPaths(t)){await rm(e,{force:!0,recursive:!0});return}t.phase===`committed`?await removeOutputPublicationBackups(t):await rollbackOutputPublication(t),await removePublicationScratchDirectory(t),await rm(e,{force:!0,recursive:!0})}function hasTokenDerivedBackupPaths(e){return e.outputBackupPath===`${e.finalOutputDir}.eve-backup-${e.token}`&&e.summaryBackupPath===`${e.finalSummaryPath}.eve-backup-${e.token}`}async function removePublicationScratchDirectory(e){let t=relative(e.scratchDir,e.stagedOutputDir);t===``||t.startsWith(`..`)||isAbsolute(t)||await rm(e.scratchDir,{force:!0,recursive:!0})}async function waitForPublicationLockChange(e,t){let n=t-Date.now();if(n<=0)throw Error(`Timed out waiting ${PUBLICATION_LOCK_TIMEOUT_MS}ms to publish completed build output.`);let r=await realpath(dirname(e)),i=basename(e),a=await readPublicationLockState(e);await new Promise((t,o)=>{let s=!1,c=setTimeout(settleResolve,Math.min(n,INCOMPLETE_LOCK_STALE_MS)),l=watch(r,(e,t)=>{e===`rename`&&(t===null||t.toString().startsWith(i))&&settleResolve()});function cleanup(){clearTimeout(c),l.close()}function settleResolve(){s||(s=!0,cleanup(),t())}function settleReject(e){s||(s=!0,cleanup(),o(e))}l.once(`error`,settleReject),Promise.all([readPublicationLockState(e),pathExists(e),pathExists(`${e}.recovery`)]).then(([e,t,n])=>{(!t&&!n||e!==a)&&settleResolve()},settleReject)})}async function readPublicationLockState(e){let t=`${e}.recovery`,[n,r,i,a]=await Promise.all([readOutputPublicationJournal(e),readRecoveryLeaseJournal(join(t,`lease`)),pathExists(e),pathExists(t)]);return JSON.stringify({lockExists:i,lockToken:n?.token,recoveryExists:a,recoveryToken:r?.token})}async function isPathStale(e){try{return Date.now()-(await stat(e)).mtimeMs>=INCOMPLETE_LOCK_STALE_MS}catch(e){if(isErrnoCode(e,`ENOENT`))return!0;throw e}}async function isJournalStale(e){try{let t=await stat(resolveJournalFilePath(e));return Date.now()-t.mtimeMs>=15e3}catch(e){if(isErrnoCode(e,`ENOENT`))return!0;throw e}}function isProcessAlive(e){try{return process.kill(e,0),!0}catch(e){return!isErrnoCode(e,`ESRCH`)}}export{acquireOutputPublicationLock,acquireRecoveryLease,resolveOutputPublicationLockPath,startPublicationJournalHeartbeat};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{resolve}from"node:path";import{
|
|
1
|
+
import{randomUUID}from"node:crypto";import{resolve}from"node:path";import{acquireOutputPublicationLock,resolveOutputPublicationLockPath,startPublicationJournalHeartbeat}from"#internal/application/output-publication-lock.js";import{assertStagedPublicationExists,backupOutputPublication,installOutputPublication,prepareOutputPublication,removeOutputPublicationBackups,rollbackOutputPublication}from"#internal/application/output-publication-artifacts.js";import{writeOutputPublicationJournal}from"#internal/application/output-publication-journal.js";var RecoverablePublicationError=class extends AggregateError{constructor(e,t,n){super(e,t,n),this.name=`RecoverablePublicationError`}};const DEFAULT_OBSERVER={async afterBackup(){},async afterOutputInstall(){},async onContention(){}};async function publishApplicationBuildArtifacts(e){await publishApplicationBuildArtifactsWithObserver(e,DEFAULT_OBSERVER)}async function publishApplicationBuildArtifactsWithObserver(e,t){let n=createOutputPublicationJournal(e);await assertStagedPublicationExists(n);let r=resolveOutputPublicationLockPath(e.appRoot),i=await acquireOutputPublicationLock(r,n,t.onContention),a=startPublicationJournalHeartbeat(r),o=!1;try{await prepareOutputPublication(n),n.phase=`prepared`,await writeOutputPublicationJournal(r,n),await backupOutputPublication(n),n.phase=`backed-up`,await writeOutputPublicationJournal(r,n),await t.afterBackup(),await installOutputPublication(n,t.afterOutputInstall),n.phase=`committed`,await writeOutputPublicationJournal(r,n),o=!0,await removeOutputPublicationBackups(n)}catch(e){o&&await throwRecoverablePublicationError({errors:[e],journal:n,lockPath:r,message:`Build output was committed but backup cleanup failed.`});try{await rollbackOutputPublication(n)}catch(t){await throwRecoverablePublicationError({errors:[e,t],journal:n,lockPath:r,message:`Build output publication failed and could not fully restore the previous output.`})}throw await i(),e}finally{a()}await i()}function createOutputPublicationJournal(e){let t=randomUUID(),n=resolve(e.finalOutputDir),r=resolve(e.finalSummaryPath);return{finalOutputDir:n,finalSummaryPath:r,hadOutput:!1,hadSummary:!1,liveness:`active`,outputBackupPath:`${n}.eve-backup-${t}`,phase:`acquired`,pid:process.pid,scratchDir:resolve(e.scratchDir),stagedOutputDir:resolve(e.stagedOutputDir),stagedSummaryPath:resolve(e.stagedSummaryPath),summaryBackupPath:`${r}.eve-backup-${t}`,token:t}}async function throwRecoverablePublicationError(e){e.journal.liveness=`recoverable`;try{await writeOutputPublicationJournal(e.lockPath,e.journal)}catch(t){throw new RecoverablePublicationError([...e.errors,t],e.message,{cause:e.errors[0]})}throw new RecoverablePublicationError(e.errors,e.message,{cause:e.errors[0]})}export{RecoverablePublicationError,publishApplicationBuildArtifacts,publishApplicationBuildArtifactsWithObserver,resolveOutputPublicationLockPath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.64.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.64.1`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(e){return createRequire(e).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),r=tryResolveDirectBuildLocation(n);if(r!==void 0)return r;let i=findNearestVerifiedPackageRoot(dirname(n));if(i!==void 0&&isSourceCheckout(i))return{packageBuildRoot:null,packageRoot:i};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let a=i===void 0?void 0:tryCreatePackageLocation(i);if(a!==void 0)return a;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(typeof t.name==`string`&&typeof t.version==`string`)return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -59,6 +59,7 @@ export interface AuthoredModuleMapBundle {
|
|
|
59
59
|
readonly workflowSourceFingerprint: string | undefined;
|
|
60
60
|
}
|
|
61
61
|
export declare function bundleAuthoredModuleMapForGeneration(input: {
|
|
62
|
+
readonly appRoot: string;
|
|
62
63
|
readonly manifest: CompiledAgentManifest;
|
|
63
64
|
readonly moduleMapPath: string;
|
|
64
65
|
}): Promise<AuthoredModuleMapBundle>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{expectObjectRecord}from"#internal/authored-module.js";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(n,`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e);return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n}),plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n})],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`_chunks/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,removeRolldownModuleRegionComments(e.code));for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})))),o=new AuthoredWorkflowSourceRecorder(
|
|
1
|
+
import{createHash}from"node:crypto";import{expectObjectRecord}from"#internal/authored-module.js";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(n,`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e);return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n}),plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n})],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`_chunks/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,removeRolldownModuleRegionComments(e.code));for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})))),o=new AuthoredWorkflowSourceRecorder(e.appRoot),s=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:e.appRoot,recorder:o}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>o.workflowFunctions(e)}),o.graphPlugin(),a,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t})].filter(e=>e!==null);try{let n=await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:s,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}});return{authoredWorkflowModules:o.modules(),code:removeRolldownModuleRegionComments(n.code),workflowSourceFingerprint:o.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}modules(){return{directiveModules:[...this.#t].sort(),workflowModules:[...this.#i.keys()].sort()}}fingerprint(){if(this.#t.size===0)return;let e=new Set,t=[...this.#t];for(let n=t.shift();n!==void 0;n=t.shift())!e.has(n)&&this.#r.has(n)&&(e.add(n),t.push(...this.#n.get(n)??[]));let n=createHash(`sha256`);for(let t of[...e].sort())n.update(relative(this.#e,t).split(sep).join(`/`)).update(`\0`).update(this.#r.get(t)??``).update(`\0`);return n.digest(`hex`)}};function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=n.channelIdentity?getChannelModuleCache():void 0,i=resolveAuthoredPackageRoot(e),a=resolveAuthoredTsConfigPath(i),o=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(r.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(CACHED_CHANNEL_PREFIX.length);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
|
|
2
2
|
`),moduleType:`js`}}}:null,...n.plugins,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:i}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{cwd:i,input:e,platform:`node`,plugins:o,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:a,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}function removeRolldownModuleRegionComments(e){return e.split(`
|
|
3
3
|
`).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
|
|
4
4
|
`)}async function loadBundledAuthoredModule(e,t){let n=await bundleAuthoredModuleCode(e,t),r=normalizeExternalDependencies(t.externalDependencies),i=createHash(`sha1`).update(e).update(`\0`).update(r.join(`\0`)).update(`\0`).update(t.extensionScopeNamespace??``).update(`\0`).update(n).digest(`hex`),a=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),o=join(a,`${i}.mjs`);existsSync(o)||(mkdirSync(a,{recursive:!0}),writeFileSync(o,n));try{return await import(`${createFileImportSpecifier(o)}?v=${i}`)}catch(t){throw createAuthoredModuleEvaluationError(e,t)}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);if(existsSync(n))return n}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let n=dirname(t);if(n===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=n}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,loadAuthoredModuleNamespace,resolveAuthoredPackageRoot,resolveAuthoredTsConfigPath};
|
|
@@ -13,6 +13,7 @@ export interface PreparedAuthoredRuntimeModules {
|
|
|
13
13
|
}
|
|
14
14
|
/** Builds the authored runtime graph before a development or production host packages it. */
|
|
15
15
|
export declare function prepareAuthoredRuntimeModules(input: {
|
|
16
|
+
readonly appRoot: string;
|
|
16
17
|
readonly manifest: CompiledAgentManifest;
|
|
17
18
|
readonly moduleMapPath: string;
|
|
18
19
|
}): Promise<PreparedAuthoredRuntimeModules>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(e){let[t,n]=await Promise.allSettled([prepareAuthoredRuntimeModules({manifest:e.manifest,moduleMapPath:e.paths.moduleMapPath}),stageDevelopmentRuntimeArtifactsSnapshot(e)]);if(n.status===`rejected`)throw t.status===`rejected`?AggregateError([t.reason,n.reason],`Failed to stage development generation.`):n.reason;let r=n.value;try{if(t.status===`rejected`)throw t.reason;let e=t.value,n=await writeMaterializedAuthoredModules({prepared:e,runtimeAppRoot:r.runtimeAppRoot});return e.workflowSourceFingerprint===void 0?{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint}:{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint,workflowSourceFingerprint:e.workflowSourceFingerprint}}catch(e){try{await rm(r.snapshotRoot,{force:!0,recursive:!0})}catch(t){throw AggregateError([e,t],`Failed to materialize and discard development generation "${r.snapshotRoot}".`)}throw e}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),n=!1;return{commit(){n||(n=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){n||(n=!0,await t.rollback())}}}async function discardDevelopmentGeneration(e){await rm(e.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
|
|
1
|
+
import{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(e){let[t,n]=await Promise.allSettled([prepareAuthoredRuntimeModules({appRoot:e.project.appRoot,manifest:e.manifest,moduleMapPath:e.paths.moduleMapPath}),stageDevelopmentRuntimeArtifactsSnapshot(e)]);if(n.status===`rejected`)throw t.status===`rejected`?AggregateError([t.reason,n.reason],`Failed to stage development generation.`):n.reason;let r=n.value;try{if(t.status===`rejected`)throw t.reason;let e=t.value,n=await writeMaterializedAuthoredModules({prepared:e,runtimeAppRoot:r.runtimeAppRoot});return e.workflowSourceFingerprint===void 0?{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint}:{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint,workflowSourceFingerprint:e.workflowSourceFingerprint}}catch(e){try{await rm(r.snapshotRoot,{force:!0,recursive:!0})}catch(t){throw AggregateError([e,t],`Failed to materialize and discard development generation "${r.snapshotRoot}".`)}throw e}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),n=!1;return{commit(){n||(n=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){n||(n=!0,await t.rollback())}}}async function discardDevelopmentGeneration(e){await rm(e.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxProviderNames(e.compileResult.manifest),r=shouldPruneLocalSandboxProviders({configuredBackendNames:n,preset:t})?createCompiledSandboxProviderPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:{tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),r=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,n),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let a=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(a,e),configureNitroStepPlugins(a,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(a);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(a,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(a,e),await addNitroStepNoExternals(a,join(e.workflowBuildDir,`steps.mjs`)),a}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxProviderNames(e.compileResult.manifest),r=shouldPruneLocalSandboxProviders({configuredBackendNames:n,preset:t})?createCompiledSandboxProviderPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[t===`vercel`?createDevelopmentRuntimePrunePlugin():null,r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:{tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),r=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,n),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let a=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(a,e),configureNitroStepPlugins(a,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(a);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(a,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(a,e),await addNitroStepNoExternals(a,join(e.workflowBuildDir,`steps.mjs`)),a}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stageDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{
|
|
1
|
+
import{stageDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{computeDevelopmentHostFingerprint}from"#internal/nitro/host/dev-host-fingerprint.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";var PostCommitDevelopmentRebuildError=class extends Error{constructor(e){super(`The development worker was replaced but its generation failed to activate. The server keeps serving the previous generation; the next rebuild retries activation.`,{cause:e}),this.name=`PostCommitDevelopmentRebuildError`}},DevelopmentWorkflowWorldChangeRequiresRestartError=class extends Error{constructor(){super(`Changing experimental.workflow.world between the parent-owned local World and a custom World requires restarting eve dev.`),this.name=`DevelopmentWorkflowWorldChangeRequiresRestartError`}};async function createDevelopmentAuthoredRebuildCoordinator(e){return new TransactionalDevelopmentAuthoredRebuildCoordinator({currentHostFingerprint:await computeDevelopmentHostFingerprint(e.initialHost),currentRuntimeFingerprint:e.initialHost.generation.fingerprint,devServer:e.devServer,initialHost:e.initialHost})}var TransactionalDevelopmentAuthoredRebuildCoordinator=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.initialHost,this.#t=e.currentHostFingerprint,this.#n=e.currentRuntimeFingerprint,this.#r=e.devServer,this.#i=usesParentDevelopmentWorkflowWorld(e.initialHost.compileResult.manifest.config.experimental?.workflow?.world)}async rebuild(e){let t=this.#e,n=stageDevelopmentEnvironmentFiles(t.appRoot),r;try{if(r=await prepareDevelopmentApplicationHost(t.appRoot,{changedPaths:e.changedPaths,previousExtensions:t.workspaceExtensions}),usesParentDevelopmentWorkflowWorld(r.compileResult.manifest.config.experimental?.workflow?.world)!==this.#i)throw new DevelopmentWorkflowWorldChangeRequiresRestartError;let i=await computeDevelopmentHostFingerprint(r),a=r.generation.fingerprint,o=i!==this.#t,s=a!==this.#n;if(!o&&!s){let e={...t,workspaceExtensions:r.workspaceExtensions};return await discardPreparedHost(r),r=void 0,this.#o(e,this.#t,this.#n),n.commit(),{host:e,kind:`unchanged`}}if(!o){await removeDevelopmentHostWorkspace(r.workspace);let e=retainActiveHostWorkspace(t,r);return await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),this.#o(e,i,a),r=void 0,n.commit(),{host:e,kind:`runtime`}}let c=await this.#a({hasRuntimeChange:s,nextHost:r,nextHostFingerprint:i,nextRuntimeFingerprint:a});return r=void 0,n.commit(),c}catch(e){throw e instanceof PostCommitDevelopmentRebuildError?(n.commit(),e):(n.rollback(),r===void 0?e:await discardFailedHost(e,r))}}async#a(e){let t=e.nextHost;e.hasRuntimeChange||(await discardDevelopmentGeneration(e.nextHost.generation),t={...e.nextHost,generation:this.#e.generation});let n=await createDevelopmentApplicationNitro(t),r=await buildDevelopmentHostCandidate({host:t,nitro:n}),i=t.workspace;if(await this.#r.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(i),entry:r.entry,workerData:r.workerData}),e.hasRuntimeChange)try{await activateDevelopmentGeneration({appRoot:t.appRoot,generation:t.generation})}catch(n){throw await discardDevelopmentGeneration(t.generation).catch(()=>void 0),this.#o({...t,generation:this.#e.generation},e.nextHostFingerprint,this.#n),new PostCommitDevelopmentRebuildError(n)}return this.#o(t,e.nextHostFingerprint,e.hasRuntimeChange?e.nextRuntimeFingerprint:this.#n),{host:t,kind:`structural`}}#o(e,t,n){this.#e=e,this.#t=t,this.#n=n}};function retainActiveHostWorkspace(e,t){return{...t,compiledArtifacts:e.compiledArtifacts,workflowBuildDir:e.workflowBuildDir,workspace:e.workspace}}async function discardPreparedHost(e){let t=(await Promise.allSettled([discardDevelopmentGeneration(e.generation),removeDevelopmentHostWorkspace(e.workspace)])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length>0)throw AggregateError(t,`Failed to discard development host "${e.workspace.rootDir}".`)}async function discardFailedHost(e,t){try{return await discardPreparedHost(t),e}catch(t){return AggregateError([e,t],`Development rebuild rollback failed.`,{cause:e})}}export{DevelopmentWorkflowWorldChangeRequiresRestartError,PostCommitDevelopmentRebuildError,createDevelopmentAuthoredRebuildCoordinator};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
interface BundlerPluginShape {
|
|
2
|
+
readonly enforce: "pre";
|
|
3
|
+
readonly name: string;
|
|
4
|
+
load?(id: string): string | null;
|
|
5
|
+
resolveId?(source: string): string | null;
|
|
6
|
+
}
|
|
7
|
+
/** Removes development-only lazy sandbox preparation from every hosted runtime bundle. */
|
|
8
|
+
export declare function createDevelopmentRuntimePrunePlugin(): BundlerPluginShape;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID=`\0eve-pruned-development-lazy-prewarm`,DEVELOPMENT_LAZY_PREWARM_SOURCE_RE=/(?:^|[/\\#])execution[/\\]sandbox[/\\]development-lazy-prewarm\.(?:js|ts)(?:[?#].*)?$/;function createDevelopmentRuntimePrunePlugin(){return{enforce:`pre`,name:`eve-hosted-development-runtime-prune`,load(e){return e===PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID?`export async function ensureDevelopmentSandboxesPrepared() {}
|
|
2
|
+
`:null},resolveId(e){return DEVELOPMENT_LAZY_PREWARM_SOURCE_RE.test(e)?PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID:null}}}export{createDevelopmentRuntimePrunePlugin};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveDiscoveryProject}from"#discover/project.js";import{eveDevArguments}from"#setup/primitives/index.js";import{detectPackageManager}from"#setup/package-manager.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{readDevelopmentRuntimeArtifactsRevision}from"#services/dev-client/runtime-artifacts.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,createDevelopmentSandboxRunId}from"#execution/sandbox/development-run.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{toErrorMessage}from"#shared/errors.js";import{
|
|
2
|
-
`))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(e){e.devServer.setControlHandler(async t=>{let n=await handleDevelopmentModelCredentialRequest(t,{appRoot:e.appRoot,secret:e.transportSecret});if(n!==void 0)return n;let r=await e.workflowWorld?.handleRequest(t);if(r!==void 0)return r;let i=new URL(t.url);if(i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&t.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:e.appRoot});let a=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH&&t.method===`POST`,o=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH&&t.method===`POST`,s=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH&&(t.method===`GET`||t.method===`POST`);if(!a&&!o&&!s)return;let c=e.getWatcher();if(c===void 0)return Response.json({error:`The development server is still starting.`},{status:503});let l=i.searchParams.get(`lease`);return(a||o)&&(l===null||l.length===0)?Response.json({error:`A suspension lease is required.`},{status:400}):a?(await c.suspend(l),Response.json({suspended:!0})):o?(await c.resume(l,{silent:i.searchParams.get(`silent`)===`1`}),handleDevRuntimeArtifactsRequest({appRoot:e.appRoot})):(i.searchParams.get(`force`)===`1`?await c.rebuild():await c.flush(),handleDevRuntimeArtifactsRequest({appRoot:e.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.workflowWorld;r!==void 0&&await attempt(()=>r.close());let i=e.devServer,a=i===void 0||await attempt(()=>i.close()),o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({appRoot:e.appRoot,devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:a}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let n=await resolveDiscoveryProject(e);await loadDevelopmentEnvironmentFiles(n.appRoot);let r=readEnvironmentPort(),i=t.port??r,a=t.host!==void 0||t.port!==void 0||r!==void 0,o=new DevelopmentServerState(n),s=await o.read();if(s!==void 0&&isLoopbackServerUrl(s)&&await isDevelopmentServerReady(s)){if(t.existing===`attach-if-unconfigured`&&!a)return{handle:{kind:`existing`,appRoot:n.appRoot,url:s},close:void 0};throw await createDevelopmentServerAlreadyRunningError(n.appRoot,s)}let c=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],l=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=l;let u,d,f,p,m,h,g,_,v=!1,y=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(n.appRoot),t.onBootProgress);_=e,
|
|
1
|
+
import{randomBytes}from"node:crypto";import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveDiscoveryProject}from"#discover/project.js";import{eveDevArguments}from"#setup/primitives/index.js";import{detectPackageManager}from"#setup/package-manager.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{readDevelopmentRuntimeArtifactsRevision}from"#services/dev-client/runtime-artifacts.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,createDevelopmentSandboxRunId}from"#execution/sandbox/development-run.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{toErrorMessage}from"#shared/errors.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{DrainedNitroDevServer}from"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{handleDevelopmentModelCredentialRequest}from"#internal/model-auth/development-broker-server.js";import{createDevelopmentAuthoredRebuildCoordinator}from"#internal/nitro/host/dev-authored-rebuild-coordinator.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";import{installLocalDevCapabilityEnvironment}from"#runtime/local-dev-capability.js";import{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment}from"#internal/nitro/host/dev-workflow-world-setup.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,PORT_ENV=`PORT`;async function isActiveDevelopmentServerForApp(e){try{let t=await resolveDiscoveryProject(e.appRoot),n=await new DevelopmentServerState(t).read();return n===void 0||!isLoopbackServerUrl(n)||!await isDevelopmentServerReady(n)?!1:new URL(n).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}async function isDevelopmentServerReady(e){return await readDevelopmentRuntimeArtifactsRevision({serverUrl:e,timeoutMs:1e3})!==void 0}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
|
|
2
|
+
`))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(e){e.devServer.setControlHandler(async t=>{let n=await handleDevelopmentModelCredentialRequest(t,{appRoot:e.appRoot,secret:e.transportSecret});if(n!==void 0)return n;let r=await e.workflowWorld?.handleRequest(t);if(r!==void 0)return r;let i=new URL(t.url);if(i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&t.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:e.appRoot});let a=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH&&t.method===`POST`,o=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH&&t.method===`POST`,s=i.pathname===EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH&&(t.method===`GET`||t.method===`POST`);if(!a&&!o&&!s)return;let c=e.getWatcher();if(c===void 0)return Response.json({error:`The development server is still starting.`},{status:503});let l=i.searchParams.get(`lease`);return(a||o)&&(l===null||l.length===0)?Response.json({error:`A suspension lease is required.`},{status:400}):a?(await c.suspend(l),Response.json({suspended:!0})):o?(await c.resume(l,{silent:i.searchParams.get(`silent`)===`1`}),handleDevRuntimeArtifactsRequest({appRoot:e.appRoot})):(i.searchParams.get(`force`)===`1`?await c.rebuild():await c.flush(),handleDevRuntimeArtifactsRequest({appRoot:e.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.workflowWorld;r!==void 0&&await attempt(()=>r.close());let i=e.devServer,a=i===void 0||await attempt(()=>i.close()),o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({appRoot:e.appRoot,devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:a}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let n=await resolveDiscoveryProject(e);await loadDevelopmentEnvironmentFiles(n.appRoot);let r=readEnvironmentPort(),i=t.port??r,a=t.host!==void 0||t.port!==void 0||r!==void 0,o=new DevelopmentServerState(n),s=await o.read();if(s!==void 0&&isLoopbackServerUrl(s)&&await isDevelopmentServerReady(s)){if(t.existing===`attach-if-unconfigured`&&!a)return{handle:{kind:`existing`,appRoot:n.appRoot,url:s},close:void 0};throw await createDevelopmentServerAlreadyRunningError(n.appRoot,s)}let c=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],l=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=l;let u,d,f,p,m,h,g,_,v=!1,y=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(n.appRoot),t.onBootProgress);_=e,pruneLocalSandboxTemplatesInBackground(e.appRoot);let r=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),t.onBootProgress);u=r,d=new DrainedNitroDevServer(r.logger);let a=d,s=randomBytes(32).toString(`base64url`);a.setClientAddressSecret(s),m=installWorkflowTransportEnvironment(n.appRoot,s),h=createDevelopmentWorkflowWorld({appRoot:n.appRoot,preparedHost:e,transportSecret:s}),addDevelopmentControlHandler({appRoot:n.appRoot,devServer:a,getWatcher:()=>g,workflowWorld:h,transportSecret:s});let b=t.host??r.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,x=i===void 0,S=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:a,host:b,port:i,retryOnAddressInUse:x}),t.onBootProgress);if(!S.url)throw Error(`Nitro dev server did not expose a URL.`);let C=normalizeDevelopmentServerClientUrl(S.url);p=installWorkflowLocalQueueEnvironment(C),f=installLocalDevCapabilityEnvironment({appRoot:n.appRoot,serverUrl:C}),await devBootPhase(`building dev bundle`,async()=>{let t=await buildDevelopmentHostCandidate({host:e,nitro:r});u=void 0;let n=e.workspace;y=!0,await a.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(n),entry:t.entry,workerData:t.workerData}),await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),v=!0},t.onBootProgress),await h?.start();let w=await createDevelopmentAuthoredRebuildCoordinator({devServer:a,initialHost:e});g=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({coordinator:w,preparedHost:e})},t.onBootProgress),await o.write(C);let T=p;if(T===void 0)throw Error(`Workflow local queue environment was not initialized.`);let E=g,D=d,O=h,k=m,A=f,j;return{handle:{kind:`started`,appRoot:n.appRoot,url:C},close:()=>(j??=(async()=>{let e=await closeDevelopmentServerResources({appRoot:n.appRoot,authoredSourceWatcher:E,devServer:D,developmentSandboxRunId:l,nitro:void 0,workflowWorld:O});e.listenerClosed&&await o.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{T(),k?.(),A?.(),restoreDevelopmentSandboxRunId(c)}})(),j)}}catch(e){let t=await closeDevelopmentServerResources({appRoot:n.appRoot,authoredSourceWatcher:g,devServer:d,developmentSandboxRunId:l,nitro:u,workflowWorld:h}),r=[...t.errors];throw _!==void 0&&!v&&await discardDevelopmentGeneration(_.generation).catch(e=>{r.push(e)}),_!==void 0&&!y&&await removeDevelopmentHostWorkspace(_.workspace).catch(e=>{r.push(e)}),p?.(),m?.(),f?.(),t.listenerClosed&&await o.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(c),r.length>0?createDevelopmentServerStartupCleanupError(e,r):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";import{findClosestLinkedVercelDirectory,findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{findConfiguredEveServiceEntry,resolveServicePrefix}from"#internal/vercel/vercel-service-config-operations.js";import{createServiceConfigRecord,hasServices,parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";import{assembleEveVercelServices}from"#internal/vercel/assemble-eve-services.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,VERCEL_OUTPUT_CONFIG_FILE_NAME=`.vercel/output/config.json`;async function resolveVercelOutputConfigLocation(e){let t=await findClosestLinkedVercelDirectory(e),n=t===void 0?e:dirname(t),r=await findClosestVercelOutputDirectory(e);return r===void 0?t
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";import{findClosestLinkedVercelDirectory,findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{findConfiguredEveServiceEntry,resolveServicePrefix}from"#internal/vercel/vercel-service-config-operations.js";import{createServiceConfigRecord,hasServices,parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";import{assembleEveVercelServices}from"#internal/vercel/assemble-eve-services.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,VERCEL_OUTPUT_CONFIG_FILE_NAME=`.vercel/output/config.json`;async function resolveVercelOutputConfigLocation(e){let t=await findClosestLinkedVercelDirectory(e),n=t===void 0?e:dirname(t),r=await findClosestVercelOutputDirectory(e);return r===void 0?{canWriteGeneratedOutput:t!==void 0||!!process.env.VERCEL,outputConfigPath:join(e,VERCEL_OUTPUT_CONFIG_FILE_NAME),projectRoot:n}:{canWriteGeneratedOutput:!0,outputConfigPath:join(r,`config.json`),projectRoot:n}}async function readVercelServicesConfig(e,t){try{return parseVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function resolveConfiguredServicePrefix(e){let t=findConfiguredEveServiceEntry(e.services,e.agent)?.service;return resolveServicePrefix(t)??e.agent.servicePrefix}function assertRootServicesIncludeEve(e){let t=[];for(let n of e.agents){let r=findConfiguredEveServiceEntry(e.services,n)?.service;if(r===void 0)throw Error(`${VERCEL_JSON_FILE_NAME} already defines services, so withEve cannot add generated eve services through ${VERCEL_OUTPUT_CONFIG_FILE_NAME}. Add the eve service for ${n.name??`the default agent`} to ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`);t.push({name:n.name,servicePrefix:resolveServicePrefix(r)??n.servicePrefix})}return t}async function ensureEveVercelOutputConfig(e){let{canWriteGeneratedOutput:t,outputConfigPath:n,projectRoot:r}=await resolveVercelOutputConfigLocation(e.nextRoot),i=(await readVercelServicesConfig(join(r,VERCEL_JSON_FILE_NAME),VERCEL_JSON_FILE_NAME)).services;if(hasServices(i))return{agents:assertRootServicesIncludeEve({agents:e.agents,services:createServiceConfigRecord(i)})};let a=await readVercelServicesConfig(n,VERCEL_OUTPUT_CONFIG_FILE_NAME),o=createServiceConfigRecord(a.services),s=e.agents.map(e=>({name:e.name,servicePrefix:resolveConfiguredServicePrefix({agent:e,services:o})}));if(!t)return{agents:s};let c=assembleEveVercelServices({agents:e.agents.map(t=>({agent:t,target:{hostOutputDirectory:dirname(n),projectRoot:e.nextRoot}})),routes:a.routes,services:o});await Promise.all(c.rootDirectories.map(e=>mkdir(e,{recursive:!0})));let{services:l,...u}=a,d={...u,routes:c.routes,services:c.services,version:3};return JSON.stringify(a)!==JSON.stringify(d)&&(await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${JSON.stringify(d,null,2)}\n`)),{agents:s}}export{ensureEveVercelOutputConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resolveRuntimeCompilerArtifactPaths}from"#runtime/loaders/artifact-paths.js";import{getRuntimeCompiledArtifactsCacheKey}from"#runtime/compiled-artifacts-source.js";import{loadCompileMetadata}from"#runtime/loaders/compile-metadata.js";async function resolveRuntimeCompiledArtifactsVersionedCacheKey(e){let t=getRuntimeCompiledArtifactsCacheKey(e),n=await resolveCompileMetadataMtimeMs(e);try{let r=(await loadCompileMetadata({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${formatMtimeMsForCacheKey(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${formatMtimeMsForCacheKey(n)}`}catch{return n===void 0?t:`${t}:mtime-${formatMtimeMsForCacheKey(n)}`}}async function resolveCompileMetadataMtimeMs(e){if(e.kind!==`disk`)return;let{stat:t}=await import(`node:fs/promises`),{compileMetadataPath:n}=resolveRuntimeCompilerArtifactPaths(e.appRoot);try{return(await t(n)).mtimeMs}catch{return}}function formatMtimeMsForCacheKey(e){return Math.floor(e).toString(36)}export{resolveRuntimeCompiledArtifactsVersionedCacheKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{createSandboxPreparedArtifactsManifest,sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{resolveRuntimeCompilerArtifactPaths}from"#runtime/loaders/artifact-paths.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";async function writeSandboxPreparedArtifactsManifest(e){if(e.entries.length===0)return;let t=`${e.compileDirectoryPath}/sandbox-prepared-artifacts.json`,n=null;try{n=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(t,`utf8`)))}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let r=new Map(n?.entries.map(e=>[e.nodeId,e]));for(let t of e.entries)r.set(t.nodeId,t);await writeFile(
|
|
1
|
+
import{randomUUID}from"node:crypto";import{readFile,rename,rm,writeFile}from"node:fs/promises";import{createSandboxPreparedArtifactsManifest,sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{resolveRuntimeCompilerArtifactPaths}from"#runtime/loaders/artifact-paths.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";async function writeSandboxPreparedArtifactsManifest(e){if(e.entries.length===0)return;let t=`${e.compileDirectoryPath}/sandbox-prepared-artifacts.json`,n=null;try{n=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(t,`utf8`)))}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let r=new Map(n?.entries.map(e=>[e.nodeId,e]));for(let t of e.entries)r.set(t.nodeId,t);let i=`${t}.${randomUUID()}.tmp`;try{await writeFile(i,`${JSON.stringify(createSandboxPreparedArtifactsManifest([...r.values()]),null,2)}\n`),await rename(i,t)}finally{await rm(i,{force:!0})}}async function loadSandboxPreparedArtifact(e){let t=(await loadSandboxPreparedArtifactsManifest(e.compiledArtifactsSource))?.entries.find(t=>t.nodeId===e.nodeId);if(t!==void 0&&t.providerName!==e.providerName)throw Error(`Prepared sandbox artifact for node "${e.nodeId}" belongs to provider "${t.providerName}", not "${e.providerName}".`);return t?.artifact}async function loadSandboxPreparedArtifactsManifest(e){if(e.kind===`bundled`)return readBundledCompiledArtifacts()?.sandboxPreparedArtifacts??null;let t=resolveRuntimeCompilerArtifactPaths(e.appRoot).sandboxPreparedArtifactsPath;try{return sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(t,`utf8`)))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}export{loadSandboxPreparedArtifact,loadSandboxPreparedArtifactsManifest,writeSandboxPreparedArtifactsManifest};
|