eve 0.24.4 → 0.24.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/src/channel/types.d.ts +13 -0
- package/dist/src/chunks/{use-eve-agent-Dwa2j1wE.js → use-eve-agent-8rerxDHY.js} +59 -6
- package/dist/src/chunks/{use-eve-agent-BP9FpQsJ.js → use-eve-agent-DhgdHzDG.js} +59 -6
- package/dist/src/cli/commands/build.d.ts +14 -0
- package/dist/src/cli/commands/build.js +1 -0
- package/dist/src/cli/commands/channels.js +1 -1
- package/dist/src/cli/commands/link.d.ts +6 -5
- package/dist/src/cli/commands/link.js +1 -1
- package/dist/src/cli/run.d.ts +3 -2
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/ndjson.js +1 -1
- package/dist/src/client/open-stream.d.ts +3 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +15 -3
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +8 -0
- package/dist/src/compiled/.vendor-stamp.json +5 -5
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +55 -0
- package/dist/src/compiled/@workflow/core/runtime/run-id-time.d.ts +9 -0
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +2 -0
- package/dist/src/compiled/@workflow/core/runtime/step-latency.d.ts +70 -4
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +10 -1
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +6 -0
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +25 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +16 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/attributes.d.ts +7 -0
- package/dist/src/compiled/@workflow/world/events.d.ts +16 -0
- package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/world-local/index.js +3 -3
- package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
- package/dist/src/compiled/_chunks/workflow/attribute-changes-DXbmITuI.js +20 -0
- package/dist/src/compiled/_chunks/workflow/{dist-DpDDcpTl.js → dist-BYo8Gno2.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-Blxnyb7-.js → dist-CSfKNxQW.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-DvvgYsRt.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-BdvQmV5a.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-id-BdE0MZz9.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-DzxrwWTs.js +1 -0
- package/dist/src/evals/assertions/run.d.ts +3 -3
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/index.d.ts +2 -1
- package/dist/src/evals/match.d.ts +4 -0
- package/dist/src/evals/match.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/session.d.ts +10 -2
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/evals/types.d.ts +52 -2
- package/dist/src/execution/cancel-descendant-turns-step.d.ts +6 -0
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -0
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +6 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/turn-cancellation-control.d.ts +0 -13
- package/dist/src/execution/turn-cancellation-control.js +1 -1
- package/dist/src/execution/turn-cancellation-token.d.ts +9 -0
- package/dist/src/execution/turn-cancellation-token.js +1 -0
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +3 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +0 -1
- package/dist/src/harness/runtime-actions.d.ts +16 -12
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/internal/application/build-profile.d.ts +64 -0
- package/dist/src/internal/application/build-profile.js +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +10 -0
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/materialized-authored-modules.d.ts +2 -4
- package/dist/src/internal/materialized-authored-modules.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +2 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +7 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +3 -0
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
- package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
- package/dist/src/protocol/cancel-turn.d.ts +11 -0
- package/dist/src/protocol/cancel-turn.js +1 -0
- package/dist/src/protocol/routes.d.ts +10 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/eve.d.ts +2 -1
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/linear/api.d.ts +0 -1
- package/dist/src/public/channels/linear/api.js +17 -22
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +20 -10
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/resolve-eve-binary.d.ts +12 -0
- package/dist/src/public/next/resolve-eve-binary.js +1 -0
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/framework-tools/agent.d.ts +13 -0
- package/dist/src/runtime/framework-tools/agent.js +1 -0
- package/dist/src/runtime/framework-tools/index.d.ts +7 -2
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/types.d.ts +2 -1
- package/dist/src/setup/boxes/reconcile-host-framework-preset.d.ts +26 -0
- package/dist/src/setup/boxes/reconcile-host-framework-preset.js +1 -0
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/index.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/index.d.ts +1 -1
- package/dist/src/setup/scaffold/index.js +1 -1
- package/dist/src/setup/scaffold/update/channels.d.ts +7 -1
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/connections.js +3 -3
- package/dist/src/setup/vercel-project-framework.d.ts +12 -0
- package/dist/src/setup/vercel-project-framework.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/eve.mdx +11 -1
- package/docs/concepts/default-harness.md +2 -0
- package/docs/concepts/sessions-runs-and-streaming.md +11 -0
- package/docs/evals/assertions.mdx +2 -2
- package/docs/evals/cases.mdx +31 -0
- package/docs/evals/overview.mdx +1 -1
- package/docs/evals/targets.mdx +2 -1
- package/docs/guides/client/continuations.mdx +2 -0
- package/docs/guides/client/streaming.mdx +17 -1
- package/docs/guides/frontend/overview.mdx +4 -2
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +2 -2
- package/docs/guides/frontend/use-eve-agent-vue.mdx +2 -2
- package/docs/guides/remote-agents.md +2 -0
- package/docs/reference/cli.md +15 -2
- package/docs/subagents.mdx +10 -0
- package/package.json +6 -6
- package/dist/src/compiled/_chunks/workflow/attribute-changes-MGTOG_uX.js +0 -20
- package/dist/src/compiled/_chunks/workflow/resume-hook-DHP5ql3-.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-D8hv1ptT.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-uA9pS-PT.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{sessionCancelHookToken}from"#execution/turn-cancellation-token.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),i=serializeContext(buildRunContext({bundle:r,run:n})),a=readParentLineage(i),o=a.sessionId===void 0?buildSessionAttributes({inputMessage:n.title??n.input.message,serializedContext:i}):buildSubagentRootAttributes({identity:{nodeId:r.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:a.callId,parentSessionId:a.sessionId,parentTurnId:a.turnId,rootSessionId:a.rootSessionId??a.sessionId,serializedContext:i}),s;try{s=await startWorkflowPreferLatest(workflowEntryReference,[{input:n.input,limits:n.limits,serializedContext:i}],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(o)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:n.continuationToken}),e}let c,getEvents=()=>(c??=parseNdjsonStream(()=>getRun(s.runId).getReadable()),c);return{continuationToken:n.continuationToken??s.runId,get events(){return getEvents()},sessionId:s.runId}},async cancelTurn(e){return await requestWorkflowTurnCancellation(e)},async deliver(e){let r={auth:e.auth,kind:`deliver`,payloads:[e.payload],requestId:e.requestId};try{return{sessionId:normalizeWorkflowHook(await resumeHook(e.continuationToken,r)).runId}}catch(r){throw HookNotFoundError.is(r)?new RuntimeNoActiveSessionError(e.continuationToken):(logError(log,`failed to deliver to active session`,r,{continuationToken:e.continuationToken}),r)}},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))}}}async function requestWorkflowTurnCancellation(e){let t=e.turnId===void 0?{}:{turnId:e.turnId};try{return await resumeHook(sessionCancelHookToken(e.sessionId),t),{status:`accepted`}}catch(e){if(isInactiveCancelTarget(e))return{status:`no_active_turn`};throw e}}function isInactiveCancelTarget(e){return HookNotFoundError.is(e)||WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e)||EntityConflictError.is(e)}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveSessionSkillRoot}from"#execution/workflow-skill-root.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let d=getPendingAuthorization(s.state),f;if(d&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=d.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},f=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let p=hydrateDurableSession({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:u.turnAgent}),m=buildAdapterContext(l,c),h;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,m):defaultDeliverResult(n);r!=null&&e.push(r)}h=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),h={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...m.state}}),o.input?.kind===`deliver`&&h===void 0){let e=reconcileSessionContinuationToken(c,p),t=serializeContext(c),n=e===p?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let g=o.parentWritable.getWriter(),_=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.resolvedAgent.dynamicToolResolvers??[],emit=async t=>{let n=await callAdapterEventHandler(l,t,m);return setChannelContext(c,{...l,state:{...m.state}}),await g.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(n))),n},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:u.turnAgent.dynamicModel,event:n,fallback:u.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicToolEvent({ctx:c,resolvers:b,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},x=c.require(ModeKey),S;try{throwIfTurnAborted(o.abortSignal),S=await runStep(c,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:u.turnAgent.outputSchema,input:h,mode:x,session:e});if(f){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of f)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=await resolveSessionSkillRoot({ctx:c,turnAgent:u.turnAgent}),i=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},session:e,skillRoot:r,turnAgent:u.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:x,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:u.graph.root,workflowMaxSubagents:i.workflowMaxSubagents})(i,t)})(t,h)})}catch(e){if(!isTurnCancellation(e))throw e;return g.releaseLock(),{action:`cancelled`,serializedContext:o.serializedContext,sessionState:o.sessionState}}let C=reconcileSessionContinuationToken(c,S.session),w=serializeContext(c);S={...S,session:C};let T=createDurableSessionState({session:S.session});if(S.next!==null&&typeof S.next==`object`&&`done`in S.next){await g.close();let e=getTurnUsageState(S.session.state)?.session;return{action:`done`,output:S.next.output,isError:S.next.isError,serializedContext:w,sessionState:T,usage:e===void 0?void 0:toUsage(e)}}if(S.next===null){g.releaseLock();let e=getPendingWorkflowInterrupt(S.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:w,sessionState:T}:{action:`park`,...derivePendingState(S.session),serializedContext:w,sessionState:T}}return g.releaseLock(),{action:`continue`,serializedContext:w,sessionState:T}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let
|
|
1
|
+
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let a=ensureWorkflowContinuationSecurity(e.session),{modelTools:o}=await applyWorkflowTool({continuationSecurity:getWorkflowContinuationSecurity(a),harnessTools:n,lifecycle:e.workflow.lifecycle?.({session:a,tools:n}),maxSubagents:e.workflow.maxSubagents,tools:e.modelTools});return{harnessTools:t,modelTools:o,session:a}}function filterUnavailableDelegationToolDefinitions(e,t){let n=[];for(let r of e)shouldHideDelegationTool(r,t)||n.push(r);return n}function filterUnavailableDelegationToolMap(e,t){let n=new Map;for(let[r,i]of e)shouldHideDelegationTool(i,t)||n.set(r,i);return n}function filterWorkflowHostToolsForRootSession(t,n){let r=new Map,i=resolveSubagentDepth(n);if(n.rootSessionId!==void 0||i.currentDepth>0)return r;for(let[e,n]of t)isDelegatedRuntimeActionTool(n)&&r.set(e,n);return r}function isDelegatedRuntimeActionTool(e){let t=e.runtimeAction;return t?.kind===`subagent-call`||t?.kind===`remote-agent-call`}function shouldHideDelegationTool(r,i){return r.name!==AGENT_TOOL_NAME||r.runtimeAction?.kind!==`subagent-call`||r.runtimeAction.nodeId!==ROOT_RUNTIME_AGENT_NODE_ID?!1:i.rootSessionId!==void 0||resolveSubagentDepth(i).currentDepth>0}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
@@ -10,7 +10,6 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
|
10
10
|
export type HarnessRuntimeActionDefinition = {
|
|
11
11
|
readonly kind: "remote-agent-call" | "subagent-call";
|
|
12
12
|
readonly nodeId: string;
|
|
13
|
-
readonly recursive?: true;
|
|
14
13
|
readonly remoteAgentName?: string;
|
|
15
14
|
readonly subagentName: string;
|
|
16
15
|
};
|
|
@@ -16,14 +16,14 @@ interface PendingRuntimeActionEventMetadata {
|
|
|
16
16
|
/**
|
|
17
17
|
* Serializable pending runtime-action batch stored on `session.state`.
|
|
18
18
|
*
|
|
19
|
-
* `childContinuationTokens`
|
|
20
|
-
* `
|
|
21
|
-
*
|
|
22
|
-
* without re-deriving the token (keeps `harness/` runtime-agnostic).
|
|
19
|
+
* `childContinuationTokens` lets the harness clear local proxy-input entries
|
|
20
|
+
* on result resolution. `childSessionIds` lets the turn workflow cancel every
|
|
21
|
+
* successfully adopted local or remote child before dropping the batch.
|
|
23
22
|
*/
|
|
24
|
-
interface PendingRuntimeActionBatch {
|
|
23
|
+
export interface PendingRuntimeActionBatch {
|
|
25
24
|
readonly actions: readonly RuntimeActionRequest[];
|
|
26
25
|
readonly childContinuationTokens?: Readonly<Record<string, string>>;
|
|
26
|
+
readonly childSessionIds?: Readonly<Record<string, string>>;
|
|
27
27
|
readonly event: PendingRuntimeActionEventMetadata;
|
|
28
28
|
readonly responseMessages: readonly ModelMessage[];
|
|
29
29
|
}
|
|
@@ -51,14 +51,18 @@ export declare function setPendingRuntimeActionBatch(input: {
|
|
|
51
51
|
readonly responseMessages: readonly ModelMessage[];
|
|
52
52
|
readonly session: HarnessSession;
|
|
53
53
|
}): HarnessSession;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
type PendingSubagentChildIdentity = {
|
|
55
|
+
readonly continuationToken: string;
|
|
56
|
+
readonly kind: "local";
|
|
57
|
+
readonly sessionId: string;
|
|
58
|
+
} | {
|
|
59
|
+
readonly kind: "remote";
|
|
60
|
+
readonly sessionId: string;
|
|
61
|
+
};
|
|
62
|
+
/** Records one successfully dispatched child's durable identities. */
|
|
63
|
+
export declare function recordPendingSubagentChild(input: {
|
|
60
64
|
readonly callId: string;
|
|
61
|
-
readonly
|
|
65
|
+
readonly child: PendingSubagentChildIdentity;
|
|
62
66
|
readonly session: HarnessSession;
|
|
63
67
|
}): HarnessSession;
|
|
64
68
|
/** Returns results in pending-key order once every requested action has completed. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function
|
|
1
|
+
import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function recordPendingSubagentChild(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t===void 0)return e.session;let n={...e.session.state};return n[PENDING_RUNTIME_ACTION_BATCH_KEY]={...t,...e.child.kind===`local`?{childContinuationTokens:{...t.childContinuationTokens,[e.callId]:e.child.continuationToken}}:{},childSessionIds:{...t.childSessionIds,[e.callId]:e.child.sessionId}},{...e.session,state:n}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results})}function resolveRuntimeActionResultsForKeys(e){let t=new Set(e.pendingKeys),n=new Map;for(let r of e.results){let e=getRuntimeActionResultKey(r);t.has(e)&&n.set(e,r)}let r=[];for(let t of e.pendingKeys){let e=n.get(t);if(e===void 0)return;r.push(e)}return r}async function resolvePendingRuntimeActions(t){let i=getPendingRuntimeActionBatch(t.session.state);if(i===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let a=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(a===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of a)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:i.event.sequence,stepIndex:i.event.stepIndex,turnId:i.event.turnId}));let o={...t.session.state};delete o[PENDING_RUNTIME_ACTION_BATCH_KEY];let s={...t.session,state:Object.keys(o).length>0?o:void 0},c=i.childContinuationTokens;if(c!==void 0)for(let e of a){if(e.kind!==`subagent-result`)continue;let t=c[e.callId];t!==void 0&&(s=clearProxyInputRequestsForChild(s,t))}for(let e of a)e.kind!==`subagent-result`||e.usage===void 0||(s=setTurnUsageState(s,accumulateSessionUsage({previous:getTurnUsageState(s.state),usage:e.usage})));let l=a.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),u=[...s.history,...i.responseMessages];return l.length>0&&u.push({content:l,role:`tool`}),{messages:u,outcome:`resolved`,session:s}}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null)return{};try{return parseJsonObject(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,recordPendingSubagentChild,resolvePendingRuntimeActions,resolveRuntimeActionResultsForKeys,resolveToolCallInputObject,setPendingRuntimeActionBatch};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Version of the machine-readable `eve build --profile` report schema. */
|
|
2
|
+
export declare const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION: 1;
|
|
3
|
+
/** Deployment target represented by one build profile. */
|
|
4
|
+
export type ApplicationBuildProfileTarget = "local" | "vercel";
|
|
5
|
+
/** One completed phase in an application build profile. */
|
|
6
|
+
export interface ApplicationBuildProfilePhase {
|
|
7
|
+
readonly durationMs: number;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
}
|
|
10
|
+
/** Size totals for one Vercel function directory in the published output. */
|
|
11
|
+
export interface ApplicationBuildProfileFunctionBundle {
|
|
12
|
+
readonly files: number;
|
|
13
|
+
readonly gzipBytes: number;
|
|
14
|
+
readonly path: string;
|
|
15
|
+
readonly rawBytes: number;
|
|
16
|
+
}
|
|
17
|
+
/** Final output-size measurements collected after a successful publication. */
|
|
18
|
+
export interface ApplicationBuildProfileOutput {
|
|
19
|
+
readonly files: number;
|
|
20
|
+
readonly functionBundles: readonly ApplicationBuildProfileFunctionBundle[];
|
|
21
|
+
readonly gzipBytes: number;
|
|
22
|
+
readonly rawBytes: number;
|
|
23
|
+
}
|
|
24
|
+
/** Timing data gathered while an application build runs. */
|
|
25
|
+
export interface ApplicationBuildProfileTiming {
|
|
26
|
+
readonly durationMs: number;
|
|
27
|
+
readonly phases: readonly ApplicationBuildProfilePhase[];
|
|
28
|
+
}
|
|
29
|
+
/** Stable JSON document written by `eve build --profile <path>`. */
|
|
30
|
+
export interface ApplicationBuildProfile {
|
|
31
|
+
readonly durationMs: number;
|
|
32
|
+
readonly kind: "eve-build-profile";
|
|
33
|
+
readonly output: ApplicationBuildProfileOutput;
|
|
34
|
+
readonly phases: readonly ApplicationBuildProfilePhase[];
|
|
35
|
+
readonly schemaVersion: typeof APPLICATION_BUILD_PROFILE_SCHEMA_VERSION;
|
|
36
|
+
readonly target: ApplicationBuildProfileTarget;
|
|
37
|
+
}
|
|
38
|
+
interface ApplicationBuildProfilerOptions {
|
|
39
|
+
readonly now?: () => number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Records elapsed build phases only when profile output was requested. The
|
|
43
|
+
* injected clock keeps its serialization behavior independently testable.
|
|
44
|
+
*/
|
|
45
|
+
export declare class ApplicationBuildProfiler {
|
|
46
|
+
#private;
|
|
47
|
+
constructor(options?: ApplicationBuildProfilerOptions);
|
|
48
|
+
measure<T>(name: string, operation: () => T | Promise<T>): Promise<T>;
|
|
49
|
+
finish(): ApplicationBuildProfileTiming;
|
|
50
|
+
}
|
|
51
|
+
/** Creates the versioned report shape from completed timings and output measurements. */
|
|
52
|
+
export declare function createApplicationBuildProfile(input: {
|
|
53
|
+
readonly output: ApplicationBuildProfileOutput;
|
|
54
|
+
readonly target: ApplicationBuildProfileTarget;
|
|
55
|
+
readonly timing: ApplicationBuildProfileTiming;
|
|
56
|
+
}): ApplicationBuildProfile;
|
|
57
|
+
/**
|
|
58
|
+
* Measures regular files in the published output without following symlinks.
|
|
59
|
+
* Each `.func` directory receives its own subtotal for Vercel output.
|
|
60
|
+
*/
|
|
61
|
+
export declare function measureApplicationBuildOutput(outputDirectory: string): Promise<ApplicationBuildProfileOutput>;
|
|
62
|
+
/** Writes one formatted profile JSON document outside the build output. */
|
|
63
|
+
export declare function writeApplicationBuildProfile(outputPath: string, profile: ApplicationBuildProfile): Promise<void>;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dirname,join,relative,sep}from"node:path";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{performance}from"node:perf_hooks";import{gzipSync}from"node:zlib";const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION=1;function roundDuration(e){return Math.round(Math.max(0,e)*10)/10}function createMutableOutputSize(){return{files:0,gzipBytes:0,rawBytes:0}}function toOutputSize(e){return{files:e.files,gzipBytes:e.gzipBytes,rawBytes:e.rawBytes}}function toProfilePath(e,t){return relative(e,t).split(sep).join(`/`)}function measureFileSize(e){return{gzipBytes:gzipSync(e).byteLength,rawBytes:e.byteLength}}function addFileSize(e,t){e.files+=1,e.rawBytes+=t.rawBytes,e.gzipBytes+=t.gzipBytes}var ApplicationBuildProfiler=class{#e;#t=[];#n;#r=!1;constructor(e={}){this.#e=e.now??performance.now.bind(performance),this.#n=this.#e()}async measure(e,t){if(this.#r)throw Error(`Cannot record a phase after the build profile has finished.`);let n=this.#e();try{return await t()}finally{this.#t.push({durationMs:roundDuration(this.#e()-n),name:e})}}finish(){if(this.#r)throw Error(`The build profile has already finished.`);return this.#r=!0,{durationMs:roundDuration(this.#e()-this.#n),phases:[...this.#t]}}};function createApplicationBuildProfile(e){return{durationMs:e.timing.durationMs,kind:`eve-build-profile`,output:e.output,phases:e.timing.phases,schemaVersion:1,target:e.target}}async function measureApplicationBuildOutput(e){let n=createMutableOutputSize(),r=new Map,visit=async(i,o)=>{let s=await readdir(i,{withFileTypes:!0});for(let a of s){let s=join(i,a.name);if(a.isDirectory()){await visit(s,a.name.endsWith(`.func`)?toProfilePath(e,s):o);continue}if(!a.isFile())continue;let c=measureFileSize(await readFile(s));if(addFileSize(n,c),o!==void 0){let e=r.get(o)??createMutableOutputSize();addFileSize(e,c),r.set(o,e)}}};return await visit(e,void 0),{...toOutputSize(n),functionBundles:[...r.entries()].map(([e,t])=>({path:e,...toOutputSize(t)})).sort((e,t)=>e.path.localeCompare(t.path))}}async function writeApplicationBuildProfile(t,n){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(n,null,2)}\n`,`utf8`)}export{APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.5`,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 isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function 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,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CompiledAgentManifest } from "#compiler/manifest.js";
|
|
1
2
|
export interface AuthoredModuleLoadOptions {
|
|
2
3
|
readonly externalDependencies?: readonly string[];
|
|
3
4
|
/**
|
|
@@ -25,3 +26,12 @@ export declare function bundleAuthoredModuleCode(modulePath: string, options?: A
|
|
|
25
26
|
* configured external dependencies keep their normal runtime resolution.
|
|
26
27
|
*/
|
|
27
28
|
export declare function bundleAuthoredModuleForGeneration(modulePath: string, options?: AuthoredModuleLoadOptions): Promise<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Bundles every runtime-authored module in one immutable generation graph.
|
|
31
|
+
* Shared dependencies are parsed and emitted once instead of once per authored
|
|
32
|
+
* entry.
|
|
33
|
+
*/
|
|
34
|
+
export declare function bundleAuthoredModuleMapForGeneration(input: {
|
|
35
|
+
readonly manifest: CompiledAgentManifest;
|
|
36
|
+
readonly moduleMapPath: string;
|
|
37
|
+
}): Promise<string>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.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(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" 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={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],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 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(`
|
|
1
|
+
import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.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(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" 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={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],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 bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=normalizeExternalDependencies([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[])),r=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath}),i=createExtensionScopePlugin(e.manifest.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot}))),a=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:r}),createAuthoredDirectiveGuardPlugin(),i,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:n,packageRoot:t})].filter(e=>e!==null);try{return removeRolldownModuleRegionComments((await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:a,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}})).code)}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}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(),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:{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){!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t)||await assertNoWorkflowDirectivePrologue({filePath:t,source:e})}}}function removeRolldownModuleRegionComments(e){return e.split(`
|
|
3
3
|
`).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
|
|
4
|
-
`)}async function loadBundledAuthoredModule(e,r){let a=await bundleAuthoredModuleCode(e,r),o=normalizeExternalDependencies(r.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(o.join(`\0`)).update(`\0`).update(r.extensionScopeNamespace??``).update(`\0`).update(a).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,a)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function resolveAuthoredTsConfigPath(e){for(let n of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,n);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let n=dirname(e);for(;;){if(existsSync(join(n,`package.json`)))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve the authored package root for "${e}".`);n=r}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,loadAuthoredModuleNamespace};
|
|
4
|
+
`)}async function loadBundledAuthoredModule(e,r){let a=await bundleAuthoredModuleCode(e,r),o=normalizeExternalDependencies(r.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(o.join(`\0`)).update(`\0`).update(r.extensionScopeNamespace??``).update(`\0`).update(a).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,a)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function resolveAuthoredTsConfigPath(e){for(let n of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,n);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let n=dirname(e);for(;;){if(existsSync(join(n,`package.json`)))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve the authored package root for "${e}".`);n=r}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,loadAuthoredModuleNamespace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{join}from"node:path";import{collectModuleRefsForManifest,compiledModuleMapSchema}from"#compiler/module-map.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{pathToFileURL}from"node:url";import{formatValidationError}from"#runtime/validation.js";const EXT_CONFIG_SCOPE=Symbol.for(`eve.ext-config-scope`);async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),e.compiledArtifactsSource.appRoot)}async function hydrateCompiledModuleMapFromManifest(e,t){let n=await readMaterializedAuthoredModuleIndex(t);if(n!==void 0)return await loadMaterializedCompiledModuleMap({moduleMapPath:n.moduleMap,runtimeAppRoot:t});let i={},a=[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))],s={byMountNamespace:new Map(e.extensionMounts.map(e=>[e.namespace,e.packageNamespace])),byMountSourceId:new Map(e.extensionMounts.map(e=>[e.mountSourceId,e.packageNamespace]))};for(let e of a)i[e.nodeId]={modules:await hydrateCompiledNodeScope({agentRoot:e.agentRoot,manifest:e.manifest,scopeIndex:s})};return{nodes:i}}async function loadMaterializedCompiledModuleMap(t){let r=join(t.runtimeAppRoot,`.eve`,`compile`,t.moduleMapPath),i=await import(`${pathToFileURL(r).href}?generation=${encodeURIComponent(t.moduleMapPath)}`),a=compiledModuleMapSchema.safeParse(i.moduleMap??i.default);if(!a.success)throw Error(`Expected materialized authored module map "${r}" to export a valid compiled eve module map. ${formatValidationError(a.error)}`);return a.data}function extensionNamespaceForSourceId(e,t){let n=e.match(/^ext:([^:]+):/);return n===null?void 0:t.byMountNamespace.get(n[1])}async function hydrateCompiledNodeScope(n){let r=collectModuleRefsForManifest(n.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),a=n.manifest.config.build?.externalDependencies??[],o=globalThis,s={};for(let t of r){let r=join(n.agentRoot,t.logicalPath),c=extensionNamespaceForSourceId(t.sourceId,n.scopeIndex),l=n.scopeIndex.byMountSourceId.get(t.sourceId);l!==void 0&&(o[EXT_CONFIG_SCOPE]=l);try{s[t.sourceId]=await loadAuthoredModuleNamespace(r,{externalDependencies:a,extensionScopeNamespace:c})}finally{l!==void 0&&(o[EXT_CONFIG_SCOPE]=void 0)}}return s}export{loadCompiledModuleMapFromAuthoredSource};
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
export interface MaterializedAuthoredModuleIndex {
|
|
2
2
|
readonly fingerprint: string;
|
|
3
3
|
readonly instrumentation?: string;
|
|
4
|
-
readonly
|
|
5
|
-
|
|
6
|
-
}>>;
|
|
7
|
-
readonly version: 1;
|
|
4
|
+
readonly moduleMap: string;
|
|
5
|
+
readonly version: 2;
|
|
8
6
|
}
|
|
9
7
|
export declare function materializeAuthoredModules(input: {
|
|
10
8
|
readonly runtimeAppRoot: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join,relative,sep}from"node:path";import{lstat,mkdir,readFile,readdir,readlink,writeFile}from"node:fs/promises";import{createHash}from"node:crypto";import{
|
|
1
|
+
import{existsSync}from"node:fs";import{join,relative,sep}from"node:path";import{lstat,mkdir,readFile,readdir,readlink,writeFile}from"node:fs/promises";import{createHash}from"node:crypto";import{COMPILED_AGENT_MANIFEST_KIND,ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{serializeCompiledManifestForFingerprint}from"#internal/compiled-manifest-fingerprint.js";const MATERIALIZED_MODULES_DIRECTORY=`authored-modules`,MATERIALIZED_MODULES_INDEX=`authored-modules.json`,INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];async function materializeAuthoredModules(e){let n=join(e.runtimeAppRoot,`.eve`,`compile`),r=await readCompiledManifest(join(n,`compiled-agent-manifest.json`)),i=join(n,MATERIALIZED_MODULES_DIRECTORY),o=createHash(`sha256`);await mkdir(i,{recursive:!0}),o.update(`manifest\0`).update(serializeCompiledManifestForFingerprint({manifest:r,runtimeAppRoot:e.runtimeAppRoot})).update(`\0`);let s=await bundleAuthoredModuleMapForGeneration({manifest:r,moduleMapPath:join(n,`module-map.mjs`)}),c=createMaterializedModuleFileName(ROOT_COMPILED_AGENT_NODE_ID,`module-map`,s),u=join(MATERIALIZED_MODULES_DIRECTORY,c);await writeFile(join(i,c),s),o.update(`module-map\0`).update(s).update(`\0`);let d=resolveInstrumentationModule(r.agentRoot),f;if(d!==void 0){let e=await bundleAuthoredModuleForGeneration(d,{externalDependencies:r.config.build?.externalDependencies??[]}),n=createMaterializedModuleFileName(ROOT_COMPILED_AGENT_NODE_ID,`instrumentation`,e);await writeFile(join(i,n),e),f=join(MATERIALIZED_MODULES_DIRECTORY,n),o.update(`instrumentation\0`).update(e).update(`\0`)}await hashDirectoryIfPresent({fingerprint:o,path:join(n,`workspace-resources`),root:join(n,`workspace-resources`)});let p={fingerprint:o.digest(`hex`),moduleMap:u,version:2};return f!==void 0&&(p.instrumentation=f),await writeFile(join(n,MATERIALIZED_MODULES_INDEX),`${JSON.stringify(p)}\n`),p}async function readMaterializedAuthoredModuleIndex(n){let r=join(n,`.eve`,`compile`,MATERIALIZED_MODULES_INDEX);if(!existsSync(r))return;let i=JSON.parse(await readFile(r,`utf8`));if(i.version!==2||typeof i.fingerprint!=`string`||i.fingerprint.length===0||typeof i.moduleMap!=`string`||i.moduleMap.length===0||i.instrumentation!==void 0&&typeof i.instrumentation!=`string`)throw Error(`Invalid materialized authored module index at "${r}".`);return i}async function readCompiledManifest(e){let t=JSON.parse(await readFile(e,`utf8`));if(t.kind!==COMPILED_AGENT_MANIFEST_KIND)throw Error(`Invalid compiled agent manifest at "${e}".`);return t}function resolveInstrumentationModule(n){for(let r of INSTRUMENTATION_EXTENSIONS){let i=join(n,`instrumentation${r}`);if(existsSync(i))return i}}function createMaterializedModuleFileName(e,t,n){return`${createHash(`sha256`).update(e).update(`\0`).update(t).update(`\0`).update(n).digest(`hex`)}.mjs`}async function hashDirectoryIfPresent(r){if(!existsSync(r.path))return;let a=await lstat(r.path),l=toPortablePath(relative(r.root,r.path));if(a.isSymbolicLink()){r.fingerprint.update(l).update(`\0link\0`).update(await readlink(r.path)).update(`\0`);return}if(a.isDirectory()){for(let e of(await readdir(r.path)).sort())await hashDirectoryIfPresent({...r,path:join(r.path,e)});return}a.isFile()&&r.fingerprint.update(l).update(`\0file\0`).update(await readFile(r.path)).update(`\0`)}function toPortablePath(e){return e.split(sep).join(`/`)}export{materializeAuthoredModules,readMaterializedAuthoredModuleIndex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`;function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),n=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(n),a=await readOptionalFile(n);try{await writeFile(t,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:t,pointerPath:n,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:t,pointerPath:n,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(!(t===void 0||t.version===1))return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:r})}return t}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let r=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(r,t);try{await renameWithTransientBusyRetry(r,e)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`;function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),n=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(n),a=await readOptionalFile(n);try{await writeFile(t,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:t,pointerPath:n,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:t,pointerPath:n,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(!(t===void 0||t.version===1))return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}if(typeof r==`string`&&n===`sourceRoot`){t[n]=rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:r})}return t}function rewritePathWithinSourceRoot(e){return isPathInsideOrEqual(e.path,e.sourceRoot)?toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:e.path,sourceRoot:e.sourceRoot}):e.path}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let r=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(r,t);try{await renameWithTransientBusyRetry(r,e)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let a=Array.from(new Set([resolve(e),resolve(t)])),s=await findClosestVercelOutputDirectory(e);if(s!==void 0)try{let e=JSON.parse(await readFile(join(s,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:await resolveVercelOutputConfigRoot(s),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=e;for(;;){for(let e of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:e.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(c);if(e===c)return;c=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t,n){let i=await createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n});try{return await buildNitroOutput(i)}finally{await i.close()}}async function buildApplication(e,t){let n=await tryReadExtensionBuildConfig(e);if(n!==null)throw Error(`Package "${n.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let r=await createApplicationBuildWorkspace((await resolveDiscoveryProject(e)).appRoot,t.vercelServiceOutput?.serviceOutputDirectory),i=!1;try{return await buildApplicationInWorkspace(r,t)}catch(e){throw i=e instanceof RecoverablePublicationError,e}finally{i||await removeApplicationBuildWorkspace(r)}}async function buildApplicationInWorkspace(e,n){let i=await prepareProductionApplicationHost(e);if(!process.env.VERCEL){let t=await createProductionApplicationNitro(i,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`});try{await buildNitroOutput(t),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath}),await stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir})}finally{await t.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}let a=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot),o=await createProductionApplicationNitro(i,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`});try{await buildNitroOutput(o),n.skipVercelSandboxPrewarm||await runVercelBuildPrewarm({appRoot:i.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:i.appRoot}),log(e){console.log(e)}});let r=await buildVercelNitroSurface(i,e,`flow`);await emitVercelWorkflowFunctions({agentName:i.compileResult.manifest.config.name,appRoot:i.appRoot,compiledArtifactsBootstrapPath:i.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir}),a!==void 0&&await normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}),n.vercelServiceOutput!==void 0&&await copyHostMiddlewareFunctions({hostOutputDirectory:n.vercelServiceOutput.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath})}finally{await o.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
|
|
1
|
+
import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{toErrorMessage}from"#shared/errors.js";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let n=relative(e,t);return n.length===0||!n.startsWith(`..${sep}`)&&n!==`..`&&!isAbsolute(n)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let r=Array.from(new Set([resolve(e),resolve(t)])),a=await findClosestVercelOutputDirectory(e);if(a!==void 0)try{let e=JSON.parse(await readFile(join(a,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:await resolveVercelOutputConfigRoot(a),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let s=e;for(;;){for(let e of[join(s,`vercel.json`),join(s,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),i=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:e.endsWith(`vercel.json`)?s:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(s);if(e===s)return;s=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildVercelNitroSurface(e,t,n,r){let a=`nitro.${n}`,o=await measureBuildPhase(r,`${a}.create`,()=>createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n}));try{return await buildNitroOutput(o,r,a)}finally{await measureBuildPhase(r,`${a}.close`,()=>o.close())}}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let a=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),s=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(a.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),l=!1,u;try{u=await buildApplicationInWorkspace(s,t,r)}catch(e){throw l=e instanceof RecoverablePublicationError,e}finally{l||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(s))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:u,profileOutputPath:n,profiler:r}),u}async function buildApplicationInWorkspace(e,n,r){let a=await measureBuildPhase(r,`host.prepare`,()=>prepareProductionApplicationHost(e));if(!process.env.VERCEL){let t=await measureBuildPhase(r,`nitro.all.create`,()=>createProductionApplicationNitro(a,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`}));try{await buildNitroOutput(t,r,`nitro.all`),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),await measureBuildPhase(r,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(r,`nitro.all.close`,()=>t.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}let o=await measureBuildPhase(r,`vercel.service-prefix.resolve`,()=>resolveCoDeployedEveServicePrefixForVercelFunctionOutput(a.appRoot,a.compileResult.project.agentRoot)),s=await measureBuildPhase(r,`nitro.app.create`,()=>createProductionApplicationNitro(a,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`}));try{await buildNitroOutput(s,r,`nitro.app`),n.skipVercelSandboxPrewarm||await measureBuildPhase(r,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:a.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:a.appRoot}),log(e){console.log(e)}}));let i=await buildVercelNitroSurface(a,e,`flow`,r);await measureBuildPhase(r,`workflow.emit`,()=>emitVercelWorkflowFunctions({agentName:a.compileResult.manifest.config.name,appRoot:a.appRoot,compiledArtifactsBootstrapPath:a.compiledArtifacts.bootstrapPath,flowNitroOutputDir:i,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir})),o!==void 0&&await measureBuildPhase(r,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:o}));let c=n.vercelServiceOutput;c!==void 0&&await measureBuildPhase(r,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:c.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath}))}finally{await measureBuildPhase(r,`nitro.app.close`,()=>s.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
|
|
@@ -11,6 +11,8 @@ import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-wor
|
|
|
11
11
|
export type NitroBuildSurface = "all" | "app" | "flow";
|
|
12
12
|
/** Options for one production application build. */
|
|
13
13
|
export interface ApplicationBuildOptions {
|
|
14
|
+
/** Absolute path for an optional machine-readable profile of a successful build. */
|
|
15
|
+
readonly profileOutputPath?: string;
|
|
14
16
|
readonly skipVercelSandboxPrewarm: boolean;
|
|
15
17
|
readonly vercelServiceOutput?: {
|
|
16
18
|
readonly hostOutputDirectory: string;
|
package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames
|
|
1
|
+
import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";import{buildFrameworkToolInfo,getRootDelegationToolNames,renderChannel,renderDynamicResolver,renderSchedule,renderSubagent,toSource}from"#internal/nitro/routes/agent-info/build-agent-info-response.js";import{resolveModelEndpointStatus}from"#internal/resolve-model-endpoint-status.js";function buildAgentInfoResponseFromManifest(i,a){let o=i.manifest,s=o.channels.filter(e=>e.kind===`channel`),c=o.channels.filter(e=>e.kind===`disabled`).map(e=>e.name),l=new Set(o.tools.map(e=>e.name)),u=new Set(o.disabledFrameworkTools),d=getAllFrameworkToolNames(),f=getAllFrameworkChannelNames(),p=getFrameworkChannelDefinitions(),m=o.tools.map(e=>({...toSource(e),description:e.description,hasAuth:!1,hasCompactionHook:!1,hasExecute:!0,hasModelOutputProjection:!1,hasOutputSchema:e.outputSchema!==void 0&&e.outputSchema!==null,inputSchema:e.inputSchema,name:e.name,origin:`authored`,outputSchema:e.outputSchema??null,replacesFrameworkTool:d.has(e.name),requiresApproval:!1})),h=new Set(s.map(e=>e.name)),g=new Set(c),_=p.filter(e=>!h.has(e.name)&&!g.has(e.name)),v=buildFrameworkToolInfo({authoredToolNames:l,delegationToolNames:getRootDelegationToolNames(o),disabledFrameworkToolNames:u}),y=s.map(e=>({...toSource(e),adapterKind:e.adapterKind,method:e.method,name:e.name,origin:`authored`,urlPath:e.urlPath}));return{agent:{agentRoot:o.agentRoot,appRoot:o.appRoot,configSource:o.config.source?toSource(o.config.source):void 0,description:o.config.description,model:{contextWindowTokens:o.config.model.contextWindowTokens,id:o.config.model.id,providerOptions:o.config.model.providerOptions,source:o.config.model.source?toSource(o.config.model.source):void 0,routing:o.config.model.routing,endpoint:resolveModelEndpointStatus(o.config.model.routing,a.gatewayCredentials)},name:o.config.name,outputSchema:o.config.outputSchema},capabilities:{devRoutes:a.mode===`development`},channels:{authored:y,available:[..._.map(e=>renderChannel(e,{origin:`framework`})),...y],disabledFramework:c,framework:p.filter(e=>f.has(e.name)).map(e=>{let t=h.has(e.name),n=g.has(e.name),r=n?`disabled`:t?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:n,replacedByAuthoredChannel:t,status:r}})},connections:o.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:!1,hasAuthorization:e.vercelConnect!==void 0,hasHeaders:!1,protocol:e.protocol,url:e.url})),diagnostics:{discoveryErrors:o.diagnosticsSummary.errors,discoveryWarnings:o.diagnosticsSummary.warnings},hooks:o.hooks.map(e=>({...toSource(e),eventNames:[],slug:e.slug})),instructions:{dynamic:o.dynamicInstructions.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:o.instructions===void 0?null:{...toSource(o.instructions),markdown:o.instructions.markdown,name:o.instructions.name}},kind:`eve-agent-info`,mode:a.mode,sandbox:o.sandbox===null?null:{...toSource(o.sandbox),description:o.sandbox.description,hasBootstrap:!1,hasOnSession:!1,revalidationKey:o.sandbox.revalidationKey,sourceHash:o.sandbox.sourceHash},schedules:i.schedules.map(renderSchedule),skills:{static:o.skills.map(e=>({...toSource(e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name})),dynamic:o.dynamicSkills.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:o.subagents.map(renderSubagent),total:o.subagents.length},tools:{available:[...v.available,...m],authored:m,disabledFramework:[...o.disabledFrameworkTools],dynamic:[...o.connections.length>0?[renderDynamicResolver(createConnectionSearchResolver(),{origin:`framework`})]:[],...o.dynamicTools.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:v.framework,reserved:[WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]},version:1,workflow:{enabled:o.workflowTool!==void 0,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:o.workspaceResourceRoot,rootEntries:[...o.workspaceResourceRoot.rootEntries]}}}export{buildAgentInfoResponseFromManifest};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentInfoData, CompiledSubagentNode, ResolvedScheduleDefinition } from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
|
|
1
|
+
import type { AgentInfoData, CompiledAgentManifest, CompiledSubagentNode, ResolvedScheduleDefinition } from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
|
|
2
2
|
import type { ResolvedChannelDefinition, ResolvedToolDefinition } from "#runtime/types.js";
|
|
3
3
|
import type { ModelRouting } from "#shared/agent-definition.js";
|
|
4
4
|
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
|
|
@@ -171,6 +171,12 @@ export interface AgentInfoResponse {
|
|
|
171
171
|
export declare function buildAgentInfoResponse(data: AgentInfoData, input: {
|
|
172
172
|
readonly mode: AgentInfoResponse["mode"];
|
|
173
173
|
}): AgentInfoResponse;
|
|
174
|
+
export declare function buildFrameworkToolInfo(input: {
|
|
175
|
+
readonly authoredToolNames: ReadonlySet<string>;
|
|
176
|
+
readonly delegationToolNames: ReadonlySet<string>;
|
|
177
|
+
readonly disabledFrameworkToolNames: ReadonlySet<string>;
|
|
178
|
+
}): Pick<AgentInfoTools, "available" | "framework">;
|
|
179
|
+
export declare function getRootDelegationToolNames(manifest: CompiledAgentManifest): ReadonlySet<string>;
|
|
174
180
|
export declare function renderChannel(channel: ResolvedChannelDefinition, input: {
|
|
175
181
|
readonly origin: "authored" | "framework";
|
|
176
182
|
}): AgentInfoChannelEntry;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames
|
|
1
|
+
import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolDefinitions,getAllFrameworkToolNames}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";function buildAgentInfoResponse(e,t){let r=e.agent,i=buildToolInfo(r,getRootDelegationToolNames(e.manifest));return{agent:{agentRoot:r.metadata.agentRoot,appRoot:r.metadata.appRoot,configSource:r.config.source?toSource(r.config.source):void 0,description:r.config.description,model:{contextWindowTokens:r.config.model.contextWindowTokens,id:r.config.model.id,providerOptions:r.config.model.providerOptions,source:r.config.model.source?toSource(r.config.model.source):void 0},name:r.config.name,outputSchema:r.config.outputSchema},capabilities:{devRoutes:t.mode===`development`},channels:buildChannelInfo(r),connections:r.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:e.approval!==void 0,hasAuthorization:e.authorization!==void 0,hasHeaders:e.headers!==void 0,protocol:e.protocol,toolFilter:e.tools,url:e.url})),diagnostics:{discoveryErrors:r.metadata.diagnosticsSummary.errors,discoveryWarnings:r.metadata.diagnosticsSummary.warnings},hooks:r.hooks.map(e=>({...toSource(e),eventNames:Object.keys(e.events).sort(),slug:e.slug})),instructions:{dynamic:r.dynamicInstructionsResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:r.instructions?{...toSource(r.instructions),markdown:r.instructions.markdown,name:r.instructions.name}:null},kind:`eve-agent-info`,mode:t.mode,sandbox:renderSandbox(r.sandbox),schedules:e.schedules.map(renderSchedule),skills:{static:r.skills.map(renderSkill),dynamic:r.dynamicSkillResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:e.manifest.subagents.map(renderSubagent),total:e.manifest.subagents.length},tools:i,version:1,workflow:{enabled:r.workflowTool!==void 0,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:r.workspaceResourceRoot,rootEntries:[...r.workspaceSpec.rootEntries]}}}function buildChannelInfo(e){let t=new Set(e.channels.map(e=>e.name)),n=new Set(e.disabledFrameworkChannels),a=getAllFrameworkChannelNames(),o=getFrameworkChannelDefinitions(),s=o.filter(e=>!t.has(e.name)&&!n.has(e.name)),c=e.channels.map(e=>renderChannel(e,{origin:`authored`})),l=o.map(e=>{let r=t.has(e.name),i=n.has(e.name),a=i?`disabled`:r?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:i,replacedByAuthoredChannel:r,status:a}});return{authored:c,available:[...s.map(e=>renderChannel(e,{origin:`framework`})),...c],disabledFramework:[...e.disabledFrameworkChannels],framework:l.filter(e=>a.has(e.name))}}function buildToolInfo(e,r){let i=new Set(e.tools.map(e=>e.name)),a=new Set(e.disabledFrameworkTools),c=getAllFrameworkToolNames(),l=e.connections.length>0?[createConnectionSearchResolver()]:[],u=e.tools.map(e=>renderTool(e,{origin:`authored`,replacesFrameworkTool:c.has(e.name)})),d=buildFrameworkToolInfo({authoredToolNames:i,delegationToolNames:r,disabledFrameworkToolNames:a});return{available:[...d.available,...u],authored:u,disabledFramework:[...e.disabledFrameworkTools],dynamic:[...l.map(e=>renderDynamicResolver(e,{origin:`framework`})),...e.dynamicToolResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:d.framework,reserved:[WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]}}function buildFrameworkToolInfo(e){let t=new Set([...e.authoredToolNames,...e.delegationToolNames]),n=[],r=[];for(let i of getAllFrameworkToolDefinitions()){let a=e.disabledFrameworkToolNames.has(i.name),o=e.authoredToolNames.has(i.name),s=a?`disabled`:t.has(i.name)?`replaced`:`active`,c=renderTool(i,{origin:`framework`,replacesFrameworkTool:!1});s===`active`&&n.push(c),r.push({...c,disabledByAuthor:a,replacedByAuthoredTool:o,status:s})}return{available:n,framework:r}}function getRootDelegationToolNames(t){let n=new Set(t.subagentEdges.filter(t=>t.parentNodeId===ROOT_COMPILED_AGENT_NODE_ID).map(e=>e.childNodeId));return new Set([...t.subagents.filter(e=>n.has(e.nodeId)).map(e=>e.name),...t.remoteAgents.map(e=>e.name)])}function renderChannel(e,t){return{...toSource(e),adapterKind:e.adapter?.kind,method:e.method,name:e.name,origin:t.origin,urlPath:e.urlPath}}function renderTool(e,t){return{...toSource(e),description:e.description,hasAuth:!1,hasExecute:e.execute!==void 0,hasModelOutputProjection:e.toModelOutput!==void 0,hasOutputSchema:e.outputSchema!==void 0&&e.outputSchema!==null,inputSchema:e.inputSchema,name:e.name,origin:t.origin,outputSchema:e.outputSchema,replacesFrameworkTool:t.replacesFrameworkTool,requiresApproval:e.approval!==void 0}}function renderSkill(e){return{...toSource(e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}}function renderSchedule(e){return{...toSource(e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name}}function renderSandbox(e){return e===null?null:{...toSource(e),backendKind:resolveBackendKind(e.backend),description:e.description,hasBootstrap:e.bootstrap!==void 0,hasOnSession:e.onSession!==void 0,revalidationKey:e.revalidationKey,sourceHash:e.sourceHash}}function renderSubagent(e){return{...toSource(e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,rootPath:e.rootPath,summary:{channels:e.agent.channels.length,connections:e.agent.connections.length,hooks:e.agent.hooks.length,instructions:e.agent.instructions!==void 0,schedules:e.agent.schedules.length,skills:e.agent.skills.length,tools:e.agent.tools.length}}}function renderDynamicResolver(e,t){return{...toSource(e),eventNames:[...e.eventNames],origin:t.origin,slug:e.slug}}function toSource(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:e.sourceKind}}function resolveBackendKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`?t:void 0}export{buildAgentInfoResponse,buildFrameworkToolInfo,getRootDelegationToolNames,renderChannel,renderDynamicResolver,renderSchedule,renderSubagent,renderTool,toSource};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`}
|
|
1
|
+
import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{attachAgentInfoRouteResponse,attachRouteAgent}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`},m=createRouteAgent(n.runtime,c);return{agent:m,args:attachRouteAgent(attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),m),backgroundTasks:u}}function createRouteAgent(e,t){return{async cancelTurn(t){return await e.cancelTurn(t)},async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
|