The Open Framework for Building Agents
feat(eve): hot reload workspace extensions (#911)
Casey Gowrie29ecffcdc5ac
diff --git a/.changeset/calm-extensions-reload.md b/.changeset/calm-extensions-reload.mdnew file mode 100644index 000000000..51d546d73--- /dev/null+++ b/.changeset/calm-extensions-reload.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Build mounted source-backed workspace extensions before `eve dev` compiles the agent, then rebuild only the affected extension when its source changes. Failed extension builds keep the previous dist and active development generation serving.diff --git a/docs/extensions.md b/docs/extensions.mdindex 2ba509d2f..04c067a57 100644--- a/docs/extensions.md+++ b/docs/extensions.md@@ -112,6 +112,10 @@ The build uses the package `tsconfig.json` when it emits declarations. Its `inclThe manifest contains only its format, the diagnostic eve build version, and the versions of extension capabilities this package actually uses. It does not contain compiled tools, schemas, names, or executable definitions; the consuming eve still discovers and normalizes the agent-shaped dist tree.+### Workspace development++During local development, `eve dev` automatically rebuilds mounted workspace extensions when their source changes.+### Dependencies`eve` is a required wildcard **peer** dependency: one eve lives in the consuming app and the extension's `eve/*` imports resolve to it. The extension's concrete eve version belongs in `devDependencies` for authoring types and build tooling. npm peer semver does not decide extension compatibility; eve validates the generated per-capability requirements. Do not mark the eve peer optional and do not add eve to regular `dependencies`.diff --git a/packages/eve/src/discover/discover-agent.ts b/packages/eve/src/discover/discover-agent.tsindex b0b075579..e494dca91 100644--- a/packages/eve/src/discover/discover-agent.ts+++ b/packages/eve/src/discover/discover-agent.ts@@ -373,7 +373,7 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discover* file form (`extensions/crm.ts`) or the directory form* (`extensions/crm/extension.ts` with optional override slots).*/-interface ExtensionMountDescriptor {+export interface ExtensionMountDescriptor {/** Mount namespace prefixed onto every composed contribution. */readonly namespace: string;/** Module ref for the mount declaration the package specifier is read from. */@@ -386,6 +386,43 @@ interface ExtensionMountDescriptor {readonly overridesRoot?: string;}+/**+ * Discovers extension mount declarations without resolving or inspecting their+ * package distributions. Development uses this before building local mounts.+ */+export async function discoverExtensionMountDeclarations(input: {+ readonly agentRoot: string;+ readonly source?: ProjectSource;+}): Promise<{+ diagnostics: DiscoverDiagnostic[];+ mounts: ExtensionMountDescriptor[];+}> {+ const source = input.source ?? createDiskProjectSource();+ const agentRoot = resolve(input.agentRoot);+ const rootEntries = await readSortedDirectoryEntries(source, agentRoot);+ const extensionsResult = await discoverNamedSourceDirectory({+ directoryName: "extensions",+ invalidDirectoryCode: DISCOVER_EXTENSIONS_DIRECTORY_INVALID,+ invalidDirectoryMessage: `Expected "${join(agentRoot, "extensions")}" to be a directory of extension mounts.`,+ recursive: false,+ rootEntries,+ rootPath: agentRoot,+ source,+ validateSegment: createExtensionNameDiagnostic,+ });+ const collection = await collectExtensionMounts({+ agentRoot,+ fileMounts: extensionsResult.sources,+ rootEntries,+ source,+ });++ return {+ diagnostics: [...extensionsResult.diagnostics, ...collection.diagnostics],+ mounts: collection.mounts,+ };+}+/*** Collects extension mounts in both the flat file form and the directory form,* validating directory names and rejecting a namespace claimed by both forms.diff --git a/packages/eve/src/discover/extensions.test.ts b/packages/eve/src/discover/extensions.test.tsindex 69a321178..03936a04f 100644--- a/packages/eve/src/discover/extensions.test.ts+++ b/packages/eve/src/discover/extensions.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from "vitest";-import { mountNamespace, packageStateNamespace } from "#discover/extensions.js";+import {+ locateExtensionMountPackage,+ mountNamespace,+ packageStateNamespace,+} from "#discover/extensions.js";+import { createModuleSourceRef } from "#discover/manifest.js";+import { createMemoryProjectSource } from "#discover/project-source.js";describe("mountNamespace", () => {it("derives the namespace from the mount filename", () => {@@ -26,3 +32,37 @@ describe("packageStateNamespace", () => {expect(packageStateNamespace("@")).toBe("extension");});});++describe("locateExtensionMountPackage", () => {+ it("resolves source and dist roots before the distribution exists", async () => {+ const appRoot = "/repo/apps/agent";+ const agentRoot = `${appRoot}/agent`;+ const packageRoot = `${appRoot}/node_modules/@acme/crm`;+ const source = createMemoryProjectSource({+ files: {+ [`${agentRoot}/extensions/crm.ts`]: 'export { default } from "@acme/crm";\n',+ [`${packageRoot}/package.json`]: JSON.stringify({+ name: "@acme/crm",+ eve: { extension: { source: "extension", dist: "dist/extension" } },+ }),+ },+ });++ const result = await locateExtensionMountPackage({+ source,+ agentRoot,+ appRoot,+ mount: createModuleSourceRef({ logicalPath: "extensions/crm.ts" }),+ namespace: "crm",+ });++ expect(result.diagnostics).toEqual([]);+ expect(result.location).toMatchObject({+ authoredSourceRoot: `${packageRoot}/extension`,+ distRoot: `${packageRoot}/dist/extension`,+ packageName: "@acme/crm",+ packageRoot,+ specifier: "@acme/crm",+ });+ });+});diff --git a/packages/eve/src/discover/extensions.ts b/packages/eve/src/discover/extensions.tsindex fc4d40715..97cda4dc2 100644--- a/packages/eve/src/discover/extensions.ts+++ b/packages/eve/src/discover/extensions.ts@@ -100,6 +100,26 @@ export interface ExtensionMountLocation {readonly sourceRoot: string;}+/**+ * Package roots resolved from one extension mount before its distribution is+ * inspected. Development uses this to build a mounted workspace extension+ * before the consumer requires its dist tree to exist.+ */+export interface ExtensionMountPackageLocation {+ /** Mount namespace derived from the mount filename. */+ readonly namespace: string;+ /** Package specifier read from the mount declaration. */+ readonly specifier: string;+ /** Package name from the resolved package manifest. */+ readonly packageName: string;+ /** Absolute path to the resolved package root. */+ readonly packageRoot: string;+ /** Absolute authoring root when the package publishes a source-backed contract. */+ readonly authoredSourceRoot?: string;+ /** Absolute path to the agent-shaped distribution root. */+ readonly distRoot: string;+}+/*** Derives the mount namespace from an `extensions/<name>.<ext>` logical path.*/@@ -159,6 +179,70 @@ export async function locateExtensionMount(input: {*/readonly namespace: string;}): Promise<{ location?: ExtensionMountLocation; diagnostics: DiscoverDiagnostic[] }> {+ const locatedPackage = await locateExtensionMountPackage(input);+ if (locatedPackage.location === undefined) {+ return { diagnostics: locatedPackage.diagnostics };+ }++ const { location } = locatedPackage;+ const compatibilityPath = join(location.distRoot, EXTENSION_COMPATIBILITY_MANIFEST_FILENAME);+ let compatibility;+ try {+ compatibility = parseExtensionCompatibilityManifest(+ await input.source.readTextFile(compatibilityPath),+ compatibilityPath,+ );+ } catch (error) {+ return {+ diagnostics: [+ createDiscoverErrorDiagnostic({+ code: DISCOVER_EXTENSION_COMPATIBILITY_INVALID,+ message: `Extension "${location.packageName}" has no valid compatibility manifest at "${compatibilityPath}". Rebuild or reinstall the extension. ${error instanceof Error ? error.message : String(error)}`,+ sourcePath: compatibilityPath,+ }),+ ],+ };+ }++ const unsupportedCapabilities = findUnsupportedExtensionCapabilities(compatibility);+ if (unsupportedCapabilities.length > 0) {+ return {+ diagnostics: unsupportedCapabilities.map((unsupported) =>+ createDiscoverErrorDiagnostic({+ code: DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE,+ message: `Extension "${location.packageName}" requires ${unsupported.capability} contract v${unsupported.requiredVersion}, but this eve supports ${unsupported.capability} contract ${formatSupportedVersions(unsupported.supportedVersions)}. Upgrade eve or install an extension release that requires a supported ${unsupported.capability} contract.`,+ sourcePath: compatibilityPath,+ }),+ ),+ };+ }++ return {+ location: {+ namespace: location.namespace,+ specifier: location.specifier,+ packageName: location.packageName,+ packageRoot: location.packageRoot,+ sourceRoot: location.distRoot,+ },+ diagnostics: [],+ };+}++/**+ * Resolves one extension mount through its package manifest without requiring+ * a built distribution or compatibility manifest.+ */+export async function locateExtensionMountPackage(input: {+ readonly source: ProjectSource;+ readonly agentRoot: string;+ readonly appRoot: string;+ readonly mount: ExtensionSourceRef;+ readonly namespace: string;+}): Promise<{+ location?: ExtensionMountPackageLocation;+ diagnostics: DiscoverDiagnostic[];+}> {const mountPath = join(input.agentRoot, input.mount.logicalPath);const { namespace } = input;@@ -240,38 +324,6 @@ export async function locateExtensionMount(input: {}const packageName = typeof pkg.name === "string" && pkg.name.length > 0 ? pkg.name : specifier;- const sourceRoot = resolve(packageRoot, extension.dist);- const compatibilityPath = join(sourceRoot, EXTENSION_COMPATIBILITY_MANIFEST_FILENAME);- let compatibility;- try {- compatibility = parseExtensionCompatibilityManifest(- await input.source.readTextFile(compatibilityPath),- compatibilityPath,- );- } catch (error) {- return {- diagnostics: [- createDiscoverErrorDiagnostic({- code: DISCOVER_EXTENSION_COMPATIBILITY_INVALID,- message: `Extension "${packageName}" has no valid compatibility manifest at "${compatibilityPath}". Rebuild or reinstall the extension. ${error instanceof Error ? error.message : String(error)}`,- sourcePath: compatibilityPath,- }),- ],- };- }-- const unsupportedCapabilities = findUnsupportedExtensionCapabilities(compatibility);- if (unsupportedCapabilities.length > 0) {- return {- diagnostics: unsupportedCapabilities.map((unsupported) =>- createDiscoverErrorDiagnostic({- code: DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE,- message: `Extension "${packageName}" requires ${unsupported.capability} contract v${unsupported.requiredVersion}, but this eve supports ${unsupported.capability} contract ${formatSupportedVersions(unsupported.supportedVersions)}. Upgrade eve or install an extension release that requires a supported ${unsupported.capability} contract.`,- sourcePath: compatibilityPath,- }),- ),- };- }return {location: {@@ -279,7 +331,10 @@ export async function locateExtensionMount(input: {specifier,packageName,packageRoot,- sourceRoot,+ ...(extension.source === undefined+ ? {}+ : { authoredSourceRoot: resolve(packageRoot, extension.source) }),+ distRoot: resolve(packageRoot, extension.dist),},diagnostics: [],};diff --git a/packages/eve/src/internal/nitro/dev-runtime-source-snapshot.ts b/packages/eve/src/internal/nitro/dev-runtime-source-snapshot.tsindex 7a9b4194e..c3b46b890 100644--- a/packages/eve/src/internal/nitro/dev-runtime-source-snapshot.ts+++ b/packages/eve/src/internal/nitro/dev-runtime-source-snapshot.ts@@ -166,7 +166,8 @@ export function toDevelopmentSourceSnapshotPath(input: {return toSnapshotPath(input);}-function resolveDevelopmentSourceRoot(appRoot: string): string {+/** Resolves the repository/workspace boundary used for authored development sources. */+export function resolveDevelopmentSourceRoot(appRoot: string): string {let currentDirectory = resolve(appRoot);while (true) {@@ -597,7 +598,8 @@ function isPathInsideOrEqual(path: string, directory: string): boolean {);}-function isAuthoredSourcePath(path: string, sourceRoot: string): boolean {+/** Returns whether a path is authored workspace source rather than installed dependency data. */+export function isAuthoredSourcePath(path: string, sourceRoot: string): boolean {if (!isPathInsideOrEqual(path, sourceRoot)) {return false;}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.tsindex 6316486a0..3e16e0cab 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts@@ -154,6 +154,7 @@ function createPreparedHost(): PreparedDevelopmentApplicationHost {sourceRoot: appRoot,},workflowBuildDir: `${appRoot}/.eve/dev-hosts/test/workflow`,+ workspaceExtensions: [],workspace: {artifactsDir: `${appRoot}/.eve/dev-hosts/test/artifacts`,compilerArtifactsDir: `${appRoot}/.eve/dev-hosts/test/compiler`,diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.tsindex c8a6022ec..488d2e888 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts@@ -91,6 +91,7 @@ function createHost(scheduleRegistrations: [],schedules: [],workflowBuildDir: `/tmp/eve-test/.eve/dev-hosts/${id}/workflow`,+ workspaceExtensions: [],workspace: {artifactsDir: `/tmp/eve-test/.eve/dev-hosts/${id}/artifacts`,compilerArtifactsDir: `/tmp/eve-test/.eve/dev-hosts/${id}/compiler`,@@ -144,6 +145,36 @@ beforeEach(() => {});describe("transactional authored rebuild coordinator", () => {+ it("passes changed paths into extension preparation and retains its committed watch plan", async () => {+ const { coordinator, devServer } = await createCoordinatorWithServer();+ const candidate = createHost("candidate", "run-1");+ const extension = {+ packageRoot: "/tmp/eve-test/packages/crm",+ buildConfigPaths: ["/tmp/eve-test/packages/crm/tsconfig.json"],+ config: {+ sourceRoot: "/tmp/eve-test/packages/crm/extension",+ distRoot: "/tmp/eve-test/packages/crm/dist/extension",+ outDir: "/tmp/eve-test/packages/crm/dist",+ packageName: "@acme/crm",+ runtimeDependencies: ["eve"],+ shortName: "crm",+ },+ } as const;+ candidate.workspaceExtensions = [extension];+ mocks.prepareDevelopmentApplicationHost.mockResolvedValueOnce(candidate);+ const changedPaths = ["/tmp/eve-test/packages/crm/extension/tools/search.ts"];++ const result = await coordinator.rebuild({ changedPaths });++ expect(mocks.prepareDevelopmentApplicationHost).toHaveBeenCalledWith("/tmp/eve-test", {+ changedPaths,+ previousExtensions: [],+ });+ expect(result.kind).toBe("unchanged");+ expect(result.host.workspaceExtensions).toEqual([extension]);+ await devServer.close();+ });+it("keeps the live worker when activation fails after the swap and retries on the next rebuild", async () => {const { coordinator, devServer } = await createCoordinatorWithServer();const structuralHost = createHost("structural", "run-2");diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.tsindex bfdfcfb4f..9bd34e070 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts@@ -113,7 +113,10 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAlet nextHost: PreparedDevelopmentApplicationHost | undefined;try {- nextHost = await prepareDevelopmentApplicationHost(previousHost.appRoot);+ nextHost = await prepareDevelopmentApplicationHost(previousHost.appRoot, {+ changedPaths: input.changedPaths,+ previousExtensions: previousHost.workspaceExtensions,+ });if (usesParentDevelopmentWorkflowWorld(nextHost.compileResult.manifest.config.experimental?.workflow?.world,@@ -127,10 +130,19 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAconst hasRuntimeChange = nextRuntimeFingerprint !== this.#currentRuntimeFingerprint;if (!hasStructuralChange && !hasRuntimeChange) {+ const committedHost = {+ ...previousHost,+ workspaceExtensions: nextHost.workspaceExtensions,+ };await discardPreparedHost(nextHost);nextHost = undefined;+ this.#commitState(+ committedHost,+ this.#currentHostFingerprint,+ this.#currentRuntimeFingerprint,+ );environmentReload.commit();- return { host: previousHost, kind: "unchanged" };+ return { host: committedHost, kind: "unchanged" };}if (!hasStructuralChange) {diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.tsindex f4ab5ee3b..cb3fc5889 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts@@ -249,6 +249,52 @@ describe("startAuthoredSourceWatcher", () => {}});+ it("watches workspace extension build inputs and ignores its managed output", async () => {+ const appRoot = await mkdtemp(join(tmpdir(), "eve-dev-watch-extension-"));+ const packageRoot = join(appRoot, "packages", "crm");+ const sourceRoot = join(packageRoot, "extension");+ const outDir = join(packageRoot, "artifacts");+ const tsconfigPath = join(packageRoot, "tsconfig.json");+ temporaryDirectories.push(appRoot);+ await mkdir(join(appRoot, "agent"), { recursive: true });+ await mkdir(sourceRoot, { recursive: true });+ await writeFile(join(appRoot, "package.json"), '{"name":"watch-agent","type":"module"}\n');+ await writeFile(join(appRoot, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");+ await writeFile(tsconfigPath, "{}\n");+ const host: PreparedDevelopmentApplicationHost = {+ ...createPreparedHost(appRoot),+ workspaceExtensions: [+ {+ packageRoot,+ buildConfigPaths: [join(packageRoot, "package.json"), tsconfigPath],+ config: {+ sourceRoot,+ distRoot: join(outDir, "extension"),+ outDir,+ packageName: "@acme/crm",+ runtimeDependencies: ["eve"],+ shortName: "crm",+ },+ },+ ],+ };+ const watcher = await startAuthoredSourceWatcher({+ coordinator: createCoordinator(host),+ preparedHost: host,+ });++ try {+ const paths = getInitialWatchPaths();+ expect(paths).toContain(sourceRoot);+ expect(paths).toContain(tsconfigPath);+ const ignored = getIgnoredPredicate();+ expect(ignored(join(outDir, "extension", "tools", "search.mjs"))).toBe(true);+ expect(ignored(join(sourceRoot, "tools", "search.ts"))).toBe(false);+ } finally {+ await watcher.close();+ }+ });+it("does not watch ancestor lockfiles for an app without a workspace marker", async () => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-dev-watch-standalone-"));const appRoot = join(tempRoot, "standalone-agent");@@ -337,6 +383,7 @@ function createPreparedHost(scheduleRegistrations: [],schedules: [],workflowBuildDir: join(appRoot, ".eve", "dev-hosts", "test", "workflow"),+ workspaceExtensions: [],workspace: {artifactsDir: join(appRoot, ".eve", "dev-hosts", "test", "artifacts"),compilerArtifactsDir: join(appRoot, ".eve", "dev-hosts", "test", "compiler"),diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.tsindex ff7075d35..f89032c61 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts@@ -5,6 +5,7 @@ import { toErrorMessage } from "#shared/errors.js";import { resolveTsConfigDependencyPaths } from "#internal/application/tsconfig-dependencies.js";import { resolveDevelopmentSourceSnapshotWatchPaths } from "#internal/nitro/dev-runtime-source-snapshot.js";import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";+import type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";import type { DevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";import { getDevelopmentEnvironmentFilePaths } from "#cli/dev/environment.js";import {@@ -71,7 +72,7 @@ export async function startAuthoredSourceWatcher(input: {},followSymlinks: false,ignoreInitial: true,- ignored: shouldIgnoreWatcherPath,+ ignored: (path) => shouldIgnoreWatcherPath(path, currentHost.workspaceExtensions),});const watcherReady = waitForWatcherReady(watcher);@@ -201,6 +202,13 @@ async function resolveAuthoredWatchPaths(const tsconfigPaths = await resolveTsConfigWatchPaths(host.appRoot);const sourceSnapshotWatchPaths = await resolveDevelopmentSourceSnapshotWatchPaths(host.appRoot);+ for (const extension of host.workspaceExtensions) {+ watchPaths.add(extension.config.sourceRoot);+ for (const path of extension.buildConfigPaths) {+ watchPaths.add(path);+ }+ }+for (const envFilePath of getDevelopmentEnvironmentFilePaths(host.appRoot)) {watchPaths.add(envFilePath);}@@ -300,8 +308,22 @@ async function resolveTsConfigWatchPaths(appRoot: string): Promise<string[]> {return await resolveTsConfigDependencyPaths(appRoot);}-function shouldIgnoreWatcherPath(path: string): boolean {+function shouldIgnoreWatcherPath(+ path: string,+ workspaceExtensions: readonly DevelopmentWorkspaceExtension[],+): boolean {const pathParts = normalize(path).split(sep).filter(Boolean);- return pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part));+ return (+ pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part)) ||+ workspaceExtensions.some((extension) => isPathInsideOrEqual(path, extension.config.outDir))+ );+}++function isPathInsideOrEqual(path: string, directory: string): boolean {+ const resolvedPath = resolve(path);+ const resolvedDirectory = resolve(directory);+ return (+ resolvedPath === resolvedDirectory || resolvedPath.startsWith(`${resolvedDirectory}${sep}`)+ );}diff --git a/packages/eve/src/internal/nitro/host/dev-workspace-extensions.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-workspace-extensions.integration.test.tsnew file mode 100644index 000000000..e61a59576--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-workspace-extensions.integration.test.ts@@ -0,0 +1,192 @@+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { discoverExtensionMountDeclarations } from "#discover/discover-agent.js";+import { locateExtensionMountPackage } from "#discover/extensions.js";+import { createDiskProjectSource } from "#discover/project-source.js";+import { resolveDiscoveryProject } from "#discover/project.js";+import {+ isAuthoredSourcePath,+ resolveDevelopmentSourceRoot,+} from "#internal/nitro/dev-runtime-source-snapshot.js";+import { tryReadExtensionBuildConfig } from "#internal/nitro/host/build-extension.js";++const mocks = vi.hoisted(() => ({+ buildExtensionPackage: vi.fn(async () => undefined),+}));++vi.mock("#internal/nitro/host/build-extension.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#internal/nitro/host/build-extension.js")>()),+ buildExtensionPackage: mocks.buildExtensionPackage,+}));++import { prepareDevelopmentWorkspaceExtensions } from "#internal/nitro/host/dev-workspace-extensions.js";++const temporaryDirectories: string[] = [];++beforeEach(() => {+ mocks.buildExtensionPackage.mockClear();+});++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map(async (path) => await rm(path, { force: true, recursive: true })),+ );+});++describe("prepareDevelopmentWorkspaceExtensions", () => {+ it("builds initial mounts and only rebuilds the extension affected by a source edit", async () => {+ const appRoot = await createWorkspaceAgent(["alpha", "beta"]);++ const mounts = await discoverExtensionMountDeclarations({+ agentRoot: join(appRoot, "agent"),+ });+ await expect(resolveDiscoveryProject(appRoot)).resolves.toMatchObject({+ agentRoot: join(appRoot, "agent"),+ appRoot,+ });+ expect(mounts.diagnostics).toEqual([]);+ expect(mounts.mounts).toHaveLength(2);+ const located = await locateExtensionMountPackage({+ source: createDiskProjectSource(),+ agentRoot: join(appRoot, "agent"),+ appRoot,+ mount: mounts.mounts[0]!.mountRef,+ namespace: mounts.mounts[0]!.namespace,+ });+ expect(located.diagnostics).toEqual([]);+ expect(located.location?.authoredSourceRoot).toBe(+ join(appRoot, "packages", "alpha", "extension"),+ );+ expect(+ isAuthoredSourcePath(+ join(appRoot, "packages", "alpha"),+ resolveDevelopmentSourceRoot(appRoot),+ ),+ ).toBe(true);+ await expect(+ tryReadExtensionBuildConfig(join(appRoot, "packages", "alpha")),+ ).resolves.not.toBeNull();++ const initial = await prepareDevelopmentWorkspaceExtensions({ appRoot });+ expect(initial).toHaveLength(2);+ expect(mocks.buildExtensionPackage).toHaveBeenCalledTimes(2);++ mocks.buildExtensionPackage.mockClear();+ const alphaSourcePath = join(appRoot, "packages", "alpha", "extension", "tools", "marker.ts");+ const next = await prepareDevelopmentWorkspaceExtensions({+ appRoot,+ changedPaths: [alphaSourcePath],+ previousExtensions: initial,+ });++ expect(next).toHaveLength(2);+ expect(mocks.buildExtensionPackage).toHaveBeenCalledOnce();+ expect(mocks.buildExtensionPackage).toHaveBeenCalledWith(+ join(appRoot, "packages", "alpha"),+ expect.objectContaining({ packageName: "@acme/alpha" }),+ );+ });++ it("does not rebuild an extension for an unrelated workspace dependency edit", async () => {+ const appRoot = await createWorkspaceAgent(["alpha"]);+ const initial = await prepareDevelopmentWorkspaceExtensions({ appRoot });+ mocks.buildExtensionPackage.mockClear();++ await prepareDevelopmentWorkspaceExtensions({+ appRoot,+ changedPaths: [join(appRoot, "packages", "shared", "src", "index.ts")],+ previousExtensions: initial,+ });++ expect(mocks.buildExtensionPackage).not.toHaveBeenCalled();+ });++ it("does not build a source-backed package installed inside node_modules", async () => {+ const appRoot = await createWorkspaceAgent([]);+ const installedRoot = join(appRoot, "node_modules", "@acme", "installed");+ await writeText(+ join(appRoot, "agent", "extensions", "installed.ts"),+ 'export { default } from "@acme/installed";\n',+ );+ await writeText(+ join(installedRoot, "package.json"),+ `${JSON.stringify({+ name: "@acme/installed",+ type: "module",+ eve: { extension: { source: "extension", dist: "dist/extension" } },+ })}\n`,+ );+ await writeText(join(installedRoot, "extension", "extension.ts"), "export default {};\n");++ const extensions = await prepareDevelopmentWorkspaceExtensions({ appRoot });++ expect(extensions).toEqual([]);+ expect(mocks.buildExtensionPackage).not.toHaveBeenCalled();+ });++ it("does not rebuild a workspace package distributed without its authored source", async () => {+ const appRoot = await createWorkspaceAgent(["alpha"]);+ const packageRoot = join(appRoot, "packages", "alpha");+ await writeText(+ join(packageRoot, "dist", "extension", "extension.mjs"),+ "export default {};\n",+ );+ await rm(join(packageRoot, "extension"), { recursive: true });++ const extensions = await prepareDevelopmentWorkspaceExtensions({ appRoot });++ expect(extensions).toEqual([]);+ expect(mocks.buildExtensionPackage).not.toHaveBeenCalled();+ });++ it("rebuilds every mounted workspace extension for a forced reload", async () => {+ const appRoot = await createWorkspaceAgent(["alpha", "beta"]);+ const initial = await prepareDevelopmentWorkspaceExtensions({ appRoot });+ mocks.buildExtensionPackage.mockClear();++ await prepareDevelopmentWorkspaceExtensions({+ appRoot,+ changedPaths: [],+ previousExtensions: initial,+ });++ expect(mocks.buildExtensionPackage).toHaveBeenCalledTimes(2);+ });+});++async function createWorkspaceAgent(extensionNames: readonly string[]): Promise<string> {+ const appRoot = await mkdtemp(join(tmpdir(), "eve-workspace-extension-dev-"));+ temporaryDirectories.push(appRoot);+ await writeText(join(appRoot, "package.json"), '{"name":"workspace-agent","type":"module"}\n');+ await writeText(join(appRoot, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");+ await writeText(join(appRoot, "agent", "instructions.md"), "Test agent.\n");++ for (const name of extensionNames) {+ const packageRoot = join(appRoot, "packages", name);+ await writeText(+ join(appRoot, "agent", "extensions", `${name}.ts`),+ `export { default } from "../../packages/${name}";\n`,+ );+ await writeText(+ join(packageRoot, "package.json"),+ `${JSON.stringify({+ name: `@acme/${name}`,+ type: "module",+ eve: { extension: { source: "extension", dist: "dist/extension" } },+ })}\n`,+ );+ await writeText(join(packageRoot, "extension", "extension.ts"), "export default {};\n");+ }++ return await realpath(appRoot);+}++async function writeText(path: string, contents: string): Promise<void> {+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, contents, "utf8");+}diff --git a/packages/eve/src/internal/nitro/host/dev-workspace-extensions.ts b/packages/eve/src/internal/nitro/host/dev-workspace-extensions.tsnew file mode 100644index 000000000..99f0da538--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-workspace-extensions.ts@@ -0,0 +1,197 @@+import { realpath, stat } from "node:fs/promises";+import { basename, dirname, join, resolve, sep } from "node:path";++import {+ discoverExtensionMountDeclarations,+ type ExtensionMountDescriptor,+} from "#discover/discover-agent.js";+import { locateExtensionMountPackage } from "#discover/extensions.js";+import { createDiskProjectSource } from "#discover/project-source.js";+import { resolveDiscoveryProject } from "#discover/project.js";+import { resolveTsConfigDependencyPaths } from "#internal/application/tsconfig-dependencies.js";+import {+ isAuthoredSourcePath,+ resolveDevelopmentSourceRoot,+} from "#internal/nitro/dev-runtime-source-snapshot.js";+import {+ buildExtensionPackage,+ tryReadExtensionBuildConfig,+ type ExtensionBuildConfig,+} from "#internal/nitro/host/build-extension.js";++/** Build inputs retained with a prepared dev host for path-scoped extension HMR. */+export interface DevelopmentWorkspaceExtension {+ readonly config: ExtensionBuildConfig;+ /** Canonical package root, with workspace links resolved. */+ readonly packageRoot: string;+ /** Non-source inputs that affect publisher output, such as tsconfig files. */+ readonly buildConfigPaths: readonly string[];+}++/**+ * Builds mounted source-backed workspace extensions before the consuming agent+ * compiles and returns the inputs needed to scope the next development rebuild.+ */+export async function prepareDevelopmentWorkspaceExtensions(input: {+ readonly appRoot: string;+ readonly changedPaths?: readonly string[];+ readonly previousExtensions?: readonly DevelopmentWorkspaceExtension[];+}): Promise<readonly DevelopmentWorkspaceExtension[]> {+ const appRoot = resolve(input.appRoot);+ const project = await resolveDiscoveryProject(appRoot);+ const source = createDiskProjectSource();+ const discovered = await discoverExtensionMountDeclarations({+ agentRoot: project.agentRoot,+ source,+ });+ const workspaceSourceRoot = await toCanonicalPath(resolveDevelopmentSourceRoot(appRoot));+ const extensionsByPackageRoot = new Map<string, DevelopmentWorkspaceExtension>();++ for (const mount of discovered.mounts) {+ const extension = await resolveWorkspaceExtension({+ appRoot,+ agentRoot: project.agentRoot,+ mount,+ source,+ workspaceSourceRoot,+ });+ if (extension !== undefined) {+ extensionsByPackageRoot.set(extension.packageRoot, extension);+ }+ }++ const extensions = [...extensionsByPackageRoot.values()].sort((left, right) =>+ left.packageRoot.localeCompare(right.packageRoot),+ );+ const previousByPackageRoot = new Map(+ input.previousExtensions?.map((extension) => [extension.packageRoot, extension]),+ );+ const changedPaths =+ input.changedPaths === undefined+ ? undefined+ : await Promise.all(input.changedPaths.map(async (path) => await toCanonicalPath(path)));+ const force = input.previousExtensions === undefined || changedPaths?.length === 0;++ await Promise.all(+ extensions.map(async (extension) => {+ const previous = previousByPackageRoot.get(extension.packageRoot);+ if (+ force === true ||+ previous === undefined ||+ !sameBuildInputs(previous, extension) ||+ changedPaths?.some((path) => affectsExtensionBuild(path, extension)) === true+ ) {+ await buildExtensionPackage(extension.packageRoot, extension.config);+ }+ }),+ );++ return extensions;+}++async function resolveWorkspaceExtension(input: {+ readonly appRoot: string;+ readonly agentRoot: string;+ readonly mount: ExtensionMountDescriptor;+ readonly source: ReturnType<typeof createDiskProjectSource>;+ readonly workspaceSourceRoot: string;+}): Promise<DevelopmentWorkspaceExtension | undefined> {+ const located = await locateExtensionMountPackage({+ source: input.source,+ agentRoot: input.agentRoot,+ appRoot: input.appRoot,+ mount: input.mount.mountRef,+ namespace: input.mount.namespace,+ });+ if (located.location?.authoredSourceRoot === undefined) {+ return undefined;+ }++ const packageRoot = await realpath(located.location.packageRoot).catch(() => undefined);+ if (packageRoot === undefined || !isAuthoredSourcePath(packageRoot, input.workspaceSourceRoot)) {+ return undefined;+ }++ const config = await tryReadExtensionBuildConfig(packageRoot);+ if (config === null) {+ return undefined;+ }+ const sourceStat = await stat(config.sourceRoot).catch(() => undefined);+ if (sourceStat?.isDirectory() !== true) {+ return undefined;+ }+ const buildConfigPaths = [+ join(packageRoot, "package.json"),+ join(packageRoot, "tsconfig.json"),+ ...(await resolveTsConfigDependencyPaths(packageRoot)),+ ];++ return {+ config,+ packageRoot,+ buildConfigPaths: [...new Set(buildConfigPaths.map((path) => resolve(path)))].sort(+ (left, right) => left.localeCompare(right),+ ),+ };+}++function affectsExtensionBuild(+ changedPath: string,+ extension: DevelopmentWorkspaceExtension,+): boolean {+ return (+ isPathInsideOrEqual(changedPath, extension.config.sourceRoot) ||+ extension.buildConfigPaths.includes(changedPath)+ );+}++function sameBuildConfig(left: ExtensionBuildConfig, right: ExtensionBuildConfig): boolean {+ return (+ left.sourceRoot === right.sourceRoot &&+ left.distRoot === right.distRoot &&+ left.outDir === right.outDir &&+ left.packageName === right.packageName &&+ left.shortName === right.shortName &&+ left.runtimeDependencies.length === right.runtimeDependencies.length &&+ left.runtimeDependencies.every(+ (dependency, index) => dependency === right.runtimeDependencies[index],+ )+ );+}++function sameBuildInputs(+ left: DevelopmentWorkspaceExtension,+ right: DevelopmentWorkspaceExtension,+): boolean {+ return (+ sameBuildConfig(left.config, right.config) &&+ left.buildConfigPaths.length === right.buildConfigPaths.length &&+ left.buildConfigPaths.every((path, index) => path === right.buildConfigPaths[index])+ );+}++function isPathInsideOrEqual(path: string, directory: string): boolean {+ const resolvedPath = resolve(path);+ const resolvedDirectory = resolve(directory);+ return (+ resolvedPath === resolvedDirectory || resolvedPath.startsWith(`${resolvedDirectory}${sep}`)+ );+}++async function toCanonicalPath(path: string): Promise<string> {+ let candidate = resolve(path);+ const missingSegments: string[] = [];++ while (true) {+ try {+ return join(await realpath(candidate), ...missingSegments.reverse());+ } catch {+ const parent = dirname(candidate);+ if (parent === candidate) {+ return resolve(path);+ }+ missingSegments.push(basename(candidate));+ candidate = parent;+ }+ }+}diff --git a/packages/eve/src/internal/nitro/host/prepare-application-host.ts b/packages/eve/src/internal/nitro/host/prepare-application-host.tsindex b1d9d7583..a3f00fb5f 100644--- a/packages/eve/src/internal/nitro/host/prepare-application-host.ts+++ b/packages/eve/src/internal/nitro/host/prepare-application-host.ts@@ -17,6 +17,10 @@ import {createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace,} from "#internal/nitro/host/dev-host-workspace.js";+import {+ prepareDevelopmentWorkspaceExtensions,+ type DevelopmentWorkspaceExtension,+} from "#internal/nitro/host/dev-workspace-extensions.js";import type {PreparedApplicationHost,PreparedDevelopmentApplicationHost,@@ -28,7 +32,23 @@ import type {*/export async function prepareDevelopmentApplicationHost(appRoot: string,+ options: {+ readonly changedPaths?: readonly string[];+ readonly previousExtensions?: readonly DevelopmentWorkspaceExtension[];+ } = {},): Promise<PreparedDevelopmentApplicationHost> {+ const extensionPreparation: {+ appRoot: string;+ changedPaths?: readonly string[];+ previousExtensions?: readonly DevelopmentWorkspaceExtension[];+ } = { appRoot };+ if (options.changedPaths !== undefined) {+ extensionPreparation.changedPaths = options.changedPaths;+ }+ if (options.previousExtensions !== undefined) {+ extensionPreparation.previousExtensions = options.previousExtensions;+ }+ const workspaceExtensions = await prepareDevelopmentWorkspaceExtensions(extensionPreparation);const workspace = await createDevelopmentHostWorkspace(appRoot);let generation: Awaited<ReturnType<typeof stageDevelopmentGeneration>> | undefined;@@ -55,6 +75,7 @@ export async function prepareDevelopmentApplicationHost(workflowBuildDir: workspace.workflowBuildDir,}),generation,+ workspaceExtensions,workspace,};} catch (error) {diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.tsindex a0dee6e2c..ac7e6e83b 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts@@ -89,6 +89,7 @@ const mocks = vi.hoisted(() => {snapshotSourceRoot: "/tmp/eve-test/.eve/dev-runtime/snapshots/test/source",sourceRoot: "/tmp/eve-test",},+ workspaceExtensions: [],workspace: {artifactsDir: "/tmp/eve-test/.eve/dev-hosts/test/artifacts",compilerArtifactsDir: "/tmp/eve-test/.eve/dev-hosts/test/compiler",diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.tsindex 50b57a0d1..53bca66b9 100644--- a/packages/eve/src/internal/nitro/host/types.ts+++ b/packages/eve/src/internal/nitro/host/types.ts@@ -5,6 +5,7 @@ import type { GeneratedCompiledArtifactsFiles } from "#internal/application/compimport type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";import type { DevelopmentGeneration } from "#internal/nitro/development-generation.js";import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";+import type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";/*** Route surface included in one programmatic Nitro host build.@@ -81,5 +82,6 @@ export interface PreparedApplicationHost {export interface PreparedDevelopmentApplicationHost extends PreparedApplicationHost {generation: DevelopmentGeneration;+ workspaceExtensions: readonly DevelopmentWorkspaceExtension[];workspace: DevelopmentHostWorkspace;}diff --git a/packages/eve/test/scenarios/dev-server.scenario.test.ts b/packages/eve/test/scenarios/dev-server.scenario.test.tsindex 47251fe32..1e24266ab 100644--- a/packages/eve/test/scenarios/dev-server.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server.scenario.test.ts@@ -1,6 +1,7 @@import { Agent } from "node:http";import { existsSync } from "node:fs";import { readFile, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";import { join } from "node:path";import { describe, expect, it } from "vitest";@@ -36,6 +37,8 @@ import {process.env.EVE_TUI_UNICODE = "1";const scenarioApp = useScenarioApp();+const require = createRequire(import.meta.url);+const TYPESCRIPT_VERSION = (require("typescript/package.json") as { version: string }).version;const DEV_SERVER_SCENARIO_TIMEOUT_MS = 360_000;const DEV_SERVER_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {...WEATHER_AGENT_DESCRIPTOR,@@ -157,6 +160,67 @@ const WORKFLOW_GENERATION_DESCRIPTOR: ScenarioAppDescriptor = {"agent/tools/get_marker.ts": createGenerationMarkerToolSource("generation-one", true),},};+const WORKSPACE_EXTENSION_HMR_DESCRIPTOR: ScenarioAppDescriptor = {+ dependencies: {+ "@acme/workspace-extension": "workspace:*",+ },+ files: {+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4-mini" };\n',+ "agent/extensions/workspace.mjs": 'export { default } from "@acme/workspace-extension";\n',+ "agent/instructions.md": "Test workspace extension development.\n",+ "packages/workspace-extension/extension/extension.ts": [+ 'import { defineExtension } from "eve/extension";',+ "export default defineExtension();",+ "",+ ].join("\n"),+ "packages/workspace-extension/extension/tools/marker.ts": createWorkspaceExtensionToolSource(+ "workspace extension marker one",+ ),+ "packages/workspace-extension/package.json": `${JSON.stringify(+ {+ name: "@acme/workspace-extension",+ version: "0.0.0",+ type: "module",+ eve: { extension: { source: "extension", dist: "dist/extension" } },+ devDependencies: { typescript: TYPESCRIPT_VERSION },+ peerDependencies: { eve: "*" },+ },+ null,+ 2,+ )}\n`,+ "packages/workspace-extension/tsconfig.json": `${JSON.stringify(+ {+ compilerOptions: {+ module: "esnext",+ moduleResolution: "bundler",+ noEmit: true,+ skipLibCheck: true,+ strict: true,+ target: "ES2022",+ },+ include: ["extension/**/*"],+ },+ null,+ 2,+ )}\n`,+ "pnpm-workspace.yaml": "packages:\n - packages/*\n",+ },+ installDependencies: true,+ name: "workspace-extension-hmr",+};++function createWorkspaceExtensionToolSource(description: string): string {+ return [+ 'import { defineTool } from "eve/tools";',+ "",+ "export default defineTool({",+ ` description: ${JSON.stringify(description)},`,+ ' inputSchema: { type: "object", properties: {}, additionalProperties: false },',+ " async execute() { return { ok: true }; },",+ "});",+ "",+ ].join("\n");+}function createGenerationMarkerToolSource(marker: string, crashOnce: boolean): string {const lifecycle = crashOnce@@ -334,7 +398,87 @@ async function waitForWebSocketEvent<T>(});}+async function workspaceExtensionToolDescription(serverUrl: string): Promise<string | undefined> {+ return (await fetchAgentInfo(serverUrl)).tools.authored.find(+ (tool) => tool.name === "workspace__marker",+ )?.description;+}++async function expectWorkspaceExtensionToolDescription(+ serverUrl: string,+ description: string,+): Promise<void> {+ await expect(workspaceExtensionToolDescription(serverUrl)).resolves.toBe(description);+}+describe("eve dev server", () => {+ it(+ "rebuilds mounted workspace extensions from source and preserves the active dist on failure",+ async () => {+ const app = await scenarioApp(WORKSPACE_EXTENSION_HMR_DESCRIPTOR);+ const sourcePath = join(+ app.appRoot,+ "packages",+ "workspace-extension",+ "extension",+ "tools",+ "marker.ts",+ );+ const distPath = join(+ app.appRoot,+ "packages",+ "workspace-extension",+ "dist",+ "extension",+ "tools",+ "marker.mjs",+ );+ expect(existsSync(distPath)).toBe(false);++ const server = await startEveDev(app.appRoot);++ try {+ expect(existsSync(distPath)).toBe(true);+ await expectWorkspaceExtensionToolDescription(server.url, "workspace extension marker one");+ const initialRevision = await readDevelopmentRevision(server.url);++ await writeFile(+ sourcePath,+ `${createWorkspaceExtensionToolSource("rejected marker")}\nconst invalid: string = 1;\n`,+ );+ await waitForCondition(+ () => `${server.stdout()}\n${server.stderr()}`.includes("rebuild failed"),+ () =>+ `Workspace extension build did not fail.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,+ );++ await expect(readDevelopmentRevision(server.url)).resolves.toBe(initialRevision);+ await expectWorkspaceExtensionToolDescription(server.url, "workspace extension marker one");+ await expect(readFile(distPath, "utf8")).resolves.toContain(+ "workspace extension marker one",+ );++ await writeFile(+ sourcePath,+ createWorkspaceExtensionToolSource("workspace extension marker two"),+ );+ await waitForCondition(+ async () =>+ (await workspaceExtensionToolDescription(server.url)) ===+ "workspace extension marker two",+ () =>+ `Workspace extension edit was not published.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,+ );++ await expect(readDevelopmentRevision(server.url)).resolves.not.toBe(initialRevision);+ expect(hasKnownDevServerFailure(`${server.stdout()}\n${server.stderr()}`)).toBe(false);+ } finally {+ await server.stop();+ }+ },+ DEV_SERVER_SCENARIO_TIMEOUT_MS,+ );+it("publishes authored tool removals without replacing the active host",async () => {