eve 0.60.1 → 0.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/src/chunks/{use-eve-agent-Dmc6sX4d.js → use-eve-agent-C5-yqRuq.js} +177 -85
- package/dist/src/chunks/{use-eve-agent-jSR8P4nK.js → use-eve-agent-CVWk5KKy.js} +177 -85
- package/dist/src/cli/agent-command.js +1 -1
- package/dist/src/cli/dev/local-server-child.js +1 -1
- package/dist/src/cli/dev/tui/runner.js +2 -2
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/client/client.d.ts +3 -1
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/eve-agent-projection.d.ts +1 -0
- package/dist/src/client/eve-agent-projection.js +1 -1
- package/dist/src/client/eve-agent-store-helpers.js +1 -1
- package/dist/src/client/eve-agent-store-state.d.ts +4 -1
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/message-response.d.ts +5 -0
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/optimistic-message-submissions.d.ts +22 -0
- package/dist/src/client/optimistic-message-submissions.js +1 -0
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +7 -7
- package/dist/src/compiled/@eve/catalog/index.js +1 -1
- package/dist/src/compiled/@workflow/core/index.js +1 -1
- package/dist/src/compiled/@workflow/core/log-format.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime.js +5 -3
- package/dist/src/compiled/@workflow/core/serialization.js +1 -1
- package/dist/src/compiled/@workflow/core/types.d.ts +22 -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/world/runs.d.ts +12 -1
- package/dist/src/compiled/@workflow/world-local/index.js +3 -3
- package/dist/src/compiled/@workflow/world-vercel/index.js +7 -7
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-3SKHZsSX.js → attribute-changes-A6HfMNG3.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-DearXsdS.js → dist-D38gP7YF.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/frames-QcJfYHmh.js +3 -0
- package/dist/src/compiled/_chunks/workflow/helpers-6kObVbfS.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{logger-CxBCNokg.js → logger-NN5YHpYy.js} +6 -5
- package/dist/src/compiled/_chunks/workflow/{resume-hook-B7_MC7FC.js → resume-hook-CAqlhwic.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{run-jGFog1uQ.js → run-DJevv8zz.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{serialization-VRHEKI6l.js → serialization-C5KgPESk.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/sleep-CbUwdv6O.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{wait-until-DDJySKt-.js → wait-until-BMY_tOr-.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{ws-transport-CEFNBXPC.js → ws-transport-DSDcKH08.js} +1 -1
- package/dist/src/compiler/default-tool-policy.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +18 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +5 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/compiler/validate-artifact.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-metadata.d.ts +1 -0
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/agent-router.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/metadata.js +1 -1
- package/dist/src/execution/tools/workflow/step-execution.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/authored-runtime-modules.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +1 -0
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/nitro/host.js +1 -1
- package/dist/src/internal/node-esm-compat-banner.js +3 -3
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/internal/workflow-bundle/nitro-step-entry.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/nitro-step-entry.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
- package/dist/src/protocol/message.d.ts +4 -0
- package/dist/src/protocol/message.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/tools/registry.js +1 -1
- package/dist/src/services/dev-client/agent-info-probe.d.ts +1 -0
- package/dist/src/services/dev-client/agent-info-probe.js +1 -1
- package/dist/src/setup/primitives/pm/pnpm.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/map-concurrent.d.ts +2 -0
- package/dist/src/shared/map-concurrent.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +2 -0
- package/dist/src/tools/dynamic.d.ts +1 -0
- package/dist/src/tools/provided/agent-router.d.ts +1 -1
- package/dist/src/tools/provided/agent-router.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +5 -3
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +32 -32
- package/docs/guides/client/overview.mdx +2 -0
- package/docs/guides/frontend/overview.mdx +7 -3
- package/docs/reference/typescript-api.md +1 -1
- package/docs/subagents/index.mdx +3 -3
- package/docs/tools/overview.mdx +17 -0
- package/docs/tools/workflows.mdx +46 -23
- package/package.json +7 -7
- package/dist/src/compiled/_chunks/workflow/frames-Bm_yZi8X.js +0 -3
- package/dist/src/compiled/_chunks/workflow/helpers-K7otPd_U.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-60eDbac6.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{executeAgentRouterTool}from"#execution/tools/agent-router-workflow.js";const AGENT_ROUTER_TOOL_DESCRIPTION=`Route a task to the best available subagent based on each subagent's declared description.`,AGENT_ROUTER_INPUT_SCHEMA=z.strictObject({message:z.string().min(1).describe(`The complete task to send to the selected agent.`),outputSchema:z.
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{executeAgentRouterTool}from"#execution/tools/agent-router-workflow.js";const AGENT_ROUTER_TOOL_DESCRIPTION=`Route a task to the best available subagent based on each subagent's declared description.`,AGENT_ROUTER_INPUT_SCHEMA=z.strictObject({message:z.string().min(1).describe(`The complete task to send to the selected agent.`),outputSchema:z.looseObject({}).describe(`Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The selected agent must match a provided schema, and that structured output becomes the tool result.`).optional()});export{AGENT_ROUTER_INPUT_SCHEMA,AGENT_ROUTER_TOOL_DESCRIPTION,executeAgentRouterTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.
|
|
1
|
+
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.61.1//executeSleepTool`;export{executeSleepTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{createHook}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{readWorkflowToolRunOwner,readWorkflowToolRunRef}from"#execution/tools/workflow/ask.js";async function agent(e,t,n){return readWorkflowToolRunRef(e),validateAgentInput({...n,target:t}),await invokeAgent(e,{agentId:n.agentId,message:n.message,outputSchema:n.outputSchema,target:t})}async function invokeAgent(e,t,n={}){validateAgentInput(t);let r=readWorkflowToolRunRef(e),i=readWorkflowToolRunOwner(e),a=createHook(),o=n.invocationId??`${e.callId}:${a.token}`;try{await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{input:t,invocationId:o,kind:`agent-invoke`}});let s=a[Symbol.asyncIterator]();for(;;){let t=await nextAgentReply(s,e.abortSignal);if(t.done)break;let c=t.value;if(c.kind===`runtime-action-result`){let e=c.results.find(e=>e.kind===`subagent-result`&&e.callId===o);if(e!==void 0){if(e.origin===`child`&&await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{kind:`agent-settled`,result:e}}),n.returnResult===!0&&r.execution===`blocking`)return e;if(e.isError===!0)throw e.output;return e.output}continue}if(c.kind===`subagent-input-request`){await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:c.childSessionInbox?.sessionId===c.childSessionId?sessionInboxHookToken(sessionCommandHookToken(c.childSessionInbox.sessionId)):c.childContinuationToken,request:{kind:`input-batch`,requests:c.event.requests},requestCoordinates:{sequence:c.event.sequence,stepIndex:c.event.stepIndex,turnId:c.event.turnId}});continue}await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{event:c,kind:`authorization-request`}})}}finally{try{await disposeHook(a)}catch{}}throw Error(`Agent "${t.target}" closed without a result.`)}async function nextAgentReply(e,t){if(t===void 0)return await e.next();if(t.aborted)throw t.reason;let n,r=new Promise((e,t)=>{n=t}),abort=()=>n?.(t.reason);t.addEventListener(`abort`,abort,{once:!0});try{return await Promise.race([e.next(),r])}finally{t.removeEventListener(`abort`,abort)}}function validateAgentInput(e){if(typeof e.target!=`string`||e.target.trim()===``)throw TypeError(`agent() requires a non-empty agent name as its first argument.`);if(typeof e.message!=`string`||e.message.trim()===``)throw TypeError("agent() requires a non-empty `message`.")}export{agent,invokeAgent,validateAgentInput};
|
|
1
|
+
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{createHook}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{readWorkflowToolRunOwner,readWorkflowToolRunRef}from"#execution/tools/workflow/ask.js";async function agent(e,t,n){return readWorkflowToolRunRef(e),validateAgentInput({...n,target:t}),await invokeAgent(e,{agentId:n.agentId,message:n.message,outputSchema:n.outputSchema,target:t})}async function invokeAgent(e,t,n={}){validateAgentInput(t);let r=readWorkflowToolRunRef(e),i=readWorkflowToolRunOwner(e),a=createHook(),o=n.invocationId??`${e.callId}:${a.token}`;try{await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{input:t,invocationId:o,kind:`agent-invoke`}});let s=a[Symbol.asyncIterator]();for(;;){let t=await nextAgentReply(s,e.abortSignal);if(t.done)break;let c=t.value;if(c.kind===`runtime-action-result`){let e=c.results.find(e=>e.kind===`subagent-result`&&e.callId===o);if(e!==void 0){if(e.origin===`child`&&await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{kind:`agent-settled`,result:e}}),n.returnResult===!0&&r.execution===`blocking`)return e;if(e.isError===!0)throw e.output;return e.output}continue}if(c.kind===`subagent-input-request`){await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:c.childSessionInbox?.sessionId===c.childSessionId?sessionInboxHookToken(sessionCommandHookToken(c.childSessionInbox.sessionId)):c.childContinuationToken,request:{kind:`input-batch`,requests:c.event.requests},requestCoordinates:{sequence:c.event.sequence,stepIndex:c.event.stepIndex,turnId:c.event.turnId}});continue}await resumeHookStep(i.inbox,{kind:`request`,from:r,replyTo:a.token,request:{event:c,kind:`authorization-request`}})}}finally{try{await disposeHook(a)}catch{}}throw Error(`Agent "${t.target}" closed without a result.`)}async function nextAgentReply(e,t){if(t===void 0)return await e.next();if(t.aborted)throw t.reason;let n,r=new Promise((e,t)=>{n=t}),abort=()=>n?.(t.reason);t.addEventListener(`abort`,abort,{once:!0});try{return await Promise.race([e.next(),r])}finally{t.removeEventListener(`abort`,abort)}}function validateAgentInput(e){if(typeof e.target!=`string`||e.target.trim()===``)throw TypeError(`agent() requires a non-empty agent name as its first argument.`);if(typeof e.message!=`string`||e.message.trim()===``)throw TypeError("agent() requires a non-empty `message`.");if(e.outputSchema!==void 0&&(typeof e.outputSchema!=`object`||e.outputSchema===null||Array.isArray(e.outputSchema)))throw TypeError("agent() `outputSchema` must be a JSON Schema object.")}export{agent,invokeAgent,validateAgentInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";function resolveWorkflowAgentMetadata(e){let t=e.get(BundleKey);if(t===void 0)return{};let n=new Map;for(let[e,r]of t.subagentRegistry.subagentsByName??[]){let t=r.definition.description;t!==void 0&&n.set(e,{description:t})}let r=effectiveDynamicSelections(e);for(let e of Object.values(r))e!==null&&n.set(e.prepared.name,{description:e.kind===`subagent`?e.agentConfig.description:e.remoteAgent.description});return Object.fromEntries(n)}function effectiveDynamicSelections(e){return{...e.get(SessionDynamicSubagentSelectionsKey),...e.get(TurnDynamicSubagentSelectionsKey)}}export{resolveWorkflowAgentMetadata};
|
|
1
|
+
import{ParentSessionKey,SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";function resolveWorkflowAgentMetadata(e){let t=e.get(BundleKey);if(t===void 0)return{};let n=new Map;t.nodeId===void 0&&e.get(ParentSessionKey)===void 0&&n.set(AGENT_TOOL_NAME,{description:t.resolvedAgent.config?.description??``});for(let[e,r]of t.subagentRegistry.subagentsByName??[]){let t=r.definition.description;t!==void 0&&n.set(e,{description:t})}let r=effectiveDynamicSelections(e);for(let e of Object.values(r))e!==null&&n.set(e.prepared.name,{description:e.kind===`subagent`?e.agentConfig.description:e.remoteAgent.description});return Object.fromEntries(n)}function effectiveDynamicSelections(e){return{...e.get(SessionDynamicSubagentSelectionsKey),...e.get(TurnDynamicSubagentSelectionsKey)}}export{resolveWorkflowAgentMetadata};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SessionIdKey,SessionKey}from"#context/keys.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;return i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults),contextStorage.run(i,async()=>{let a=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization}),o={...buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}}),getToken:a.getToken,requireAuth:a.requireAuth},s;try{s=await a.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?o:e)))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}let c=i.get(PendingAuthorizationResultKey)??[],l=r.authorizationResults.filter(e=>!c.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(s)?{kind:`authorization-required`,signal:s,authorized:l}:{kind:`result`,output:s,authorized:l}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}export{withWorkflowStepAuthorization};
|
|
1
|
+
import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SessionIdKey,SessionKey}from"#context/keys.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;return i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults),contextStorage.run(i,async()=>{let a=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization}),o={...buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}}),agent:()=>unavailableInStep(`ctx.agent()`,`Call ctx.agent() in the workflow body.`),ask:()=>unavailableInStep(`ctx.ask()`,`Call ctx.ask() in the workflow body.`),getToken:a.getToken,requireAuth:a.requireAuth};Object.defineProperty(o,"agents",{get:()=>unavailableInStep(`ctx.agents`,`Read ctx.agents in the workflow body and pass the required serializable metadata into the step.`)});let s;try{s=await a.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?o:e)))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}let c=i.get(PendingAuthorizationResultKey)??[],l=r.authorizationResults.filter(e=>!c.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(s)?{kind:`authorization-required`,signal:s,authorized:l}:{kind:`result`,output:s,authorized:l}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}function unavailableInStep(e,t){throw Object.assign(Error(`${e} is unavailable inside a "use step" function. ${t}`),{fatal:!0})}export{withWorkflowStepAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableToolDefinitions(e.tools,e.session):filterUnavailableToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){return{harnessTools:filterUnavailableToolMap(e.tools,e.session),modelTools:e.modelTools,session:e.session}}function filterUnavailableToolDefinitions(e,t){let n=[];for(let r of e)shouldHideTool(r,t)||n.push(r);return n}function filterUnavailableToolMap(e,t){let n=new Map;for(let[r,i]of e)shouldHideTool(i,t)||n.set(r,i);return n}function shouldHideTool(e,t){let n=t.rootSessionId!==void 0;return e.rootOnly===!0||e.behavior?.availability.includes(`root-session`)===!0?n:e.behavior?.availability.includes(`delegated-task-child`)===!0&&t.taskId===void 0}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
1
|
+
function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableToolDefinitions(e.tools,e.session):filterUnavailableToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){return{harnessTools:filterUnavailableToolMap(e.tools,e.session),modelTools:e.modelTools,session:e.session}}function filterUnavailableToolDefinitions(e,t){let n=[];for(let r of e)shouldHideTool(r,t)||n.push(r);return n}function filterUnavailableToolMap(e,t){let n=new Map;for(let[r,i]of e)shouldHideTool(i,t)||n.set(r,i);return n}function shouldHideTool(e,t){let n=t.rootSessionId!==void 0;return e.rootOnly===!0||e.availableInSubagents===!1||e.behavior?.availability.includes(`root-session`)===!0?n:e.behavior?.availability.includes(`delegated-task-child`)===!0&&t.taskId===void 0}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{collectActionPresentation,createPresentedRuntimeActionRequestFromToolCall}from"#harness/action-presentation.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{projectDeltaPresentation,projectResultPresentation}from"#harness/tool-presentation.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{normalizeAssistantStepFinishReason}from"#harness/finish-reason.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r,i,a){let o=n.turnId!==``,s=o?n.turnId:`turn_${n.sequence}`;n.sessionStarted||await e(createSessionStartedEvent({runtime:i,trace:a})),o||await e(createTurnStartedEvent({sequence:n.sequence,trace:a,turnId:s}),r),t.message!==void 0
|
|
1
|
+
import{createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{frameworkMessageKindForStepInput}from"#harness/messages.js";import{collectActionPresentation,createPresentedRuntimeActionRequestFromToolCall}from"#harness/action-presentation.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{projectDeltaPresentation,projectResultPresentation}from"#harness/tool-presentation.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{normalizeAssistantStepFinishReason}from"#harness/finish-reason.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r,i,a){let o=n.turnId!==``,s=o?n.turnId:`turn_${n.sequence}`;if(n.sessionStarted||await e(createSessionStartedEvent({runtime:i,trace:a})),o||await e(createTurnStartedEvent({sequence:n.sequence,trace:a,turnId:s}),r),t.message!==void 0){let r=frameworkMessageKindForStepInput(t);await e(createMessageReceivedEvent({kind:r===`execution.background_task`?r:void 0,message:t.message,sequence:n.sequence,turnId:s}))}let c={sessionStarted:!0,sequence:n.sequence,stepIndex:o?n.stepIndex:0,turnId:s};return o&&n.assistantOutputStarted?{...c,assistantOutputStarted:!0}:c}async function emitStepStarted(e,t,n,r){await e(createStepStartedEvent({modelId:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),r)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function readSubagentBackgroundTaskReceipt(e,t){if(e.isError===!0||t?.get(e.toolName)?.resultKind!==`subagent`||typeof e.output!=`object`||e.output===null||Array.isArray(e.output))return;let n=Reflect.get(e.output,`status`),r=Reflect.get(e.output,`taskId`);return n===`working`&&typeof r==`string`?{status:n,taskId:r}:void 0}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(e,t,n,r,i){let a=``,o=``,s=`stop`,c,l=new Set,u=new Set,d=new Set,f=new Set,p=new Set,m=new Set,h=[],g=[],_=new Map,v=new Map,flushCurrentMessage=async()=>{o.length!==0&&(await e(createMessageCompletedEvent({finishReason:`tool-calls`,message:o,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),o=``)},emitActionInput=async(n,r,i)=>e(createActionInputAppendedEvent({callId:n,inputTextDelta:i,sequence:t.sequence,stepIndex:t.stepIndex,toolName:r,turnId:t.turnId})),emitActionRequest=async n=>{let{action:r}=n;u.has(r.callId)||(o.trim().length>0&&await flushCurrentMessage(),u.add(r.callId),_.set(r.callId,r.input),await e(createActionsRequestedEvent({actions:[r],presentation:collectActionPresentation([n]),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})))},collectProviderToolCall=async e=>{if(f.has(e.toolCallId)||(f.add(e.toolCallId),u.has(e.toolCallId)))return;u.add(e.toolCallId),o.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e,i?.tools??new Map);if(t.toolError!==void 0){m.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),p.add(e.toolCallId),g.push(createToolResultMessagePartFromToolError(t.toolError));return}_.set(t.request.action.callId,t.request.action.input),r.observe(t.request)},emitActionResult=async n=>{if(d.has(n.callId))return;d.add(n.callId);let r=readSubagentBackgroundTaskReceipt(n,i?.tools);r!==void 0&&await e({data:{backgroundTask:r,callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.toolName},type:`subagent.completed`});let a=n.isError===!0?void 0:projectResultPresentation(i?.tools.get(n.toolName),n.callId,_.get(n.callId),n.output);await e(createActionResultEvent({presentation:a,result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}))},emitActionPartial=async n=>{let r=projectDeltaPresentation(i?.tools.get(n.toolName),n.callId,_.get(n.callId),n.output);await e(createActionPartialEvent({presentation:r,result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}))},emitToolCall=async e=>{if(isInvalidToolCall(e)){m.add(e.toolCallId);return}if(!(i===void 0||i.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createPresentedRuntimeActionRequestFromToolCall({toolCall:e,tools:i.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});m.add(e.toolCallId),o.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),p.add(e.toolCallId),g.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let d of n)if(c===void 0)switch(d.type){case`reasoning-delta`:await r.flush(),a+=d.text,await e(createReasoningAppendedEvent({reasoningDelta:d.text,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}));break;case`text-delta`:await r.flush(),a.trim().length>0&&(await e(createReasoningCompletedEvent({reasoning:a,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),a=``),o+=d.text,await e(createMessageAppendedEvent({messageDelta:d.text,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}));break;case`tool-input-start`:if(i===void 0||d.providerExecuted===!0||i.excludedActionToolNames.has(d.toolName)){v.delete(d.id);break}await r.flush(),o.trim().length>0&&await flushCurrentMessage(),v.set(d.id,{toolName:d.toolName});break;case`tool-input-delta`:{let e=v.get(d.id);if(e===void 0)break;await r.flush(),await emitActionInput(d.id,e.toolName,d.delta);break}case`tool-input-end`:v.delete(d.id);break;case`tool-call`:{let e=d;v.delete(e.toolCallId),l.add(e.toolCallId),e.providerExecuted===!0?await collectProviderToolCall(e):(await r.flush(),await emitToolCall(e));break}case`tool-result`:{let e=d;if(e.preliminary===!0){e.providerExecuted!==!0&&await emitActionPartial(createRuntimeToolResultFromStepResult(e));break}if(e.providerExecuted===!0){await collectProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await r.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(l.has(d.toolCallId)){if(isInlineAuthorizationToolResult(e))break;u.has(d.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),p.add(d.toolCallId));break}if(await r.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){p.add(d.toolCallId),h.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),p.add(d.toolCallId);break}case`tool-error`:{let e=d;e.providerExecuted===!0?(await collectProviderToolCall(e),await r.flush(),await emitActionResult(createRuntimeToolResultFromToolError(e))):u.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(e)),p.add(e.toolCallId),g.push(createToolResultMessagePartFromToolError(e)));break}case`finish-step`:s=normalizeAssistantStepFinishReason(d.finishReason),await r.flush();break;case`error`:c=normalizeModelStreamError(d.error);break;case`abort`:throw new DOMException(d.reason??`The model stream was aborted.`,`AbortError`)}if(await r.flush(),c!==void 0)throw c;return a.trim().length>0&&await e(createReasoningCompletedEvent({reasoning:a,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),s!==`content-filter`&&s!==`tool-calls`&&hasEmptyDeliverySentinel(o)?await e(createMessageCompletedEvent({finishReason:s,message:null,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})):s!==`content-filter`&&o.trim().length>0&&await e(createMessageCompletedEvent({finishReason:s,message:o,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),{emittedActionCallIds:u,handledInlineToolResultCallIds:p,invalidInputToolCallIds:m,inlineAuthorizationResults:h,trailingInlineToolResultParts:g}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState};
|
|
@@ -17,6 +17,7 @@ export type HarnessRuntimeActionDefinition = {
|
|
|
17
17
|
* Unified harness-owned tool definition.
|
|
18
18
|
*/
|
|
19
19
|
export interface HarnessToolDefinition {
|
|
20
|
+
readonly availableInSubagents?: boolean;
|
|
20
21
|
readonly label?: InternalToolLabelDefinition;
|
|
21
22
|
readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;
|
|
22
23
|
readonly behavior?: PreparedToolBehavior;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.61.1`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(e){return createRequire(e).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),r=tryResolveDirectBuildLocation(n);if(r!==void 0)return r;let i=findNearestVerifiedPackageRoot(dirname(n));if(i!==void 0&&isSourceCheckout(i))return{packageBuildRoot:null,packageRoot:i};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let a=i===void 0?void 0:tryCreatePackageLocation(i);if(a!==void 0)return a;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(typeof t.name==`string`&&typeof t.version==`string`)return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{serializeInputSchema,serializeOutputSchema}from"#tools/schema.js";import{isDisabledToolSentinel}from"#tools/definition.js";import{readWorkflowFunctionId}from"#internal/workflow/reference.js";import{assertResolverOnlyDynamicSentinel,isDynamicSentinel}from"#dynamic/definition.js";import{isWorkflowToolDefinition}from"#tools/workflow-definition.js";import{shouldRebindDynamicCallbacks}from"#internal/dynamic-tool-rebind.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{isWebSearchToolDefinition}from"#tools/provided/web-search.js";import{readToolBehavior}from"#tools/behavior.js";import{readWorkflowProgramOptions}from"#tools/workflow-program-input.js";function normalizeToolDefinition(e,t){if(isDynamicSentinel(e))return assertResolverOnlyDynamicSentinel(e,t),{kind:`dynamic-tool`,eventNames:Object.keys(e.events),rebindMissingCallbacks:shouldRebindDynamicCallbacks(e)};if(isDisabledToolSentinel(e))return{kind:`disabled`};if(isWebSearchToolDefinition(e)){let n=expectObjectRecord(e,t);expectOnlyKnownKeys(n,[`kind`,`provider`],t);let r=expectString(n.provider,t);if(r!==`exa`&&r!==`parallel`)throw Error(`${t} Expected "provider" to be one of: exa, parallel.`);return{kind:`web-search-tool`,provider:r}}let n=expectObjectRecord(e,t),r=readWorkflowFunctionId(n.execute);if(isWorkflowToolDefinition(e)){if(r===void 0)throw Error(`${t} defineWorkflowTool() requires a compiled workflow executor. Start execute with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`)}else if(r!==void 0)throw Error(`${t} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`);expectOnlyKnownKeys(n,[`label`,`auth`,`description`,`execute`,`execution`,`inputSchema`,`approval`,`approvalKey`,`outputSchema`,`toModelOutput`],t);let i=n.inputSchema===void 0?null:serializeInputSchema(n.inputSchema),a=serializeOutputSchema(n.outputSchema),o=readToolBehavior(e),s=readWorkflowProgramOptions(e),c=n.execute!==void 0;!c&&o?.handling?.kind!==`dispatch`&&o?.handling?.kind!==`request-input`&&expectFunction(n.execute,t);let l={description:expectString(n.description,t),hasApproval:n.approval!==void 0,hasExecute:c,hasModelOutputProjection:n.toModelOutput!==void 0,inputSchema:i};if(o!==void 0&&(l.behavior=o),s!==void 0&&(l.workflowProgram=s),c&&(l.execute=expectFunction(n.execute,t)),n.execution!==void 0){if(!c)throw Error(`${t} Execute-less native tools cannot use background execution.`);let e=expectString(n.execution,t);if(e!==`background`)throw Error(`${t} Expected "execution" to be "background".`);l.execution=e}if(a!==void 0&&(l.outputSchema=a),n.label!==void 0){let e=expectObjectRecord(n.label,t);expectOnlyKnownKeys(e,[`start`,`complete`,`delta`],t),expectFunction(e.start,t),e.complete!==void 0&&expectFunction(e.complete,t),e.delta!==void 0&&expectFunction(e.delta,t)}if(n.approval!==void 0&&normalizeApproval(n.approval,t),n.approvalKey!==void 0&&expectFunction(n.approvalKey,t),n.toModelOutput!==void 0&&expectFunction(n.toModelOutput,t),n.auth!==void 0){let e=expectObjectRecord(n.auth,t);expectFunction(e.getToken,t)}return{kind:`tool`,definition:l}}export{normalizeToolDefinition};
|
|
1
|
+
import{expectBoolean,expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{serializeInputSchema,serializeOutputSchema}from"#tools/schema.js";import{isDisabledToolSentinel}from"#tools/definition.js";import{readWorkflowFunctionId}from"#internal/workflow/reference.js";import{assertResolverOnlyDynamicSentinel,isDynamicSentinel}from"#dynamic/definition.js";import{isWorkflowToolDefinition}from"#tools/workflow-definition.js";import{shouldRebindDynamicCallbacks}from"#internal/dynamic-tool-rebind.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{isWebSearchToolDefinition}from"#tools/provided/web-search.js";import{readToolBehavior}from"#tools/behavior.js";import{readWorkflowProgramOptions}from"#tools/workflow-program-input.js";function normalizeToolDefinition(e,t){if(isDynamicSentinel(e))return assertResolverOnlyDynamicSentinel(e,t),{kind:`dynamic-tool`,eventNames:Object.keys(e.events),rebindMissingCallbacks:shouldRebindDynamicCallbacks(e)};if(isDisabledToolSentinel(e))return{kind:`disabled`};if(isWebSearchToolDefinition(e)){let n=expectObjectRecord(e,t);expectOnlyKnownKeys(n,[`kind`,`provider`],t);let r=expectString(n.provider,t);if(r!==`exa`&&r!==`parallel`)throw Error(`${t} Expected "provider" to be one of: exa, parallel.`);return{kind:`web-search-tool`,provider:r}}let n=expectObjectRecord(e,t),r=readWorkflowFunctionId(n.execute);if(isWorkflowToolDefinition(e)){if(r===void 0)throw Error(`${t} defineWorkflowTool() requires a compiled workflow executor. Start execute with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`)}else if(r!==void 0)throw Error(`${t} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`);expectOnlyKnownKeys(n,[`availableInSubagents`,`label`,`auth`,`description`,`execute`,`execution`,`inputSchema`,`approval`,`approvalKey`,`outputSchema`,`toModelOutput`],t);let i=n.inputSchema===void 0?null:serializeInputSchema(n.inputSchema),a=serializeOutputSchema(n.outputSchema),o=readToolBehavior(e),s=readWorkflowProgramOptions(e),c=n.execute!==void 0;!c&&o?.handling?.kind!==`dispatch`&&o?.handling?.kind!==`request-input`&&expectFunction(n.execute,t);let l={availableInSubagents:n.availableInSubagents===void 0?void 0:expectBoolean(n.availableInSubagents,t),description:expectString(n.description,t),hasApproval:n.approval!==void 0,hasExecute:c,hasModelOutputProjection:n.toModelOutput!==void 0,inputSchema:i};if(o!==void 0&&(l.behavior=o),s!==void 0&&(l.workflowProgram=s),c&&(l.execute=expectFunction(n.execute,t)),n.execution!==void 0){if(!c)throw Error(`${t} Execute-less native tools cannot use background execution.`);let e=expectString(n.execution,t);if(e!==`background`)throw Error(`${t} Expected "execution" to be "background".`);l.execution=e}if(a!==void 0&&(l.outputSchema=a),n.label!==void 0){let e=expectObjectRecord(n.label,t);expectOnlyKnownKeys(e,[`start`,`complete`,`delta`],t),expectFunction(e.start,t),e.complete!==void 0&&expectFunction(e.complete,t),e.delta!==void 0&&expectFunction(e.delta,t)}if(n.approval!==void 0&&normalizeApproval(n.approval,t),n.approvalKey!==void 0&&expectFunction(n.approvalKey,t),n.toModelOutput!==void 0&&expectFunction(n.toModelOutput,t),n.auth!==void 0){let e=expectObjectRecord(n.auth,t);expectFunction(e.getToken,t)}return{kind:`tool`,definition:l}}export{normalizeToolDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{resolveInstrumentationLayout}from"#internal/instrumentation-layout.js";async function prepareAuthoredRuntimeModules(e){let{authoredWorkflowModules:t,code:n,workflowSourceFingerprint:r}=await bundleAuthoredModuleMapForGeneration(e),i=e.manifest.config.experimental?.instrumentationProviders??!1?resolveInstrumentationLayout({agentRoot:e.manifest.agentRoot,providersEnabled:!0}):void 0,a=e.manifest.config.build?.externalDependencies??[],bundleInstrumentationModule=async e=>await bundleAuthoredModuleForGeneration(e,{externalDependencies:a}),o;
|
|
1
|
+
import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{resolveInstrumentationLayout}from"#internal/instrumentation-layout.js";import{mapConcurrent}from"#shared/map-concurrent.js";async function prepareAuthoredRuntimeModules(e){let{authoredWorkflowModules:t,code:n,workflowSourceFingerprint:r}=await bundleAuthoredModuleMapForGeneration(e),i=e.manifest.config.experimental?.instrumentationProviders??!1?resolveInstrumentationLayout({agentRoot:e.manifest.agentRoot,providersEnabled:!0}):void 0,a=e.manifest.config.build?.externalDependencies??[],bundleInstrumentationModule=async e=>await bundleAuthoredModuleForGeneration(e,{externalDependencies:a}),o;return i?.kind===`directory`&&(o={kind:`directory`,moduleCodeBySlot:Object.fromEntries(await mapConcurrent(Object.entries(i.modulePathsBySlot),async([e,t])=>[e,await bundleInstrumentationModule(t)]))}),o===void 0?{authoredWorkflowModules:t,moduleMapCode:n,workflowSourceFingerprint:r}:{authoredWorkflowModules:t,instrumentation:o,moduleMapCode:n,workflowSourceFingerprint:r}}export{prepareAuthoredRuntimeModules};
|
|
@@ -3,6 +3,7 @@ export interface DevelopmentRuntimeArtifactsRevision {
|
|
|
3
3
|
readonly revision: string;
|
|
4
4
|
}
|
|
5
5
|
export interface DevelopmentRuntimeArtifactsSnapshot {
|
|
6
|
+
readonly sourceWatchPaths?: readonly string[];
|
|
6
7
|
readonly runtimeAppRoot: string;
|
|
7
8
|
readonly snapshotRoot: string;
|
|
8
9
|
readonly snapshotSourceRoot: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{cp,mkdir,readFile,rm,symlink,writeFile}from"node:fs/promises";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageRoot}from"#internal/application/package.js";import{existsSync,readFileSync}from"node:fs";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.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,authoredSourceRoots:collectExtensionMountSourceRoots(e.manifest),snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await mountFrameworkPackage(n.runtimeAppRoot),await mountExtensionExternalDependencies({manifest:e.manifest,runtimeAppRoot:n.runtimeAppRoot}),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 mountFrameworkPackage(e){let t=join(e,`node_modules`,`eve`);await mkdir(dirname(t),{recursive:!0}),await rm(t,{force:!0,recursive:!0}),await symlink(resolvePackageRoot(),t,`junction`)}async function mountExtensionExternalDependencies(e){if(e.manifest===void 0)return;let t=[e.manifest,...(e.manifest.subagents??[]).map(e=>e.agent)].flatMap(e=>e.extensionMounts??[]).filter(e=>(e.externalDependencies??[]).length>0);for(let[n,r]of Object.entries(resolveExtensionExternalDependencyPaths(t))){let t=findPackageRoot(r,n),i=join(e.runtimeAppRoot,`node_modules`,...n.split(`/`));await mkdir(dirname(i),{recursive:!0}),await rm(i,{force:!0,recursive:!0}),await symlink(t,i,`junction`)}}function findPackageRoot(e,t){let n=dirname(e);for(;;){let e=join(n,`package.json`);if(existsSync(e))try{if(JSON.parse(readFileSync(e,`utf8`)).name===t)return n}catch{}let r=dirname(n);if(r===n)throw Error(`Cannot locate package root for extension external dependency "${t}".`);n=r}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=await readMaterializedAuthoredModuleIndex(e.snapshot.runtimeAppRoot);if(t===void 0||!existsSync(join(e.snapshot.runtimeAppRoot,`.eve`,`compile`,t.moduleMap)))throw Error(`Cannot activate development runtime generation "${e.snapshot.snapshotRoot}" before its authored modules are materialized.`);let n=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),r=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(r),a=await readOptionalFile(r);try{await writeFile(n,``),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:n,pointerPath:r,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:n,pointerPath:r,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 collectExtensionMountSourceRoots(e){return e===void 0?[]:[e,...(e.subagents??[]).map(e=>e.agent)].flatMap(e=>(e.extensionMounts??[]).map(e=>e.sourceRoot))}function readDevelopmentRuntimeArtifactsPointer(e){if(e!==void 0&&existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return t.kind!==`eve-dev-runtime-artifacts-pointer`||typeof t.version!=`number`?void 0:t.version===1&&typeof t.appRoot==`string`&&t.appRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:t.version===2&&typeof t.appRoot==`string`&&typeof t.runtimeAppRoot==`string`&&t.runtimeAppRoot.length>0&&typeof t.snapshotRoot==`string`&&t.snapshotRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.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 n=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(n,t);try{await renameWithTransientBusyRetry(n,e)}catch(e){throw await rm(n,{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{randomUUID}from"node:crypto";import{cp,mkdir,readFile,rm,symlink,writeFile}from"node:fs/promises";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageRoot}from"#internal/application/package.js";import{existsSync,readFileSync}from"node:fs";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.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,authoredSourceRoots:collectExtensionMountSourceRoots(e.manifest),snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await mountFrameworkPackage(n.runtimeAppRoot),await mountExtensionExternalDependencies({manifest:e.manifest,runtimeAppRoot:n.runtimeAppRoot}),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{sourceWatchPaths:n.watchPaths,runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function mountFrameworkPackage(e){let t=join(e,`node_modules`,`eve`);await mkdir(dirname(t),{recursive:!0}),await rm(t,{force:!0,recursive:!0}),await symlink(resolvePackageRoot(),t,`junction`)}async function mountExtensionExternalDependencies(e){if(e.manifest===void 0)return;let t=[e.manifest,...(e.manifest.subagents??[]).map(e=>e.agent)].flatMap(e=>e.extensionMounts??[]).filter(e=>(e.externalDependencies??[]).length>0);for(let[n,r]of Object.entries(resolveExtensionExternalDependencyPaths(t))){let t=findPackageRoot(r,n),i=join(e.runtimeAppRoot,`node_modules`,...n.split(`/`));await mkdir(dirname(i),{recursive:!0}),await rm(i,{force:!0,recursive:!0}),await symlink(t,i,`junction`)}}function findPackageRoot(e,t){let n=dirname(e);for(;;){let e=join(n,`package.json`);if(existsSync(e))try{if(JSON.parse(readFileSync(e,`utf8`)).name===t)return n}catch{}let r=dirname(n);if(r===n)throw Error(`Cannot locate package root for extension external dependency "${t}".`);n=r}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=await readMaterializedAuthoredModuleIndex(e.snapshot.runtimeAppRoot);if(t===void 0||!existsSync(join(e.snapshot.runtimeAppRoot,`.eve`,`compile`,t.moduleMap)))throw Error(`Cannot activate development runtime generation "${e.snapshot.snapshotRoot}" before its authored modules are materialized.`);let n=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),r=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(r),a=await readOptionalFile(r);try{await writeFile(n,``),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:n,pointerPath:r,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:n,pointerPath:r,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 collectExtensionMountSourceRoots(e){return e===void 0?[]:[e,...(e.subagents??[]).map(e=>e.agent)].flatMap(e=>(e.extensionMounts??[]).map(e=>e.sourceRoot))}function readDevelopmentRuntimeArtifactsPointer(e){if(e!==void 0&&existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return t.kind!==`eve-dev-runtime-artifacts-pointer`||typeof t.version!=`number`?void 0:t.version===1&&typeof t.appRoot==`string`&&t.appRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:t.version===2&&typeof t.appRoot==`string`&&typeof t.runtimeAppRoot==`string`&&t.runtimeAppRoot.length>0&&typeof t.snapshotRoot==`string`&&t.snapshotRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.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 n=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(n,t);try{await renameWithTransientBusyRetry(n,e)}catch(e){throw await rm(n,{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{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(e){let
|
|
1
|
+
import{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(e){let[t,n]=await Promise.allSettled([prepareAuthoredRuntimeModules({manifest:e.manifest,moduleMapPath:e.paths.moduleMapPath}),stageDevelopmentRuntimeArtifactsSnapshot(e)]);if(n.status===`rejected`)throw t.status===`rejected`?AggregateError([t.reason,n.reason],`Failed to stage development generation.`):n.reason;let r=n.value;try{if(t.status===`rejected`)throw t.reason;let e=t.value,n=await writeMaterializedAuthoredModules({prepared:e,runtimeAppRoot:r.runtimeAppRoot});return e.workflowSourceFingerprint===void 0?{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint}:{...r,authoredWorkflowModules:e.authoredWorkflowModules,fingerprint:n.fingerprint,workflowSourceFingerprint:e.workflowSourceFingerprint}}catch(e){try{await rm(r.snapshotRoot,{force:!0,recursive:!0})}catch(t){throw AggregateError([e,t],`Failed to materialize and discard development generation "${r.snapshotRoot}".`)}throw e}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),n=!1;return{commit(){n||(n=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){n||(n=!0,await t.rollback())}}}async function discardDevelopmentGeneration(e){await rm(e.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:{...createNitroBundlerConfig(c),tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),r=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,n),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let a=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(a,e),configureNitroStepPlugins(a,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(a);let t=createProductionNitroArtifactsConfig();registerScheduleTaskHandlers(a,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(a,e),await addNitroStepNoExternals(a,join(e.workflowBuildDir,`steps.mjs`)),a}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:{tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),r=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,n),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let a=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(a,e),configureNitroStepPlugins(a,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(a);let t=createProductionNitroArtifactsConfig();registerScheduleTaskHandlers(a,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(a,e),await addNitroStepNoExternals(a,join(e.workflowBuildDir,`steps.mjs`)),a}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{dirname,join,normalize,resolve,sep}from"node:path";import{existsSync}from"node:fs";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=new Set,s=new Map,c=new Set,l=await resolveAuthoredWatchPaths(t),u=createWatchPathMap(l),d=watch$1(l,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),f=waitForWatcherReady(d),rebuild=async(i,a=!1)=>{n||o.size>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),u=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:u,watcher:d})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return d.on(`all`,(e,t)=>{!n&&a&&e!==`addDir`&&e!==`unlinkDir`&&(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await f,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await d.close(),await r},flush,rebuild:forceRebuild,async suspend(e){o.has(e)||(o.add(e),i!==void 0&&(clearTimeout(i),i=void 0),await r)},async resume(e,t){o.delete(e)&&o.size===0&&await forceRebuild(t?.silent)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),n=await resolveTsConfigWatchPaths(e.appRoot),r=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of e.workspaceExtensions){t.add(n.config.sourceRoot);for(let e of n.buildConfigPaths)t.add(e)}for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of r)t.add(e);for(let e of n)t.add(e);for(let n of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(n,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),n=[t],r=t;for(;;){if(hasWatchRootMarker(r))return n;let e=dirname(r);if(e===r)return[t];r=e,n.push(r)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(t=>existsSync(join(e,t)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
|
|
1
|
+
import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{dirname,join,normalize,resolve,sep}from"node:path";import{existsSync}from"node:fs";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=new Set,s=new Map,c=new Set,l=await resolveAuthoredWatchPaths(t),u=createWatchPathMap(l),d=watch$1(l,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),f=waitForWatcherReady(d),rebuild=async(i,a=!1)=>{n||o.size>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),u=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:u,watcher:d})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return d.on(`all`,(e,t)=>{!n&&a&&e!==`addDir`&&e!==`unlinkDir`&&(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await f,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await d.close(),await r},flush,rebuild:forceRebuild,async suspend(e){o.has(e)||(o.add(e),i!==void 0&&(clearTimeout(i),i=void 0),await r)},async resume(e,t){o.delete(e)&&o.size===0&&await forceRebuild(t?.silent)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),n=await resolveTsConfigWatchPaths(e.appRoot),r=e.generation.sourceWatchPaths??await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of e.workspaceExtensions){t.add(n.config.sourceRoot);for(let e of n.buildConfigPaths)t.add(e)}for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of r)t.add(e);for(let e of n)t.add(e);for(let n of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(n,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),n=[t],r=t;for(;;){if(hasWatchRootMarker(r))return n;let e=dirname(r);if(e===r)return[t];r=e,n.push(r)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(t=>existsSync(join(e,t)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{cp,mkdir,readdir,rename,writeFile}from"node:fs/promises";import{dirname,join,relative}from"node:path";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{bundleExtensionDistributionGraph}from"#internal/authored-module-loader.js";import{EXTENSION_COMPATIBILITY_MANIFEST_FILENAME}from"#compiler/extension-compatibility.js";import{emitExtensionDeclarations}from"#internal/nitro/host/extension-declarations.js";async function emitExtensionDistribution(e){let t=await collectExtensionSourceFiles(e.sourceRoot),n=e.manifest.skills.filter(e=>e.sourceKind===`skill-package`).map(t=>relative(e.sourceRoot,t.rootPath).replaceAll(`\\`,`/`)),r=t.filter(e=>isAuthoredModule(e.logicalPath)&&!n.some(t=>e.logicalPath.startsWith(`${t}/`)));await copyDistributionDataFiles({files:t,moduleLogicalPaths:new Set(r.map(e=>e.logicalPath)),stagedDistRoot:e.stagedDistRoot});let i=await createDistributionEntries({...e,moduleFiles:r}),a=await bundleExtensionDistributionGraph({entries:i,packageRoot:e.appRoot,runtimeDependencies:e.runtimeDependencies});for(let[t,n]of
|
|
1
|
+
import{cp,mkdir,readdir,rename,writeFile}from"node:fs/promises";import{dirname,join,relative}from"node:path";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{bundleExtensionDistributionGraph}from"#internal/authored-module-loader.js";import{EXTENSION_COMPATIBILITY_MANIFEST_FILENAME}from"#compiler/extension-compatibility.js";import{emitExtensionDeclarations}from"#internal/nitro/host/extension-declarations.js";async function emitExtensionDistribution(e){let t=await collectExtensionSourceFiles(e.sourceRoot),n=e.manifest.skills.filter(e=>e.sourceKind===`skill-package`).map(t=>relative(e.sourceRoot,t.rootPath).replaceAll(`\\`,`/`)),r=t.filter(e=>isAuthoredModule(e.logicalPath)&&!n.some(t=>e.logicalPath.startsWith(`${t}/`)));await copyDistributionDataFiles({files:t,moduleLogicalPaths:new Set(r.map(e=>e.logicalPath)),stagedDistRoot:e.stagedDistRoot});let i=await createDistributionEntries({...e,moduleFiles:r}),[a,o]=await Promise.allSettled([bundleExtensionDistributionGraph({entries:i,packageRoot:e.appRoot,runtimeDependencies:e.runtimeDependencies}),emitExtensionDeclarations({appRoot:e.appRoot,declarationsRoot:e.declarationsRoot,moduleLogicalPaths:r.map(e=>e.logicalPath),sourceRoot:e.sourceRoot})]);if(a.status===`rejected`)throw a.reason;if(o.status===`rejected`)throw o.reason;let s=a.value;for(let[t,n]of s.files){let r=join(e.stagedOutDir,t);await mkdir(dirname(r),{recursive:!0}),await writeFile(r,n,`utf8`)}let c=relative(e.appRoot,e.sourceRoot);try{await cp(join(e.declarationsRoot,c),e.stagedDistRoot,{recursive:!0})}catch(e){throw isFileSystemError(e,`ENOENT`)?Error(`TypeScript emitted no declarations for "${c}". Ensure the package tsconfig.json \`include\` covers every module under \`eve.extension.source\`.`,{cause:e}):e}return await emitDeclarationBarrels(e),s.imports}var ExtensionOutputRestoreError=class extends Error{preservedOutputPath;constructor(e,t){super(`Publishing the extension build output failed, and the previous output could not be restored. It is preserved at "${e}".`,t),this.name=`ExtensionOutputRestoreError`,this.preservedOutputPath=e}};async function replaceExtensionBuildOutput(e){await mkdir(dirname(e.outDir),{recursive:!0});let t=join(e.transactionRoot,`previous-output`),n=!1;try{await rename(e.outDir,t),n=!0}catch(e){if(!isFileSystemError(e,`ENOENT`))throw e}try{await rename(e.stagedOutDir,e.outDir)}catch(r){if(n)try{await rename(t,e.outDir)}catch{throw new ExtensionOutputRestoreError(t,{cause:r})}throw r}}async function collectExtensionSourceFiles(e,t=e){let n=[];for(let r of await readdir(t,{withFileTypes:!0})){let i=join(t,r.name);if(r.isDirectory())n.push(...await collectExtensionSourceFiles(e,i));else if(r.isFile()){let t=relative(e,i).replaceAll(`\\`,`/`);if(t===EXTENSION_COMPATIBILITY_MANIFEST_FILENAME)throw Error(`The extension source cannot contain "${EXTENSION_COMPATIBILITY_MANIFEST_FILENAME}"; eve reserves it for generated compatibility metadata.`);n.push({absolutePath:i,logicalPath:t})}else throw Error(`Extension source entry "${i}" must be a regular file or directory.`)}return n.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath))}function isAuthoredModule(e){return!/\.d\.[cm]?ts$/.test(e)&&SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS.some(t=>e.endsWith(t))}async function copyDistributionDataFiles(e){await Promise.all(e.files.filter(t=>!e.moduleLogicalPaths.has(t.logicalPath)).map(async t=>{let n=join(e.stagedDistRoot,t.logicalPath);await mkdir(dirname(n),{recursive:!0}),await cp(t.absolutePath,n)}))}async function createDistributionEntries(e){let t=relative(e.stagedOutDir,e.stagedDistRoot).replaceAll(`\\`,`/`),n=e.moduleFiles.map(e=>({name:`${t}/${stripAuthoredModuleExtension(e.logicalPath)}`,path:e.absolutePath})),r=new Set;for(let e of n){if(r.has(e.name))throw Error(`Multiple extension modules emit the same path "${e.name}.mjs".`);r.add(e.name)}let i=join(e.transactionRoot,`barrels`);return n.push(await stageRuntimeBarrel({barrelPath:join(i,`index.mjs`),name:`index`,reexports:[{name:`default`,path:join(e.sourceRoot,e.declarationModule.logicalPath)},{name:e.shortName,path:join(e.sourceRoot,e.declarationModule.logicalPath)}]}),await stageRuntimeBarrel({barrelPath:join(i,`tools.mjs`),name:`tools/index`,reexports:e.manifest.tools.map(t=>({name:toolExportName(t.logicalPath),path:join(e.sourceRoot,t.logicalPath)}))})),n}async function stageRuntimeBarrel(e){await mkdir(dirname(e.barrelPath),{recursive:!0});let t=e.reexports.map(t=>reexportLine(t.name,relativeImport(dirname(e.barrelPath),t.path)));return await writeFile(e.barrelPath,`${t.join(`
|
|
2
2
|
`)}\n`,`utf8`),{name:e.name,path:e.barrelPath}}async function emitDeclarationBarrels(e){await mkdir(join(e.stagedOutDir,`tools`),{recursive:!0});let t=relativeImport(e.stagedOutDir,join(e.stagedDistRoot,e.declarationModule.logicalPath));await writeDeclarationBarrel({path:join(e.stagedOutDir,`index.d.ts`),reexports:[{name:`default`,specifier:t},{name:e.shortName,specifier:t}]}),await writeDeclarationBarrel({path:join(e.stagedOutDir,`tools`,`index.d.ts`),reexports:e.manifest.tools.map(t=>({name:toolExportName(t.logicalPath),specifier:relativeImport(join(e.stagedOutDir,`tools`),join(e.stagedDistRoot,t.logicalPath))}))})}async function writeDeclarationBarrel(e){let t=e.reexports.map(e=>reexportLine(e.name,toDeclarationSpecifier(e.specifier)));await writeFile(e.path,[`// Generated by eve. Do not edit by hand.`,``,...t,``].join(`
|
|
3
3
|
`),`utf8`)}function stripAuthoredModuleExtension(e){for(let t of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(t))return e.slice(0,e.length-t.length);return e}function toolExportName(e){let t=stripAuthoredModuleExtension(e).replace(/^tools\//,``).replace(/[^A-Za-z0-9_$]/g,`_`);return/^[A-Za-z_$]/.test(t)?t:`_${t}`}function relativeImport(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}function reexportLine(e,t){return e==="default"?`export { default } from ${JSON.stringify(t)};`:`export { default as ${e} } from ${JSON.stringify(t)};`}function toDeclarationSpecifier(e){return e.replace(/\.mts$/,`.mjs`).replace(/\.cts$/,`.cjs`).replace(/\.tsx?$/,`.js`)}function isFileSystemError(e,t){return e instanceof Error&&`code`in e&&e.code===t}export{ExtensionOutputRestoreError,emitExtensionDistribution,replaceExtensionBuildOutput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createDevelopmentServer,isActiveDevelopmentServerForApp}from"#internal/nitro/host/start-development-server.js";import{buildApplication}from"#internal/nitro/host/build-application.js";import{startProductionServer}from"#internal/nitro/host/start-production-server.js";export{buildApplication,createDevelopmentServer,isActiveDevelopmentServerForApp,startProductionServer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
const BANNER_LINES=[{importLine:`import { fileURLToPath as __eveFileURLToPath } from "node:url";`,declarationLine:`const __filename = __eveFileURLToPath(import.meta.url);`,bindingName:`__filename`},{importLine:`import { dirname as __eveDirname } from "node:path";`,declarationLine:`const __dirname = __eveDirname(__filename);`,bindingName:`__dirname`}],FILENAME_BANNER_LINE=BANNER_LINES[0],DIRNAME_BANNER_LINE=BANNER_LINES[1],REQUIRE_LINE={importLine:`import { createRequire as __eveCreateRequire } from "node:module";`,declarationLine:`const require = __eveCreateRequire(import.meta.url);`,bindingName:`require`};function buildNodeEsmCompatBanner(e,t={}){let n=[...BANNER_LINES];t.includeRequire===!0&&n.push(REQUIRE_LINE);let r=[],i=[],a=collectTopLevelVariableBindings(e),o=a.has(FILENAME_BANNER_LINE.bindingName),s=a.has(DIRNAME_BANNER_LINE.bindingName);for(let e of n)a.has(e.bindingName)||(r.push(e.importLine),i.push(e===DIRNAME_BANNER_LINE&&o?`const __dirname = __eveDirname(__eveFileURLToPath(import.meta.url));`:e.declarationLine));return o&&!s&&r.unshift(FILENAME_BANNER_LINE.importLine),i.length===0?``:[...r,...i].join(`
|
|
2
|
-
`)}function collectTopLevelVariableBindings(e){let t=new Set;for(let n of e.body)if(n.type===`VariableDeclaration`)for(let e of n.declarations??[])e.id.type===`Identifier`&&e.id.name!==void 0&&t.add(e.id.name);return t}function createNodeEsmCompatBannerPlugin(e={}){return{name:`eve-node-esm-compat-banner`,renderChunk(t,n){let r=buildNodeEsmCompatBanner(this.parse(t),e);return r===``?null:{code:`${r}\n${t}`,map:createPrependedLineSourceMap({insertedLineCount:r.split(`
|
|
3
|
-
`).length,source:n?.fileName??`eve-node-esm-compat-banner-input`,sourceContent:t})}}}}function createPrependedLineSourceMap({insertedLineCount:e,source:t,sourceContent:n}){let r=n.split(`
|
|
4
|
-
`).length
|
|
2
|
+
`)}function collectTopLevelVariableBindings(e){let t=new Set;for(let n of e.body)if(n.type===`VariableDeclaration`)for(let e of n.declarations??[])e.id.type===`Identifier`&&e.id.name!==void 0&&t.add(e.id.name);return t}function createNodeEsmCompatBannerPlugin(e={}){return{name:`eve-node-esm-compat-banner`,renderChunk(t,n){let r=buildNodeEsmCompatBanner(mayDeclareCompatibilityBinding(t,e)?this.parse(t):{body:[]},e);return r===``?null:{code:`${r}\n${t}`,map:createPrependedLineSourceMap({insertedLineCount:r.split(`
|
|
3
|
+
`).length,source:n?.fileName??`eve-node-esm-compat-banner-input`,sourceContent:t})}}}}const DECLARATION_TRIVIA=String.raw`(?:\s|/\*[\s\S]*?\*/|//[^\r\n\u2028\u2029]*[\r\n\u2028\u2029])*`,PATH_BINDING_DECLARATION=new RegExp(String.raw`(?:\b(?:var|let|const|using)\b|,)${DECLARATION_TRIVIA}(?:__filename|__dirname)\b`),REQUIRE_BINDING_DECLARATION=new RegExp(String.raw`(?:\b(?:var|let|const|using)\b|,)${DECLARATION_TRIVIA}require\b`);function mayDeclareCompatibilityBinding(e,t){return e.includes(`\\u`)||PATH_BINDING_DECLARATION.test(e)||t.includeRequire===!0&&REQUIRE_BINDING_DECLARATION.test(e)}function createPrependedLineSourceMap({insertedLineCount:e,source:t,sourceContent:n}){let r=n.split(`
|
|
4
|
+
`).length;return{version:3,sources:[t],sourcesContent:[n],names:[],mappings:`${`;`.repeat(e)}AAAA${`;AACA`.repeat(r-1)}`}}export{buildNodeEsmCompatBanner,createNodeEsmCompatBannerPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const HOISTED_EXECUTE_NAME=`execute`;async function prepareAuthoredWorkflowDirectives(e){let t=/\.[cm]?js$/.test(e.filePath)?`${e.filePath}.jsx`:e.filePath,n=await parseWithNitroRolldownAst(t,e.source),r=n.body??[];if(r.some(e=>e.source?.value===`eve/workflow`))throw Error(`${e.filePath}: "eve/workflow" has been removed. Use defineWorkflowTool() from "eve/tools" and call ctx.agent(target, input) or ctx.ask(request) in its executor.`);for(let t of r){if(typeof t.directive!=`string`)break;let n=readWorkflowDirective(t);if(n!==void 0)throw Error(`${JSON.stringify(n)} in "${e.filePath}" is a module-level directive. Put it as the first statement of the function it marks: a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`)}let i=new Set;for(let e of r){let t=e.type===`FunctionDeclaration`?e:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`?e.declaration:void 0;t!==void 0&&i.add(t)}let a=findDefaultExportExecuteProperty(r),o=a!==void 0&&isAstNode(a.value)&&isFunctionLike(a.value)?a.value:void 0;o!==void 0&&i.add(o);let s=collectDirectiveFunctions(n);if(s.length===0)return{hasDirectives:!1,hasWorkflowDirective:!1,source:e.source};let c=s.some(e=>e.directive===`use workflow`);for(let t of s){if(!i.has(t.fn))throw Error(`${JSON.stringify(t.directive)} in "${e.filePath}" marks ${describeFunction(t.fn)}. Workflow directives must mark a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`);if(t.fn.async!==!0)throw Error(`${JSON.stringify(t.directive)} in "${e.filePath}" marks ${describeFunction(t.fn)}, which is not async. Declare it with "async function".`);if(t.fn===o&&t.directive!==`use workflow`)throw Error(`"use step" in "${e.filePath}" marks the default export's "execute" method. A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`)}let l=s.find(e=>e.fn===o);if(l===void 0||a===void 0)return{hasDirectives:!0,hasWorkflowDirective:c,source:e.source};if(declaresTopLevelBinding(r,HOISTED_EXECUTE_NAME))throw Error(`"use workflow" in "${e.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`);return{hasDirectives:!0,hasWorkflowDirective:c,source:hoistExecuteMethod(e.source,a,l.fn)}}function findDefaultExportExecuteProperty(e){let t=e.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration,n=t?.type===`CallExpression`?t.arguments?.[0]:t;if(n?.type===`ObjectExpression`)return n.properties?.find(e=>e.type===`Property`&&e.kind===`init`&&e.computed!==!0&&readPropertyName(e.key)===HOISTED_EXECUTE_NAME)}function hoistExecuteMethod(e,t,n){if(t.start===void 0||t.end===void 0||!isAstNode(n.body)||n.body.start===void 0||n.body.end===void 0)throw Error(`Cannot hoist an execute method without source ranges.`);let r=n.params??[],i=r[0],a=r[r.length-1],o=i?.start===void 0||a?.end===void 0?``:e.slice(i.start,a.end),s=sliceNode(e,n.typeParameters),c=sliceNode(e,n.returnType),l=e.slice(n.body.start,n.body.end),u=`async function${n.generator===!0?`*`:``} ${HOISTED_EXECUTE_NAME}${s}(${o})${c} ${l}`;return`${e.slice(0,t.start)}${HOISTED_EXECUTE_NAME}${e.slice(t.end)}\n${u}\n`}function sliceNode(e,t){return t==null||t.start===void 0||t.end===void 0?``:e.slice(t.start,t.end)}function declaresTopLevelBinding(e,t){for(let n of e){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e!=null){if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.name===t)return!0;if(e.type===`VariableDeclaration`){for(let n of e.declarations??[])if(n.id?.name===t)return!0}if(e.type===`ImportDeclaration`){for(let n of e.specifiers??[])if(n.local?.name===t)return!0}}}return!1}function collectDirectiveFunctions(e){let t=[];return visit(e,e=>{if(!isFunctionLike(e))return;let n=readLeadingDirective(e);n!==void 0&&t.push({directive:n,fn:e})}),t}function readLeadingDirective(e){if(isAstNode(e.body)&&e.body.type===`BlockStatement`&&Array.isArray(e.body.body))return readWorkflowDirective(e.body.body[0])}function describeFunction(e){return e.type===`FunctionDeclaration`?e.id?.name===void 0?`a nested function declaration`:`the nested function "${e.id.name}"`:e.type===`ArrowFunctionExpression`?`an arrow function`:e.id?.name===void 0?`a function expression`:`the function "${e.id.name}"`}function readPropertyName(e){if(e!=null){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`&&typeof e.value==`string`)return e.value}}function isFunctionLike(e){return e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`}function visit(e,t){if(!e.type?.startsWith(`TS`)){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visit(e,t);else isAstNode(n)&&visit(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{prepareAuthoredWorkflowDirectives};
|
|
1
|
+
import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{mayContainWorkflowDirective,readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const HOISTED_EXECUTE_NAME=`execute`;async function prepareAuthoredWorkflowDirectives(e){if(!mayContainWorkflowDirective(e.source)&&!e.source.includes(`eve/workflow`))return{hasDirectives:!1,hasWorkflowDirective:!1,source:e.source};let t=/\.[cm]?js$/.test(e.filePath)?`${e.filePath}.jsx`:e.filePath,n=await parseWithNitroRolldownAst(t,e.source),r=n.body??[];if(r.some(e=>e.source?.value===`eve/workflow`))throw Error(`${e.filePath}: "eve/workflow" has been removed. Use defineWorkflowTool() from "eve/tools" and call ctx.agent(target, input) or ctx.ask(request) in its executor.`);for(let t of r){if(typeof t.directive!=`string`)break;let n=readWorkflowDirective(t);if(n!==void 0)throw Error(`${JSON.stringify(n)} in "${e.filePath}" is a module-level directive. Put it as the first statement of the function it marks: a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`)}let i=new Set;for(let e of r){let t=e.type===`FunctionDeclaration`?e:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`?e.declaration:void 0;t!==void 0&&i.add(t)}let a=findDefaultExportExecuteProperty(r),o=a!==void 0&&isAstNode(a.value)&&isFunctionLike(a.value)?a.value:void 0;o!==void 0&&i.add(o);let s=collectDirectiveFunctions(n);if(s.length===0)return{hasDirectives:!1,hasWorkflowDirective:!1,source:e.source};let c=s.some(e=>e.directive===`use workflow`);for(let t of s){if(!i.has(t.fn))throw Error(`${JSON.stringify(t.directive)} in "${e.filePath}" marks ${describeFunction(t.fn)}. Workflow directives must mark a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`);if(t.fn.async!==!0)throw Error(`${JSON.stringify(t.directive)} in "${e.filePath}" marks ${describeFunction(t.fn)}, which is not async. Declare it with "async function".`);if(t.fn===o&&t.directive!==`use workflow`)throw Error(`"use step" in "${e.filePath}" marks the default export's "execute" method. A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`)}let l=s.find(e=>e.fn===o);if(l===void 0||a===void 0)return{hasDirectives:!0,hasWorkflowDirective:c,source:e.source};if(declaresTopLevelBinding(r,HOISTED_EXECUTE_NAME))throw Error(`"use workflow" in "${e.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`);return{hasDirectives:!0,hasWorkflowDirective:c,source:hoistExecuteMethod(e.source,a,l.fn)}}function findDefaultExportExecuteProperty(e){let t=e.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration,n=t?.type===`CallExpression`?t.arguments?.[0]:t;if(n?.type===`ObjectExpression`)return n.properties?.find(e=>e.type===`Property`&&e.kind===`init`&&e.computed!==!0&&readPropertyName(e.key)===HOISTED_EXECUTE_NAME)}function hoistExecuteMethod(e,t,n){if(t.start===void 0||t.end===void 0||!isAstNode(n.body)||n.body.start===void 0||n.body.end===void 0)throw Error(`Cannot hoist an execute method without source ranges.`);let r=n.params??[],i=r[0],a=r[r.length-1],o=i?.start===void 0||a?.end===void 0?``:e.slice(i.start,a.end),s=sliceNode(e,n.typeParameters),c=sliceNode(e,n.returnType),l=e.slice(n.body.start,n.body.end),u=`async function${n.generator===!0?`*`:``} ${HOISTED_EXECUTE_NAME}${s}(${o})${c} ${l}`;return`${e.slice(0,t.start)}${HOISTED_EXECUTE_NAME}${e.slice(t.end)}\n${u}\n`}function sliceNode(e,t){return t==null||t.start===void 0||t.end===void 0?``:e.slice(t.start,t.end)}function declaresTopLevelBinding(e,t){for(let n of e){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e!=null){if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.name===t)return!0;if(e.type===`VariableDeclaration`){for(let n of e.declarations??[])if(n.id?.name===t)return!0}if(e.type===`ImportDeclaration`){for(let n of e.specifiers??[])if(n.local?.name===t)return!0}}}return!1}function collectDirectiveFunctions(e){let t=[];return visit(e,e=>{if(!isFunctionLike(e))return;let n=readLeadingDirective(e);n!==void 0&&t.push({directive:n,fn:e})}),t}function readLeadingDirective(e){if(isAstNode(e.body)&&e.body.type===`BlockStatement`&&Array.isArray(e.body.body))return readWorkflowDirective(e.body.body[0])}function describeFunction(e){return e.type===`FunctionDeclaration`?e.id?.name===void 0?`a nested function declaration`:`the nested function "${e.id.name}"`:e.type===`ArrowFunctionExpression`?`an arrow function`:e.id?.name===void 0?`a function expression`:`the function "${e.id.name}"`}function readPropertyName(e){if(e!=null){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`&&typeof e.value==`string`)return e.value}}function isFunctionLike(e){return e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`}function visit(e,t){if(!e.type?.startsWith(`TS`)){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visit(e,t);else isAstNode(n)&&visit(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{prepareAuthoredWorkflowDirectives};
|
|
@@ -102,4 +102,5 @@ export declare function createWorkflowEntrypointSource(input: {
|
|
|
102
102
|
export declare function convertStepsManifest(steps: WorkflowManifest["steps"]): Record<string, unknown>;
|
|
103
103
|
export declare function convertWorkflowsManifest(workflows: WorkflowManifest["workflows"]): Record<string, unknown>;
|
|
104
104
|
export declare function convertClassesManifest(classes: WorkflowManifest["classes"]): Record<string, unknown>;
|
|
105
|
+
export declare function mergeWorkflowManifest(target: WorkflowManifest, source: WorkflowManifest): void;
|
|
105
106
|
export {};
|
|
@@ -8,4 +8,4 @@ ${r}
|
|
|
8
8
|
const workflowCode = Buffer.from(${JSON.stringify(n)}.join(""), "base64").toString("utf8");
|
|
9
9
|
|
|
10
10
|
export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });
|
|
11
|
-
`}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=e.replaceAll(`\\`,`/`),i=relative(r,n).replaceAll(`\\`,`/`);return i.startsWith(`../`)&&(i=i.split(`/`).filter(e=>e!==`..`).join(`/`)),i}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowEntrypointSource,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,isWorkflowSourceFile};
|
|
11
|
+
`}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=e.replaceAll(`\\`,`/`),i=relative(r,n).replaceAll(`\\`,`/`);return i.startsWith(`../`)&&(i=i.split(`/`).filter(e=>e!==`..`).join(`/`)),i}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowEntrypointSource,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,isWorkflowSourceFile,mergeWorkflowManifest};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/subagents`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, or subagents source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=e=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]}
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{mapConcurrent}from"#shared/map-concurrent.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,mergeWorkflowManifest}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/subagents`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, or subagents source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=(e,t)=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,precomputedManifest:t,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c,u);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]},n=await mapConcurrent(e,async e=>{let t=await readFile(e,`utf8`);return{filePath:e,patterns:await findWorkflowPatterns(e,t)}});for(let{filePath:e,patterns:r}of n)r.hasUseStep&&t.discoveredSteps.push(e),r.hasUseWorkflow&&t.discoveredWorkflows.push(e),r.hasSerde&&t.discoveredSerdeFiles.push(e);return t}async createWorkflowsBundle({additionalOutputs:e=[],appWorkflowFiles:t,frameworkSerdeFiles:n,frameworkWorkflowFiles:r,outfile:i,stepRegistrationsPath:a,tsconfigPath:o}){let s={},c=await mapConcurrent([{label:`framework`,serdeFiles:n,workflowFiles:r},{label:`app`,serdeFiles:[],workflowFiles:t}],async e=>{let t={};return{code:await this.#a({...e,manifest:t,tsconfigPath:o}),manifest:t}});for(let e of c)mergeWorkflowManifest(s,e.manifest);let l=composeWorkflowDriverCode(c.map(e=>e.code));return await Promise.all([{outfile:i,stepRegistrationsPath:a},...e].map(e=>bundleFinalWorkflowOutput({code:l,outfile:e.outfile,queueNamespace:this.#r,stepRegistrationsPath:e.stepRegistrationsPath}))),{manifest:s}}async#a(e){let t=[...e.workflowFiles].sort(),n=new Set(t),r=[...e.serdeFiles].sort().filter(e=>!n.has(e));if(t.length===0&&r.length===0)return``;let i=[...t.map(e=>createWorkflowImport(e,this.config.workingDir)),...r.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
|
|
2
2
|
`);return(await buildSingleRolldownChunk(`${e.label} workflow driver chunk`,{cwd:this.config.workingDir,onwarn(e,t){if(e.code===`UNRESOLVED_IMPORT`)throw Error(`Cannot build workflow bundle: ${e.message}`);t(e)},input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(i),createWorkflowPseudoPackagePlugin(),createWorkflowDriverAliasPlugin(this.config.workingDir),createAuthoredRelativeExtensionResolverPlugin({extensions:WORKFLOW_SOURCE_EXTENSIONS}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:this.transformProjectRoot,extensions:WORKFLOW_SOURCE_EXTENSIONS}),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:e.manifest,projectRoot:this.transformProjectRoot,sideEffectFiles:[...t,...r],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`],extensions:WORKFLOW_SOURCE_EXTENSIONS,mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`cjs`,sourcemap:`inline`}})).code}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},r=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),r),r}async#o(){return await this.getInputFiles()}};function mergeStepEntries(e,t){return{discoveredSerdeFiles:e.discoveredSerdeFiles,discoveredSteps:[...new Set([...e.discoveredSteps,...t.directiveModules])]}}export{WorkflowBundleBuilder};
|
|
@@ -11,6 +11,7 @@ export declare function writeNitroStepEntrypoint(input: {
|
|
|
11
11
|
readonly builtinsPath?: string;
|
|
12
12
|
readonly discoveredEntries: NitroStepEntrypointDiscoveredEntries;
|
|
13
13
|
readonly outfile: string;
|
|
14
|
+
readonly precomputedManifest?: WorkflowManifest | undefined;
|
|
14
15
|
readonly preferAbsoluteFileImports?: boolean;
|
|
15
16
|
readonly projectRoot: string;
|
|
16
17
|
readonly sideEffectFiles: readonly string[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,relative}from"node:path";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";async function writeNitroStepEntrypoint(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=await collectNitroStepManifest({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=dirname(e.outfile),o=[`// Generated by eve. Do not edit by hand.`,...createEntrypointImportLines({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:createFileImportSpecifier({outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,targetPath:e.builtinsPath}),outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,serdeOnlyFiles:r,sideEffectFiles:e.sideEffectFiles,stepFiles:t}),`export const __steps_registered = true;`,``].join(`
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,relative}from"node:path";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";async function writeNitroStepEntrypoint(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=e.precomputedManifest??await collectNitroStepManifest({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=dirname(e.outfile),o=[`// Generated by eve. Do not edit by hand.`,...createEntrypointImportLines({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:createFileImportSpecifier({outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,targetPath:e.builtinsPath}),outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,serdeOnlyFiles:r,sideEffectFiles:e.sideEffectFiles,stepFiles:t}),`export const __steps_registered = true;`,``].join(`
|
|
2
2
|
`);return await mkdir(a,{recursive:!0}),await readTextFileIfPresent(e.outfile)!==o&&await writeFile(e.outfile,o),i}function createEntrypointImportLines(e){return[e.builtinsImportSpecifier,...e.sideEffectFiles.map(t=>createFileImportSpecifier({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.stepFiles.map(t=>createFileImportSpecifier({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>createFileImportSpecifier({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function createFileImportSpecifier(e){return e.preferAbsoluteFileImports?normalizeEsmImportSpecifier(e.targetPath):createRelativeImportSpecifier(e.outfileDirectory,e.targetPath)}async function collectNitroStepManifest(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await readFile(r,`utf8`),i=createManifestRelativeFilepath(e.workingDir,r);mergeWorkflowManifest(t,(await applyWorkflowTransform(i,n,`step`,r,e.projectRoot)).workflowManifest)}return t}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=e.replaceAll(`\\`,`/`),i=relative(r,n).replaceAll(`\\`,`/`);return i.startsWith(`../`)&&(i=i.split(`/`).filter(e=>e!==`..`).join(`/`)),i}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function readTextFileIfPresent(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}export{writeNitroStepEntrypoint};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function readWorkflowDirective(e){let t=e?.expression,n=e?.directive??(e?.type===`ExpressionStatement`&&t?.type===`Literal`?t.value:void 0);return n===`use step`||n===`use workflow`?n:void 0}export{readWorkflowDirective};
|
|
1
|
+
function mayContainWorkflowDirective(e){return e.includes(`use step`)||e.includes(`use workflow`)||e.includes(`\\`)}function readWorkflowDirective(e){let t=e?.expression,n=e?.directive??(e?.type===`ExpressionStatement`&&t?.type===`Literal`?t.value:void 0);return n===`use step`||n===`use workflow`?n:void 0}export{mayContainWorkflowDirective,readWorkflowDirective};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const BUILTIN_STEP_NAMES=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`,`__builtin_set_attributes`]);async function findWorkflowDirectiveFunctions(e,t){return findDirectiveFunctions(await parseWorkflowSource(e,t)).map(e=>({directive:e.directive,name:e.name}))}async function transformWorkflowDirectives(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await parseWorkflowSource(e.filename,e.source),n=findDirectiveFunctions(t),r=e.authorizeSteps===!0,i=r&&n.some(e=>e.directive===`use step`&&!BUILTIN_STEP_NAMES.has(e.name));if(n.length===0)return{code:e.source,workflowManifest:{}};let a=e.moduleSpecifier??`./${stripJavaScriptExtension(e.filename)}`,o=e.stableModuleSpecifier??a,s={},c=[],l=[],u=!1,d=e.authored?`eve/internal/workflow-step-execution`:`#execution/tools/workflow/step-execution.js`;for(let t of n){if(t.directive===`use step`){let n=createStepId(a,t.name);s.steps??={};let i=s.steps[e.filename]??={};i[t.name]={stepId:n};let o=authorizationTwinId(a,t.name,r);if(o!==void 0&&(i[`${t.name}${AUTHORIZATION_STEP_SUFFIX}`]={stepId:o}),e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;c.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = ${createStepProxy(a,t.name,r)};`})}else if(e.mode===`metadata`)continue;else c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(u=!0,l.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`),o!==void 0&&l.push(`registerStepFunction(${JSON.stringify(o)}, withWorkflowStepAuthorization(${t.name}));`)):l.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=createWorkflowId(e.stableWorkflowNames?.has(t.name)===!0?o:a,t.name);s.workflows??={};let i=s.workflows[e.filename]??={};i[t.name]={workflowId:n},e.mode===`workflow`?(c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),l.push(`globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(n)}, ${t.name});`)):(e.mode===`metadata`||c.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let f=`/**__internal_workflows${JSON.stringify(s)}*/;`,p=[];u&&p.push(`import { registerStepFunction } from "workflow/internal/private";`),i&&e.mode===`workflow`?p.push(`import { workflowToolStep } from ${JSON.stringify(`#execution/tools/workflow/step.js`)};`):i&&u&&p.push(`import { withWorkflowStepAuthorization } from ${JSON.stringify(d)};`);let m=[...p,f].join(`
|
|
1
|
+
import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{mayContainWorkflowDirective,readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const BUILTIN_STEP_NAMES=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`,`__builtin_set_attributes`]);async function findWorkflowDirectiveFunctions(e,t){return mayContainWorkflowDirective(t)?findDirectiveFunctions(await parseWorkflowSource(e,t)).map(e=>({directive:e.directive,name:e.name})):[]}async function transformWorkflowDirectives(e){if(e.mode===!1||!mayContainWorkflowDirective(e.source))return{code:e.source,workflowManifest:{}};let t=await parseWorkflowSource(e.filename,e.source),n=findDirectiveFunctions(t),r=e.authorizeSteps===!0,i=r&&n.some(e=>e.directive===`use step`&&!BUILTIN_STEP_NAMES.has(e.name));if(n.length===0)return{code:e.source,workflowManifest:{}};let a=e.moduleSpecifier??`./${stripJavaScriptExtension(e.filename)}`,o=e.stableModuleSpecifier??a,s={},c=[],l=[],u=!1,d=e.authored?`eve/internal/workflow-step-execution`:`#execution/tools/workflow/step-execution.js`;for(let t of n){if(t.directive===`use step`){let n=createStepId(a,t.name);s.steps??={};let i=s.steps[e.filename]??={};i[t.name]={stepId:n};let o=authorizationTwinId(a,t.name,r);if(o!==void 0&&(i[`${t.name}${AUTHORIZATION_STEP_SUFFIX}`]={stepId:o}),e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;c.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = ${createStepProxy(a,t.name,r)};`})}else if(e.mode===`metadata`)continue;else c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(u=!0,l.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`),o!==void 0&&l.push(`registerStepFunction(${JSON.stringify(o)}, withWorkflowStepAuthorization(${t.name}));`)):l.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=createWorkflowId(e.stableWorkflowNames?.has(t.name)===!0?o:a,t.name);s.workflows??={};let i=s.workflows[e.filename]??={};i[t.name]={workflowId:n},e.mode===`workflow`?(c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),l.push(`globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(n)}, ${t.name});`)):(e.mode===`metadata`||c.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let f=`/**__internal_workflows${JSON.stringify(s)}*/;`,p=[];u&&p.push(`import { registerStepFunction } from "workflow/internal/private";`),i&&e.mode===`workflow`?p.push(`import { workflowToolStep } from ${JSON.stringify(`#execution/tools/workflow/step.js`)};`):i&&u&&p.push(`import { withWorkflowStepAuthorization } from ${JSON.stringify(d)};`);let m=[...p,f].join(`
|
|
2
2
|
`),h=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!h&&e.authored!==!0)return{code:`${m}\n${createWorkflowStepProxySource(e.source,t,n,a,r)}`,workflowManifest:s};e.mode===`workflow`&&e.authored===!0&&c.push(...removeEveDefinerDefaultExport(t));let g=applySourceReplacements(e.source,c);return{code:`${m}\n${e.mode===`workflow`?await stripUnusedValueImports(e.filename,g):g}${l.length>0?`\n${l.join(`
|
|
3
3
|
`)}\n`:``}`,workflowManifest:s}}async function parseWorkflowSource(e,t){return await parseWithNitroRolldownAst(e,t)}function createWorkflowStepProxySource(e,t,n,r,i){let a=findExportedLiteralValueDeclarations(e,t),o=n.filter(e=>e.directive===`use step`).map(e=>`${e.exported?`export `:``}var ${e.name} = ${createStepProxy(r,e.name,i)};`),s=[...a,...o];return s.length>0?`${s.join(`
|
|
4
4
|
`)}\n`:``}const AUTHORIZATION_STEP_SUFFIX=`:eve-authorization`;function authorizationTwinId(e,t,n){if(n&&!BUILTIN_STEP_NAMES.has(t))return createStepId(e,`${t}${AUTHORIZATION_STEP_SUFFIX}`)}function createStepProxy(e,t,n){let useStep=e=>`globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(e)})`,r=useStep(createStepId(e,t)),i=authorizationTwinId(e,t,n);return i===void 0?r:`workflowToolStep(${r}, ${useStep(i)})`}function findDirectiveFunctions(e){let t=[],n=collectLocalNamesReExportedAtModuleLevel(e);for(let r of e.body??[]){let e=readTopLevelFunctionDeclaration(r);if(e===null)continue;let i=e.fn,a=i.id?.name,o=readBlockStatements(i.body);if(i.async!==!0||a===void 0||o===void 0)continue;let s=readFunctionDirective(o[0]);s!==null&&t.push({directive:s.value,directiveEnd:s.end,directiveStart:s.start,exportPrefix:e.exported?`export `:``,exported:e.exported||n.has(a),name:a,rangeEnd:e.end,rangeStart:e.start})}return t}function collectLocalNamesReExportedAtModuleLevel(e){let t=new Set;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&(n.source===void 0||n.source===null)&&(n.declaration===void 0||n.declaration===null))for(let e of n.specifiers??[]){let n=e.local?.name;n!==void 0&&t.add(n)}return t}function readTopLevelFunctionDeclaration(e){return e.type===`FunctionDeclaration`?readFunctionDeclarationRange(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:readFunctionDeclarationRange(e.declaration,!0,e)}function readFunctionDeclarationRange(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function readBlockStatements(e){return e===void 0||Array.isArray(e)?e:e.body}function readFunctionDirective(e){let t=readWorkflowDirective(e);return t===void 0||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function applySourceReplacements(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}function removeEveDefinerDefaultExport(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source?.value;if(typeof e==`string`&&/^eve(?:\/|$)/.test(e))for(let e of n.specifiers??[]){if(e.importKind===`type`)continue;let n=e.local?.name;n!==void 0&&t.add(n)}}let n=[];for(let r of e.body??[]){if(r.type!==`ExportDefaultDeclaration`||r.start===void 0)continue;let e=r.declaration;if(e?.type!==`CallExpression`||r.end===void 0)continue;let i=e.callee,a=i?.type===`MemberExpression`?i.object:i;a?.type===`Identifier`&&t.has(a.name??``)&&n.push({end:r.end,start:r.start,text:``})}return n}async function stripUnusedValueImports(e,t){let n=await parseWorkflowSource(e,t),r=collectReferencedIdentifiers(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=readValueImportBindings(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:extendRemovalEnd(t,e.end),start:e.start,text:``})}return i.length>0?applySourceReplacements(t,i):t}function findExportedLiteralValueDeclarations(e,t){let n=[],r=collectLocalReExportAliases(t);for(let i of t.body??[]){if(i.type===`ExportNamedDeclaration`&&i.declaration?.type===`VariableDeclaration`&&i.declaration.kind===`const`&&i.start!==void 0&&i.end!==void 0&&(i.declaration.declarations??[]).every(isLiteralValueDeclarator)){n.push(e.slice(i.start,i.end).trim());continue}if(i.type===`VariableDeclaration`&&(i.kind===`const`||i.kind===`var`||i.kind===`let`))for(let t of i.declarations??[]){if(!isLiteralValueDeclarator(t)||t.start===void 0||t.end===void 0)continue;let a=t.id?.name;if(a===void 0)continue;let o=r.get(a);if(o===void 0||o.length===0)continue;let s=e.slice(t.start,t.end).trim(),c=o.map(e=>e===a?a:`${a} as ${e}`);n.push(`${i.kind} ${s};\nexport { ${c.join(`, `)} };`)}}return n}function collectLocalReExportAliases(e){let t=new Map;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&(n.source===void 0||n.source===null)&&(n.declaration===void 0||n.declaration===null))for(let e of n.specifiers??[]){let n=e.local?.name,r=e.exported?.name??n;if(n!==void 0&&r!==void 0){let e=t.get(n)??[];e.push(r),t.set(n,e)}}return t}function isLiteralValueDeclarator(e){return isLiteralValueExpression(e.init)}function isLiteralValueExpression(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TemplateLiteral`&&(e.expressions??[]).length===0?!0:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?isLiteralValueExpression(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`&&typeof e.argument.value==`number`}function readValueImportBindings(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function collectReferencedIdentifiers(e){let t=new Set;return visitAstNode(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function visitAstNode(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visitAstNode(e,t);else isAstNode(n)&&visitAstNode(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function extendRemovalEnd(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
|