eve 0.22.2 → 0.22.4

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.
Files changed (123) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/src/chunks/{use-eve-agent-CM24ZUEI.js → use-eve-agent-CFBTHlPx.js} +43 -14
  3. package/dist/src/chunks/{use-eve-agent-CxcKypLZ.js → use-eve-agent-dEGV09g_.js} +43 -14
  4. package/dist/src/cli/dev/url.js +1 -1
  5. package/dist/src/client/agent-host.d.ts +4 -0
  6. package/dist/src/client/agent-host.js +1 -0
  7. package/dist/src/client/client-error.d.ts +5 -1
  8. package/dist/src/client/client-error.js +1 -1
  9. package/dist/src/client/client.js +1 -1
  10. package/dist/src/client/open-stream.js +1 -1
  11. package/dist/src/client/session.js +1 -1
  12. package/dist/src/client/types.d.ts +2 -1
  13. package/dist/src/client/url.js +1 -1
  14. package/dist/src/compiler/manifest.d.ts +44 -6
  15. package/dist/src/compiler/manifest.js +1 -1
  16. package/dist/src/compiler/module-map.js +2 -2
  17. package/dist/src/compiler/normalize-extension.d.ts +68 -0
  18. package/dist/src/compiler/normalize-extension.js +1 -0
  19. package/dist/src/compiler/normalize-manifest.js +2 -2
  20. package/dist/src/compiler/normalize-subagent.js +1 -1
  21. package/dist/src/compiler/remote-agent-node.d.ts +1 -1
  22. package/dist/src/compiler/remote-agent-node.js +1 -1
  23. package/dist/src/compiler/workspace-resources.js +1 -1
  24. package/dist/src/context/dynamic-skill-lifecycle.js +1 -1
  25. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  26. package/dist/src/discover/discover-agent.d.ts +14 -1
  27. package/dist/src/discover/discover-agent.js +1 -1
  28. package/dist/src/discover/extension-specifier.d.ts +15 -0
  29. package/dist/src/discover/extension-specifier.js +1 -0
  30. package/dist/src/discover/extensions.d.ts +109 -0
  31. package/dist/src/discover/extensions.js +1 -0
  32. package/dist/src/discover/filesystem.d.ts +2 -2
  33. package/dist/src/discover/filesystem.js +1 -1
  34. package/dist/src/discover/grammar.d.ts +27 -0
  35. package/dist/src/discover/grammar.js +1 -1
  36. package/dist/src/discover/manifest.d.ts +46 -0
  37. package/dist/src/discover/manifest.js +1 -1
  38. package/dist/src/discover/project.js +1 -1
  39. package/dist/src/evals/assertions/run.d.ts +3 -2
  40. package/dist/src/evals/assertions/run.js +2 -2
  41. package/dist/src/evals/index.d.ts +1 -1
  42. package/dist/src/evals/loaders/yaml.js +1 -1
  43. package/dist/src/evals/match.d.ts +11 -6
  44. package/dist/src/execution/sandbox/bindings/microsandbox-network.js +1 -1
  45. package/dist/src/internal/application/package.js +1 -1
  46. package/dist/src/internal/authored-module-loader.d.ts +14 -0
  47. package/dist/src/internal/authored-module-loader.js +2 -2
  48. package/dist/src/internal/authored-module-map-loader.js +1 -1
  49. package/dist/src/internal/bundler/extension-scope-plugin.d.ts +37 -0
  50. package/dist/src/internal/bundler/extension-scope-plugin.js +3 -0
  51. package/dist/src/internal/helpers/gray-matter.d.ts +25 -0
  52. package/dist/src/internal/helpers/gray-matter.js +1 -0
  53. package/dist/src/internal/helpers/markdown.js +1 -1
  54. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  55. package/dist/src/internal/nitro/host/build-application.js +1 -1
  56. package/dist/src/internal/nitro/host/build-extension.d.ts +24 -0
  57. package/dist/src/internal/nitro/host/build-extension.js +4 -0
  58. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  59. package/dist/src/internal/workflow-bundle/eve-service-route-output.d.ts +1 -2
  60. package/dist/src/internal/workflow-bundle/eve-service-route-output.js +1 -54
  61. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  62. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  63. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  64. package/dist/src/public/channels/slack/api.js +1 -1
  65. package/dist/src/public/channels/slack/mrkdwn.d.ts +0 -2
  66. package/dist/src/public/channels/slack/mrkdwn.js +1 -1
  67. package/dist/src/public/definitions/extension.d.ts +68 -0
  68. package/dist/src/public/definitions/extension.js +1 -0
  69. package/dist/src/public/definitions/remote-agent.d.ts +11 -2
  70. package/dist/src/public/extension/index.d.ts +10 -0
  71. package/dist/src/public/extension/index.js +1 -0
  72. package/dist/src/public/index.d.ts +1 -1
  73. package/dist/src/public/next/index.d.ts +38 -3
  74. package/dist/src/public/next/index.js +1 -1
  75. package/dist/src/public/next/server.d.ts +1 -0
  76. package/dist/src/public/next/server.js +2 -1
  77. package/dist/src/public/next/vercel-output-config.d.ts +12 -3
  78. package/dist/src/public/next/vercel-output-config.js +1 -1
  79. package/dist/src/react/use-eve-agent.d.ts +8 -1
  80. package/dist/src/react/use-eve-agent.js +1 -1
  81. package/dist/src/runtime/connections/openapi-client.js +1 -1
  82. package/dist/src/runtime/connections/openapi-spec.js +1 -1
  83. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  84. package/dist/src/runtime/resolve-dynamic-skill.js +1 -1
  85. package/dist/src/runtime/resolve-dynamic-tool.js +1 -1
  86. package/dist/src/runtime/types.d.ts +10 -0
  87. package/dist/src/services/dev-client/vercel-auth-error.d.ts +2 -2
  88. package/dist/src/services/dev-client/vercel-auth-error.js +3 -3
  89. package/dist/src/setup/scaffold/connections/catalog.js +1 -1
  90. package/dist/src/setup/scaffold/create/project.js +3 -3
  91. package/dist/src/svelte/index.js +1 -1
  92. package/dist/src/svelte/use-eve-agent.d.ts +8 -1
  93. package/dist/src/svelte/use-eve-agent.js +1 -1
  94. package/dist/src/vue/index.js +1 -1
  95. package/dist/src/vue/use-eve-agent.d.ts +8 -1
  96. package/dist/src/vue/use-eve-agent.js +1 -1
  97. package/docs/channels/custom.mdx +2 -2
  98. package/docs/channels/linear.mdx +1 -1
  99. package/docs/channels/slack.mdx +2 -0
  100. package/docs/concepts/context-control.md +1 -1
  101. package/docs/connections/openapi.mdx +3 -1
  102. package/docs/evals/assertions.mdx +4 -2
  103. package/docs/extensions.md +176 -0
  104. package/docs/guides/client/overview.mdx +1 -1
  105. package/docs/guides/dev-tui.md +4 -0
  106. package/docs/guides/dynamic-capabilities.md +3 -3
  107. package/docs/guides/frontend/nextjs.mdx +32 -7
  108. package/docs/guides/frontend/overview.mdx +7 -1
  109. package/docs/guides/hooks.md +9 -0
  110. package/docs/guides/instrumentation.md +1 -1
  111. package/docs/guides/remote-agents.md +23 -8
  112. package/docs/guides/state.md +3 -3
  113. package/docs/instructions.mdx +1 -1
  114. package/docs/patterns/dynamic-scheduling.md +11 -11
  115. package/docs/patterns/multi-tenant-approvals.md +6 -6
  116. package/docs/patterns/multi-tenant-auth.md +13 -13
  117. package/docs/patterns/multi-tenant-memory.md +9 -9
  118. package/docs/schedules.mdx +1 -1
  119. package/docs/tutorial/guard-the-spend.mdx +2 -2
  120. package/docs/tutorial/query-sample-data.mdx +1 -1
  121. package/docs/tutorial/remember-definitions.mdx +2 -2
  122. package/docs/tutorial/ship-it.mdx +1 -1
  123. package/package.json +6 -1
@@ -106,6 +106,38 @@ export interface SandboxWorkspaceFolderSourceRef {
106
106
  * Package-local helper module preserved by the discovery manifest.
107
107
  */
108
108
  export type LibSourceRef = ModuleSourceRef;
109
+ /**
110
+ * Extension mount source reference preserved by the discovery manifest. Each
111
+ * `agent/extensions/*.ts` file re-exports (and configures) an extension
112
+ * package; the file basename is the mount namespace.
113
+ */
114
+ export type ExtensionSourceRef = ModuleSourceRef;
115
+ /**
116
+ * A mounted extension resolved to its package and discovered agent-shaped
117
+ * source tree. The compiler composes each mount's {@link manifest} into the
118
+ * consuming agent, prefixing contributions with {@link namespace}.
119
+ */
120
+ export interface ResolvedExtensionMount {
121
+ /** Mount namespace derived from the mount filename (e.g. `crm`). */
122
+ readonly namespace: string;
123
+ /** Package specifier the mount imports (e.g. `@acme/crm`). */
124
+ readonly specifier: string;
125
+ /** Package name from the resolved package.json, used to scope state. */
126
+ readonly packageName: string;
127
+ /** Absolute path to the resolved package root. */
128
+ readonly packageRoot: string;
129
+ /** Absolute path to the extension's agent-shaped source root. */
130
+ readonly sourceRoot: string;
131
+ /** Discovered agent-shaped source manifest for the extension. */
132
+ readonly manifest: AgentSourceManifest;
133
+ /**
134
+ * Consumer-authored overrides discovered in the mount directory form
135
+ * (`extensions/<ns>/{tools,connections,…}/`). Composed under the same
136
+ * `<ns>__` namespace as the extension's own contributions but winning on
137
+ * name collision. Absent for the flat file mount form.
138
+ */
139
+ readonly overrides?: AgentSourceManifest;
140
+ }
109
141
  /**
110
142
  * Subagent source reference preserved by the discovery manifest.
111
143
  */
@@ -127,6 +159,18 @@ export interface AgentSourceManifest {
127
159
  connections: ConnectionSourceRef[];
128
160
  configModule?: ModuleSourceRef;
129
161
  diagnosticsSummary: DiscoverDiagnosticsSummary;
162
+ /**
163
+ * Mounted extension source references discovered under `agent/extensions/`.
164
+ * Each entry's logical-path basename is the mount namespace the compiler
165
+ * prefixes onto the extension's composed contributions.
166
+ */
167
+ extensions: ExtensionSourceRef[];
168
+ /**
169
+ * Mounted extensions resolved to their packages and discovered source trees.
170
+ * Populated only for the agent root; extension trees do not mount further
171
+ * extensions (transitive mounting is a non-goal).
172
+ */
173
+ resolvedExtensions: ResolvedExtensionMount[];
130
174
  hooks: ModuleSourceRef[];
131
175
  lib: LibSourceRef[];
132
176
  kind: typeof AGENT_SOURCE_MANIFEST_KIND;
@@ -170,6 +214,8 @@ export interface CreateAgentSourceManifestInput {
170
214
  connections?: readonly ConnectionSourceRef[];
171
215
  configModule?: ModuleSourceRef;
172
216
  diagnostics?: readonly DiscoverDiagnostic[];
217
+ extensions?: readonly ExtensionSourceRef[];
218
+ resolvedExtensions?: readonly ResolvedExtensionMount[];
173
219
  hooks?: readonly ModuleSourceRef[];
174
220
  lib?: readonly LibSourceRef[];
175
221
  /**
@@ -1 +1 @@
1
- import{basename,relative,resolve}from"node:path";import{summarizeDiscoverDiagnostics}from"#discover/diagnostics.js";import{normalizeLogicalPath}from"#discover/filesystem.js";const AGENT_SOURCE_MANIFEST_KIND=`eve-agent-discovery-manifest`,AGENT_SOURCE_MANIFEST_VERSION=12;function createAgentSourceManifest(e){let t=resolve(e.appRoot),i=resolve(e.agentRoot),o={agentId:e.agentId??deriveAgentIdFromRoots(t,i,e.packageName),agentRoot:i,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:summarizeDiscoverDiagnostics(e.diagnostics??[]),hooks:[...e.hooks??[]],instructions:[...e.instructions??[]],lib:[...e.lib??[]],kind:AGENT_SOURCE_MANIFEST_KIND,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(o.configModule=e.configModule),o}function deriveAgentIdFromRoots(n,r,a){let o=normalizeLogicalPath(relative(n,r));return o===``||o===`.`||o===`agent`?a??basename(n):basename(r)}function createPathDerivedSourceId(e){return normalizeLogicalPath(e)}function createModuleSourceRef(e){let t=normalizeLogicalPath(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??createPathDerivedSourceId(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function createConnectionSourceRef(e){return{...createModuleSourceRef(e),connectionName:e.connectionName}}function createLocalSubagentSourceRef(e){let t=normalizeLogicalPath(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??createPathDerivedSourceId(t),subagentId:e.subagentId}}function createSkillPackageSourceRef(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:normalizeLogicalPath(e.logicalPath),markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId,sourceKind:`skill-package`}}export{AGENT_SOURCE_MANIFEST_KIND,AGENT_SOURCE_MANIFEST_VERSION,createAgentSourceManifest,createConnectionSourceRef,createLocalSubagentSourceRef,createModuleSourceRef,createPathDerivedSourceId,createSkillPackageSourceRef,deriveAgentIdFromRoots};
1
+ import{basename,relative,resolve}from"node:path";import{summarizeDiscoverDiagnostics}from"#discover/diagnostics.js";import{normalizeLogicalPath}from"#discover/filesystem.js";const AGENT_SOURCE_MANIFEST_KIND=`eve-agent-discovery-manifest`,AGENT_SOURCE_MANIFEST_VERSION=12;function createAgentSourceManifest(e){let t=resolve(e.appRoot),i=resolve(e.agentRoot),o={agentId:e.agentId??deriveAgentIdFromRoots(t,i,e.packageName),agentRoot:i,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:summarizeDiscoverDiagnostics(e.diagnostics??[]),extensions:[...e.extensions??[]],resolvedExtensions:[...e.resolvedExtensions??[]],hooks:[...e.hooks??[]],instructions:[...e.instructions??[]],lib:[...e.lib??[]],kind:AGENT_SOURCE_MANIFEST_KIND,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(o.configModule=e.configModule),o}function deriveAgentIdFromRoots(n,r,a){let o=normalizeLogicalPath(relative(n,r));return o===``||o===`.`||o===`agent`?a??basename(n):basename(r)}function createPathDerivedSourceId(e){return normalizeLogicalPath(e)}function createModuleSourceRef(e){let t=normalizeLogicalPath(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??createPathDerivedSourceId(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function createConnectionSourceRef(e){return{...createModuleSourceRef(e),connectionName:e.connectionName}}function createLocalSubagentSourceRef(e){let t=normalizeLogicalPath(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??createPathDerivedSourceId(t),subagentId:e.subagentId}}function createSkillPackageSourceRef(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:normalizeLogicalPath(e.logicalPath),markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId,sourceKind:`skill-package`}}export{AGENT_SOURCE_MANIFEST_KIND,AGENT_SOURCE_MANIFEST_VERSION,createAgentSourceManifest,createConnectionSourceRef,createLocalSubagentSourceRef,createModuleSourceRef,createPathDerivedSourceId,createSkillPackageSourceRef,deriveAgentIdFromRoots};
@@ -1 +1 @@
1
- import{basename,dirname,join,resolve}from"node:path";import{DISCOVER_PROJECT_NOT_FOUND,createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifyAgentRootEntry,getDirectoryEntryType,isProjectMarkerEntry}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";var DiscoveryProjectResolutionError=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function resolveDiscoveryProject(e=process.cwd(),n={}){let r=n.source??createDiskProjectSource(),a=await resolveSearchDirectory(r,e),o=a;for(;;){let e=await tryResolveNestedProjectFromAgentDirectory(r,o);if(e!==null)return e;let n=await tryResolveNestedProjectFromAppRoot(r,o);if(n!==null)return n;if(await isFlatAgentRoot(r,o))return{agentRoot:o,appRoot:o,layout:`flat`};let i=dirname(o);if(i===o)break;o=i}throw new DiscoveryProjectResolutionError(createDiscoverErrorDiagnostic({code:DISCOVER_PROJECT_NOT_FOUND,message:`Could not resolve an eve agent root from "${a}".`,sourcePath:a}))}async function resolveSearchDirectory(e,n){let i=resolve(n);return await e.stat(i)===`directory`?i:dirname(i)}async function tryResolveNestedProjectFromAgentDirectory(n,r){if(basename(r)!==`agent`)return null;let i=dirname(r);return await hasProjectMarkers(n,i)?{agentRoot:r,appRoot:i,layout:`nested`}:null}async function tryResolveNestedProjectFromAppRoot(e,t){if(!await hasProjectMarkers(e,t))return null;let r=join(t,`agent`);return await directoryExists(e,r)?{agentRoot:r,appRoot:t,layout:`nested`}:null}async function isFlatAgentRoot(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=classifyAgentRootEntry(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function hasProjectMarkers(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>isProjectMarkerEntry(e,t))}async function readDirectoryEntryTypes(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,getDirectoryEntryType(e)]))}async function directoryExists(e,t){return await e.stat(t)===`directory`}export{DiscoveryProjectResolutionError,resolveDiscoveryProject};
1
+ import{basename,dirname,join,resolve}from"node:path";import{DISCOVER_PROJECT_NOT_FOUND,createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifyAgentRootEntry,getDirectoryEntryType,isProjectMarkerEntry}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";var DiscoveryProjectResolutionError=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function resolveDiscoveryProject(e=process.cwd(),n={}){let r=n.source??createDiskProjectSource(),a=await resolveSearchDirectory(r,e),o=a;for(;;){let e=await tryResolveNestedProjectFromAgentDirectory(r,o);if(e!==null)return e;let n=await tryResolveNestedProjectFromAppRoot(r,o);if(n!==null)return n;if(await isFlatAgentRoot(r,o))return{agentRoot:o,appRoot:o,layout:`flat`};let i=dirname(o);if(i===o)break;o=i}throw new DiscoveryProjectResolutionError(createDiscoverErrorDiagnostic({code:DISCOVER_PROJECT_NOT_FOUND,message:`Could not resolve an eve agent root from "${a}".`,sourcePath:a}))}async function resolveSearchDirectory(e,n){let i=resolve(n);return await e.stat(i)===`directory`?i:dirname(i)}async function tryResolveNestedProjectFromAgentDirectory(n,r){if(basename(r)!==`agent`)return null;let i=dirname(r);return await hasProjectMarkers(n,i)?{agentRoot:r,appRoot:i,layout:`nested`}:null}async function tryResolveNestedProjectFromAppRoot(e,t){if(!await hasProjectMarkers(e,t))return null;let r=join(t,`agent`);return await directoryExists(e,r)?{agentRoot:r,appRoot:t,layout:`nested`}:null}async function isFlatAgentRoot(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=classifyAgentRootEntry(e,t);return n!==`unknown`&&n!==`ignored-directory`&&n!==`lib-directory`})}async function hasProjectMarkers(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>isProjectMarkerEntry(e,t))}async function readDirectoryEntryTypes(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,getDirectoryEntryType(e)]))}async function directoryExists(e,t){return await e.stat(t)===`directory`}export{DiscoveryProjectResolutionError,resolveDiscoveryProject};
@@ -27,7 +27,8 @@ export declare function messageIncludes(token: string | RegExp): RunAssertion;
27
27
  /**
28
28
  * Asserts a completed tool call with `name` happened. Options constrain the
29
29
  * call further: `input` partial-deep-matches, `output` matches the result,
30
- * `status` overrides the lifecycle state, and `count` requires an exact count.
30
+ * `status` overrides the lifecycle state, and `count` constrains the number of
31
+ * matches with either an exact number or a predicate.
31
32
  */
32
33
  export declare function calledTool(name: string, options?: EveEvalToolCallMatchOptions): RunAssertion;
33
34
  /**
@@ -68,7 +69,7 @@ export declare function calledSubagent(name: string, options?: EveEvalSubagentCa
68
69
  * stream. `label` names the assertion in reports.
69
70
  */
70
71
  export declare function eventsSatisfy(label: string, predicate: (events: readonly HandleMessageStreamEvent[]) => boolean): RunAssertion;
71
- /** Asserts a typed stream event exists, optionally with an exact count. */
72
+ /** Asserts a typed stream event exists, optionally constraining its count. */
72
73
  export declare function typedEvent(matcher: EveEvalEventMatch): RunAssertion;
73
74
  /** Asserts no typed stream event matches. */
74
75
  export declare function notEvent(matcher: EveEvalEventMatch): RunAssertion;
@@ -1,2 +1,2 @@
1
- import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on ${e.derived.inputRequests.length} unanswered input request(s)`):PASS:t}}}function parked(){return{name:`parked`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`):t}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let n=joinCompletedMessages(t.events);return(typeof e==`string`?n.includes(e):testRegExp(e,n))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(n)}`)}}}function calledTool(e,t={}){return validateCount(t.count),{name:`calledTool(${e})`,evaluate(n){let r=n.derived.toolCalls.filter(t=>t.name===e),a=r.filter(e=>toolCallMatches(e,t));if(t.count===void 0?a.length>0:a.length===t.count)return{score:1,metadata:{matchingCalls:a.length}};let o=r.length>0?`observed ${e} calls: ${r.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`;return fail(`${t.count===void 0?`expected a matching call to "${e}"`:`expected exactly ${t.count} matching call(s), found ${a.length}`}; ${o}`)}}}function loadedSkill(e,t={}){return{...calledTool(LOAD_SKILL_TOOL_NAME,{...t,input:{skill:e}}),name:`loadedSkill(${e})`}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=requestedTools(t.events).map(e=>e.name),r=missingOrderedName(e,n);return r===void 0?PASS:fail(`missing "${r.name}" after [${e.slice(0,r.cursor).join(`, `)}]; observed request order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return validateCount(e),{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(formatFailedActionResult);return fail(`${t.length} failed action(s): ${n.join(`; `)}`,{failedActions:t.map(e=>({callId:e.data.result.callId,error:e.data.error,kind:e.data.result.kind,output:e.data.result.output,status:e.data.status}))})}}}function calledSubagent(e,t={}){return validateCount(t.count),{name:`calledSubagent(${e})`,evaluate(r){let i=r.derived.subagentCalls.filter(t=>t.name===e),a=i.filter(e=>subagentCallMatches(e,t));return(t.count===void 0?a.length>0:a.length===t.count)?{score:1,metadata:{matchingCalls:a.length}}:i.length===0?fail(`subagent "${e}" was never called; observed: [${r.derived.subagentCalls.map(e=>e.name).join(`, `)}]`,{observedSubagentCalls:r.derived.subagentCalls}):fail(`subagent "${e}" was called but ${a.length} call(s) matched the constraints`,{observedSubagentCalls:i})}}}function eventsSatisfy(e,t){return{name:`eventsSatisfy(${e})`,evaluate(n){return t(n.events)?PASS:fail(`event predicate "${e}" did not hold`)}}}function typedEvent(e){return validateCount(e.count),{name:`event(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return(e.count===void 0?r.length>0:r.length===e.count)?{score:1,metadata:{matchingEvents:r.length}}:fail(`expected ${e.count===void 0?`at least one`:`exactly ${e.count}`} matching ${e.type} event(s), found ${r.length}; observed: [${n.events.map(e=>e.type).join(`, `)}]`)}}}function notEvent(e){return{name:`notEvent(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return r.length===0?PASS:fail(`expected no matching ${e.type} events, found ${r.length}`)}}}function eventOrder(e){for(let t of e)validateCount(t.count);return{name:`eventOrder(${e.map(e=>e.type).join(` → `)})`,evaluate(n){let r=-1;for(let i of e){let e=n.events.flatMap((e,n)=>eventMatches(e,i)?[n]:[]);if(!(i.count===void 0?e.length>0:e.length===i.count))return fail(`expected ${i.count===void 0?`at least one`:`exactly ${i.count}`} matching ${i.type} event(s), found ${e.length}`);let a=e[0];if(a===void 0||a<=r)return fail(`event group ${i.type} did not occur after the previous group`);r=e[e.length-1]??r}return PASS}}}function outputEquals(t){return{name:`outputEquals`,evaluate(n){return deepEquals(n.output,t)?PASS:fail(`output ${truncate(JSON.stringify(n.output))} does not equal expected ${truncate(JSON.stringify(t))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);return!(`issues`in n)||n.issues===void 0?PASS:fail(`output failed schema validation: ${n.issues.map(e=>e.message).join(`; `)}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&n.data.message!==null&&t.push(n.data.message);return t.join(`
2
- `)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function formatFailedActionResult(e){let{result:t,status:n}=e.data;return[actionResultLabel(t),`callId=${t.callId}`,`status=${n}`,t.isError===!0?`isError=true`:void 0,e.data.error?.message===void 0?void 0:`error=${e.data.error.message}`,`output=${truncate(formatUnknown(t.output))}`].filter(e=>e!==void 0).join(` `)}function actionResultLabel(e){switch(e.kind){case`tool-result`:return`tool-result:${e.toolName}`;case`subagent-result`:return`subagent-result:${e.subagentName}`;case`load-skill-result`:return e.name===void 0?`load-skill-result`:`load-skill-result:${e.name}`}}function runFailure(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?void 0:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}function formatUnknown(e){if(e!==void 0){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}}function validateCount(e){if(e!==void 0&&(!Number.isInteger(e)||e<0))throw TypeError(`Assertion count must be a non-negative integer; received ${e}.`)}function missingOrderedName(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return;let r=e[n];return r===void 0?void 0:{cursor:n,name:r}}function requestedTools(e){let t=[],n=new Set,append=(e,r)=>{n.has(e)||(n.add(e),t.push({callId:e,name:r}))};for(let t of e)if(t.type===`actions.requested`)for(let e of t.data.actions)e.kind===`tool-call`&&append(e.callId,e.toolName);else if(t.type===`input.requested`)for(let e of t.data.requests){let{action:t}=e;t.kind===`tool-call`&&append(t.callId,t.toolName)}return t}export{calledSubagent,calledTool,eventOrder,eventsSatisfy,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,notEvent,outputEquals,outputMatches,parked,succeeded,toolOrder,typedEvent,usedNoTools};
1
+ import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on ${e.derived.inputRequests.length} unanswered input request(s)`):PASS:t}}}function parked(){return{name:`parked`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`):t}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let n=joinCompletedMessages(t.events);return(typeof e==`string`?n.includes(e):testRegExp(e,n))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(n)}`)}}}function calledTool(e,t={}){return validateCount(t.count),{name:`calledTool(${e})`,evaluate(n){let r=n.derived.toolCalls.filter(t=>t.name===e),a=r.filter(e=>toolCallMatches(e,t));if(matchesCount(t.count,a.length))return{score:1,metadata:{matchingCalls:a.length}};let o=r.length>0?`observed ${e} calls: ${r.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`,s;return s=t.count===void 0?`expected a matching call to "${e}"`:typeof t.count==`number`?`expected exactly ${t.count} matching call(s), found ${a.length}`:`expected matching call count to satisfy the count predicate, found ${a.length}`,fail(`${s}; ${o}`)}}}function loadedSkill(e,t={}){return{...calledTool(LOAD_SKILL_TOOL_NAME,{...t,input:{skill:e}}),name:`loadedSkill(${e})`}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=requestedTools(t.events).map(e=>e.name),r=missingOrderedName(e,n);return r===void 0?PASS:fail(`missing "${r.name}" after [${e.slice(0,r.cursor).join(`, `)}]; observed request order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return validateCount(e),{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(formatFailedActionResult);return fail(`${t.length} failed action(s): ${n.join(`; `)}`,{failedActions:t.map(e=>({callId:e.data.result.callId,error:e.data.error,kind:e.data.result.kind,output:e.data.result.output,status:e.data.status}))})}}}function calledSubagent(e,t={}){return validateCount(t.count),{name:`calledSubagent(${e})`,evaluate(r){let i=r.derived.subagentCalls.filter(t=>t.name===e),a=i.filter(e=>subagentCallMatches(e,t));return matchesCount(t.count,a.length)?{score:1,metadata:{matchingCalls:a.length}}:i.length===0?fail(`subagent "${e}" was never called; observed: [${r.derived.subagentCalls.map(e=>e.name).join(`, `)}]`,{observedSubagentCalls:r.derived.subagentCalls}):fail(`subagent "${e}" was called but ${a.length} call(s) matched the constraints`,{observedSubagentCalls:i})}}}function eventsSatisfy(e,t){return{name:`eventsSatisfy(${e})`,evaluate(n){return t(n.events)?PASS:fail(`event predicate "${e}" did not hold`)}}}function typedEvent(e){return validateCount(e.count),{name:`event(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return matchesCount(e.count,r.length)?{score:1,metadata:{matchingEvents:r.length}}:fail(`expected ${describeCount(e.count)} matching ${e.type} event(s), found ${r.length}; observed: [${n.events.map(e=>e.type).join(`, `)}]`)}}}function notEvent(e){return{name:`notEvent(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return r.length===0?PASS:fail(`expected no matching ${e.type} events, found ${r.length}`)}}}function eventOrder(e){for(let t of e)validateCount(t.count);return{name:`eventOrder(${e.map(e=>e.type).join(` → `)})`,evaluate(n){let r=-1;for(let i of e){let e=n.events.flatMap((e,n)=>eventMatches(e,i)?[n]:[]);if(!matchesCount(i.count,e.length))return fail(`expected ${describeCount(i.count)} matching ${i.type} event(s), found ${e.length}`);let a=e[0];if(a===void 0||a<=r)return fail(`event group ${i.type} did not occur after the previous group`);r=e[e.length-1]??r}return PASS}}}function outputEquals(t){return{name:`outputEquals`,evaluate(n){return deepEquals(n.output,t)?PASS:fail(`output ${truncate(JSON.stringify(n.output))} does not equal expected ${truncate(JSON.stringify(t))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);return!(`issues`in n)||n.issues===void 0?PASS:fail(`output failed schema validation: ${n.issues.map(e=>e.message).join(`; `)}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&n.data.message!==null&&t.push(n.data.message);return t.join(`
2
+ `)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function formatFailedActionResult(e){let{result:t,status:n}=e.data;return[actionResultLabel(t),`callId=${t.callId}`,`status=${n}`,t.isError===!0?`isError=true`:void 0,e.data.error?.message===void 0?void 0:`error=${e.data.error.message}`,`output=${truncate(formatUnknown(t.output))}`].filter(e=>e!==void 0).join(` `)}function actionResultLabel(e){switch(e.kind){case`tool-result`:return`tool-result:${e.toolName}`;case`subagent-result`:return`subagent-result:${e.subagentName}`;case`load-skill-result`:return e.name===void 0?`load-skill-result`:`load-skill-result:${e.name}`}}function runFailure(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?void 0:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}function formatUnknown(e){if(e!==void 0){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}}function matchesCount(e,t){return e===void 0?t>0:typeof e==`function`?e(t):t===e}function describeCount(e){return e===void 0?`at least one`:typeof e==`function`?`a count satisfying the predicate`:`exactly ${e}`}function validateCount(e){if(!(e===void 0||typeof e==`function`)&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw TypeError(`Assertion count must be a non-negative integer or predicate; received ${String(e)}.`)}function missingOrderedName(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return;let r=e[n];return r===void 0?void 0:{cursor:n,name:r}}function requestedTools(e){let t=[],n=new Set,append=(e,r)=>{n.has(e)||(n.add(e),t.push({callId:e,name:r}))};for(let t of e)if(t.type===`actions.requested`)for(let e of t.data.actions)e.kind===`tool-call`&&append(e.callId,e.toolName);else if(t.type===`input.requested`)for(let e of t.data.requests){let{action:t}=e;t.kind===`tool-call`&&append(t.callId,t.toolName)}return t}export{calledSubagent,calledTool,eventOrder,eventsSatisfy,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,notEvent,outputEquals,outputMatches,parked,succeeded,toolOrder,typedEvent,usedNoTools};
@@ -4,6 +4,6 @@ export { EveEvalTurnFailedError } from "#evals/session.js";
4
4
  export { mockModel } from "#evals/mock-model.js";
5
5
  export type { RuntimeIdentity } from "#protocol/message.js";
6
6
  export type { InputRequest } from "#runtime/input/types.js";
7
- export type { EveEvalEventMatch, EveEvalInputRequestMatchOptions, EveEvalValueMatcher, EveEvalToolCallMatchOptions, EveEvalSkillLoadMatchOptions, EveEvalSubagentCallMatchOptions, } from "#evals/match.js";
7
+ export type { EveEvalCountMatcher, EveEvalEventMatch, EveEvalInputRequestMatchOptions, EveEvalValueMatcher, EveEvalToolCallMatchOptions, EveEvalSkillLoadMatchOptions, EveEvalSubagentCallMatchOptions, } from "#evals/match.js";
8
8
  export type { Assertion, AssertionHandle, AssertionResult, AssertionSeverity, AutoevalsJudges, EveEvalActionStatus, EveEvalAssertions, EveEvalContext, EveEvalDerivedFacts, EveEvalJudgeConfig, EveEvalRunSummary, EveEvalSession, EveEvalSessionResult, EveEvalScheduleDispatchResult, EveEvalSubagentCall, EveEval, EveEvalConfig, EveEvalConfigInput, EveEvalDefinition, EveEvalInput, EveEvalResult, EveEvalTarget, EveEvalTargetCapabilities, EveEvalTargetHandle, EveEvalTaskResult, EveEvalToolCall, EveEvalTurn, EveEvalVerdict, JudgeContext, JudgeOpts, } from "#evals/types.js";
9
9
  export type { MockModelMessage, MockModelOptions, MockModelRequest, MockModelResponder, MockModelResponse, MockModelTool, MockModelToolCall, MockModelToolResult, MockModelUsage, } from "#evals/mock-model.js";
@@ -1 +1 @@
1
- import{isAbsolute,resolve}from"node:path";import{readFile}from"node:fs/promises";import matter from"#compiled/gray-matter/index.js";async function loadYaml(e){let t=await readFile(isAbsolute(e)?e:resolve(process.cwd(),e),`utf-8`);return matter(t.trimStart().startsWith(`---`)?t:`---\n${t}\n---`).data??{}}export{loadYaml};
1
+ import{isAbsolute,resolve}from"node:path";import{readFile}from"node:fs/promises";import{parseFrontmatter}from"#internal/helpers/gray-matter.js";async function loadYaml(e){let t=await readFile(isAbsolute(e)?e:resolve(process.cwd(),e),`utf-8`);return parseFrontmatter(t.trimStart().startsWith(`---`)?t:`---\n${t}\n---`).data}export{loadYaml};
@@ -15,6 +15,11 @@ import type { EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
15
15
  * - a **function** receives the observed value and returns a boolean verdict
16
16
  */
17
17
  export type EveEvalValueMatcher<T = JsonValue | undefined> = EveEvalDeepMatcher<T>;
18
+ /**
19
+ * Constraint over an observed assertion count. A number requires an exact
20
+ * count; a predicate receives the observed count and returns its verdict.
21
+ */
22
+ export type EveEvalCountMatcher = number | ((count: number) => boolean);
18
23
  type EveEvalDeepMatcher<T> = RegExp | ((value: T) => boolean) | (T extends readonly (infer TEntry)[] ? readonly EveEvalDeepMatcher<TEntry>[] : T extends object ? {
19
24
  readonly [K in keyof T]?: EveEvalDeepMatcher<T[K]>;
20
25
  } : T);
@@ -29,8 +34,8 @@ export interface EveEvalToolCallMatchOptions {
29
34
  readonly output?: EveEvalValueMatcher;
30
35
  /** Required lifecycle outcome. Defaults to `"completed"`. */
31
36
  readonly status?: EveEvalToolCall["status"];
32
- /** Exact number of matching calls required. Defaults to "at least one". */
33
- readonly count?: number;
37
+ /** Constraint over the matching call count. Defaults to "at least one". */
38
+ readonly count?: EveEvalCountMatcher;
34
39
  }
35
40
  /**
36
41
  * Constraints applied to a `load_skill` call by `t.loadedSkill`. Identical to
@@ -48,8 +53,8 @@ export interface EveEvalSubagentCallMatchOptions {
48
53
  readonly output?: EveEvalValueMatcher;
49
54
  /** Required lifecycle outcome. Defaults to `"completed"`. */
50
55
  readonly status?: EveEvalSubagentCall["status"];
51
- /** Exact number of matching delegations required. Defaults to "at least one". */
52
- readonly count?: number;
56
+ /** Constraint over the matching delegation count. Defaults to "at least one". */
57
+ readonly count?: EveEvalCountMatcher;
53
58
  }
54
59
  /** Constraints accepted by `requireInputRequest`. */
55
60
  export interface EveEvalInputRequestMatchOptions {
@@ -74,8 +79,8 @@ export type EveEvalEventMatch<TType extends HandleMessageStreamEvent["type"] = H
74
79
  }> extends {
75
80
  data: infer TData;
76
81
  } ? TData : never>;
77
- /** Exact number of matching events required. Defaults to "at least one". */
78
- readonly count?: number;
82
+ /** Constraint over the matching event count. Defaults to "at least one". */
83
+ readonly count?: EveEvalCountMatcher;
79
84
  } : never;
80
85
  /**
81
86
  * Returns true when the observed value satisfies a matcher (literal, RegExp,
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";function applyMicrosandboxNetwork(e,t){let n=createMicrosandboxNetworkPlan(t);return n.disabled?e.disableNetwork():n.policy===null&&n.transformHeaderRules.length===0?e:e.network(e=>{let t=e.enabled(!0);if(n.policy!==null&&(t=t.policyJson(serializeMicrosandboxNetworkPolicyJson(n.policy))),n.transformHeaderRules.length===0)return t;t=t.trustHostCAs(!0);for(let e of n.transformHeaderRules)for(let[n,r]of Object.entries(e.headers)){let i=e.placeholderHeaders[n];if(i===void 0)continue;let a=createSecretEnvName(e.domain,n,r);t=t.secret(t=>{let n=t.env(a).value(r).placeholder(i).injectHeaders(!0).injectBasicAuth(!0).injectQuery(!1).injectBody(!1).requireTlsIdentity(!0);return n=e.domain===`*`?n.allowAnyHostDangerous(!0):e.domain.startsWith(`*.`)?n.allowHostPattern(e.domain):n.allowHost(e.domain),n})}return t})}function serializeMicrosandboxNetworkPolicyJson(e){let t={default_egress:e.defaultEgress,default_ingress:e.defaultIngress,rules:e.rules.map(e=>({action:e.action,destination:serializeMicrosandboxNetworkDestination(e.destination),direction:e.direction,ports:e.ports,protocols:e.protocols}))};return JSON.stringify(t)}function createMicrosandboxNetworkPlan(e){if(e===void 0||e===`allow-all`)return{disabled:!1,policy:{defaultEgress:`allow`,defaultIngress:`deny`,rules:[]},transformHeaderRules:[]};if(e===`deny-all`)return{disabled:!0,policy:null,transformHeaderRules:[]};let t=[],n=[],r=normalizeAllowEntries(e.allow),i=r.some(e=>e.domain===`*`),a=i?`allow`:`deny`;for(let n of e.subnets?.deny??[])t.push({action:`deny`,destination:{cidr:n,kind:`cidr`},direction:`egress`,ports:[],protocols:[]});for(let n of e.subnets?.allow??[])t.push({action:`allow`,destination:{cidr:n,kind:`cidr`},direction:`egress`,ports:[],protocols:[]});i||t.push({action:`allow`,destination:{kind:`any`},direction:`egress`,ports:[{start:53,end:53}],protocols:[`udp`,`tcp`]});for(let e of r)if(e.domain!==`*`){t.push({action:`allow`,destination:domainToDestination(e.domain),direction:`egress`,ports:[],protocols:[]});for(let t of e.rules)for(let r of normalizeTransforms(t.transform))Object.keys(r.headers).length!==0&&n.push({domain:e.domain,headers:r.headers,match:t.match,placeholderHeaders:createPlaceholderHeaders(e.domain,r.headers)})}return{disabled:!1,policy:{defaultEgress:a,defaultIngress:`deny`,rules:t},transformHeaderRules:n}}function createTransformBrokerEnvironment(e){if(e.transformHeaderRules.length===0)return{};let t=e.transformHeaderRules.flatMap(e=>Object.entries(e.placeholderHeaders).filter(([e])=>e.toLowerCase()===`authorization`).flatMap(([t,n])=>e.domain===`*`||e.domain.startsWith(`*.`)?[]:[{key:`http.https://${e.domain}/.extraheader`,value:`${t}: ${n}`}])),n={};return t.length>0&&(n.GIT_CONFIG_COUNT=String(t.length),t.forEach((e,t)=>{n[`GIT_CONFIG_KEY_${t}`]=e.key,n[`GIT_CONFIG_VALUE_${t}`]=e.value})),{EVE_MICROSANDBOX_NETWORK_TRANSFORMS:Buffer.from(JSON.stringify(e.transformHeaderRules)).toString(`base64`),...n}}function normalizeAllowEntries(e){return e===void 0?[]:Array.isArray(e)?e.map(e=>({domain:e,rules:[]})):Object.entries(e).map(([e,t])=>({domain:e,rules:Array.isArray(t)?t:[]}))}function normalizeTransforms(e){return e===void 0?[]:e.map(e=>({headers:e.headers??{}}))}function domainToDestination(e){return e.startsWith(`*.`)?{kind:`domainSuffix`,suffix:e.slice(2)}:{domain:e,kind:`domain`}}function serializeMicrosandboxNetworkDestination(e){switch(e.kind){case`any`:return`any`;case`cidr`:return{cidr:e.cidr??``};case`domain`:return{domain:e.domain??``};case`domainSuffix`:return{domain_suffix:e.suffix??``};case`group`:return{group:e.group??``};default:throw Error(`Unsupported microsandbox network destination kind.`)}}function createPlaceholderHeaders(e,t){let n={};for(let[r,i]of Object.entries(t))n[r]=`__EVE_MSB_SECRET_${createStableHash(`${e}:${r}:${i}`).slice(0,24)}__`;return n}function createSecretEnvName(e,t,n){return`EVE_MSB_SECRET_${createStableHash(`${e}:${t}:${n}`).slice(0,24).toUpperCase()}`}function createStableHash(t){return createHash(`sha256`).update(t).digest(`hex`)}export{applyMicrosandboxNetwork,createMicrosandboxNetworkPlan,createTransformBrokerEnvironment,serializeMicrosandboxNetworkPolicyJson};
1
+ import{createHash}from"node:crypto";function applyMicrosandboxNetwork(e,t){let n=createMicrosandboxNetworkPlan(t);return n.disabled?e.disableNetwork():n.policy===null&&n.transformHeaderRules.length===0?e:e.network(e=>{let t=e.enabled(!0);if(n.policy!==null&&(t=t.policyJson(serializeMicrosandboxNetworkPolicyJson(n.policy))),n.transformHeaderRules.length===0)return t;t=t.trustHostCAs(!0);for(let e of n.transformHeaderRules)for(let[n,r]of Object.entries(e.headers)){let i=e.placeholderHeaders[n];if(i===void 0)continue;let a=createSecretEnvName(e.domain,n,r);t=t.secret(t=>{let n=t.env(a).value(r).placeholder(i).injectHeaders(!0).injectBasicAuth(!0).injectQuery(!1).injectBody(!1).requireTlsIdentity(!0);return n=e.domain===`*`?n.allowAnyHostDangerous(!0):e.domain.startsWith(`*.`)?n.allowHostPattern(e.domain):n.allowHost(e.domain),n})}return t})}function serializeMicrosandboxNetworkPolicyJson(e){let t={default_egress:e.defaultEgress,default_ingress:e.defaultIngress,rules:e.rules.map(e=>({action:e.action,destination:serializeMicrosandboxNetworkDestination(e.destination),direction:e.direction,ports:e.ports,protocols:e.protocols}))};return JSON.stringify(t)}function createMicrosandboxNetworkPlan(e){if(e===void 0||e===`allow-all`)return{disabled:!1,policy:{defaultEgress:`allow`,defaultIngress:`deny`,rules:[]},transformHeaderRules:[]};if(e===`deny-all`)return{disabled:!0,policy:null,transformHeaderRules:[]};let t=[],n=[],r=normalizeAllowEntries(e.allow),i=r.some(e=>e.domain===`*`),a=i?`allow`:`deny`;for(let n of e.subnets?.deny??[])t.push({action:`deny`,destination:{cidr:n,kind:`cidr`},direction:`egress`,ports:[],protocols:[]});for(let n of e.subnets?.allow??[])t.push({action:`allow`,destination:{cidr:n,kind:`cidr`},direction:`egress`,ports:[],protocols:[]});i||t.push({action:`allow`,destination:{kind:`any`},direction:`egress`,ports:[{start:53,end:53}],protocols:[`udp`,`tcp`]});for(let e of r)if(e.domain!==`*`){t.push({action:`allow`,destination:domainToDestination(e.domain),direction:`egress`,ports:[],protocols:[]});for(let t of e.rules)for(let r of normalizeTransforms(t.transform))Object.keys(r.headers).length!==0&&n.push({domain:e.domain,headers:r.headers,match:t.match,placeholderHeaders:createPlaceholderHeaders(e.domain,r.headers)})}return{disabled:!1,policy:{defaultEgress:a,defaultIngress:`deny`,rules:t},transformHeaderRules:n}}function createTransformBrokerEnvironment(e){if(e.transformHeaderRules.length===0)return{};let t=e.transformHeaderRules.flatMap(e=>Object.entries(e.placeholderHeaders).filter(([e])=>e.toLowerCase()===`authorization`).flatMap(([t,n])=>e.domain===`*`||e.domain.startsWith(`*.`)?[]:[{key:`http.https://${e.domain}/.extraheader`,value:`${t}: ${n}`}])),n={};return t.length>0&&(n.GIT_CONFIG_COUNT=String(t.length),t.forEach((e,t)=>{n[`GIT_CONFIG_KEY_${t}`]=e.key,n[`GIT_CONFIG_VALUE_${t}`]=e.value})),n}function normalizeAllowEntries(e){return e===void 0?[]:Array.isArray(e)?e.map(e=>({domain:e,rules:[]})):Object.entries(e).map(([e,t])=>({domain:e,rules:Array.isArray(t)?t:[]}))}function normalizeTransforms(e){return e===void 0?[]:e.map(e=>({headers:e.headers??{}}))}function domainToDestination(e){return e.startsWith(`*.`)?{kind:`domainSuffix`,suffix:e.slice(2)}:{domain:e,kind:`domain`}}function serializeMicrosandboxNetworkDestination(e){switch(e.kind){case`any`:return`any`;case`cidr`:return{cidr:e.cidr??``};case`domain`:return{domain:e.domain??``};case`domainSuffix`:return{domain_suffix:e.suffix??``};case`group`:return{group:e.group??``};default:throw Error(`Unsupported microsandbox network destination kind.`)}}function createPlaceholderHeaders(e,t){let n={};for(let[r,i]of Object.entries(t))n[r]=`__EVE_MSB_SECRET_${createStableHash(`${e}:${r}:${i}`).slice(0,24)}__`;return n}function createSecretEnvName(e,t,n){return`EVE_MSB_SECRET_${createStableHash(`${e}:${t}:${n}`).slice(0,24).toUpperCase()}`}function createStableHash(t){return createHash(`sha256`).update(t).digest(`hex`)}export{applyMicrosandboxNetwork,createMicrosandboxNetworkPlan,createTransformBrokerEnvironment,serializeMicrosandboxNetworkPolicyJson};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.22.2`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.22.4`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1,5 +1,11 @@
1
1
  export interface AuthoredModuleLoadOptions {
2
2
  readonly externalDependencies?: readonly string[];
3
+ /**
4
+ * When set, the module being loaded is extension-owned: its
5
+ * `defineState`/`defineExtension` calls (and those of its same-package
6
+ * dependencies bundled with it) are scoped to this namespace at bundle time.
7
+ */
8
+ readonly extensionScopeNamespace?: string;
3
9
  }
4
10
  /**
5
11
  * Loads one authored module namespace from disk during compile-time
@@ -7,3 +13,11 @@ export interface AuthoredModuleLoadOptions {
7
13
  * Promise so the underlying bundle/import pipeline runs once.
8
14
  */
9
15
  export declare function loadAuthoredModuleNamespace(modulePath: string, options?: AuthoredModuleLoadOptions): Promise<Record<string, unknown>>;
16
+ /**
17
+ * Bundles one authored entry module to a self-contained ESM string using the
18
+ * same plugin stack the dev/eval loader uses: `eve/*` and node_modules deps stay
19
+ * external, relative source is inlined, and (when `extensionScopeNamespace` is
20
+ * set) `defineState`/`defineExtension` are scoped to that namespace. Shared with
21
+ * `eve build`'s extension entrypoint compilation so both paths bundle identically.
22
+ */
23
+ export declare function bundleAuthoredModuleCode(modulePath: string, options?: AuthoredModuleLoadOptions): Promise<string>;
@@ -1,2 +1,2 @@
1
- import{createRequire}from"node:module";import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,realpathSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve,sep}from"node:path";import{createHash}from"node:crypto";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`,CACHED_CHANNEL_PREFIX=`eve-cached-channel:`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,n):await import(createFileImportSpecifier(e)),`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function loadBundledAuthoredModule(e,t){let i=getChannelModuleCache(),a=resolveAuthoredPackageRoot(e),s=resolveAuthoredTsConfigPath(a),c=normalizeExternalDependencies(t.externalDependencies),l=[i&&i.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let r=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(r===null||typeof r.id!=`string`)return;let a=resolve(r.id);if(i.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(19);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
- `),moduleType:`js`}}}:null,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:a,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createPackageBoundaryPlugin(a,c)].filter(e=>e!==null),u;try{u=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:a,input:e,platform:`node`,plugins:l,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:s,write:!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}}),`authored module for "${e}"`)}catch(t){throw createAuthoredModuleBundleError(e,t)}let d=createHash(`sha1`).update(e).update(`\0`).update(c.join(`\0`)).update(`\0`).update(u.code).digest(`hex`),f=join(a,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),p=join(f,`${d}.mjs`);return existsSync(p)||(mkdirSync(f,{recursive:!0}),writeFileSync(p,u.code)),await import(`${createFileImportSpecifier(p)}?v=${d}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createPackageBoundaryPlugin(e,t){let n=toCanonicalPath(e);return{name:`eve-package-boundary`,async resolveId(r,i,a){if(!isPackageImport(r))return;if(isEveFrameworkImport(r))return{external:!0,id:r};let o=resolveConfiguredExternalDependency(r,t);if(o!==void 0){if(r!==o){let t=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(t!==null&&typeof t.id==`string`)return{external:!0,id:resolveExternalFilePath({importer:i,packageRoot:e,resolvedId:t.id,source:r})};let n=resolveExternalFilePath({importer:i,packageRoot:e,source:r});if(n!==void 0)return{external:!0,id:n}}return{external:!0,id:r}}let s=i===void 0||i.startsWith(`\0`)||i.startsWith(CACHED_CHANNEL_PREFIX)?void 0:resolve(i);if(s!==void 0&&isPathInsideOrEqual(toCanonicalPath(s),n)){let e=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${r}" imported from "${s}". 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:r}}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}`}function normalizeExternalDependencies(e=[]){return[...new Set([...SERVER_EXTERNAL_PACKAGES,...e])].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function resolveExternalFilePath(t){if(t.resolvedId!==void 0){let e=resolveExistingExternalFilePath(t.resolvedId);if(e!==void 0)return e}let n=normalizeImporterPath(t.importer);if(n!==void 0)try{return createRequire(n).resolve(t.source)}catch{}try{return createRequire(join(t.packageRoot,`package.json`)).resolve(t.source)}catch{return t.resolvedId}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let r=`${e}${t}`;if(existsSync(r))return r}}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function normalizeImporterPath(e){if(!(e===void 0||e.startsWith(`\0`)||e.startsWith(CACHED_CHANNEL_PREFIX)))return resolve(e)}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function isEveFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)}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}`)}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,t);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=r}}export{loadAuthoredModuleNamespace};
1
+ import{createRequire}from"node:module";import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,realpathSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve,sep}from"node:path";import{createHash}from"node:crypto";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`,CACHED_CHANNEL_PREFIX=`eve-cached-channel:`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,n):await import(createFileImportSpecifier(e)),`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){let n=getChannelModuleCache(),r=resolveAuthoredPackageRoot(e),i=resolveAuthoredTsConfigPath(r),a=normalizeExternalDependencies(t.externalDependencies),o=[n&&n.size>0?{name:`eve-channel-identity`,async resolveId(e,t,r){if(!/channels[/\\]/.test(e)||r.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:r.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(n.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(19);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
+ `),moduleType:`js`}}}:null,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:r,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createPackageBoundaryPlugin(r,a)].filter(e=>e!==null);try{return getSingleRolldownChunk(await buildWithNitroRolldown({cwd:r,input:e,platform:`node`,plugins:o,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:i,write:!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}}),`authored module for "${e}"`).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}async function loadBundledAuthoredModule(e,t){let i=await bundleAuthoredModuleCode(e,t),a=normalizeExternalDependencies(t.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(a.join(`\0`)).update(`\0`).update(t.extensionScopeNamespace??``).update(`\0`).update(i).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,i)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createPackageBoundaryPlugin(e,t){let n=toCanonicalPath(e);return{name:`eve-package-boundary`,async resolveId(r,i,a){if(!isPackageImport(r))return;if(isEveFrameworkImport(r))return{external:!0,id:r};let o=resolveConfiguredExternalDependency(r,t);if(o!==void 0){if(r!==o){let t=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(t!==null&&typeof t.id==`string`)return{external:!0,id:resolveExternalFilePath({importer:i,packageRoot:e,resolvedId:t.id,source:r})};let n=resolveExternalFilePath({importer:i,packageRoot:e,source:r});if(n!==void 0)return{external:!0,id:n}}return{external:!0,id:r}}let s=i===void 0||i.startsWith(`\0`)||i.startsWith(CACHED_CHANNEL_PREFIX)?void 0:resolve(i);if(s!==void 0&&isPathInsideOrEqual(toCanonicalPath(s),n)){let e=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${r}" imported from "${s}". 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:r}}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function normalizeExternalDependencies(e=[]){return[...new Set([...SERVER_EXTERNAL_PACKAGES,...e])].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function resolveExternalFilePath(t){if(t.resolvedId!==void 0){let e=resolveExistingExternalFilePath(t.resolvedId);if(e!==void 0)return e}let n=normalizeImporterPath(t.importer);if(n!==void 0)try{return createRequire(n).resolve(t.source)}catch{}try{return createRequire(join(t.packageRoot,`package.json`)).resolve(t.source)}catch{return t.resolvedId}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let r=`${e}${t}`;if(existsSync(r))return r}}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function normalizeImporterPath(e){if(!(e===void 0||e.startsWith(`\0`)||e.startsWith(CACHED_CHANNEL_PREFIX)))return resolve(e)}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function isEveFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)}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}`)}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,t);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=r}}export{bundleAuthoredModuleCode,loadAuthoredModuleNamespace};
@@ -1 +1 @@
1
- import{join}from"node:path";import{collectModuleRefsForManifest}from"#compiler/module-map.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}))}async function hydrateCompiledModuleMapFromManifest(e){let t={},r=[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))];for(let e of r)t[e.nodeId]={modules:await hydrateCompiledNodeScope({agentRoot:e.agentRoot,manifest:e.manifest})};return{nodes:t}}async function hydrateCompiledNodeScope(n){let i=collectModuleRefsForManifest(n.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),a=n.manifest.config.build?.externalDependencies??[],o={};for(let t of i){let i=join(n.agentRoot,t.logicalPath);o[t.sourceId]=await loadAuthoredModuleNamespace(i,{externalDependencies:a})}return o}export{loadCompiledModuleMapFromAuthoredSource};
1
+ import{join}from"node:path";import{collectModuleRefsForManifest}from"#compiler/module-map.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";const EXT_CONFIG_SCOPE=Symbol.for(`eve.ext-config-scope`);async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}))}async function hydrateCompiledModuleMapFromManifest(e){let t={},r=[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))],i={byMountNamespace:new Map(e.extensionMounts.map(e=>[e.namespace,e.packageNamespace])),byMountSourceId:new Map(e.extensionMounts.map(e=>[e.mountSourceId,e.packageNamespace]))};for(let e of r)t[e.nodeId]={modules:await hydrateCompiledNodeScope({agentRoot:e.agentRoot,manifest:e.manifest,scopeIndex:i})};return{nodes:t}}function extensionNamespaceForSourceId(e,t){let n=e.match(/^ext:([^:]+):/);return n===null?void 0:t.byMountNamespace.get(n[1])}async function hydrateCompiledNodeScope(n){let i=collectModuleRefsForManifest(n.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),a=n.manifest.config.build?.externalDependencies??[],o=globalThis,s={};for(let t of i){let i=join(n.agentRoot,t.logicalPath),c=extensionNamespaceForSourceId(t.sourceId,n.scopeIndex),l=n.scopeIndex.byMountSourceId.get(t.sourceId);l!==void 0&&(o[EXT_CONFIG_SCOPE]=l);try{s[t.sourceId]=await loadAuthoredModuleNamespace(i,{externalDependencies:a,extensionScopeNamespace:c})}finally{l!==void 0&&(o[EXT_CONFIG_SCOPE]=void 0)}}return s}export{loadCompiledModuleMapFromAuthoredSource};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * One extension's on-disk source root paired with the namespace its durable
3
+ * state keys and config binding must be scoped to.
4
+ */
5
+ export interface ExtensionScope {
6
+ /** Absolute path to the extension's source root. */
7
+ readonly sourceRoot: string;
8
+ /** Package-derived namespace (e.g. `acme-crm`). */
9
+ readonly packageNamespace: string;
10
+ }
11
+ /** The subset of the rolldown/rollup plugin shape this plugin implements. */
12
+ export interface ExtensionScopeBundlerPlugin {
13
+ readonly name: string;
14
+ resolveId(source: string, importer: string | undefined): string | undefined;
15
+ load(id: string): {
16
+ code: string;
17
+ moduleType: "js";
18
+ } | undefined;
19
+ }
20
+ /**
21
+ * Path-containment scope plugin for the whole-application bundle (the production
22
+ * build). Any module physically under an extension's source root has its
23
+ * `eve/context`/`eve/extension` imports redirected to a generated shim that
24
+ * bakes the extension's package namespace into `defineState`/`defineExtension`.
25
+ *
26
+ * Returns `null` when there are no extensions, so consumer-only builds carry no
27
+ * extra plugin and their output is byte-identical to a non-extension build.
28
+ */
29
+ export declare function createExtensionScopePlugin(scopes: readonly ExtensionScope[]): ExtensionScopeBundlerPlugin | null;
30
+ /**
31
+ * Fixed-namespace scope plugin for a single extension-owned module bundle (the
32
+ * dev/eval per-module loader). The compiler already knows the loaded module is
33
+ * extension-owned and under which namespace, so every module in the bundle —
34
+ * the entry plus its same-package dependencies — is scoped, with no reliance on
35
+ * filesystem path matching (which is unreliable under workspace symlinks).
36
+ */
37
+ export declare function createFixedNamespaceScopePlugin(namespace: string): ExtensionScopeBundlerPlugin;
@@ -0,0 +1,3 @@
1
+ import{realpathSync}from"node:fs";import{resolve,sep}from"node:path";const VIRTUAL_PREFIX=`\0eve-ext-scope:`,SCOPED_FRAMEWORK_MODULES={"eve/context":`context`,"eve/extension":`extension`};function canonicalize(n){try{return realpathSync(n)}catch{return resolve(n)}}function importerPath(e){let t=e.indexOf(`?`);return canonicalize(t===-1?e:e.slice(0,t))}function isUnder(e,t){return e===t||e.startsWith(`${t}${sep}`)}function shimSource(e,t){let n=JSON.stringify(t);return e===`context`?[`import { defineState as __eveScopedDefineState } from "eve/context";`,`export function defineState(name, initial) {`,` return __eveScopedDefineState(${n} + "." + name, initial);`,`}`,``].join(`
2
+ `):[`import { defineExtension as __eveScopedDefineExtension } from "eve/extension";`,`export function defineExtension(options, namespace) {`,` return __eveScopedDefineExtension(options, namespace === undefined ? ${n} : namespace);`,`}`,``].join(`
3
+ `)}function scopeHooks(e,t){return{name:e,resolveId(e,n){let r=SCOPED_FRAMEWORK_MODULES[e];if(r===void 0||n===void 0||n.startsWith(`\0`))return;let i=t(n);if(i!==void 0)return`${VIRTUAL_PREFIX}${r}:${i}`},load(e){if(!e.startsWith(VIRTUAL_PREFIX))return;let t=e.slice(15),n=t.indexOf(`:`);return{code:shimSource(t.slice(0,n),t.slice(n+1)),moduleType:`js`}}}}function createExtensionScopePlugin(e){if(e.length===0)return null;let t=e.map(e=>({root:canonicalize(e.sourceRoot),packageNamespace:e.packageNamespace}));return scopeHooks(`eve-extension-scope`,e=>{let n=importerPath(e);for(let e of t)if(isUnder(n,e.root))return e.packageNamespace})}function createFixedNamespaceScopePlugin(e){return scopeHooks(`eve-extension-scope-fixed`,()=>e)}export{createExtensionScopePlugin,createFixedNamespaceScopePlugin};
@@ -0,0 +1,25 @@
1
+ import { type GrayMatterFile } from "#compiled/gray-matter/index.js";
2
+ /** Options for {@link parseFrontmatter}. */
3
+ export interface ParseFrontmatterOptions {
4
+ /**
5
+ * Opt in to gray-matter's built-in code-capable engines, so a `---js` /
6
+ * `---javascript` frontmatter fence is `eval()`d while parsing. This runs
7
+ * arbitrary code the instant the document is read, so only enable it for
8
+ * input you fully control and trust. Defaults to `false`, which rejects a
9
+ * JavaScript frontmatter fence instead of evaluating it.
10
+ */
11
+ readonly allowCodeEngines?: boolean;
12
+ }
13
+ /**
14
+ * Parses a document's YAML frontmatter and body.
15
+ *
16
+ * Safe by default: the code-capable frontmatter engines are disabled, so a
17
+ * `---js` fence throws rather than executing. This is the only supported way
18
+ * to run gray-matter in eve — callers must not import the bundled module
19
+ * directly, so that untrusted input can never reach an evaluating engine by
20
+ * accident. Pass `{ allowCodeEngines: true }` to deliberately opt back into
21
+ * evaluation for trusted input.
22
+ */
23
+ export declare function parseFrontmatter(source: string, options?: ParseFrontmatterOptions): GrayMatterFile<string>;
24
+ /** Reports whether a document opens with a frontmatter delimiter. */
25
+ export declare function hasFrontmatter(source: string): boolean;
@@ -0,0 +1 @@
1
+ import matter from"#compiled/gray-matter/index.js";function rejectJavaScriptFrontmatter(){throw Error(`JavaScript frontmatter is not supported.`)}const SAFE_GRAY_MATTER_OPTIONS={language:`yaml`,engines:{javascript:rejectJavaScriptFrontmatter,js:rejectJavaScriptFrontmatter}};function parseFrontmatter(t,n={}){return n.allowCodeEngines?matter(t):matter(t,SAFE_GRAY_MATTER_OPTIONS)}function hasFrontmatter(e){return matter.test(e)}export{hasFrontmatter,parseFrontmatter};
@@ -1,3 +1,3 @@
1
- import{isObject}from"#shared/guards.js";import{normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition}from"#internal/authored-definition/core.js";import matter from"#compiled/gray-matter/index.js";import{defineSchedule}from"#public/definitions/schedule.js";import{defineSkill}from"#public/definitions/skill.js";const CLOSED_FRONTMATTER_PATTERN=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function rejectJavaScriptFrontmatter(){throw Error(`JavaScript frontmatter is not supported.`)}const SAFE_GRAY_MATTER_OPTIONS={language:`yaml`,engines:{javascript:rejectJavaScriptFrontmatter,js:rejectJavaScriptFrontmatter}};function parseMarkdownDocument(t){if(!matter.test(t))return{hasFrontmatter:!1,frontmatter:{},markdown:t};let n;try{n=matter(t,SAFE_GRAY_MATTER_OPTIONS)}catch(e){throw startsWithFrontmatterFence(t)&&!hasClosedFrontmatterFence(t)?Error(`Markdown frontmatter is missing a closing delimiter.`):e}if(!isObject(n.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:n.data,markdown:normalizeFrontmatterMarkdownBody(n.content)}}function lowerInstructionsMarkdown(e){return normalizeInstructionsDefinition({markdown:e},`Expected authored instructions markdown to match the public eve shape.`)}function lowerScheduleMarkdown(e){let t=parseMarkdownDocument(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');return defineSchedule(normalizeScheduleDefinition({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public eve shape.`))}function lowerSkillMarkdown(e,t={}){let n=parseMarkdownDocument(e),i=t.slug;if(i===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let a=stripIgnoredSkillFrontmatterKeys(n.frontmatter),o=toOptionalString(a.description,`description`),s=i===void 0?requireStringFrontmatter(a.description,`description`):o??t.description??deriveFlatSkillDescription(n.markdown,i),c={...a,description:s,markdown:n.markdown};return applyOptionalSkillFrontmatter(c,a),defineSkill(normalizeSkillDefinition(c,`Expected authored skill markdown to match the public eve shape.`))}function startsWithFrontmatterFence(e){return e.startsWith(`---
1
+ import{isObject}from"#shared/guards.js";import{normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{hasFrontmatter,parseFrontmatter}from"#internal/helpers/gray-matter.js";import{defineSchedule}from"#public/definitions/schedule.js";import{defineSkill}from"#public/definitions/skill.js";const CLOSED_FRONTMATTER_PATTERN=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function parseMarkdownDocument(t){if(!hasFrontmatter(t))return{hasFrontmatter:!1,frontmatter:{},markdown:t};let n;try{n=parseFrontmatter(t)}catch(e){throw startsWithFrontmatterFence(t)&&!hasClosedFrontmatterFence(t)?Error(`Markdown frontmatter is missing a closing delimiter.`):e}if(!isObject(n.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:n.data,markdown:normalizeFrontmatterMarkdownBody(n.content)}}function lowerInstructionsMarkdown(e){return normalizeInstructionsDefinition({markdown:e},`Expected authored instructions markdown to match the public eve shape.`)}function lowerScheduleMarkdown(e){let t=parseMarkdownDocument(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');return defineSchedule(normalizeScheduleDefinition({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public eve shape.`))}function lowerSkillMarkdown(e,t={}){let n=parseMarkdownDocument(e),i=t.slug;if(i===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let a=stripIgnoredSkillFrontmatterKeys(n.frontmatter),o=toOptionalString(a.description,`description`),s=i===void 0?requireStringFrontmatter(a.description,`description`):o??t.description??deriveFlatSkillDescription(n.markdown,i),c={...a,description:s,markdown:n.markdown};return applyOptionalSkillFrontmatter(c,a),defineSkill(normalizeSkillDefinition(c,`Expected authored skill markdown to match the public eve shape.`))}function startsWithFrontmatterFence(e){return e.startsWith(`---
2
2
  `)||e.startsWith(`---\r
3
3
  `)}function hasClosedFrontmatterFence(e){return CLOSED_FRONTMATTER_PATTERN.test(e)}function normalizeFrontmatterMarkdownBody(e){return e.replace(/^\r?\n/u,``)}function applyOptionalSkillFrontmatter(e,t){let n=toOptionalString(t.license,`license`);n!==void 0&&(e.license=n);let r=toOptionalStringRecord(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const IGNORED_SKILL_FRONTMATTER_KEYS=[`name`];function stripIgnoredSkillFrontmatterKeys(e){let t={...e};for(let e of IGNORED_SKILL_FRONTMATTER_KEYS)delete t[e];return t}function toOptionalString(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function requireStringFrontmatter(e,t){let n=toOptionalString(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function toOptionalStringRecord(t,n){if(t==null)return;if(!isObject(t))throw Error(`Expected "${n}" frontmatter to be an object.`);let r=Object.entries(t).map(([e,t])=>{if(typeof t!=`string`)throw Error(`Expected "${n}.${e}" frontmatter to be a string.`);return[e,t]});return Object.fromEntries(r)}function deriveFlatSkillDescription(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}export{lowerInstructionsMarkdown,lowerScheduleMarkdown,lowerSkillMarkdown};
@@ -1 +1 @@
1
- import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
1
+ import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,n){let i=relative(e.sourceRoot,n);return i.length===0?!1:i.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(n,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:n})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
@@ -1 +1 @@
1
- import{resolvePackageRoot}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroSurfaceOutputDirectory}from"#internal/application/paths.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config)||!isRecord(e.config.experimentalServices))return;let t=!1,n;for(let r of Object.values(e.config.experimentalServices)){if(!isRecord(r))continue;if(r.framework!==`eve`){t=!0;continue}let i=normalizeEntrypoint(e.configRoot,r.entrypoint),a=normalizeServicePrefix(r);i===e.appRoot&&a.length>0&&a!==`/`&&(n=a)}return t?n:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e){let r=await findClosestVercelOutputDirectory(e);if(r!==void 0)try{let t=resolveCoDeployedEveServicePrefix({appRoot:e,configRoot:e,config:JSON.parse(await readFile(join(r,`config.json`),`utf8`))});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let a=e;for(;;){for(let t of[join(a,`vercel.json`),join(a,`.vercel`,`output`,`config.json`)])try{let n=JSON.parse(await readFile(t,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoot:e,configRoot:t.endsWith(`vercel.json`)?a:e,config:n});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let r=dirname(a);if(r===a)return;a=r}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t){let n=await createApplicationNitro(e,!1,{outputDir:resolveNitroSurfaceOutputDirectory(e.appRoot,t),surface:t});try{return await buildNitroOutput(n)}finally{await n.close()}}async function buildApplication(e){let t=await prepareApplicationHost(e);if(!process.env.VERCEL){let e=await createApplicationNitro(t,!1);try{let n=await buildNitroOutput(e);return await emitVercelAgentSummary({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(t.appRoot),r=await createApplicationNitro(t,!1,{surface:`app`});try{let e=await buildNitroOutput(r);await runVercelBuildPrewarm({appRoot:t.appRoot,log(e){console.log(e)}});let i=await buildVercelNitroSurface(t,`flow`);return await emitVercelWorkflowFunctions({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:i,outputDir:e,workflowBuildDir:t.workflowBuildDir}),n!==void 0&&await normalizeEveVercelFunctionOutput(e,{servicePrefix:n}),await emitVercelAgentSummary({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await r.close()}}export{buildApplication};
1
+ import{resolvePackageRoot}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroSurfaceOutputDirectory}from"#internal/application/paths.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{buildExtensionPackage,tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,a){let o=Array.from(new Set([resolve(e),resolve(a)])),s=await findClosestVercelOutputDirectory(e);if(s!==void 0)try{let e=JSON.parse(await readFile(join(s,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:o,configRoot:await resolveVercelOutputConfigRoot(s),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=e;for(;;){for(let e of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let n=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:o,configRoot:e.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(e)),config:n});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(c);if(e===c)return;c=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let a=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(a,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(a,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return a}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t){let n=await createApplicationNitro(e,!1,{outputDir:resolveNitroSurfaceOutputDirectory(e.appRoot,t),surface:t});try{return await buildNitroOutput(n)}finally{await n.close()}}async function buildApplication(e){let t=await tryReadExtensionBuildConfig(e);if(t!==null)return buildExtensionPackage(e,t);let n=await prepareApplicationHost(e);if(!process.env.VERCEL){let e=await createApplicationNitro(n,!1);try{let t=await buildNitroOutput(e);return await emitVercelAgentSummary({manifest:n.compileResult.manifest,appRoot:n.appRoot}),t}finally{await e.close()}}let r=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(n.appRoot,n.compileResult.project.agentRoot),i=await createApplicationNitro(n,!1,{surface:`app`});try{let e=await buildNitroOutput(i);await runVercelBuildPrewarm({appRoot:n.appRoot,log(e){console.log(e)}});let t=await buildVercelNitroSurface(n,`flow`);return await emitVercelWorkflowFunctions({agentName:n.compileResult.manifest.config.name,appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,flowNitroOutputDir:t,outputDir:e,workflowBuildDir:n.workflowBuildDir}),r!==void 0&&await normalizeEveVercelFunctionOutput(e,{servicePrefix:r}),await emitVercelAgentSummary({manifest:n.compileResult.manifest,appRoot:n.appRoot}),e}finally{await i.close()}}export{buildApplication};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Resolved build inputs for an extension package (a `package.json` declaring
3
+ * `eve.extension`).
4
+ */
5
+ export interface ExtensionBuildConfig {
6
+ /** Absolute path to the agent-shaped source root (`eve.extension`). */
7
+ readonly sourceRoot: string;
8
+ /** Package name from `package.json`. */
9
+ readonly packageName: string;
10
+ /** Short name a consumer mounts by (`@acme/crm` → `crm`). */
11
+ readonly shortName: string;
12
+ }
13
+ /**
14
+ * Reads `package.json#eve.extension` from a project root, returning the
15
+ * extension build inputs or `null` when the package is a regular agent app.
16
+ */
17
+ export declare function tryReadExtensionBuildConfig(rootDir: string): Promise<ExtensionBuildConfig | null>;
18
+ /**
19
+ * Builds an extension package: emits `dist/index.mjs` (the mount factory) and
20
+ * `dist/tools/index.mjs` (named tool re-exports for consumer overrides), and
21
+ * fills the package `exports` map. Re-exports point at the authored source so the
22
+ * consumer's compiled tools and the mount share one handle instance.
23
+ */
24
+ export declare function buildExtensionPackage(rootDir: string, config: ExtensionBuildConfig): Promise<string>;
@@ -0,0 +1,4 @@
1
+ import{join,relative,resolve}from"node:path";import{discoverAgent}from"#discover/discover-agent.js";import{mkdir,readFile,writeFile}from"node:fs/promises";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{bundleAuthoredModuleCode}from"#internal/authored-module-loader.js";import{packageStateNamespace}from"#discover/extensions.js";import{discoverFlatModuleSource,readSortedDirectoryEntries}from"#discover/grammar.js";async function tryReadExtensionBuildConfig(t){let r=resolve(t),i;try{i=JSON.parse(await readFile(join(r,`package.json`),`utf8`))}catch{return null}let o=i.eve?.extension;if(typeof o!=`string`||o.length===0)return null;let s=typeof i.name==`string`&&i.name.length>0?i.name:`extension`,c=safeJsIdentifier(s.slice(s.lastIndexOf(`/`)+1));return{sourceRoot:resolve(r,o),packageName:s,shortName:c}}const MANAGED_EXTENSION_EXPORTS={".":{types:`./dist/index.d.ts`,default:`./dist/index.mjs`},"./tools":{types:`./dist/tools/index.d.ts`,default:`./dist/tools/index.mjs`}};async function ensureExtensionExports(t){let n=join(t,`package.json`),r=await readFile(n,`utf8`),i=JSON.parse(r),s=typeof i.exports==`object`&&i.exports!==null&&!Array.isArray(i.exports)?i.exports:{},c=!1;for(let[e,t]of Object.entries(MANAGED_EXTENSION_EXPORTS)){let n=s[e];typeof n==`object`&&n&&n.types===t.types&&n.default===t.default||(s[e]=t,c=!0)}c&&(i.exports=s,await writeFile(n,`${JSON.stringify(i,null,2)}\n`,`utf8`))}async function buildExtensionPackage(a,o){let s=resolve(a),l=createDiskProjectSource(),{diagnostics:u,manifest:d}=await discoverAgent({agentRoot:o.sourceRoot,appRoot:s,source:l,role:`extension`}),f=u.filter(e=>e.severity===`error`);if(f.length>0)throw Error(`Cannot build extension "${o.packageName}":\n${f.map(e=>` - ${e.message}`).join(`
2
+ `)}`);let p=discoverFlatModuleSource({rootEntries:await readSortedDirectoryEntries(l,o.sourceRoot),rootPath:o.sourceRoot,slotName:`extension`}).module;if(p===void 0)throw Error(`Cannot build extension "${o.packageName}": its source root "${o.sourceRoot}" is missing an "extension.<ext>" declaration. Add \`export default defineExtension(...)\` there (with or without config).`);let m=join(s,`dist`);await mkdir(join(m,`tools`),{recursive:!0});let h=packageStateNamespace(o.packageName),specifierFrom=(n,r)=>{let i=relative(n,join(o.sourceRoot,r)).replaceAll(`\\`,`/`);return i.startsWith(`.`)?i:`./${i}`},g=specifierFrom(m,p.logicalPath);return await emitEntrypoint({entryPath:join(m,`index.mjs`),typesPath:join(m,`index.d.ts`),reexports:[{name:`default`,specifier:g},{name:o.shortName,specifier:g}],scopeNamespace:h}),await emitEntrypoint({entryPath:join(m,`tools`,`index.mjs`),typesPath:join(m,`tools`,`index.d.ts`),reexports:d.tools.map(t=>({name:toolExportName(t.logicalPath),specifier:specifierFrom(join(m,`tools`),t.logicalPath)})),scopeNamespace:h}),await ensureExtensionExports(s),m}async function emitEntrypoint(e){let t=`// Generated by eve. Do not edit by hand.`,line=(e,t)=>e.name==="default"?`export { default } from ${JSON.stringify(t)};`:`export { default as ${e.name} } from ${JSON.stringify(t)};`,n=[t,``,...e.reexports.map(e=>line(e,e.specifier)),``].join(`
3
+ `);await writeFile(e.entryPath,n,`utf8`),await writeFile(e.entryPath,await bundleAuthoredModuleCode(e.entryPath,{extensionScopeNamespace:e.scopeNamespace}),`utf8`);let r=[t,``,...e.reexports.map(e=>line(e,toDeclarationSpecifier(e.specifier))),``].join(`
4
+ `);await writeFile(e.typesPath,r,`utf8`)}function toDeclarationSpecifier(e){return e.replace(/\.mts$/,`.mjs`).replace(/\.cts$/,`.cjs`).replace(/\.tsx?$/,`.js`)}function toolExportName(e){let t=e;for(let e of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(t.endsWith(e)){t=t.slice(0,t.length-e.length);break}return safeJsIdentifier(t.replace(/^tools\//,``))}function safeJsIdentifier(e){let t=e.replace(/[^A-Za-z0-9_$]/g,`_`);return/^[A-Za-z_$]/.test(t)?t:`_${t}`}export{buildExtensionPackage,tryReadExtensionBuildConfig};