eve 0.79.2 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/src/compiled/.vendor-stamp.json +8 -8
- package/dist/src/compiled/@chat-adapter/slack/api.d.ts +6 -0
- package/dist/src/compiled/@chat-adapter/slack/api.js +1 -1
- package/dist/src/compiled/@chat-adapter/slack/blocks.js +1 -1
- package/dist/src/compiled/@chat-adapter/slack/format.js +1 -1
- package/dist/src/compiled/@chat-adapter/slack/index.d.ts +14 -8
- package/dist/src/compiled/@chat-adapter/slack/index.js +33 -32
- package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +37 -1
- package/dist/src/compiled/@chat-adapter/twilio/index.js +2 -2
- package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.js +1 -1
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +1 -1
- package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/ai-sdk-telemetry.d.ts +2 -2
- package/dist/src/compiled/{@eve/tracing/agent-tracing.d.ts → @vercel/agent-runs/agent-run.d.ts} +3 -3
- package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/index.d.ts +1 -1
- package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/index.js +1 -1
- package/dist/src/compiled/@vercel/connect/index.js +5 -5
- package/dist/src/compiled/@vercel/connect/token.d.ts +11 -1
- package/dist/src/compiled/@workflow/world-vercel/index.js +3 -3
- package/dist/src/compiled/_chunks/node/chunk-NBSLXVG3-Bt7pDfyn.js +12 -0
- package/dist/src/compiled/_chunks/node/dist-BKsV21Vu.js +6 -0
- package/dist/src/compiled/_chunks/node/dist-CO_n_hUa.js +98 -0
- package/dist/src/compiled/chat/index.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +6 -6
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +8 -4
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/context/schedule-collection-tools.js +1 -1
- package/dist/src/execution/catalog/connection-auth.d.ts +4 -2
- package/dist/src/execution/catalog/connection-auth.js +1 -1
- package/dist/src/execution/catalog/connection-entry.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session-event-stream.js +1 -1
- package/dist/src/execution/stable-workflow-names.d.ts +2 -0
- package/dist/src/execution/stable-workflow-names.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/web-fetch/execute.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +6 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/extensions/git/extension/extension.d.ts +3 -1
- package/dist/src/extensions/git/extension/extension.js +1 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/extensions/git/extension/lib/github-shell.d.ts +14 -0
- package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
- package/dist/src/harness/compaction/engine.js +2 -2
- package/dist/src/harness/compaction/prompt.d.ts +6 -0
- package/dist/src/harness/compaction/prompt.js +1 -1
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/errors.d.ts +2 -2
- package/dist/src/harness/model-call/recovery.d.ts +2 -3
- package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -1
- package/dist/src/instrumentation/principal-summary.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +1 -1
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/session-init.d.ts +2 -1
- package/dist/src/instrumentation/session-init.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/authored-definition/schedule-collection.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +4 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +2 -2
- package/dist/src/internal/logging.js +1 -1
- package/dist/src/internal/nitro/host/application-route-registry.d.ts +7 -2
- package/dist/src/internal/nitro/host/application-route-registry.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/external-dependency-output-check-plugin.d.ts +23 -0
- package/dist/src/internal/nitro/host/external-dependency-output-check-plugin.js +3 -0
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +3 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/nitro/routes/connection-events.d.ts +5 -0
- package/dist/src/internal/nitro/routes/connection-events.js +1 -0
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -1
- package/dist/src/public/channels/slack/blocks.js +2 -2
- package/dist/src/public/connections/index.d.ts +1 -0
- package/dist/src/public/definitions/connections/events.d.ts +43 -0
- package/dist/src/public/definitions/connections/events.js +1 -0
- package/dist/src/public/definitions/connections/mcp.d.ts +3 -0
- package/dist/src/public/schedules/subscription.d.ts +4 -3
- package/dist/src/runtime/connections/events/actions.d.ts +17 -0
- package/dist/src/runtime/connections/events/actions.js +1 -0
- package/dist/src/runtime/connections/events/delivery.d.ts +10 -0
- package/dist/src/runtime/connections/events/delivery.js +1 -0
- package/dist/src/runtime/connections/events/dispatch-step.d.ts +20 -0
- package/dist/src/runtime/connections/events/dispatch-step.js +1 -0
- package/dist/src/runtime/connections/events/lifecycle-step.d.ts +42 -0
- package/dist/src/runtime/connections/events/lifecycle-step.js +1 -0
- package/dist/src/runtime/connections/events/owner.d.ts +38 -0
- package/dist/src/runtime/connections/events/owner.js +1 -0
- package/dist/src/runtime/connections/events/path.d.ts +4 -0
- package/dist/src/runtime/connections/events/path.js +1 -0
- package/dist/src/runtime/connections/events/state.d.ts +37 -0
- package/dist/src/runtime/connections/events/state.js +1 -0
- package/dist/src/runtime/connections/events/workflow.d.ts +28 -0
- package/dist/src/runtime/connections/events/workflow.js +1 -0
- package/dist/src/runtime/connections/mcp-client.d.ts +4 -2
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/schedules/collection-client.d.ts +0 -2
- package/dist/src/runtime/schedules/collection-client.js +1 -1
- package/dist/src/runtime/types.d.ts +11 -0
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/dist/src/setup/scaffold/update/connections.js +2 -2
- package/dist/src/setup/scaffold/version-tokens.d.ts +1 -1
- package/dist/src/setup/scaffold/version-tokens.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +12 -4
- package/dist/src/shared/connection-events.d.ts +84 -0
- package/dist/src/shared/connection-events.js +1 -0
- package/dist/src/shared/connection-types.d.ts +10 -0
- package/dist/src/shared/validate-authorization.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/no-reply.d.ts +5 -0
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tracing/eve/agent-approval-instrumentation.d.ts +2 -2
- package/dist/src/tracing/eve/agent-channel-delivery-instrumentation.js +1 -1
- package/dist/src/tracing/eve/agent-memory-instrumentation.d.ts +2 -2
- package/dist/src/tracing/eve/agent-memory-instrumentation.js +1 -1
- package/dist/src/tracing/eve/agent-otel-provider.d.ts +1 -1
- package/dist/src/tracing/eve/agent-tool-instrumentation.d.ts +3 -3
- package/dist/src/tracing/eve/agent-trace-context.js +1 -1
- package/dist/src/tracing/eve/agent-trace-state.d.ts +1 -1
- package/dist/src/tracing/eve/connection-events.d.ts +25 -0
- package/dist/src/tracing/eve/connection-events.js +1 -0
- package/dist/src/tracing/eve/content-span-processor.js +1 -1
- package/dist/src/tracing/eve/delegation.js +1 -1
- package/dist/src/tracing/eve/gateway.d.ts +1 -1
- package/dist/src/tracing/eve/install-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
- package/dist/src/tracing/eve/mcp.d.ts +2 -1
- package/dist/src/tracing/eve/mcp.js +1 -1
- package/dist/src/tracing/eve/metadata.d.ts +1 -1
- package/dist/src/tracing/eve/operation-input.d.ts +2 -2
- package/dist/src/tracing/eve/operation-input.js +1 -1
- package/dist/src/tracing/eve/otel-declaration.d.ts +5 -0
- package/dist/src/tracing/eve/otel-registration.d.ts +2 -2
- package/dist/src/tracing/eve/otel-registration.js +1 -1
- package/dist/src/tracing/eve/profile.d.ts +1 -1
- package/dist/src/tracing/eve/session.d.ts +2 -2
- package/dist/src/tracing/local/trace-summary.js +1 -1
- package/docs/agent-config.md +38 -13
- package/docs/code-extension.mdx +28 -0
- package/docs/concepts/built-in-tools.md +2 -0
- package/docs/connections/mcp.mdx +105 -0
- package/docs/connections/openapi.mdx +2 -0
- package/docs/guides/instrumentation/otel.mdx +10 -0
- package/docs/sandbox/vercel.mdx +46 -0
- package/package.json +8 -8
- package/dist/src/compiled/_chunks/node/chunk-6QHBXN7B-gl4n6nmi.js +0 -12
- package/dist/src/compiled/_chunks/node/dist-DYDVZ-FS.js +0 -98
- package/dist/src/compiled/_chunks/node/dist-iEFkK9qw.js +0 -6
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/agent-transport.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/ai-sdk-payload.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/otel-error.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/otel-ids.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/otel.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/adapters/serialization.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/ai-sdk.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/ai-sdk.js +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/capture.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/activation.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/attributes.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/content-policy.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/context.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/delegation.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/mcp.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/scopes.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/snapshot.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/span-kinds.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/types.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/core/writer.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/delegation.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/delegation.js +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/operations.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/otel.d.ts +0 -0
- /package/dist/src/compiled/{@eve/tracing → @vercel/agent-runs}/otel.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:resolveFrameworkRuntimeImport(t)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?normalizeEsmImportSpecifier(i.resolvedId):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:resolveRuntimeLoaderFrameworkImport(n)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:normalizeEsmImportSpecifier(t)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:normalizeEsmImportSpecifier(e)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies};
|
|
1
|
+
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:resolveFrameworkRuntimeImport(t)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?normalizeEsmImportSpecifier(i.resolvedId):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:resolveRuntimeLoaderFrameworkImport(n)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:normalizeEsmImportSpecifier(t)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:normalizeEsmImportSpecifier(e)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies,packageImportName,resolveConfiguredExternalDependency};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
type RolldownOutputChunk = {
|
|
1
|
+
export type RolldownOutputChunk = {
|
|
2
2
|
readonly type: "chunk";
|
|
3
3
|
readonly code: string;
|
|
4
4
|
readonly fileName: string;
|
|
5
5
|
readonly imports: readonly string[];
|
|
6
6
|
readonly dynamicImports: readonly string[];
|
|
7
7
|
};
|
|
8
|
-
type RolldownOutputAsset = {
|
|
8
|
+
export type RolldownOutputAsset = {
|
|
9
9
|
readonly type: "asset";
|
|
10
10
|
readonly fileName: string;
|
|
11
11
|
readonly source: string | Uint8Array;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isNonEmptyString,isObject}from"#shared/guards.js";import{inspect}from"node:util";import{SpanStatusCode,trace}from"#compiled/@opentelemetry/api/index.js";import{truncateTelemetryText}from"#compiled/@
|
|
1
|
+
import{isNonEmptyString,isObject}from"#shared/guards.js";import{inspect}from"node:util";import{SpanStatusCode,trace}from"#compiled/@opentelemetry/api/index.js";import{truncateTelemetryText}from"#compiled/@vercel/agent-runs/otel.js";import{currentCapture}from"#compiled/@vercel/agent-runs/index.js";import{getErrorMessage}from"#compiled/@ai-sdk/provider/index.js";const LEVEL_SEVERITY={debug:10,info:20,warn:30,error:40};function createLogger(e){return{debug(t,n){write(`debug`,e,t,n)},info(t,n){write(`info`,e,t,n)},warn(t,n){write(`warn`,e,t,n)},error(t,n){write(`error`,e,t,n),recordOnActiveSpan(t,n)}}}function logError(e,t,n,r){let i=formatError(n);return e.error(t,{...r,error:i}),typeof i.errorId==`string`?i.errorId:createErrorId()}function createErrorId(){return crypto.randomUUID()}function formatError(e,t){let n={errorId:t??createErrorId(),message:extractErrorMessage(e)},r=extractErrorName(e);return r!==void 0&&(n.name=r),n.detail=inspectError(e),n}function extractErrorName(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(isObject(e)&&isNonEmptyString(e.name)&&e.name!==`Error`)return e.name}function extractErrorMessage(e){return isObject(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:getErrorMessage(e)}function extractErrorId(e){if(isObject(e))return isNonEmptyString(e.errorId)?e.errorId:void 0}function formatErrorHint(e){let t=isObject(e.details)?e.details.name:void 0,n=isNonEmptyString(t)?t:void 0,r=typeof e.message==`string`?e.message.trim():``;return n&&r.length>0?` (${n}: ${truncateForDisplay(r)})`:n?` (${n})`:r.length>0?` (${truncateForDisplay(r)})`:``}function truncateForDisplay(e,t=160){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function recordErrorOnSpan(e,t){if(currentCapture()?.recordOutputs===!1){e.setStatus({code:SpanStatusCode.ERROR});return}let n=truncateTelemetryText(t instanceof Error?t.message:getErrorMessage(t),4096),r=t instanceof Error?truncateTelemetryText(t.name,128):`Error`;e.setStatus({code:SpanStatusCode.ERROR,message:n}),e.recordException({message:n,name:r,stack:inspectError(t)})}function resolveThreshold(){let e=process.env.EVE_LOG_LEVEL?.toLowerCase();return e===`debug`||e===`info`||e===`warn`||e===`error`?LEVEL_SEVERITY[e]:LEVEL_SEVERITY.info}function isLogLevelEnabled(e){return LEVEL_SEVERITY[e]>=resolveThreshold()}let logRecordSubscriber;function setLogRecordSubscriber(e){logRecordSubscriber=e}function write(e,t,n,r){if(LEVEL_SEVERITY[e]<resolveThreshold())return;let i=logRecordSubscriber;if(i!==void 0)try{i(r===void 0?{level:e,namespace:t,message:n}:{level:e,namespace:t,message:n,fields:renderFields(r)});return}catch{}let a=e===`error`?console.error:e===`warn`?console.warn:console.log,o=`[eve:${t}] ${n}`;if(r===void 0){a(o);return}a(o,renderFields(r))}function renderFields(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=formatError(r);continue}t[n]=r}return t}function recordOnActiveSpan(e,t){let n=trace.getActiveSpan();if(n===void 0)return;let r=t?.error;if(currentCapture()?.recordOutputs===!1){(r instanceof Error||isFormattedError(r))&&n.setStatus({code:SpanStatusCode.ERROR});return}if(r instanceof Error){recordErrorOnSpan(n,r);return}if(isFormattedError(r)){let e=truncateTelemetryText(r.message,4096);n.setStatus({code:SpanStatusCode.ERROR,message:e}),n.recordException({message:e,name:typeof r.name==`string`?truncateTelemetryText(r.name,128):`Error`,stack:typeof r.detail==`string`?truncateTelemetryText(r.detail,8192):void 0});return}n.addEvent(e,t?renderFields(t):void 0)}function isFormattedError(e){return isObject(e)&&typeof e.errorId==`string`&&typeof e.message==`string`}function inspectError(e){return truncate(inspect(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function truncate(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=e.slice(0,t);for(;Buffer.byteLength(n,`utf8`)>t&&n.length>0;)n=n.slice(0,-1);return`${n}<…truncated>`}export{createErrorId,createLogger,extractErrorId,formatError,formatErrorHint,inspectError,isLogLevelEnabled,logError,recordErrorOnSpan,setLogRecordSubscriber};
|
|
@@ -18,7 +18,12 @@ export interface ApplicationChannelPreflightRoute {
|
|
|
18
18
|
readonly path: string;
|
|
19
19
|
readonly cors: NormalizedChannelCorsOptions;
|
|
20
20
|
}
|
|
21
|
-
export type ApplicationRouteRegistration =
|
|
21
|
+
export type ApplicationRouteRegistration = {
|
|
22
|
+
readonly kind: "connection-event";
|
|
23
|
+
readonly method: "POST";
|
|
24
|
+
readonly path: string;
|
|
25
|
+
readonly connectionName: string;
|
|
26
|
+
} | ApplicationChannelPreflightRoute | ApplicationChannelRoute | {
|
|
22
27
|
readonly kind: "development-artifacts";
|
|
23
28
|
readonly method: "GET";
|
|
24
29
|
readonly path: string;
|
|
@@ -38,7 +43,7 @@ export interface ApplicationRouteRegistry {
|
|
|
38
43
|
}
|
|
39
44
|
interface ApplicationRouteRegistryHost {
|
|
40
45
|
readonly compileResult: {
|
|
41
|
-
readonly manifest: Pick<CompiledAgentManifest, "channelRoutes"
|
|
46
|
+
readonly manifest: Pick<CompiledAgentManifest, "channelRoutes"> & Partial<Pick<CompiledAgentManifest, "connections">>;
|
|
42
47
|
};
|
|
43
48
|
}
|
|
44
49
|
/** Projects the compiler-owned route plan into Nitro registration records. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{EVE_WORKFLOW_FLOW_ROUTE_PATH}from"#internal/workflow-bundle/eve-service-route-output.js";function createApplicationRouteRegistry(e,t={}){let n=e.compileResult.manifest.channelRoutes,r=n.effective.map(e=>({cors:e.cors,method:e.method,route:e.urlPath})),i=[...n.effective.map(e=>({cors:e.cors,kind:`channel`,method:e.method,path:e.urlPath})),...n.preflight.map(e=>({cors:e.cors,kind:`channel-preflight`,method:`OPTIONS`,path:e.urlPath}))],a=[...i];return t.development===!0&&a.push({kind:`development-artifacts`,method:`GET`,path:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH},{kind:`development-schedule`,method:`POST`,path:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN}),a.push({kind:`workflow`,method:`ALL`,path:EVE_WORKFLOW_FLOW_ROUTE_PATH}),{channelRegistrations:r,channelRoutes:i,routes:a}}function computeApplicationChannelRouteRegistrations(e){return createApplicationRouteRegistry(e).channelRegistrations}export{computeApplicationChannelRouteRegistrations,createApplicationRouteRegistry};
|
|
1
|
+
import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{EVE_WORKFLOW_FLOW_ROUTE_PATH}from"#internal/workflow-bundle/eve-service-route-output.js";import{connectionEventRoute}from"#runtime/connections/events/path.js";function createApplicationRouteRegistry(e,t={}){let n=e.compileResult.manifest.channelRoutes,r=n.effective.map(e=>({cors:e.cors,method:e.method,route:e.urlPath})),i=[...n.effective.map(e=>({cors:e.cors,kind:`channel`,method:e.method,path:e.urlPath})),...n.preflight.map(e=>({cors:e.cors,kind:`channel-preflight`,method:`OPTIONS`,path:e.urlPath}))],a=[...i];for(let t of e.compileResult.manifest.connections??[]){if(t.experimental_events!==!0)continue;let e=connectionEventRoute(t.connectionName);if(a.some(t=>t.path===e))throw Error(`Connection event receiver conflicts with an existing route: ${e}`);a.push({kind:`connection-event`,method:`POST`,path:e,connectionName:t.connectionName})}return t.development===!0&&a.push({kind:`development-artifacts`,method:`GET`,path:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH},{kind:`development-schedule`,method:`POST`,path:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN}),a.push({kind:`workflow`,method:`ALL`,path:EVE_WORKFLOW_FLOW_ROUTE_PATH}),{channelRegistrations:r,channelRoutes:i,routes:a}}function computeApplicationChannelRouteRegistrations(e){return createApplicationRouteRegistry(e).channelRegistrations}export{computeApplicationChannelRouteRegistrations,createApplicationRouteRegistry};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{mkdir,writeFile}from"node:fs/promises";import{dirname,join,relative}from"node:path";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createApplicationRouteRegistry}from"#internal/nitro/host/application-route-registry.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{EVE_SCHEDULE_COLLECTION_CONSUMER_ROUTE_PATH,hasVercelScheduleCollections}from"#internal/schedules/consumer-route.js";function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=t.directHandlers??[],o=a.length>0&&t.workflowWorldPluginPath!==void 0?createRelativeImportSpecifier(r,t.workflowWorldPluginPath):void 0,s=a.map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:s,runtimeImportSpecifier:t.runtimeImportSpecifier,workflowWorldPluginImportSpecifier:o})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);e.workflowWorldPluginImportSpecifier!==void 0&&t.push(`import ${JSON.stringify(e.workflowWorldPluginImportSpecifier)};`),t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
2
2
|
`)}function addHostVirtualHandler(e,t){let n=`#eve-route${t.route}`,r=stringifyEsmImportSpecifier(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
3
|
-
`)}async function registerWorkflowArtifactBuildHook(e,t){let n=!0;await t(),e.hooks.hook(`build:before`,async()=>{if(n){n=!1;return}await t()})}function registerApplicationRoutes(e,t,n){for(let r of n.routes)switch(r.kind){case`channel`:case`channel-preflight`:registerChannelVirtualHandlers(e,{artifactsConfig:t,routes:[r]});break;case`development-artifacts`:addHostVirtualHandler(e,{args:JSON.stringify({appRoot:t.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:r.method,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:r.path});break;case`development-schedule`:addHostVirtualHandler(e,{args:JSON.stringify(t),handlerExport:`handleDevScheduleDispatchRequest`,method:r.method,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:r.path})}}function findWorkflowRoute(e){return e.routes.find(e=>e.kind===`workflow`)?.path}function createWorkflowDirectHandlerEntry(e,t){return{bundlePath:t,queuePrefix:deriveEveWorkflowQueuePrefix(e.compileResult.manifest.config.name)}}async function registerWorkflowRoute(e,t,n,r,i){await addWorkflowFileHandler(e,{bundleName:`workflows`,bundlePath:n,directHandlers:r,route:i,runtimeImportSpecifier:r.length===0?void 0:normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),workflowWorldPluginPath:t.compiledArtifacts.workflowWorldPluginPath})}async function configureDevelopmentNitroRoutes(e,t){let n=resolveNitroWorkflowBuildDirectory(e),r=new WorkflowBundleBuilder({authoredWorkflowModules:t.compiledArtifacts.authoredWorkflowModules,agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!0});await registerWorkflowArtifactBuildHook(e,async()=>{await r.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})});let i=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot,configuredWorld:t.compileResult.manifest.config.experimental?.workflow?.world}),a=createApplicationRouteRegistry(t,{development:!0});registerApplicationRoutes(e,i,a);let o=join(n,`workflows.mjs`),s=[];usesParentDevelopmentWorkflowWorld(t.compileResult.manifest.config.experimental?.workflow?.world)||s.push(createWorkflowDirectHandlerEntry(t,o));let c=findWorkflowRoute(a);c!==void 0&&await registerWorkflowRoute(e,t,o,s,c),e.routing.sync()}async function configureProductionNitroRoutes(e,t){let n=new WorkflowBundleBuilder({authoredWorkflowModules:t.compiledArtifacts.authoredWorkflowModules,agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1});await registerWorkflowArtifactBuildHook(e,async()=>{await n.build({nitroStepOutfile:join(resolveNitroWorkflowBuildDirectory(e),`steps.mjs`)})});let r=createApplicationRouteRegistry(t),i=createProductionNitroArtifactsConfig(t.appRoot);registerApplicationRoutes(e,i,r),isVercelBuildEnvironment()&&hasVercelScheduleCollections(t.compileResult.manifest)&&addHostVirtualHandler(e,{args:JSON.stringify(i),handlerExport:`handleScheduleCollectionConsumer`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-collection-consumer.ts`),route:EVE_SCHEDULE_COLLECTION_CONSUMER_ROUTE_PATH});let a=join(t.workflowBuildDir,`workflows.mjs`),o=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0,s=!isVercelBuildEnvironment()&&o?[createWorkflowDirectHandlerEntry(t,a)]:[],c=findWorkflowRoute(r);c!==void 0&&await registerWorkflowRoute(e,t,a,s,c),e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
|
|
3
|
+
`)}async function registerWorkflowArtifactBuildHook(e,t){let n=!0;await t(),e.hooks.hook(`build:before`,async()=>{if(n){n=!1;return}await t()})}function registerApplicationRoutes(e,t,n){for(let r of n.routes)switch(r.kind){case`connection-event`:addHostVirtualHandler(e,{args:JSON.stringify({artifactsConfig:t,connectionName:r.connectionName}),handlerExport:`handleConnectionEventRequest`,method:r.method,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/connection-events.ts`),route:r.path});break;case`channel`:case`channel-preflight`:registerChannelVirtualHandlers(e,{artifactsConfig:t,routes:[r]});break;case`development-artifacts`:addHostVirtualHandler(e,{args:JSON.stringify({appRoot:t.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:r.method,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:r.path});break;case`development-schedule`:addHostVirtualHandler(e,{args:JSON.stringify(t),handlerExport:`handleDevScheduleDispatchRequest`,method:r.method,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:r.path})}}function findWorkflowRoute(e){return e.routes.find(e=>e.kind===`workflow`)?.path}function createWorkflowDirectHandlerEntry(e,t){return{bundlePath:t,queuePrefix:deriveEveWorkflowQueuePrefix(e.compileResult.manifest.config.name)}}async function registerWorkflowRoute(e,t,n,r,i){await addWorkflowFileHandler(e,{bundleName:`workflows`,bundlePath:n,directHandlers:r,route:i,runtimeImportSpecifier:r.length===0?void 0:normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),workflowWorldPluginPath:t.compiledArtifacts.workflowWorldPluginPath})}async function configureDevelopmentNitroRoutes(e,t){let n=resolveNitroWorkflowBuildDirectory(e),r=new WorkflowBundleBuilder({authoredWorkflowModules:t.compiledArtifacts.authoredWorkflowModules,agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!0});await registerWorkflowArtifactBuildHook(e,async()=>{await r.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})});let i=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot,configuredWorld:t.compileResult.manifest.config.experimental?.workflow?.world}),a=createApplicationRouteRegistry(t,{development:!0});registerApplicationRoutes(e,i,a);let o=join(n,`workflows.mjs`),s=[];usesParentDevelopmentWorkflowWorld(t.compileResult.manifest.config.experimental?.workflow?.world)||s.push(createWorkflowDirectHandlerEntry(t,o));let c=findWorkflowRoute(a);c!==void 0&&await registerWorkflowRoute(e,t,o,s,c),e.routing.sync()}async function configureProductionNitroRoutes(e,t){let n=new WorkflowBundleBuilder({authoredWorkflowModules:t.compiledArtifacts.authoredWorkflowModules,agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1});await registerWorkflowArtifactBuildHook(e,async()=>{await n.build({nitroStepOutfile:join(resolveNitroWorkflowBuildDirectory(e),`steps.mjs`)})});let r=createApplicationRouteRegistry(t),i=createProductionNitroArtifactsConfig(t.appRoot);registerApplicationRoutes(e,i,r),isVercelBuildEnvironment()&&hasVercelScheduleCollections(t.compileResult.manifest)&&addHostVirtualHandler(e,{args:JSON.stringify(i),handlerExport:`handleScheduleCollectionConsumer`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-collection-consumer.ts`),route:EVE_SCHEDULE_COLLECTION_CONSUMER_ROUTE_PATH});let a=join(t.workflowBuildDir,`workflows.mjs`),o=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0,s=!isVercelBuildEnvironment()&&o?[createWorkflowDirectHandlerEntry(t,a)]:[],c=findWorkflowRoute(r);c!==void 0&&await registerWorkflowRoute(e,t,a,s,c),e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
|
|
@@ -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{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.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{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s].filter(e=>e!==null);return{nitroRolldownConfig:{tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}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){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),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`},builder:EVE_NITRO_BUILDER,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,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.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{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createExternalDependencyOutputCheckPlugin}from"#internal/nitro/host/external-dependency-output-check-plugin.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,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=collectConfiguredExternalDependencies(e.compileResult.manifest);return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectConfiguredExternalDependencies(e){return[...e.config.build?.externalDependencies??[],...e.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),t.development?null:createExternalDependencyOutputCheckPlugin({appRoot:e.appRoot,externalDependencies:collectConfiguredExternalDependencies(e.compileResult.manifest)}),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s].filter(e=>e!==null);return{nitroRolldownConfig:{output:{sourcemapIgnoreList:/node_modules/},tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}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){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),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`},builder:EVE_NITRO_BUILDER,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,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { RolldownOutputAsset, RolldownOutputChunk } from "#internal/bundler/nitro-rolldown.js";
|
|
2
|
+
interface ExternalDependencyOutputCheckPlugin {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
writeBundle(outputOptions: {
|
|
5
|
+
readonly dir: string;
|
|
6
|
+
}, bundle: Readonly<Record<string, RolldownOutputChunk | RolldownOutputAsset>>): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Fails the hosted build when a written chunk imports (statically or by a
|
|
10
|
+
* literal dynamic import) a configured external that Node does not resolve,
|
|
11
|
+
* from that chunk, to a file inside the output. Nitro's tracer only warns
|
|
12
|
+
* when it cannot find a package to copy, so without this check the build
|
|
13
|
+
* succeeds and the deployed function fails with ERR_MODULE_NOT_FOUND (or
|
|
14
|
+
* ERR_PACKAGE_PATH_NOT_EXPORTED when it copied a different version).
|
|
15
|
+
*
|
|
16
|
+
* Resolution is Node's own ESM resolver, run by the build's Node in a child
|
|
17
|
+
* process; no dependency code is loaded.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createExternalDependencyOutputCheckPlugin(input: {
|
|
20
|
+
readonly appRoot: string;
|
|
21
|
+
readonly externalDependencies: readonly string[];
|
|
22
|
+
}): ExternalDependencyOutputCheckPlugin | null;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";import{rm,writeFile}from"node:fs/promises";import{realpathSync,statSync}from"node:fs";import{dirname,join}from"node:path";import{execFile}from"node:child_process";import{promisify}from"node:util";import{fileURLToPath,pathToFileURL}from"node:url";import{packageImportName,resolveConfiguredExternalDependency}from"#internal/authored-package-boundary.js";import{isPathInsideOrEqual}from"#internal/nitro/dev-runtime-source-snapshot-local-roots.js";function createExternalDependencyOutputCheckPlugin(e){return e.externalDependencies.length===0?null:{name:`eve-external-dependency-output-check`,async writeBundle(t,n){let r=realpathSync(t.dir),i=`.eve-resolve-${randomUUID()}.mjs`,a=[];for(let t of Object.values(n)){if(t.type!==`chunk`)continue;let n=join(dirname(join(r,t.fileName)),i);for(let r of[...t.imports,...t.dynamicImports])resolveConfiguredExternalDependency(r,e.externalDependencies)!==void 0&&a.push({chunk:t.fileName,probe:n,specifier:r})}if(a.length===0)return;let o=await resolveWithNode(r,i,a);a.forEach(({chunk:t,specifier:n},i)=>{let a=o[i],s=a?.startsWith(`file:`)===!0?fileURLToPath(a):void 0;if(s===void 0||statSync(s,{throwIfNoEntry:!1})?.isFile()!==!0||!isPathInsideOrEqual(s,r))throw Error(`"${n}" is listed in build.externalDependencies and imported by the hosted bundle (${t}), but the build output cannot resolve it. Add "${packageImportName(n)}" to the dependencies in ${join(e.appRoot,`package.json`)}.`)})}}}async function resolveWithNode(e,t,n){let r=[...new Set(n.map(({probe:e})=>e))],i=join(e,t.replace(/\.mjs$/,`-driver.mjs`)),a=n.map(({probe:e,specifier:t})=>({probe:pathToFileURL(e).href,specifier:t}));try{await Promise.all(r.map(e=>writeFile(e,`export const resolve = (specifier) => import.meta.resolve(specifier);
|
|
2
|
+
`))),await writeFile(i,[`const results = [];`,`for (const { probe, specifier } of ${JSON.stringify(a)}) {`,` const { resolve } = await import(probe);`,` try { results.push(resolve(specifier)); } catch { results.push(null); }`,`}`,`process.stdout.write(JSON.stringify(results));`,``].join(`
|
|
3
|
+
`));let{NODE_OPTIONS:t,...n}=process.env,o;try{({stdout:o}=await promisify(execFile)(process.execPath,[i],{cwd:e,env:n,maxBuffer:10485760}))}catch(e){throw Error(`Cannot check build.externalDependencies in the hosted output: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return JSON.parse(o)}finally{await Promise.all([i,...r].map(e=>rm(e,{force:!0})))}}export{createExternalDependencyOutputCheckPlugin};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { type Span, type SpanContext } from "#compiled/@opentelemetry/api/index.js";
|
|
1
2
|
export interface ChannelRequestTrace {
|
|
2
|
-
readonly reference:
|
|
3
|
+
readonly reference: SpanContext;
|
|
3
4
|
channel(input: {
|
|
4
5
|
channelName?: string;
|
|
5
6
|
channelKind?: string;
|
|
@@ -10,3 +11,4 @@ export declare function traceChannelRequest<T extends Response>(input: {
|
|
|
10
11
|
readonly request: Request;
|
|
11
12
|
readonly routeKey: string;
|
|
12
13
|
}, handler: (operation: ChannelRequestTrace | undefined) => Promise<T>): Promise<T>;
|
|
14
|
+
export declare function traceConnectionEventRequest(request: Request, handler: (span: Span | undefined) => Promise<Response>): Promise<Response>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SpanKind,SpanStatusCode,context,propagation,trace}from"#compiled/@opentelemetry/api/index.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{markAgentTraceContext}from"#tracing/eve/agent-trace-context.js";import{withErrorContent}from"#compiled/@
|
|
1
|
+
import{SpanKind,SpanStatusCode,context,propagation,trace}from"#compiled/@opentelemetry/api/index.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{markAgentTraceContext}from"#tracing/eve/agent-trace-context.js";import{withErrorContent}from"#compiled/@vercel/agent-runs/otel.js";import{connectionEventDestination}from"#runtime/connections/events/path.js";const headersGetter={get:(e,t)=>e.get(t)??void 0,keys:e=>[...e.keys()]};async function traceChannelRequest(e,t){return traceRequest({...e,spanName:`agent.channel.request`},e=>t(e===void 0?void 0:{reference:e.spanContext(),channel(t){t.channelName!==void 0&&(e.setAttribute(`agent.channel.name`,t.channelName),e.setAttribute(`eve.channel.name`,t.channelName)),t.channelKind!==void 0&&(e.setAttribute(`agent.channel.kind`,t.channelKind),e.setAttribute(`eve.channel.kind`,t.channelKind))}}))}async function traceConnectionEventRequest(e,t){return traceRequest({request:e,routeKey:`POST ${connectionEventDestination(`:connectionName`).replace(`%3AconnectionName`,`:connectionName`)}`,spanName:`agent.connection.event.request`},t)}async function traceRequest(e,t){if(getInstrumentationRuntime()?.otelSettings?.traceChannelRequests!==!0)return t(void 0);let{request:n,routeKey:r}=e,i=propagation.extract(context.active(),n.headers,headersGetter),a=r.indexOf(` `),o;try{o=new URL(n.url)}catch{}let s=trace.getTracer(`eve.channel`).startSpan(e.spanName,{kind:SpanKind.SERVER,attributes:{"operation.name":e.spanName,"resource.name":e.spanName,"http.request.method":n.method,"http.route":a===-1?r:r.slice(a+1),"url.scheme":o?.protocol.replace(/:$/,``),"server.address":o?.hostname}},i);try{let e=await context.with(markAgentTraceContext(withErrorContent(trace.setSpan(i,s),!1)),()=>t(s));return s.setAttribute(`http.response.status_code`,e.status),e.status>=500&&s.setStatus({code:SpanStatusCode.ERROR}),e}catch(e){throw s.setStatus({code:SpanStatusCode.ERROR}),e}finally{s.end()}}export{traceChannelRequest,traceConnectionEventRequest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{connectionEventDestination}from"#runtime/connections/events/path.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{traceConnectionEventRequest}from"#internal/nitro/routes/channel-request-instrumentation.js";import{connectionEventAttributes,connectionEventError,connectionEventTraceContext}from"#tracing/eve/connection-events.js";import{startConnectionEventDelivery}from"#runtime/connections/events/owner.js";async function handleConnectionEventRequest(e,t){return traceConnectionEventRequest(t,async n=>{if(t.method!==`POST`)return new Response(null,{status:405});let r=`load`,i={};try{let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveNitroCompiledArtifactsSource(e.artifactsConfig)}),o=a.resolvedAgent.connections.find(t=>t.connectionName===e.connectionName)?.experimental_events;if(o===void 0)return new Response(null,{status:404});r=`verify`;let s=await o.backend.verify(t,{path:connectionEventDestination(e.connectionName)}),c=s.context.eve;if(!isObject(c)||c.version!==1||typeof c.sessionId!=`string`||c.sessionId.length===0||c.sessionId.length>256||c.sessionId.includes(`:`)||typeof c.bindingId!=`string`||!/^[a-f0-9]{64}$/.test(c.bindingId))return new Response(null,{status:400});i=connectionEventAttributes({connectionName:e.connectionName,sessionId:c.sessionId,deliveryId:s.deliveryId,subscriptionId:s.subscriptionId});for(let[e,t]of Object.entries(i))n?.setAttribute(e,t);r=`handler`;let l=connectionEventTraceContext(n?.spanContext()),u=await startConnectionEventDelivery({kind:`connection-event`,connectionName:e.connectionName,bindingId:c.bindingId,delivery:s,requestTraceContext:l},a);return new Response(null,{status:u?202:410})}catch(e){return isObject(e)&&e.code===`invalid_delivery`?new Response(null,{status:401}):(logError(createLogger(`connection.events.receiver`),`connection event receipt failed`,connectionEventError(e),{...i,stage:r}),new Response(null,{status:503,headers:{"Retry-After":`5`}}))}})}export{handleConnectionEventRequest};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{mapConcurrent}from"#shared/map-concurrent.js";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,mergeWorkflowManifest}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/subagents`),resolvePackageSourceDirectoryPath(`src/tools/provided`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, subagents, or tools/provided source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=(e,t)=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,precomputedManifest:t,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c,u);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]},n=await mapConcurrent(e,async e=>{let t=await readFile(e,`utf8`);return{filePath:e,patterns:await findWorkflowPatterns(e,t)}});for(let{filePath:e,patterns:r}of n)r.hasUseStep&&t.discoveredSteps.push(e),r.hasUseWorkflow&&t.discoveredWorkflows.push(e),r.hasSerde&&t.discoveredSerdeFiles.push(e);return t}async createWorkflowsBundle({additionalOutputs:e=[],appWorkflowFiles:t,frameworkSerdeFiles:n,frameworkWorkflowFiles:r,outfile:i,stepRegistrationsPath:a,tsconfigPath:o}){let s={},c=await mapConcurrent([{label:`framework`,serdeFiles:n,workflowFiles:r},{label:`app`,serdeFiles:[],workflowFiles:t}],async e=>{let t={};return{code:await this.#a({...e,manifest:t,tsconfigPath:o}),manifest:t}});for(let e of c)mergeWorkflowManifest(s,e.manifest);let l=composeWorkflowDriverCode(c.map(e=>e.code));return await Promise.all([{outfile:i,stepRegistrationsPath:a},...e].map(e=>bundleFinalWorkflowOutput({code:l,outfile:e.outfile,queueNamespace:this.#r,stepRegistrationsPath:e.stepRegistrationsPath}))),{manifest:s}}async#a(e){let t=[...e.workflowFiles].sort(),n=new Set(t),r=[...e.serdeFiles].sort().filter(e=>!n.has(e));if(t.length===0&&r.length===0)return``;let i=[...t.map(e=>createWorkflowImport(e,this.config.workingDir)),...r.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{mapConcurrent}from"#shared/map-concurrent.js";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,mergeWorkflowManifest}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/runtime/connections/events`),resolvePackageSourceDirectoryPath(`src/subagents`),resolvePackageSourceDirectoryPath(`src/tools/provided`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, subagents, or tools/provided source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=(e,t)=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,precomputedManifest:t,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c,u);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]},n=await mapConcurrent(e,async e=>{let t=await readFile(e,`utf8`);return{filePath:e,patterns:await findWorkflowPatterns(e,t)}});for(let{filePath:e,patterns:r}of n)r.hasUseStep&&t.discoveredSteps.push(e),r.hasUseWorkflow&&t.discoveredWorkflows.push(e),r.hasSerde&&t.discoveredSerdeFiles.push(e);return t}async createWorkflowsBundle({additionalOutputs:e=[],appWorkflowFiles:t,frameworkSerdeFiles:n,frameworkWorkflowFiles:r,outfile:i,stepRegistrationsPath:a,tsconfigPath:o}){let s={},c=await mapConcurrent([{label:`framework`,serdeFiles:n,workflowFiles:r},{label:`app`,serdeFiles:[],workflowFiles:t}],async e=>{let t={};return{code:await this.#a({...e,manifest:t,tsconfigPath:o}),manifest:t}});for(let e of c)mergeWorkflowManifest(s,e.manifest);let l=composeWorkflowDriverCode(c.map(e=>e.code));return await Promise.all([{outfile:i,stepRegistrationsPath:a},...e].map(e=>bundleFinalWorkflowOutput({code:l,outfile:e.outfile,queueNamespace:this.#r,stepRegistrationsPath:e.stepRegistrationsPath}))),{manifest:s}}async#a(e){let t=[...e.workflowFiles].sort(),n=new Set(t),r=[...e.serdeFiles].sort().filter(e=>!n.has(e));if(t.length===0&&r.length===0)return``;let i=[...t.map(e=>createWorkflowImport(e,this.config.workingDir)),...r.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
|
|
2
2
|
`);return(await buildSingleRolldownChunk(`${e.label} workflow driver chunk`,{cwd:this.config.workingDir,onLog(e,t,n){if(e===`warn`&&t.code===`UNRESOLVED_IMPORT`)throw Error(`Cannot build workflow bundle: ${t.message}`);onVendoredDependencyLog(e,t,n)},input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(i),createWorkflowPseudoPackagePlugin(),createWorkflowDriverAliasPlugin(this.config.workingDir),createAuthoredRelativeExtensionResolverPlugin({extensions:WORKFLOW_SOURCE_EXTENSIONS}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:this.transformProjectRoot,extensions:WORKFLOW_SOURCE_EXTENSIONS}),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:e.manifest,projectRoot:this.transformProjectRoot,sideEffectFiles:[...t,...r],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`],extensions:WORKFLOW_SOURCE_EXTENSIONS,mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`cjs`,sourcemap:`inline`}})).code}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},r=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),r),r}async#o(){return await this.getInputFiles()}};function mergeStepEntries(e,t){return{discoveredSerdeFiles:e.discoveredSerdeFiles,discoveredSteps:[...new Set([...e.discoveredSteps,...t.directiveModules])]}}export{WorkflowBundleBuilder};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function findProperty(e,t){return e.properties?.find(e=>e.type===`Property`&&!e.computed&&(e.key?.type===`Identifier`?e.key.name===t:e.key?.value===t))}function walkNode(e,t){if(t(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&walkNode(e,t);else isAstNode(n)&&walkNode(n,t)}function getChildContext(e,t,n){return t===`typeAnnotation`||t===`returnType`||t===`typeParameters`||t===`typeArguments`?null:e.type===`VariableDeclarator`&&t===`id`||(e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`)&&(t===`id`||t===`params`)||e.type===`CatchClause`&&t===`param`||(e.type===`ClassDeclaration`||e.type===`ClassExpression`)&&t===`id`?`binding`:e.type===`Property`&&t===`key`?e.computed===!0?`reference`:null:e.type===`Property`&&t===`value`?n:e.type===`AssignmentPattern`?t===`right`?`reference`:n:(e.type===`ObjectPattern`||e.type===`ArrayPattern`||e.type===`RestElement`)&&(t===`properties`||t===`elements`||t===`argument`)?n:(e.type===`MemberExpression`||e.type===`OptionalMemberExpression`)&&t===`property`||(e.type===`MethodDefinition`||e.type===`PropertyDefinition`)&&t===`key`?e.computed===!0?`reference`:null:(e.type===`LabeledStatement`||e.type===`BreakStatement`||e.type===`ContinueStatement`)&&t===`label`?null:`reference`}function isRuntimeTypeScriptExpression(e){return e.type===`TSAsExpression`||e.type===`TSInstantiationExpression`||e.type===`TSNonNullExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSTypeAssertion`}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function findEveImportAliases(e,t){let n=new Set;return walkNode(e,e=>{if(e.type!==`ImportDeclaration`)return!0;let r=e.source?.value;if(typeof r!=`string`||r!==`eve`&&!r.startsWith(`eve/`))return!1;for(let r of e.specifiers??[]){if(r.type===`ImportNamespaceSpecifier`&&r.local?.name)for(let e of t)n.add(`${r.local.name}.${e}`);r.type===`ImportSpecifier`&&t.includes(String(r.imported?.name??r.imported?.value))&&r.local?.name&&n.add(r.local.name)}return!1}),n}function readDefinerName(e){if(e?.type===`Identifier`)return e.name;if(e?.type!==`MemberExpression`||e.object?.type!==`Identifier`)return;let t=e.computed?e.property?.value:e.property?.name;return typeof t==`string`?`${e.object.name}.${t}`:void 0}function collectPatternNames(e,t){if(e){if(e.type===`Identifier`&&e.name){t.push(e.name);return}if(e.type===`ObjectPattern`)for(let n of e.properties??[])collectPatternNames(n.type===`RestElement`?n.argument:n.value,t);if(e.type===`ArrayPattern`)for(let n of e.elements??[])collectPatternNames(n,t);e.type===`AssignmentPattern`&&collectPatternNames(e.left,t)}}function extractParamNames(e){let t=[];for(let n of e.params??[])collectPatternNames(n,t);return t}function isFunction(e){return e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`||e.type===`FunctionExpression`}function walkDefinerCalls(e,t,n){let walk=(e,r)=>{let i=e.arguments?.[0];if(e.type===`CallExpression`&&t.has(readDefinerName(e.callee)??``)&&e.arguments?.length===1&&i?.type===`ObjectExpression`){n(e,i,r);return}let a=e.type===`Program`?r:withScopeBindings(e,r);for(let t of Object.values(e))for(let e of Array.isArray(t)?t:[t])isAstNode(e)&&walk(e,a)};walk(e,new Set)}function collectFreeVariables(e){let t=new Set,visit=(e,n,r)=>{if(e.type?.startsWith(`TS`)){isRuntimeTypeScriptExpression(e)&&e.expression&&visit(e.expression,`reference`,r);return}e.type===`Identifier`&&e.name&&n===`reference`&&!r.has(e.name)&&t.add(e.name);let i=withScopeBindings(e,r);for(let[t,r]of Object.entries(e)){let a=getChildContext(e,t,n);if(a)for(let e of Array.isArray(r)?r:[r])isAstNode(e)&&visit(e,a,i)}};return visit(e,`reference`,new Set),t}function withScopeBindings(e,t){let n=scopeBindings(e);return n.length===0?t:new Set([...t,...n])}function scopeBindings(e){let t=[];if(isFunction(e)){e.type===`FunctionExpression`&&e.id?.name&&t.push(e.id.name);for(let n of e.params??[])collectPatternNames(n,t);isAstNode(e.body)&&collectVarNames(e.body,t)}else if(e.type===`BlockStatement`||e.type===`StaticBlock`)collectLexicalNames(e.body,t);else if(e.type===`SwitchStatement`)for(let n of e.cases??[])collectLexicalNames(n.consequent,t);else if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.type===`ForStatement`?e.init:e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations??[])collectPatternNames(e.id,t)}else e.type===`CatchClause`?collectPatternNames(e.param??null,t):e.type===`ClassExpression`&&e.id?.name&&t.push(e.id.name);return t}function collectVarNames(e,t){walkNode(e,e=>{if(isFunction(e))return!1;if(e.type===`VariableDeclaration`&&e.kind===`var`)for(let n of e.declarations??[])collectPatternNames(n.id,t);return!0})}function collectLexicalNames(e,t){if(Array.isArray(e))for(let n of e)if(n.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations??[])collectPatternNames(e.id,t);else(n.type===`FunctionDeclaration`||n.type===`ClassDeclaration`||n.type===`TSEnumDeclaration`)&&n.id?.name&&t.push(n.id.name)}export{collectFreeVariables,collectPatternNames,extractParamNames,findEveImportAliases,findProperty,isAstNode,isFunction,readDefinerName,walkDefinerCalls,walkNode};
|
|
1
|
+
function findProperty(e,t){return e.properties?.find(e=>e.type===`Property`&&!e.computed&&(e.key?.type===`Identifier`?e.key.name===t:e.key?.value===t))}function walkNode(e,t){if(t(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&walkNode(e,t);else isAstNode(n)&&walkNode(n,t)}function getChildContext(e,t,n){return t===`typeAnnotation`||t===`returnType`||t===`typeParameters`||t===`typeArguments`?null:e.type===`VariableDeclarator`&&t===`id`||(e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`)&&(t===`id`||t===`params`)||e.type===`CatchClause`&&t===`param`||(e.type===`ClassDeclaration`||e.type===`ClassExpression`)&&t===`id`?`binding`:e.type===`Property`&&t===`key`?e.computed===!0?`reference`:null:e.type===`Property`&&t===`value`?n:e.type===`AssignmentPattern`?t===`right`?`reference`:n:(e.type===`ObjectPattern`||e.type===`ArrayPattern`||e.type===`RestElement`)&&(t===`properties`||t===`elements`||t===`argument`)?n:(e.type===`MemberExpression`||e.type===`OptionalMemberExpression`)&&t===`property`||(e.type===`MethodDefinition`||e.type===`PropertyDefinition`)&&t===`key`?e.computed===!0?`reference`:null:(e.type===`LabeledStatement`||e.type===`BreakStatement`||e.type===`ContinueStatement`)&&t===`label`?null:`reference`}function isRuntimeTypeScriptExpression(e){return e.type===`TSAsExpression`||e.type===`TSInstantiationExpression`||e.type===`TSNonNullExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSTypeAssertion`}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function findEveImportAliases(e,t){let n=new Set;return walkNode(e,e=>{if(e.type!==`ImportDeclaration`)return!0;let r=e.source?.value;if(typeof r!=`string`||r!==`eve`&&!r.startsWith(`eve/`))return!1;for(let r of e.specifiers??[]){if(r.type===`ImportNamespaceSpecifier`&&r.local?.name)for(let e of t)n.add(`${r.local.name}.${e}`);r.type===`ImportSpecifier`&&t.includes(String(r.imported?.name??r.imported?.value))&&r.local?.name&&n.add(r.local.name)}return!1}),n}function readDefinerName(e){if(e?.type===`Identifier`)return e.name;if(e?.type!==`MemberExpression`||e.object?.type!==`Identifier`)return;let t=e.computed?e.property?.value:e.property?.name;return typeof t==`string`?`${e.object.name}.${t}`:void 0}function collectPatternNames(e,t){if(e){if(e.type===`Identifier`&&e.name){t.push(e.name);return}if(e.type===`ObjectPattern`)for(let n of e.properties??[])collectPatternNames(n.type===`RestElement`?n.argument:n.value,t);if(e.type===`ArrayPattern`)for(let n of e.elements??[])collectPatternNames(n,t);e.type===`RestElement`&&collectPatternNames(e.argument,t),e.type===`AssignmentPattern`&&collectPatternNames(e.left,t)}}function extractParamNames(e){let t=[];for(let n of e.params??[])collectPatternNames(n,t);return t}function isFunction(e){return e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`||e.type===`FunctionExpression`}function walkDefinerCalls(e,t,n){let walk=(e,r)=>{let i=e.arguments?.[0];if(e.type===`CallExpression`&&t.has(readDefinerName(e.callee)??``)&&e.arguments?.length===1&&i?.type===`ObjectExpression`){n(e,i,r);return}let a=e.type===`Program`?r:withScopeBindings(e,r);for(let t of Object.values(e))for(let e of Array.isArray(t)?t:[t])isAstNode(e)&&walk(e,a)};walk(e,new Set)}function collectFreeVariables(e){let t=new Set,visit=(e,n,r)=>{if(e.type?.startsWith(`TS`)){isRuntimeTypeScriptExpression(e)&&e.expression&&visit(e.expression,`reference`,r);return}e.type===`Identifier`&&e.name&&n===`reference`&&!r.has(e.name)&&t.add(e.name);let i=withScopeBindings(e,r);for(let[t,r]of Object.entries(e)){let a=getChildContext(e,t,n);if(a)for(let e of Array.isArray(r)?r:[r])isAstNode(e)&&visit(e,a,i)}};return visit(e,`reference`,new Set),t}function withScopeBindings(e,t){let n=scopeBindings(e);return n.length===0?t:new Set([...t,...n])}function scopeBindings(e){let t=[];if(isFunction(e)){e.type===`FunctionExpression`&&e.id?.name&&t.push(e.id.name);for(let n of e.params??[])collectPatternNames(n,t);isAstNode(e.body)&&collectVarNames(e.body,t)}else if(e.type===`BlockStatement`||e.type===`StaticBlock`)collectLexicalNames(e.body,t);else if(e.type===`SwitchStatement`)for(let n of e.cases??[])collectLexicalNames(n.consequent,t);else if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.type===`ForStatement`?e.init:e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations??[])collectPatternNames(e.id,t)}else e.type===`CatchClause`?collectPatternNames(e.param??null,t):e.type===`ClassExpression`&&e.id?.name&&t.push(e.id.name);return t}function collectVarNames(e,t){walkNode(e,e=>{if(isFunction(e))return!1;if(e.type===`VariableDeclaration`&&e.kind===`var`)for(let n of e.declarations??[])collectPatternNames(n.id,t);return!0})}function collectLexicalNames(e,t){if(Array.isArray(e))for(let n of e)if(n.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations??[])collectPatternNames(e.id,t);else(n.type===`FunctionDeclaration`||n.type===`ClassDeclaration`||n.type===`TSEnumDeclaration`)&&n.id?.name&&t.push(n.id.name)}export{collectFreeVariables,collectPatternNames,extractParamNames,findEveImportAliases,findProperty,isAstNode,isFunction,readDefinerName,walkDefinerCalls,walkNode};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{cardChildToFallbackText}from"#compiled/chat/index.js";import{cardToSlackBlocks}from"#compiled/@chat-adapter/slack/blocks.js";function cardToBlocks(e){return cardToSlackBlocks({...e,children:e.children.map(
|
|
2
|
-
`).trim()}function
|
|
1
|
+
import{cardChildToFallbackText}from"#compiled/chat/index.js";import{cardToSlackBlocks}from"#compiled/@chat-adapter/slack/blocks.js";function cardToBlocks(e){return cardToSlackBlocks({...e,children:e.children.map(toSlackCardChild)})}function cardToFallbackText(e){let t=[];e.title&&t.push(e.title),e.subtitle&&t.push(e.subtitle);for(let n of e.children){let e=cardChildToFallbackText(n);e&&t.push(e)}return t.join(`
|
|
2
|
+
`).trim()}function toSlackCardChild(e){return e.type===`section`?{...e,children:e.children.map(toSlackCardChild)}:e.type===`text_input`?{content:e.label,type:`text`}:e.type===`actions`?{...e,children:e.children.map(e=>e.type===`link-button`&&e.id===void 0?{...e,id:`link:${e.url}`}:e)}:e}export{cardToBlocks,cardToFallbackText};
|
|
@@ -10,3 +10,4 @@ export { defineMcpClientConnection, type McpClientConnectionDefinition, } from "
|
|
|
10
10
|
export type { ConnectionToolCallDefinition, ProvidedArgumentContext, ProvidedArgumentsDefinition, ProvidedArgumentValue, } from "#public/definitions/connections/tool-call.js";
|
|
11
11
|
export { defineOpenAPIConnection, type OpenAPIConnectionDefinition, type OpenAPISpecSource, } from "#public/definitions/connections/openapi.js";
|
|
12
12
|
export { type ConnectionAuthorizationChallenge, ConnectionAuthorizationFailedError, type ConnectionAuthorizationFailedErrorOptions, ConnectionAuthorizationRequiredError, type ConnectionAuthorizationRequiredErrorOptions, isConnectionAuthorizationFailedError, isConnectionAuthorizationRequiredError, } from "#public/connections/errors.js";
|
|
13
|
+
export type { Experimental_ConnectionEvents, Experimental_ConnectionEvent, Experimental_ConnectionEventOrigin, Experimental_ConnectionEventContext, } from "#public/definitions/connections/events.js";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Session } from "#channel/session.js";
|
|
2
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
3
|
+
/** Framework-owned origin captured when the authorized caller subscribes. */
|
|
4
|
+
export interface Experimental_ConnectionEventOrigin {
|
|
5
|
+
readonly sessionId: string;
|
|
6
|
+
readonly connectionName: string;
|
|
7
|
+
readonly subscriptionId: string;
|
|
8
|
+
}
|
|
9
|
+
export interface Experimental_ConnectionEventContext {
|
|
10
|
+
readonly origin: Experimental_ConnectionEventOrigin;
|
|
11
|
+
readonly deliveryId: string;
|
|
12
|
+
/** The subscription creator's authenticated session identity. */
|
|
13
|
+
readonly auth: SessionAuthContext | null;
|
|
14
|
+
/** Attaches to an existing session; never creates a replacement session. */
|
|
15
|
+
readonly attachSession: (sessionId: string) => Session;
|
|
16
|
+
}
|
|
17
|
+
export interface Experimental_ConnectionEvent {
|
|
18
|
+
readonly eventId: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly timestamp: string;
|
|
21
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
22
|
+
readonly cursor: string | null;
|
|
23
|
+
}
|
|
24
|
+
/** Opts a static Connect-backed MCP connection into managed webhook events. */
|
|
25
|
+
export interface Experimental_ConnectionEvents {
|
|
26
|
+
/** Called durably after verification and subscription binding checks. */
|
|
27
|
+
readonly onEvent: (input: Experimental_ConnectionEventContext & {
|
|
28
|
+
readonly event: Experimental_ConnectionEvent;
|
|
29
|
+
}) => void | PromiseLike<void>;
|
|
30
|
+
/** The upstream server could not deliver a contiguous event stream. */
|
|
31
|
+
readonly onGap?: (input: Experimental_ConnectionEventContext & {
|
|
32
|
+
readonly cursor: string | null;
|
|
33
|
+
readonly truncated?: true;
|
|
34
|
+
}) => void | PromiseLike<void>;
|
|
35
|
+
/** The upstream subscription ended; no model turn starts automatically. */
|
|
36
|
+
readonly onTerminated?: (input: Experimental_ConnectionEventContext & {
|
|
37
|
+
readonly error: {
|
|
38
|
+
readonly code: number;
|
|
39
|
+
readonly message: string;
|
|
40
|
+
readonly data?: unknown;
|
|
41
|
+
};
|
|
42
|
+
}) => void | PromiseLike<void>;
|
|
43
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Experimental_ConnectionEvents } from "#public/definitions/connections/events.js";
|
|
1
2
|
import type { ConnectionAuthDefinition, HeadersDefinition, ToolFilterDefinition } from "#shared/connection-types.js";
|
|
2
3
|
import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
|
|
3
4
|
import type { Approval } from "#public/definitions/approval.js";
|
|
@@ -14,6 +15,8 @@ import type { Approval } from "#public/definitions/approval.js";
|
|
|
14
15
|
* servers that require no authentication (e.g. localhost).
|
|
15
16
|
*/
|
|
16
17
|
export interface McpClientConnectionDefinition {
|
|
18
|
+
/** Opt-in Connect webhook callbacks. Enabling this does not subscribe. */
|
|
19
|
+
readonly experimental_events?: Experimental_ConnectionEvents;
|
|
17
20
|
/**
|
|
18
21
|
* The MCP server's HTTP endpoint URL.
|
|
19
22
|
*
|
|
@@ -11,6 +11,7 @@ import type { InferReceiveTarget } from "#channel/receive-target.js";
|
|
|
11
11
|
import type { Session } from "#channel/session.js";
|
|
12
12
|
import { SCHEDULE_COLLECTION_DEFINITION_BRAND } from "#shared/schedule-collection-definition.js";
|
|
13
13
|
import type { ScheduleProviderContext } from "#runtime/schedules/provider-types.js";
|
|
14
|
+
import type { AgentToolExposure } from "#shared/agent-definition.js";
|
|
14
15
|
/** A provider namespace scope, represented by one key or a hierarchical key path. */
|
|
15
16
|
export type ScheduleScopeValue = string | readonly string[];
|
|
16
17
|
/** Return `null` to deny the current schedule operation. */
|
|
@@ -242,8 +243,8 @@ export interface DynamicSchedulesDefinition<TPayload = unknown, TSchema extends
|
|
|
242
243
|
/** On a permanent provider failure or after its retry budget is exhausted. */
|
|
243
244
|
readonly "occurrence.failed"?: ScheduleOccurrenceEventHandler<NoInfer<TPrepared>>;
|
|
244
245
|
};
|
|
245
|
-
/** Expose operation tools directly (default true),
|
|
246
|
-
readonly tool?:
|
|
246
|
+
/** Expose operation tools directly (default true), defer them to the catalog, or disable them. */
|
|
247
|
+
readonly tool?: AgentToolExposure;
|
|
247
248
|
/** Model-call policies keyed by operation. Create and update receive the prepared payload. */
|
|
248
249
|
readonly approval?: ScheduleApprovals<NoInfer<TPrepared>>;
|
|
249
250
|
}
|
|
@@ -257,7 +258,7 @@ type DynamicSchedulesOptions<TInput, TSchema extends StandardSchemaV1<unknown, T
|
|
|
257
258
|
readonly tool: false;
|
|
258
259
|
readonly approval?: never;
|
|
259
260
|
} | {
|
|
260
|
-
readonly tool?: true;
|
|
261
|
+
readonly tool?: true | "deferred";
|
|
261
262
|
readonly approval?: ScheduleApprovals<NoInfer<TPrepared>>;
|
|
262
263
|
});
|
|
263
264
|
/**
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ResolvedConnectionDefinition, ResolvedConnectionEvents } from "#runtime/types.js";
|
|
2
|
+
import type { ConnectionToolExecuteOptions, ConnectionToolMetadata } from "#shared/connection-types.js";
|
|
3
|
+
export declare function isEventAction(name: string): boolean;
|
|
4
|
+
export declare class ConnectionEventActions {
|
|
5
|
+
private readonly connection;
|
|
6
|
+
private readonly events;
|
|
7
|
+
private readonly headers;
|
|
8
|
+
private readonly transportFetch;
|
|
9
|
+
constructor(connection: ResolvedConnectionDefinition, events: ResolvedConnectionEvents, headers: () => Promise<Record<string, string>>, transportFetch?: typeof fetch);
|
|
10
|
+
private scope;
|
|
11
|
+
private withClient;
|
|
12
|
+
private catalog;
|
|
13
|
+
metadata(): Promise<ConnectionToolMetadata[]>;
|
|
14
|
+
/** Existing watches must remain stoppable when upstream discovery fails. */
|
|
15
|
+
recoveryMetadata(): ConnectionToolMetadata[];
|
|
16
|
+
execute(name: string, input: unknown, options: ConnectionToolExecuteOptions): Promise<unknown>;
|
|
17
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";import{contextStorage}from"#context/container.js";import{AuthKey,SessionIdKey,SessionTraceSeedKey}from"#context/keys.js";import{defineJsonSchema,toInputSchema}from"#tools/schema.js";import{parseJsonObject}from"#shared/json.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{principalOf}from"#execution/session/principal.js";import{connectionEventDestination}from"#runtime/connections/events/path.js";import{withConnectionEventSpan}from"#tracing/eve/connection-events.js";import{createMcpTraceFetch}from"#runtime/connections/mcp-tracing.js";import{createMcpTracing}from"#tracing/eve/mcp.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";import{sameEventOwner}from"#runtime/connections/events/state.js";const GET=`events_get_subscription`,STOP=`events_unsubscribe`,PREFIX=`events_subscribe_`,MIN_TTL_MS=12e4,MAX_TTL_MS=31536e6,SUBSCRIBE_INPUT_SCHEMA=defineJsonSchema(parseJsonObject(subscribeInputSchema()));function isEventAction(e){return e===GET||e===STOP||e.startsWith(PREFIX)}var ConnectionEventActions=class{connection;events;headers;transportFetch;constructor(e,t,n,r){this.connection=e,this.events=t,this.headers=n,this.transportFetch=r}scope(){let e=contextStorage.getStore();if(e===void 0)throw Error(`Event subscriptions require an active eve session.`);if(e.get(BundleKey)?.nodeId!==void 0)throw Error(`Experimental event subscriptions currently require a root-agent connection.`);let{authorization:t,backend:n,connector:r}=this.events,i=resolveConnectionPrincipal(this.connection.connectionName,t,e),a=e.require(SessionIdKey),o=principalKey(i),s=principalOf(e.get(AuthKey));return{ctx:e,principal:i,sessionId:a,owner:o,executionPrincipal:s,caller:{connectionName:this.connection.connectionName,instanceId:this.connection.instanceId,connector:r,principalKey:o,executionPrincipal:s},backend:n,connector:r}}async withClient(e){this.scope();let t,n={transport:{type:`http`,fetch:createMcpTraceFetch({connectionName:this.connection.connectionName,fetcher:this.transportFetch,getProtocolVersion:()=>t?.initializeResult?.protocolVersion}),url:this.connection.url,headers:await this.headers()},protocolVersionDiscovery:this.connection.protocolVersionDiscovery};t=await createMCPClient(n);try{return await e(t.experimental_events)}finally{await t.close()}}async catalog(e){let t=[],n=new Set,r,i=0;for(let a=0;a<20;a++){let a=await withConnectionEventSpan({ctx:this.scope().ctx,connectionName:this.connection.connectionName,operation:`catalog`},()=>createMcpTracing().list({connectionName:this.connection.connectionName,method:`events/list`,execute:()=>e.list({params:{cursor:r},options:{timeout:15e3}})}));if(i+=a.events.length,i>1e3)throw Error(`MCP event catalog exceeds the 1000-event limit.`);if(t.push(...a.events.filter(e=>e.delivery.includes(`webhook`))),r=a.nextCursor??void 0,r===void 0)return t;if(n.has(r))throw Error(`MCP event catalog returned a repeated cursor.`);n.add(r)}throw Error(`MCP event catalog exceeds the 20-page limit.`)}async metadata(){return this.withClient(async e=>[...(await this.catalog(e)).map(e=>({name:actionName(e.name),description:`Watch ${e.name}. ${e.description??``} Events reach this connection's authored callback for ttlMs milliseconds or until stopped. Set ttlMs to null to watch indefinitely. Watching the same event with the same arguments again returns the existing watch.`,inputSchema:subscribeInputSchema(e.inputSchema)})),...managementMetadata()])}recoveryMetadata(){return this.scope(),managementMetadata().map(e=>({...e,description:`MCP discovery is unavailable. ${e.description}`}))}async execute(e,t,n){let r=parseJsonObject(t),{ctx:i,principal:a,backend:o,sessionId:s,owner:c,executionPrincipal:l,caller:u}=this.scope(),{findConnectionEventOwner:d,startConnectionEventOwner:f,retireConnectionEventOwner:p}=await import(`#runtime/connections/events/owner.js`);if(e===GET||e===STOP){if(typeof r.id!=`string`)throw Error(`id must be a subscription id.`);let t=r.id,n=await d(t);if(n===void 0||!sameEventOwner(n.owner,u))throw Error(`Unknown subscription for this caller and account.`);if(e===STOP){if(!await p(t))throw Error(`Unknown subscription for this caller and account.`);return{id:t,status:`stopping`}}if(n.subscription===void 0)return pendingResult(n.owner);let s=n.subscription.id,c=await o.createAdapter({principal:a,connection:{url:this.connection.url},destination:{path:connectionEventDestination(this.connection.connectionName)}});return subscriptionResult(t,await withConnectionEventSpan({ctx:i,connectionName:this.connection.connectionName,bindingId:t,subscriptionId:s,operation:`get`},()=>c.getSubscription({id:s,options:{timeout:3e4}})))}return this.withClient(async t=>{let a=(await this.catalog(t)).find(t=>actionName(t.name)===e);if(a===void 0)throw Error(`Unknown event subscription action for this account.`);let o=await SUBSCRIBE_INPUT_SCHEMA[`~standard`].validate(r);if(o.issues!==void 0)throw Error(`Invalid subscription input: ${o.issues.map(({message:e})=>e).join(`; `)}`);let{arguments:d,ttlMs:p}=o.value,m=typeof a.inputSchema==`boolean`?{allOf:[a.inputSchema]}:a.inputSchema,h=await toInputSchema(m)[`~standard`].validate(parseJsonObject(d));if(h.issues!==void 0)throw Error(`Event arguments do not match the authorized catalog schema.`);let g=parseJsonObject(h.value),_=createHash(`sha256`).update(canonicalJson([s,this.connection.instanceId,this.connection.connectionName,c,l,a.name,g])).digest(`hex`),v={...u,id:_,sessionId:s,auth:structuredClone(i.get(AuthKey)??null),traceSeed:i.get(SessionTraceSeedKey),request:{name:a.name,arguments:structuredClone(g),ttlMs:p,context:{eve:{version:1,sessionId:s,bindingId:_}}}},y=await f(v,i.require(BundleKey),n.abortSignal);return y===void 0?pendingResult(v):subscriptionResult(_,y)})}};function subscribeInputSchema(e={type:`object`}){return{type:`object`,additionalProperties:!1,required:[`arguments`,`ttlMs`],properties:{arguments:e,ttlMs:{type:[`integer`,`null`],minimum:MIN_TTL_MS,maximum:MAX_TTL_MS,description:`How long to watch, in milliseconds (${MIN_TTL_MS} to ${MAX_TTL_MS}), or null until stopped`}}}}function subscriptionResult(e,t){return{...t,id:e,subscriptionId:t.id}}function pendingResult(e){let{name:t,arguments:n}=e.request;return{id:e.id,name:t,arguments:n,status:`pending`}}function canonicalJson(e){return JSON.stringify(e,(e,t)=>typeof t==`object`&&t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:1)):t)}function actionName(e){return`${PREFIX}${createHash(`sha256`).update(e).digest(`hex`).slice(0,24)}`}function managementMetadata(){return[GET,STOP].map(e=>({name:e,description:e===GET?`Get one of this caller's subscriptions, by the id its subscribe call returned, with Connect's current status.`:`Stop one of this caller's subscriptions, by the id its subscribe call returned. The watch then cancels upstream and ends; get reports it until it has.`,inputSchema:{type:`object`,properties:{id:{type:`string`}},required:[`id`],additionalProperties:!1}}))}export{ConnectionEventActions,isEventAction};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SpanContext } from "#compiled/@opentelemetry/api/index.js";
|
|
2
|
+
import type { ConnectionEventDelivery } from "#shared/connection-events.js";
|
|
3
|
+
/** Only the verified receiver constructs this event-handler delivery. */
|
|
4
|
+
export interface ConnectionEventPayload {
|
|
5
|
+
readonly kind: "connection-event";
|
|
6
|
+
readonly connectionName: string;
|
|
7
|
+
readonly bindingId: string;
|
|
8
|
+
readonly requestTraceContext?: SpanContext;
|
|
9
|
+
readonly delivery: ConnectionEventDelivery;
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { EventBinding } from "#runtime/connections/events/state.js";
|
|
2
|
+
import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";
|
|
3
|
+
import type { AlsContext } from "#context/container.js";
|
|
4
|
+
/** Re-checks the run's saved binding against the deployed connection before any work runs as its creator. */
|
|
5
|
+
export declare function resolveBinding(ctx: AlsContext, binding: EventBinding): {
|
|
6
|
+
binding: EventBinding;
|
|
7
|
+
connection: import("../../types.ts").ResolvedConnectionDefinition;
|
|
8
|
+
events: import("../../types.ts").ResolvedConnectionEvents;
|
|
9
|
+
principal: import("../../../shared/connection-types.ts").ConnectionPrincipal;
|
|
10
|
+
} | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Runs one delivery's callback as the watch's creator. A crash before the
|
|
13
|
+
* step completes re-runs the callback, so callbacks are idempotent on
|
|
14
|
+
* deliveryId. A `terminated` delivery then retires the watch.
|
|
15
|
+
*/
|
|
16
|
+
export declare function dispatchConnectionEventStep(input: {
|
|
17
|
+
readonly serializedContext: Record<string, unknown>;
|
|
18
|
+
readonly binding: EventBinding;
|
|
19
|
+
readonly payload: ConnectionEventPayload;
|
|
20
|
+
}): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAttachSessionFn}from"#channel/session.js";import{AuthKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{withConnectionEventSpan}from"#tracing/eve/connection-events.js";import{retireConnectionEventOwner}from"#runtime/connections/events/owner.js";import{principalKey,resolveConnectionPrincipalFromAuth}from"#runtime/connections/principal.js";function resolveBinding(e,t){let n=e.require(BundleKey).resolvedAgent.connections.find(e=>e.connectionName===t.connectionName),r=n?.experimental_events;if(n===void 0||r===void 0||t.instanceId!==n.instanceId||r.connector!==t.connector)return;let i=resolveConnectionPrincipalFromAuth(t.connectionName,r.authorization,t.auth);if(principalKey(i)===t.principalKey)return{binding:t,connection:n,events:r,principal:i}}function accepts(e,t){let{delivery:n}=t;return t.connectionName===e.connectionName&&!(`event`in n&&n.event.name!==e.request.name)}async function dispatchConnectionEventStep(e){"use step";let t=await deserializeContext(e.serializedContext),{delivery:n}=e.payload,r=accepts(e.binding,e.payload)?resolveBinding(t,e.binding):void 0;if(r===void 0)return;let{binding:i,connection:a}=r,o=t.require(BundleKey),{callbacks:s}=r.events;t.setVirtualContext(AuthKey,i.auth);let c=`event`in n?`onEvent`:n.control.type===`gap`?`onGap`:`onTerminated`;await withConnectionEventSpan({ctx:t,connectionName:a.connectionName,operation:c,bindingId:i.id,subscriptionId:n.subscriptionId,deliveryId:n.deliveryId,requestTraceContext:e.payload.requestTraceContext},async e=>{let t={auth:i.auth,deliveryId:n.deliveryId,origin:{sessionId:i.sessionId,connectionName:i.connectionName,subscriptionId:n.subscriptionId},attachSession:createAttachSessionFn(createWorkflowRuntime({compiledArtifactsSource:o.compiledArtifactsSource}),{turnPolicy:`queue`,channelKind:`mcp-events`,channelName:i.connectionName,requestId:n.deliveryId,requestTraceContext:e})};`event`in n?await s.onEvent({...t,event:n.event}):n.control.type===`gap`?await s.onGap?.({...t,cursor:n.control.cursor,truncated:n.control.truncated}):await s.onTerminated?.({...t,error:n.control.error})}),`control`in n&&n.control.type===`terminated`&&await retireConnectionEventOwner(i.id)}export{dispatchConnectionEventStep,resolveBinding};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ConnectionEventSubscribeOutcome, type ConnectionEventSubscribeResult, type EventBinding } from "#runtime/connections/events/state.js";
|
|
2
|
+
import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";
|
|
3
|
+
/**
|
|
4
|
+
* Subscribes from inside the watch run, after its hook is registered, so a
|
|
5
|
+
* delivery that beats the subscribe response finds the binding it runs under.
|
|
6
|
+
* The key is the run's own: a retried step reuses it, and a later run for the
|
|
7
|
+
* same watch, after this one ended, subscribes afresh.
|
|
8
|
+
*/
|
|
9
|
+
export declare function openConnectionEventStep(input: {
|
|
10
|
+
readonly serializedContext: Record<string, unknown>;
|
|
11
|
+
readonly binding: EventBinding;
|
|
12
|
+
}): Promise<ConnectionEventSubscribeResult>;
|
|
13
|
+
/**
|
|
14
|
+
* Connect's definitive refusals reach the model, and the run then ends
|
|
15
|
+
* without a watch. Anything else, such as a timeout after Connect may have
|
|
16
|
+
* created the subscription, throws so the step retries with the same
|
|
17
|
+
* idempotency key.
|
|
18
|
+
*/
|
|
19
|
+
export declare function subscribeConnectionEvent(serializedContext: Record<string, unknown>, binding: EventBinding, idempotencyKey: string): Promise<ConnectionEventSubscribeResult>;
|
|
20
|
+
/**
|
|
21
|
+
* One unsubscribe attempt for a stopped watch. "done" only once Connect has
|
|
22
|
+
* finished cleanup or no longer has the subscription. Anything else, whether
|
|
23
|
+
* Connect still cleaning up, an outage, refused credentials or a connection a
|
|
24
|
+
* redeploy removed, is "pending": the watch keeps its hook and repeats the
|
|
25
|
+
* attempt with its own durable backoff, so Workflow's step retries never
|
|
26
|
+
* decide when cleanup gives up.
|
|
27
|
+
*/
|
|
28
|
+
export declare function unsubscribeConnectionEventStep(input: {
|
|
29
|
+
readonly serializedContext: Record<string, unknown>;
|
|
30
|
+
readonly binding: EventBinding;
|
|
31
|
+
readonly subscriptionId: string;
|
|
32
|
+
}): Promise<"pending" | "done">;
|
|
33
|
+
/** Starts a delivery the watch's run took because it arrived before the subscribe response. */
|
|
34
|
+
export declare function startConnectionEventDeliveryStep(input: {
|
|
35
|
+
readonly binding: EventBinding;
|
|
36
|
+
readonly serializedContext: Record<string, unknown>;
|
|
37
|
+
readonly payload: ConnectionEventPayload;
|
|
38
|
+
}): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Publishes, for a duplicate run's caller, the run that owns the watch.
|
|
41
|
+
*/
|
|
42
|
+
export declare function publishConnectionEventOutcomeStep(outcome: ConnectionEventSubscribeOutcome): Promise<void>;
|