eve 0.60.0 → 0.61.0
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 +20 -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 +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 +6 -6
- 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/coordination-dispatch-shared.d.ts +2 -0
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/coordination-dispatch-step.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/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.d.ts +5 -0
- package/dist/src/execution/tools/agent-router-workflow.js +1 -0
- package/dist/src/execution/tools/agent-router.d.ts +9 -0
- package/dist/src/execution/tools/agent-router.js +1 -0
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/metadata.d.ts +4 -0
- package/dist/src/execution/tools/subagent/metadata.js +1 -0
- package/dist/src/execution/tools/workflow/body.d.ts +3 -0
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/start.d.ts +1 -0
- package/dist/src/execution/tools/workflow/start.js +1 -1
- package/dist/src/execution/tools/workflow/types.d.ts +2 -0
- 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/agent-router.d.ts +1 -0
- package/dist/src/public/tools/agent-router.js +1 -0
- 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 +7 -0
- package/dist/src/tools/provided/agent-router.js +1 -0
- package/dist/src/tools/workflow-definition.d.ts +6 -1
- 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/evaluate.md +1 -1
- package/docs/guides/frontend/overview.mdx +7 -3
- package/docs/reference/typescript-api.md +3 -1
- package/docs/subagents/index.mdx +3 -3
- package/docs/tools/overview.mdx +17 -0
- package/docs/tools/workflows.mdx +99 -5
- package/package.json +12 -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{createDurableSessionState}from"#execution/durable-session-store.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";async function dispatchCoordinationStep(e){"use step";let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],sessionState:e.sessionState,pendingTasks:[]};let{batch:n,session:r}=t,i=r,a=[],o=[];for(let r of t.plan){if(r.kind===`workflow-task`){let o=await startWorkflowTask({auth:t.auth,batchEvent:n.event,initiatorAuth:t.initiatorAuth,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r.task});i=o.session,o.result!==void 0&&a.push(o.result);continue}if(r.kind===`task-control`){let e=await executeTaskControlAction({action:r.action,cancelOwnedWork:cancelBackgroundAgentTask,serializedContext:t.serializedContext,session:i});i=e.session,e.pendingTask!==void 0&&o.push(e.pendingTask),a.push(e.result)}}return{results:a,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),pendingTasks:o}}export{dispatchCoordinationStep};
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";async function dispatchCoordinationStep(e){"use step";let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],sessionState:e.sessionState,pendingTasks:[]};let{batch:n,session:r}=t,i=r,a=[],o=[];for(let r of t.plan){if(r.kind===`workflow-task`){let o=await startWorkflowTask({agents:t.workflowAgents,auth:t.auth,batchEvent:n.event,initiatorAuth:t.initiatorAuth,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r.task});i=o.session,o.result!==void 0&&a.push(o.result);continue}if(r.kind===`task-control`){let e=await executeTaskControlAction({action:r.action,cancelOwnedWork:cancelBackgroundAgentTask,serializedContext:t.serializedContext,session:i});i=e.session,e.pendingTask!==void 0&&o.push(e.pendingTask),a.push(e.result)}}return{results:a,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),pendingTasks:o}}export{dispatchCoordinationStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.61.0//executeWorkflowProgram`;export{executeWorkflowProgram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/background.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{preparePersistedStepDynamicToolMetadata}from"#context/dynamic-tool-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{createTaskToolHarnessDefinitions}from"#execution/tools/tasks.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{ASK_QUESTION_TOOL_NAME}from"#harness/request-input-tool.js";import{WEB_SEARCH_TOOL_NAME,resolveWebSearchActivityLabel}from"#harness/provider-tool-schemas.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel,e.abortSignal),r=createNodeHarnessTools({node:e.node}),i=e.instrumentation,a=i?.prepareExecution(),o=createToolLoopHarness({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,handleEvent:e.handleEvent,historyProjector:e.historyProjector,historyView:e.historyView,instrumentation:a,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,resolveStepDynamicTools:t=>preparePersistedStepDynamicToolMetadata({...t,resolvers:e.node.agent.dynamicToolResolvers??[]}),dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?o:async(e,t)=>{try{return await o(e,t)}finally{await i.flush()}}}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),n={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:t.version},r=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),i=process.env.VERCEL_GIT_COMMIT_REF?.trim(),a=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return r||i||a?{...n,build:{deployedAt:a||void 0,gitBranch:i||void 0,gitSha:r||void 0}}:n}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t,n){return r=>dispatchDynamicModelEvent({abortSignal:n,ctx:r.ctx,dynamicModel:t,event:r.event,messages:r.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t}function resolveHarnessToolDefinition(e){let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);return isPreparedRuntimeWorkflowTool(e.tool)?t===null?createPreparedWorkflowToolHarnessDefinition(e.tool):createWorkflowToolHarnessDefinition({executeInput:t.definition.executeInput,definition:createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}),nodeId:e.tool.task.nodeId,resultKind:e.tool.task.resultKind,workflowId:e.tool.task.workflowId}):t===null?(log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null):createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly})}function isPreparedRuntimeWorkflowTool(e){return e.task!==void 0}function createRegisteredHarnessToolDefinition(e){let t=e.definition;if(t.owner.kind===`framework`){let n=createTaskToolHarnessDefinitions().find(e=>e.name===t.name);if(n!==void 0)return{...n,behavior:e.behavior}}let n=t.execute,r=t.owner.kind===`framework`&&t.name===ASK_QUESTION_TOOL_NAME;return{label:t.label??(t.owner.kind===`framework`&&t.name===WEB_SEARCH_TOOL_NAME?{start:resolveWebSearchActivityLabel}:void 0),approvalKey:t.approvalKey,behavior:e.behavior,description:t.description,execution:t.execution,executeInput:t.executeInput,execute:r?void 0:resolveAuthoredExecute({rawExecute:n,scope:t.name}),frameworkAction:t.owner.kind===`framework`&&t.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:t.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:t.name,approval:t.approval,outputSchema:t.outputSchema,rootOnly:e.rootOnly,toModelOutput:t.toModelOutput}}function resolveAuthoredExecute(e){let{rawExecute:t,scope:n}=e;return t===void 0?void 0:createToolExecuteWithAuth({execute:t,scope:n})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/background.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{preparePersistedStepDynamicToolMetadata}from"#context/dynamic-tool-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{createTaskToolHarnessDefinitions}from"#execution/tools/tasks.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{ASK_QUESTION_TOOL_NAME}from"#harness/request-input-tool.js";import{WEB_SEARCH_TOOL_NAME,resolveWebSearchActivityLabel}from"#harness/provider-tool-schemas.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel,e.abortSignal),r=createNodeHarnessTools({node:e.node}),i=e.instrumentation,a=i?.prepareExecution(),o=createToolLoopHarness({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,handleEvent:e.handleEvent,historyProjector:e.historyProjector,historyView:e.historyView,instrumentation:a,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,resolveStepDynamicTools:t=>preparePersistedStepDynamicToolMetadata({...t,resolvers:e.node.agent.dynamicToolResolvers??[]}),dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?o:async(e,t)=>{try{return await o(e,t)}finally{await i.flush()}}}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),n={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:t.version},r=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),i=process.env.VERCEL_GIT_COMMIT_REF?.trim(),a=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return r||i||a?{...n,build:{deployedAt:a||void 0,gitBranch:i||void 0,gitSha:r||void 0}}:n}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t,n){return r=>dispatchDynamicModelEvent({abortSignal:n,ctx:r.ctx,dynamicModel:t,event:r.event,messages:r.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t}function resolveHarnessToolDefinition(e){let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);return isPreparedRuntimeWorkflowTool(e.tool)?t===null?createPreparedWorkflowToolHarnessDefinition(e.tool):createWorkflowToolHarnessDefinition({executeInput:t.definition.executeInput,definition:createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}),nodeId:e.tool.task.nodeId,resultKind:e.tool.task.resultKind,workflowId:e.tool.task.workflowId}):t===null?(log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null):createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly})}function isPreparedRuntimeWorkflowTool(e){return e.task!==void 0}function createRegisteredHarnessToolDefinition(e){let t=e.definition;if(t.owner.kind===`framework`){let n=createTaskToolHarnessDefinitions().find(e=>e.name===t.name);if(n!==void 0)return{...n,behavior:e.behavior}}let n=t.execute,r=t.owner.kind===`framework`&&t.name===ASK_QUESTION_TOOL_NAME;return{availableInSubagents:t.availableInSubagents,label:t.label??(t.owner.kind===`framework`&&t.name===WEB_SEARCH_TOOL_NAME?{start:resolveWebSearchActivityLabel}:void 0),approvalKey:t.approvalKey,behavior:e.behavior,description:t.description,execution:t.execution,executeInput:t.executeInput,execute:r?void 0:resolveAuthoredExecute({rawExecute:n,scope:t.name}),frameworkAction:t.owner.kind===`framework`&&t.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:t.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:t.name,approval:t.approval,outputSchema:t.outputSchema,rootOnly:e.rootOnly,toModelOutput:t.toModelOutput}}function resolveAuthoredExecute(e){let{rawExecute:t,scope:n}=e;return t===void 0?void 0:createToolExecuteWithAuth({execute:t,scope:n})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{findSessionTaskEntry,recordSessionTask}from"#tasks/session-index.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{sendTaskCommand,sendTaskInboundPayload,startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{beginBackgroundTask,createTaskAgentDispatchContext,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{projectToolStartLabel}from"#harness/action-presentation.js";import{createTaskMessage,isTaskMessage}from"#tools/task.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";import{steerBackgroundAgent}from"#execution/tools/subagent/steer.js";const IN_PROCESS_WORKFLOW_EXECUTOR={data:{},kind:`workflow-task`};function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}hasPendingTasks(){return this.records.some(e=>e.settled&&e.task!==void 0)}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=recordSessionTask(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[{callId:e.callId,taskInboxToken:e.task.taskInboxToken,taskId:e.task.taskId,taskRunId:e.task.taskRunId}]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e}}async start(e){let t={callId:e.options.toolCallId,settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t});if(i.kind===`steered`)return t.settled=!0,i.receipt;let a=i.task;t.task=a;let o={binding:{taskId:a.taskId,token:a.taskInboxToken},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:this.initialSession,task:a,taskId:a.taskId};if(e.definition.workflowId!==void 0)return t.settled=!0,{...i.receipt,status:`working`,taskId:a.taskId};let s=e.definition.execute(e.toolInput,e.options,o),c=isAsyncIterable(s)?await executeBackgroundIterable({callId:e.options.toolCallId,output:s,task:a}):await s;return isAuthorizationSignal(c)?c:(await deliverTaskCommand(a,{data:parseJsonValue(c),kind:`complete`}),t.settled=!0,{status:`working`,taskId:a.taskId})}async startTask(e){let t=e.input.definition.workflowId===void 0?void 0:{...e.input.definition,workflowId:e.input.definition.workflowId},n=t===void 0?void 0:parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t?.resultKind===`subagent`&&n!==void 0?projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}}):void 0;if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o=projectToolStartLabel(e.input.definition,e.input.toolInput),s=buildCallbackContext().session,c={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,label:o,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,dispatchContext:createTaskAgentDispatchContext(e.ctx,s.auth),metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession};if(t===void 0)return{kind:`started`,task:await beginBackgroundTask({activityObserver:c.activityObserver,callId:c.callId,dispatchContext:c.dispatchContext,metadata:c.metadata,parentSessionId:c.parentSessionId,parentStepIndex:c.parentStepIndex,parentTurnId:c.parentTurnId,session:c.session})};if(n===void 0)throw Error(`Background workflow tool "${e.input.definition.name}" has no input.`);let l={...prepareBackgroundTask(c),activityWorkIdentity:t.resultKind===`subagent`?c.activityObserver?.workIdentity:void 0};if(t.resultKind===`subagent`&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:c.callId,kind:`reserve`,operationId:t.operation.id,ownerId:l.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.resultKind===`subagent`&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:c.callId,parentSessionId:c.parentSessionId,parentTurnId:r}),a=this.applyAgentHandleCommand({agentId:i.metadata.agentId,callId:c.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:l.taskId});if(a.kind===`busy`&&a.handle.phase===`claimed`){let t=a.handle,r=findSessionTaskEntry(this.agentHandleSession.state,t.ownerId);if(r?.metadata.kind===`subagent`&&r.metadata.agentId===t.identity.id&&r.metadata.name===t.identity.name&&r.terminalView===void 0)return await steerBackgroundAgent({ctx:e.ctx,handle:t,callId:c.callId,input:n,session:this.agentHandleSession}),{kind:`steered`,receipt:{agentId:t.identity.id,taskId:r.taskId,status:`working`}}}readClaimedHandle(a)?e.record.claim={operationId:t,taskId:l.taskId}:throwAgentClaimError(i.metadata.agentId,a)}await startTaskRun({activityObserver:c.activityObserver,initialView:{metadata:l.metadata,status:`working`,taskId:l.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:l.taskInboxToken,workflow:{callId:c.callId,executeInput:t.executeInput?.(n),input:n,resultKind:t.resultKind,session:s,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,taskId:l.taskId,workflowId:t.workflowId}});let u=await waitForTaskCommandOwner({taskInboxToken:l.taskInboxToken}),d={...l,executor:IN_PROCESS_WORKFLOW_EXECUTOR,taskRunId:u.runId};return e.record.task=d,t.resultKind!==`subagent`||i===void 0?{kind:`started`,task:d}:{kind:`started`,receipt:i.receipt,task:d}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};async function executeBackgroundIterable(e){let t=e.output[Symbol.asyncIterator](),n=0,r=await t.next();for(;!r.done;){let i=isTaskMessage(r.value)?{callId:e.callId,kind:`task-message`,message:r.value.message,messageEpoch:e.task.taskId,messageIndex:n++}:{callId:e.callId,kind:`task-update`,message:typeof r.value==`string`?r.value:JSON.stringify(r.value),updateEpoch:e.task.taskId,updateIndex:n++};if(await sendTaskInboundPayload({payload:i,taskInboxToken:e.task.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.task.taskId}" did not accept "${i.kind}".`);r=await t.next()}return r.value??null}function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{findSessionTaskEntry,recordSessionTask}from"#tasks/session-index.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveWorkflowAgentMetadata}from"#execution/tools/subagent/metadata.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{sendTaskCommand,sendTaskInboundPayload,startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{beginBackgroundTask,createTaskAgentDispatchContext,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{projectToolStartLabel}from"#harness/action-presentation.js";import{createTaskMessage,isTaskMessage}from"#tools/task.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";import{steerBackgroundAgent}from"#execution/tools/subagent/steer.js";const IN_PROCESS_WORKFLOW_EXECUTOR={data:{},kind:`workflow-task`};function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}hasPendingTasks(){return this.records.some(e=>e.settled&&e.task!==void 0)}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=recordSessionTask(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[{callId:e.callId,taskInboxToken:e.task.taskInboxToken,taskId:e.task.taskId,taskRunId:e.task.taskRunId}]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e}}async start(e){let t={callId:e.options.toolCallId,settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t});if(i.kind===`steered`)return t.settled=!0,i.receipt;let a=i.task;t.task=a;let o={binding:{taskId:a.taskId,token:a.taskInboxToken},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:this.initialSession,task:a,taskId:a.taskId};if(e.definition.workflowId!==void 0)return t.settled=!0,{...i.receipt,status:`working`,taskId:a.taskId};let s=e.definition.execute(e.toolInput,e.options,o),c=isAsyncIterable(s)?await executeBackgroundIterable({callId:e.options.toolCallId,output:s,task:a}):await s;return isAuthorizationSignal(c)?c:(await deliverTaskCommand(a,{data:parseJsonValue(c),kind:`complete`}),t.settled=!0,{status:`working`,taskId:a.taskId})}async startTask(e){let t=e.input.definition.workflowId===void 0?void 0:{...e.input.definition,workflowId:e.input.definition.workflowId},n=t===void 0?void 0:parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t?.resultKind===`subagent`&&n!==void 0?projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}}):void 0;if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o=projectToolStartLabel(e.input.definition,e.input.toolInput),s=buildCallbackContext().session,c={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,label:o,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,dispatchContext:createTaskAgentDispatchContext(e.ctx,s.auth),metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession};if(t===void 0)return{kind:`started`,task:await beginBackgroundTask({activityObserver:c.activityObserver,callId:c.callId,dispatchContext:c.dispatchContext,metadata:c.metadata,parentSessionId:c.parentSessionId,parentStepIndex:c.parentStepIndex,parentTurnId:c.parentTurnId,session:c.session})};if(n===void 0)throw Error(`Background workflow tool "${e.input.definition.name}" has no input.`);let l={...prepareBackgroundTask(c),activityWorkIdentity:t.resultKind===`subagent`?c.activityObserver?.workIdentity:void 0};if(t.resultKind===`subagent`&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:c.callId,kind:`reserve`,operationId:t.operation.id,ownerId:l.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.resultKind===`subagent`&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:c.callId,parentSessionId:c.parentSessionId,parentTurnId:r}),a=this.applyAgentHandleCommand({agentId:i.metadata.agentId,callId:c.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:l.taskId});if(a.kind===`busy`&&a.handle.phase===`claimed`){let t=a.handle,r=findSessionTaskEntry(this.agentHandleSession.state,t.ownerId);if(r?.metadata.kind===`subagent`&&r.metadata.agentId===t.identity.id&&r.metadata.name===t.identity.name&&r.terminalView===void 0)return await steerBackgroundAgent({ctx:e.ctx,handle:t,callId:c.callId,input:n,session:this.agentHandleSession}),{kind:`steered`,receipt:{agentId:t.identity.id,taskId:r.taskId,status:`working`}}}readClaimedHandle(a)?e.record.claim={operationId:t,taskId:l.taskId}:throwAgentClaimError(i.metadata.agentId,a)}await startTaskRun({activityObserver:c.activityObserver,initialView:{metadata:l.metadata,status:`working`,taskId:l.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:l.taskInboxToken,workflow:{agents:resolveWorkflowAgentMetadata(e.ctx),callId:c.callId,executeInput:t.executeInput?.(n),input:n,resultKind:t.resultKind,session:s,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,taskId:l.taskId,workflowId:t.workflowId}});let u=await waitForTaskCommandOwner({taskInboxToken:l.taskInboxToken}),d={...l,executor:IN_PROCESS_WORKFLOW_EXECUTOR,taskRunId:u.runId};return e.record.task=d,t.resultKind!==`subagent`||i===void 0?{kind:`started`,task:d}:{kind:`started`,receipt:i.receipt,task:d}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};async function executeBackgroundIterable(e){let t=e.output[Symbol.asyncIterator](),n=0,r=await t.next();for(;!r.done;){let i=isTaskMessage(r.value)?{callId:e.callId,kind:`task-message`,message:r.value.message,messageEpoch:e.task.taskId,messageIndex:n++}:{callId:e.callId,kind:`task-update`,message:typeof r.value==`string`?r.value:JSON.stringify(r.value),updateEpoch:e.task.taskId,updateIndex:n++};if(await sendTaskInboundPayload({payload:i,taskInboxToken:e.task.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.task.taskId}" did not accept "${i.kind}".`);r=await t.next()}return r.value??null}function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { JsonValue } from "#shared/json.js";
|
|
2
|
+
import type { WorkflowToolContext } from "#tools/workflow-definition.js";
|
|
3
|
+
import type { AgentRouterInput } from "#execution/tools/agent-router.js";
|
|
4
|
+
/** Routes one task through the complete workflow agent metadata snapshot. */
|
|
5
|
+
export declare function executeAgentRouterTool(input: AgentRouterInput, ctx: WorkflowToolContext): Promise<JsonValue>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.61.0//executeAgentRouterTool`;export{executeAgentRouterTool};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from "#compiled/zod/index.js";
|
|
2
|
+
import type { JsonObject } from "#shared/json.js";
|
|
3
|
+
export { executeAgentRouterTool } from "#execution/tools/agent-router-workflow.js";
|
|
4
|
+
export declare const AGENT_ROUTER_TOOL_DESCRIPTION = "Route a task to the best available subagent based on each subagent's declared description.";
|
|
5
|
+
export interface AgentRouterInput {
|
|
6
|
+
readonly message: string;
|
|
7
|
+
readonly outputSchema?: JsonObject;
|
|
8
|
+
}
|
|
9
|
+
export declare const AGENT_ROUTER_INPUT_SCHEMA: z.ZodType<AgentRouterInput>;
|
|
@@ -0,0 +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.record(z.string(),z.json()).describe(`Optional JSON Schema the selected agent's output must match.`).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.0//executeSleepTool`;export{executeSleepTool};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ContextReader } from "#context/key.js";
|
|
2
|
+
import type { WorkflowAgentMetadata } from "#tools/workflow-definition.js";
|
|
3
|
+
/** Snapshots callable agent metadata for one workflow tool run. */
|
|
4
|
+
export declare function resolveWorkflowAgentMetadata(ctx: ContextReader): Readonly<Record<string, WorkflowAgentMetadata>>;
|
|
@@ -0,0 +1 @@
|
|
|
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,7 +1,10 @@
|
|
|
1
1
|
import type { SessionContext } from "#context/session-context.js";
|
|
2
|
+
import type { WorkflowToolContext } from "#tools/workflow-definition.js";
|
|
2
3
|
import { type WorkflowToolRunOutcome, type WorkflowToolRunOwner, type WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
|
|
3
4
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
4
5
|
export interface WorkflowBodyDefinition {
|
|
6
|
+
/** Snapshot added for new runs; absent only when resuming an older durable payload. */
|
|
7
|
+
readonly agents?: WorkflowToolContext["agents"];
|
|
5
8
|
readonly callId: string;
|
|
6
9
|
readonly executeInput?: JsonValue;
|
|
7
10
|
readonly input: JsonObject;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{createTaskMessage}from"#tools/task.js";import{ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{agent}from"#execution/tools/subagent/invoke-agent.js";import"#execution/tools/workflow/messages.js";import{readRegisteredWorkflow}from"#execution/workflow-registry.js";async function executeWorkflowBody(e,t){let n=createWorkflowBodyRef(e),r=createWorkflowBodyContext(e,t);attachWorkflowToolRunContext(r,{from:n,owner:e.owner});let i=0;try{let t=resolveWorkflowToolExecute(e),a=e.execution===`background`?createWorkflowTaskExec(e):void 0,o=t(e.executeInput??e.input,r,a),s;if(!isAsyncIterable(o))s=await o;else{let t=o[Symbol.asyncIterator](),r,a=await t.next();for(;a.done!==!0;){r=a.value;let o={from:n,update:a.value};await resumeHookStep(e.owner.inbox,{kind:`report`,...o}),i+=1,a=await t.next()}s=a.value??(e.execution===`blocking`?r:void 0)??null}return{outcome:{output:s,status:`completed`},reportCount:i}}catch(e){return t.aborted?{outcome:{reason:t.reason instanceof Error?t.reason.message:String(t.reason??``),status:`cancelled`},reportCount:i}:{outcome:{error:normalizeSerializableError(e),status:`failed`},reportCount:i}}}function createWorkflowBodyRef(e){return{callId:e.callId,execution:e.execution,input:e.input,resultKind:e.resultKind,runId:e.runId??getWorkflowMetadata().workflowRunId,sequence:e.session.turn.sequence,stepIndex:e.stepIndex,toolName:e.toolName,turnId:e.session.turn.id}}function resolveWorkflowToolExecute(e){let t=readRegisteredWorkflow(e.workflowId);if(typeof t!=`function`)throw Error(`Tool "${e.toolName}" is not registered as a workflow in this deployment (${e.workflowId}). The tool was renamed or removed after this run started.`);return t}function createWorkflowBodyContext(e,t){let unavailable=(t,n)=>{throw Error(`ctx.${t} is not available inside a workflow tool; ${n}. Tool "${e.toolName}" runs as a durable workflow body, which only replays deterministic code.`)},n={agent:((e,t)=>agent(n,e,t)),ask:e=>ask(n,e),abortSignal:t,callId:e.callId,getSandbox:()=>unavailable(`getSandbox()`,`the session sandbox belongs to the turn`),getSkill:()=>unavailable(`getSkill()`,`skills are read through the session sandbox`),getToken:()=>unavailable(`getToken()`,`pass ctx directly to a "use step" helper to resolve credentials`),requireAuth:()=>unavailable(`requireAuth()`,`pass ctx directly to a "use step" helper to request authorization`),session:e.session,toolName:e.toolName};return n}function createWorkflowTaskExec(e){if(e.taskId===void 0)throw Error(`Background workflow tool "${e.toolName}" has no task id.`);return{binding:{taskId:e.taskId,token:e.taskId},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:void 0,task:void 0,taskId:e.taskId}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}export{createWorkflowBodyRef,executeWorkflowBody};
|
|
1
|
+
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{createTaskMessage}from"#tools/task.js";import{ask,attachWorkflowToolRunContext}from"#execution/tools/workflow/ask.js";import{agent}from"#execution/tools/subagent/invoke-agent.js";import"#execution/tools/workflow/messages.js";import{readRegisteredWorkflow}from"#execution/workflow-registry.js";async function executeWorkflowBody(e,t){let n=createWorkflowBodyRef(e),r=createWorkflowBodyContext(e,t);attachWorkflowToolRunContext(r,{from:n,owner:e.owner});let i=0;try{let t=resolveWorkflowToolExecute(e),a=e.execution===`background`?createWorkflowTaskExec(e):void 0,o=t(e.executeInput??e.input,r,a),s;if(!isAsyncIterable(o))s=await o;else{let t=o[Symbol.asyncIterator](),r,a=await t.next();for(;a.done!==!0;){r=a.value;let o={from:n,update:a.value};await resumeHookStep(e.owner.inbox,{kind:`report`,...o}),i+=1,a=await t.next()}s=a.value??(e.execution===`blocking`?r:void 0)??null}return{outcome:{output:s,status:`completed`},reportCount:i}}catch(e){return t.aborted?{outcome:{reason:t.reason instanceof Error?t.reason.message:String(t.reason??``),status:`cancelled`},reportCount:i}:{outcome:{error:normalizeSerializableError(e),status:`failed`},reportCount:i}}}function createWorkflowBodyRef(e){return{callId:e.callId,execution:e.execution,input:e.input,resultKind:e.resultKind,runId:e.runId??getWorkflowMetadata().workflowRunId,sequence:e.session.turn.sequence,stepIndex:e.stepIndex,toolName:e.toolName,turnId:e.session.turn.id}}function resolveWorkflowToolExecute(e){let t=readRegisteredWorkflow(e.workflowId);if(typeof t!=`function`)throw Error(`Tool "${e.toolName}" is not registered as a workflow in this deployment (${e.workflowId}). The tool was renamed or removed after this run started.`);return t}function createWorkflowBodyContext(e,t){let unavailable=(t,n)=>{throw Error(`ctx.${t} is not available inside a workflow tool; ${n}. Tool "${e.toolName}" runs as a durable workflow body, which only replays deterministic code.`)},n={agent:((e,t)=>agent(n,e,t)),agents:Object.freeze(Object.fromEntries(Object.entries(e.agents??{}).map(([e,t])=>[e,Object.freeze({...t})]))),ask:e=>ask(n,e),abortSignal:t,callId:e.callId,getSandbox:()=>unavailable(`getSandbox()`,`the session sandbox belongs to the turn`),getSkill:()=>unavailable(`getSkill()`,`skills are read through the session sandbox`),getToken:()=>unavailable(`getToken()`,`pass ctx directly to a "use step" helper to resolve credentials`),requireAuth:()=>unavailable(`requireAuth()`,`pass ctx directly to a "use step" helper to request authorization`),session:e.session,toolName:e.toolName};return n}function createWorkflowTaskExec(e){if(e.taskId===void 0)throw Error(`Background workflow tool "${e.toolName}" has no task id.`);return{binding:{taskId:e.taskId,token:e.taskId},postMessage:createTaskMessage,send(){throw Error(`task.send() was replaced by yielded task descriptors.`)},session:void 0,task:void 0,taskId:e.taskId}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}export{createWorkflowBodyRef,executeWorkflowBody};
|
|
@@ -7,6 +7,7 @@ import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js
|
|
|
7
7
|
export declare function startWorkflowToolRun(input: Omit<WorkflowToolRunInput, "hookToken">): Promise<WorkflowToolRunAddress>;
|
|
8
8
|
/** Starts one durable workflow task and records it on the owning session. */
|
|
9
9
|
export declare function startWorkflowTask(input: {
|
|
10
|
+
readonly agents: WorkflowToolRunInput["agents"];
|
|
10
11
|
readonly auth: SessionAuth["current"];
|
|
11
12
|
readonly batchEvent: {
|
|
12
13
|
readonly sequence: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{toError}from"#shared/errors.js";import{startWorkflowOnCurrentDeployment,workflowToolRunWorkflowReference}from"#execution/workflow-runtime.js";import{recordWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";const log=createLogger(`execution.workflow-tool-run`);async function startWorkflowToolRun(e){let t=crypto.randomUUID();return{hookToken:t,runId:(await startWorkflowOnCurrentDeployment(workflowToolRunWorkflowReference,[{...e,hookToken:t}])).runId}}async function startWorkflowTask(e){let{task:t,batchEvent:n,session:r}=e;try{let i=await startWorkflowToolRun({callId:t.callId,executeInput:t.executeInput,input:t.input,owner:e.owner,resultKind:t.resultKind,session:{auth:{current:e.auth,initiator:e.initiatorAuth},id:r.sessionId,parent:e.parentSession,turn:{id:n.turnId,sequence:n.sequence}},stepIndex:n.stepIndex,toolName:t.toolName,workflowId:t.workflowId});return{session:recordWorkflowToolRun(r,{callId:t.callId,hookToken:i.hookToken,resultKind:t.resultKind??`tool`,runId:i.runId,toolName:t.toolName})}}catch(e){return logError(log,`workflow tool run failed to start`,e,{callId:t.callId,toolName:t.toolName}),{result:createRuntimeToolResultFromValue({callId:t.callId,isError:!0,output:toError(e),toolName:t.toolName}),session:r}}}export{startWorkflowTask,startWorkflowToolRun};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{toError}from"#shared/errors.js";import{startWorkflowOnCurrentDeployment,workflowToolRunWorkflowReference}from"#execution/workflow-runtime.js";import{recordWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";const log=createLogger(`execution.workflow-tool-run`);async function startWorkflowToolRun(e){let t=crypto.randomUUID();return{hookToken:t,runId:(await startWorkflowOnCurrentDeployment(workflowToolRunWorkflowReference,[{...e,hookToken:t}])).runId}}async function startWorkflowTask(e){let{task:t,batchEvent:n,session:r}=e;try{let i=await startWorkflowToolRun({agents:e.agents,callId:t.callId,executeInput:t.executeInput,input:t.input,owner:e.owner,resultKind:t.resultKind,session:{auth:{current:e.auth,initiator:e.initiatorAuth},id:r.sessionId,parent:e.parentSession,turn:{id:n.turnId,sequence:n.sequence}},stepIndex:n.stepIndex,toolName:t.toolName,workflowId:t.workflowId});return{session:recordWorkflowToolRun(r,{callId:t.callId,hookToken:i.hookToken,resultKind:t.resultKind??`tool`,runId:i.runId,toolName:t.toolName})}}catch(e){return logError(log,`workflow tool run failed to start`,e,{callId:t.callId,toolName:t.toolName}),{result:createRuntimeToolResultFromValue({callId:t.callId,isError:!0,output:toError(e),toolName:t.toolName}),session:r}}}export{startWorkflowTask,startWorkflowToolRun};
|
|
@@ -2,12 +2,14 @@ import type { SessionContext } from "#context/session-context.js";
|
|
|
2
2
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
3
3
|
import type { TaskExecutorBinding } from "#tools/task.js";
|
|
4
4
|
import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
|
|
5
|
+
import type { WorkflowAgentMetadata } from "#tools/workflow-definition.js";
|
|
5
6
|
export type WorkflowToolRunSessionContext = SessionContext["session"];
|
|
6
7
|
export declare const WORKFLOW_TOOL_EXECUTOR_KIND = "workflow-tool";
|
|
7
8
|
/** Private task executor binding for the workflow tool run doing the task's work. */
|
|
8
9
|
export declare function createWorkflowToolExecutorBinding(input: WorkflowToolRunAddress): TaskExecutorBinding;
|
|
9
10
|
export declare function readWorkflowToolExecutorAddress(executor: TaskExecutorBinding | undefined): WorkflowToolRunAddress | undefined;
|
|
10
11
|
export interface WorkflowToolRunInput {
|
|
12
|
+
readonly agents: Readonly<Record<string, WorkflowAgentMetadata>>;
|
|
11
13
|
readonly callId: string;
|
|
12
14
|
readonly execution?: "background" | "blocking";
|
|
13
15
|
readonly executeInput?: JsonValue;
|
|
@@ -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.0`,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};
|