From 941a6b1870307f890dc477e95aec0f53babcefaa Mon Sep 17 00:00:00 2001 From: Gitika <53349492+notgitika@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:43:52 -0500 Subject: [PATCH 1/8] feat(build): add ContainerLocal build mode (re-land #2814) (#2855) Adds a ContainerLocal build type for runtimes and harnesses: images are built locally with Docker, Finch, or Podman and published through CDK. - --build-config (Advanced: group) on add runtime / add harness - agentcore build builds (does not push) ContainerLocal images from the synthesized assembly - deploy rejects switching a deployed workload between Container and ContainerLocal; without CloudFormation read access it warns, or fails when a workload uses ContainerLocal - deploy checks that the detected builder can build Linux ARM64 images and passes it to CDK as CDK_DOCKER - deploy telemetry counts runtimes and harnesses by build type Co-authored-by: gitikavj --- src/core/dev/container.ts | 29 +- src/core/dev/containerTool.test.ts | 47 + src/core/dev/containerTool.ts | 43 + src/core/dev/supervisor.ts | 3 +- src/core/project/backends/cdk.test.ts | 541 +++++- src/core/project/backends/cdk.ts | 195 +- .../AgentCore-Fixture.assets.json | 65 + .../AgentCore-Fixture.template.json | 1690 +++++++++++++++++ .../cdk/__fixtures__/local-images/README.md | 29 + .../__fixtures__/local-images/manifest.json | 511 +++++ .../project/backends/cdk/arm64Builder.test.ts | 337 ++++ src/core/project/backends/cdk/arm64Builder.ts | 236 +++ .../backends/cdk/compatibility.test.ts | 25 +- .../project/backends/cdk/compatibility.ts | 21 + .../backends/cdk/localContainers.test.ts | 268 +++ .../project/backends/cdk/localContainers.ts | 144 ++ .../project/backends/cdk/localImages.test.ts | 133 ++ src/core/project/backends/cdk/localImages.ts | 171 ++ src/core/project/backends/cdk/toolkit.test.ts | 23 + src/core/project/backends/cdk/toolkit.ts | 10 + src/core/project/backends/types.ts | 3 + src/core/project/manager.tsx | 17 +- src/core/project/runtimeBuild.test.ts | 16 + src/core/project/runtimeBuild.ts | 13 +- src/core/project/templates/harness.ts | 43 +- src/core/project/templates/runtime.ts | 5 +- src/core/project/templates/runtimeDocs.ts | 44 +- src/handlers/project/add/buildConfig.ts | 45 + .../project/add/harness/index.test.ts | 113 ++ src/handlers/project/add/harness/index.ts | 15 + .../project/add/runtime/index.test.ts | 150 ++ src/handlers/project/add/runtime/index.ts | 5 +- src/handlers/project/add/runtime/types.ts | 22 + src/handlers/project/deploy/index.test.ts | 92 +- src/handlers/project/deploy/index.ts | 28 +- src/handlers/project/deploy/screen.tsx | 2 + src/handlers/project/dev/index.ts | 7 +- src/handlers/project/shortcuts.ts | 6 +- src/handlers/project/types.ts | 22 +- src/projectSchemas/constants.ts | 7 +- src/projectSchemas/harness.test.ts | 13 +- src/projectSchemas/harness.ts | 51 +- src/projectSchemas/runtime.ts | 9 +- src/telemetry/shapes.tsx | 5 + 44 files changed, 5160 insertions(+), 94 deletions(-) create mode 100644 src/core/dev/containerTool.test.ts create mode 100644 src/core/dev/containerTool.ts create mode 100644 src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.assets.json create mode 100644 src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.template.json create mode 100644 src/core/project/backends/cdk/__fixtures__/local-images/README.md create mode 100644 src/core/project/backends/cdk/__fixtures__/local-images/manifest.json create mode 100644 src/core/project/backends/cdk/arm64Builder.test.ts create mode 100644 src/core/project/backends/cdk/arm64Builder.ts create mode 100644 src/core/project/backends/cdk/localContainers.test.ts create mode 100644 src/core/project/backends/cdk/localContainers.ts create mode 100644 src/core/project/backends/cdk/localImages.test.ts create mode 100644 src/core/project/backends/cdk/localImages.ts create mode 100644 src/handlers/project/add/buildConfig.ts diff --git a/src/core/dev/container.ts b/src/core/dev/container.ts index 8f3d329771..24945edd4b 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -6,16 +6,15 @@ import { join, resolve } from "node:path"; import { InputValidationError, InvalidEnvironmentError, ResourceNotFoundError } from "../../errors"; import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types"; import { - MissingToolError, streamProcess, toolAvailable, type ProcessStreamer, type StreamProcessOptions, } from "../../io"; +import { resolveContainerTool, type ContainerTool, type ToolAvailable } from "./containerTool"; import { isDirectory, isFile, resolvePathWithinProject } from "./path"; import { DEV_PORTS } from "./port"; -const CONTAINER_TOOLS = ["docker", "podman", "finch"] as const; const AWS_ENV_KEYS = [ "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", @@ -26,9 +25,6 @@ const AWS_ENV_KEYS = [ ] as const; const CLEANUP_TIMEOUT_MS = 2_000; const DOCKERFILE_NAME = "Dockerfile"; -const CONTAINER_RUNTIME_INSTALL_HINT = - "Install Docker (https://docs.docker.com/get-docker/), Podman (https://podman.io/), " + - "or Finch (https://runfinch.com/)."; const BUILD_CONTEXT_DOCKERIGNORE = `# Generated by agentcore because buildContextPath widens the Docker build context. .env @@ -50,9 +46,6 @@ __pycache__ agentcore/ `; -type ContainerTool = (typeof CONTAINER_TOOLS)[number]; -type ToolAvailable = typeof toolAvailable; - type ContainerDevRunnerConfig = { streamProcess?: ProcessStreamer; toolAvailable?: ToolAvailable; @@ -103,7 +96,7 @@ export class ContainerDevRunner implements DevRunner { ); } - const tool = await this.resolveContainerTool(input.signal); + const tool = await resolveContainerTool(this.toolAvailable, input.signal); input.signal.throwIfAborted(); if (input.runtime.buildContextPath) { const dockerignore = ensureBuildContextDockerignore(context); @@ -210,24 +203,6 @@ export class ContainerDevRunner implements DevRunner { } } - private async resolveContainerTool(signal: AbortSignal): Promise { - for (const tool of CONTAINER_TOOLS) { - const hasVersion = await this.toolAvailable(tool); - signal.throwIfAborted(); - if (!hasVersion) continue; - - const canBuild = await this.toolAvailable(tool, ["build", "--help"]); - signal.throwIfAborted(); - if (canBuild) return tool; - if (tool === "finch") { - throw new InvalidEnvironmentError( - "Finch is installed but its VM is not initialized. Run 'finch vm init' and retry.", - ); - } - } - throw new MissingToolError("container runtime", CONTAINER_RUNTIME_INSTALL_HINT); - } - private async removeContainer( tool: ContainerTool, containerName: string, diff --git a/src/core/dev/containerTool.test.ts b/src/core/dev/containerTool.test.ts new file mode 100644 index 0000000000..50615145d9 --- /dev/null +++ b/src/core/dev/containerTool.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, test } from "bun:test"; +import { resolveCdkDockerExecutable, resolveContainerTool } from "./containerTool"; + +function available(installed: Record) { + const probes: string[] = []; + const check = async (tool: string, args: string[] = ["--version"]) => { + probes.push(`${tool} ${args.join(" ")}`); + const entry = installed[tool]; + if (!entry) return false; + return args[0] === "build" ? entry.build : true; + }; + return { check, probes }; +} + +describe("resolveContainerTool", () => { + test("prefers docker, then podman, then finch", async () => { + expect(await resolveContainerTool(available({ docker: { build: true } }).check)).toBe("docker"); + expect( + await resolveContainerTool( + available({ podman: { build: true }, finch: { build: true } }).check, + ), + ).toBe("podman"); + expect(await resolveContainerTool(available({ finch: { build: true } }).check)).toBe("finch"); + }); + + test("explains an uninitialized Finch VM and a missing runtime", async () => { + await expect( + resolveContainerTool(available({ finch: { build: false } }).check), + ).rejects.toThrow("finch vm init"); + await expect(resolveContainerTool(available({}).check)).rejects.toThrow("Install Docker"); + }); +}); + +describe("resolveCdkDockerExecutable", () => { + test("honors an explicit CDK_DOCKER without probing", async () => { + const { check, probes } = available({ docker: { build: true } }); + expect(await resolveCdkDockerExecutable({ CDK_DOCKER: "/opt/bin/nerdctl" }, check)).toBe( + "/opt/bin/nerdctl", + ); + expect(probes).toEqual([]); + }); + + test("detects the builder when CDK_DOCKER is unset", async () => { + const { check } = available({ finch: { build: true } }); + expect(await resolveCdkDockerExecutable({}, check)).toBe("finch"); + }); +}); diff --git a/src/core/dev/containerTool.ts b/src/core/dev/containerTool.ts new file mode 100644 index 0000000000..a8d424999e --- /dev/null +++ b/src/core/dev/containerTool.ts @@ -0,0 +1,43 @@ +import { InvalidEnvironmentError } from "../../errors"; +import { MissingToolError, toolAvailable } from "../../io"; + +export const CONTAINER_TOOLS = ["docker", "podman", "finch"] as const; +export type ContainerTool = (typeof CONTAINER_TOOLS)[number]; +export type ToolAvailable = typeof toolAvailable; + +const CONTAINER_RUNTIME_INSTALL_HINT = + "Install Docker (https://docs.docker.com/get-docker/), Podman (https://podman.io/), " + + "or Finch (https://runfinch.com/)."; + +/** Returns the first installed container tool that can build (docker, then podman, then finch). */ +export async function resolveContainerTool( + available: ToolAvailable = toolAvailable, + signal?: AbortSignal, +): Promise { + for (const tool of CONTAINER_TOOLS) { + const hasVersion = await available(tool); + signal?.throwIfAborted(); + if (!hasVersion) continue; + + const canBuild = await available(tool, ["build", "--help"]); + signal?.throwIfAborted(); + if (canBuild) return tool; + if (tool === "finch") { + throw new InvalidEnvironmentError( + "Finch is installed but its VM is not initialized. Run 'finch vm init' and retry.", + ); + } + } + throw new MissingToolError("container runtime", CONTAINER_RUNTIME_INSTALL_HINT); +} + +/** + * The executable CDK uses to build and publish local container images. An explicit + * CDK_DOCKER is honored as-is; otherwise the same detection as `agentcore dev` applies. + */ +export async function resolveCdkDockerExecutable( + env: NodeJS.ProcessEnv = process.env, + available: ToolAvailable = toolAvailable, +): Promise { + return env.CDK_DOCKER || resolveContainerTool(available); +} diff --git a/src/core/dev/supervisor.ts b/src/core/dev/supervisor.ts index 289846468c..eddb58fc85 100644 --- a/src/core/dev/supervisor.ts +++ b/src/core/dev/supervisor.ts @@ -2,6 +2,7 @@ import { ResourceNotFoundError } from "../../errors"; import { waitForPort } from "../../io"; import type { DevEvent, DevRunner } from "../../handlers/project/dev/types"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { isContainerBuild } from "../../projectSchemas/constants"; export type AgentPhase = "idle" | "starting" | "running" | "failed"; @@ -195,7 +196,7 @@ export class DevSupervisor { try { const port = await this.config.resolvePort(entry.runtime); const env = await this.config.getDevEnvVarsForRuntime(entry.runtime); - const runner = this.config.runners[entry.runtime.build]; + const runner = this.config.runners[isContainerBuild(entry.runtime) ? "Container" : "CodeZip"]; let ready = false; const activity = { at: Date.now() }; diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 19d07cf287..c1a916e49c 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -1,4 +1,5 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; @@ -9,7 +10,7 @@ import { ProjectSpecSchema } from "../../../projectSchemas/project"; import { ProjectRuntimeSchema } from "../../../projectSchemas/runtime"; import { createSilentLogger } from "../../../testing"; import { TransactionSearchSetupError } from "../../../errors"; -import { CdkBackend } from "./cdk"; +import { CdkBackend, type CdkBackendConfig } from "./cdk"; import type { CredentialProviderCalls, CredentialProvisionInput, @@ -105,6 +106,10 @@ async function project(withDependencies = true): Promise { type AssemblyOptions = { /** Overrides the resources every stack's template declares. */ resources?: Record; + /** A custom CloudFormation stack name for every stack, as a customized CDK app sets. */ + stackName?: string; + /** The `agentcore:localImages` metadata every stack's template records. */ + localImages?: Record; }; async function writeAssembly( @@ -125,6 +130,9 @@ async function writeAssembly( writeFile( join(directory, stack.templateFile), JSON.stringify({ + ...(options.localImages && { + Metadata: { "agentcore:localImages": options.localImages }, + }), Resources: options.resources ?? { Runtime: { Type: "AWS::BedrockAgentCore::Runtime" } }, }), ), @@ -138,15 +146,23 @@ async function writeAssembly( artifacts: { Tree: { type: "cdk:tree" }, ...Object.fromEntries( - stacks.map((stack) => [ - stack.id, - { - type: "aws:cloudformation:stack", - properties: { - templateFile: stack.templateFile, - tags: { "agentcore:target-name": stack.target }, + stacks.flatMap((stack) => [ + [ + stack.id, + { + type: "aws:cloudformation:stack", + dependencies: [`${stack.id}.assets`], + properties: { + templateFile: stack.templateFile, + tags: { "agentcore:target-name": stack.target }, + ...(options.stackName && { stackName: options.stackName }), + }, }, - }, + ], + [ + `${stack.id}.assets`, + { type: "cdk:asset-manifest", properties: { file: `${stack.id}.assets.json` } }, + ], ]), ), }, @@ -154,7 +170,29 @@ async function writeAssembly( ); } +/** Writes a ContainerLocal image asset manifest for the runtime "agent", as the companion CDK does. */ +async function writeLocalImageManifest(p: Project): Promise { + await writeFile( + join(assemblyDirectory(p), "AgentCore-example-default-0.assets.json"), + JSON.stringify({ + version: "36.0.0", + files: {}, + dockerImages: { + abc123: { + source: { directory: "asset.abc123", platform: "linux/arm64" }, + destinations: {}, + }, + }, + }), + ); +} + type HarnessOptions = { + deployedTemplate?: object | null; + /** Thrown by GetTemplate instead of returning the deployed template. */ + getTemplateError?: Error; + checkLocalBuilder?: CdkBackendConfig["checkLocalBuilder"]; + resolveContainerExecutable?: CdkBackendConfig["resolveContainerExecutable"]; account?: string; bootstrap?: BootstrapState; outputs?: CdkOutputs; @@ -197,6 +235,21 @@ function harness(options: HarnessOptions = {}) { const backend = new CdkBackend({ logger: createSilentLogger(), + assertLocalCdkSupport: () => {}, + createCloudFormationClient: () => + ({ + send: async () => { + if (options.getTemplateError) throw options.getTemplateError; + return { + TemplateBody: + options.deployedTemplate === null + ? undefined + : JSON.stringify(options.deployedTemplate ?? { Resources: {} }), + }; + }, + }) as unknown as ReturnType>, + checkLocalBuilder: options.checkLocalBuilder, + resolveContainerExecutable: options.resolveContainerExecutable ?? (async () => "docker"), identity: unusedIdentity(), runner: async (command, { cwd, onOutput }) => { commands.push({ command, cwd }); @@ -314,6 +367,127 @@ function stepMessages(events: ProjectEvent[]): string[] { } describe("CdkBackend.build", () => { + test("builds, but does not publish, each ContainerLocal image after synthesis", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "local_agent", + build: "ContainerLocal", + codeLocation: "app/local_agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name, "preview"], { + localImages: { "runtime/local_agent": "abc123" }, + }); + const image = { + source: { + directory: "asset.abc123", + dockerFile: "Dockerfile", + dockerBuildArgs: { VERSION: "v1" }, + platform: "linux/arm64", + }, + destinations: {}, + }; + // The same image in two target stacks is built once. + for (const stack of ["AgentCore-example-default-0", "AgentCore-example-preview-1"]) { + await writeFile( + join(assemblyDirectory(p), `${stack}.assets.json`), + JSON.stringify({ version: "36.0.0", files: {}, dockerImages: { abc123: image } }), + ); + } + // A manifest left by an earlier synth (here, before a target existed) is not built. + await writeFile( + join(assemblyDirectory(p), "AgentCore-example.assets.json"), + JSON.stringify({ + version: "36.0.0", + files: {}, + dockerImages: { + stale999: { ...image, source: { ...image.source, directory: "asset.stale999" } }, + }, + }), + ); + const checked: string[] = []; + const h = harness({ + resolveContainerExecutable: async () => "finch", + checkLocalBuilder: async (_runner, _cwd, executable) => { + checked.push(executable); + return {}; + }, + synthOutput: ["step 1/2\n"], + }); + const events = await collect(h.backend.build(p)); + expect(checked).toEqual(["finch"]); + expect(h.commands.map(({ command }) => command)).toEqual([ + synthCommand(p), + [ + "finch", + "build", + "--platform", + "linux/arm64", + "--tag", + "agentcore-local/example-runtime-local_agent:abc123", + "--file", + "Dockerfile", + "--build-arg", + "VERSION=v1", + ".", + ], + ]); + expect(h.commands[1]?.cwd).toBe(join(assemblyDirectory(p), "asset.abc123")); + expect(stepMessages(events)).toContain( + "building runtime/local_agent image agentcore-local/example-runtime-local_agent:abc123", + ); + expect(events.some((event) => event.type === "output")).toBe(true); + expect(h.runs).toHaveLength(0); + expect(h.credentialRegions).toHaveLength(0); + }); + test("loads Docker buildx images and warns about a non-docker driver", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name], { localImages: { "runtime/agent": "abc123" } }); + await writeLocalImageManifest(p); + const h = harness({ + resolveContainerExecutable: async () => "docker", + checkLocalBuilder: async () => ({ + buildx: { name: "multiarch-builder", driver: "docker-container" }, + }), + }); + const events = await collect(h.backend.build(p)); + expect(h.commands[1]?.command.slice(0, 3)).toEqual(["docker", "build", "--load"]); + const warnings = events.filter((event) => event.type === "warning"); + expect(warnings.map((event) => event.message).join("\n")).toContain( + "docker buildx use default", + ); + }); + test("builds no images when no workload builds locally", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "Container", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + const h = harness({ + resolveContainerExecutable: async () => { + throw new Error("must not detect a builder"); + }, + checkLocalBuilder: async () => { + throw new Error("build must not probe Docker"); + }, + }); + await collect(h.backend.build(p)); + expect(h.commands.map(({ command }) => command)).toEqual([synthCommand(p)]); + }); test("synthesizes into the assembly directory deploy reads", async () => { const input = await project(); const subject = harness(); @@ -408,6 +582,353 @@ describe("CdkBackend.build", () => { }); describe("CdkBackend.deploy", () => { + test.each([ + ["Container", "ContainerLocal"], + ["ContainerLocal", "Container"], + ])("rejects %s to %s after synthesis and before bootstrap or deploy", async (before, after) => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: after, + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + deployedTemplate: { Metadata: { "agentcore:builds": { "runtime/agent": before } } }, + checkLocalBuilder: async () => ({}), + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "between Container and ContainerLocal is not supported", + ); + expect(h.commands.map(({ command }) => command)).toEqual([synthCommand(p)]); + expect(h.runs).toHaveLength(0); + expect(h.bootstrapRegions).toHaveLength(0); + expect(h.transactionSearchRegions).toHaveLength(0); + expect(h.stackReads[0]?.region).toBe(TARGET.region); + expect(h.stackReads[0]?.stackName).toBe("AgentCore-example-default-0"); + }); + + test.each(["DELETE_COMPLETE", "ROLLBACK_COMPLETE", "REVIEW_IN_PROGRESS"] as const)( + "treats a %s stack as not deployed", + async (status) => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + describedStack: { + StackName: "AgentCore-example-default", + CreationTime: new Date(0), + StackStatus: status, + }, + getTemplateError: new Error("GetTemplate must not be called"), + checkLocalBuilder: async () => ({}), + }); + await collectDeploy(h.backend.deploy(p, deployInput())); + expect(h.runs.some((run) => run.operation.kind === "deploy")).toBe(true); + }, + ); + test("warns and continues when the template is unreadable and nothing builds locally", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "Container", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + getTemplateError: Object.assign(new Error("denied"), { name: "AccessDenied" }), + }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + const warnings = events.filter((event) => event.type === "warning"); + expect(warnings.map((event) => event.message).join("\n")).toContain( + "cloudformation:GetTemplate", + ); + expect(h.runs.some((run) => run.operation.kind === "deploy")).toBe(true); + }); + test("fails closed on an unreadable template when a workload builds locally", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + getTemplateError: Object.assign(new Error("denied"), { + name: "AccessDeniedException", + $metadata: { httpStatusCode: 403 }, + }), + checkLocalBuilder: async () => ({}), + }); + const error = await collectDeploy(h.backend.deploy(p, deployInput())).catch( + (caught: unknown) => caught as Error, + ); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain("cloudformation:DescribeStacks"); + expect((error as Error).message).toContain("cloudformation:GetTemplate"); + expect(h.runs).toHaveLength(0); + expect(h.bootstrapRegions).toHaveLength(0); + }); + test("propagates errors other than authorization failures", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "Container", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ getTemplateError: new Error("Rate exceeded") }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "Rate exceeded", + ); + }); + test("refuses to deploy when the previous stack template cannot be inspected", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ deployedTemplate: null, checkLocalBuilder: async () => ({}) }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "template is unavailable", + ); + expect(h.runs).toHaveLength(0); + }); + test("checks the selected target's synthesized stack, including an unchanged local workload", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + const otherTarget = { ...TARGET, name: "preview", region: "us-west-2" }; + await writeAssembly(p, [otherTarget.name]); + const h = harness({ + deployedTemplate: { + Metadata: { "agentcore:builds": { "runtime/agent": "ContainerLocal" } }, + }, + checkLocalBuilder: async () => ({}), + }); + await collectDeploy(h.backend.deploy(p, deployInput({ target: otherTarget }))); + expect(h.stackReads[0]?.stackName).toBe("AgentCore-example-preview-0"); + expect(h.stackReads[0]?.region).toBe(otherTarget.region); + expect(h.accountRegions).toEqual([otherTarget.region]); + }); + test("checks a custom-named stack with no earlier assembly or deployed state", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + // The fake synth leaves this in place, as a first synth of a customized app writes it. + await writeAssembly(p, [TARGET.name], { stackName: "CustomOrders" }); + const h = harness({ + deployedTemplate: { Metadata: { "agentcore:builds": { "runtime/agent": "Container" } } }, + checkLocalBuilder: async () => ({}), + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "between Container and ContainerLocal is not supported", + ); + expect(h.stackReads[0]?.stackName).toBe("CustomOrders"); + expect(h.runs).toHaveLength(0); + }); + test("inspects the live stack by name, not a recorded ARN of a deleted stack", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await updateTargetState(json, p.rootPath, TARGET.name, { + stackArn: + "arn:aws:cloudformation:us-east-1:111122223333:stack/AgentCore-example-default-0/deleted", + }); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + deployedTemplate: { Metadata: { "agentcore:builds": { "runtime/agent": "Container" } } }, + checkLocalBuilder: async () => ({}), + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "between Container and ContainerLocal is not supported", + ); + expect(h.stackReads[0]?.stackName).toBe("AgentCore-example-default-0"); + expect(h.runs).toHaveLength(0); + }); + test("refuses an unavailable local builder before provisioning credentials or invoking Toolkit", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + let provisioned = false; + const h = harness({ + checkLocalBuilder: async () => { + throw new Error("ARM64 builder unavailable"); + }, + provisionCredentials: async function* () { + provisioned = true; + yield { type: "step", message: "provisioning credentials" }; + return {}; + }, + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "ARM64 builder unavailable", + ); + expect(provisioned).toBe(false); + expect(h.runs).toHaveLength(0); + expect(h.commands).toHaveLength(0); + }); + + test("reuses the workload build modes the command resolved instead of rereading harness.yaml", async () => { + const p = await project(); + p.spec.harnesses.push({ name: "helper", path: "app/helper" }); + await mkdir(join(p.rootPath, "app", "helper"), { recursive: true }); + // Unparseable, so any reread would fail the deploy. + await writeFile(join(p.rootPath, "app", "helper", "harness.yaml"), "name: [unclosed"); + await writeAssembly(p, [TARGET.name]); + const reads = spyOn(fs, "readFileSync"); + try { + const h = harness({ describedStack: null, checkLocalBuilder: async () => ({}) }); + await collectDeploy( + h.backend.deploy( + p, + deployInput({ workloadBuilds: { "harness/helper": "ContainerLocal" } }), + ), + ); + expect( + reads.mock.calls.filter(([path]) => String(path).endsWith("harness.yaml")), + ).toHaveLength(0); + // The harness from the resolved map still selects the local builder check. + expect(h.runs.find((run) => run.operation.kind === "deploy")?.options).toHaveProperty( + "containerExecutable", + "docker", + ); + } finally { + reads.mockRestore(); + } + }); + test("build reads each harness.yaml once for synthesis and image builds", async () => { + const p = await project(); + p.spec.harnesses.push({ name: "helper", path: "app/helper" }); + await mkdir(join(p.rootPath, "app", "helper"), { recursive: true }); + await writeFile( + join(p.rootPath, "app", "helper", "harness.yaml"), + "name: helper\nmodel: {bedrockModelConfig: {modelId: test-model}}\n" + + "dockerfile: Dockerfile\nbuild: ContainerLocal\n", + ); + const reads = spyOn(fs, "readFileSync"); + try { + const h = harness({ checkLocalBuilder: async () => ({}) }); + await collect(h.backend.build(p)); + expect( + reads.mock.calls.filter(([path]) => String(path).endsWith("harness.yaml")), + ).toHaveLength(1); + } finally { + reads.mockRestore(); + } + }); + test("checks and hands CDK the detected container builder for ContainerLocal", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const checked: string[] = []; + const h = harness({ + describedStack: null, + resolveContainerExecutable: async () => "podman", + checkLocalBuilder: async (_runner, _cwd, executable) => { + checked.push(executable); + return {}; + }, + }); + await collectDeploy(h.backend.deploy(p, deployInput())); + expect(checked).toEqual(["podman"]); + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options.containerExecutable).toBe("podman"); + }); + test("warns during deploy when the Docker buildx driver is not docker", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + describedStack: null, + checkLocalBuilder: async () => ({ + buildx: { name: "multiarch-builder", driver: "docker-container" }, + }), + }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + const warnings = events.filter((event) => event.type === "warning"); + expect(warnings.map((event) => event.message).join("\n")).toContain( + "'multiarch-builder' uses the docker-container driver", + ); + }); + test("skips builder detection when no workload builds locally", async () => { + const p = await project(); + await writeAssembly(p, [TARGET.name]); + const h = harness({ + describedStack: null, + resolveContainerExecutable: async () => { + throw new Error("must not detect a builder"); + }, + checkLocalBuilder: async () => { + throw new Error("must not probe a builder"); + }, + }); + await collectDeploy(h.backend.deploy(p, deployInput())); + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options).not.toHaveProperty("containerExecutable"); + }); test("preflights, synthesizes, and deploys the selected stack", async () => { const input = await project(); await writeAssembly(input, [TARGET.name]); diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 85b1c1d337..6701df8453 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -1,6 +1,7 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; -import type { Stack } from "@aws-sdk/client-cloudformation"; +import { GetTemplateCommand, type Stack } from "@aws-sdk/client-cloudformation"; +import { parse as parseYaml } from "yaml"; import { MalformedServiceResponseError, ProjectStateError } from "../../../errors/errors"; import type { DeployResult, @@ -9,8 +10,18 @@ import type { DeployableResource, ResolvedDeployedResource, ResolvedProjectResource, + WorkloadBuilds, } from "../../../handlers/project/types"; -import { cdkCompatibilityWarning } from "./cdk/compatibility"; +import { assertCdkLocalContainerSupport, cdkCompatibilityWarning } from "./cdk/compatibility"; +import { + assertSupportedBuildTransitions, + hasLocalContainerBuilds, + resolveWorkloadBuilds, + type DeployedTemplate, +} from "./cdk/localContainers"; +import { buildxDriverWarning, checkArm64Builder } from "./cdk/arm64Builder"; +import { localImageBuilds } from "./cdk/localImages"; +import { resolveCdkDockerExecutable } from "../../dev/containerTool"; import { createLineSplitter, FsReadWriteJson, @@ -73,6 +84,7 @@ import { type CdkRunner, type CdkRunOptions, type CdkRunResult, + type CdkCredentialProvider, } from "./cdk/toolkit"; import { createPaymentConnectorAuthorizationUrlReporter, @@ -149,8 +161,28 @@ export type CdkBackendConfig = { removeCredentials?: CredentialRemover; describeStack?: StackDescriber; reportPaymentConnectorAuthorizationUrls?: PaymentConnectorAuthorizationUrlReporter; + checkLocalBuilder?: typeof checkArm64Builder; + resolveContainerExecutable?: () => Promise; + assertLocalCdkSupport?: typeof assertCdkLocalContainerSupport; }; +// Stacks in these states hold no deployed workloads: deleted, rolled back after a +// failed first create, or a change set created but never executed. +const NOT_DEPLOYED_STACK_STATUSES = new Set([ + "DELETE_COMPLETE", + "ROLLBACK_COMPLETE", + "REVIEW_IN_PROGRESS", +]); + +function isAuthorizationError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode; + return ( + status === 403 || + ["AccessDenied", "AccessDeniedException", "UnauthorizedOperation"].includes(error.name) + ); +} + /** Builds and deploys projects through the scaffolded CDK app. */ export class CdkBackend implements ProjectBackend { private readonly logger: Logger; @@ -167,10 +199,20 @@ export class CdkBackend implements ProjectBackend { private readonly removeCredentials: CredentialRemover; private readonly describeStack: StackDescriber; private readonly reportPaymentConnectorAuthorizationUrls: PaymentConnectorAuthorizationUrlReporter; + private readonly checkLocalBuilder: typeof checkArm64Builder; + private readonly resolveContainerExecutable: () => Promise; + private readonly assertLocalCdkSupport: typeof assertCdkLocalContainerSupport; + private readonly createCloudFormationClient: CreateCloudFormationClient; constructor(config: CdkBackendConfig) { this.logger = config.logger; this.runner = config.runner ?? runProcess; + this.checkLocalBuilder = config.checkLocalBuilder ?? checkArm64Builder; + this.resolveContainerExecutable = + config.resolveContainerExecutable ?? (() => resolveCdkDockerExecutable()); + this.assertLocalCdkSupport = config.assertLocalCdkSupport ?? assertCdkLocalContainerSupport; + this.createCloudFormationClient = + config.createCloudFormationClient ?? createCloudFormationClient; this.checkTool = config.checkTool ?? requireTool; this.json = config.json ?? new FsReadWriteJson({ logger: config.logger }); this.cdk = config.cdk ?? createCdkRunner(config.logger); @@ -216,6 +258,7 @@ export class CdkBackend implements ProjectBackend { private async *synthesize( project: Project, explainUndeployedCredentials: boolean, + builds: WorkloadBuilds, ): AsyncGenerator { await this.ensureCdkDependencies(project); @@ -224,6 +267,9 @@ export class CdkBackend implements ProjectBackend { yield { type: "warning", message: compatibilityWarning }; } + if (hasLocalContainerBuilds(builds)) { + this.assertLocalCdkSupport(this.cdkDirectory(project)); + } yield { type: "step", message: "synthesizing CloudFormation templates" }; try { yield* withOutputEvents((emit) => { @@ -254,7 +300,49 @@ export class CdkBackend implements ProjectBackend { } public async *build(project: Project): AsyncGenerator { - yield* this.synthesize(project, true); + const builds = resolveWorkloadBuilds(project); + yield* this.synthesize(project, true, builds); + yield* this.buildLocalImages(project, builds); + } + + /** + * Builds, but does not push, each ContainerLocal image from the staged context + * in the synthesized assembly, so `agentcore build` catches Dockerfile errors + * without AWS credentials. `agentcore deploy` builds and publishes through CDK. + */ + private async *buildLocalImages( + project: Project, + builds: WorkloadBuilds, + ): AsyncGenerator { + if (!hasLocalContainerBuilds(builds)) return; + const images = await localImageBuilds( + this.json, + this.assemblyDirectory(project), + project.name, + builds, + ); + if (images.length === 0) return; + const executable = await this.resolveContainerExecutable(); + yield { type: "step", message: `checking that ${executable} can build Linux ARM64 images` }; + const report = await this.checkLocalBuilder(this.runner, project.rootPath, executable); + const warning = buildxDriverWarning(report); + if (warning) yield { type: "warning", message: warning }; + // Docker with buildx may build with a driver that keeps the image out of the + // local store; --load keeps it there. Finch and Podman load by default. + const load = report.buildx !== undefined; + for (const image of images) { + yield { type: "step", message: `building ${image.resource} image ${image.tag}` }; + yield* withOutputEvents((emit) => { + const lines = createLineSplitter(emit); + return this.runner(image.command(executable, { load }), { + cwd: image.directory, + onOutput: (chunk) => { + this.logger.debug(chunk); + lines.push(chunk); + }, + }).finally(() => lines.flush()); + }); + } } public async *deploy( @@ -269,13 +357,33 @@ export class CdkBackend implements ProjectBackend { // before any AWS mutation, so a local problem never leaves credentials // provisioned or the stack ARN unrecorded. await this.ensureCdkDependencies(project); + const builds = input.workloadBuilds ?? resolveWorkloadBuilds(project); + const deployedState = (await readDeployedState(this.json, project.rootPath)).targets[ + target.name + ]; + // CDK builds and publishes ContainerLocal images with CDK_DOCKER, so check + // that same executable. + let containerExecutable: string | undefined; + if (hasLocalContainerBuilds(builds)) { + this.assertLocalCdkSupport(this.cdkDirectory(project)); + containerExecutable = await this.resolveContainerExecutable(); + yield { + type: "step", + message: `checking that ${containerExecutable} can build Linux ARM64 images`, + }; + const report = await this.checkLocalBuilder( + this.runner, + project.rootPath, + containerExecutable, + ); + const warning = buildxDriverWarning(report); + if (warning) yield { type: "warning", message: warning }; + } // Read before provisioning rewrites the credentials map: it is the only record // of what this target provisioned, so it is the only way to find a provider whose // credential has since left the spec. - const recorded = - (await readDeployedState(this.json, project.rootPath)).targets[target.name]?.resources - ?.credentials ?? {}; + const recorded = deployedState?.resources?.credentials ?? {}; assertPaymentConnectorCredentials(project, target.name, recorded); const orphaned = orphanedCredentials(recorded, project.spec.credentials); @@ -293,10 +401,28 @@ export class CdkBackend implements ProjectBackend { resources: { credentials: provisioned }, }); - yield* this.synthesize(project, false); + yield* this.synthesize(project, false, builds); const assemblyDirectory = this.assemblyDirectory(project); const artifact = await stackArtifactForTarget(this.json, assemblyDirectory, target.name); - const options = { assemblyDirectory, credentials, region: target.region }; + // Checked against the stack this deploy is about to update, before teardown + // detection, bootstrap, or the deploy itself touch it. + if (Object.keys(builds).length) { + yield { type: "step", message: "checking deployed workload build modes" }; + const warning = await this.assertBuildModesUnchanged( + project, + target, + credentials, + builds, + artifact.stackName, + ); + if (warning) yield { type: "warning", message: warning }; + } + const options = { + assemblyDirectory, + credentials, + region: target.region, + ...(containerExecutable && { containerExecutable }), + }; // Decided before the Toolkit is handed the assembly: it reads a template // with nothing in it as an instruction to delete the stack, and reports that @@ -706,6 +832,59 @@ export class CdkBackend implements ProjectBackend { ]; } + /** + * Rejects switching a deployed workload between Container and ContainerLocal. + * Reads the live template of the synthesized stack, looked up by name (never by + * a recorded ARN, which can point at a deleted stack), after synthesis and + * before the stack is touched. Credential providers are already provisioned. + * Returns a warning when the check could not run for lack of permissions and no + * workload uses ContainerLocal, since nothing can then be switched into it. + */ + private async assertBuildModesUnchanged( + project: Project, + target: AwsDeploymentTarget, + credentials: CdkCredentialProvider, + builds: WorkloadBuilds, + stackName: string, + ): Promise { + let template: string | undefined; + try { + const stack = await this.describeStack(target.region, credentials, stackName); + if (!stack || NOT_DEPLOYED_STACK_STATUSES.has(stack.StackStatus ?? "")) return undefined; + const client = this.createCloudFormationClient({ region: target.region, credentials }); + const previous = await client.send( + new GetTemplateCommand({ + StackName: stack.StackId ?? stackName, + TemplateStage: "Original", + }), + ); + template = previous.TemplateBody; + } catch (error) { + if (!isAuthorizationError(error)) throw error; + const message = + `Cannot read stack '${stackName}' to check build modes: the deployment credentials ` + + "need cloudformation:DescribeStacks and cloudformation:GetTemplate on it."; + if (hasLocalContainerBuilds(builds)) { + throw new ProjectStateError(`${message} This check is required for ContainerLocal.`, { + cause: error, + }); + } + return `${message} Skipping the check because no workload uses ContainerLocal.`; + } + if (!template) { + throw new ProjectStateError( + "Cannot verify build modes: the deployed stack template is unavailable.", + ); + } + assertSupportedBuildTransitions( + parseYaml(template) as DeployedTemplate, + builds, + project.name, + project.spec.migratedFrom ? undefined : target.name, + ); + return undefined; + } + private async credentialsForTarget(target: AwsDeploymentTarget) { const credentials = await this.resolveCredentials(target.region); const account = await this.resolveAccount(target.region, credentials); diff --git a/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.assets.json b/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.assets.json new file mode 100644 index 0000000000..8d3e234978 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.assets.json @@ -0,0 +1,65 @@ +{ + "version": "54.0.0", + "files": { + "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c": { + "displayName": "Application/RuntimeBilling/ContainerSourceAsset/SourceAsset", + "source": { + "path": "asset.cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c", + "packaging": "zip" + }, + "destinations": { + "current_account-current_region-4443d752": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c.zip", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "00db132ea825f2e79ddea58fa309048f2cbd20f2858ae2b57c29863903d64128": { + "displayName": "AgentCore-Fixture Template", + "source": { + "path": "AgentCore-Fixture.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region-0d30b6f2": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "00db132ea825f2e79ddea58fa309048f2cbd20f2858ae2b57c29863903d64128.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": { + "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e": { + "displayName": "Application/RuntimeOrders/LocalContainerImage/Image", + "source": { + "directory": "asset.b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "dockerFile": "Dockerfile", + "platform": "linux/arm64" + }, + "destinations": { + "current_account-current_region-e3460c4d": { + "repositoryName": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}", + "imageTag": "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-image-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624": { + "displayName": "Application/HarnessAssistant/LocalContainerImage/Image", + "source": { + "directory": "asset.312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624", + "dockerFile": "Dockerfile", + "platform": "linux/arm64" + }, + "destinations": { + "current_account-current_region-56e3b610": { + "repositoryName": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}", + "imageTag": "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-image-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + } +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.template.json b/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.template.json new file mode 100644 index 0000000000..4e95581ea9 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/local-images/AgentCore-Fixture.template.json @@ -0,0 +1,1690 @@ +{ + "Description": "AgentCore stack for Fixture (no deployment target configured)", + "Metadata": { + "agentcore:builds": { + "runtime/orders": "ContainerLocal", + "runtime/billing": "Container", + "harness/assistant": "ContainerLocal" + }, + "agentcore:localImages": { + "runtime/orders": "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "harness/assistant": "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + }, + "Resources": { + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":runtime/Fixture_orders*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "Execution role for Bedrock Agent Core Runtime", + "MaxSessionDuration": 28800 + } + }, + "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:DescribeLogStreams", + "logs:CreateLogGroup" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "LogGroupAccess" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "DescribeLogGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "LogStreamAccess" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayAccess" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetrics" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT", + "bedrock-agentcore:GetWorkloadAccessTokenForUserId" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/*" + ] + ] + } + ], + "Sid": "GetAgentAccessToken" + }, + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:CountTokens" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*:", + { + "Ref": "AWS::AccountId" + }, + ":inference-profile/*" + ] + ] + } + ] + }, + { + "Action": [ + "logs:GetLogEvents", + "logs:FilterLogEvents", + "logs:PutResourcePolicy" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + } + }, + { + "Action": [ + "bedrock-agentcore:GetConfigurationBundle", + "bedrock-agentcore:GetConfigurationBundleVersion", + "bedrock-agentcore:ListConfigurationBundles", + "bedrock-agentcore:ListConfigurationBundleVersions", + "bedrock-agentcore:CreateConfigurationBundle", + "bedrock-agentcore:UpdateConfigurationBundle", + "bedrock-agentcore:DeleteConfigurationBundle" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:*:*:configuration-bundle/*" + ] + ] + } + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "ecr:BatchGetImage", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ecr:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":repository/", + { + "Fn::Sub": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360", + "Roles": [ + { + "Ref": "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC" + } + ] + } + }, + "ApplicationRuntimeOrdersRuntimeACF3F5A3": { + "Type": "AWS::BedrockAgentCore::Runtime", + "Properties": { + "AgentRuntimeArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e" + } + } + }, + "AgentRuntimeName": "Fixture_orders", + "Description": "AgentCore Runtime: Fixture_orders", + "LifecycleConfiguration": {}, + "NetworkConfiguration": { + "NetworkMode": "PUBLIC" + }, + "ProtocolConfiguration": "HTTP", + "RoleArn": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC", + "Arn" + ] + } + }, + "DependsOn": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360", + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC" + ] + }, + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400": { + "Type": "AWS::KMS::Key", + "Properties": { + "Description": "ECR encryption key for fixture/billing", + "EnableKeyRotation": true, + "KeyPolicy": { + "Statement": [ + { + "Action": "kms:*", + "Effect": "Allow", + "Principal": { + "AWS": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::", + { + "Ref": "AWS::AccountId" + }, + ":root" + ] + ] + } + }, + "Resource": "*" + } + ], + "Version": "2012-10-17" + } + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingContainerRepositoryD276BA4F": { + "Type": "AWS::ECR::Repository", + "Properties": { + "EmptyOnDelete": true, + "EncryptionConfiguration": { + "EncryptionType": "KMS", + "KmsKey": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400", + "Arn" + ] + } + }, + "ImageScanningConfiguration": { + "ScanOnPush": true + }, + "LifecyclePolicy": { + "LifecyclePolicyText": "{\"rules\":[{\"rulePriority\":1,\"description\":\"Keep last 10 images\",\"selection\":{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":10},\"action\":{\"type\":\"expire\"}}]}" + }, + "RepositoryName": "fixture/billing" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ] + ] + } + ] + } + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "codebuild:StartBuild", + "codebuild:BatchGetBuilds" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ContainerBuildProject5A4F8922", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "Roles": [ + { + "Ref": "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48" + } + ] + } + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "ZipFile": "\nconst { CodeBuildClient, StartBuildCommand, BatchGetBuildsCommand } = require('@aws-sdk/client-codebuild');\nconst codebuild = new CodeBuildClient();\n\nexports.handler = async function(event, context) {\n const props = event.ResourceProperties;\n const requestType = event.RequestType;\n\n // Build the response object\n const response = {\n Status: 'SUCCESS',\n PhysicalResourceId: props.ImageUri || 'container-build',\n StackId: event.StackId,\n RequestId: event.RequestId,\n LogicalResourceId: event.LogicalResourceId,\n Data: {},\n };\n\n try {\n if (requestType === 'Delete') {\n response.Data = {};\n await sendResponse(event, response);\n return;\n }\n\n // Docker build args: forward each as its own build environment variable and reference it with\n // '--build-arg NAME' (no value), so docker inherits the value from the environment. This keeps\n // arbitrary values off the shell command line (no quoting/word-splitting hazards). BUILD_ARG_FLAGS\n // is the space-separated flag list the buildspec interpolates; it is empty when there are no args.\n const buildArgs = props.BuildArgs ? JSON.parse(props.BuildArgs) : {};\n const buildArgNames = Object.keys(buildArgs);\n const buildArgEnv = buildArgNames.map(name => ({ name, value: String(buildArgs[name]), type: 'PLAINTEXT' }));\n const buildArgFlags = buildArgNames.map(name => '--build-arg ' + name).join(' ');\n\n // Start CodeBuild\n const startResult = await codebuild.send(new StartBuildCommand({\n projectName: props.ProjectName,\n sourceTypeOverride: 'S3',\n sourceLocationOverride: props.SourceBucket + '/' + props.SourceKey,\n environmentVariablesOverride: [\n { name: 'ECR_REGISTRY', value: props.EcrRegistry, type: 'PLAINTEXT' },\n { name: 'IMAGE_URI', value: props.ImageUri, type: 'PLAINTEXT' },\n { name: 'DOCKERFILE_PATH', value: props.DockerfilePath, type: 'PLAINTEXT' },\n { name: 'BUILD_ARG_FLAGS', value: buildArgFlags, type: 'PLAINTEXT' },\n ...buildArgEnv,\n ],\n }));\n\n const buildId = startResult.build.id;\n console.log('Started build:', buildId);\n\n // Poll until complete (14 minutes max to stay within Lambda's 15-minute timeout)\n const maxWaitMs = 14 * 60 * 1000;\n const start = Date.now();\n while (Date.now() - start < maxWaitMs) {\n const result = await codebuild.send(new BatchGetBuildsCommand({ ids: [buildId] }));\n const build = result.builds[0];\n if (build.buildStatus !== 'IN_PROGRESS') {\n if (build.buildStatus === 'SUCCEEDED') {\n response.Data = { ContainerUri: props.ImageUri };\n await sendResponse(event, response);\n return;\n } else {\n const logsUrl = build.logs && build.logs.deepLink ? build.logs.deepLink : 'Check CloudWatch Logs';\n response.Status = 'FAILED';\n response.Reason = 'CodeBuild build failed. Status: ' + build.buildStatus + '. Logs: ' + logsUrl;\n await sendResponse(event, response);\n return;\n }\n }\n await new Promise(r => setTimeout(r, 10000));\n }\n\n response.Status = 'FAILED';\n response.Reason = 'Build timed out after 14 minutes';\n await sendResponse(event, response);\n } catch (err) {\n response.Status = 'FAILED';\n response.Reason = err.message || 'Unknown error';\n await sendResponse(event, response);\n }\n};\n\nasync function sendResponse(event, response) {\n const https = require('https');\n const responseBody = JSON.stringify(response);\n const parsedUrl = new URL(event.ResponseURL);\n const options = {\n hostname: parsedUrl.hostname,\n port: 443,\n path: parsedUrl.pathname + parsedUrl.search,\n method: 'PUT',\n headers: { 'content-type': '', 'content-length': responseBody.length },\n };\n return new Promise((resolve, reject) => {\n const req = https.request(options, resolve);\n req.on('error', reject);\n req.write(responseBody);\n req.end();\n });\n}\n" + }, + "Handler": "index.handler", + "MemorySize": 256, + "Role": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "Arn" + ] + }, + "Runtime": "nodejs22.x", + "Timeout": 900 + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48" + ] + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F": { + "Type": "AWS::CloudFormation::CustomResource", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "Arn" + ] + }, + "ProjectName": { + "Ref": "ContainerBuildProject5A4F8922" + }, + "SourceBucket": { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "SourceKey": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c.zip", + "ImageUri": { + "Fn::Join": [ + "", + [ + { + "Fn::Select": [ + 4, + { + "Fn::Split": [ + ":", + { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + ] + } + ] + }, + ".dkr.ecr.", + { + "Fn::Select": [ + 3, + { + "Fn::Split": [ + ":", + { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + ] + } + ] + }, + ".", + { + "Ref": "AWS::URLSuffix" + }, + "/", + { + "Ref": "ApplicationRuntimeBillingContainerRepositoryD276BA4F" + }, + ":cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c" + ] + ] + }, + "DockerfilePath": "Dockerfile", + "EcrRegistry": { + "Fn::Join": [ + "", + [ + { + "Ref": "AWS::AccountId" + }, + ".dkr.ecr.", + { + "Ref": "AWS::Region" + }, + ".", + { + "Ref": "AWS::URLSuffix" + } + ] + ] + }, + "SourceHash": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":runtime/Fixture_billing*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "Execution role for Bedrock Agent Core Runtime", + "MaxSessionDuration": 28800 + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F" + ] + }, + "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:DescribeLogStreams", + "logs:CreateLogGroup" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "LogGroupAccess" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "DescribeLogGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "LogStreamAccess" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayAccess" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetrics" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT", + "bedrock-agentcore:GetWorkloadAccessTokenForUserId" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/*" + ] + ] + } + ], + "Sid": "GetAgentAccessToken" + }, + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:CountTokens" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*:", + { + "Ref": "AWS::AccountId" + }, + ":inference-profile/*" + ] + ] + } + ] + }, + { + "Action": [ + "logs:GetLogEvents", + "logs:FilterLogEvents", + "logs:PutResourcePolicy" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + } + }, + { + "Action": [ + "bedrock-agentcore:GetConfigurationBundle", + "bedrock-agentcore:GetConfigurationBundleVersion", + "bedrock-agentcore:ListConfigurationBundles", + "bedrock-agentcore:ListConfigurationBundleVersions", + "bedrock-agentcore:CreateConfigurationBundle", + "bedrock-agentcore:UpdateConfigurationBundle", + "bedrock-agentcore:DeleteConfigurationBundle" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:*:*:configuration-bundle/*" + ] + ] + } + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "ecr:BatchGetImage", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + }, + { + "Action": "kms:Decrypt", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC", + "Roles": [ + { + "Ref": "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19" + } + ] + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F" + ] + }, + "ApplicationRuntimeBillingRuntime3CC6043B": { + "Type": "AWS::BedrockAgentCore::Runtime", + "Properties": { + "AgentRuntimeArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F", + "ContainerUri" + ] + } + } + }, + "AgentRuntimeName": "Fixture_billing", + "Description": "AgentCore Runtime: Fixture_billing", + "LifecycleConfiguration": {}, + "NetworkConfiguration": { + "NetworkMode": "PUBLIC" + }, + "ProtocolConfiguration": "HTTP", + "RoleArn": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19", + "Arn" + ] + } + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F", + "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC", + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19" + ] + }, + "ApplicationHarnessAssistantRoleExecutionRole1A384D55": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "AgentCore Harness assistant execution role" + } + }, + "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":*" + ] + ] + } + ], + "Sid": "BedrockModelInvocation" + }, + { + "Action": "ecr-public:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "EcrPublicTokenAccess" + }, + { + "Action": "sts:GetServiceBearerToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "StsForEcrPublicPull" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayTracingAccess" + }, + { + "Action": [ + "logs:CreateLogGroup", + "logs:DescribeLogStreams" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "CloudWatchLogsGroup" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "CloudWatchLogsDescribeGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "CloudWatchLogsStream" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetricsPublish" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/harness_Fixture_assistant-*" + ] + ] + } + ], + "Sid": "AgentCoreWorkloadIdentity" + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "ECRTokenAccess" + }, + { + "Action": [ + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ecr:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":repository/", + { + "Fn::Sub": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + }, + "Sid": "ECRImageAccess" + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13", + "Roles": [ + { + "Ref": "ApplicationHarnessAssistantRoleExecutionRole1A384D55" + } + ] + } + }, + "ApplicationHarnessAssistantHarness1F2A9185": { + "Type": "AWS::BedrockAgentCore::Harness", + "Properties": { + "EnvironmentArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + } + }, + "ExecutionRoleArn": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantRoleExecutionRole1A384D55", + "Arn" + ] + }, + "HarnessName": "Fixture_assistant", + "Memory": { + "Disabled": {} + }, + "Model": { + "BedrockModelConfig": { + "ModelId": "global.anthropic.claude-sonnet-4-6" + } + } + }, + "DependsOn": [ + "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13", + "ApplicationHarnessAssistantRoleExecutionRole1A384D55" + ] + }, + "ContainerBuildProjectContainerBuildExecutionRole69AD3217": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "codebuild.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + } + } + }, + "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/codebuild/*" + ] + ] + } + }, + { + "Action": [ + "ecr:BatchCheckLayerAvailability", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:CompleteLayerUpload", + "ecr:UploadLayerPart", + "ecr:InitiateLayerUpload", + "ecr:PutImage" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + }, + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::", + { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::", + { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "/*" + ] + ] + } + ] + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239", + "Roles": [ + { + "Ref": "ContainerBuildProjectContainerBuildExecutionRole69AD3217" + } + ] + } + }, + "ContainerBuildProject5A4F8922": { + "Type": "AWS::CodeBuild::Project", + "Properties": { + "Artifacts": { + "Type": "NO_ARTIFACTS" + }, + "Cache": { + "Modes": [ + "LOCAL_DOCKER_LAYER_CACHE" + ], + "Type": "LOCAL" + }, + "EncryptionKey": "alias/aws/s3", + "Environment": { + "ComputeType": "BUILD_GENERAL1_SMALL", + "Image": "aws/codebuild/amazonlinux-aarch64-standard:3.0", + "ImagePullCredentialsType": "CODEBUILD", + "PrivilegedMode": true, + "Type": "ARM_CONTAINER" + }, + "Name": "AgentCore-Fixture-container-builder", + "ServiceRole": { + "Fn::GetAtt": [ + "ContainerBuildProjectContainerBuildExecutionRole69AD3217", + "Arn" + ] + }, + "Source": { + "BuildSpec": "{\n \"version\": \"0.2\",\n \"phases\": {\n \"pre_build\": {\n \"commands\": [\n \"echo \\\"Logging in to Amazon ECR...\\\"\",\n \"aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $ECR_REGISTRY\"\n ]\n },\n \"build\": {\n \"commands\": [\n \"echo \\\"Building container image...\\\"\",\n \"docker build -t $IMAGE_URI -f $DOCKERFILE_PATH $BUILD_ARG_FLAGS .\"\n ]\n },\n \"post_build\": {\n \"commands\": [\n \"echo \\\"Pushing image to ECR...\\\"\",\n \"docker push $IMAGE_URI\",\n \"echo \\\"Image pushed: $IMAGE_URI\\\"\"\n ]\n }\n }\n}", + "Type": "NO_SOURCE" + }, + "TimeoutInMinutes": 30 + }, + "DependsOn": [ + "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239", + "ContainerBuildProjectContainerBuildExecutionRole69AD3217" + ] + } + }, + "Outputs": { + "ApplicationRuntimeOrdersRuntimeIdOutput16125101": { + "Description": "Runtime ID for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeACF3F5A3", + "AgentRuntimeId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RuntimeId" + } + }, + "ApplicationRuntimeOrdersRuntimeArnOutputFC642947": { + "Description": "Runtime ARN for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeACF3F5A3", + "AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RuntimeArn" + } + }, + "ApplicationRuntimeOrdersRoleArnOutputC7A8CEC9": { + "Description": "Execution Role ARN for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RoleArn" + } + }, + "ApplicationRuntimeBillingRuntimeIdOutputBCE2E749": { + "Description": "Runtime ID for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntime3CC6043B", + "AgentRuntimeId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RuntimeId" + } + }, + "ApplicationRuntimeBillingRuntimeArnOutputB69FF2F2": { + "Description": "Runtime ARN for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntime3CC6043B", + "AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RuntimeArn" + } + }, + "ApplicationRuntimeBillingRoleArnOutputC3A2D95A": { + "Description": "Execution Role ARN for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RoleArn" + } + }, + "ApplicationHarnessAssistantImageUriOutput444CA041": { + "Description": "Container image URI for harness \"assistant\"", + "Value": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + }, + "ApplicationHarnessAssistantRoleRoleArnOutput0DE2C07F": { + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantRoleExecutionRole1A384D55", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-RoleArn" + } + }, + "ApplicationHarnessAssistantIdOutputBA102026": { + "Description": "Harness ID for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "HarnessId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Id" + } + }, + "ApplicationHarnessAssistantArnOutput31DCA32F": { + "Description": "Harness ARN for: assistant", + "Value": { + "Ref": "ApplicationHarnessAssistantHarness1F2A9185" + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Arn" + } + }, + "ApplicationHarnessAssistantStatusOutput0CFD8979": { + "Description": "Harness status for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Status" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Status" + } + }, + "ApplicationHarnessAssistantVersionOutputBBE292E0": { + "Description": "Harness config version for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Version" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Version" + } + }, + "ApplicationHarnessAssistantAgentRuntimeArnOutput6F4D9700": { + "Description": "Underlying AgentCore Runtime ARN for harness: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Environment.AgentCoreRuntimeEnvironment.AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-AgentRuntimeArn" + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/__fixtures__/local-images/README.md b/src/core/project/backends/cdk/__fixtures__/local-images/README.md new file mode 100644 index 0000000000..3439b88160 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/local-images/README.md @@ -0,0 +1,29 @@ +# ContainerLocal assembly fixture + +A real cloud assembly synthesized by `@aws/agentcore-cdk` with ContainerLocal support +(aws/agentcore-l3-cdk-constructs#463). `localImages.test.ts` reads it to pin the contract between +the CDK package and `agentcore build`: each stack template's `Metadata["agentcore:localImages"]` +maps `runtime/` or `harness/` to the key of its image under `dockerImages` in the +stack's asset manifest. + +The project had no deployment targets, so it synthesized one environment-agnostic stack, +`AgentCore-Fixture`, with: + +- Runtime `orders`: `build: ContainerLocal` +- Runtime `billing`: `build: Container` (CodeBuild) +- Harness `assistant`: `build: ContainerLocal`, `dockerfile: Dockerfile` + +Only `manifest.json`, the stack template, and the asset manifest are kept. The staged `asset.*` +directories, `tree.json`, and the stack's `*.metadata.json`, which `manifest.json` still +references, are not needed by the CLI and are not included. + +## Regenerating + +1. In a checkout of aws/agentcore-l3-cdk-constructs with ContainerLocal support, run + `npm run build && npm pack`. +2. Create an AgentCore project (no `aws-targets.json` entries) with the three workloads above. +3. In its `agentcore/cdk/` directory, install the packed tarball together with the + `aws-cdk-lib` and `constructs` versions it requires, then synthesize the vended app + (`npx cdk synth`, or run the compiled `bin/cdk` app with `CDK_OUTDIR` set). +4. Copy `manifest.json`, `AgentCore-Fixture.template.json`, and `AgentCore-Fixture.assets.json` + from the output directory into this directory. diff --git a/src/core/project/backends/cdk/__fixtures__/local-images/manifest.json b/src/core/project/backends/cdk/__fixtures__/local-images/manifest.json new file mode 100644 index 0000000000..2414b248ce --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/local-images/manifest.json @@ -0,0 +1,511 @@ +{ + "version": "54.0.0", + "artifacts": { + "AgentCore-Fixture.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "AgentCore-Fixture.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "AgentCore-Fixture": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "AgentCore-Fixture.template.json", + "terminationProtection": false, + "tags": { + "agentcore:project-name": "Fixture" + }, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/00db132ea825f2e79ddea58fa309048f2cbd20f2858ae2b57c29863903d64128.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "AgentCore-Fixture.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "AgentCore-Fixture.assets" + ], + "additionalMetadataFile": "AgentCore-Fixture.metadata.json", + "displayName": "AgentCore-Fixture" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + }, + "aws-cdk-lib/feature-flag-report": { + "type": "cdk:feature-flag-report", + "properties": { + "module": "aws-cdk-lib", + "flags": { + "@aws-cdk/aws-signer:signingProfileNamePassedToCfn": { + "recommendedValue": true, + "explanation": "Pass signingProfileName to CfnSigningProfile" + }, + "@aws-cdk/core:newStyleStackSynthesis": { + "recommendedValue": true, + "explanation": "Switch to new stack synthesis method which enables CI/CD", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:stackRelativeExports": { + "recommendedValue": true, + "explanation": "Name exports based on the construct paths relative to the stack, rather than the global construct path", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:secGroupsDisablesImplicitOpenListener": { + "recommendedValue": true, + "explanation": "Disable implicit openListener when custom security groups are provided" + }, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": { + "recommendedValue": true, + "explanation": "Force lowercasing of RDS Cluster names in CDK", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": { + "recommendedValue": true, + "explanation": "Allow adding/removing multiple UsagePlanKeys independently", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeVersionProps": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeLayerVersion": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`." + }, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have cloudfront distributions use the security policy TLSv1.2_2021 by default.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:checkSecretUsage": { + "recommendedValue": true, + "explanation": "Enable this flag to make it impossible to accidentally use SecretValues in unsafe locations" + }, + "@aws-cdk/core:target-partitions": { + "recommendedValue": [ + "aws", + "aws-cn" + ], + "explanation": "What regions to include in lookup tables of environment agnostic stacks" + }, + "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": { + "recommendedValue": true, + "explanation": "ECS extensions will automatically add an `awslogs` driver if no logging is specified" + }, + "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have Launch Templates generated by the `InstanceRequireImdsv2Aspect` use unique names." + }, + "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": { + "recommendedValue": true, + "explanation": "ARN format used by ECS. In the new ARN format, the cluster name is part of the resource ID." + }, + "@aws-cdk/aws-iam:minimizePolicies": { + "recommendedValue": true, + "explanation": "Minimize IAM policies by combining Statements" + }, + "@aws-cdk/core:validateSnapshotRemovalPolicy": { + "recommendedValue": true, + "explanation": "Error on snapshot removal policies on resources that do not support it." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": { + "recommendedValue": true, + "explanation": "Generate key aliases that include the stack name" + }, + "@aws-cdk/aws-s3:createDefaultLoggingPolicy": { + "recommendedValue": true, + "explanation": "Enable this feature flag to create an S3 bucket policy by default in cases where an AWS service would automatically create the Policy if one does not exist." + }, + "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": { + "recommendedValue": true, + "explanation": "Restrict KMS key policy for encrypted Queues a bit more" + }, + "@aws-cdk/aws-apigateway:disableCloudWatchRole": { + "recommendedValue": true, + "explanation": "Make default CloudWatch Role behavior safe for multiple API Gateways in one environment" + }, + "@aws-cdk/core:enablePartitionLiterals": { + "recommendedValue": true, + "explanation": "Make ARNs concrete if AWS partition is known" + }, + "@aws-cdk/aws-events:eventsTargetQueueSameAccount": { + "recommendedValue": true, + "explanation": "Event Rules may only push to encrypted SQS queues in the same account" + }, + "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": { + "recommendedValue": true, + "explanation": "Avoid setting the \"ECS\" deployment controller when adding a circuit breaker" + }, + "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": { + "recommendedValue": true, + "explanation": "Enable this feature to create default policy names for imported roles that depend on the stack the role is in." + }, + "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": { + "recommendedValue": true, + "explanation": "Use S3 Bucket Policy instead of ACLs for Server Access Logging" + }, + "@aws-cdk/aws-route53-patters:useCertificate": { + "recommendedValue": true, + "explanation": "Use the official `Certificate` resource instead of `DnsValidatedCertificate`" + }, + "@aws-cdk/customresources:installLatestAwsSdkDefault": { + "recommendedValue": false, + "explanation": "Whether to install the latest SDK by default in AwsCustomResource" + }, + "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": { + "recommendedValue": true, + "explanation": "Use unique resource name for Database Proxy" + }, + "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": { + "recommendedValue": true, + "explanation": "Remove CloudWatch alarms from deployment group" + }, + "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": { + "recommendedValue": true, + "explanation": "Include authorizer configuration in the calculation of the API deployment logical ID." + }, + "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": { + "recommendedValue": true, + "explanation": "Define user data for a launch template by default when a machine image is provided." + }, + "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": { + "recommendedValue": true, + "explanation": "SecretTargetAttachments uses the ResourcePolicy of the attached Secret." + }, + "@aws-cdk/aws-redshift:columnId": { + "recommendedValue": true, + "explanation": "Whether to use an ID to track Redshift column changes" + }, + "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": { + "recommendedValue": true, + "explanation": "Enable AmazonEMRServicePolicy_v2 managed policies" + }, + "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": { + "recommendedValue": true, + "explanation": "Restrict access to the VPC default security group" + }, + "@aws-cdk/aws-apigateway:requestValidatorUniqueId": { + "recommendedValue": true, + "explanation": "Generate a unique id for each RequestValidator added to a method" + }, + "@aws-cdk/aws-kms:aliasNameRef": { + "recommendedValue": true, + "explanation": "KMS Alias name and keyArn will have implicit reference to KMS Key" + }, + "@aws-cdk/aws-kms:applyImportedAliasPermissionsToPrincipal": { + "recommendedValue": true, + "explanation": "Enable grant methods on Aliases imported by name to use kms:ResourceAliases condition" + }, + "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": { + "recommendedValue": true, + "explanation": "Generate a launch template when creating an AutoScalingGroup" + }, + "@aws-cdk/core:includePrefixInUniqueNameGeneration": { + "recommendedValue": true, + "explanation": "Include the stack prefix in the stack name generation process" + }, + "@aws-cdk/aws-efs:denyAnonymousAccess": { + "recommendedValue": true, + "explanation": "EFS denies anonymous clients accesses" + }, + "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": { + "recommendedValue": true, + "explanation": "Enables support for Multi-AZ with Standby deployment for opensearch domains" + }, + "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": { + "recommendedValue": true, + "explanation": "Enables aws-lambda-nodejs.Function to use the latest available NodeJs runtime as the default" + }, + "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": { + "recommendedValue": true, + "explanation": "When enabled, mount targets will have a stable logicalId that is linked to the associated subnet." + }, + "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": { + "recommendedValue": true, + "explanation": "When enabled, a scope of InstanceParameterGroup for AuroraClusterInstance with each parameters will change." + }, + "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": { + "recommendedValue": true, + "explanation": "When enabled, will always use the arn for identifiers for CfnSourceApiAssociation in the GraphqlApi construct rather than id." + }, + "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": { + "recommendedValue": true, + "explanation": "When enabled, creating an RDS database cluster from a snapshot will only render credentials for snapshot credentials." + }, + "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": { + "recommendedValue": true, + "explanation": "When enabled, the CodeCommit source action is using the default branch name 'main'." + }, + "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": { + "recommendedValue": true, + "explanation": "When enabled, the logical ID of a Lambda permission for a Lambda action includes an alarm ID." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default value for crossAccountKeys to false." + }, + "@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default pipeline type to V2." + }, + "@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": { + "recommendedValue": true, + "explanation": "When enabled, IAM Policy created from KMS key grant will reduce the resource scope to this key only." + }, + "@aws-cdk/pipelines:reduceAssetRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from PipelineAssetsFileRole trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-eks:nodegroupNameAttribute": { + "recommendedValue": true, + "explanation": "When enabled, nodegroupName attribute of the provisioned EKS NodeGroup will not have the cluster name prefix." + }, + "@aws-cdk/aws-eks:useNativeOidcProvider": { + "recommendedValue": true, + "explanation": "When enabled, EKS V2 clusters will use the native OIDC provider resource AWS::IAM::OIDCProvider instead of creating the OIDCProvider with a custom resource (iam.OpenIDConnectProvider)." + }, + "@aws-cdk/aws-ec2:ebsDefaultGp3Volume": { + "recommendedValue": true, + "explanation": "When enabled, the default volume type of the EBS volume will be GP3" + }, + "@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": { + "recommendedValue": true, + "explanation": "When enabled, remove default deployment alarm settings" + }, + "@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": { + "recommendedValue": false, + "explanation": "When enabled, the custom resource used for `AwsCustomResource` will configure the `logApiResponseData` property as true by default" + }, + "@aws-cdk/aws-s3:keepNotificationInImportedBucket": { + "recommendedValue": false, + "explanation": "When enabled, Adding notifications to a bucket in the current stack will not remove notification from imported stack." + }, + "@aws-cdk/aws-stepfunctions-tasks:useNewS3UriParametersForBedrockInvokeModelTask": { + "recommendedValue": true, + "explanation": "When enabled, use new props for S3 URI field in task definition of state machine for bedrock invoke model.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:explicitStackTags": { + "recommendedValue": true, + "explanation": "When enabled, stack tags need to be assigned explicitly on a Stack." + }, + "@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": { + "recommendedValue": true, + "explanation": "When enabled, we will only grant the necessary permissions when users specify cloudwatch log group through logConfiguration" + }, + "@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": { + "recommendedValue": true, + "explanation": "When enabled will allow you to specify a resource policy per replica, and not copy the source table policy to all replicas" + }, + "@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": { + "recommendedValue": true, + "explanation": "When enabled, initOptions.timeout and resourceSignalTimeout values will be summed together." + }, + "@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": { + "recommendedValue": true, + "explanation": "When enabled, a Lambda authorizer Permission created when using GraphqlApi will be properly scoped with a SourceArn." + }, + "@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": { + "recommendedValue": true, + "explanation": "When enabled, the value of property `instanceResourceId` in construct `DatabaseInstanceReadReplica` will be set to the correct value which is `DbiResourceId` instead of currently `DbInstanceArn`" + }, + "@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": { + "recommendedValue": true, + "explanation": "When enabled, CFN templates added with `cfn-include` will error if the template contains Resource Update or Create policies with CFN Intrinsics that include non-primitive values." + }, + "@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": { + "recommendedValue": true, + "explanation": "When enabled, both `@aws-sdk` and `@smithy` packages will be excluded from the Lambda Node.js 18.x runtime to prevent version mismatches in bundled applications." + }, + "@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": { + "recommendedValue": true, + "explanation": "When enabled, the resource of IAM Run Ecs policy generated by SFN EcsRunTask will reference the definition, instead of constructing ARN." + }, + "@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": { + "recommendedValue": true, + "explanation": "When enabled, the BastionHost construct will use the latest Amazon Linux 2023 AMI, instead of Amazon Linux 2." + }, + "@aws-cdk/core:aspectStabilization": { + "recommendedValue": true, + "explanation": "When enabled, a stabilization loop will be run when invoking Aspects during synthesis.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": { + "recommendedValue": true, + "explanation": "When enabled, use a new method for DNS Name of user pool domain target without creating a custom resource." + }, + "@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": { + "recommendedValue": true, + "explanation": "When enabled, the default security group ingress rules will allow IPv6 ingress from anywhere" + }, + "@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": { + "recommendedValue": true, + "explanation": "When enabled, the default behaviour of OIDC provider will reject unauthorized connections" + }, + "@aws-cdk/core:enableAdditionalMetadataCollection": { + "recommendedValue": true, + "explanation": "When enabled, CDK will expand the scope of usage data collected to better inform CDK development and improve communication for security concerns and emerging issues." + }, + "@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": { + "recommendedValue": false, + "explanation": "[Deprecated] When enabled, Lambda will create new inline policies with AddToRolePolicy instead of adding to the Default Policy Statement" + }, + "@aws-cdk/aws-s3:setUniqueReplicationRoleName": { + "recommendedValue": true, + "explanation": "When enabled, CDK will automatically generate a unique role name that is used for s3 object replication." + }, + "@aws-cdk/pipelines:reduceStageRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from Stage addActions trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-events:requireEventBusPolicySid": { + "recommendedValue": true, + "explanation": "When enabled, grantPutEventsTo() will use resource policies with Statement IDs for service principals." + }, + "@aws-cdk/core:aspectPrioritiesMutating": { + "recommendedValue": true, + "explanation": "When set to true, Aspects added by the construct library on your behalf will be given a priority of MUTATING." + }, + "@aws-cdk/aws-dynamodb:retainTableReplica": { + "recommendedValue": true, + "explanation": "When enabled, table replica will be default to the removal policy of source table unless specified otherwise." + }, + "@aws-cdk/cognito:logUserPoolClientSecretValue": { + "recommendedValue": false, + "explanation": "When disabled, the value of the user pool client secret will not be logged in the custom resource lambda function logs." + }, + "@aws-cdk/pipelines:reduceCrossAccountActionRoleTrustScope": { + "recommendedValue": true, + "explanation": "When enabled, scopes down the trust policy for the cross-account action role", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2": { + "recommendedValue": true, + "explanation": "When enabled, the resultWriterV2 property of DistributedMap will be used insted of resultWriter" + }, + "@aws-cdk/s3-notifications:addS3TrustKeyPolicyForSnsSubscriptions": { + "recommendedValue": true, + "explanation": "Add an S3 trust policy to a KMS key resource policy for SNS subscriptions." + }, + "@aws-cdk/aws-ec2:requirePrivateSubnetsForEgressOnlyInternetGateway": { + "recommendedValue": true, + "explanation": "When enabled, the EgressOnlyGateway resource is only created if private subnets are defined in the dual-stack VPC." + }, + "@aws-cdk/aws-ec2-alpha:useResourceIdForVpcV2Migration": { + "recommendedValue": false, + "explanation": "When enabled, use resource IDs for VPC V2 migration" + }, + "@aws-cdk/aws-s3:publicAccessBlockedByDefault": { + "recommendedValue": true, + "explanation": "When enabled, setting any combination of options for BlockPublicAccess will automatically set true for any options not defined." + }, + "@aws-cdk/aws-lambda:useCdkManagedLogGroup": { + "recommendedValue": true, + "explanation": "When enabled, CDK creates and manages loggroup for the lambda function" + }, + "@aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault": { + "recommendedValue": true, + "explanation": "When enabled, Network Load Balancer will be created with a security group by default." + }, + "@aws-cdk/aws-stepfunctions-tasks:httpInvokeDynamicJsonPathEndpoint": { + "recommendedValue": true, + "explanation": "When enabled, allows using a dynamic apiEndpoint with JSONPath format in HttpInvoke tasks.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:uniqueTargetGroupId": { + "recommendedValue": true, + "explanation": "When enabled, ECS patterns will generate unique target group IDs to prevent conflicts during load balancer replacement" + }, + "@aws-cdk/aws-route53-patterns:useDistribution": { + "recommendedValue": true, + "explanation": "Use the `Distribution` resource instead of `CloudFrontWebDistribution`" + }, + "@aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0": { + "recommendedValue": true, + "explanation": "Use cloudfront-js-2.0 as the default runtime for CloudFront Functions" + }, + "@aws-cdk/aws-elasticloadbalancingv2:usePostQuantumTlsPolicy": { + "recommendedValue": true, + "explanation": "When enabled, HTTPS/TLS listeners use post-quantum TLS policy by default" + }, + "@aws-cdk/core:automaticL1Traits": { + "recommendedValue": true, + "explanation": "Automatically use the default L1 traits for L1 constructs`", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-batch:defaultToAL2023": { + "recommendedValue": true, + "explanation": "Use AL2023 as the default imageType for EC2 Batch compute environments instead of the deprecated AL2" + }, + "@aws-cdk/aws-eks:defaultToAL2023": { + "recommendedValue": true, + "explanation": "Use AL2023 as the default AMI type for EKS managed node groups using non-GPU instance types instead of the deprecated AL2" + }, + "@aws-cdk/core:annotationsInValidationReport": { + "recommendedValue": true, + "explanation": "Include construct annotations (warnings and errors) in the policy validation report" + }, + "@aws-cdk/core:defaultCrossStackReferences": { + "recommendedValue": "weak", + "explanation": "Controls whether cross-stack references are strong, weak, or both", + "unconfiguredBehavesLike": { + "v2": "strong" + } + }, + "@aws-cdk/core:validateAgainstDefaultRules": { + "recommendedValue": true, + "explanation": "Treat CloudFormation Validate findings as errors" + }, + "@aws-cdk/aws-ecs:removeEmptyLoadBalancers": { + "recommendedValue": true, + "explanation": "Render an empty `LoadBalancers` array on an ECS service that has no target groups" + } + } + } + } + }, + "minimumCliVersion": "2.1144.0" +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/arm64Builder.test.ts b/src/core/project/backends/cdk/arm64Builder.test.ts new file mode 100644 index 0000000000..b70bc3bb67 --- /dev/null +++ b/src/core/project/backends/cdk/arm64Builder.test.ts @@ -0,0 +1,337 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildxDriverWarning, checkArm64Builder } from "./arm64Builder"; + +describe("local container builder prerequisites", () => { + const projects: string[] = []; + const projectDirectory = () => { + const path = mkdtempSync(join(tmpdir(), "agentcore-builder-test-")); + projects.push(path); + return path; + }; + afterEach(() => { + for (const path of projects.splice(0)) rmSync(path, { recursive: true, force: true }); + }); + + test("accepts a native Linux ARM64 daemon without probing or creating builders", async () => { + const commands: string[][] = []; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + options.onOutput?.('{"OSType":"linux","Architecture":"aarch64"}'); + }, + "/project", + "/tools/docker-wrapper", + ); + // buildx is still inspected, for its driver, but nothing is built. + expect(commands).toEqual([ + ["/tools/docker-wrapper", "info", "--format", "{{json .}}"], + ["/tools/docker-wrapper", "buildx", "inspect"], + ]); + }); + test("accepts formatted daemon information alongside Finch stderr diagnostics", async () => { + const commands: string[][] = []; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + options.onOutput?.('time="now" level=warning msg="config {defaults}"\n'); + options.onOutput?.('{"OSType":"linux","Architecture":"arm64"}\n'); + options.onOutput?.('{"diagnostic":"after daemon output"}\n'); + }, + "/project", + "finch", + ); + expect(commands.map((command) => command[1])).toEqual(["info", "buildx"]); + }); + + test.each(["linux/arm64", "linux/arm64/v8", "linux/arm64*"])( + "accepts advertised %s support without building or provisioning a builder", + async (platform) => { + const commands: string[][] = []; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + options.onOutput?.( + command[1] === "info" + ? '{"OSType":"linux","Architecture":"x86_64"}' + : `Platforms: linux/amd64*, ${platform}\n`, + ); + }, + "/project", + "docker", + ); + expect(commands).toEqual([ + ["docker", "info", "--format", "{{json .}}"], + ["docker", "buildx", "inspect"], + ]); + }, + ); + + test.each(["unsupported buildx", "unadvertised ARM64", "failed buildx with partial output"])( + "checks real ARM64 execution for a compatible builder with %s", + async (capabilities) => { + const commands: string[][] = []; + const project = projectDirectory(); + let context = ""; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + if (command[1] === "info") { + options.onOutput?.('{"OSType":"linux","Architecture":"x86_64"}'); + } else if (command[1] === "buildx") { + if (capabilities === "unadvertised ARM64") { + options.onOutput?.("Platforms: linux/amd64\n"); + return; + } + if (capabilities === "failed buildx with partial output") { + options.onOutput?.("Platforms: linux/arm64\n"); + } + throw new Error('unknown command "buildx"'); + } else if (command[1] === "build") { + context = options.cwd; + expect(context.startsWith(join(project, "agentcore", ".cli", "arm64-probe-"))).toBe( + true, + ); + expect(readFileSync(join(context, "Dockerfile"), "utf8")).toBe( + 'FROM scratch\nCOPY --chmod=0555 arm64-check /arm64-check\nRUN ["/arm64-check"]\n', + ); + const executable = readFileSync(join(context, "arm64-check")); + expect(executable.subarray(0, 4).toString("hex")).toBe("7f454c46"); + expect(executable.readUInt16LE(18)).toBe(183); // ELF machine: AArch64. + expect(options.signal).toBeInstanceOf(AbortSignal); + expect(existsSync(join(context, "output"))).toBe(true); + writeFileSync(join(context, "output", "arm64-check"), executable); + } else { + throw new Error(`Unexpected builder command: ${command.join(" ")}`); + } + }, + project, + "/tools/finch wrapper", + ); + expect(commands[2]).toEqual([ + "/tools/finch wrapper", + "build", + "--platform", + "linux/arm64", + "--network", + "none", + "--no-cache", + "--output", + "type=local,dest=output", + "--file", + "Dockerfile", + ".", + ]); + expect(existsSync(context)).toBe(false); + }, + ); + + test("refuses an unavailable daemon with an actionable error", async () => { + await expect( + checkArm64Builder( + async () => { + throw new Error("daemon denied"); + }, + "/project", + "docker", + ), + ).rejects.toThrow("daemon or VM is running"); + }); + + test("refuses an x86 builder without Linux ARM64 capability", async () => { + const project = projectDirectory(); + let context = ""; + const buildError = new Error("exec format error"); + await expect( + checkArm64Builder( + async (command, options) => { + if (command[1] === "build") { + context = options.cwd; + throw buildError; + } + options.onOutput?.( + command[1] === "info" + ? '{"OSType":"linux","Architecture":"x86_64"}' + : "Platforms: linux/amd64\n", + ); + }, + project, + "docker", + ), + ).rejects.toThrow("cannot build Linux ARM64 images"); + expect(context).not.toBe(""); + expect(existsSync(context)).toBe(false); + }); + + test("reports a failed Finch build and cleans up its context", async () => { + const project = projectDirectory(); + let context = ""; + const buildError = new Error("configured BuildKit is unavailable"); + let caught: unknown; + try { + await checkArm64Builder( + async (command, options) => { + if (command[1] === "info") { + options.onOutput?.('{"OSType":"linux","Architecture":"x86_64"}'); + } else if (command[1] === "buildx") { + throw new Error('unknown command "buildx"'); + } else { + context = options.cwd; + throw buildError; + } + }, + project, + "finch", + ); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain("cannot build Linux ARM64 images"); + expect((caught as Error).message).toContain("binfmt"); + expect((caught as Error).cause).toBe(buildError); + expect(context).not.toBe(""); + expect(existsSync(context)).toBe(false); + }); + + test("falls through to the later checks when daemon information is unreadable", async () => { + const commands: string[][] = []; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + options.onOutput?.(command[1] === "info" ? "not JSON" : "Platforms: linux/arm64\n"); + }, + "/project", + "finch", + ); + expect(commands.map((command) => command[1])).toEqual(["info", "buildx"]); + }); + + test("accepts a native ARM64 Podman host from its host.os/host.arch info", async () => { + const commands: string[][] = []; + await checkArm64Builder( + async (command, options) => { + commands.push(command); + options.onOutput?.(JSON.stringify({ host: { os: "linux", arch: "arm64" } })); + }, + "/project", + "podman", + ); + expect(commands).toEqual([["podman", "info", "--format", "{{json .}}"]]); + }); + + test("probes an x86 Podman host without calling buildx", async () => { + const commands: string[][] = []; + const project = projectDirectory(); + await checkArm64Builder( + async (command, options) => { + commands.push(command); + if (command[1] === "info") { + options.onOutput?.(JSON.stringify({ host: { os: "linux", arch: "amd64" } })); + } + }, + project, + "/usr/bin/podman", + ); + expect(commands.map((command) => command[1])).toEqual(["info", "build"]); + }); + + test("bounds the info and buildx queries with a timeout", async () => { + const signals: (AbortSignal | undefined)[] = []; + await checkArm64Builder( + async (command, options) => { + signals.push(options.signal); + options.onOutput?.( + command[1] === "info" + ? '{"OSType":"linux","Architecture":"x86_64"}' + : "Platforms: linux/arm64\n", + ); + }, + "/project", + "docker", + ); + expect(signals).toHaveLength(2); + for (const signal of signals) expect(signal).toBeInstanceOf(AbortSignal); + }); + + test("reports what it found when an x86 host cannot run ARM64", async () => { + const project = projectDirectory(); + const error = await checkArm64Builder( + async (command, options) => { + if (command[1] === "info") { + options.onOutput?.('{"OSType":"linux","Architecture":"x86_64"}'); + } else if (command[1] === "buildx") { + options.onOutput?.( + "Name: multiarch-builder\nDriver: docker-container\n" + + "Nodes:\nName: multiarch-builder0\nStatus: inactive\nPlatforms:\n", + ); + } else { + options.onOutput?.("#5 [2/2] RUN /arm64-check\n"); + options.onOutput?.("exec /arm64-check: exec format error\n"); + throw new Error("exit code 1"); + } + }, + project, + "docker", + ).catch((caught: unknown) => caught as Error); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain("daemon linux/x86_64"); + expect(message).toContain( + "buildx builder 'multiarch-builder' (driver docker-container) does not list linux/arm64", + ); + expect(message).toContain("ARM64 test build failed: exec format error"); + expect(message).toContain("binfmt"); + }); + + test("reports the probe's last output line when the reason is not exec format error", async () => { + const project = projectDirectory(); + const error = await checkArm64Builder( + async (command, options) => { + if (command[1] === "info") options.onOutput?.("not JSON"); + else if (command[1] === "buildx") throw new Error("unknown command"); + else { + options.onOutput?.("starting\nbuildkit is not running\n"); + throw new Error("exit code 1"); + } + }, + project, + "finch", + ).catch((caught: unknown) => caught as Error); + const message = (error as Error).message; + expect(message).toContain("daemon architecture unknown"); + expect(message).toContain("no buildx"); + expect(message).toContain("ARM64 test build failed: buildkit is not running"); + }); + + test("reports the active buildx builder and its driver", async () => { + const report = await checkArm64Builder( + async (command, options) => { + options.onOutput?.( + command[1] === "info" + ? '{"OSType":"linux","Architecture":"aarch64"}' + : "Name: multiarch-builder\nDriver: docker-container\nNodes:\nName: node0\n", + ); + }, + "/project", + "docker", + ); + expect(report).toEqual({ buildx: { name: "multiarch-builder", driver: "docker-container" } }); + }); +}); + +describe("buildxDriverWarning", () => { + const containerDriver = { buildx: { name: "multiarch-builder", driver: "docker-container" } }; + test("warns about a non-docker driver and suggests the default builder", () => { + const warning = buildxDriverWarning(containerDriver); + expect(warning).toContain("'multiarch-builder'"); + expect(warning).toContain("docker-container"); + expect(warning).toContain("docker buildx use default"); + }); + test("stays quiet for the docker driver and without buildx", () => { + expect(buildxDriverWarning({ buildx: { name: "default", driver: "docker" } })).toBeUndefined(); + expect(buildxDriverWarning({})).toBeUndefined(); + }); +}); diff --git a/src/core/project/backends/cdk/arm64Builder.ts b/src/core/project/backends/cdk/arm64Builder.ts new file mode 100644 index 0000000000..bd834401f1 --- /dev/null +++ b/src/core/project/backends/cdk/arm64Builder.ts @@ -0,0 +1,236 @@ +/** + * Checks that the local container builder can produce Linux ARM64 images before a + * ContainerLocal deploy. AgentCore runs ARM64 images only, and an x86 builder + * without emulation fails late (mid-deploy, after credential providers exist) or, + * worse, publishes an image that cannot start. The check never installs emulation + * or provisions a builder; it only reports what to fix. + * + * In order, the first that succeeds wins: + * 1. ` info`: a native linux/arm64 daemon builds ARM64 directly. Docker + * and Finch report OSType/Architecture; Podman reports host.os/host.arch. + * Unreadable info is not fatal: the later checks decide. + * 2. ` buildx inspect`: the active builder lists linux/arm64. + * 3. An execution probe: build a scratch image whose only step runs a tiny ARM64 + * program. This covers builders without buildx (Finch, Podman) and proves + * emulation (binfmt/QEMU) actually executes ARM64 code, not just that it is + * advertised. It uses --network none and --no-cache, so it downloads nothing. + * + * The probe's build context lives in the project's agentcore/.cli/ directory, not + * the OS temp directory: VM-backed builders (Finch, Podman machine, Docker Desktop) + * share only some host paths, typically the home directory, and on macOS the temp + * directory is outside it. agentcore/.cli/ is git-ignored and excluded from build + * contexts, and the directory is removed afterwards. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { basename, join } from "node:path"; +import { ProjectStateError } from "../../../../errors"; +import type { ProcessRunner } from "../../../../io"; + +const REMEDIATION = + "Use an ARM64 machine or CI runner, or enable ARM64 emulation for your builder " + + "(for Docker: enable buildx and install QEMU binfmt handlers, e.g. " + + "'docker run --privileged --rm tonistiigi/binfmt --install arm64'). " + + "Set CDK_DOCKER to choose a different Docker-compatible builder."; + +// The probe program: a 132-byte static Linux ELF64 executable for AArch64 with a +// single read/execute segment and entry point 0x400078. Its three instructions, +// mov x0, #0; mov x8, #93; svc #0 +// make the Linux exit(0) syscall. It needs no shell, libraries, or base image. +const ARM64_EXECUTION_PROBE = Buffer.from( + [ + "7f454c460201010000000000000000000200b700010000007800400000000000", + "4000000000000000000000000000000000000000400038000100000000000000", + "0100000005000000000000000000000000004000000000000000400000000000", + "840000000000000084000000000000000010000000000000", + "000080d2a80b80d2010000d4", + ].join(""), + "hex", +); + +/** Runs the probe; on failure, throws with the probe's output attached as `output`. */ +async function probeArm64Execution( + runner: ProcessRunner, + cwd: string, + executable: string, +): Promise { + const parent = join(cwd, "agentcore", ".cli"); + mkdirSync(parent, { recursive: true }); + const context = mkdtempSync(join(parent, "arm64-probe-")); + let output = ""; + try { + // Create the export directory ourselves so a builder running as root cannot own it. + mkdirSync(join(context, "output")); + writeFileSync(join(context, "arm64-check"), ARM64_EXECUTION_PROBE); + writeFileSync( + join(context, "Dockerfile"), + 'FROM scratch\nCOPY --chmod=0555 arm64-check /arm64-check\nRUN ["/arm64-check"]\n', + ); + await runner( + [ + executable, + "build", + "--platform", + "linux/arm64", + "--network", + "none", + "--no-cache", + "--output", + "type=local,dest=output", + "--file", + "Dockerfile", + ".", + ], + { + cwd: context, + signal: AbortSignal.timeout(60_000), + onOutput: (chunk) => { + output += chunk; + }, + }, + ); + } catch (error) { + throw Object.assign(error instanceof Error ? error : new Error(String(error)), { output }); + } finally { + rmSync(context, { recursive: true, force: true }); + } +} + +const QUERY_TIMEOUT_MS = 30_000; + +async function capture(runner: ProcessRunner, command: string[], cwd: string): Promise { + let output = ""; + await runner(command, { + cwd, + signal: AbortSignal.timeout(QUERY_TIMEOUT_MS), + onOutput: (chunk) => { + output += chunk; + }, + }); + return output; +} + +type Daemon = { os: string; arch: string }; + +/** Reads OS and architecture from Docker/Finch (OSType, Architecture) or Podman (host.os, host.arch) info. */ +function parseDaemon(info: string): Daemon | undefined { + // Output mixes stdout and stderr, and Finch can print startup lines before its + // single-line JSON, so try the whole output and then each line from the end. + for (const candidate of [info.trim(), ...info.trim().split(/\r?\n/).reverse()]) { + let value: unknown; + try { + value = JSON.parse(candidate); + } catch { + continue; + } + if (typeof value !== "object" || value === null) continue; + const record = value as Record; + if (typeof record.OSType === "string" && typeof record.Architecture === "string") { + return { os: record.OSType, arch: record.Architecture }; + } + const host = record.host as Record | undefined; + if (typeof host?.os === "string" && typeof host.arch === "string") { + return { os: host.os, arch: host.arch }; + } + } + return undefined; +} + +/** The active buildx builder, as `buildx inspect` reports it. */ +export type BuildxBuilder = { name?: string; driver?: string }; + +/** What the check learned about the builder, for the image build and its warnings. */ +export type Arm64BuilderReport = { buildx?: BuildxBuilder }; + +function parseBuildx(output: string): BuildxBuilder { + // The first Name: line is the builder; later ones name its nodes. + return { + name: /^Name:\s*(\S+)/m.exec(output)?.[1], + driver: /^Driver:\s*(\S+)/m.exec(output)?.[1], + }; +} + +/** A short reason from the probe's output, preferring the error that means "no ARM64 emulation". */ +function probeFailureReason(error: unknown): string { + const output = (error as { output?: string }).output ?? ""; + if (/exec format error/i.test(output)) return "exec format error"; + const last = output + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .pop(); + const reason = last ?? (error instanceof Error ? error.message : String(error)); + return reason.length > 200 ? `${reason.slice(0, 200)}…` : reason; +} + +/** + * Throws a {@link ProjectStateError} that says what was found and how to fix it + * unless `executable` can build Linux ARM64 images. + */ +export async function checkArm64Builder( + runner: ProcessRunner, + cwd: string, + executable: string, +): Promise { + let info: string; + try { + info = await capture(runner, [executable, "info", "--format", "{{json .}}"], cwd); + } catch { + throw new ProjectStateError( + `Cannot access the container builder '${executable}'. Check that it is installed and ` + + "its daemon or VM is running. Set CDK_DOCKER to choose a different Docker-compatible builder.", + ); + } + const daemon = parseDaemon(info); + + // Podman's `buildx` is an alias for `build` with no inspect, so it is never asked. + let buildx: BuildxBuilder | undefined; + let platforms: string[] = []; + if (!basename(executable).startsWith("podman")) { + try { + const output = await capture(runner, [executable, "buildx", "inspect"], cwd); + buildx = parseBuildx(output); + platforms = [...output.matchAll(/^\s*Platforms:\s*(.+)$/gm)].flatMap((match) => + match[1]!.split(",").map((platform) => platform.trim().replace(/\*$/, "")), + ); + } catch { + // Finch and others need not implement buildx; the probe below decides. + } + } + const report = { ...(buildx && { buildx }) }; + if (daemon?.os === "linux" && ["arm64", "aarch64"].includes(daemon.arch)) return report; + if (platforms.includes("linux/arm64") || platforms.includes("linux/arm64/v8")) return report; + + try { + await probeArm64Execution(runner, cwd, executable); + return report; + } catch (error) { + const found = [ + daemon ? `daemon ${daemon.os}/${daemon.arch}` : "daemon architecture unknown", + buildx + ? `buildx builder '${buildx.name ?? "unknown"}' (driver ${buildx.driver ?? "unknown"}) ` + + "does not list linux/arm64" + : "no buildx", + `ARM64 test build failed: ${probeFailureReason(error)}`, + ].join("; "); + throw new ProjectStateError( + `The container builder '${executable}' cannot build Linux ARM64 images, which ` + + `ContainerLocal requires. Found: ${found}. ${REMEDIATION}`, + { cause: error }, + ); + } +} + +/** + * A warning when the active Docker buildx builder's driver is not `docker`: images + * it builds may not be loaded into the local image store, so CDK's push can fail. + */ +export function buildxDriverWarning(report: Arm64BuilderReport): string | undefined { + const driver = report.buildx?.driver; + if (!driver || driver === "docker") return undefined; + const name = report.buildx?.name ?? "the active builder"; + return ( + `The active buildx builder '${name}' uses the ${driver} driver, so images it builds may not ` + + "be loaded into the local Docker image store and the CDK push can fail. " + + "Run 'docker buildx use default' to switch to the docker driver." + ); +} diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 706562788c..1fe9fdebe7 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -2,7 +2,11 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { cdkCompatibilityWarning, MINIMUM_COMPATIBLE_CDK_VERSION } from "./compatibility"; +import { + assertCdkLocalContainerSupport, + cdkCompatibilityWarning, + MINIMUM_COMPATIBLE_CDK_VERSION, +} from "./compatibility"; const tempDirectories: string[] = []; @@ -22,6 +26,25 @@ async function cdkDirectoryWith(version: unknown): Promise { } describe("cdkCompatibilityWarning", () => { + test("rejects an older package that would ignore a local harness build selection", async () => { + const directory = await cdkDirectoryWith("1.0.1"); + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await writeFile( + join(packageDirectory, "index.js"), + "exports.BuildTypeSchema = { safeParse: () => ({ success: false }) };", + ); + expect(() => assertCdkLocalContainerSupport(directory)).toThrow('supports "ContainerLocal"'); + }); + + test("accepts a supporting local or prerelease CDK package by capability", async () => { + const directory = await cdkDirectoryWith("1.0.2-rc.1"); + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await writeFile( + join(packageDirectory, "index.js"), + 'exports.BuildTypeSchema = { safeParse: value => ({ success: value === "ContainerLocal" }) }; exports.LocalContainerImageAsset = class {};', + ); + expect(() => assertCdkLocalContainerSupport(directory)).not.toThrow(); + }); test.each(["0.0.0-0", "1.0.0-rc.1", "1.0.0-rc.2"])( "warns for incompatible version %s", async (version) => { diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 3e56bf0b00..2eced4df0d 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -1,9 +1,30 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import semver from "semver"; +import { createRequire } from "node:module"; +import { ProjectStateError } from "../../../../errors"; export const MINIMUM_COMPATIBLE_CDK_VERSION = "1.0.0"; +/** Detect support directly so prereleases and local CDK packages also work. */ +export function assertCdkLocalContainerSupport(cdkDirectory: string): void { + try { + const require = createRequire(join(cdkDirectory, "package.json")); + const cdk = require("@aws/agentcore-cdk") as { + BuildTypeSchema?: { safeParse(value: string): { success: boolean } }; + LocalContainerImageAsset?: unknown; + }; + if (cdk.BuildTypeSchema?.safeParse("ContainerLocal").success && cdk.LocalContainerImageAsset) + return; + } catch { + // An old or unavailable package must never silently strip a harness build selection. + } + throw new ProjectStateError( + 'This project requires an @aws/agentcore-cdk package that supports "ContainerLocal". ' + + `Update the dependency in ${cdkDirectory} and run npm install.`, + ); +} + export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { const packagePath = join(cdkDirectory, "node_modules", "@aws", "agentcore-cdk", "package.json"); diff --git a/src/core/project/backends/cdk/localContainers.test.ts b/src/core/project/backends/cdk/localContainers.test.ts new file mode 100644 index 0000000000..b7ec268d92 --- /dev/null +++ b/src/core/project/backends/cdk/localContainers.test.ts @@ -0,0 +1,268 @@ +import { describe, expect, test } from "bun:test"; +import { HarnessSpecSchema } from "../../../../projectSchemas/harness"; +import { ProjectRuntimeSchema } from "../../../../projectSchemas/runtime"; +import type { WorkloadBuildMode } from "../../../../handlers/project/types"; +import { assertSupportedBuildTransitions, type DeployedTemplate } from "./localContainers"; + +describe("container configuration", () => { + const networkConfig = { + subnets: ["subnet-0123456789abcdef0"], + securityGroups: Array.from({ length: 6 }, (_, index) => `sg-0123456789abcde${index}0`), + }; + test("local runtime builds use workload networking limits rather than CodeBuild requirements", () => { + expect( + ProjectRuntimeSchema.safeParse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + dockerfile: "Dockerfile", + networkMode: "VPC", + networkConfig, + }).success, + ).toBe(true); + }); + test("local harness builds accept workload networking without a CodeBuild VPC ID", () => { + expect( + HarnessSpecSchema.safeParse({ + name: "agent", + model: { provider: "bedrock", modelId: "test-model" }, + build: "ContainerLocal", + dockerfile: "Dockerfile", + networkMode: "VPC", + networkConfig, + }).success, + ).toBe(true); + }); + test.each(["Container", "ContainerLocal"])( + "rejects explicit %s build settings for a prebuilt harness image", + (build) => { + expect( + HarnessSpecSchema.safeParse({ + name: "agent", + model: { provider: "bedrock", modelId: "test-model" }, + build, + containerUri: "111122223333.dkr.ecr.us-east-1.amazonaws.com/image:latest", + }).success, + ).toBe(false); + }, + ); +}); + +describe("assertSupportedBuildTransitions", () => { + test.each([ + ["Container", "ContainerLocal"], + ["ContainerLocal", "Container"], + ] as const satisfies [string, WorkloadBuildMode][])( + "rejects a deployed %s to %s transition", + (before, after) => { + for (const kind of ["runtime", "harness"]) { + const key = `${kind}/agent`; + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { [key]: before } } }, + { [key]: after }, + "example", + "default", + ), + ).toThrow("between Container and ContainerLocal is not supported"); + } + }, + ); + test.each([ + ["CodeZip", "ContainerLocal"], + ["ContainerLocal", "CodeZip"], + ["Managed", "ContainerLocal"], + ] as const satisfies [string, WorkloadBuildMode][])( + "allows a deployed %s to %s transition", + (before, after) => { + const key = "runtime/agent"; + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { [key]: before } } }, + { [key]: after }, + "example", + "default", + ), + ).not.toThrow(); + }, + ); + test("allows unchanged local workloads and new workloads in an existing mixed project", () => { + expect(() => + assertSupportedBuildTransitions( + { + Metadata: { + "agentcore:builds": { + "runtime/existing": "Container", + "harness/local": "ContainerLocal", + }, + }, + }, + { + "runtime/existing": "Container", + "harness/local": "ContainerLocal", + "runtime/new": "ContainerLocal", + }, + "example", + "default", + ), + ).not.toThrow(); + }); + test.each(["runtime", "harness"] as const)( + "detects pre-feature %s templates without local state", + (kind) => { + const previous: DeployedTemplate = { + Resources: { + Workload: { + Type: + kind === "runtime" + ? "AWS::BedrockAgentCore::Runtime" + : "AWS::BedrockAgentCore::Harness", + Properties: { + [kind === "runtime" ? "AgentRuntimeName" : "HarnessName"]: "example_prod_us_agent", + [kind === "runtime" ? "AgentRuntimeArtifact" : "EnvironmentArtifact"]: { + ContainerConfiguration: { ContainerUri: "image" }, + }, + }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { [`${kind}/agent` as const]: "ContainerLocal" as const }, + "example", + "prod-us", + ), + ).toThrow("between Container and ContainerLocal is not supported"); + }, + ); + test("allows a pre-feature CodeZip runtime to become ContainerLocal", () => { + const previous: DeployedTemplate = { + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { + AgentRuntimeName: "example_default_agent", + AgentRuntimeArtifact: { CodeConfiguration: { Code: {} } }, + }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "ContainerLocal" }, + "example", + "default", + ), + ).not.toThrow(); + }); + test("recognizes v0 target-less physical names", () => { + const previous: DeployedTemplate = { + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { + AgentRuntimeName: "example_agent", + AgentRuntimeArtifact: { ContainerConfiguration: { ContainerUri: "image" } }, + }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "ContainerLocal" }, + "example", + undefined, + ), + ).toThrow("Cannot change runtime/agent from Container to ContainerLocal"); + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "Container" }, + "example", + undefined, + ), + ).not.toThrow(); + }); + test("treats workloads absent from a legacy template as new", () => { + const previous: DeployedTemplate = { + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { AgentRuntimeName: "example_default_other" }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "ContainerLocal", "harness/agent": "ContainerLocal" }, + "example", + "default", + ), + ).not.toThrow(); + }); + test("trusts recorded metadata over legacy name matching", () => { + const previous: DeployedTemplate = { + Metadata: { "agentcore:builds": { "runtime/agent": "ContainerLocal" } }, + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { AgentRuntimeName: "example_default_agent" }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "ContainerLocal" }, + "example", + "default", + ), + ).not.toThrow(); + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "Container" }, + "example", + "default", + ), + ).toThrow("Cannot change runtime/agent from ContainerLocal to Container"); + }); + test("fails closed on malformed deployed build metadata", () => { + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": [] } }, + {}, + "example", + "default", + ), + ).toThrow("invalid build metadata"); + }); + test("rejects adopting an existing legacy role-only Harness into local mode", () => { + const previous: DeployedTemplate = { + Outputs: { + HarnessRole: { Export: { Name: "AgentCore-example-default-Harness-assistant-RoleArn" } }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "harness/assistant": "ContainerLocal" }, + "example", + "default", + ), + ).toThrow("between Container and ContainerLocal is not supported"); + expect(() => + assertSupportedBuildTransitions( + previous, + { "harness/assistant": "Container" }, + "example", + "default", + ), + ).not.toThrow(); + }); +}); diff --git a/src/core/project/backends/cdk/localContainers.ts b/src/core/project/backends/cdk/localContainers.ts new file mode 100644 index 0000000000..3764514f7d --- /dev/null +++ b/src/core/project/backends/cdk/localContainers.ts @@ -0,0 +1,144 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parse } from "yaml"; +import { HarnessYamlSchema } from "../../../../projectSchemas/harness"; +import type { + Project, + WorkloadBuildMode, + WorkloadBuilds, + WorkloadKey, +} from "../../../../handlers/project/types"; +import { ProjectStateError } from "../../../../errors"; + +/** + * Resolves every workload's build mode from agentcore.json and each harness.yaml. + * It reads the harness files, so resolve once per command and pass the result on. + * A Harness is Managed without a Dockerfile or image, ContainerUri with an image. + */ +export function resolveWorkloadBuilds(project: Project): WorkloadBuilds { + const builds: WorkloadBuilds = {}; + for (const runtime of project.spec.runtimes) builds[`runtime/${runtime.name}`] = runtime.build; + for (const entry of project.spec.harnesses) { + const path = join(project.rootPath, entry.path, "harness.yaml"); + if (!existsSync(path)) continue; + const harness = HarnessYamlSchema.parse(parse(readFileSync(path, "utf8"))); + builds[`harness/${harness.name}`] = + harness.build ?? + (harness.dockerfile ? "Container" : harness.containerUri ? "ContainerUri" : "Managed"); + } + return builds; +} + +/** The workload entries of a build map, with their typed keys. */ +export function workloadEntries(builds: WorkloadBuilds): [WorkloadKey, WorkloadBuildMode][] { + return Object.entries(builds) as [WorkloadKey, WorkloadBuildMode][]; +} + +export function hasLocalContainerBuilds(builds: WorkloadBuilds): boolean { + return Object.values(builds).includes("ContainerLocal"); +} + +type TemplateResource = { Type?: string; Properties?: Record }; +export type DeployedTemplate = { + Metadata?: Record; + Resources?: Record; + Outputs?: Record; +}; + +/** + * Finds the build mode a workload was deployed with. Templates synthesized by a + * CDK package that supports ContainerLocal record it in `agentcore:builds`. Older + * templates predate ContainerLocal, so a workload found in them is either a + * container image (Container) or not. Returns undefined when it was not deployed. + */ +function deployedBuild( + template: DeployedTemplate, + recorded: Record | undefined, + key: string, + projectName: string, + targetName: string | undefined, +): string | undefined { + const value = recorded?.[key]; + if (value !== undefined) { + if (typeof value !== "string") { + throw new ProjectStateError(`Cannot verify the deployed build mode for ${key}.`); + } + return value; + } + + const [kind, name] = key.split("/") as [string, string]; + // Physical names are __; v0 projects omit the target. + const physicalName = [ + projectName, + ...(targetName ? [targetName.replace(/-/g, "_")] : []), + name, + ].join("_"); + const [type, nameProperty] = + kind === "runtime" + ? ["AWS::BedrockAgentCore::Runtime", "AgentRuntimeName"] + : ["AWS::BedrockAgentCore::Harness", "HarnessName"]; + const found = Object.values(template.Resources ?? {}).find( + (resource) => resource.Type === type && resource.Properties?.[nameProperty] === physicalName, + ); + if (found) { + const artifact = found.Properties?.[ + kind === "runtime" ? "AgentRuntimeArtifact" : "EnvironmentArtifact" + ] as { ContainerConfiguration?: unknown } | undefined; + if (artifact?.ContainerConfiguration !== undefined) return "Container"; + return kind === "runtime" ? "CodeZip" : "Managed"; + } + + // Older vended apps managed the Harness outside CloudFormation; its execution + // role output still identifies a deployed workload. Its image source is not in + // the template, so assume a container build and fail closed. + if (kind === "harness") { + const roleExport = `-Harness-${name.replaceAll("_", "-")}-RoleArn`; + const legacyHarness = Object.values(template.Outputs ?? {}).some((output) => + JSON.stringify(output.Export?.Name)?.includes(roleExport), + ); + if (legacyHarness) return "Container"; + } + return undefined; +} + +/** + * Rejects switching a deployed workload between Container (CodeBuild) and + * ContainerLocal, in either direction. Other changes, such as CodeZip to + * ContainerLocal, are left to CloudFormation. The deployed + * template is authoritative: editing agentcore.json or deleting deployed-state.json + * must not permit a build-mode migration. + */ +export function assertSupportedBuildTransitions( + template: DeployedTemplate, + builds: WorkloadBuilds, + projectName: string, + targetName: string | undefined, +): void { + const recorded = template.Metadata?.["agentcore:builds"]; + if ( + recorded !== undefined && + (typeof recorded !== "object" || recorded === null || Array.isArray(recorded)) + ) { + throw new ProjectStateError( + "Cannot verify build modes: the deployed template has invalid build metadata.", + ); + } + for (const [key, desired] of Object.entries(builds)) { + const deployed = deployedBuild( + template, + recorded as Record | undefined, + key, + projectName, + targetName, + ); + if (deployed === undefined) continue; + const pair = new Set([deployed, desired]); + if (pair.has("Container") && pair.has("ContainerLocal")) { + throw new ProjectStateError( + `Cannot change ${key} from ${deployed} to ${desired}. ` + + "Switching a deployed workload between Container and ContainerLocal is not supported. " + + "Keep the deployed build mode or add a workload with a new name.", + ); + } + } +} diff --git a/src/core/project/backends/cdk/localImages.test.ts b/src/core/project/backends/cdk/localImages.test.ts new file mode 100644 index 0000000000..8c7768564e --- /dev/null +++ b/src/core/project/backends/cdk/localImages.test.ts @@ -0,0 +1,133 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { FsReadWriteJson } from "../../../../io"; +import { createSilentLogger } from "../../../../testing"; +import { localImageBuilds } from "./localImages"; + +const json = new FsReadWriteJson({ logger: createSilentLogger() }); +// A real assembly synthesized by @aws/agentcore-cdk; see __fixtures__/local-images/README.md. +const FIXTURE = join(import.meta.dir, "__fixtures__", "local-images"); +const ORDERS_HASH = "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e"; +const ASSISTANT_HASH = "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624"; +const FIXTURE_BUILDS = { + "runtime/orders": "ContainerLocal", + "runtime/billing": "Container", + "harness/assistant": "ContainerLocal", +} as const; + +const directories: string[] = []; +afterEach(() => Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true })))); + +/** A writable copy of the fixture assembly. */ +async function fixtureCopy(): Promise { + const directory = await mkdtemp(join(tmpdir(), "agentcore-local-images-")); + directories.push(directory); + await cp(FIXTURE, directory, { recursive: true }); + return directory; +} + +async function editJson(path: string, edit: (value: Record) => void): Promise { + const value = JSON.parse(await readFile(path, "utf8")) as Record; + edit(value); + await writeFile(path, JSON.stringify(value)); +} + +describe("localImageBuilds", () => { + test("finds the ContainerLocal images of a real synthesized assembly", async () => { + // manifest.json references tree.json and a *.metadata.json the fixture omits. + const images = await localImageBuilds(json, FIXTURE, "Fixture", FIXTURE_BUILDS); + expect(images.map((image) => image.resource).sort()).toEqual([ + "harness/assistant", + "runtime/orders", + ]); + const orders = images.find((image) => image.resource === "runtime/orders")!; + expect(orders.directory).toBe(join(FIXTURE, `asset.${ORDERS_HASH}`)); + expect(orders.tag).toBe(`agentcore-local/fixture-runtime-orders:${ORDERS_HASH}`); + expect(orders.command("docker")).toEqual([ + "docker", + "build", + "--platform", + "linux/arm64", + "--tag", + orders.tag, + "--file", + "Dockerfile", + ".", + ]); + const assistant = images.find((image) => image.resource === "harness/assistant")!; + expect(assistant.directory).toBe(join(FIXTURE, `asset.${ASSISTANT_HASH}`)); + expect(assistant.command("finch")).toContain("linux/arm64"); + }); + + test("ignores asset manifests and templates no current stack lists", async () => { + const directory = await fixtureCopy(); + // Left by a synth before a target existed, when the stack had another name. + await writeFile( + join(directory, "AgentCore-Old.assets.json"), + JSON.stringify({ + version: "36.0.0", + files: {}, + dockerImages: { stale: { source: { directory: "asset.stale" } } }, + }), + ); + await writeFile( + join(directory, "AgentCore-Old.template.json"), + JSON.stringify({ Metadata: { "agentcore:localImages": { "runtime/orders": "stale" } } }), + ); + const images = await localImageBuilds(json, directory, "Fixture", FIXTURE_BUILDS); + expect(images.map((image) => image.tag).sort()).toEqual([ + `agentcore-local/fixture-harness-assistant:${ASSISTANT_HASH}`, + `agentcore-local/fixture-runtime-orders:${ORDERS_HASH}`, + ]); + }); + + test("fails when a ContainerLocal workload has no recorded image", async () => { + const directory = await fixtureCopy(); + await editJson(join(directory, "AgentCore-Fixture.template.json"), (template) => { + delete template.Metadata["agentcore:localImages"]["harness/assistant"]; + }); + await expect(localImageBuilds(json, directory, "Fixture", FIXTURE_BUILDS)).rejects.toThrow( + /no local image for harness\/assistant.*@aws\/agentcore-cdk package is too old/, + ); + }); + + test("fails when a recorded image is missing from the asset manifest", async () => { + const directory = await fixtureCopy(); + await editJson(join(directory, "AgentCore-Fixture.assets.json"), (manifest) => { + delete manifest.dockerImages[ORDERS_HASH]; + }); + await expect(localImageBuilds(json, directory, "Fixture", FIXTURE_BUILDS)).rejects.toThrow( + /records image b418ebb8.* for runtime\/orders, but its asset manifest has no such image/, + ); + }); + + test("rejects malformed local image metadata", async () => { + const directory = await fixtureCopy(); + await editJson(join(directory, "AgentCore-Fixture.template.json"), (template) => { + template.Metadata["agentcore:localImages"] = { orders: ORDERS_HASH }; + }); + await expect(localImageBuilds(json, directory, "Fixture", FIXTURE_BUILDS)).rejects.toThrow( + 'invalid "agentcore:localImages" metadata', + ); + }); + + test("adds --load only on request, and returns nothing before synthesis", async () => { + const [image] = await localImageBuilds(json, FIXTURE, "Fixture", { + "runtime/orders": "ContainerLocal", + "harness/assistant": "ContainerLocal", + }); + expect(image!.command("docker", { load: true }).slice(0, 3)).toEqual([ + "docker", + "build", + "--load", + ]); + expect(image!.command("finch")).not.toContain("--load"); + expect( + await localImageBuilds(json, join(tmpdir(), "agentcore-missing-assembly"), "Fixture", { + "runtime/orders": "ContainerLocal", + }), + ).toEqual([]); + }); +}); diff --git a/src/core/project/backends/cdk/localImages.ts b/src/core/project/backends/cdk/localImages.ts new file mode 100644 index 0000000000..73fe95f948 --- /dev/null +++ b/src/core/project/backends/cdk/localImages.ts @@ -0,0 +1,171 @@ +import { existsSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { z } from "zod"; +import { ProjectStateError } from "../../../../errors"; +import type { ReadWriteJson } from "../../../../io"; +import type { WorkloadBuilds } from "../../../../handlers/project/types"; +import { workloadEntries } from "./localContainers"; + +// The assembly's manifest.json, which each synth rewrites: only the stacks it lists, +// and the asset manifests they depend on, are current. Older files can linger. +const AssemblyManifestSchema = z.object({ + artifacts: z + .record( + z.string(), + z.object({ + type: z.string(), + dependencies: z.array(z.string()).optional(), + properties: z + .object({ file: z.string().optional(), templateFile: z.string().optional() }) + .passthrough() + .optional(), + }), + ) + .default({}), +}); + +const WorkloadKeySchema = z.string().regex(/^(runtime|harness)\/.+$/); + +// The companion CDK package records each ContainerLocal workload's image in its +// stack template: workload key -> key of the image under the asset manifest's +// dockerImages. +const LocalImagesSchema = z.record(WorkloadKeySchema, z.string().min(1)); +const StackTemplateSchema = z.object({ + Metadata: z.object({ "agentcore:localImages": z.unknown() }).passthrough().optional(), +}); + +// The parts of a cloud assembly asset manifest (`.assets.json`) that +// describe how CDK builds a Docker image asset. +const AssetManifestSchema = z.object({ + dockerImages: z + .record( + z.string(), + z.object({ + source: z.object({ + directory: z.string().optional(), + dockerFile: z.string().optional(), + dockerBuildArgs: z.record(z.string(), z.string()).optional(), + platform: z.string().optional(), + }), + }), + ) + .default({}), +}); + +export type LocalImageBuild = { + /** `runtime/` or `harness/`. */ + resource: string; + tag: string; + /** The staged, already filtered build context inside the assembly. */ + directory: string; + /** `load` adds --load, which Docker with a non-default buildx driver needs to keep the image. */ + command: (executable: string, options?: { load?: boolean }) => string[]; +}; + +const tagComponent = (value: string) => + value + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, "-") + .replace(/^[^a-z0-9]+/, ""); + +const cdkMismatch = (detail: string) => + new ProjectStateError( + `${detail} The project's @aws/agentcore-cdk package is too old for ContainerLocal or does ` + + "not match this CLI. Update the dependency in agentcore/cdk and run npm install.", + ); + +/** + * The ContainerLocal images the synthesized assembly's stacks declare, as local + * build commands. Images shared by several target stacks are built once. + * Throws when a ContainerLocal workload has no recorded image. + */ +export async function localImageBuilds( + json: ReadWriteJson, + assemblyDirectory: string, + projectName: string, + builds: WorkloadBuilds, +): Promise { + const manifestPath = join(assemblyDirectory, "manifest.json"); + if (!existsSync(manifestPath)) return []; + const { artifacts } = await json.read(manifestPath, AssemblyManifestSchema); + const expected = workloadEntries(builds) + .filter(([, build]) => build === "ContainerLocal") + .map(([key]) => key); + const found = new Set(); + const images = new Map(); + + for (const [stackId, stack] of Object.entries(artifacts)) { + if (stack.type !== "aws:cloudformation:stack" || !stack.properties?.templateFile) continue; + const template = await json.read( + join(assemblyDirectory, stack.properties.templateFile), + StackTemplateSchema, + ); + const parsed = LocalImagesSchema.safeParse(template.Metadata?.["agentcore:localImages"] ?? {}); + if (!parsed.success) { + throw cdkMismatch( + `Stack ${stackId} has invalid "agentcore:localImages" metadata: expected an object ` + + "mapping runtime/ or harness/ to an image asset hash.", + ); + } + const recorded = parsed.data; + if (Object.keys(recorded).length === 0) continue; + const assetFiles = (stack.dependencies ?? []) + .map((dependency) => artifacts[dependency]) + .filter((artifact) => artifact?.type === "cdk:asset-manifest") + .flatMap((artifact) => (artifact?.properties?.file ? [artifact.properties.file] : [])); + const dockerImages: z.infer["dockerImages"] = {}; + for (const file of assetFiles) { + Object.assign( + dockerImages, + (await json.read(join(assemblyDirectory, file), AssetManifestSchema)).dockerImages, + ); + } + + for (const [resource, hash] of Object.entries(recorded)) { + const image = dockerImages[hash]; + if (!image) { + throw cdkMismatch( + `Stack ${stackId} records image ${hash} for ${resource}, but its asset manifest has no such image.`, + ); + } + found.add(resource); + if (images.has(hash)) continue; + const { directory, dockerFile, dockerBuildArgs, platform } = image.source; + if (!directory) { + throw cdkMismatch( + `The asset manifest of stack ${stackId} has no build context for ${resource}.`, + ); + } + const tag = `agentcore-local/${tagComponent(`${projectName}-${resource.replace("/", "-")}`)}:${hash}`; + images.set(hash, { + resource, + tag, + directory: resolve(assemblyDirectory, directory), + command: (executable, options) => [ + executable, + "build", + ...(options?.load ? ["--load"] : []), + "--platform", + platform ?? "linux/arm64", + "--tag", + tag, + ...(dockerFile ? ["--file", dockerFile] : []), + ...Object.entries(dockerBuildArgs ?? {}).flatMap(([key, value]) => [ + "--build-arg", + `${key}=${value}`, + ]), + ".", + ], + }); + } + } + + const missing = expected.filter((key) => !found.has(key)); + if (missing.length > 0) { + throw cdkMismatch( + `The synthesized stacks record no local image for ${missing.join(", ")} ` + + '(no "agentcore:localImages" entry).', + ); + } + return [...images.values()]; +} diff --git a/src/core/project/backends/cdk/toolkit.test.ts b/src/core/project/backends/cdk/toolkit.test.ts index 3575b9a4a5..8b7d5417e6 100644 --- a/src/core/project/backends/cdk/toolkit.test.ts +++ b/src/core/project/backends/cdk/toolkit.test.ts @@ -290,6 +290,29 @@ describe("Toolkit loading", () => { expect(providers).toEqual([credentials]); }); + test("sets CDK_DOCKER to the container executable only for the operation", async () => { + const { loaded } = loadedToolkit(); + const previous = process.env.CDK_DOCKER; + process.env.CDK_DOCKER = "configured"; + let during: string | undefined; + loaded.toolkit.destroy = async () => { + during = process.env.CDK_DOCKER; + return { stacks: [] } as never; + }; + const runner = createCdkRunner(createSilentLogger(), async () => loaded); + try { + await runner( + { kind: "destroy", stackArtifactId: "AgentCore-orders-default" }, + runOptions({ containerExecutable: "finch" }), + ); + expect(during).toBe("finch"); + expect(process.env.CDK_DOCKER).toBe("configured"); + } finally { + if (previous === undefined) delete process.env.CDK_DOCKER; + else process.env.CDK_DOCKER = previous; + } + }); + test("routes the operation's ioHost messages into its onOutput sink", async () => { const { loaded } = loadedToolkit(); const lines: string[] = []; diff --git a/src/core/project/backends/cdk/toolkit.ts b/src/core/project/backends/cdk/toolkit.ts index 3168567d7e..488562bf82 100644 --- a/src/core/project/backends/cdk/toolkit.ts +++ b/src/core/project/backends/cdk/toolkit.ts @@ -30,6 +30,11 @@ export type CdkRunOptions = { * whether or not a sink is given. */ onOutput?: (line: string) => void; + /** + * Docker-compatible executable CDK builds and publishes image assets with. The + * Toolkit runs in-process and reads CDK_DOCKER, so it is set for the operation. + */ + containerExecutable?: string; }; export type CdkOutputs = Record; @@ -277,6 +282,8 @@ export function createCdkRunner( firstFailure ??= failure; }); const loaded = await load(ioHost, options.region, options.credentials); + const previousCdkDocker = process.env.CDK_DOCKER; + if (options.containerExecutable) process.env.CDK_DOCKER = options.containerExecutable; try { return await performCdkOperation(loaded, operation, options); } catch (error) { @@ -286,6 +293,9 @@ export function createCdkRunner( `(${firstFailure.status}): ${firstFailure.reason}`; } throw error; + } finally { + if (previousCdkDocker === undefined) delete process.env.CDK_DOCKER; + else process.env.CDK_DOCKER = previousCdkDocker; } }; } diff --git a/src/core/project/backends/types.ts b/src/core/project/backends/types.ts index 1f54d772b1..c534ca66a0 100644 --- a/src/core/project/backends/types.ts +++ b/src/core/project/backends/types.ts @@ -1,3 +1,4 @@ +import type { WorkloadBuilds } from "../../../handlers/project/types"; import type { DeployResult, Project, @@ -17,6 +18,8 @@ export type DeployBackendInput = { transactionSearch?: boolean; /** Leaves the CDK bootstrap stack alone for accounts bootstrapped outside the CLI. */ skipBootstrap?: boolean; + /** Effective workload build modes the manager resolved; resolved here when absent. */ + workloadBuilds?: WorkloadBuilds; }; export type ResolveDeployedResourcesBackendInput = { diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 637913c8ed..2a370d5ee6 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -114,6 +114,8 @@ import { loadLegacyProject } from "./legacy/load"; import { assertV1Project } from "./legacy/writeGate"; import { assertNoPendingMigration } from "./migrate/journal"; import { prepareRuntimes } from "./runtimeBuild"; +import { isContainerBuild } from "../../projectSchemas/constants"; +import { resolveWorkloadBuilds } from "./backends/cdk/localContainers"; const TARGETS_EXAMPLE = '[{ "name": "default", "account": "111122223333", "region": "us-east-1" }]'; @@ -547,7 +549,8 @@ export class FsProjectManager implements ProjectManager { yield* this.installRuntimeDependencies(appDir, scaffoldRuntimeInput); } } else if ( - scaffoldRuntimeInput?.build === "Container" && + scaffoldRuntimeInput !== undefined && + isContainerBuild({ build: scaffoldRuntimeInput.build }) && templateManagesDependencies(resolveRuntimeTemplateProfile(scaffoldRuntimeInput)) ) { // Container builds install from a lockfile, so generate it even with no-install. @@ -758,6 +761,7 @@ export class FsProjectManager implements ProjectManager { if (!existsSync(outputPath)) scaffoldedPaths.push(outputPath); const resolver = getHarnessTemplateResolver({ + projectRoot: project.rootPath, assetSource: this.assetSource, templateRenderer: this.templateRenderer, }); @@ -793,7 +797,11 @@ export class FsProjectManager implements ProjectManager { const relativeFolder = `app/${input.resourceConfig.name}`; yield { type: "step", message: `writing runtime docs to '${relativeFolder}'` }; const tree = await runtimeDocsTree( - { assetSource: this.assetSource, templateRenderer: this.templateRenderer }, + { + assetSource: this.assetSource, + templateRenderer: this.templateRenderer, + projectRoot: project.rootPath, + }, input.resourceConfig, ); // Tracked as each file is written, so a write that fails partway is @@ -1586,6 +1594,10 @@ export class FsProjectManager implements ProjectManager { const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); for (const message of synced.messages) yield { type: "step", message }; project = synced.project; + // Resolved once, after auto-detection, so the caller (telemetry) and the + // backend see the build modes this deploy actually uses. + const workloadBuilds = resolveWorkloadBuilds(project); + input.onWorkloadBuilds?.(workloadBuilds); // China (aws-cn) targets cannot run runtimes whose scaffolded code is // wired to Bedrock/Anthropic/OpenAI/Gemini (unreachable there), nor @@ -1687,6 +1699,7 @@ export class FsProjectManager implements ProjectManager { confirmTeardown: input.confirmTeardown, transactionSearch: input.transactionSearch, skipBootstrap: input.skipBootstrap, + workloadBuilds, }); } diff --git a/src/core/project/runtimeBuild.test.ts b/src/core/project/runtimeBuild.test.ts index 47ab9452d2..ae1f6112ee 100644 --- a/src/core/project/runtimeBuild.test.ts +++ b/src/core/project/runtimeBuild.test.ts @@ -47,6 +47,22 @@ const pyproject = (requiresPython: string, extra = "") => const packageJson = (fields: Record) => JSON.stringify({ name: "search", ...fields }); +test("build inference preserves an explicit ContainerLocal choice", async () => { + const root = await project({ "app/search/Dockerfile": "FROM scratch\n" }); + const synced = syncRuntimeBuild( + runtime({ build: "ContainerLocal", runtimeVersion: undefined }), + root, + ); + expect(synced.runtime.build).toBe("ContainerLocal"); + expect(synced.runtime.dockerfile).toBe("Dockerfile"); + expect(synced.runtime.runtimeVersion).toBeUndefined(); + expect(prepareRuntimes(root, [synced.runtime], "deploy").runtimes[0]?.build).toBe( + "ContainerLocal", + ); + // Auto-detection from a Dockerfile only ever selects the CodeBuild Container mode. + expect(syncRuntimeBuild(runtime({ build: "CodeZip" }), root).runtime.build).toBe("Container"); +}); + describe("runtimeVersion from requires-python", () => { test.each([ [">=3.12", "PYTHON_3_14"], diff --git a/src/core/project/runtimeBuild.ts b/src/core/project/runtimeBuild.ts index be74f38f3b..fff0e2741f 100644 --- a/src/core/project/runtimeBuild.ts +++ b/src/core/project/runtimeBuild.ts @@ -4,6 +4,7 @@ import semver from "semver"; import { parse as parseToml, type TomlTableWithoutBigInt } from "smol-toml"; import { ProjectStateError } from "../../errors"; import { + isContainerBuild, NodeRuntimeSchema, PythonRuntimeSchema, type RuntimeVersion, @@ -90,7 +91,7 @@ export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): next.build = "Container"; next.dockerfile = DOCKERFILE_NAME; reasons.build = reasons.dockerfile = `${DOCKERFILE_NAME} in ${contextLabel}`; - } else if (runtime.build === "Container" && runtime.dockerfile === undefined) { + } else if (isContainerBuild({ build: runtime.build }) && runtime.dockerfile === undefined) { next.dockerfile = DOCKERFILE_NAME; reasons.dockerfile = "default"; } @@ -111,7 +112,7 @@ export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): } // runtimeVersion: CodeZip only; a Container image picks its own. - if (next.build === "Container") { + if (isContainerBuild({ build: next.build })) { delete next.runtimeVersion; reasons.runtimeVersion = "Container build"; } else { @@ -564,7 +565,7 @@ function runtimeProblems( const folder = resolve(projectRoot, runtime.codeLocation); const folderLabel = `${displayPath(projectRoot, folder)}/`; const problems: string[] = []; - if (runtime.build === "Container") { + if (isContainerBuild(runtime)) { const context = contextDir(runtime, projectRoot); const dockerfile = runtime.dockerfile ?? DOCKERFILE_NAME; if (!isFile(join(context, dockerfile))) { @@ -578,7 +579,11 @@ function runtimeProblems( `${codeZipRevertEdits(runtime)}.`, ); } - if (runtime.networkMode === "VPC" && !runtime.networkConfig?.vpcId) { + if ( + runtime.build === "Container" && + runtime.networkMode === "VPC" && + !runtime.networkConfig?.vpcId + ) { problems.push( `${prefix} networkConfig.vpcId is required for Container builds in VPC mode ` + `(CodeBuild cannot infer the VPC from subnets).`, diff --git a/src/core/project/templates/harness.ts b/src/core/project/templates/harness.ts index 3abc429353..fbf1203b12 100644 --- a/src/core/project/templates/harness.ts +++ b/src/core/project/templates/harness.ts @@ -1,4 +1,5 @@ import { existsSync } from "node:fs"; +import { resolve } from "node:path"; import { stringify } from "yaml"; import { ZodError, z } from "zod"; import { @@ -59,6 +60,7 @@ export function harnessApiKeyCredentialName( type GetHarnessTemplateResolverConfig = { assetSource: AssetSource; templateRenderer: TemplateRenderer; + projectRoot?: string; }; /** Given a harness spec, resolve the {@link TemplateResolver} that renders its config directory **/ @@ -67,12 +69,16 @@ export function getHarnessTemplateResolver( ): TemplateResolver> { return { async resolve(spec) { - validateHarnessTemplateSource(spec); + validateHarnessTemplateSource(spec, config.projectRoot); const parsed = parseHarnessSpec({ ...spec, memory: spec.memory === undefined ? { mode: "managed" } : spec.memory, - dockerfile: spec.dockerfile ? "Dockerfile" : undefined, + dockerfile: spec.dockerfile + ? spec.buildContextPath + ? spec.dockerfile + : "Dockerfile" + : undefined, }); const { systemPrompt, ...settings } = parsed; const context = buildTemplateContext(settings); @@ -89,7 +95,22 @@ export function getHarnessTemplateResolver( "system-prompt.md", async () => systemPrompt ?? DEFAULT_SYSTEM_PROMPT, ), - ...(spec.dockerfile ? [FsTreeNode.fromTextFile("Dockerfile", spec.dockerfile)] : []), + // Without a build context the Dockerfile is copied into the harness + // directory; a Dockerfile-specific ignore file, which Docker reads instead + // of .dockerignore, goes with it under the copied name. + ...(spec.dockerfile && !spec.buildContextPath + ? [ + FsTreeNode.fromTextFile("Dockerfile", spec.dockerfile), + ...(existsSync(`${spec.dockerfile}.dockerignore`) + ? [ + FsTreeNode.fromTextFile( + "Dockerfile.dockerignore", + `${spec.dockerfile}.dockerignore`, + ), + ] + : []), + ] + : []), ); return { @@ -128,9 +149,19 @@ function buildTemplateContext(spec: HarnessSpec) { }; } -export function validateHarnessTemplateSource(spec: z.input): void { - if (spec.dockerfile && !existsSync(spec.dockerfile)) { - throw new ResourceNotFoundError(`no dockerfile exists at ${spec.dockerfile}`); +export function validateHarnessTemplateSource( + spec: z.input, + projectRoot?: string, +): void { + if (spec.buildContextPath && !projectRoot) { + throw new InputValidationError("projectRoot is required for a Harness build context override."); + } + const dockerfile = + spec.dockerfile && typeof spec.buildContextPath === "string" + ? resolve(projectRoot!, spec.buildContextPath, spec.dockerfile) + : spec.dockerfile; + if (dockerfile && !existsSync(dockerfile)) { + throw new ResourceNotFoundError(`no dockerfile exists at ${dockerfile}`); } } diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index e3c92630bf..2a5cc7fb9f 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -14,6 +14,7 @@ import { InputValidationError } from "../../../errors"; import { toPythonPackageName } from "../fsUtils"; import { templateUsesModel } from "../../../handlers/project/templateProfile"; import { resolveRuntimeTemplateProfile } from "../../../handlers/project/runtimeTemplateProfile"; +import { isContainerBuild } from "../../../projectSchemas/constants"; /** A model provider's render context, spec entries, and .env.local secrets for a scaffolded runtime. */ type ModelProviderTemplateConfig = { @@ -107,7 +108,7 @@ function buildRuntimeSpec(input: RuntimeResourceConfig): ProjectRuntime { ...(scaffoldRuntimeInput.runtimeVersion && { runtimeVersion: scaffoldRuntimeInput.runtimeVersion, }), - ...(scaffoldRuntimeInput.build === "Container" && { + ...(isContainerBuild({ build: scaffoldRuntimeInput.build }) && { dockerfile: runtimeProfile?.dockerfile ?? "Dockerfile", }), ...(infra.description && { description: infra.description }), @@ -268,7 +269,7 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa // The strands template's entrypoint is fixed to main.py; the container Dockerfile launches it as the `main` module. entrypoint: "main", }; - const isContainer = input.scaffoldRuntimeInput.build === "Container"; + const isContainer = isContainerBuild({ build: input.scaffoldRuntimeInput.build }); const tree = await FsTreeNode.fromAssetSource( { assetSource }, { assetDir: "templates/agent-python-strands" }, diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index 09261c4d5c..0dd0a5e2ec 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -11,6 +11,9 @@ import { import { defaultMemoryName, memoryEnvVarName } from "../../../projectSchemas/memory"; import { credentialProviderNameEnvVarName } from "../../../projectSchemas/credential"; import { LATEST_NODE, LATEST_PYTHON } from "../runtimeBuild"; +import { existsSync } from "node:fs"; +import { resolve } from "node:path"; +import { InputValidationError, ResourceNotFoundError } from "../../../errors"; /** * The discovery prefix @aws/agentcore-cdk gives a project gateway: @@ -50,8 +53,8 @@ export function docsRuntimeEntrypoint(language: RuntimeDocsConfig["language"]): * The README.md and AGENTS.md for a runtime the user writes themselves, * rendered for its language and protocol. */ -export function runtimeDocsTree( - config: { assetSource: AssetSource; templateRenderer: TemplateRenderer }, +export async function runtimeDocsTree( + config: { assetSource: AssetSource; templateRenderer: TemplateRenderer; projectRoot?: string }, input: RuntimeDocsConfig, ): Promise { const protocol = input.protocol ?? "HTTP"; @@ -82,7 +85,7 @@ export function runtimeDocsTree( env: credentialProviderNameEnvVarName("openai-key"), }, }; - return FsTreeNode.fromAssetSource( + const tree = await FsTreeNode.fromAssetSource( { assetSource: config.assetSource }, { assetDir: `templates/runtime-docs/${input.language === "TypeScript" ? "typescript" : "python"}`, @@ -92,6 +95,28 @@ export function runtimeDocsTree( transformContent: (raw) => config.templateRenderer.render(raw, context), }, ); + if (input.dockerfile) { + if (input.buildContextPath && !config.projectRoot) { + throw new InputValidationError("projectRoot is required for a build context override."); + } + const dockerfile = input.buildContextPath + ? resolve(config.projectRoot!, input.buildContextPath, input.dockerfile) + : input.dockerfile; + if (!existsSync(dockerfile)) + throw new ResourceNotFoundError(`no dockerfile exists at ${dockerfile}`); + // Without a build context the Dockerfile is copied into the resource directory; + // a Dockerfile-specific ignore file, which Docker reads instead of .dockerignore, + // goes with it under the copied name. + if (!input.buildContextPath) { + tree.children.push(FsTreeNode.fromTextFile("Dockerfile", dockerfile)); + if (existsSync(`${dockerfile}.dockerignore`)) { + tree.children.push( + FsTreeNode.fromTextFile("Dockerfile.dockerignore", `${dockerfile}.dockerignore`), + ); + } + } + } + return tree; } /** @@ -104,8 +129,17 @@ export function buildDocsRuntimeSpec(input: RuntimeDocsConfig): ProjectRuntime { return { name, codeLocation: `app/${name}` as ProjectRuntime["codeLocation"], - build: "CodeZip", - runtimeVersion: language === "TypeScript" ? LATEST_NODE : LATEST_PYTHON, + build: input.build ?? "CodeZip", + ...((input.build === undefined || input.build === "CodeZip") && { + runtimeVersion: language === "TypeScript" ? LATEST_NODE : LATEST_PYTHON, + }), + ...(input.dockerfile && { + dockerfile: input.buildContextPath ? input.dockerfile : "Dockerfile", + }), + ...(input.buildContextPath !== undefined && { buildContextPath: input.buildContextPath }), + ...(input.customDockerBuildArgs !== undefined && { + customDockerBuildArgs: input.customDockerBuildArgs, + }), entrypoint: docsRuntimeEntrypoint(language), protocol: infra.protocol ?? "HTTP", ...(infra.description && { description: infra.description }), diff --git a/src/handlers/project/add/buildConfig.ts b/src/handlers/project/add/buildConfig.ts new file mode 100644 index 0000000000..b367de6eb9 --- /dev/null +++ b/src/handlers/project/add/buildConfig.ts @@ -0,0 +1,45 @@ +import z from "zod"; +import { flag } from "../../../router"; +import { parseJsonFlagWithSchema } from "../../utils"; +import { + isReservedBuildArgKey, + ProjectRuntimeSchema, + RESERVED_BUILD_ARG_KEYS, +} from "../../../projectSchemas/runtime"; +import { HarnessSpecSchema } from "../../../projectSchemas/harness"; + +export const ADVANCED = "Advanced:"; + +// Keys map 1:1 to the build fields in agentcore.json and harness.yaml. dockerfile +// is a path to an existing Dockerfile: it is copied into the resource directory +// unless buildContextPath is set, in which case it is relative to that context. +const buildFields = { + dockerfile: z.string().min(1).optional(), + buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, + customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs.refine( + (args) => !Object.keys(args ?? {}).some(isReservedBuildArgKey), + `customDockerBuildArgs must not use keys reserved by the build environment (${RESERVED_BUILD_ARG_KEYS.join(", ")}, CODEBUILD_*, AWS_*)`, + ), +}; +export const RuntimeBuildConfigSchema = z.strictObject({ + build: ProjectRuntimeSchema.shape.build.optional(), + ...buildFields, +}); +export const HarnessBuildConfigSchema = z.strictObject({ + build: HarnessSpecSchema.shape.build, + ...buildFields, +}); + +export function buildConfigFlag(builds: string) { + return flag( + "build-config", + `advanced build settings (JSON object): build (${builds}), dockerfile, buildContextPath, ` + + "customDockerBuildArgs. Build args are not secret: they appear in logs and image metadata", + z.string().optional(), + { group: ADVANCED }, + ); +} + +export function parseBuildConfig(raw: string | undefined, schema: z.ZodType): T | undefined { + return parseJsonFlagWithSchema("build-config", raw, schema); +} diff --git a/src/handlers/project/add/harness/index.test.ts b/src/handlers/project/add/harness/index.test.ts index 1e3a7cc0b2..835ae5c2b4 100644 --- a/src/handlers/project/add/harness/index.test.ts +++ b/src/handlers/project/add/harness/index.test.ts @@ -32,6 +32,119 @@ async function run(args: string[], opts?: { core?: TestCoreClient; stdin?: strin } describe("project add harness", () => { + test("persists --build-config with --dockerfile in harness.yaml", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Dockerfile"); + await Bun.write(dockerfile, "FROM scratch\n"); + await run([ + "add", + "harness", + "--name", + "local", + "--dockerfile", + dockerfile, + "--build-config", + '{"build":"ContainerLocal","customDockerBuildArgs":{"VERSION":"v1"}}', + ]); + const spec = parse(await Bun.file(join(projectRoot, "app", "local", "harness.yaml")).text()); + expect(spec).toMatchObject({ + build: "ContainerLocal", + dockerfile: "Dockerfile", + customDockerBuildArgs: { VERSION: "v1" }, + }); + }); + test("accepts the Dockerfile from --build-config alone", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Dockerfile"); + await Bun.write(dockerfile, "FROM scratch\n"); + await run([ + "add", + "harness", + "--name", + "local", + "--build-config", + JSON.stringify({ build: "Container", dockerfile }), + ]); + const spec = parse(await Bun.file(join(projectRoot, "app", "local", "harness.yaml")).text()); + expect(spec).toMatchObject({ build: "Container", dockerfile: "Dockerfile" }); + }); + test.each<[string, string[], string]>([ + [ + "a Dockerfile from both --dockerfile and --build-config", + ["--dockerfile", "Dockerfile", "--build-config", '{"dockerfile":"Dockerfile"}'], + "--dockerfile and --build-config dockerfile both set the Dockerfile", + ], + [ + "build CodeZip", + ["--dockerfile", "Dockerfile", "--build-config", '{"build":"CodeZip"}'], + "--build-config", + ], + [ + "--dockerfile with a build context", + ["--dockerfile", "Dockerfile", "--build-config", '{"buildContextPath":"."}'], + "--dockerfile cannot be combined with --build-config buildContextPath", + ], + ["invalid JSON", ["--build-config", "{bad}"], "Invalid JSON for option '--build-config'"], + [ + "a build without a Dockerfile", + ["--build-config", '{"build":"ContainerLocal"}'], + "build requires a Dockerfile", + ], + ])("rejects %s", async (_label, flags, message) => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await Bun.write(join(projectRoot, "Dockerfile"), "FROM scratch\n"); + const error = await run(["add", "harness", "--name", "local", ...flags]).catch( + (caught: unknown) => caught, + ); + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toContain(message); + expect(existsSync(join(projectRoot, "app", "local", "harness.yaml"))).toBe(false); + }); + test("copies a Dockerfile-specific ignore file along with the Dockerfile, renamed to match", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Agent.Dockerfile"); + await Bun.write(dockerfile, "FROM scratch\n"); + await Bun.write(`${dockerfile}.dockerignore`, "*.log\n"); + await run(["add", "harness", "--name", "local", "--dockerfile", dockerfile]); + const harnessDir = join(projectRoot, "app", "local"); + expect(await Bun.file(join(harnessDir, "Dockerfile")).text()).toBe("FROM scratch\n"); + expect(await Bun.file(join(harnessDir, "Dockerfile.dockerignore")).text()).toBe("*.log\n"); + }); + test("accepts a Dockerfile-specific ignore file in an existing build context", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await Bun.write(join(projectRoot, "docker", "Agent.Dockerfile"), "FROM scratch\n"); + await Bun.write(join(projectRoot, "docker", "Agent.Dockerfile.dockerignore"), "*.log\n"); + await run([ + "add", + "harness", + "--name", + "local", + "--build-config", + JSON.stringify({ + build: "ContainerLocal", + dockerfile: "Agent.Dockerfile", + buildContextPath: "docker", + }), + ]); + const spec = parse(await Bun.file(join(projectRoot, "app", "local", "harness.yaml")).text()); + expect(spec).toMatchObject({ dockerfile: "Agent.Dockerfile", buildContextPath: "docker" }); + expect(existsSync(join(projectRoot, "app", "local", "Dockerfile.dockerignore"))).toBe(false); + }); + test("without --build-config a --dockerfile harness records no build key", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Dockerfile"); + await Bun.write(dockerfile, "FROM scratch\n"); + await run(["add", "harness", "--name", "plain", "--dockerfile", dockerfile]); + const spec = parse(await Bun.file(join(projectRoot, "app", "plain", "harness.yaml")).text()); + expect(spec.build).toBeUndefined(); + expect(spec.dockerfile).toBe("Dockerfile"); + }); const defaultModel = { provider: "bedrock", modelId: "global.anthropic.claude-sonnet-5-5" }; test.each<[string, string[], Record]>([ diff --git a/src/handlers/project/add/harness/index.ts b/src/handlers/project/add/harness/index.ts index f1af1214d5..6b4146d3fb 100644 --- a/src/handlers/project/add/harness/index.ts +++ b/src/handlers/project/add/harness/index.ts @@ -17,6 +17,7 @@ import { import { SourceResolver } from "../../../../io"; import type { AddResourceInput, Project } from "../../types"; import { toLiteLlmGatewayModel } from "../../../harness/liteLlmGateway"; +import { buildConfigFlag, HarnessBuildConfigSchema, parseBuildConfig } from "../buildConfig"; const CONFIGURATION = "Configuration:"; const TOOLS_AND_SKILLS = "Tools and skills:"; @@ -194,8 +195,21 @@ export const createAddHarnessHandler = (config: AddProjectResourceConfig) => z.string().optional(), { group: ACCESS_AND_PERMISSIONS }, ), + buildConfigFlag("Container or ContainerLocal"), ], handle: async (ctx, flags) => { + const buildConfig = parseBuildConfig(flags["build-config"], HarnessBuildConfigSchema); + if (buildConfig?.dockerfile !== undefined && flags.dockerfile !== undefined) { + throw new InputValidationError( + "--dockerfile and --build-config dockerfile both set the Dockerfile; pass only one", + ); + } + if (buildConfig?.buildContextPath !== undefined && flags.dockerfile !== undefined) { + throw new InputValidationError( + "--dockerfile cannot be combined with --build-config buildContextPath: with a build " + + 'context, set "dockerfile" inside --build-config, relative to that context', + ); + } const harnessInput = { name: flags.name, model: parseJsonFlag("model", flags["model"]) ?? DEFAULT_HARNESS_MODEL, @@ -227,6 +241,7 @@ export const createAddHarnessHandler = (config: AddProjectResourceConfig) => timeoutSeconds: flags["timeout-seconds"], tags: parseTags(flags["tags"]), dockerfile: flags["dockerfile"], + ...buildConfig, }; const project = ctx.require(ProjectKey); diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index f46787bc2f..0440b68b83 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -66,6 +66,153 @@ async function runtimeOf(projectRoot: string, name: string) { } describe("project add runtime", () => { + test.each(["Container", "ContainerLocal"])( + "--build-config with build %s persists it and copies the Dockerfile", + async (build) => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Dockerfile"); + await writeFile(dockerfile, "FROM scratch\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ build, dockerfile, customDockerBuildArgs: { VERSION: "v1" } }), + ]); + const runtime = await runtimeOf(projectRoot, "local"); + expect(runtime).toMatchObject({ + build, + dockerfile: "Dockerfile", + codeLocation: "app/local", + customDockerBuildArgs: { VERSION: "v1" }, + }); + expect(runtime.runtimeVersion).toBeUndefined(); + expect(await Bun.file(join(projectRoot, "app", "local", "Dockerfile")).text()).toBe( + "FROM scratch\n", + ); + }, + ); + test("--build-config with buildContextPath keeps the Dockerfile in that context", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await mkdir(join(projectRoot, "docker"), { recursive: true }); + await writeFile(join(projectRoot, "docker", "Agent.Dockerfile"), "FROM scratch\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ + build: "ContainerLocal", + dockerfile: "Agent.Dockerfile", + buildContextPath: "docker", + }), + ]); + expect(await runtimeOf(projectRoot, "local")).toMatchObject({ + build: "ContainerLocal", + dockerfile: "Agent.Dockerfile", + buildContextPath: "docker", + }); + expect(await Bun.file(join(projectRoot, "app", "local", "Dockerfile")).exists()).toBe(false); + }); + test("copies a Dockerfile-specific ignore file along with the Dockerfile, renamed to match", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Agent.Dockerfile"); + await writeFile(dockerfile, "FROM scratch\n"); + await writeFile(`${dockerfile}.dockerignore`, "*.log\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ build: "ContainerLocal", dockerfile }), + ]); + const appDir = join(projectRoot, "app", "local"); + expect(await Bun.file(join(appDir, "Dockerfile")).text()).toBe("FROM scratch\n"); + expect(await Bun.file(join(appDir, "Dockerfile.dockerignore")).text()).toBe("*.log\n"); + }); + test("accepts a Dockerfile-specific ignore file in an existing build context", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await mkdir(join(projectRoot, "docker"), { recursive: true }); + await writeFile(join(projectRoot, "docker", "Agent.Dockerfile"), "FROM scratch\n"); + await writeFile(join(projectRoot, "docker", "Agent.Dockerfile.dockerignore"), "*.log\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ + build: "ContainerLocal", + dockerfile: "Agent.Dockerfile", + buildContextPath: "docker", + }), + ]); + expect(await runtimeOf(projectRoot, "local")).toMatchObject({ buildContextPath: "docker" }); + expect( + await Bun.file(join(projectRoot, "app", "local", "Dockerfile.dockerignore")).exists(), + ).toBe(false); + }); + test("without --build-config a runtime stays CodeZip", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await run(["add", "runtime", "--name", "plain", "--language", "python"]); + const runtime = await runtimeOf(projectRoot, "plain"); + expect(runtime.build).toBe("CodeZip"); + expect(runtime.runtimeVersion).toBeDefined(); + expect(runtime.dockerfile).toBeUndefined(); + }); + test.each<[string, string, string]>([ + ["invalid JSON", "{bad}", "Invalid JSON for option '--build-config'"], + ["an unknown key", '{"build":"Container","image":"x"}', "--build-config"], + ["an unknown build", '{"build":"Local","dockerfile":"Dockerfile"}', "--build-config"], + [ + "a reserved build argument", + '{"build":"Container","dockerfile":"Dockerfile","customDockerBuildArgs":{"AWS_REGION":"x"}}', + "--build-config", + ], + [ + "a container build without a Dockerfile", + '{"build":"ContainerLocal"}', + "dockerfile is required", + ], + [ + "container settings without a container build", + '{"dockerfile":"Dockerfile"}', + "dockerfile requires build Container or ContainerLocal", + ], + ])("rejects --build-config with %s and writes nothing", async (_label, value, message) => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await writeFile(join(projectRoot, "Dockerfile"), "FROM scratch\n"); + await expectError( + run(["add", "runtime", "--name", "local", "--language", "python", "--build-config", value]), + message, + InputValidationError, + ); + expect((await specOf(projectRoot)).runtimes ?? []).toEqual([]); + }); + test("--dockerfile is not an add runtime option", async () => { + const { cleanup } = await initProject(); + cleanups.push(cleanup); + await expect( + run(["add", "runtime", "--name", "local", "--language", "python", "--dockerfile", "x"]), + ).rejects.toThrow("unknown option '--dockerfile'"); + }); const allInfrastructureFlags = [ "--description", "Configured runtime", @@ -527,5 +674,8 @@ describe("project add runtime --agent-id (Bedrock Agent import)", () => { await expect(run([...importArgs, "--protocol", "MCP"])).rejects.toThrow( /--protocol cannot be combined/, ); + await expect( + run([...importArgs, "--build-config", '{"build":"Container","dockerfile":"Dockerfile"}']), + ).rejects.toThrow(/--build-config cannot be combined/); }); }); diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index 84b033f8c3..eecaebc547 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -24,6 +24,7 @@ import { } from "../../importBedrockAgent"; import { RegionKey } from "../../../keys"; import { addProjectResource, requireDeployedNameFits, addDescription } from "../shared"; +import { buildConfigFlag, parseBuildConfig, RuntimeBuildConfigSchema } from "../buildConfig"; const CONFIGURATION = "Configuration:"; const ENVIRONMENT = "Environment:"; @@ -185,6 +186,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => z.enum(["strands", "langgraph"]).optional(), { group: BEDROCK_AGENT_IMPORT }, ), + buildConfigFlag("CodeZip, Container, or ContainerLocal"), ], handle: async (ctx, flags) => { const project = ctx.require(ProjectKey); @@ -203,7 +205,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => } } if (isImport) { - const offending = (["language", "protocol"] as const).find( + const offending = (["language", "protocol", "build-config"] as const).find( (flagName) => flags[flagName] !== undefined, ); if (offending !== undefined) { @@ -261,6 +263,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => const infra = { name: flags.name, + ...parseBuildConfig(flags["build-config"], RuntimeBuildConfigSchema), description: flags.description, executionRoleArn: flags["role-arn"], additionalPolicies: flags["additional-policies"], diff --git a/src/handlers/project/add/runtime/types.ts b/src/handlers/project/add/runtime/types.ts index 4ddafc7e61..618aebb731 100644 --- a/src/handlers/project/add/runtime/types.ts +++ b/src/handlers/project/add/runtime/types.ts @@ -21,6 +21,10 @@ const RuntimeInfraConfigSchema = z.object({ lifecycleConfiguration: ProjectRuntimeSchema.shape.lifecycleConfiguration, filesystemConfigurations: ProjectRuntimeSchema.shape.filesystemConfigurations, tags: ProjectRuntimeSchema.shape.tags, + build: ProjectRuntimeSchema.shape.build.optional(), + dockerfile: z.string().min(1).optional(), + buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, + customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs, }); export const RuntimeResourceConfigSchema = RuntimeInfraConfigSchema.extend({ @@ -38,6 +42,24 @@ export type RuntimeResourceConfig = z.infer; */ export const RuntimeDocsConfigSchema = RuntimeInfraConfigSchema.extend({ language: z.enum(["Python", "TypeScript"]), +}).superRefine((data, ctx) => { + const container = data.build === "Container" || data.build === "ContainerLocal"; + if (container && data.dockerfile === undefined) { + ctx.addIssue({ + code: "custom", + message: "dockerfile is required for a Container or ContainerLocal build", + path: ["dockerfile"], + }); + } + for (const field of ["dockerfile", "buildContextPath", "customDockerBuildArgs"] as const) { + if (!container && data[field] !== undefined) { + ctx.addIssue({ + code: "custom", + message: `${field} requires build Container or ContainerLocal`, + path: [field], + }); + } + } }); export type RuntimeDocsConfig = z.infer; diff --git a/src/handlers/project/deploy/index.test.ts b/src/handlers/project/deploy/index.test.ts index c6622217fb..3802460b03 100644 --- a/src/handlers/project/deploy/index.test.ts +++ b/src/handlers/project/deploy/index.test.ts @@ -1,4 +1,5 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { @@ -417,6 +418,11 @@ describe("project deploy handler", () => { project_memory_count: 0, project_gateway_count: 0, project_harness_count: 0, + project_runtime_codezip_count: 1, + project_runtime_container_count: 0, + project_runtime_container_local_count: 0, + project_harness_container_count: 0, + project_harness_container_local_count: 0, }); expect(subject.calls).toHaveLength(1); expect(subject.calls[0]?.input.target).toEqual(DEFAULT_TARGET); @@ -429,6 +435,90 @@ describe("project deploy handler", () => { expect(subject.io.stdout()).toBe(""); }); + test("counts runtimes and harnesses by build type", async () => { + const subject = await testDeployCommand({ outputs: {} }); + const projectRoot = await inProjectWithTargets(); + const dockerfile = join(projectRoot, "Dockerfile"); + await writeFile(dockerfile, "FROM scratch\n"); + const add = createRootHandler(new TestCoreClient(), { + io: testIO().io, + globalConfigAccessor: new TestGlobalConfigAccessor(), + logger: createSilentLogger(), + }); + for (const args of [ + ["runtime", "--name", "local_rt", "--language", "python", "--build-config"], + ["harness", "--name", "local_h", "--dockerfile", dockerfile, "--build-config"], + ]) { + const config = + args[0] === "runtime" + ? { build: "ContainerLocal", dockerfile } + : { build: "ContainerLocal" }; + await add.route(["node", "agentcore", "add", ...args, JSON.stringify(config)]); + } + await add.route([ + "node", + "agentcore", + "add", + "harness", + "--name", + "cb_h", + "--dockerfile", + dockerfile, + ]); + + // Telemetry and the deploy share one resolution of harness.yaml. + const reads = spyOn(fs, "readFileSync"); + try { + await subject.run(); + const harnessReads = reads.mock.calls.filter(([path]) => + String(path).endsWith("harness.yaml"), + ); + expect(harnessReads).toHaveLength(2); // one per harness + } finally { + reads.mockRestore(); + } + expect(subject.calls[0]?.input.workloadBuilds).toEqual({ + "runtime/agent": "CodeZip", + "runtime/local_rt": "ContainerLocal", + "harness/local_h": "ContainerLocal", + "harness/cb_h": "Container", + }); + + await assertMetricEmitted(subject.telemetryFilePath, "cli.command_run", { + command_path: "/agentcore/deploy", + project_runtime_count: 2, + project_harness_count: 2, + project_runtime_codezip_count: 1, + project_runtime_container_count: 0, + project_runtime_container_local_count: 1, + project_harness_container_count: 1, + project_harness_container_local_count: 1, + }); + }); + + test("counts the build type a runtime deploys with after Dockerfile auto-detection", async () => { + const subject = await testDeployCommand({ outputs: {} }); + const projectRoot = await inProjectWithTargets(); + const spec = JSON.parse( + await readFile(join(projectRoot, "agentcore", "agentcore.json"), "utf8"), + ); + expect(spec.runtimes[0]).toMatchObject({ name: "agent", build: "CodeZip" }); + // A Dockerfile added to a CodeZip runtime's code switches it to Container at deploy. + await writeFile( + join(projectRoot, spec.runtimes[0].codeLocation, "Dockerfile"), + "FROM scratch\n", + ); + + await subject.run(); + + expect(subject.calls[0]?.input.workloadBuilds).toEqual({ "runtime/agent": "Container" }); + await assertMetricEmitted(subject.telemetryFilePath, "cli.command_run", { + command_path: "/agentcore/deploy", + project_runtime_codezip_count: 0, + project_runtime_container_count: 1, + }); + }); + test("passes the global config's transactionSearch flag into the deploy", async () => { const enabled = await testDeployCommand({ outputs: {} }); await inProjectWithTargets(); diff --git a/src/handlers/project/deploy/index.ts b/src/handlers/project/deploy/index.ts index 95e8f837d0..a2a26b0629 100644 --- a/src/handlers/project/deploy/index.ts +++ b/src/handlers/project/deploy/index.ts @@ -24,7 +24,14 @@ import { JsonRendererKey } from "../../../tui"; import { runWithProgress } from "../../../tui/progress"; import { JsonKey, RegionExplicitKey, RegionKey } from "../../keys"; import { renderJsonError } from "../../utils"; -import type { DeployResult, Project, ProjectManager, TeardownConfirmationHandler } from "../types"; +import type { + DeployResult, + Project, + ProjectManager, + TeardownConfirmationHandler, + WorkloadBuildMode, + WorkloadBuilds, +} from "../types"; export type DeployProjectHandlerConfig = { projectManager: ProjectManager; @@ -130,6 +137,7 @@ export const createDeployProjectHandler = (config: DeployProjectHandlerConfig) = confirmTeardown, transactionSearch: globalConfig.transactionSearch, skipBootstrap: flags["skip-bootstrap"], + onWorkloadBuilds: (builds) => recordBuildTypeCounts(ctx, builds), }); // Progress goes to stderr, keeping stdout for machine output. --json // forces the plain path so no ANSI reaches a scripted caller's stderr. @@ -154,6 +162,24 @@ export const createDeployProjectHandler = (config: DeployProjectHandlerConfig) = }, }); +/** + * Records how many runtimes and harnesses deploy with each build type. Deploy + * reports the effective build modes, after Dockerfile auto-detection, through + * DeployProjectInput.onWorkloadBuilds; pass this as that callback. + */ +export function recordBuildTypeCounts(ctx: Context, builds: WorkloadBuilds): void { + const entries = Object.entries(builds); + const count = (kind: "runtime" | "harness", build: WorkloadBuildMode) => + entries.filter(([key, value]) => key.startsWith(`${kind}/`) && value === build).length; + ctx.value(CommandRunMetricEventKey)?.setAttributes({ + project_runtime_codezip_count: count("runtime", "CodeZip"), + project_runtime_container_count: count("runtime", "Container"), + project_runtime_container_local_count: count("runtime", "ContainerLocal"), + project_harness_container_count: count("harness", "Container"), + project_harness_container_local_count: count("harness", "ContainerLocal"), + }); +} + export function recordProjectResourceCounts(ctx: Context, project: Project): void { const { spec } = project; ctx.value(CommandRunMetricEventKey)?.setAttributes({ diff --git a/src/handlers/project/deploy/screen.tsx b/src/handlers/project/deploy/screen.tsx index 1bcab0289a..6398db3e13 100644 --- a/src/handlers/project/deploy/screen.tsx +++ b/src/handlers/project/deploy/screen.tsx @@ -14,6 +14,7 @@ import { declaresNothingDeployable, DEPLOY_NEXT_STEP, deployedMessage, + recordBuildTypeCounts, recordProjectResourceCounts, teardownQuestion, } from "./index"; @@ -117,6 +118,7 @@ function DeployConfirm({ region, confirmTeardown: async () => teardown, transactionSearch: globalConfig?.transactionSearch, + onWorkloadBuilds: (builds) => recordBuildTypeCounts(ctx, builds), }); // The title follows the result, not the preflight heuristic, which // synthesis can disagree with. Outputs are not listed: the command diff --git a/src/handlers/project/dev/index.ts b/src/handlers/project/dev/index.ts index 18bc0c8586..a21cfa09e1 100644 --- a/src/handlers/project/dev/index.ts +++ b/src/handlers/project/dev/index.ts @@ -31,6 +31,7 @@ import type { Project, ProjectManager } from "../types"; import { BMA_TEMPLATE_NAME, isBmaRuntime } from "../bma"; import type { DevEnvironmentLoader } from "./environment"; import type { DevEvent, DevRunner, DevTraceCollector, DevTraceCollectorStarter } from "./types"; +import { isContainerBuild } from "../../../projectSchemas/constants"; /** The Inspector UI binds 8081 or, when that is taken, the next free port. */ const UI_DEFAULT_PORT = 8081; @@ -66,7 +67,7 @@ function otelEnvForRuntime( runtime: ProjectRuntime, ): Record { const env = { ...collector.envVars, OTEL_SERVICE_NAME: runtime.name }; - return runtime.build === "Container" ? rewriteOtelEndpointForContainer(env) : env; + return isContainerBuild(runtime) ? rewriteOtelEndpointForContainer(env) : env; } function supportsLocalDev(runtime: ProjectRuntime): boolean { @@ -565,7 +566,7 @@ async function startRuntimeTraceCollector({ const collector = await config.startTraceCollector({ tracesDirectory, // A container reaches the collector over the host bridge, which a loopback bind refuses. - host: runtimes.some((runtime) => runtime.build === "Container") ? "0.0.0.0" : "127.0.0.1", + host: runtimes.some((runtime) => isContainerBuild(runtime)) ? "0.0.0.0" : "127.0.0.1", onError: (error) => { if (tracePersistErrorReported) return; tracePersistErrorReported = true; @@ -624,7 +625,7 @@ async function runWithoutUi({ const env = await options.environment(runtime); signal.throwIfAborted(); - const runner = config.runners[runtime.build]; + const runner = config.runners[isContainerBuild(runtime) ? "Container" : "CodeZip"]; for await (const event of runner.run({ runtime, projectRoot: project.rootPath, diff --git a/src/handlers/project/shortcuts.ts b/src/handlers/project/shortcuts.ts index 9fb198b07a..3c8848c329 100644 --- a/src/handlers/project/shortcuts.ts +++ b/src/handlers/project/shortcuts.ts @@ -183,7 +183,11 @@ const FRAMEWORK_ORDER: Record = { bma: 3, none: 4, }; -const BUILD_ORDER: Record = { CodeZip: 0, Container: 1 }; +const BUILD_ORDER: Record = { + CodeZip: 0, + Container: 1, + ContainerLocal: 2, +}; function templateSortKey(template: RuntimeTemplateShortcut): number[] { return [ diff --git a/src/handlers/project/types.ts b/src/handlers/project/types.ts index f81a8476a5..041df8a4a9 100644 --- a/src/handlers/project/types.ts +++ b/src/handlers/project/types.ts @@ -14,7 +14,11 @@ import type { } from "./add/runtime/types"; import type { OnlineEvalConfigSchema } from "../../projectSchemas/online-eval-config"; import { AgentNameSchema, BuildTypeSchema } from "../../projectSchemas/runtime"; -import { ProtocolModeSchema, RuntimeVersionSchema } from "../../projectSchemas/constants"; +import { + isContainerBuild, + ProtocolModeSchema, + RuntimeVersionSchema, +} from "../../projectSchemas/constants"; import type { AgentCoreGateway, AgentCoreGatewayTarget } from "../../projectSchemas/gateway"; import type { PolicyEngineSchema, PolicySchema } from "../../projectSchemas/policy"; import type { AwsDeploymentTarget } from "../../projectSchemas/aws-targets"; @@ -142,7 +146,7 @@ export const ScaffoldRuntimeInputSchema = z path: ["runtimeVersion"], }); } - if (build === "Container" && runtimeVersion !== undefined) { + if (isContainerBuild({ build }) && runtimeVersion !== undefined) { ctx.addIssue({ code: "custom", message: "runtimeVersion is not supported for Container builds", @@ -223,8 +227,22 @@ export type DeployProjectInput = { transactionSearch?: boolean; /** Leaves the CDK bootstrap stack alone for accounts bootstrapped outside the CLI. */ skipBootstrap?: boolean; + /** + * Called once, before anything is deployed, with the build mode every runtime + * and harness deploys with: after Dockerfile auto-detection, read from + * agentcore.json and each harness.yaml. + */ + onWorkloadBuilds?: (builds: WorkloadBuilds) => void; }; +/** How a workload's code reaches AgentCore, as @aws/agentcore-cdk records it. */ +export type WorkloadBuildMode = + "CodeZip" | "Container" | "ContainerLocal" | "ContainerUri" | "Managed"; +/** A workload's key: `runtime/` or `harness/`, matching @aws/agentcore-cdk. */ +export type WorkloadKey = `runtime/${string}` | `harness/${string}`; +/** Build mode of every runtime and harness in a project. */ +export type WorkloadBuilds = Record; + export type DeployResult = { /** * Named outputs the deployment produced, e.g. a runtime ARN or a gateway URL. diff --git a/src/projectSchemas/constants.ts b/src/projectSchemas/constants.ts index 731edef5d5..a7a8c6e31f 100644 --- a/src/projectSchemas/constants.ts +++ b/src/projectSchemas/constants.ts @@ -79,7 +79,12 @@ export function isContainerBuild(spec: { containerUri?: string; dockerfile?: string; }): boolean { - return spec.build === "Container" || !!spec.containerUri || !!spec.dockerfile; + return ( + spec.build === "Container" || + spec.build === "ContainerLocal" || + !!spec.containerUri || + !!spec.dockerfile + ); } export const ProtocolModeSchema = z.enum(["HTTP", "MCP", "A2A", "AGUI"]); export type ProtocolMode = z.infer; diff --git a/src/projectSchemas/harness.test.ts b/src/projectSchemas/harness.test.ts index 326efa7dc8..40deced61f 100644 --- a/src/projectSchemas/harness.test.ts +++ b/src/projectSchemas/harness.test.ts @@ -286,15 +286,16 @@ describe("harness custom validation", () => { }).success, ).toBe(false); }); - it("applies the CodeBuild security-group cap to every container build source", () => { + it("applies the CodeBuild security-group cap only when building in CodeBuild", () => { const securityGroups = Array.from( { length: 6 }, (_, index) => `sg-${String(index + 1).padStart(17, "0")}`, ); - for (const source of [ - { dockerfile: "Dockerfile" }, - { containerUri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:tag" }, - ]) { + for (const [source, expected] of [ + [{ dockerfile: "Dockerfile" }, false], + [{ dockerfile: "Dockerfile", build: "ContainerLocal" }, true], + [{ containerUri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:tag" }, true], + ] as const) { expect( HarnessSpecSchema.safeParse({ ...minimalHarness, @@ -302,7 +303,7 @@ describe("harness custom validation", () => { networkMode: "VPC", networkConfig: { ...networkConfig, securityGroups }, }).success, - ).toBe(false); + ).toBe(expected); } }); }); diff --git a/src/projectSchemas/harness.ts b/src/projectSchemas/harness.ts index f2a5744811..6f1a341590 100644 --- a/src/projectSchemas/harness.ts +++ b/src/projectSchemas/harness.ts @@ -1,8 +1,5 @@ -import { - MAX_CONTAINER_BUILD_SECURITY_GROUPS, - NetworkModeSchema, - isContainerBuild, -} from "./constants"; +import { ProjectRuntimeSchema, BuildTypeSchema, isReservedBuildArgKey } from "./runtime"; +import { MAX_CONTAINER_BUILD_SECURITY_GROUPS, NetworkModeSchema } from "./constants"; import { EfsAccessPointConfigSchema, LifecycleConfigurationSchema, @@ -524,6 +521,9 @@ export const HarnessSpecSchema = z "containerUri must be an ECR image URI (12-digit private ECR or public.ecr.aws)", ) .optional(), + build: BuildTypeSchema.exclude(["CodeZip"]).optional(), + buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, + customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs, dockerfile: z.string().min(1).optional(), executionRoleArn: z.string().optional(), networkMode: NetworkModeSchema.optional(), @@ -547,6 +547,37 @@ export const HarnessSpecSchema = z tags: TagsSchema.optional(), }) .superRefine((data, ctx) => { + if (data.build !== undefined && data.dockerfile === undefined) { + ctx.addIssue({ code: "custom", message: "build requires a Dockerfile", path: ["build"] }); + } + for (const field of [ + "build", + "dockerfile", + "buildContextPath", + "customDockerBuildArgs", + ] as const) { + if (data.containerUri !== undefined && data[field] !== undefined) { + ctx.addIssue({ + code: "custom", + message: `${field} cannot be combined with containerUri`, + path: [field], + }); + } + } + for (const field of ["buildContextPath", "customDockerBuildArgs"] as const) { + if (data[field] !== undefined && data.dockerfile === undefined) { + ctx.addIssue({ code: "custom", message: `${field} requires a Dockerfile`, path: [field] }); + } + } + for (const key of Object.keys(data.customDockerBuildArgs ?? {})) { + if (isReservedBuildArgKey(key)) { + ctx.addIssue({ + code: "custom", + message: `customDockerBuildArgs key "${key}" is reserved by the build environment`, + path: ["customDockerBuildArgs", key], + }); + } + } if (data.containerUri !== undefined && data.dockerfile !== undefined) { ctx.addIssue({ code: "custom", @@ -568,7 +599,12 @@ export const HarnessSpecSchema = z path: ["networkConfig"], }); } - if (data.networkMode === "VPC" && data.dockerfile && !data.networkConfig?.vpcId) { + if ( + data.networkMode === "VPC" && + data.dockerfile && + data.build !== "ContainerLocal" && + !data.networkConfig?.vpcId + ) { ctx.addIssue({ code: "custom", message: @@ -578,7 +614,8 @@ export const HarnessSpecSchema = z } if ( data.networkMode === "VPC" && - isContainerBuild(data) && + data.dockerfile !== undefined && + data.build !== "ContainerLocal" && data.networkConfig && data.networkConfig.securityGroups.length > MAX_CONTAINER_BUILD_SECURITY_GROUPS ) { diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index e74694dfba..4b18fc8e49 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -6,7 +6,6 @@ import { SECURITY_GROUP_ID_PATTERN, SUBNET_ID_PATTERN, VPC_ID_PATTERN, - isContainerBuild, } from "./constants"; import type { DirectoryPath } from "./types"; import { AuthorizerConfigSchema, RuntimeAuthorizerTypeSchema } from "./auth"; @@ -41,7 +40,7 @@ export const AccessSchema = z.enum(["read", "readwrite"]); export type Access = z.infer; export const AgentTypeSchema = z.literal("AgentCoreRuntime"); export type AgentType = z.infer; -export const BuildTypeSchema = z.enum(["CodeZip", "Container"]); +export const BuildTypeSchema = z.enum(["CodeZip", "Container", "ContainerLocal"]); export type BuildType = z.infer; export const EntrypointSchema = z .string() @@ -347,7 +346,7 @@ export const ProjectRuntimeSchema = z } if ( data.networkMode === "VPC" && - isContainerBuild(data) && + data.build === "Container" && data.networkConfig && data.networkConfig.securityGroups.length > MAX_CONTAINER_BUILD_SECURITY_GROUPS ) { @@ -389,7 +388,7 @@ export const ProjectRuntimeSchema = z // runtimeVersion: it is the field that selects the packager. Validating it here // means the CLI reports it against agentcore.json instead of letting synthesis // fail later with the same rule. - if (data.build !== "Container" && !data.runtimeVersion) { + if (data.build === "CodeZip" && !data.runtimeVersion) { ctx.addIssue({ code: "custom", message: "runtimeVersion is required for CodeZip builds", @@ -397,7 +396,7 @@ export const ProjectRuntimeSchema = z }); } for (const field of ["dockerfile", "buildContextPath", "customDockerBuildArgs"] as const) { - if (data.build !== "Container" && data[field]) { + if (data.build === "CodeZip" && data[field]) { ctx.addIssue({ code: "custom", message: `${field} is only allowed for Container builds`, diff --git a/src/telemetry/shapes.tsx b/src/telemetry/shapes.tsx index 9d16e97456..1b67371050 100644 --- a/src/telemetry/shapes.tsx +++ b/src/telemetry/shapes.tsx @@ -76,6 +76,11 @@ export const commandRunSchema = safeSchema({ project_policy_engine_count: z.number().int().nonnegative().optional(), project_config_bundle_count: z.number().int().nonnegative().optional(), project_harness_count: z.number().int().nonnegative().optional(), + project_runtime_codezip_count: z.number().int().nonnegative().optional(), + project_runtime_container_count: z.number().int().nonnegative().optional(), + project_runtime_container_local_count: z.number().int().nonnegative().optional(), + project_harness_container_count: z.number().int().nonnegative().optional(), + project_harness_container_local_count: z.number().int().nonnegative().optional(), project_payment_manager_count: z.number().int().nonnegative().optional(), project_gateway_target_count: z.number().int().nonnegative().optional(), project_policy_count: z.number().int().nonnegative().optional(), From 175e6055d5424bdcfc386b72a64d6e0d2769846d Mon Sep 17 00:00:00 2001 From: Gitika <53349492+notgitika@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:54:49 -0500 Subject: [PATCH 2/8] fix(build): address ContainerLocal bug bash findings (#2856) - K08/K09: the deploy guard rejects any change into or out of ContainerLocal for a deployed workload (CodeZip, Managed, Container <-> ContainerLocal). The service rejects artifact-type changes in place ("Agent artifact type cannot be updated"), so only a new workload may use ContainerLocal. A pre-feature (legacy) template's workload is never ContainerLocal, so it is rejected too. ContainerUri transitions are unchanged. - Item 3 (#2856): the guard also rejects a deployed Runtime changing between CodeZip and Container, both ways. The CLI flips a CodeZip Runtime to Container itself when a Dockerfile appears; on a deployed Runtime that ran a full CodeBuild, then the service failed the update ("Agent artifact type cannot be updated", UPDATE_ROLLBACK_COMPLETE) and agentcore.json stayed flipped, so every later deploy failed the same way. A pre-feature template's Runtime counts as CodeZip without a ContainerConfiguration, otherwise as Container. The error says to add a Runtime with a new name or keep the deployed build. Harness Managed <-> Container is unchanged. - A04/A06: the rejection says to keep the deployed build mode or add a workload with a new name, and, after a remove + re-add under the same name, to deploy the removal first, then add it again. The CodeZip -> Container auto-flip message says ContainerLocal can only be chosen when adding a workload. - I21/I22: the ARM64 execution probe always runs on a non-ARM64 daemon, even when `buildx inspect` lists linux/arm64; native ARM64 daemons still skip it. The error says when the builder lists linux/arm64 but cannot run ARM64 code. - I23: deploy chooses the builder first. When the executable is Docker and the active buildx builder's driver is not `docker`, the target is the docker-driver builder of the active Docker context (`docker context show`; each context has one under its own name). `default` would select the `default` context's builder, a different daemon on Docker Desktop, Colima, Rancher Desktop, or an ssh context. The buildx inspect and ARM64 probe run with that BUILDX_BUILDER, and the CDK operation gets the same value (set and restored like CDK_DOCKER). If `docker context show` fails, nothing is redirected and the warning says so. - I24: a relative CDK_DOCKER (one with a path separator) resolves against the current directory, like --build-config paths, before the builder check and before it reaches CDK. - K06: deploy warns when a ContainerLocal runtime or harness uses its own executionRoleArn: the role needs ecr:GetAuthorizationToken on * and ecr:BatchGetImage / ecr:GetDownloadUrlForLayer on cdk--container-assets--, otherwise the service fails at first invoke. - A01/A02: a failed `agentcore build` image build names the build context and Dockerfile it uses; add says it copied the Dockerfile to app//Dockerfile and that later edits to the original are not used. - A08: add runtime refuses when app//Dockerfile (or its .dockerignore) already exists and differs from the requested file; identical files proceed. - A07: --build-config rejects an absolute buildContextPath; dev resolves the build context instead of joining it, so it never double-prefixes. - A14: --build-config errors are reported against --build-config at parse time: dockerfile must be relative to buildContextPath, and the runtime and harness "requires a Dockerfile" rules. - A15: --build-config help states how dockerfile resolves with and without buildContextPath. - A13: the CodeBuild reserved build-arg rule (AWS_*, CODEBUILD_*, ...) no longer applies to ContainerLocal in the CLI schemas or --build-config; it stays for Container. The @aws/agentcore-cdk (L3) schema must match; that change is in a separate L3 PR. - H11: a ContainerLocal harness.yaml no longer suggests networkConfig.vpcId. Review follow-ups (#2855, #2856): - An invalid harness.yaml fails with InputValidationError naming the file (z.prettifyError), not a raw ZodError. - Harness builds are keyed by the agentcore.json entry name, as L3 keys its metadata, not by the name inside harness.yaml. - Local image tags trim separators from both ends of the name, so a name ending in `_` gives a valid reference. - harness.yaml: dockerfile with containerUri is reported once. - projectRoot is required by the harness and runtime docs templates; the runtime "is required" guards are gone. - The ContainerLocal capability check reports only a missing package as "update the dependency"; other load errors surface with their message. - Tests: Windows-safe CDK_DOCKER paths, a missing build context in the asset manifest, and an invalid harness.yaml in resolveWorkloads. I23 local evidence (x86_64, Docker 25.0.18, buildx 0.12.2; builder multiarch-builder uses the docker-container driver; restored to default after): $ BUILDX_BUILDER=multiarch-builder docker build --platform linux/arm64 -t i23-c . WARNING: No output specified with docker-container driver. Build result will only remain in the build cache. ... $ docker image inspect i23-c Error response from daemon: No such image: i23-c:latest $ BUILDX_BUILDER=default docker build --platform linux/arm64 -t i23-d . #3 naming to docker.io/library/i23-d done $ docker image inspect i23-d --format '{{.Id}}' sha256:3bb32867... This is the plain `docker build` cdk-assets runs (no --load), with the builder selected the way docker/setup-buildx-action selects it (BUILDX_BUILDER). On this host `docker buildx use multiarch-builder` alone did not redirect plain `docker build` (only `docker buildx build`, which then hit the same "No such image"), so the env var is the case that matters, and BUILDX_BUILDER=default overrides it. This host's active Docker context is `default`, so `default` is the context builder the deploy now selects. Co-authored-by: gitikavj --- src/assets/templates/harness/harness.yaml | 2 + src/core/dev/container.test.ts | 11 + src/core/dev/container.ts | 3 +- src/core/dev/containerTool.test.ts | 13 + src/core/dev/containerTool.ts | 11 +- src/core/project/backends/cdk.test.ts | 279 +++++++++++++++++- src/core/project/backends/cdk.ts | 73 +++-- .../project/backends/cdk/arm64Builder.test.ts | 175 ++++++++++- src/core/project/backends/cdk/arm64Builder.ts | 164 ++++++++-- .../backends/cdk/compatibility.test.ts | 21 ++ .../project/backends/cdk/compatibility.ts | 14 +- .../backends/cdk/localContainers.test.ts | 168 ++++++++++- .../project/backends/cdk/localContainers.ts | 110 +++++-- .../project/backends/cdk/localImages.test.ts | 25 ++ src/core/project/backends/cdk/localImages.ts | 2 +- src/core/project/backends/cdk/toolkit.test.ts | 29 ++ src/core/project/backends/cdk/toolkit.ts | 10 + src/core/project/backends/types.ts | 4 +- src/core/project/manager.tsx | 25 +- src/core/project/runtimeBuild.test.ts | 4 +- src/core/project/runtimeBuild.ts | 4 +- src/core/project/templates/harness.test.ts | 15 +- src/core/project/templates/harness.ts | 11 +- src/core/project/templates/runtimeDocs.ts | 30 +- src/handlers/project/add/buildConfig.test.ts | 64 ++++ src/handlers/project/add/buildConfig.ts | 89 +++++- .../project/add/harness/index.test.ts | 48 ++- src/handlers/project/add/harness/index.ts | 9 + .../project/add/runtime/index.test.ts | 109 ++++++- src/handlers/project/types.ts | 11 + src/projectSchemas/harness.ts | 12 +- src/projectSchemas/runtime.ts | 4 +- 32 files changed, 1393 insertions(+), 156 deletions(-) create mode 100644 src/handlers/project/add/buildConfig.test.ts diff --git a/src/assets/templates/harness/harness.yaml b/src/assets/templates/harness/harness.yaml index 1a4ecb7bbe..a1204b0776 100644 --- a/src/assets/templates/harness/harness.yaml +++ b/src/assets/templates/harness/harness.yaml @@ -181,7 +181,9 @@ tags: {} {{#if yaml.networkConfig}} {{yaml.networkConfig}} {{else}} +{{#unless containerLocal}} # For VPC Dockerfile builds, also supply networkConfig.vpcId. +{{/unless}} {{/if}} {{#if yaml.connections}} # Grants existing project resources and exposes their connection variables. diff --git a/src/core/dev/container.test.ts b/src/core/dev/container.test.ts index c26250c289..5fc7295c39 100644 --- a/src/core/dev/container.test.ts +++ b/src/core/dev/container.test.ts @@ -141,6 +141,17 @@ function commandCall(calls: ProcessCall[], operation: "build" | "run"): ProcessC } describe("ContainerDevRunner", () => { + test("uses an absolute buildContextPath inside the project without prefixing it again", async () => { + const root = await mkdtemp(join(tmpdir(), "agentcore-container-")); + tempDirectories.push(root); + await mkdir(join(root, "ctx"), { recursive: true }); + await writeFile(join(root, "ctx", "Dockerfile"), "FROM scratch\n"); + const { calls, runner } = harness(); + + await collect(runner.run(input(root, runtime({ buildContextPath: join(root, "ctx") })))); + + expect(commandCall(calls, "build").options.cwd).toBe(join(root, "ctx")); + }); test("builds with a widened context and redacts build arg values from errors", async () => { const projectRuntime = runtime({ buildContextPath: ".", diff --git a/src/core/dev/container.ts b/src/core/dev/container.ts index 24945edd4b..89cb9de544 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -68,7 +68,8 @@ export class ContainerDevRunner implements DevRunner { public async *run(input: DevServerInput): AsyncGenerator { input.signal.throwIfAborted(); - const context = join( + // resolve, not join: an absolute buildContextPath must not be prefixed again. + const context = resolve( input.projectRoot, input.runtime.buildContextPath ?? input.runtime.codeLocation, ); diff --git a/src/core/dev/containerTool.test.ts b/src/core/dev/containerTool.test.ts index 50615145d9..cf1da5d305 100644 --- a/src/core/dev/containerTool.test.ts +++ b/src/core/dev/containerTool.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test"; +import { resolve } from "node:path"; import { resolveCdkDockerExecutable, resolveContainerTool } from "./containerTool"; function available(installed: Record) { @@ -40,6 +41,18 @@ describe("resolveCdkDockerExecutable", () => { expect(probes).toEqual([]); }); + test("resolves a relative CDK_DOCKER path against the current directory", async () => { + const { check } = available({}); + expect(await resolveCdkDockerExecutable({ CDK_DOCKER: "./bin/dw" }, check)).toBe( + resolve(process.cwd(), "bin", "dw"), + ); + expect(await resolveCdkDockerExecutable({ CDK_DOCKER: "tools/dw" }, check)).toBe( + resolve(process.cwd(), "tools", "dw"), + ); + // A bare name is looked up on PATH, so it stays as-is. + expect(await resolveCdkDockerExecutable({ CDK_DOCKER: "nerdctl" }, check)).toBe("nerdctl"); + }); + test("detects the builder when CDK_DOCKER is unset", async () => { const { check } = available({ finch: { build: true } }); expect(await resolveCdkDockerExecutable({}, check)).toBe("finch"); diff --git a/src/core/dev/containerTool.ts b/src/core/dev/containerTool.ts index a8d424999e..3bd133245a 100644 --- a/src/core/dev/containerTool.ts +++ b/src/core/dev/containerTool.ts @@ -1,3 +1,4 @@ +import { isAbsolute, resolve, sep } from "node:path"; import { InvalidEnvironmentError } from "../../errors"; import { MissingToolError, toolAvailable } from "../../io"; @@ -33,11 +34,17 @@ export async function resolveContainerTool( /** * The executable CDK uses to build and publish local container images. An explicit - * CDK_DOCKER is honored as-is; otherwise the same detection as `agentcore dev` applies. + * CDK_DOCKER is honored; a relative path in it (one with a path separator, such as + * ./bin/docker) is resolved against the current directory, like --build-config + * paths, because image builds run from other directories. Without CDK_DOCKER the + * same detection as `agentcore dev` applies. */ export async function resolveCdkDockerExecutable( env: NodeJS.ProcessEnv = process.env, available: ToolAvailable = toolAvailable, ): Promise { - return env.CDK_DOCKER || resolveContainerTool(available); + const configured = env.CDK_DOCKER; + if (!configured) return resolveContainerTool(available); + const hasSeparator = configured.includes("/") || (sep === "\\" && configured.includes("\\")); + return hasSeparator && !isAbsolute(configured) ? resolve(configured) : configured; } diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index c1a916e49c..267b8db4dc 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { tmpdir } from "node:os"; import type { Stack } from "@aws-sdk/client-cloudformation"; import type { DeployResult, Project, ProjectEvent } from "../../../handlers/project/types"; @@ -209,6 +209,10 @@ type HarnessOptions = { describedStack?: Stack | null; /** Failure thrown by the fake synth process after emitting its output. */ synthError?: Error; + /** Failure a fake process throws for a given command, e.g. a local image build. */ + commandError?: (command: string[]) => Error | undefined; + /** Output a fake process streams for a given command, e.g. `docker buildx inspect`. */ + commandOutput?: (command: string[]) => string | undefined; /** Chunks the fake synth process streams through onOutput. */ synthOutput?: string[]; /** Lines the fake Toolkit reports through each operation's onOutput sink. */ @@ -217,6 +221,8 @@ type HarnessOptions = { function harness(options: HarnessOptions = {}) { const commands: { command: string[]; cwd: string }[] = []; + /** BUILDX_BUILDER each command ran with, from its env (undefined when inherited). */ + const commandBuilders: { command: string[]; buildxBuilder: string | undefined }[] = []; const runs: { operation: CdkOperation; options: CdkRunOptions }[] = []; const credentialRegions: string[] = []; const accountCredentials: CdkCredentialProvider[] = []; @@ -249,10 +255,19 @@ function harness(options: HarnessOptions = {}) { }, }) as unknown as ReturnType>, checkLocalBuilder: options.checkLocalBuilder, - resolveContainerExecutable: options.resolveContainerExecutable ?? (async () => "docker"), + // An explicit `resolveContainerExecutable: undefined` keeps the backend's own resolver. + resolveContainerExecutable: + "resolveContainerExecutable" in options + ? options.resolveContainerExecutable + : async () => "docker", identity: unusedIdentity(), - runner: async (command, { cwd, onOutput }) => { + runner: async (command, { cwd, env, onOutput }) => { commands.push({ command, cwd }); + commandBuilders.push({ command, buildxBuilder: env?.BUILDX_BUILDER }); + const commandError = options.commandError?.(command); + if (commandError) throw commandError; + const commandOutput = options.commandOutput?.(command); + if (commandOutput !== undefined) onOutput?.(commandOutput); for (const chunk of options.synthOutput ?? []) onOutput?.(chunk); if (options.synthError) throw options.synthError; }, @@ -329,6 +344,7 @@ function harness(options: HarnessOptions = {}) { backend, bootstrapCredentials, bootstrapRegions, + commandBuilders, commands, credentialRegions, credentials, @@ -464,9 +480,35 @@ describe("CdkBackend.build", () => { expect(h.commands[1]?.command.slice(0, 3)).toEqual(["docker", "build", "--load"]); const warnings = events.filter((event) => event.type === "warning"); expect(warnings.map((event) => event.message).join("\n")).toContain( - "docker buildx use default", + "build and publish with the docker-driver builder of the active Docker context", ); }); + test("names the build context and Dockerfile when a local image build fails", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + dockerfile: "Dockerfile.agent", + }), + ); + await writeAssembly(p, [TARGET.name], { localImages: { "runtime/agent": "abc123" } }); + await writeLocalImageManifest(p); + const h = harness({ + checkLocalBuilder: async () => ({}), + commandError: (command) => + command[1] === "build" ? new Error("COPY requirements.txt: not found") : undefined, + }); + const error = await collect(h.backend.build(p)).catch((caught: unknown) => caught as Error); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain("Building the runtime/agent image failed."); + expect(message).toContain("Build context: app/agent/"); + expect(message).toContain("Dockerfile: app/agent/Dockerfile.agent"); + expect(message).toContain("COPY requirements.txt: not found"); + }); test("builds no images when no workload builds locally", async () => { const p = await project(); p.spec.runtimes.push( @@ -582,6 +624,48 @@ describe("CdkBackend.build", () => { }); describe("CdkBackend.deploy", () => { + test.each(["build", "deploy"] as const)( + "%s resolves a relative CDK_DOCKER against the current directory", + async (operation) => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name], { localImages: { "runtime/agent": "abc123" } }); + await writeLocalImageManifest(p); + const checked: string[] = []; + const h = harness({ + describedStack: null, + resolveContainerExecutable: undefined, + checkLocalBuilder: async (_runner, _cwd, executable) => { + checked.push(executable); + return {}; + }, + }); + const expected = resolve(process.cwd(), "bin", "dw"); + const previous = process.env.CDK_DOCKER; + process.env.CDK_DOCKER = "./bin/dw"; + try { + if (operation === "build") await collect(h.backend.build(p)); + else await collectDeploy(h.backend.deploy(p, deployInput())); + } finally { + if (previous === undefined) delete process.env.CDK_DOCKER; + else process.env.CDK_DOCKER = previous; + } + expect(checked).toEqual([expected]); + if (operation === "deploy") { + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options.containerExecutable).toBe(expected); + } else { + expect(h.commands[1]?.command[0]).toBe(expected); + } + }, + ); test.each([ ["Container", "ContainerLocal"], ["ContainerLocal", "Container"], @@ -601,9 +685,12 @@ describe("CdkBackend.deploy", () => { checkLocalBuilder: async () => ({}), }); await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( - "between Container and ContainerLocal is not supported", + "cannot be switched into or out of ContainerLocal", ); - expect(h.commands.map(({ command }) => command)).toEqual([synthCommand(p)]); + // Besides a buildx builder query, only synth ran: nothing was built or deployed. + expect( + h.commands.map(({ command }) => command).filter((command) => command[1] !== "buildx"), + ).toEqual([synthCommand(p)]); expect(h.runs).toHaveLength(0); expect(h.bootstrapRegions).toHaveLength(0); expect(h.transactionSearchRegions).toHaveLength(0); @@ -758,7 +845,7 @@ describe("CdkBackend.deploy", () => { checkLocalBuilder: async () => ({}), }); await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( - "between Container and ContainerLocal is not supported", + "cannot be switched into or out of ContainerLocal", ); expect(h.stackReads[0]?.stackName).toBe("CustomOrders"); expect(h.runs).toHaveLength(0); @@ -783,7 +870,7 @@ describe("CdkBackend.deploy", () => { checkLocalBuilder: async () => ({}), }); await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( - "between Container and ContainerLocal is not supported", + "cannot be switched into or out of ContainerLocal", ); expect(h.stackReads[0]?.stackName).toBe("AgentCore-example-default-0"); expect(h.runs).toHaveLength(0); @@ -814,7 +901,8 @@ describe("CdkBackend.deploy", () => { ); expect(provisioned).toBe(false); expect(h.runs).toHaveLength(0); - expect(h.commands).toHaveLength(0); + // Only the buildx builder query ran, not synth. + expect(h.commands.map(({ command }) => command)).toEqual([["docker", "buildx", "inspect"]]); }); test("reuses the workload build modes the command resolved instead of rereading harness.yaml", async () => { @@ -913,6 +1001,179 @@ describe("CdkBackend.deploy", () => { "'multiarch-builder' uses the docker-container driver", ); }); + test.each([ + ["docker", "docker-container", "desktop-linux"], + ["/usr/local/bin/docker", "kubernetes", "desktop-linux"], + ["docker", "docker", undefined], + ["finch", "docker-container", undefined], + ] as const)( + "with %s and a %s buildx driver, hands CDK BUILDX_BUILDER=%s", + async (executable, driver, expected) => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const checks: (string | undefined)[] = []; + const h = harness({ + describedStack: null, + resolveContainerExecutable: async () => executable, + commandOutput: (command) => + command[1] === "buildx" + ? `Name: ci\nDriver: ${driver}\n` + : command[1] === "context" + ? "desktop-linux\n" + : undefined, + checkLocalBuilder: async (_runner, _cwd, _executable, options) => { + checks.push(options?.buildxBuilder); + return {}; + }, + }); + await collectDeploy(h.backend.deploy(p, deployInput())); + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options.buildxBuilder).toBe(expected); + expect(checks).toEqual([expected]); + }, + ); + test.each(["default", "colima"])( + "probes and deploys with the same BUILDX_BUILDER for Docker context %s", + async (context) => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + // The real check runs: an x86 daemon, so the ARM64 probe builds. + const h = harness({ + describedStack: null, + commandOutput: (command) => { + if (command[1] === "info") return '{"OSType":"linux","Architecture":"x86_64"}'; + if (command[1] === "context") return `${context}\n`; + if (command[1] === "buildx") { + // The redirected builder is the context's docker-driver builder. + return h.commandBuilders.at(-1)?.buildxBuilder === context + ? `Name: ${context}\nDriver: docker\n` + : "Name: ci\nDriver: docker-container\n"; + } + return undefined; + }, + }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + const probe = h.commandBuilders.find( + ({ command }) => command[1] === "build" && command.includes("linux/arm64"), + ); + const inspects = h.commandBuilders.filter(({ command }) => command[1] === "buildx"); + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options.buildxBuilder).toBe(context); + expect(probe?.buildxBuilder).toBe(context); + // First the active builder is read, then the chosen one is inspected. + expect(inspects.map(({ buildxBuilder }) => buildxBuilder)).toEqual([undefined, context]); + const warnings = events.filter((event) => event.type === "warning").map((e) => e.message); + expect(warnings.join("\n")).toContain(`BUILDX_BUILDER=${context}`); + }, + ); + test("falls back to the active builder with a warning when docker context show fails", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const checks: (string | undefined)[] = []; + const h = harness({ + describedStack: null, + commandOutput: (command) => + command[1] === "buildx" ? "Name: ci\nDriver: docker-container\n" : undefined, + commandError: (command) => + command[1] === "context" + ? new Error("docker: 'context' is not a docker command") + : undefined, + checkLocalBuilder: async (_runner, _cwd, _executable, options) => { + checks.push(options?.buildxBuilder); + return { buildx: { name: "ci", driver: "docker-container" } }; + }, + }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + const deployRun = h.runs.find((run) => run.operation.kind === "deploy"); + expect(deployRun?.options).not.toHaveProperty("buildxBuilder"); + expect(checks).toEqual([undefined]); + const warnings = events.filter((event) => event.type === "warning").map((e) => e.message); + const warning = warnings.find((message) => message.includes("docker context")); + expect(warning).toContain("could not read the active Docker context"); + expect(warning).toContain("'context' is not a docker command"); + expect(warnings.join("\n")).not.toContain("BUILDX_BUILDER"); + }); + test("warns that a bring-your-own execution role needs ECR pull access", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + executionRoleArn: "arn:aws:iam::111122223333:role/Mine", + }), + ProjectRuntimeSchema.parse({ + name: "other", + build: "ContainerLocal", + codeLocation: "app/other", + entrypoint: "main.py", + }), + ); + p.spec.harnesses.push({ name: "helper", path: "app/helper" }); + await mkdir(join(p.rootPath, "app", "helper"), { recursive: true }); + await writeFile( + join(p.rootPath, "app", "helper", "harness.yaml"), + "name: helper\nmodel: {bedrockModelConfig: {modelId: test-model}}\n" + + "dockerfile: Dockerfile\nbuild: ContainerLocal\n" + + "executionRoleArn: arn:aws:iam::111122223333:role/HarnessRole\n", + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ describedStack: null, checkLocalBuilder: async () => ({}) }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + const warnings = events.filter((event) => event.type === "warning").map((e) => e.message); + const warning = warnings.find((message) => message.includes("executionRoleArn")); + expect(warning).toContain("runtime/agent, harness/helper use ContainerLocal"); + expect(warning).not.toContain("runtime/other"); + expect(warning).toContain("ecr:GetAuthorizationToken on *"); + expect(warning).toContain("ecr:BatchGetImage and ecr:GetDownloadUrlForLayer"); + expect(warning).toContain("cdk--container-assets--"); + expect(warning).toContain("fails at first invoke"); + expect(warning).not.toContain("111122223333"); + }); + test("does not warn about execution roles the project creates", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "ContainerLocal", + codeLocation: "app/agent", + entrypoint: "main.py", + }), + ); + await writeAssembly(p, [TARGET.name]); + const h = harness({ describedStack: null, checkLocalBuilder: async () => ({}) }); + const { events } = await collectDeploy(h.backend.deploy(p, deployInput())); + expect( + events.some( + (event) => event.type === "warning" && event.message.includes("executionRoleArn"), + ), + ).toBe(false); + }); test("skips builder detection when no workload builds locally", async () => { const p = await project(); await writeAssembly(p, [TARGET.name]); diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 6701df8453..6c1864ac32 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -10,16 +10,19 @@ import type { DeployableResource, ResolvedDeployedResource, ResolvedProjectResource, + LocalWorkloadSources, WorkloadBuilds, + WorkloadKey, } from "../../../handlers/project/types"; import { assertCdkLocalContainerSupport, cdkCompatibilityWarning } from "./cdk/compatibility"; import { assertSupportedBuildTransitions, + byoExecutionRoleWarning, hasLocalContainerBuilds, - resolveWorkloadBuilds, + resolveWorkloads, type DeployedTemplate, } from "./cdk/localContainers"; -import { buildxDriverWarning, checkArm64Builder } from "./cdk/arm64Builder"; +import { buildxDriverWarning, checkArm64Builder, selectBuildxBuilder } from "./cdk/arm64Builder"; import { localImageBuilds } from "./cdk/localImages"; import { resolveCdkDockerExecutable } from "../../dev/containerTool"; import { @@ -300,9 +303,9 @@ export class CdkBackend implements ProjectBackend { } public async *build(project: Project): AsyncGenerator { - const builds = resolveWorkloadBuilds(project); + const { builds, local } = resolveWorkloads(project); yield* this.synthesize(project, true, builds); - yield* this.buildLocalImages(project, builds); + yield* this.buildLocalImages(project, builds, local); } /** @@ -313,6 +316,7 @@ export class CdkBackend implements ProjectBackend { private async *buildLocalImages( project: Project, builds: WorkloadBuilds, + local: LocalWorkloadSources, ): AsyncGenerator { if (!hasLocalContainerBuilds(builds)) return; const images = await localImageBuilds( @@ -325,23 +329,38 @@ export class CdkBackend implements ProjectBackend { const executable = await this.resolveContainerExecutable(); yield { type: "step", message: `checking that ${executable} can build Linux ARM64 images` }; const report = await this.checkLocalBuilder(this.runner, project.rootPath, executable); - const warning = buildxDriverWarning(report); + const warning = buildxDriverWarning(report, executable); if (warning) yield { type: "warning", message: warning }; // Docker with buildx may build with a driver that keeps the image out of the // local store; --load keeps it there. Finch and Podman load by default. const load = report.buildx !== undefined; for (const image of images) { yield { type: "step", message: `building ${image.resource} image ${image.tag}` }; - yield* withOutputEvents((emit) => { - const lines = createLineSplitter(emit); - return this.runner(image.command(executable, { load }), { - cwd: image.directory, - onOutput: (chunk) => { - this.logger.debug(chunk); - lines.push(chunk); - }, - }).finally(() => lines.flush()); - }); + try { + yield* withOutputEvents((emit) => { + const lines = createLineSplitter(emit); + return this.runner(image.command(executable, { load }), { + cwd: image.directory, + onOutput: (chunk) => { + this.logger.debug(chunk); + lines.push(chunk); + }, + }).finally(() => lines.flush()); + }); + } catch (error) { + // The failing command ran in the staged copy inside the assembly; name the + // project directory and Dockerfile the image is actually built from. + const source = local.get(image.resource as WorkloadKey); + const from = source + ? ` Build context: ${source.context}/ (COPY and ADD paths resolve against it); ` + + `Dockerfile: ${source.context}/${source.dockerfile}.` + : ""; + throw new ProjectStateError( + `Building the ${image.resource} image failed.${from}\n\n` + + (error instanceof Error ? error.message : String(error)), + { cause: error }, + ); + } } } @@ -357,13 +376,16 @@ export class CdkBackend implements ProjectBackend { // before any AWS mutation, so a local problem never leaves credentials // provisioned or the stack ARN unrecorded. await this.ensureCdkDependencies(project); - const builds = input.workloadBuilds ?? resolveWorkloadBuilds(project); + const { builds, local } = input.workloadBuilds + ? { builds: input.workloadBuilds, local: input.localWorkloads ?? new Map() } + : resolveWorkloads(project); const deployedState = (await readDeployedState(this.json, project.rootPath)).targets[ target.name ]; - // CDK builds and publishes ContainerLocal images with CDK_DOCKER, so check - // that same executable. + // CDK builds and publishes ContainerLocal images with CDK_DOCKER and the + // BUILDX_BUILDER chosen here, so the check runs on that same builder. let containerExecutable: string | undefined; + let buildxBuilder: string | undefined; if (hasLocalContainerBuilds(builds)) { this.assertLocalCdkSupport(this.cdkDirectory(project)); containerExecutable = await this.resolveContainerExecutable(); @@ -371,13 +393,22 @@ export class CdkBackend implements ProjectBackend { type: "step", message: `checking that ${containerExecutable} can build Linux ARM64 images`, }; + const selection = await selectBuildxBuilder( + this.runner, + project.rootPath, + containerExecutable, + ); + buildxBuilder = selection.buildxBuilder; const report = await this.checkLocalBuilder( this.runner, project.rootPath, containerExecutable, + { ...(buildxBuilder && { buildxBuilder }) }, ); - const warning = buildxDriverWarning(report); + const warning = selection.warning ?? buildxDriverWarning(report, containerExecutable); if (warning) yield { type: "warning", message: warning }; + const roleWarning = byoExecutionRoleWarning(local); + if (roleWarning) yield { type: "warning", message: roleWarning }; } // Read before provisioning rewrites the credentials map: it is the only record @@ -422,6 +453,7 @@ export class CdkBackend implements ProjectBackend { credentials, region: target.region, ...(containerExecutable && { containerExecutable }), + ...(buildxBuilder && { buildxBuilder }), }; // Decided before the Toolkit is handed the assembly: it reads a template @@ -833,7 +865,8 @@ export class CdkBackend implements ProjectBackend { } /** - * Rejects switching a deployed workload between Container and ContainerLocal. + * Rejects switching a deployed workload into or out of ContainerLocal, or a + * deployed Runtime between CodeZip and Container. * Reads the live template of the synthesized stack, looked up by name (never by * a recorded ARN, which can point at a deleted stack), after synthesis and * before the stack is touched. Credential providers are already provisioned. diff --git a/src/core/project/backends/cdk/arm64Builder.test.ts b/src/core/project/backends/cdk/arm64Builder.test.ts index b70bc3bb67..3ba7110827 100644 --- a/src/core/project/backends/cdk/arm64Builder.test.ts +++ b/src/core/project/backends/cdk/arm64Builder.test.ts @@ -2,7 +2,13 @@ import { afterEach, describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { buildxDriverWarning, checkArm64Builder } from "./arm64Builder"; +import { + buildxDriverWarning, + checkArm64Builder, + needsDockerDriverBuilder, + selectBuildxBuilder, +} from "./arm64Builder"; +import type { ProcessRunner } from "../../../../io"; describe("local container builder prerequisites", () => { const projects: string[] = []; @@ -47,9 +53,10 @@ describe("local container builder prerequisites", () => { }); test.each(["linux/arm64", "linux/arm64/v8", "linux/arm64*"])( - "accepts advertised %s support without building or provisioning a builder", + "still runs the execution probe when buildx advertises %s on an x86 daemon", async (platform) => { const commands: string[][] = []; + const project = projectDirectory(); await checkArm64Builder( async (command, options) => { commands.push(command); @@ -59,16 +66,40 @@ describe("local container builder prerequisites", () => { : `Platforms: linux/amd64*, ${platform}\n`, ); }, - "/project", + project, "docker", ); - expect(commands).toEqual([ - ["docker", "info", "--format", "{{json .}}"], - ["docker", "buildx", "inspect"], - ]); + expect(commands.map((command) => command[1])).toEqual(["info", "buildx", "build"]); }, ); + test("rejects a builder that advertises linux/arm64 but cannot execute ARM64 code", async () => { + const project = projectDirectory(); + const error = await checkArm64Builder( + async (command, options) => { + if (command[1] === "info") { + options.onOutput?.('{"OSType":"linux","Architecture":"x86_64"}'); + } else if (command[1] === "buildx") { + options.onOutput?.( + "Name: stale\nDriver: docker-container\nPlatforms: linux/amd64, linux/arm64\n", + ); + } else { + options.onOutput?.("exec /arm64-check: exec format error\n"); + throw new Error("exit code 1"); + } + }, + project, + "docker", + ).catch((caught: unknown) => caught as Error); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain("cannot build Linux ARM64 images"); + expect(message).toContain( + "buildx builder 'stale' (driver docker-container) lists linux/arm64 but cannot run ARM64 code", + ); + expect(message).toContain("ARM64 test build failed: exec format error"); + }); + test.each(["unsupported buildx", "unadvertised ARM64", "failed buildx with partial output"])( "checks real ARM64 execution for a compatible builder with %s", async (capabilities) => { @@ -203,10 +234,10 @@ describe("local container builder prerequisites", () => { commands.push(command); options.onOutput?.(command[1] === "info" ? "not JSON" : "Platforms: linux/arm64\n"); }, - "/project", + projectDirectory(), "finch", ); - expect(commands.map((command) => command[1])).toEqual(["info", "buildx"]); + expect(commands.map((command) => command[1])).toEqual(["info", "buildx", "build"]); }); test("accepts a native ARM64 Podman host from its host.os/host.arch info", async () => { @@ -238,7 +269,7 @@ describe("local container builder prerequisites", () => { expect(commands.map((command) => command[1])).toEqual(["info", "build"]); }); - test("bounds the info and buildx queries with a timeout", async () => { + test("bounds the info and buildx queries and the probe with a timeout", async () => { const signals: (AbortSignal | undefined)[] = []; await checkArm64Builder( async (command, options) => { @@ -249,10 +280,10 @@ describe("local container builder prerequisites", () => { : "Platforms: linux/arm64\n", ); }, - "/project", + projectDirectory(), "docker", ); - expect(signals).toHaveLength(2); + expect(signals).toHaveLength(3); for (const signal of signals) expect(signal).toBeInstanceOf(AbortSignal); }); @@ -322,16 +353,130 @@ describe("local container builder prerequisites", () => { }); }); +describe("checkArm64Builder with a chosen buildx builder", () => { + test("runs buildx inspect and the probe with that BUILDX_BUILDER", async () => { + const project = mkdtempSync(join(tmpdir(), "agentcore-builder-test-")); + try { + const seen: { command: string; builder: string | undefined }[] = []; + await checkArm64Builder( + async (command, options) => { + seen.push({ command: command[1]!, builder: options.env?.BUILDX_BUILDER }); + if (command[1] === "info") + options.onOutput?.('{"OSType":"linux","Architecture":"x86_64"}'); + }, + project, + "docker", + { buildxBuilder: "colima" }, + ); + expect(seen).toEqual([ + { command: "info", builder: "colima" }, + { command: "buildx", builder: "colima" }, + { command: "build", builder: "colima" }, + ]); + } finally { + rmSync(project, { recursive: true, force: true }); + } + }); + test("inherits the environment when no builder is chosen", async () => { + const envs: (NodeJS.ProcessEnv | undefined)[] = []; + await checkArm64Builder( + async (_command, options) => { + envs.push(options.env); + options.onOutput?.('{"OSType":"linux","Architecture":"aarch64"}'); + }, + "project", + "docker", + ); + expect(envs).toEqual([undefined, undefined]); + }); +}); + +describe("selectBuildxBuilder", () => { + function runner(outputs: Record): { + run: ProcessRunner; + commands: string[][]; + } { + const commands: string[][] = []; + const run: ProcessRunner = async (command, options) => { + commands.push(command); + const output = outputs[command.slice(1).join(" ")]; + if (output instanceof Error) throw output; + if (output !== undefined) options.onOutput?.(output); + }; + return { run, commands }; + } + const containerDriver = "Name: ci-builder\nDriver: docker-container\nNodes:\nName: ci0\n"; + + test.each(["default", "colima", "desktop-linux"])( + "redirects a non-docker driver to the docker-driver builder of context %s", + async (context) => { + const { run } = runner({ "buildx inspect": containerDriver, "context show": `${context}\n` }); + const selection = await selectBuildxBuilder(run, "project", "/usr/local/bin/docker"); + expect(selection.buildxBuilder).toBe(context); + expect(selection.warning).toContain("'ci-builder' uses the docker-container driver"); + expect(selection.warning).toContain(`build and publish with '${context}'`); + expect(selection.warning).toContain(`BUILDX_BUILDER=${context}`); + }, + ); + test("does not redirect, and says so, when docker context show fails", async () => { + const { run } = runner({ + "buildx inspect": containerDriver, + "context show": new Error("context: unknown command"), + }); + const selection = await selectBuildxBuilder(run, "project", "docker"); + expect(selection.buildxBuilder).toBeUndefined(); + expect(selection.warning).toContain("could not read the active Docker context"); + expect(selection.warning).toContain("context: unknown command"); + expect(selection.warning).toContain("'ci-builder' unchanged"); + expect(selection.warning).not.toContain("BUILDX_BUILDER"); + }); + test("does not redirect when docker context show prints no usable name", async () => { + const { run } = runner({ "buildx inspect": containerDriver, "context show": "not a name\n" }); + const selection = await selectBuildxBuilder(run, "project", "docker"); + expect(selection.buildxBuilder).toBeUndefined(); + expect(selection.warning).toContain("it printed 'not a name'"); + }); + test("leaves the docker driver, missing buildx, and non-Docker builders alone", async () => { + const docker = runner({ "buildx inspect": "Name: default\nDriver: docker\n" }); + expect(await selectBuildxBuilder(docker.run, "project", "docker")).toEqual({}); + expect(docker.commands).toEqual([["docker", "buildx", "inspect"]]); + const noBuildx = runner({ "buildx inspect": new Error("unknown command: buildx") }); + expect(await selectBuildxBuilder(noBuildx.run, "project", "docker")).toEqual({}); + const finch = runner({ "buildx inspect": containerDriver }); + expect(await selectBuildxBuilder(finch.run, "project", "finch")).toEqual({}); + expect(finch.commands).toEqual([]); + }); +}); + describe("buildxDriverWarning", () => { const containerDriver = { buildx: { name: "multiarch-builder", driver: "docker-container" } }; - test("warns about a non-docker driver and suggests the default builder", () => { - const warning = buildxDriverWarning(containerDriver); + test("says Docker deploys build with the active context's docker-driver builder", () => { + const warning = buildxDriverWarning(containerDriver, "/usr/bin/docker"); expect(warning).toContain("'multiarch-builder'"); expect(warning).toContain("docker-container"); - expect(warning).toContain("docker buildx use default"); + expect(warning).toContain("docker-driver builder of the active Docker context"); + expect(warning).not.toContain("BUILDX_BUILDER=default"); + }); + test("suggests the default builder for a builder the deploy cannot redirect", () => { + expect(buildxDriverWarning(containerDriver, "/tools/dw")).toContain( + "Run 'docker buildx use default'", + ); + expect(buildxDriverWarning(containerDriver, "/tools/dw")).not.toContain("BUILDX_BUILDER"); }); test("stays quiet for the docker driver and without buildx", () => { expect(buildxDriverWarning({ buildx: { name: "default", driver: "docker" } })).toBeUndefined(); expect(buildxDriverWarning({})).toBeUndefined(); }); }); + +describe("needsDockerDriverBuilder", () => { + test("redirects Docker only when the active builder's driver is not docker", () => { + const containerDriver = { name: "ci", driver: "docker-container" }; + expect(needsDockerDriverBuilder("docker", containerDriver)).toBe(true); + expect(needsDockerDriverBuilder("/usr/local/bin/docker", containerDriver)).toBe(true); + expect(needsDockerDriverBuilder("docker", { name: "default", driver: "docker" })).toBe(false); + expect(needsDockerDriverBuilder("docker", undefined)).toBe(false); + expect(needsDockerDriverBuilder("finch", containerDriver)).toBe(false); + expect(needsDockerDriverBuilder("/tools/dw", containerDriver)).toBe(false); + }); +}); diff --git a/src/core/project/backends/cdk/arm64Builder.ts b/src/core/project/backends/cdk/arm64Builder.ts index bd834401f1..76a5ee062c 100644 --- a/src/core/project/backends/cdk/arm64Builder.ts +++ b/src/core/project/backends/cdk/arm64Builder.ts @@ -5,15 +5,18 @@ * worse, publishes an image that cannot start. The check never installs emulation * or provisions a builder; it only reports what to fix. * - * In order, the first that succeeds wins: - * 1. ` info`: a native linux/arm64 daemon builds ARM64 directly. Docker - * and Finch report OSType/Architecture; Podman reports host.os/host.arch. - * Unreadable info is not fatal: the later checks decide. - * 2. ` buildx inspect`: the active builder lists linux/arm64. - * 3. An execution probe: build a scratch image whose only step runs a tiny ARM64 - * program. This covers builders without buildx (Finch, Podman) and proves - * emulation (binfmt/QEMU) actually executes ARM64 code, not just that it is - * advertised. It uses --network none and --no-cache, so it downloads nothing. + * In order: + * 1. ` info`: a native linux/arm64 daemon builds ARM64 directly, and + * the check passes. Docker and Finch report OSType/Architecture; Podman + * reports host.os/host.arch. Unreadable info is not fatal: the probe decides. + * 2. ` buildx inspect`: read for the active builder's name, driver, and + * platforms, which go into warnings and the error message. A listed + * linux/arm64 is not proof: a builder can keep advertising a platform whose + * emulation is gone (binfmt lost after a reboot, a builder cached in CI). + * 3. An execution probe, on every non-ARM64 daemon: build a scratch image whose + * only step runs a tiny ARM64 program. This covers builders without buildx + * (Finch, Podman) and proves emulation (binfmt/QEMU) actually executes ARM64 + * code. It uses --network none and --no-cache, so it downloads nothing. * * The probe's build context lives in the project's agentcore/.cli/ directory, not * the OS temp directory: VM-backed builders (Finch, Podman machine, Docker Desktop) @@ -52,6 +55,7 @@ async function probeArm64Execution( runner: ProcessRunner, cwd: string, executable: string, + env: NodeJS.ProcessEnv | undefined, ): Promise { const parent = join(cwd, "agentcore", ".cli"); mkdirSync(parent, { recursive: true }); @@ -82,6 +86,7 @@ async function probeArm64Execution( ], { cwd: context, + ...(env && { env }), signal: AbortSignal.timeout(60_000), onOutput: (chunk) => { output += chunk; @@ -97,10 +102,16 @@ async function probeArm64Execution( const QUERY_TIMEOUT_MS = 30_000; -async function capture(runner: ProcessRunner, command: string[], cwd: string): Promise { +async function capture( + runner: ProcessRunner, + command: string[], + cwd: string, + env?: NodeJS.ProcessEnv, +): Promise { let output = ""; await runner(command, { cwd, + ...(env && { env }), signal: AbortSignal.timeout(QUERY_TIMEOUT_MS), onOutput: (chunk) => { output += chunk; @@ -141,6 +152,14 @@ export type BuildxBuilder = { name?: string; driver?: string }; /** What the check learned about the builder, for the image build and its warnings. */ export type Arm64BuilderReport = { buildx?: BuildxBuilder }; +export type Arm64BuilderCheckOptions = { + /** + * Set as BUILDX_BUILDER for every command the check runs, so `buildx inspect` + * and the probe describe the builder the deploy hands to CDK. + */ + buildxBuilder?: string; +}; + function parseBuildx(output: string): BuildxBuilder { // The first Name: line is the builder; later ones name its nodes. return { @@ -170,10 +189,14 @@ export async function checkArm64Builder( runner: ProcessRunner, cwd: string, executable: string, + options: Arm64BuilderCheckOptions = {}, ): Promise { + const env = options.buildxBuilder + ? { ...process.env, BUILDX_BUILDER: options.buildxBuilder } + : undefined; let info: string; try { - info = await capture(runner, [executable, "info", "--format", "{{json .}}"], cwd); + info = await capture(runner, [executable, "info", "--format", "{{json .}}"], cwd, env); } catch { throw new ProjectStateError( `Cannot access the container builder '${executable}'. Check that it is installed and ` + @@ -187,7 +210,7 @@ export async function checkArm64Builder( let platforms: string[] = []; if (!basename(executable).startsWith("podman")) { try { - const output = await capture(runner, [executable, "buildx", "inspect"], cwd); + const output = await capture(runner, [executable, "buildx", "inspect"], cwd, env); buildx = parseBuildx(output); platforms = [...output.matchAll(/^\s*Platforms:\s*(.+)$/gm)].flatMap((match) => match[1]!.split(",").map((platform) => platform.trim().replace(/\*$/, "")), @@ -198,17 +221,17 @@ export async function checkArm64Builder( } const report = { ...(buildx && { buildx }) }; if (daemon?.os === "linux" && ["arm64", "aarch64"].includes(daemon.arch)) return report; - if (platforms.includes("linux/arm64") || platforms.includes("linux/arm64/v8")) return report; + const listsArm64 = platforms.includes("linux/arm64") || platforms.includes("linux/arm64/v8"); try { - await probeArm64Execution(runner, cwd, executable); + await probeArm64Execution(runner, cwd, executable, env); return report; } catch (error) { const found = [ daemon ? `daemon ${daemon.os}/${daemon.arch}` : "daemon architecture unknown", buildx ? `buildx builder '${buildx.name ?? "unknown"}' (driver ${buildx.driver ?? "unknown"}) ` + - "does not list linux/arm64" + (listsArm64 ? "lists linux/arm64 but cannot run ARM64 code" : "does not list linux/arm64") : "no buildx", `ARM64 test build failed: ${probeFailureReason(error)}`, ].join("; "); @@ -221,16 +244,109 @@ export async function checkArm64Builder( } /** - * A warning when the active Docker buildx builder's driver is not `docker`: images - * it builds may not be loaded into the local image store, so CDK's push can fail. + * Whether ContainerLocal deploys must redirect Docker to a docker-driver builder. + * CDK publishes with a plain `docker build` (no --load), so a builder whose driver + * is not `docker` (docker-container, kubernetes, remote; what + * docker/setup-buildx-action creates) keeps the image out of the local store and + * the push fails with "No such image". Only Docker reads BUILDX_BUILDER. */ -export function buildxDriverWarning(report: Arm64BuilderReport): string | undefined { - const driver = report.buildx?.driver; - if (!driver || driver === "docker") return undefined; - const name = report.buildx?.name ?? "the active builder"; +export function needsDockerDriverBuilder( + executable: string, + builder: BuildxBuilder | undefined, +): boolean { + const driver = builder?.driver; + return basename(executable).startsWith("docker") && !!driver && driver !== "docker"; +} + +function driverWarningPrefix(builder: BuildxBuilder): string { return ( - `The active buildx builder '${name}' uses the ${driver} driver, so images it builds may not ` + - "be loaded into the local Docker image store and the CDK push can fail. " + - "Run 'docker buildx use default' to switch to the docker driver." + `The active buildx builder '${builder.name ?? "unknown"}' uses the ${builder.driver} driver, ` + + "which does not load the images it builds into the local Docker image store that CDK pushes from." ); } + +/** The BUILDX_BUILDER a ContainerLocal deploy builds with, and a warning to show. */ +export type BuildxBuilderSelection = { buildxBuilder?: string; warning?: string }; + +// Docker context names: a letter or digit, then letters, digits, `_`, `.`, `+`, `-`. +const CONTEXT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.+-]*$/; + +/** + * Chooses the builder a ContainerLocal deploy builds and publishes with, before the + * ARM64 check runs on it. When the executable is Docker and the active buildx + * builder's driver is not `docker`, the deploy is redirected to the docker-driver + * builder of the active Docker context: every context has one, named after the + * context (`docker context show`). BUILDX_BUILDER=default would instead select the + * `default` context's builder, which on Docker Desktop, Colima, Rancher Desktop, + * or an ssh context is a different daemon. If the context cannot be read, nothing + * is redirected and the warning says so. + */ +export async function selectBuildxBuilder( + runner: ProcessRunner, + cwd: string, + executable: string, +): Promise { + if (!basename(executable).startsWith("docker")) return {}; + let active: BuildxBuilder; + try { + active = parseBuildx(await capture(runner, [executable, "buildx", "inspect"], cwd)); + } catch { + // Without buildx, plain `docker build` uses the daemon's builder; nothing to redirect. + return {}; + } + if (!needsDockerDriverBuilder(executable, active)) return {}; + + let context: string | undefined; + let reason = "it printed no context name"; + try { + const output = await capture(runner, [executable, "context", "show"], cwd); + const last = output + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .pop(); + if (last && CONTEXT_NAME.test(last)) context = last; + else if (last) reason = `it printed '${last.length > 80 ? `${last.slice(0, 80)}…` : last}'`; + } catch (error) { + reason = error instanceof Error ? error.message : String(error); + } + if (!context) { + return { + warning: + `${driverWarningPrefix(active)} The deploy could not read the active Docker context ` + + `('${executable} context show' failed: ${reason}), so it builds with ` + + `'${active.name ?? "the active builder"}' unchanged and the CDK push can fail. ` + + "Run 'docker buildx use ' with the name 'docker context show' prints to " + + "switch to the docker driver.", + }; + } + return { + buildxBuilder: context, + warning: + `${driverWarningPrefix(active)} ContainerLocal deploys therefore build and publish with ` + + `'${context}', the docker-driver builder of the active Docker context, by setting ` + + `BUILDX_BUILDER=${context} for the deploy.`, + }; +} + +/** + * A warning when the active Docker buildx builder's driver is not `docker`: images + * it builds may not be loaded into the local image store, so CDK's push can fail. + * For Docker, deploys avoid that by building with the active Docker context's + * docker-driver builder instead (see {@link selectBuildxBuilder}). + */ +export function buildxDriverWarning( + report: Arm64BuilderReport, + executable = "docker", +): string | undefined { + const builder = report.buildx; + if (!builder?.driver || builder.driver === "docker") return undefined; + const prefix = driverWarningPrefix(builder); + if (needsDockerDriverBuilder(executable, builder)) { + return ( + `${prefix} ContainerLocal deploys therefore build and publish with the docker-driver ` + + "builder of the active Docker context instead, by setting BUILDX_BUILDER for the deploy." + ); + } + return `${prefix} The CDK push can fail. Run 'docker buildx use default' to switch to the docker driver.`; +} diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 1fe9fdebe7..8aa60252a3 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -36,6 +36,27 @@ describe("cdkCompatibilityWarning", () => { expect(() => assertCdkLocalContainerSupport(directory)).toThrow('supports "ContainerLocal"'); }); + test("asks to update the dependency when the package is not installed", async () => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-compatibility-")); + tempDirectories.push(directory); + expect(() => assertCdkLocalContainerSupport(directory)).toThrow('supports "ContainerLocal"'); + }); + + test("reports a package that fails to load with its own error", async () => { + const directory = await cdkDirectoryWith("1.0.2"); + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await writeFile(join(packageDirectory, "index.js"), 'throw new Error("corrupt install");'); + let message = ""; + try { + assertCdkLocalContainerSupport(directory); + } catch (error) { + message = (error as Error).message; + } + expect(message).toContain("Cannot load @aws/agentcore-cdk"); + expect(message).toContain("corrupt install"); + expect(message).not.toContain('supports "ContainerLocal"'); + }); + test("accepts a supporting local or prerelease CDK package by capability", async () => { const directory = await cdkDirectoryWith("1.0.2-rc.1"); const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 2eced4df0d..45b38ec0f5 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -16,9 +16,19 @@ export function assertCdkLocalContainerSupport(cdkDirectory: string): void { }; if (cdk.BuildTypeSchema?.safeParse("ContainerLocal").success && cdk.LocalContainerImageAsset) return; - } catch { - // An old or unavailable package must never silently strip a harness build selection. + } catch (error) { + // A missing package falls through to "update the dependency". Anything else is a + // broken install, which that advice would hide. + const code = (error as { code?: unknown }).code; + if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND") { + throw new ProjectStateError( + `Cannot load @aws/agentcore-cdk from ${cdkDirectory}: ` + + (error instanceof Error ? error.message : String(error)), + { cause: error }, + ); + } } + // An old or unavailable package must never silently strip a harness build selection. throw new ProjectStateError( 'This project requires an @aws/agentcore-cdk package that supports "ContainerLocal". ' + `Update the dependency in ${cdkDirectory} and run npm install.`, diff --git a/src/core/project/backends/cdk/localContainers.test.ts b/src/core/project/backends/cdk/localContainers.test.ts index b7ec268d92..ad19ef4db5 100644 --- a/src/core/project/backends/cdk/localContainers.test.ts +++ b/src/core/project/backends/cdk/localContainers.test.ts @@ -1,8 +1,60 @@ -import { describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { InputValidationError } from "../../../../errors"; import { HarnessSpecSchema } from "../../../../projectSchemas/harness"; +import { ProjectSpecSchema } from "../../../../projectSchemas/project"; import { ProjectRuntimeSchema } from "../../../../projectSchemas/runtime"; -import type { WorkloadBuildMode } from "../../../../handlers/project/types"; -import { assertSupportedBuildTransitions, type DeployedTemplate } from "./localContainers"; +import type { Project, WorkloadBuildMode } from "../../../../handlers/project/types"; +import { + assertSupportedBuildTransitions, + resolveWorkloads, + type DeployedTemplate, +} from "./localContainers"; + +describe("resolveWorkloads", () => { + const roots: string[] = []; + afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); + }); + function harnessProject(entryName: string, yaml: string): Project { + const rootPath = mkdtempSync(join(tmpdir(), "agentcore-local-containers-")); + roots.push(rootPath); + mkdirSync(join(rootPath, "app", "helper"), { recursive: true }); + writeFileSync(join(rootPath, "app", "helper", "harness.yaml"), yaml); + const spec = ProjectSpecSchema.parse({ name: "example", version: 2 }); + spec.harnesses.push({ name: entryName, path: join("app", "helper") }); + return { name: "example", rootPath, spec }; + } + + test("keys a harness by its agentcore.json entry name, not the name in harness.yaml", () => { + const p = harnessProject( + "helper", + "name: renamed\nmodel: {bedrockModelConfig: {modelId: test-model}}\n" + + "dockerfile: Dockerfile\nbuild: ContainerLocal\n", + ); + const { builds, local } = resolveWorkloads(p); + expect(builds).toEqual({ "harness/helper": "ContainerLocal" }); + expect([...local.keys()]).toEqual(["harness/helper"]); + }); + test("names the file when harness.yaml is invalid", () => { + const p = harnessProject("helper", "name: helper\nbuild: NotABuildMode\n"); + const error = (() => { + try { + resolveWorkloads(p); + } catch (caught) { + return caught; + } + })(); + expect(error).toBeInstanceOf(InputValidationError); + const message = (error as Error).message; + expect(message).toContain( + `Invalid harness.yaml at '${join(p.rootPath, "app", "helper", "harness.yaml")}'`, + ); + expect(message).toContain("build"); + }); +}); describe("container configuration", () => { const networkConfig = { @@ -34,6 +86,31 @@ describe("container configuration", () => { }).success, ).toBe(true); }); + test("applies the CodeBuild reserved build-arg rule to Container builds only", () => { + const customDockerBuildArgs = { AWS_REGION: "us-west-2", CODEBUILD_X: "1" }; + const runtime = (build: string) => + ProjectRuntimeSchema.safeParse({ + name: "agent", + build, + codeLocation: "app/agent", + entrypoint: "main.py", + dockerfile: "Dockerfile", + customDockerBuildArgs, + }).success; + const harness = (build: string | undefined) => + HarnessSpecSchema.safeParse({ + name: "agent", + model: { provider: "bedrock", modelId: "test-model" }, + ...(build && { build }), + dockerfile: "Dockerfile", + customDockerBuildArgs, + }).success; + expect(runtime("ContainerLocal")).toBe(true); + expect(runtime("Container")).toBe(false); + expect(harness("ContainerLocal")).toBe(true); + expect(harness("Container")).toBe(false); + expect(harness(undefined)).toBe(false); + }); test.each(["Container", "ContainerLocal"])( "rejects explicit %s build settings for a prebuilt harness image", (build) => { @@ -53,6 +130,10 @@ describe("assertSupportedBuildTransitions", () => { test.each([ ["Container", "ContainerLocal"], ["ContainerLocal", "Container"], + ["CodeZip", "ContainerLocal"], + ["ContainerLocal", "CodeZip"], + ["Managed", "ContainerLocal"], + ["ContainerLocal", "Managed"], ] as const satisfies [string, WorkloadBuildMode][])( "rejects a deployed %s to %s transition", (before, after) => { @@ -65,18 +146,69 @@ describe("assertSupportedBuildTransitions", () => { "example", "default", ), - ).toThrow("between Container and ContainerLocal is not supported"); + ).toThrow("cannot be switched into or out of ContainerLocal"); } }, ); test.each([ - ["CodeZip", "ContainerLocal"], - ["ContainerLocal", "CodeZip"], - ["Managed", "ContainerLocal"], + ["CodeZip", "Container", 'delete the Dockerfile and set "build": "CodeZip" in agentcore.json'], + ["Container", "CodeZip", 'set "build": "Container" and its "dockerfile" in agentcore.json'], + ] as const)("rejects a deployed runtime %s to %s transition", (before, after, keep) => { + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { "runtime/agent": before } } }, + { "runtime/agent": after }, + "example", + "default", + ), + ).toThrow( + `Cannot change runtime/agent from ${before} to ${after}. The service does not allow ` + + "changing a Runtime's artifact type, so the deploy would fail and roll back. Add a " + + `Runtime with a new name, or keep the deployed build: ${keep}`, + ); + }); + test("rejects a pre-feature CodeZip runtime becoming Container", () => { + const previous: DeployedTemplate = { + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { + AgentRuntimeName: "example_default_agent", + AgentRuntimeArtifact: { CodeConfiguration: { Code: {} } }, + }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "Container" }, + "example", + "default", + ), + ).toThrow("Cannot change runtime/agent from CodeZip to Container"); + }); + test.each([ + ["Managed", "Container"], + ["Container", "Managed"], + ] as const)("leaves a deployed harness %s to %s transition allowed", (before, after) => { + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { "harness/agent": before } } }, + { "harness/agent": after }, + "example", + "default", + ), + ).not.toThrow(); + }); + test.each([ + ["ContainerUri", "ContainerLocal"], + ["ContainerLocal", "ContainerUri"], + ["Managed", "ContainerUri"], ] as const satisfies [string, WorkloadBuildMode][])( "allows a deployed %s to %s transition", (before, after) => { - const key = "runtime/agent"; + const key = "harness/agent"; expect(() => assertSupportedBuildTransitions( { Metadata: { "agentcore:builds": { [key]: before } } }, @@ -134,10 +266,10 @@ describe("assertSupportedBuildTransitions", () => { "example", "prod-us", ), - ).toThrow("between Container and ContainerLocal is not supported"); + ).toThrow("cannot be switched into or out of ContainerLocal"); }, ); - test("allows a pre-feature CodeZip runtime to become ContainerLocal", () => { + test("rejects a pre-feature CodeZip runtime becoming ContainerLocal", () => { const previous: DeployedTemplate = { Resources: { Runtime: { @@ -156,7 +288,19 @@ describe("assertSupportedBuildTransitions", () => { "example", "default", ), - ).not.toThrow(); + ).toThrow("Cannot change runtime/agent from CodeZip to ContainerLocal"); + }); + test("says how to recover: a new name, the deployed build mode, or deploying the removal first", () => { + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { "runtime/agent": "Container" } } }, + { "runtime/agent": "ContainerLocal" }, + "example", + "default", + ), + ).toThrow( + /only a new workload can use ContainerLocal\. Keep the deployed build mode \(Container\), or add a workload with a new name\..*deploy the removal first, then add it again\./, + ); }); test("recognizes v0 target-less physical names", () => { const previous: DeployedTemplate = { @@ -255,7 +399,7 @@ describe("assertSupportedBuildTransitions", () => { "example", "default", ), - ).toThrow("between Container and ContainerLocal is not supported"); + ).toThrow("cannot be switched into or out of ContainerLocal"); expect(() => assertSupportedBuildTransitions( previous, diff --git a/src/core/project/backends/cdk/localContainers.ts b/src/core/project/backends/cdk/localContainers.ts index 3764514f7d..6e4c7cf436 100644 --- a/src/core/project/backends/cdk/localContainers.ts +++ b/src/core/project/backends/cdk/localContainers.ts @@ -1,32 +1,82 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parse } from "yaml"; +import { z } from "zod"; import { HarnessYamlSchema } from "../../../../projectSchemas/harness"; import type { + LocalWorkloadSources, Project, WorkloadBuildMode, WorkloadBuilds, WorkloadKey, } from "../../../../handlers/project/types"; -import { ProjectStateError } from "../../../../errors"; +import { InputValidationError, ProjectStateError } from "../../../../errors"; /** - * Resolves every workload's build mode from agentcore.json and each harness.yaml. - * It reads the harness files, so resolve once per command and pass the result on. - * A Harness is Managed without a Dockerfile or image, ContainerUri with an image. + * Resolves every workload's build mode from agentcore.json and each harness.yaml, + * and, for each ContainerLocal workload, where it is built from and its execution + * role. It reads the harness files, so resolve once per command and pass the + * result on. A Harness is Managed without a Dockerfile or image, ContainerUri with + * an image. */ -export function resolveWorkloadBuilds(project: Project): WorkloadBuilds { +export function resolveWorkloads(project: Project): { + builds: WorkloadBuilds; + local: LocalWorkloadSources; +} { const builds: WorkloadBuilds = {}; - for (const runtime of project.spec.runtimes) builds[`runtime/${runtime.name}`] = runtime.build; + const local: LocalWorkloadSources = new Map(); + for (const runtime of project.spec.runtimes) { + builds[`runtime/${runtime.name}`] = runtime.build; + if (runtime.build !== "ContainerLocal") continue; + local.set(`runtime/${runtime.name}`, { + context: runtime.buildContextPath ?? runtime.codeLocation, + dockerfile: runtime.dockerfile ?? "Dockerfile", + ...(runtime.executionRoleArn && { executionRoleArn: runtime.executionRoleArn }), + }); + } for (const entry of project.spec.harnesses) { const path = join(project.rootPath, entry.path, "harness.yaml"); if (!existsSync(path)) continue; - const harness = HarnessYamlSchema.parse(parse(readFileSync(path, "utf8"))); - builds[`harness/${harness.name}`] = + const parsed = HarnessYamlSchema.safeParse(parse(readFileSync(path, "utf8"))); + if (!parsed.success) { + throw new InputValidationError( + `Invalid harness.yaml at '${path}': ${z.prettifyError(parsed.error)}`, + { cause: parsed.error }, + ); + } + const harness = parsed.data; + // Keyed by the agentcore.json entry name, as the CDK package keys its metadata. + const key = `harness/${entry.name}` as const; + builds[key] = harness.build ?? (harness.dockerfile ? "Container" : harness.containerUri ? "ContainerUri" : "Managed"); + if (harness.build !== "ContainerLocal") continue; + local.set(key, { + context: harness.buildContextPath ?? entry.path, + dockerfile: harness.dockerfile ?? "Dockerfile", + ...(harness.executionRoleArn && { executionRoleArn: harness.executionRoleArn }), + }); } - return builds; + return { builds, local }; +} + +/** + * A warning naming the ContainerLocal workloads that bring their own execution + * role. The CLI imports such a role without changing it, so nothing grants it + * pull access to the CDK bootstrap repository the image is published to. + */ +export function byoExecutionRoleWarning(local: LocalWorkloadSources): string | undefined { + const keys = [...local].filter(([, source]) => source.executionRoleArn).map(([key]) => key); + if (keys.length === 0) return undefined; + return ( + `${keys.join(", ")} ${keys.length === 1 ? "uses" : "use"} ContainerLocal with an existing ` + + "execution role (executionRoleArn), which the deploy does not modify. That role needs ECR " + + "pull access to the CDK bootstrap repository the image is published to: " + + "ecr:GetAuthorizationToken on *, and ecr:BatchGetImage and ecr:GetDownloadUrlForLayer on " + + "arn:aws:ecr:::repository/cdk--container-assets-- " + + "(the default qualifier is hnb659fds). Otherwise the service cannot pull the image and " + + "fails at first invoke." + ); } /** The workload entries of a build map, with their typed keys. */ @@ -48,8 +98,10 @@ export type DeployedTemplate = { /** * Finds the build mode a workload was deployed with. Templates synthesized by a * CDK package that supports ContainerLocal record it in `agentcore:builds`. Older - * templates predate ContainerLocal, so a workload found in them is either a - * container image (Container) or not. Returns undefined when it was not deployed. + * templates predate ContainerLocal, so a workload found in them is a container + * image (Container) or a code artifact (CodeZip, or Managed for a Harness); either + * way it is not ContainerLocal, so switching it to ContainerLocal is rejected. + * Returns undefined when it was not deployed. */ function deployedBuild( template: DeployedTemplate, @@ -102,11 +154,14 @@ function deployedBuild( } /** - * Rejects switching a deployed workload between Container (CodeBuild) and - * ContainerLocal, in either direction. Other changes, such as CodeZip to - * ContainerLocal, are left to CloudFormation. The deployed - * template is authoritative: editing agentcore.json or deleting deployed-state.json - * must not permit a build-mode migration. + * Rejects switching a deployed workload into or out of ContainerLocal, and a + * deployed Runtime between CodeZip and Container. AgentCore rejects an + * artifact-type change in place ("Agent artifact type cannot be updated"), and + * Container to ContainerLocal replaces how the image is built and published, so + * only a new workload may use ContainerLocal. ContainerUri is left + * to CloudFormation. The deployed template is authoritative: editing + * agentcore.json or deleting deployed-state.json must not permit a build-mode + * migration. */ export function assertSupportedBuildTransitions( template: DeployedTemplate, @@ -131,13 +186,28 @@ export function assertSupportedBuildTransitions( projectName, targetName, ); - if (deployed === undefined) continue; + if (deployed === undefined || deployed === desired) continue; const pair = new Set([deployed, desired]); - if (pair.has("Container") && pair.has("ContainerLocal")) { + if (pair.has("ContainerLocal") && !pair.has("ContainerUri")) { throw new ProjectStateError( `Cannot change ${key} from ${deployed} to ${desired}. ` + - "Switching a deployed workload between Container and ContainerLocal is not supported. " + - "Keep the deployed build mode or add a workload with a new name.", + "A deployed workload cannot be switched into or out of ContainerLocal; only a new " + + `workload can use ContainerLocal. Keep the deployed build mode (${deployed}), or add ` + + "a workload with a new name. If you removed this workload and added it again under " + + "the same name, deploy the removal first, then add it again.", + ); + } + // The CLI flips a CodeZip Runtime to Container itself when a Dockerfile appears + // (runtimeBuild.ts); on a deployed Runtime the service then fails the update. + if (key.startsWith("runtime/") && pair.has("CodeZip") && pair.has("Container")) { + const keep = + deployed === "CodeZip" + ? 'delete the Dockerfile and set "build": "CodeZip" in agentcore.json' + : 'set "build": "Container" and its "dockerfile" in agentcore.json again'; + throw new ProjectStateError( + `Cannot change ${key} from ${deployed} to ${desired}. The service does not allow ` + + "changing a Runtime's artifact type, so the deploy would fail and roll back. Add a " + + `Runtime with a new name, or keep the deployed build: ${keep}.`, ); } } diff --git a/src/core/project/backends/cdk/localImages.test.ts b/src/core/project/backends/cdk/localImages.test.ts index 8c7768564e..d2536866f1 100644 --- a/src/core/project/backends/cdk/localImages.test.ts +++ b/src/core/project/backends/cdk/localImages.test.ts @@ -103,6 +103,31 @@ describe("localImageBuilds", () => { ); }); + test("fails when the asset manifest has no build context for a recorded image", async () => { + const directory = await fixtureCopy(); + await editJson(join(directory, "AgentCore-Fixture.assets.json"), (manifest) => { + delete manifest.dockerImages[ORDERS_HASH].source.directory; + }); + await expect(localImageBuilds(json, directory, "Fixture", FIXTURE_BUILDS)).rejects.toThrow( + /asset manifest of stack .* has no build context for runtime\/orders.*too old/, + ); + }); + + test("trims separators from both ends of the image name", async () => { + const directory = await fixtureCopy(); + await editJson(join(directory, "AgentCore-Fixture.template.json"), (template) => { + const recorded = template.Metadata["agentcore:localImages"]; + recorded["runtime/orders_"] = recorded["runtime/orders"]; + delete recorded["runtime/orders"]; + }); + const images = await localImageBuilds(json, directory, "_Fixture", { + "runtime/orders_": "ContainerLocal", + "harness/assistant": "ContainerLocal", + }); + const orders = images.find((image) => image.resource === "runtime/orders_")!; + expect(orders.tag).toBe(`agentcore-local/fixture-runtime-orders:${ORDERS_HASH}`); + }); + test("rejects malformed local image metadata", async () => { const directory = await fixtureCopy(); await editJson(join(directory, "AgentCore-Fixture.template.json"), (template) => { diff --git a/src/core/project/backends/cdk/localImages.ts b/src/core/project/backends/cdk/localImages.ts index 73fe95f948..b5f5a7b5b8 100644 --- a/src/core/project/backends/cdk/localImages.ts +++ b/src/core/project/backends/cdk/localImages.ts @@ -66,7 +66,7 @@ const tagComponent = (value: string) => value .toLowerCase() .replace(/[^a-z0-9._-]+/g, "-") - .replace(/^[^a-z0-9]+/, ""); + .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ""); const cdkMismatch = (detail: string) => new ProjectStateError( diff --git a/src/core/project/backends/cdk/toolkit.test.ts b/src/core/project/backends/cdk/toolkit.test.ts index 8b7d5417e6..c0fc73d639 100644 --- a/src/core/project/backends/cdk/toolkit.test.ts +++ b/src/core/project/backends/cdk/toolkit.test.ts @@ -313,6 +313,35 @@ describe("Toolkit loading", () => { } }); + test("sets BUILDX_BUILDER only for the operation and restores the caller's value", async () => { + const { loaded } = loadedToolkit(); + const previous = process.env.BUILDX_BUILDER; + process.env.BUILDX_BUILDER = "ci"; + let during: string | undefined; + loaded.toolkit.destroy = async () => { + during = process.env.BUILDX_BUILDER; + return { stacks: [] } as never; + }; + const runner = createCdkRunner(createSilentLogger(), async () => loaded); + try { + await runner( + { kind: "destroy", stackArtifactId: "AgentCore-orders-default" }, + runOptions({ containerExecutable: "docker", buildxBuilder: "default" }), + ); + expect(during).toBe("default"); + expect(process.env.BUILDX_BUILDER).toBe("ci"); + delete process.env.BUILDX_BUILDER; + await runner( + { kind: "destroy", stackArtifactId: "AgentCore-orders-default" }, + runOptions({ containerExecutable: "docker" }), + ); + expect(during).toBeUndefined(); + } finally { + if (previous === undefined) delete process.env.BUILDX_BUILDER; + else process.env.BUILDX_BUILDER = previous; + } + }); + test("routes the operation's ioHost messages into its onOutput sink", async () => { const { loaded } = loadedToolkit(); const lines: string[] = []; diff --git a/src/core/project/backends/cdk/toolkit.ts b/src/core/project/backends/cdk/toolkit.ts index 488562bf82..2773bed7e8 100644 --- a/src/core/project/backends/cdk/toolkit.ts +++ b/src/core/project/backends/cdk/toolkit.ts @@ -35,6 +35,12 @@ export type CdkRunOptions = { * Toolkit runs in-process and reads CDK_DOCKER, so it is set for the operation. */ containerExecutable?: string; + /** + * Docker buildx builder CDK builds image assets with, set as BUILDX_BUILDER for + * the operation. CDK's `docker build` has no --load, so a builder whose driver is + * not `docker` would leave nothing in the local image store to push. + */ + buildxBuilder?: string; }; export type CdkOutputs = Record; @@ -283,7 +289,9 @@ export function createCdkRunner( }); const loaded = await load(ioHost, options.region, options.credentials); const previousCdkDocker = process.env.CDK_DOCKER; + const previousBuildxBuilder = process.env.BUILDX_BUILDER; if (options.containerExecutable) process.env.CDK_DOCKER = options.containerExecutable; + if (options.buildxBuilder) process.env.BUILDX_BUILDER = options.buildxBuilder; try { return await performCdkOperation(loaded, operation, options); } catch (error) { @@ -296,6 +304,8 @@ export function createCdkRunner( } finally { if (previousCdkDocker === undefined) delete process.env.CDK_DOCKER; else process.env.CDK_DOCKER = previousCdkDocker; + if (previousBuildxBuilder === undefined) delete process.env.BUILDX_BUILDER; + else process.env.BUILDX_BUILDER = previousBuildxBuilder; } }; } diff --git a/src/core/project/backends/types.ts b/src/core/project/backends/types.ts index c534ca66a0..29b0be374c 100644 --- a/src/core/project/backends/types.ts +++ b/src/core/project/backends/types.ts @@ -1,4 +1,4 @@ -import type { WorkloadBuilds } from "../../../handlers/project/types"; +import type { LocalWorkloadSources, WorkloadBuilds } from "../../../handlers/project/types"; import type { DeployResult, Project, @@ -20,6 +20,8 @@ export type DeployBackendInput = { skipBootstrap?: boolean; /** Effective workload build modes the manager resolved; resolved here when absent. */ workloadBuilds?: WorkloadBuilds; + /** Build sources of the ContainerLocal workloads, resolved with workloadBuilds. */ + localWorkloads?: LocalWorkloadSources; }; export type ResolveDeployedResourcesBackendInput = { diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 2a370d5ee6..e4b260e4df 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -115,7 +115,7 @@ import { assertV1Project } from "./legacy/writeGate"; import { assertNoPendingMigration } from "./migrate/journal"; import { prepareRuntimes } from "./runtimeBuild"; import { isContainerBuild } from "../../projectSchemas/constants"; -import { resolveWorkloadBuilds } from "./backends/cdk/localContainers"; +import { resolveWorkloads } from "./backends/cdk/localContainers"; const TARGETS_EXAMPLE = '[{ "name": "default", "account": "111122223333", "region": "us-east-1" }]'; @@ -497,12 +497,12 @@ export class FsProjectManager implements ProjectManager { ); } + const destination = join(process.cwd(), input.name); if (input.scaffoldHarnessInput) { - validateHarnessTemplateSource(input.scaffoldHarnessInput); + validateHarnessTemplateSource(input.scaffoldHarnessInput, destination); } const scaffoldRuntimeInput = input.scaffoldRuntimeInput; - const destination = join(process.cwd(), input.name); const { tree: projectTree, envEntries } = await createProjectTree( { templateRenderer: this.templateRenderer, assetSource: this.assetSource }, @@ -767,6 +767,14 @@ export class FsProjectManager implements ProjectManager { }); const result = await resolver.resolve(resourceConfig); await result.tree.write(dirname(outputPath)); + if (resourceConfig.dockerfile && !resourceConfig.buildContextPath) { + yield { + type: "step", + message: + `copied ${resourceConfig.dockerfile} to app/${harnessName}/Dockerfile; later ` + + "edits to the original are not used", + }; + } if (result.spec.harnesses) projectSpec.harnesses.push(...result.spec.harnesses); if (harnessEnvEntries.length > 0) { envFile = new EnvLocalFile(project.rootPath); @@ -815,6 +823,14 @@ export class FsProjectManager implements ProjectManager { throw err; } if (folderExisted) scaffoldedPaths.push(...written); + if (written.includes(join(outputPath, "Dockerfile"))) { + yield { + type: "step", + message: + `copied ${input.resourceConfig.dockerfile} to ${relativeFolder}/Dockerfile; ` + + "later edits to the original are not used", + }; + } for (const child of tree.children) { if (!written.includes(join(outputPath, child.name))) { yield { @@ -1596,7 +1612,7 @@ export class FsProjectManager implements ProjectManager { project = synced.project; // Resolved once, after auto-detection, so the caller (telemetry) and the // backend see the build modes this deploy actually uses. - const workloadBuilds = resolveWorkloadBuilds(project); + const { builds: workloadBuilds, local: localWorkloads } = resolveWorkloads(project); input.onWorkloadBuilds?.(workloadBuilds); // China (aws-cn) targets cannot run runtimes whose scaffolded code is @@ -1700,6 +1716,7 @@ export class FsProjectManager implements ProjectManager { transactionSearch: input.transactionSearch, skipBootstrap: input.skipBootstrap, workloadBuilds, + localWorkloads, }); } diff --git a/src/core/project/runtimeBuild.test.ts b/src/core/project/runtimeBuild.test.ts index ae1f6112ee..0e731d548b 100644 --- a/src/core/project/runtimeBuild.test.ts +++ b/src/core/project/runtimeBuild.test.ts @@ -284,7 +284,9 @@ describe("build", () => { "search: build CodeZip -> Container (Dockerfile in app/search). It now builds and " + "deploys as a container image from that Dockerfile; to go back, delete the Dockerfile, " + 'then in agentcore.json set "build": "CodeZip", remove "dockerfile", and add back the ' + - '"runtimeVersion" removed below.', + '"runtimeVersion" removed below. Container images are built by CodeBuild; a local ' + + "build (ContainerLocal) can only be chosen when adding a workload, with --build-config, " + + "and a workload cannot be switched to it later.", ); }); diff --git a/src/core/project/runtimeBuild.ts b/src/core/project/runtimeBuild.ts index fff0e2741f..e40337cd6e 100644 --- a/src/core/project/runtimeBuild.ts +++ b/src/core/project/runtimeBuild.ts @@ -51,7 +51,9 @@ export function describeChange(name: string, change: RuntimeChange): string { return change.field === "build" && change.to === "Container" ? `${line}. It now builds and deploys as a container image from that Dockerfile; to go ` + `back, delete the Dockerfile, then in agentcore.json set "build": "CodeZip", remove ` + - `"dockerfile", and add back the "runtimeVersion" removed below.` + `"dockerfile", and add back the "runtimeVersion" removed below. Container images are ` + + `built by CodeBuild; a local build (ContainerLocal) can only be chosen when adding a ` + + `workload, with --build-config, and a workload cannot be switched to it later.` : line; } diff --git a/src/core/project/templates/harness.test.ts b/src/core/project/templates/harness.test.ts index 4421a576c6..035352b23d 100644 --- a/src/core/project/templates/harness.test.ts +++ b/src/core/project/templates/harness.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { parse } from "yaml"; @@ -27,6 +27,7 @@ const defaultSettings = { const config = { assetSource: new FsAssetSource(), templateRenderer: new HandlebarsTemplateRenderer(), + projectRoot: process.cwd(), }; afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); @@ -223,6 +224,18 @@ test("renders supplied deployment settings once in their sections", async () => }); }); +test.each([ + ["Container", true], + ["ContainerLocal", false], +] as const)("a %s harness hints at networkConfig.vpcId: %s", async (build, hinted) => { + const dockerfileRoot = await mkdtemp(join(tmpdir(), "harness-dockerfile-")); + roots.push(dockerfileRoot); + const dockerfile = join(dockerfileRoot, "Dockerfile"); + await writeFile(dockerfile, "FROM scratch\n"); + const { yaml } = await scaffold({ build, dockerfile }); + expect(yaml.includes("networkConfig.vpcId")).toBe(hinted); +}); + test("preserves explicit empty settings and disabled truncation", async () => { const { data, yaml } = await scaffold({ allowedTools: [], diff --git a/src/core/project/templates/harness.ts b/src/core/project/templates/harness.ts index fbf1203b12..294bc231ac 100644 --- a/src/core/project/templates/harness.ts +++ b/src/core/project/templates/harness.ts @@ -60,7 +60,7 @@ export function harnessApiKeyCredentialName( type GetHarnessTemplateResolverConfig = { assetSource: AssetSource; templateRenderer: TemplateRenderer; - projectRoot?: string; + projectRoot: string; }; /** Given a harness spec, resolve the {@link TemplateResolver} that renders its config directory **/ @@ -143,6 +143,8 @@ function buildTemplateContext(spec: HarnessSpec) { apiKeyExample: provider !== "bedrock" && !model.apiKeyArn && !model.apiKeyCredentialName, modelMaxTokensExample: !("maxTokens" in spec.model), managedMemoryEmpty: mode === "managed" && Object.keys(memoryConfig).length === 0, + // A local build needs no CodeBuild VPC, so it gets no networkConfig.vpcId hint. + containerLocal: spec.build === "ContainerLocal", additionalSettings: Object.entries(yaml) .filter(([key]) => !TEMPLATE_FIELDS.has(key)) .map(([, value]) => value), @@ -151,14 +153,11 @@ function buildTemplateContext(spec: HarnessSpec) { export function validateHarnessTemplateSource( spec: z.input, - projectRoot?: string, + projectRoot: string, ): void { - if (spec.buildContextPath && !projectRoot) { - throw new InputValidationError("projectRoot is required for a Harness build context override."); - } const dockerfile = spec.dockerfile && typeof spec.buildContextPath === "string" - ? resolve(projectRoot!, spec.buildContextPath, spec.dockerfile) + ? resolve(projectRoot, spec.buildContextPath, spec.dockerfile) : spec.dockerfile; if (dockerfile && !existsSync(dockerfile)) { throw new ResourceNotFoundError(`no dockerfile exists at ${dockerfile}`); diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index 0dd0a5e2ec..f5ed443e11 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -11,8 +11,8 @@ import { import { defaultMemoryName, memoryEnvVarName } from "../../../projectSchemas/memory"; import { credentialProviderNameEnvVarName } from "../../../projectSchemas/credential"; import { LATEST_NODE, LATEST_PYTHON } from "../runtimeBuild"; -import { existsSync } from "node:fs"; -import { resolve } from "node:path"; +import { existsSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; import { InputValidationError, ResourceNotFoundError } from "../../../errors"; /** @@ -54,7 +54,7 @@ export function docsRuntimeEntrypoint(language: RuntimeDocsConfig["language"]): * rendered for its language and protocol. */ export async function runtimeDocsTree( - config: { assetSource: AssetSource; templateRenderer: TemplateRenderer; projectRoot?: string }, + config: { assetSource: AssetSource; templateRenderer: TemplateRenderer; projectRoot: string }, input: RuntimeDocsConfig, ): Promise { const protocol = input.protocol ?? "HTTP"; @@ -96,11 +96,8 @@ export async function runtimeDocsTree( }, ); if (input.dockerfile) { - if (input.buildContextPath && !config.projectRoot) { - throw new InputValidationError("projectRoot is required for a build context override."); - } const dockerfile = input.buildContextPath - ? resolve(config.projectRoot!, input.buildContextPath, input.dockerfile) + ? resolve(config.projectRoot, input.buildContextPath, input.dockerfile) : input.dockerfile; if (!existsSync(dockerfile)) throw new ResourceNotFoundError(`no dockerfile exists at ${dockerfile}`); @@ -108,11 +105,22 @@ export async function runtimeDocsTree( // a Dockerfile-specific ignore file, which Docker reads instead of .dockerignore, // goes with it under the copied name. if (!input.buildContextPath) { - tree.children.push(FsTreeNode.fromTextFile("Dockerfile", dockerfile)); + const copies: [string, string][] = [["Dockerfile", dockerfile]]; if (existsSync(`${dockerfile}.dockerignore`)) { - tree.children.push( - FsTreeNode.fromTextFile("Dockerfile.dockerignore", `${dockerfile}.dockerignore`), - ); + copies.push(["Dockerfile.dockerignore", `${dockerfile}.dockerignore`]); + } + for (const [name, source] of copies) { + // The resource directory is written without overwriting, so a different file + // already there would silently win over the one the user asked for. + const existing = join(config.projectRoot, "app", input.name, name); + if (existsSync(existing) && !readFileSync(existing).equals(readFileSync(source))) { + throw new InputValidationError( + `app/${input.name}/${name} already exists and differs from ${source}. Remove it, or ` + + `use it by passing "dockerfile": "app/${input.name}/Dockerfile" in --build-config, ` + + "then retry.", + ); + } + tree.children.push(FsTreeNode.fromTextFile(name, source)); } } } diff --git a/src/handlers/project/add/buildConfig.test.ts b/src/handlers/project/add/buildConfig.test.ts new file mode 100644 index 0000000000..91f8a45ade --- /dev/null +++ b/src/handlers/project/add/buildConfig.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from "bun:test"; +import { + buildConfigFlag, + HarnessBuildConfigSchema, + parseBuildConfig, + RuntimeBuildConfigSchema, +} from "./buildConfig"; + +describe("--build-config", () => { + test("help states how dockerfile paths resolve with and without buildContextPath", () => { + expect(buildConfigFlag("Container or ContainerLocal").description).toContain( + "Without buildContextPath, dockerfile is a path relative to the current directory, " + + "copied once to app//Dockerfile (app// is the build context). With " + + "buildContextPath (relative to the project root), dockerfile is relative to that build " + + "context and used in place.", + ); + }); + + test.each([RuntimeBuildConfigSchema, HarnessBuildConfigSchema])( + "prefixes its schema errors with the option name", + (schema) => { + expect(() => + parseBuildConfig( + JSON.stringify({ build: "ContainerLocal", buildContextPath: "/abs", dockerfile: "D" }), + schema, + ), + ).toThrow( + "Invalid value for option '--build-config': buildContextPath must be relative to the " + + "project root, not an absolute path", + ); + expect(() => + parseBuildConfig( + JSON.stringify({ + build: "ContainerLocal", + buildContextPath: "ctx", + dockerfile: "/ctx/D", + }), + schema, + ), + ).toThrow( + "Invalid value for option '--build-config': with buildContextPath, dockerfile must be " + + "relative to that build context", + ); + }, + ); + + test("applies the CodeBuild reserved build-arg rule to Container only", () => { + const args = { AWS_REGION: "us-west-2", CODEBUILD_SRC: "x", PATH: "/bin" }; + for (const schema of [RuntimeBuildConfigSchema, HarnessBuildConfigSchema]) { + expect( + schema.safeParse({ build: "ContainerLocal", dockerfile: "D", customDockerBuildArgs: args }) + .success, + ).toBe(true); + expect( + schema.safeParse({ build: "Container", dockerfile: "D", customDockerBuildArgs: args }) + .success, + ).toBe(false); + } + // A Harness with a Dockerfile and no build builds as Container. + expect( + HarnessBuildConfigSchema.safeParse({ dockerfile: "D", customDockerBuildArgs: args }).success, + ).toBe(false); + }); +}); diff --git a/src/handlers/project/add/buildConfig.ts b/src/handlers/project/add/buildConfig.ts index b367de6eb9..b87e781303 100644 --- a/src/handlers/project/add/buildConfig.ts +++ b/src/handlers/project/add/buildConfig.ts @@ -1,7 +1,9 @@ import z from "zod"; import { flag } from "../../../router"; import { parseJsonFlagWithSchema } from "../../utils"; +import { isAbsolute } from "node:path"; import { + DockerfilePathSchema, isReservedBuildArgKey, ProjectRuntimeSchema, RESERVED_BUILD_ARG_KEYS, @@ -13,28 +15,89 @@ export const ADVANCED = "Advanced:"; // Keys map 1:1 to the build fields in agentcore.json and harness.yaml. dockerfile // is a path to an existing Dockerfile: it is copied into the resource directory // unless buildContextPath is set, in which case it is relative to that context. +// Every rule a --build-config value can break is checked here, so the error names +// --build-config instead of surfacing later against agentcore.json or harness.yaml. const buildFields = { dockerfile: z.string().min(1).optional(), - buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, - customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs.refine( - (args) => !Object.keys(args ?? {}).some(isReservedBuildArgKey), - `customDockerBuildArgs must not use keys reserved by the build environment (${RESERVED_BUILD_ARG_KEYS.join(", ")}, CODEBUILD_*, AWS_*)`, + buildContextPath: ProjectRuntimeSchema.shape.buildContextPath.refine( + (path) => path === undefined || !isAbsolute(path), + "buildContextPath must be relative to the project root, not an absolute path", ), + customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs, }; -export const RuntimeBuildConfigSchema = z.strictObject({ - build: ProjectRuntimeSchema.shape.build.optional(), - ...buildFields, -}); -export const HarnessBuildConfigSchema = z.strictObject({ - build: HarnessSpecSchema.shape.build, - ...buildFields, -}); + +type BuildConfigFields = { + build?: string; + dockerfile?: string; + buildContextPath?: string; + customDockerBuildArgs?: Record; +}; + +/** Rules across fields; `defaultBuild` is the build when "build" is omitted. */ +function checkBuildFields(data: BuildConfigFields, ctx: z.RefinementCtx, defaultBuild?: string) { + if (data.buildContextPath !== undefined && data.dockerfile !== undefined) { + const dockerfile = DockerfilePathSchema.safeParse(data.dockerfile); + if (!dockerfile.success) { + ctx.addIssue({ + code: "custom", + message: + "with buildContextPath, dockerfile must be relative to that build context: " + + (dockerfile.error.issues[0]?.message ?? "invalid path"), + path: ["dockerfile"], + }); + } + } + // The reserved keys are the CodeBuild build environment's; a ContainerLocal image + // builds on the local machine, where they collide with nothing. + if ((data.build ?? defaultBuild) !== "ContainerLocal") { + if (Object.keys(data.customDockerBuildArgs ?? {}).some(isReservedBuildArgKey)) { + ctx.addIssue({ + code: "custom", + message: + "customDockerBuildArgs must not use keys reserved by the CodeBuild build environment " + + `(${RESERVED_BUILD_ARG_KEYS.join(", ")}, CODEBUILD_*, AWS_*); ContainerLocal builds ` + + "allow them", + path: ["customDockerBuildArgs"], + }); + } + } +} + +export const RuntimeBuildConfigSchema = z + .strictObject({ build: ProjectRuntimeSchema.shape.build.optional(), ...buildFields }) + .superRefine((data, ctx) => { + const container = data.build === "Container" || data.build === "ContainerLocal"; + if (container && data.dockerfile === undefined) { + ctx.addIssue({ + code: "custom", + message: "dockerfile is required for a Container or ContainerLocal build", + path: ["dockerfile"], + }); + } + for (const field of ["dockerfile", "buildContextPath", "customDockerBuildArgs"] as const) { + if (!container && data[field] !== undefined) { + ctx.addIssue({ + code: "custom", + message: `${field} requires build Container or ContainerLocal`, + path: [field], + }); + } + } + checkBuildFields(data, ctx); + }); +export const HarnessBuildConfigSchema = z + .strictObject({ build: HarnessSpecSchema.shape.build, ...buildFields }) + .superRefine((data, ctx) => checkBuildFields(data, ctx, "Container")); export function buildConfigFlag(builds: string) { return flag( "build-config", `advanced build settings (JSON object): build (${builds}), dockerfile, buildContextPath, ` + - "customDockerBuildArgs. Build args are not secret: they appear in logs and image metadata", + "customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the " + + "current directory, copied once to app//Dockerfile (app// is the build " + + "context). With buildContextPath (relative to the project root), dockerfile is relative " + + "to that build context and used in place. Build args are not secret: they appear in " + + "logs and image metadata", z.string().optional(), { group: ADVANCED }, ); diff --git a/src/handlers/project/add/harness/index.test.ts b/src/handlers/project/add/harness/index.test.ts index 835ae5c2b4..e9e689ca48 100644 --- a/src/handlers/project/add/harness/index.test.ts +++ b/src/handlers/project/add/harness/index.test.ts @@ -90,7 +90,30 @@ describe("project add harness", () => { [ "a build without a Dockerfile", ["--build-config", '{"build":"ContainerLocal"}'], - "build requires a Dockerfile", + "Invalid value for option '--build-config': build requires a Dockerfile", + ], + [ + "build args without a Dockerfile", + ["--build-config", '{"customDockerBuildArgs":{"A":"1"}}'], + "Invalid value for option '--build-config': customDockerBuildArgs requires a Dockerfile", + ], + [ + "an absolute buildContextPath", + [ + "--build-config", + '{"build":"ContainerLocal","buildContextPath":"/tmp/ctx","dockerfile":"Dockerfile"}', + ], + "Invalid value for option '--build-config': buildContextPath must be relative to the project root", + ], + [ + "a reserved build argument for Container", + [ + "--dockerfile", + "Dockerfile", + "--build-config", + '{"customDockerBuildArgs":{"AWS_REGION":"x"}}', + ], + "Invalid value for option '--build-config': customDockerBuildArgs must not use keys reserved", ], ])("rejects %s", async (_label, flags, message) => { const { projectRoot, cleanup } = await initProject(); @@ -135,6 +158,29 @@ describe("project add harness", () => { expect(spec).toMatchObject({ dockerfile: "Agent.Dockerfile", buildContextPath: "docker" }); expect(existsSync(join(projectRoot, "app", "local", "Dockerfile.dockerignore"))).toBe(false); }); + test("says it copied the Dockerfile and that later edits to the original are not used", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const dockerfile = join(projectRoot, "Dockerfile"); + await Bun.write(dockerfile, "FROM scratch\n"); + const { io } = await run([ + "add", + "harness", + "--name", + "local", + "--build-config", + JSON.stringify({ + build: "ContainerLocal", + dockerfile, + customDockerBuildArgs: { AWS_REGION: "us-west-2" }, + }), + ]); + expect(io.stderr()).toContain( + `copied ${dockerfile} to app/local/Dockerfile; later edits to the original are not used`, + ); + const spec = parse(await Bun.file(join(projectRoot, "app", "local", "harness.yaml")).text()); + expect(spec.customDockerBuildArgs).toEqual({ AWS_REGION: "us-west-2" }); + }); test("without --build-config a --dockerfile harness records no build key", async () => { const { projectRoot, cleanup } = await initProject(); cleanups.push(cleanup); diff --git a/src/handlers/project/add/harness/index.ts b/src/handlers/project/add/harness/index.ts index 6b4146d3fb..9b8c66899a 100644 --- a/src/handlers/project/add/harness/index.ts +++ b/src/handlers/project/add/harness/index.ts @@ -204,6 +204,15 @@ export const createAddHarnessHandler = (config: AddProjectResourceConfig) => "--dockerfile and --build-config dockerfile both set the Dockerfile; pass only one", ); } + const needsDockerfile = ( + ["build", "buildContextPath", "customDockerBuildArgs"] as const + ).find((field) => buildConfig?.[field] !== undefined); + if (needsDockerfile && buildConfig?.dockerfile === undefined && !flags.dockerfile) { + throw new InputValidationError( + `Invalid value for option '--build-config': ${needsDockerfile} requires a Dockerfile; ` + + 'set "dockerfile" in --build-config or pass --dockerfile', + ); + } if (buildConfig?.buildContextPath !== undefined && flags.dockerfile !== undefined) { throw new InputValidationError( "--dockerfile cannot be combined with --build-config buildContextPath: with a build " + diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index 0440b68b83..b9bc61335a 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -167,6 +167,94 @@ describe("project add runtime", () => { await Bun.file(join(projectRoot, "app", "local", "Dockerfile.dockerignore")).exists(), ).toBe(false); }); + test("says it copied the Dockerfile and that later edits to the original are not used", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await writeFile(join(projectRoot, "Dockerfile"), "FROM scratch\n"); + const { io } = await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ build: "ContainerLocal", dockerfile: join(projectRoot, "Dockerfile") }), + ]); + expect(io.stderr()).toContain( + `copied ${join(projectRoot, "Dockerfile")} to app/local/Dockerfile; later edits to the original are not used`, + ); + }); + test("refuses a different Dockerfile already in app/ and writes nothing", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await mkdir(join(projectRoot, "app", "local"), { recursive: true }); + await writeFile(join(projectRoot, "app", "local", "Dockerfile"), "FROM scratch\n"); + const other = join(projectRoot, "other.Dockerfile"); + await writeFile(other, "FROM public.ecr.aws/docker/library/python:3.12-slim\n"); + await expectError( + run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ build: "ContainerLocal", dockerfile: other }), + ]), + `app/local/Dockerfile already exists and differs from ${other}`, + InputValidationError, + ); + expect(await Bun.file(join(projectRoot, "app", "local", "Dockerfile")).text()).toBe( + "FROM scratch\n", + ); + expect((await specOf(projectRoot)).runtimes ?? []).toEqual([]); + expect((await readdir(join(projectRoot, "app", "local"))).sort()).toEqual(["Dockerfile"]); + }); + test("accepts an identical Dockerfile already in app/", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await mkdir(join(projectRoot, "app", "local"), { recursive: true }); + await writeFile(join(projectRoot, "app", "local", "Dockerfile"), "FROM scratch\n"); + await writeFile(join(projectRoot, "same.Dockerfile"), "FROM scratch\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ build: "ContainerLocal", dockerfile: join(projectRoot, "same.Dockerfile") }), + ]); + expect(await runtimeOf(projectRoot, "local")).toMatchObject({ + build: "ContainerLocal", + dockerfile: "Dockerfile", + }); + }); + test("accepts CodeBuild-reserved build args for ContainerLocal", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await writeFile(join(projectRoot, "Dockerfile"), "FROM scratch\n"); + await run([ + "add", + "runtime", + "--name", + "local", + "--language", + "python", + "--build-config", + JSON.stringify({ + build: "ContainerLocal", + dockerfile: join(projectRoot, "Dockerfile"), + customDockerBuildArgs: { AWS_REGION: "us-west-2", CODEBUILD_X: "1" }, + }), + ]); + expect(await runtimeOf(projectRoot, "local")).toMatchObject({ + customDockerBuildArgs: { AWS_REGION: "us-west-2", CODEBUILD_X: "1" }, + }); + }); test("without --build-config a runtime stays CodeZip", async () => { const { projectRoot, cleanup } = await initProject(); cleanups.push(cleanup); @@ -183,17 +271,32 @@ describe("project add runtime", () => { [ "a reserved build argument", '{"build":"Container","dockerfile":"Dockerfile","customDockerBuildArgs":{"AWS_REGION":"x"}}', - "--build-config", + "Invalid value for option '--build-config': customDockerBuildArgs must not use keys reserved by the CodeBuild build environment", ], [ "a container build without a Dockerfile", '{"build":"ContainerLocal"}', - "dockerfile is required", + "Invalid value for option '--build-config': dockerfile is required", ], [ "container settings without a container build", '{"dockerfile":"Dockerfile"}', - "dockerfile requires build Container or ContainerLocal", + "Invalid value for option '--build-config': dockerfile requires build Container or ContainerLocal", + ], + [ + "an absolute buildContextPath", + '{"build":"ContainerLocal","buildContextPath":"/tmp/ctx","dockerfile":"Dockerfile"}', + "Invalid value for option '--build-config': buildContextPath must be relative to the project root", + ], + [ + "an absolute dockerfile inside a build context", + '{"build":"ContainerLocal","buildContextPath":"ctx","dockerfile":"/tmp/ctx/Dockerfile"}', + "Invalid value for option '--build-config': with buildContextPath, dockerfile must be relative to that build context", + ], + [ + "a dockerfile escaping its build context", + '{"build":"ContainerLocal","buildContextPath":"ctx","dockerfile":"../Dockerfile"}', + "Invalid value for option '--build-config': with buildContextPath, dockerfile must be relative", ], ])("rejects --build-config with %s and writes nothing", async (_label, value, message) => { const { projectRoot, cleanup } = await initProject(); diff --git a/src/handlers/project/types.ts b/src/handlers/project/types.ts index 041df8a4a9..a51217dc39 100644 --- a/src/handlers/project/types.ts +++ b/src/handlers/project/types.ts @@ -242,6 +242,17 @@ export type WorkloadBuildMode = export type WorkloadKey = `runtime/${string}` | `harness/${string}`; /** Build mode of every runtime and harness in a project. */ export type WorkloadBuilds = Record; +/** Where a ContainerLocal workload is built from, as agentcore.json or harness.yaml sets it. */ +export type LocalWorkloadSource = { + /** Project-relative build context: buildContextPath, else the workload's directory. */ + context: string; + /** The Dockerfile, relative to the build context. */ + dockerfile: string; + /** The bring-your-own execution role, when one is set. */ + executionRoleArn?: string; +}; +/** Each ContainerLocal workload's build source, by workload key. */ +export type LocalWorkloadSources = Map; export type DeployResult = { /** diff --git a/src/projectSchemas/harness.ts b/src/projectSchemas/harness.ts index 6f1a341590..b6208b1e59 100644 --- a/src/projectSchemas/harness.ts +++ b/src/projectSchemas/harness.ts @@ -550,12 +550,8 @@ export const HarnessSpecSchema = z if (data.build !== undefined && data.dockerfile === undefined) { ctx.addIssue({ code: "custom", message: "build requires a Dockerfile", path: ["build"] }); } - for (const field of [ - "build", - "dockerfile", - "buildContextPath", - "customDockerBuildArgs", - ] as const) { + // dockerfile is reported by the mutually-exclusive check below. + for (const field of ["build", "buildContextPath", "customDockerBuildArgs"] as const) { if (data.containerUri !== undefined && data[field] !== undefined) { ctx.addIssue({ code: "custom", @@ -569,8 +565,10 @@ export const HarnessSpecSchema = z ctx.addIssue({ code: "custom", message: `${field} requires a Dockerfile`, path: [field] }); } } + // Reserved by the CodeBuild build environment; ContainerLocal builds locally. + // Keep in step with the @aws/agentcore-cdk schema. for (const key of Object.keys(data.customDockerBuildArgs ?? {})) { - if (isReservedBuildArgKey(key)) { + if (data.build !== "ContainerLocal" && isReservedBuildArgKey(key)) { ctx.addIssue({ code: "custom", message: `customDockerBuildArgs key "${key}" is reserved by the build environment`, diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index 4b18fc8e49..bd7bbc1926 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -404,8 +404,10 @@ export const ProjectRuntimeSchema = z }); } } + // Reserved by the CodeBuild build environment; ContainerLocal builds locally. + // Keep in step with the @aws/agentcore-cdk schema. for (const key of Object.keys(data.customDockerBuildArgs ?? {})) { - if (isReservedBuildArgKey(key)) { + if (data.build !== "ContainerLocal" && isReservedBuildArgKey(key)) { ctx.addIssue({ code: "custom", message: `customDockerBuildArgs key "${key}" is reserved by the build environment (must not be ${RESERVED_BUILD_ARG_KEYS.join(", ")}, or start with CODEBUILD_ or AWS_)`, From bde9a77e299d7cf8e68d497477fcfe94cf85d7ec Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Fri, 20 Nov 2026 15:22:55 -0500 Subject: [PATCH 3/8] feat(project): sync vended CDK dependencies on build and deploy (#2861) * feat(project): sync vended CDK dependencies on build and deploy agentcore create is the only writer of agentcore/cdk/package.json, so a project kept the @aws/agentcore-cdk it was created with across CLI upgrades. Fields a newer CLI writes to agentcore.json that the old library does not know were dropped at synth without an error. Before synth, build and deploy now rewrite every dependency the vended package.json names to the specifier this CLI vends and run npm install, leaving dependencies the user added alone. A pin newer than this CLI fails with an upgrade hint, non-version specifiers are skipped with a warning, and a failed install restores package.json. A deploy that removes the stack only warns. Opt out with 'agentcore config disableDependencyManagement true'. Ports the v0 behavior from #1777. * feat(project): install CDK dependencies when node_modules is missing When agentcore/cdk/node_modules is missing, build and deploy now run npm install in agentcore/cdk before synth (and before any AWS mutation on deploy), even when the pins already match, instead of failing with "Run 'npm install'". A failed install raises a ProjectStateError that names the directory and carries npm's error; a teardown only warns. With disableDependencyManagement set, the existing error is kept. * fix(project): explain that CLI-managed CDK dependencies can't be upgraded A newer @aws/agentcore-cdk now points at 'agentcore update'. A newer toolchain pin lists every CDK dependency the CLI manages, read from the vended package.json, and says to set it back or opt out with disableDependencyManagement. Blocking behavior is unchanged. * refactor(project): reuse declaresNothingDeployable and tidy CDK dependency sync Move declaresNothingDeployable to src/core/project/spec.ts so the CDK backend uses it to decide whether a dependency problem only warns, in place of its own inline check. Warn when package.json cannot be restored after a failed install, run npm install with --no-audit --no-fund as migrate does, correct the writers named in the sync's doc comment, and stop exporting types nothing else uses. Add tests that the build and deploy handlers and screens pass disableDependencyManagement to the backend. * refactor(project): simplify CDK dependency sync types and test setup parseSpecifier returns the base version and isNewer takes whether the vended pin is exact, since only that distinction was ever read. BuildBackendInput duplicated BuildProjectInput and is removed. The build and deploy handler tests seed the global config with applyOverrides. * test(project): drop CDK dependency sync tests covered by the backend suite * fix(project): decide CDK dependency installs from what is installed Address review feedback on the CDK dependency sync: - Install when the installed @aws/agentcore-cdk is missing or does not satisfy the declared pin, so a pulled manifest or an interrupted install no longer leaves a stale library. The restore-on-failure path is gone and npm's ProcessFailedError propagates unwrapped. - Leave a tilde or caret pin alone when major.minor match and its patch is at or above the vended one, so two CLI releases do not flip it. - With dependency management disabled, skip the newer-pin warning and warn about an older L3 pin instead. - Compare against the version this CLI vends, name both 'agentcore update' and the opt-out, give one sentence per newer pin, and show only the L3 pin when it is newer. - Validate the manifest with zod through ReadWriteJson so a malformed shape is a ProjectStateError, share the specifier parse with declaredCdkDependency, and keep the file's indent and line endings. * docs(readme): explain CDK dependency management on build and deploy --------- Co-authored-by: jariy17 --- README.md | 6 + src/core/project/backends/cdk.test.ts | 91 ++++- src/core/project/backends/cdk.ts | 46 ++- .../project/backends/cdk/compatibility.ts | 16 +- .../project/backends/cdk/dependencies.test.ts | 320 ++++++++++++++++++ src/core/project/backends/cdk/dependencies.ts | 236 +++++++++++++ src/core/project/backends/types.ts | 5 +- src/core/project/manager.test.ts | 40 ++- src/core/project/manager.tsx | 16 +- src/core/project/spec.ts | 29 ++ src/globalConfig/config.tsx | 3 + src/globalConfig/types.tsx | 1 + src/handlers/project/build/index.test.ts | 29 +- src/handlers/project/build/index.ts | 13 +- src/handlers/project/build/screen.tsx | 19 +- .../project/buildDeploy.screen.test.tsx | 50 ++- src/handlers/project/deploy/index.test.ts | 33 +- src/handlers/project/deploy/index.ts | 29 +- src/handlers/project/deploy/screen.tsx | 3 +- src/handlers/project/project.test.ts | 22 +- src/handlers/project/types.ts | 9 +- 21 files changed, 929 insertions(+), 87 deletions(-) create mode 100644 src/core/project/backends/cdk/dependencies.test.ts create mode 100644 src/core/project/backends/cdk/dependencies.ts create mode 100644 src/core/project/spec.ts diff --git a/README.md b/README.md index 34e74c71b5..6a3dba7b7e 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,12 @@ Global flags, available on every command: (`transformAgentCoreJson`). All three come from `@aws/agentcore-cdk`, so that logic is updated through the library rather than changes to your CDK app. +`agentcore build` and `agentcore deploy` keep the dependencies `agentcore create` +wrote to `agentcore/cdk/package.json` at the versions this CLI vends, and run +`npm install` when they change or are not installed, so both commands may need +network access to npm. Dependencies you add yourself are left alone. To manage +the CDK dependencies yourself, run `agentcore config disableDependencyManagement true`. + `lib/cdk-stack.ts` instantiates one `AgentCoreApplication`. This is the file you edit to add your own resources. Runtimes and harnesses implement `iam.IGrantable`, so you can pass them to a resource's CDK grant methods to give your agents access. diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 267b8db4dc..69470a7025 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { tmpdir } from "node:os"; import type { Stack } from "@aws-sdk/client-cloudformation"; @@ -36,6 +36,7 @@ const OLD_PAYMENT_ARN = "arn:aws:bedrock-agentcore:us-east-1:111122223333:" + `token-vault/default/paymentcredentialprovider/${OLD_PAYMENT_PROVIDER}`; const json = new FsReadWriteJson({ logger: createSilentLogger() }); +const VENDED_CDK_PACKAGE_JSON = join(import.meta.dir, "../../../assets/cdk/package.json"); /** A template holding only what CDK adds itself, as an empty project synthesizes. */ const METADATA_ONLY = { CDKMetadata: { Type: "AWS::CDK::Metadata" } }; @@ -574,6 +575,46 @@ describe("CdkBackend.build", () => { ]); }); + test("syncs the project's CDK dependencies to the vended pins before synthesizing", async () => { + const input = await project(); + const vended = JSON.parse(await readFile(VENDED_CDK_PACKAGE_JSON, "utf8")); + const manifestPath = join(cdkDirectory(input), "package.json"); + await writeFile( + manifestPath, + JSON.stringify({ + ...vended, + dependencies: { ...vended.dependencies, "@aws/agentcore-cdk": "1.0.3", zod: "4.1.0" }, + }), + ); + const subject = harness(); + + const events = await collect(subject.backend.build(input)); + + const updated = JSON.parse(await readFile(manifestPath, "utf8")); + expect(updated.dependencies).toEqual({ ...vended.dependencies, zod: "4.1.0" }); + expect(events[0]).toEqual({ + type: "step", + message: `updating CDK dependencies: @aws/agentcore-cdk 1.0.3 -> ${vended.dependencies["@aws/agentcore-cdk"]}`, + }); + expect(subject.commands).toEqual([ + { command: ["npm", "install", "--no-audit", "--no-fund"], cwd: cdkDirectory(input) }, + { command: synthCommand(input), cwd: cdkDirectory(input) }, + ]); + }); + + test("leaves the CDK dependencies alone when dependency management is disabled", async () => { + const input = await project(); + const manifest = JSON.stringify({ dependencies: { "@aws/agentcore-cdk": "1.0.3" } }); + const manifestPath = join(cdkDirectory(input), "package.json"); + await writeFile(manifestPath, manifest); + const subject = harness(); + + await collect(subject.backend.build(input, { disableDependencyManagement: true })); + + expect(await readFile(manifestPath, "utf8")).toBe(manifest); + expect(subject.commands).toEqual([{ command: synthCommand(input), cwd: cdkDirectory(input) }]); + }); + test("fails actionably when CDK dependencies are missing", async () => { const input = await project(false); const subject = harness(); @@ -1441,6 +1482,30 @@ describe("CdkBackend.deploy", () => { expect(state.targets.default?.stackArn).toBeUndefined(); }); + test("installs a missing node_modules before provisioning credentials", async () => { + const input = await project(false); + await writeFile( + join(cdkDirectory(input), "package.json"), + await readFile(VENDED_CDK_PACKAGE_JSON, "utf8"), + ); + await writeAssembly(input, [TARGET.name]); + let commandsBeforeProvisioning: string[] = []; + // eslint-disable-next-line require-yield -- a spy that only records when provisioning starts + const provisionCredentials: CredentialProvisioner = async function* () { + commandsBeforeProvisioning = subject.commands.map(({ command }) => command.join(" ")); + return {}; + }; + const subject = harness({ provisionCredentials }); + + const deployed = await collectDeploy(subject.backend.deploy(input, deployInput())); + + expect(deployed.events).toContainEqual({ + type: "step", + message: "installing CDK dependencies (node_modules missing)", + }); + expect(commandsBeforeProvisioning).toEqual(["npm install --no-audit --no-fund"]); + }); + test("checks local CDK prerequisites before provisioning credentials", async () => { const input = await project(false); // no agentcore/cdk/node_modules let provisioned = false; @@ -1613,6 +1678,30 @@ describe("CdkBackend.deploy", () => { expect(subject.transactionSearchRegions).toEqual([]); }); + test("does not block a teardown on a CDK pin newer than this CLI", async () => { + const input = await project(); + await writeAssembly(input, [TARGET.name], { resources: METADATA_ONLY }); + const vended = JSON.parse(await readFile(VENDED_CDK_PACKAGE_JSON, "utf8")); + await writeFile( + join(cdkDirectory(input), "package.json"), + JSON.stringify({ + ...vended, + dependencies: { ...vended.dependencies, "@aws/agentcore-cdk": "999.0.0" }, + }), + ); + const subject = harness(); + + const deployed = await collectDeploy( + subject.backend.deploy(input, deployInput({ confirmTeardown: async () => true })), + ); + + expect(deployed.result).toEqual({ outputs: {}, tornDown: true }); + expect(deployed.events).toContainEqual({ + type: "warning", + message: expect.stringContaining("@aws/agentcore-cdk 999.0.0"), + }); + }); + test("removes the stack when the teardown is confirmed", async () => { const input = await project(); await writeAssembly(input, [TARGET.name], { resources: METADATA_ONLY }); diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 6c1864ac32..2b60f67fe9 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -4,6 +4,7 @@ import { GetTemplateCommand, type Stack } from "@aws-sdk/client-cloudformation"; import { parse as parseYaml } from "yaml"; import { MalformedServiceResponseError, ProjectStateError } from "../../../errors/errors"; import type { + BuildProjectInput, DeployResult, Project, ProjectEvent, @@ -25,6 +26,9 @@ import { import { buildxDriverWarning, checkArm64Builder, selectBuildxBuilder } from "./cdk/arm64Builder"; import { localImageBuilds } from "./cdk/localImages"; import { resolveCdkDockerExecutable } from "../../dev/containerTool"; +import { syncCdkDependencies } from "./cdk/dependencies"; +import { declaresNothingDeployable } from "../spec"; +import { defaultSource, type AssetSource } from "../source"; import { createLineSplitter, FsReadWriteJson, @@ -151,6 +155,8 @@ export type CdkBackendConfig = { runner?: ProcessRunner; checkTool?: typeof requireTool; json?: ReadWriteJson; + /** Where the CDK package.json this CLI vends is read from, as the pins to sync to. */ + source?: AssetSource; createCloudFormationClient?: CreateCloudFormationClient; /** Identity client used to provision the project's credential providers. */ identity: CredentialProviderCalls; @@ -192,6 +198,7 @@ export class CdkBackend implements ProjectBackend { private readonly runner: ProcessRunner; private readonly checkTool: typeof requireTool; private readonly json: ReadWriteJson; + private readonly source: AssetSource; private readonly cdk: CdkRunner; private readonly resolveCredentials: CdkCredentialResolver; private readonly bootstrap: BootstrapProbe; @@ -218,6 +225,7 @@ export class CdkBackend implements ProjectBackend { config.createCloudFormationClient ?? createCloudFormationClient; this.checkTool = config.checkTool ?? requireTool; this.json = config.json ?? new FsReadWriteJson({ logger: config.logger }); + this.source = config.source ?? defaultSource(); this.cdk = config.cdk ?? createCdkRunner(config.logger); this.resolveCredentials = config.resolveCredentials ?? createCdkCredentialResolver(config.logger); @@ -247,15 +255,32 @@ export class CdkBackend implements ProjectBackend { // Local prerequisites for synth. Checked before any AWS mutation so a missing // toolchain or dependencies fails without having provisioned credentials. - private async ensureCdkDependencies(project: Project): Promise { + private async *ensureCdkDependencies( + project: Project, + input: BuildProjectInput & { lenient?: boolean }, + ): AsyncGenerator { const cdkDir = this.cdkDirectory(project); - if (!existsSync(join(cdkDir, "node_modules"))) { + await this.checkTool("npm", "Install Node.js: https://nodejs.org/"); + // The sync installs a missing node_modules, unless the user manages dependencies + // themselves or there is no package.json to install from. + if ( + !existsSync(join(cdkDir, "node_modules")) && + (input.disableDependencyManagement || !existsSync(join(cdkDir, "package.json"))) + ) { throw new ProjectStateError( `CDK dependencies are missing for project '${project.name}'. ` + `Run 'npm install' in ${cdkDir}.`, ); } - await this.checkTool("npm", "Install Node.js: https://nodejs.org/"); + yield* syncCdkDependencies({ + cdkDirectory: cdkDir, + vendedManifest: await this.source.read("cdk/package.json"), + json: this.json, + runner: this.runner, + logger: this.logger, + disabled: input.disableDependencyManagement, + lenient: input.lenient, + }); } private async *synthesize( @@ -263,8 +288,6 @@ export class CdkBackend implements ProjectBackend { explainUndeployedCredentials: boolean, builds: WorkloadBuilds, ): AsyncGenerator { - await this.ensureCdkDependencies(project); - const compatibilityWarning = await cdkCompatibilityWarning(this.cdkDirectory(project)); if (compatibilityWarning) { yield { type: "warning", message: compatibilityWarning }; @@ -302,7 +325,11 @@ export class CdkBackend implements ProjectBackend { } } - public async *build(project: Project): AsyncGenerator { + public async *build( + project: Project, + input: BuildProjectInput = {}, + ): AsyncGenerator { + yield* this.ensureCdkDependencies(project, input); const { builds, local } = resolveWorkloads(project); yield* this.synthesize(project, true, builds); yield* this.buildLocalImages(project, builds, local); @@ -375,7 +402,12 @@ export class CdkBackend implements ProjectBackend { // Fail on local setup errors (missing toolchain/deps) and malformed state // before any AWS mutation, so a local problem never leaves credentials // provisioned or the stack ARN unrecorded. - await this.ensureCdkDependencies(project); + // A project that declares nothing is about to have its stack removed, and a + // dependency problem must not keep that from happening. + yield* this.ensureCdkDependencies(project, { + ...input, + lenient: declaresNothingDeployable(project), + }); const { builds, local } = input.workloadBuilds ? { builds: input.workloadBuilds, local: input.localWorkloads ?? new Map() } : resolveWorkloads(project); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 45b38ec0f5..5dbfcd3f9e 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -35,21 +35,21 @@ export function assertCdkLocalContainerSupport(cdkDirectory: string): void { ); } -export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { +/** The `@aws/agentcore-cdk` version installed in `node_modules`, if it can be read. */ +export async function installedCdkVersion(cdkDirectory: string): Promise { const packagePath = join(cdkDirectory, "node_modules", "@aws", "agentcore-cdk", "package.json"); - - let installedVersion: unknown; try { - const packageJson = JSON.parse(await readFile(packagePath, "utf8")) as { - version?: unknown; - }; - installedVersion = packageJson.version; + const { version } = JSON.parse(await readFile(packagePath, "utf8")) as { version?: unknown }; + return typeof version === "string" ? version : undefined; } catch { return undefined; } +} +export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { + const installedVersion = await installedCdkVersion(cdkDirectory); if ( - typeof installedVersion !== "string" || + installedVersion === undefined || semver.valid(installedVersion) === null || !semver.lt(installedVersion, MINIMUM_COMPATIBLE_CDK_VERSION) ) { diff --git a/src/core/project/backends/cdk/dependencies.test.ts b/src/core/project/backends/cdk/dependencies.test.ts new file mode 100644 index 0000000000..f8bffbfb22 --- /dev/null +++ b/src/core/project/backends/cdk/dependencies.test.ts @@ -0,0 +1,320 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { ProjectEvent } from "../../../../handlers/project/types"; +import { FsReadWriteJson, ProcessFailedError, type ProcessRunner } from "../../../../io"; +import { createSilentLogger } from "../../../../testing"; +import { ProjectStateError } from "../../../../errors/errors"; +import { newerPinMessage, planDependencySync, syncCdkDependencies } from "./dependencies"; + +const VENDED = { + devDependencies: { "aws-cdk": "~2.1126.0", typescript: "~5.9.3" }, + dependencies: { "@aws/agentcore-cdk": "1.1.0", "aws-cdk-lib": "~2.269.0" }, +}; + +const tempDirectories: string[] = []; + +afterEach(async () => { + await Promise.all( + tempDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })), + ); +}); + +/** A CDK directory whose package.json is `manifest`, with `installed` as the installed L3 (null: none). */ +async function cdkDirectoryWith( + manifest: object | string, + installed: string | null = VENDED.dependencies["@aws/agentcore-cdk"], +): Promise { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-dependencies-")); + tempDirectories.push(directory); + await writeFile( + join(directory, "package.json"), + typeof manifest === "string" ? manifest : JSON.stringify(manifest, undefined, 2), + ); + if (installed) await installL3(directory, installed); + return directory; +} + +async function installL3(directory: string, version: string): Promise { + const library = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await mkdir(library, { recursive: true }); + await writeFile(join(library, "package.json"), JSON.stringify({ version })); +} + +async function run( + cdkDirectory: string, + options: { runner?: ProcessRunner; lenient?: boolean; disabled?: boolean } = {}, +): Promise<{ events: ProjectEvent[]; installs: number }> { + const events: ProjectEvent[] = []; + let installs = 0; + for await (const event of syncCdkDependencies({ + cdkDirectory, + vendedManifest: JSON.stringify(VENDED), + json: new FsReadWriteJson({ logger: createSilentLogger() }), + runner: + options.runner ?? + (async () => { + installs++; + }), + logger: createSilentLogger(), + lenient: options.lenient, + disabled: options.disabled, + })) { + events.push(event); + } + return { events, installs }; +} + +const manifestOf = (directory: string) => readFile(join(directory, "package.json"), "utf8"); + +describe("planDependencySync", () => { + test("moves an older exact L3 pin and older tilde pins to the vended specifiers", () => { + const plan = planDependencySync(VENDED, { + devDependencies: { "aws-cdk": "~2.1126.0", typescript: "~5.9.2" }, + dependencies: { "@aws/agentcore-cdk": "1.0.3", "aws-cdk-lib": "~2.260.0" }, + }); + + expect(plan.changes).toEqual([ + { name: "@aws/agentcore-cdk", section: "dependencies", from: "1.0.3", to: "1.1.0" }, + { name: "aws-cdk-lib", section: "dependencies", from: "~2.260.0", to: "~2.269.0" }, + { name: "typescript", section: "devDependencies", from: "~5.9.2", to: "~5.9.3" }, + ]); + expect(plan.newer).toEqual([]); + }); + + test("migrates caret ranges and restores a managed dependency the user deleted", () => { + const plan = planDependencySync(VENDED, { + devDependencies: { "aws-cdk": "^2.1000.0" }, + dependencies: VENDED.dependencies, + }); + + expect(plan.changes).toEqual([ + { name: "aws-cdk", section: "devDependencies", from: "^2.1000.0", to: "~2.1126.0" }, + { name: "typescript", section: "devDependencies", to: "~5.9.3" }, + ]); + }); + + test("reports pins a newer CLI wrote instead of downgrading them", () => { + const plan = planDependencySync(VENDED, { + devDependencies: { "aws-cdk": "~2.1126.9", typescript: "~5.9.3" }, + dependencies: { "@aws/agentcore-cdk": "1.2.0", "aws-cdk-lib": "~2.270.0" }, + }); + + // A higher patch on a tilde range is inside the vended range, so it is left alone. + expect(plan.changes).toEqual([]); + expect(plan.newer.map(({ name }) => name)).toEqual(["@aws/agentcore-cdk", "aws-cdk-lib"]); + }); + + test("leaves non-version specifiers and the user's own dependencies alone", () => { + const plan = planDependencySync(VENDED, { + devDependencies: VENDED.devDependencies, + dependencies: { + "@aws/agentcore-cdk": "file:../agentcore-cdk.tgz", + "aws-cdk-lib": ">=2.200.0", + "my-construct": "^3.0.0", + }, + }); + + expect(plan.changes).toEqual([]); + expect(plan.skipped).toEqual([ + { name: "@aws/agentcore-cdk", declared: "file:../agentcore-cdk.tgz" }, + { name: "aws-cdk-lib", declared: ">=2.200.0" }, + ]); + }); +}); + +describe("newerPinMessage", () => { + test("names only the L3 pin when it is newer, since the update fixes the rest", () => { + expect( + newerPinMessage([ + { name: "typescript", declared: "~6.0.0", expected: "~5.9.3" }, + { name: "@aws/agentcore-cdk", declared: "1.2.0", expected: "1.1.0" }, + ]), + ).toBe( + "agentcore/cdk/package.json pins @aws/agentcore-cdk 1.2.0, newer than the version this " + + "CLI vends (1.1.0). Run 'agentcore update', or run 'agentcore config " + + "disableDependencyManagement true' to manage the CDK dependencies yourself.", + ); + }); + + test("gives one sentence per newer toolchain pin", () => { + expect( + newerPinMessage([ + { name: "typescript", declared: "~6.0.0", expected: "~5.9.3" }, + { name: "aws-cdk-lib", declared: "~2.270.0", expected: "~2.269.0" }, + ]), + ).toBe( + "agentcore/cdk/package.json pins typescript ~6.0.0, newer than the version this CLI " + + "vends (~5.9.3). agentcore/cdk/package.json pins aws-cdk-lib ~2.270.0, newer than the " + + "version this CLI vends (~2.269.0). Run 'agentcore update', or run 'agentcore config " + + "disableDependencyManagement true' to manage the CDK dependencies yourself.", + ); + }); +}); + +describe("syncCdkDependencies", () => { + test("does nothing when the pins match and the pinned L3 is installed", async () => { + const directory = await cdkDirectoryWith(VENDED); + + expect(await run(directory)).toEqual({ events: [], installs: 0 }); + }); + + test("installs when the manifest matches but an older L3 is installed", async () => { + const directory = await cdkDirectoryWith(VENDED, "1.0.3"); + + const { events, installs } = await run(directory); + + expect(installs).toBe(1); + expect(events[0]).toEqual({ + type: "step", + message: + "installing CDK dependencies (@aws/agentcore-cdk 1.0.3 is installed, " + + "agentcore/cdk/package.json pins 1.1.0)", + }); + }); + + test("installs when node_modules is missing", async () => { + const directory = await cdkDirectoryWith(VENDED, null); + + expect((await run(directory)).installs).toBe(1); + }); + + test("retries the install on the next run after an interrupted one", async () => { + const directory = await cdkDirectoryWith( + { ...VENDED, dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "1.0.3" } }, + "1.0.3", + ); + const interrupted = new ProcessFailedError(["npm", "install"], directory, 130, ""); + + await expect( + run(directory, { + runner: async () => { + throw interrupted; + }, + }), + ).rejects.toBe(interrupted); + expect(JSON.parse(await manifestOf(directory)).dependencies["@aws/agentcore-cdk"]).toBe( + "1.1.0", + ); + + expect((await run(directory)).installs).toBe(1); + }); + + test("rethrows npm's failure, or warns with it when lenient", async () => { + const directory = await cdkDirectoryWith(VENDED, null); + const failure = new ProcessFailedError(["npm", "install"], directory, 1, "npm error E404"); + const runner: ProcessRunner = async () => { + throw failure; + }; + + await expect(run(directory, { runner })).rejects.toBe(failure); + const { events } = await run(directory, { runner, lenient: true }); + expect(events.at(-1)).toEqual({ type: "warning", message: failure.message }); + }); + + test("does nothing when the project has no CDK package.json", async () => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-dependencies-")); + tempDirectories.push(directory); + + expect(await run(directory)).toEqual({ events: [], installs: 0 }); + }); + + test("fails on an L3 library newer than this CLI vends, leaving package.json alone", async () => { + const directory = await cdkDirectoryWith({ + ...VENDED, + dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "1.2.0" }, + }); + const before = await manifestOf(directory); + + await expect(run(directory)).rejects.toThrow( + newerPinMessage([{ name: "@aws/agentcore-cdk", declared: "1.2.0", expected: "1.1.0" }]), + ); + expect(await manifestOf(directory)).toBe(before); + }); + + test("fails on a newer toolchain pin", async () => { + const directory = await cdkDirectoryWith({ + ...VENDED, + dependencies: { ...VENDED.dependencies, "aws-cdk-lib": "~2.270.0" }, + }); + + await expect(run(directory)).rejects.toThrow( + "agentcore/cdk/package.json pins aws-cdk-lib ~2.270.0, newer than the version this CLI " + + "vends (~2.269.0).", + ); + }); + + test("says nothing about a newer pin when dependency management is disabled", async () => { + const directory = await cdkDirectoryWith({ + ...VENDED, + dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "1.2.0" }, + }); + + expect(await run(directory, { disabled: true })).toEqual({ events: [], installs: 0 }); + }); + + test("warns about an older L3 pin when dependency management is disabled", async () => { + const directory = await cdkDirectoryWith( + { ...VENDED, dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "1.0.3" } }, + "1.0.3", + ); + const before = await manifestOf(directory); + + expect(await run(directory, { disabled: true })).toEqual({ + events: [ + { + type: "warning", + message: + "agentcore/cdk/package.json pins @aws/agentcore-cdk 1.0.3, older than the version " + + "this CLI vends (1.1.0). Fields this CLI writes that 1.0.3 does not know are " + + "dropped at synth. Set it to 1.1.0, or run 'agentcore config " + + "disableDependencyManagement false' to let the CLI manage it.", + }, + ], + installs: 0, + }); + expect(await manifestOf(directory)).toBe(before); + }); + + test("warns about a specifier that is not a single pinned version", async () => { + const directory = await cdkDirectoryWith({ + ...VENDED, + dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "file:../cdk.tgz" }, + }); + + expect((await run(directory)).events).toEqual([ + { + type: "warning", + message: + "@aws/agentcore-cdk file:../cdk.tgz in agentcore/cdk/package.json is not a single " + + "pinned version, so the CLI leaves it unchanged.", + }, + ]); + }); + + test("keeps the indent, line endings, key order and unknown fields of package.json", async () => { + const manifest = { + name: "my-app", + private: true, + devDependencies: VENDED.devDependencies, + dependencies: { ...VENDED.dependencies, "@aws/agentcore-cdk": "1.0.3" }, + overrides: { foo: "1.0.0" }, + }; + const format = (value: object) => + `${JSON.stringify(value, undefined, "\t").replace(/\n/g, "\r\n")}\r\n`; + const directory = await cdkDirectoryWith(format(manifest)); + + await run(directory); + + expect(await manifestOf(directory)).toBe( + format({ ...manifest, dependencies: VENDED.dependencies }), + ); + }); + + test("reports a malformed package.json as a project state error", async () => { + const directory = await cdkDirectoryWith({ dependencies: { "aws-cdk-lib": 5 } }); + + await expect(run(directory)).rejects.toBeInstanceOf(ProjectStateError); + }); +}); diff --git a/src/core/project/backends/cdk/dependencies.ts b/src/core/project/backends/cdk/dependencies.ts new file mode 100644 index 0000000000..cf8661c782 --- /dev/null +++ b/src/core/project/backends/cdk/dependencies.ts @@ -0,0 +1,236 @@ +import { existsSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import semver from "semver"; +import z from "zod"; +import { DeserializationError, ProjectStateError } from "../../../../errors/errors"; +import type { ProjectEvent } from "../../../../handlers/project/types"; +import { createLineSplitter, type ProcessRunner, type ReadWriteJson } from "../../../../io"; +import type { Logger } from "../../../../logging"; +import { withOutputEvents } from "../../events"; +import { installedCdkVersion } from "./compatibility"; + +type Section = "dependencies" | "devDependencies"; + +const ManifestSchema = z.object({ + dependencies: z.record(z.string(), z.string()).optional(), + devDependencies: z.record(z.string(), z.string()).optional(), +}); + +type Manifest = z.infer; + +/** A managed dependency whose declared specifier is rewritten to the one this CLI vends. */ +type DependencyChange = { name: string; section: Section; from?: string; to: string }; + +type DependencyPlan = { + changes: DependencyChange[]; + /** Managed dependencies the project declares newer than this CLI vends. */ + newer: { name: string; declared: string; expected: string }[]; + /** Managed dependencies declared with a specifier the sync cannot reason about. */ + skipped: { name: string; declared: string }[]; +}; + +const SECTIONS: Section[] = ["dependencies", "devDependencies"]; + +const L3_LIBRARY = "@aws/agentcore-cdk"; + +const MANIFEST = "agentcore/cdk/package.json"; + +/** + * The version behind a single pinned specifier (`1.2.3`, `~1.2.3`, `^1.2.3`, `=1.2.3`). + * node-semver's Range API expands ~ and ^ into comparators, so the base version is read + * directly; anything else, such as `file:`, `>=1.0.0` or `2.x`, is not a single pin. + */ +export function pinnedVersion(spec: string): semver.SemVer | null { + return semver.parse(spec.trim().replace(/^[~^=]/, "")); +} + +function compare(declared: semver.SemVer, expected: semver.SemVer, exact: boolean): number { + // An exact pin (the L3 library) compares fully, prerelease included, so a project a + // newer CLI moved to 1.2.0 is never silently put back on 1.1.0. + if (exact) return semver.compare(declared, expected); + if (declared.major !== expected.major) return declared.major - expected.major; + if (declared.minor !== expected.minor) return declared.minor - expected.minor; + // A higher patch is inside the vended range, and rewriting it down would flip the file + // back and forth when two CLI releases build the same repo. + return declared.patch >= expected.patch ? 0 : -1; +} + +/** + * Compares the project's CDK manifest with the one this CLI vends. Every dependency the + * vended manifest names is managed; anything else the project declares is left alone. + */ +export function planDependencySync(vended: Manifest, project: Manifest): DependencyPlan { + const plan: DependencyPlan = { changes: [], newer: [], skipped: [] }; + for (const section of SECTIONS) { + for (const [name, to] of Object.entries(vended[section] ?? {})) { + const declaredIn = SECTIONS.find((s) => project[s]?.[name] !== undefined); + const from = declaredIn && project[declaredIn]?.[name]; + if (!declaredIn || from === undefined) { + // The vended CDK app cannot synthesize without it. + plan.changes.push({ name, section, to }); + continue; + } + if (from === to) continue; + const declared = pinnedVersion(from); + const expected = pinnedVersion(to); + if (!declared || !expected) { + // file:, git:, tags and open ranges are deliberate overrides, such as a tarball + // under test, so they are never rewritten. + plan.skipped.push({ name, declared: from }); + continue; + } + const order = compare(declared, expected, !/^[~^]/.test(to.trim())); + if (order > 0) plan.newer.push({ name, declared: from, expected: to }); + else if (order < 0) plan.changes.push({ name, section: declaredIn, from, to }); + } + } + return plan; +} + +function formatChanges(changes: DependencyChange[]): string { + return changes.map(({ name, from, to }) => `${name} ${from ?? "(missing)"} -> ${to}`).join(", "); +} + +/** + * Explains managed pins the project declares newer than this CLI vends. Only a newer CLI + * writes a newer L3 pin, and updating to it fixes the toolchain pins too, so those are + * left out when the L3 pin is newer. + */ +export function newerPinMessage(newer: DependencyPlan["newer"]): string { + const library = newer.filter(({ name }) => name === L3_LIBRARY); + const pins = (library.length > 0 ? library : newer).map( + ({ name, declared, expected }) => + `${MANIFEST} pins ${name} ${declared}, newer than the version this CLI vends (${expected}).`, + ); + return ( + `${pins.join(" ")} Run 'agentcore update', or run ` + + `'agentcore config disableDependencyManagement true' to manage the CDK dependencies yourself.` + ); +} + +/** Writes `manifest` with the indent, line endings and trailing newline found in `raw`. */ +function formatLike(raw: string, manifest: unknown): string { + const indent = /^[ \t]+(?=")/m.exec(raw)?.[0] ?? ""; + const eol = raw.includes("\r\n") ? "\r\n" : "\n"; + const text = JSON.stringify(manifest, undefined, indent).replace(/\n/g, eol); + return /\r?\n$/.test(raw) ? text + eol : text; +} + +type SyncCdkDependenciesInput = { + cdkDirectory: string; + /** Text of the CDK package.json this CLI vends at create. */ + vendedManifest: string; + json: ReadWriteJson; + runner: ProcessRunner; + logger: Logger; + /** From the global config: leave package.json and node_modules alone. */ + disabled?: boolean; + /** Downgrade failures to warnings, so a deploy that removes the stack is never blocked. */ + lenient?: boolean; +}; + +/** + * Brings the project's managed CDK dependencies to the versions this CLI release vends. + * + * Otherwise only `create` and `migrate` write agentcore/cdk/package.json, so without this a + * project keeps the L3 library it was created with across CLI upgrades, and any field + * the newer CLI writes to agentcore.json that the old library does not know is dropped + * at synth without an error. + */ +export async function* syncCdkDependencies( + input: SyncCdkDependenciesInput, +): AsyncGenerator { + const manifestPath = join(input.cdkDirectory, "package.json"); + // A project without the vended manifest has no CDK app this sync could keep current; + // synth reports that on its own. + if (!existsSync(manifestPath)) return; + + let project: Manifest; + try { + project = await input.json.read(manifestPath, ManifestSchema); + } catch (error) { + if (!(error instanceof DeserializationError)) throw error; + throw new ProjectStateError(error.message, { cause: error }); + } + const plan = planDependencySync(ManifestSchema.parse(JSON.parse(input.vendedManifest)), project); + + for (const { name, declared } of plan.skipped) { + yield { + type: "warning", + message: `${name} ${declared} in ${MANIFEST} is not a single pinned version, so the CLI leaves it unchanged.`, + }; + } + + if (input.disabled) { + const library = plan.changes.find(({ name, from }) => name === L3_LIBRARY && from); + if (library) { + yield { + type: "warning", + message: + `${MANIFEST} pins ${L3_LIBRARY} ${library.from}, older than the version this CLI ` + + `vends (${library.to}). Fields this CLI writes that ${library.from} does not know ` + + `are dropped at synth. Set it to ${library.to}, or run ` + + `'agentcore config disableDependencyManagement false' to let the CLI manage it.`, + }; + } + return; + } + + if (plan.newer.length > 0) { + const message = newerPinMessage(plan.newer); + if (!input.lenient) throw new ProjectStateError(message); + yield { type: "warning", message }; + } + + if (plan.changes.length > 0) { + // Edits the parsed file, not the validated copy, so key order and unknown fields survive. + const raw = await readFile(manifestPath, "utf8"); + const manifest = JSON.parse(raw) as Record | undefined>; + for (const { name, section, to } of plan.changes) { + (manifest[section] ??= {})[name] = to; + } + yield { type: "step", message: `updating CDK dependencies: ${formatChanges(plan.changes)}` }; + await writeFile(manifestPath, formatLike(raw, manifest)); + } else { + // What is installed decides, not the manifest: a pulled package.json a teammate + // already synced, or an interrupted install, leaves matching pins over an old library. + // A newer L3 pin only gets this far on a teardown, which needs no newer library. + const installed = await installedCdkVersion(input.cdkDirectory); + const declared = project.dependencies?.[L3_LIBRARY]; + const stale = + installed === undefined || + (declared !== undefined && + semver.validRange(declared) !== null && + !plan.newer.some(({ name }) => name === L3_LIBRARY) && + !semver.satisfies(installed, declared)); + if (!stale) return; + yield { + type: "step", + message: + installed === undefined + ? "installing CDK dependencies (node_modules missing)" + : `installing CDK dependencies (${L3_LIBRARY} ${installed} is installed, ${MANIFEST} pins ${declared})`, + }; + } + + try { + // npm reconciles the edited manifest against the existing lockfile, so dependencies + // the user added keep their resolved versions. + yield* withOutputEvents((emit) => { + const lines = createLineSplitter(emit); + return input + .runner(["npm", "install", "--no-audit", "--no-fund"], { + cwd: input.cdkDirectory, + onOutput: (chunk) => { + input.logger.debug(chunk); + lines.push(chunk); + }, + }) + .finally(() => lines.flush()); + }); + } catch (error) { + if (!input.lenient) throw error; + yield { type: "warning", message: (error as Error).message }; + } +} diff --git a/src/core/project/backends/types.ts b/src/core/project/backends/types.ts index 29b0be374c..e01b41ca42 100644 --- a/src/core/project/backends/types.ts +++ b/src/core/project/backends/types.ts @@ -1,5 +1,6 @@ import type { LocalWorkloadSources, WorkloadBuilds } from "../../../handlers/project/types"; import type { + BuildProjectInput, DeployResult, Project, ProjectEvent, @@ -9,7 +10,7 @@ import type { } from "../../../handlers/project/types"; import type { AwsDeploymentTarget } from "../../../projectSchemas/aws-targets"; -export type DeployBackendInput = { +export type DeployBackendInput = BuildProjectInput & { /** Fully resolved account and region selected from aws-targets.json. */ target: AwsDeploymentTarget; /** Requests approval after synthesis identifies a teardown. */ @@ -34,7 +35,7 @@ export type ResolveProjectResourcesBackendInput = { /** Builds the deployable artifacts owned by a project's selected backend. */ export interface ProjectBackend { - build(project: Project): AsyncGenerator; + build(project: Project, input?: BuildProjectInput): AsyncGenerator; deploy(project: Project, input: DeployBackendInput): AsyncGenerator; resolveDeployedResources( project: Project, diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 7c81b1c56a..08f9c2bfb7 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -1727,7 +1727,7 @@ describe("chinaModelProviderRestriction", () => { describe("FsProjectManager.build", () => { // build() requires the CDK app's node_modules; create() with skipInstall - // never produces them, so tests stub the directory in. + // never produces them, so tests stub in the library at the pin create() vends. async function scaffolded( subject: FsProjectManager, directory: string, @@ -1740,9 +1740,16 @@ describe("FsProjectManager.build", () => { skipGit: true, }); if (withDependencies) { - await mkdir(join(directory, "example", "agentcore", "cdk", "node_modules"), { - recursive: true, - }); + const cdkDirectory = join(directory, "example", "agentcore", "cdk"); + const library = join(cdkDirectory, "node_modules", "@aws", "agentcore-cdk"); + const { dependencies } = JSON.parse( + await readFile(join(cdkDirectory, "package.json"), "utf8"), + ); + await mkdir(library, { recursive: true }); + await writeFile( + join(library, "package.json"), + JSON.stringify({ version: dependencies["@aws/agentcore-cdk"] }), + ); } return project; } @@ -1779,13 +1786,34 @@ describe("FsProjectManager.build", () => { expect(events).toEqual([{ type: "step", message: "synthesizing CloudFormation templates" }]); }); - test("fails actionably when the CDK dependencies are missing", async () => { + test("installs the CDK dependencies when node_modules is missing", async () => { + const directory = await inTempDirectory(); + const { manager: subject, commands } = manager(); + const project = await scaffolded(subject, directory, false); + commands.length = 0; + const cdkDirectory = join(directory, "example", "agentcore", "cdk"); + + const events = await drain(subject.build(project)); + + expect(events[0]).toEqual({ + type: "step", + message: "installing CDK dependencies (node_modules missing)", + }); + expect(commands.map(({ command, cwd }) => [command.slice(0, 2), cwd])).toEqual([ + [["npm", "install"], cdkDirectory], + [["npm", "run"], cdkDirectory], + ]); + }); + + test("fails actionably when node_modules is missing and dependency management is off", async () => { const directory = await inTempDirectory(); const { manager: subject, commands } = manager(); const project = await scaffolded(subject, directory, false); commands.length = 0; - await expect(drain(subject.build(project))).rejects.toThrow(/npm install/); + await expect( + drain(subject.build(project, { disableDependencyManagement: true })), + ).rejects.toThrow(/Run 'npm install'/); expect(commands).toEqual([]); }); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index e4b260e4df..1f84022969 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -6,6 +6,7 @@ import type { AddResourceOptions, AddResourceInput, CreateProjectInput, + BuildProjectInput, DeployProjectInput, DeployResult, EnvLocalEntry, @@ -90,6 +91,7 @@ import { isChinaRegion } from "../partition"; import z from "zod"; import { CdkBackend, type TransactionSearchEnabler } from "./backends/cdk"; import { resolveAwsAccount } from "./backends/cdk/environment"; +import { pinnedVersion } from "./backends/cdk/dependencies"; import type { ProjectBackend } from "./backends/types"; import { AwsDeploymentTargetSchema, @@ -434,6 +436,7 @@ export class FsProjectManager implements ProjectManager { runner: config.runner, checkTool: config.checkTool, json: config.json, + source: this.assetSource, }), }; this.templateRenderer = config.templateRenderer ?? new HandlebarsTemplateRenderer(); @@ -483,9 +486,8 @@ export class FsProjectManager implements ProjectManager { const declared = manifest?.dependencies?.["@aws/agentcore-cdk"]; if (typeof declared !== "string") return undefined; - const spec = declared.trim(); - const version = semver.valid(spec.replace(/^[~^=]/, "")); - return version ? { spec, version } : undefined; + const version = pinnedVersion(declared)?.version; + return version ? { spec: declared.trim(), version } : undefined; } public async *create(input: CreateProjectInput): AsyncGenerator { @@ -1501,14 +1503,17 @@ export class FsProjectManager implements ProjectManager { return { spec: result.spec, envEntries: result.envEntries ?? [] }; } - public async *build(project: Project): AsyncGenerator { + public async *build( + project: Project, + input: BuildProjectInput = {}, + ): AsyncGenerator { assertV1Project(project, "build"); // Half-written project files from an interrupted `agentcore migrate` must not // be synced or synthesized; build has no target, so only that state stops it. await assertNoPendingMigration(project.rootPath); const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); for (const message of synced.messages) yield { type: "step", message }; - yield* this.backendFor(project).build(synced.project); + yield* this.backendFor(project).build(synced.project, input); } public async syncRuntimeBuilds( @@ -1717,6 +1722,7 @@ export class FsProjectManager implements ProjectManager { skipBootstrap: input.skipBootstrap, workloadBuilds, localWorkloads, + disableDependencyManagement: input.disableDependencyManagement, }); } diff --git a/src/core/project/spec.ts b/src/core/project/spec.ts new file mode 100644 index 0000000000..f45b21b868 --- /dev/null +++ b/src/core/project/spec.ts @@ -0,0 +1,29 @@ +import type { Project } from "../../handlers/project/types"; + +/** + * True when the spec declares none of the resources `removeAllResources` + * clears, i.e. what an emptied project looks like. This is the up-front proxy + * for the backend's post-synth zero-resource count; the two can disagree when a + * declared resource synthesizes no CloudFormation resource (or a hand-edited + * CDK app adds one), so the backend's count stays authoritative and this only + * decides whether to ask the user before starting, and whether a CDK dependency + * problem only warns so the teardown still runs. + */ +export function declaresNothingDeployable(project: Project): boolean { + const { spec } = project; + const collections = [ + spec.runtimes, + spec.memories, + spec.knowledgeBases, + spec.credentials, + spec.evaluators, + spec.onlineEvalConfigs, + spec.agentCoreGateways, + spec.policyEngines, + spec.configBundles, + spec.harnesses, + spec.toolRuntimes ?? [], + spec.payments ?? [], + ]; + return collections.every((collection) => collection.length === 0); +} diff --git a/src/globalConfig/config.tsx b/src/globalConfig/config.tsx index 8530ccbc34..4ef2179c2a 100644 --- a/src/globalConfig/config.tsx +++ b/src/globalConfig/config.tsx @@ -11,6 +11,7 @@ export const DEFAULT_GLOBAL_CONFIG: GlobalConfig = { }, installationId: crypto.randomUUID(), transactionSearch: true, + disableDependencyManagement: false, }; /** @@ -28,5 +29,7 @@ export function applyOverrides( }, installationId: overrides.installationId ?? defaults.installationId, transactionSearch: overrides.transactionSearch ?? defaults.transactionSearch, + disableDependencyManagement: + overrides.disableDependencyManagement ?? defaults.disableDependencyManagement, }; } diff --git a/src/globalConfig/types.tsx b/src/globalConfig/types.tsx index 0963129f76..faf665507a 100644 --- a/src/globalConfig/types.tsx +++ b/src/globalConfig/types.tsx @@ -21,6 +21,7 @@ export const globalConfigFileSchema = z.object({ .optional(), installationId: z.uuid().optional(), transactionSearch: z.boolean().optional(), + disableDependencyManagement: z.boolean().optional(), }); /** The raw shape stored on disk for overriding defaults. */ diff --git a/src/handlers/project/build/index.test.ts b/src/handlers/project/build/index.test.ts index a538889f88..62e9b60b5e 100644 --- a/src/handlers/project/build/index.test.ts +++ b/src/handlers/project/build/index.test.ts @@ -7,20 +7,26 @@ import { TestGlobalConfigAccessor, testIO, } from "../../../testing"; -import type { DeployResult, ProjectEvent } from "../types"; +import type { BuildProjectInput, DeployResult, ProjectEvent } from "../types"; import type { ProjectBackend } from "../../../core/project"; +import { DEFAULT_GLOBAL_CONFIG } from "../../../globalConfig"; +import { applyOverrides } from "../../../globalConfig/config"; type TestBuildOptions = { events?: ProjectEvent[]; /** Thrown by the fake backend after its events, to exercise failure paths. */ failure?: Error; + /** Seeds the global config's disableDependencyManagement flag (defaults to off). */ + disableDependencyManagement?: boolean; }; /** Stubs the backend so the real FsProjectManager and withProject stay in the path. */ function testBuildCommand(options: TestBuildOptions = {}) { const io = testIO(); + const calls: (BuildProjectInput | undefined)[] = []; const backend: ProjectBackend = { - async *build() { + async *build(_project, input) { + calls.push(input); yield* options.events ?? []; if (options.failure) throw options.failure; }, @@ -37,12 +43,17 @@ function testBuildCommand(options: TestBuildOptions = {}) { const core = new TestCoreClient({ backends: { CDK: backend } }); const root = createRootHandler(core, { io: io.io, - globalConfigAccessor: new TestGlobalConfigAccessor(), + globalConfigAccessor: new TestGlobalConfigAccessor({ + initialConfigData: applyOverrides(DEFAULT_GLOBAL_CONFIG, { + disableDependencyManagement: options.disableDependencyManagement, + }), + }), logger: createSilentLogger(), }); return { io, + calls, run: (args: string[] = []) => root.route(["node", "agentcore", "build", ...args]), }; } @@ -57,6 +68,18 @@ async function inProject(): Promise { } describe("project build handler", () => { + test("passes the global config's disableDependencyManagement flag into the build", async () => { + const managed = testBuildCommand(); + await inProject(); + await managed.run(); + expect(managed.calls[0]?.disableDependencyManagement).toBe(false); + + const optedOut = testBuildCommand({ disableDependencyManagement: true }); + await inProject(); + await optedOut.run(); + expect(optedOut.calls[0]?.disableDependencyManagement).toBe(true); + }); + test("writes step lines and the success line to stderr, nothing to stdout", async () => { const subject = testBuildCommand({ events: [ diff --git a/src/handlers/project/build/index.ts b/src/handlers/project/build/index.ts index 30fc419e49..42429e6135 100644 --- a/src/handlers/project/build/index.ts +++ b/src/handlers/project/build/index.ts @@ -1,4 +1,9 @@ -import { createHandler, ProjectKey, type Middleware } from "../../../router"; +import { + createHandler, + GlobalConfigAccessorKey, + ProjectKey, + type Middleware, +} from "../../../router"; import type { AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; import { JsonKey } from "../../keys"; @@ -31,8 +36,12 @@ export const createBuildProjectHandler = (config: BuildProjectHandlerConfig) => // and the subprocess output stays in the debug log (ProcessFailedError // carries it on failure). --json forces the plain path so no ANSI // reaches a scripted caller's stderr. + const globalConfig = await ctx.require(GlobalConfigAccessorKey).get(); try { - await runWithProgress(config.projectManager.build(project), { + const build = config.projectManager.build(project, { + disableDependencyManagement: globalConfig.disableDependencyManagement, + }); + await runWithProgress(build, { io: config.io, interactive: jsonOutput ? false : undefined, }); diff --git a/src/handlers/project/build/screen.tsx b/src/handlers/project/build/screen.tsx index 7c7298cf40..569de2e508 100644 --- a/src/handlers/project/build/screen.tsx +++ b/src/handlers/project/build/screen.tsx @@ -1,6 +1,6 @@ import { useNavigate } from "react-router"; import { ConfirmAction } from "../../../components/ConfirmAction"; -import { ProjectKey } from "../../../router"; +import { GlobalConfigAccessorKey, ProjectKey, type Context } from "../../../router"; import type { ScreenProps } from "../../types"; import { ProjectGate } from "../ProjectGate"; import type { Project } from "../types"; @@ -22,12 +22,20 @@ export function BuildProjectScreen({ ctx, core }: ScreenProps) { seed={ctx.value(ProjectKey)} onBack={() => navigate(PROJECT_MENU)} > - {(project) => } + {(project) => } ); } -function BuildConfirm({ project, core }: { project: Project; core: ScreenProps["core"] }) { +function BuildConfirm({ + ctx, + project, + core, +}: { + ctx: Context; + project: Project; + core: ScreenProps["core"]; +}) { const navigate = useNavigate(); // No confirmation: a build changes nothing outside the project directory. @@ -39,7 +47,10 @@ function BuildConfirm({ project, core }: { project: Project; core: ScreenProps[" isPending={false} error={null} action={async function* () { - yield* core.projectManager.build(project); + const globalConfig = await ctx.value(GlobalConfigAccessorKey)?.get(); + yield* core.projectManager.build(project, { + disableDependencyManagement: globalConfig?.disableDependencyManagement, + }); return { rows: {} }; }} successTitle={builtMessage(project)} diff --git a/src/handlers/project/buildDeploy.screen.test.tsx b/src/handlers/project/buildDeploy.screen.test.tsx index e6aa8fb1a8..6be85ec83b 100644 --- a/src/handlers/project/buildDeploy.screen.test.tsx +++ b/src/handlers/project/buildDeploy.screen.test.tsx @@ -4,7 +4,8 @@ import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { writeMigrationState } from "../../core/project/migrate/journal"; import type { DeployBackendInput, ProjectBackend } from "../../core/project"; -import { CommandRunMetricEventKey } from "../../router"; +import { DEFAULT_GLOBAL_CONFIG } from "../../globalConfig"; +import { CommandRunMetricEventKey, GlobalConfigAccessorKey, type Context } from "../../router"; import { assertMetricEmitted, cleanupScreens, @@ -15,11 +16,12 @@ import { inTempDirectory, renderScreen, TestCoreClient, + TestGlobalConfigAccessor, waitFor, waitForFlatText, waitForText, } from "../../testing"; -import type { DeployResult, Project, ProjectEvent } from "./types"; +import type { BuildProjectInput, DeployResult, Project, ProjectEvent } from "./types"; import { ProjectKey } from "../../router"; import { TuiHandoffKey } from "../../tui/handoff"; @@ -42,8 +44,10 @@ type FakeBackendOptions = { function fakeBackend(options: FakeBackendOptions = {}) { const deploys: { project: Project; input: DeployBackendInput; confirmed?: boolean }[] = []; + const builds: (BuildProjectInput | undefined)[] = []; const backend: ProjectBackend = { - async *build() { + async *build(_project, input) { + builds.push(input); yield* options.events ?? EVENTS; if (options.failure) throw options.failure; }, @@ -68,7 +72,17 @@ function fakeBackend(options: FakeBackendOptions = {}) { return []; }, }; - return { backend, deploys }; + return { backend, deploys, builds }; +} + +/** The global config accessor the TUI's command context carries, with dependency management off. */ +function optedOut(ctx: Context): Context { + return ctx.withValue( + GlobalConfigAccessorKey, + new TestGlobalConfigAccessor({ + initialConfigData: { ...DEFAULT_GLOBAL_CONFIG, disableDependencyManagement: true }, + }), + ); } const cleanups: Array<() => Promise> = []; @@ -162,6 +176,20 @@ describe("project build screen", () => { r.unmount(); }); + test("passes the global config's disableDependencyManagement flag into the build", async () => { + const { backend, builds } = fakeBackend(); + const core = new TestCoreClient({ backends: { CDK: backend } }); + await inProject(core); + const r = renderScreen("/agentcore/build", { + core, + withContext: optedOut, + }); + + await waitForText(r.lastFrame, "✔ built project 'orders'"); + expect(builds).toEqual([{ disableDependencyManagement: true }]); + r.unmount(); + }); + test("a failing step is marked ✕ with its output kept, above the error", async () => { const { backend } = fakeBackend({ failure: new Error("synth exploded") }); const core = new TestCoreClient({ backends: { CDK: backend } }); @@ -285,6 +313,20 @@ describe("project deploy screen", () => { r.unmount(); }); + test("passes the global config's disableDependencyManagement flag into the deploy", async () => { + const { backend, deploys } = fakeBackend(); + const core = new TestCoreClient({ backends: { CDK: backend } }); + await inProject(core); + const r = renderScreen("/agentcore/deploy", { + core, + withContext: optedOut, + }); + + await waitForText(r.lastFrame, "✔ deployed project 'orders' to target 'default'"); + expect(deploys[0]!.input.disableDependencyManagement).toBe(true); + r.unmount(); + }); + test("a target-loading failure offers esc back and r to retry", async () => { const { backend } = fakeBackend(); const core = new TestCoreClient({ backends: { CDK: backend } }); diff --git a/src/handlers/project/deploy/index.test.ts b/src/handlers/project/deploy/index.test.ts index 3802460b03..99827861fb 100644 --- a/src/handlers/project/deploy/index.test.ts +++ b/src/handlers/project/deploy/index.test.ts @@ -9,6 +9,7 @@ import { } from "../../../errors/errors"; import { createRootHandler } from "../../index"; import { DEFAULT_GLOBAL_CONFIG } from "../../../globalConfig"; +import { applyOverrides } from "../../../globalConfig/config"; import { ValueContext } from "../../../router"; import { assertMetricEmitted, @@ -98,6 +99,8 @@ type TestDeployOptions = { resolveAccount?: (region: string) => Promise; /** Seeds the global config's transactionSearch flag (defaults to on). */ transactionSearch?: boolean; + /** Seeds the global config's disableDependencyManagement flag (defaults to off). */ + disableDependencyManagement?: boolean; runV0Deploy?: V0DeployRunner; }; @@ -113,16 +116,12 @@ async function testDeployCommand( resolveAccount: options.resolveAccount, }); const logger = createSilentLogger(); - const globalConfigAccessor = new TestGlobalConfigAccessor( - options.transactionSearch === undefined - ? undefined - : { - initialConfigData: { - ...DEFAULT_GLOBAL_CONFIG, - transactionSearch: options.transactionSearch, - }, - }, - ); + const globalConfigAccessor = new TestGlobalConfigAccessor({ + initialConfigData: applyOverrides(DEFAULT_GLOBAL_CONFIG, { + transactionSearch: options.transactionSearch, + disableDependencyManagement: options.disableDependencyManagement, + }), + }); const { client, filePath, cleanup } = await getTestTelemetryClient(); cleanups.push(cleanup); const root = createRootHandler(core, { @@ -531,6 +530,20 @@ describe("project deploy handler", () => { expect(disabled.calls[0]?.input.transactionSearch).toBe(false); }); + test("passes the global config's disableDependencyManagement flag into the deploy", async () => { + const managed = await testDeployCommand({ outputs: {} }); + await inProjectWithTargets(); + await managed.run(); + expect(managed.calls[0]?.input.disableDependencyManagement).toBe(false); + + const optedOut = await testDeployCommand({ outputs: {} }, [], { + disableDependencyManagement: true, + }); + await inProjectWithTargets(); + await optedOut.run(); + expect(optedOut.calls[0]?.input.disableDependencyManagement).toBe(true); + }); + test("passes --skip-bootstrap into the deploy", async () => { const subject = await testDeployCommand({ outputs: {} }); await inProjectWithTargets(); diff --git a/src/handlers/project/deploy/index.ts b/src/handlers/project/deploy/index.ts index a2a26b0629..5a46d87904 100644 --- a/src/handlers/project/deploy/index.ts +++ b/src/handlers/project/deploy/index.ts @@ -1,6 +1,7 @@ import { createInterface } from "node:readline/promises"; import z from "zod"; import { enclosingProjectRoot, isV0Project } from "../../../core/project/fsUtils"; +import { declaresNothingDeployable } from "../../../core/project/spec"; import { runV0Deploy, type V0DeployRunner } from "../../../core/project/legacy/deploy"; import { assertNoPendingMigration } from "../../../core/project/migrate/journal"; import { @@ -136,6 +137,7 @@ export const createDeployProjectHandler = (config: DeployProjectHandlerConfig) = region: ctx.require(RegionKey), confirmTeardown, transactionSearch: globalConfig.transactionSearch, + disableDependencyManagement: globalConfig.disableDependencyManagement, skipBootstrap: flags["skip-bootstrap"], onWorkloadBuilds: (builds) => recordBuildTypeCounts(ctx, builds), }); @@ -294,33 +296,6 @@ async function delegateV0Deploy( if (exitCode !== 0) throw new LegacyDeployError(exitCode); } -/** - * True when the spec declares none of the resources `removeAllResources` - * clears, i.e. what an emptied project looks like. This is the up-front proxy - * for the backend's post-synth zero-resource count; the two can disagree when a - * declared resource synthesizes no CloudFormation resource (or a hand-edited - * CDK app adds one), so the backend's count stays authoritative and this only - * decides whether to ask the user before starting. - */ -export function declaresNothingDeployable(project: Project): boolean { - const { spec } = project; - const collections = [ - spec.runtimes, - spec.memories, - spec.knowledgeBases, - spec.credentials, - spec.evaluators, - spec.onlineEvalConfigs, - spec.agentCoreGateways, - spec.policyEngines, - spec.configBundles, - spec.harnesses, - spec.toolRuntimes ?? [], - spec.payments ?? [], - ]; - return collections.every((collection) => collection.length === 0); -} - /** * Resolves the teardown question before the deploy generator starts. The * returned handler never blocks on input: it is a pre-answered decision the diff --git a/src/handlers/project/deploy/screen.tsx b/src/handlers/project/deploy/screen.tsx index 6398db3e13..af25cd5bb6 100644 --- a/src/handlers/project/deploy/screen.tsx +++ b/src/handlers/project/deploy/screen.tsx @@ -10,8 +10,8 @@ import { RegionKey } from "../../keys"; import type { ScreenProps } from "../../types"; import { ProjectGate } from "../ProjectGate"; import type { Project } from "../types"; +import { declaresNothingDeployable } from "../../../core/project/spec"; import { - declaresNothingDeployable, DEPLOY_NEXT_STEP, deployedMessage, recordBuildTypeCounts, @@ -119,6 +119,7 @@ function DeployConfirm({ confirmTeardown: async () => teardown, transactionSearch: globalConfig?.transactionSearch, onWorkloadBuilds: (builds) => recordBuildTypeCounts(ctx, builds), + disableDependencyManagement: globalConfig?.disableDependencyManagement, }); // The title follows the result, not the preflight heuristic, which // synthesis can disagree with. Outputs are not listed: the command diff --git a/src/handlers/project/project.test.ts b/src/handlers/project/project.test.ts index 0ace4da996..5e27a67cf5 100644 --- a/src/handlers/project/project.test.ts +++ b/src/handlers/project/project.test.ts @@ -1,6 +1,6 @@ import { afterEach, test, expect, describe } from "bun:test"; import { existsSync } from "node:fs"; -import { mkdir, readdir, readFile, rm } from "node:fs/promises"; +import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createRootHandler } from "../index"; import { @@ -1090,8 +1090,15 @@ describe("project build", () => { async function inBuildableProject(): Promise { const { projectRoot, cleanup } = await initProject({ name: "MyAgent" }); cleanups.push(cleanup); - // create --skip-install leaves no node_modules, which build requires. - await mkdir(join(projectRoot, "agentcore", "cdk", "node_modules"), { recursive: true }); + // create --skip-install installs nothing, and build installs a missing library. + const cdkDirectory = join(projectRoot, "agentcore", "cdk"); + const library = join(cdkDirectory, "node_modules", "@aws", "agentcore-cdk"); + const { dependencies } = JSON.parse(await readFile(join(cdkDirectory, "package.json"), "utf8")); + await mkdir(library, { recursive: true }); + await writeFile( + join(library, "package.json"), + JSON.stringify({ version: dependencies["@aws/agentcore-cdk"] }), + ); return projectRoot; } @@ -1135,11 +1142,16 @@ describe("project build", () => { await expect(run(["build"])).rejects.toThrow(/No AgentCore project found/); }); - test("fails when the CDK dependencies have not been installed", async () => { + test("installs the CDK dependencies when they have not been installed", async () => { const projectRoot = await inBuildableProject(); await rm(join(projectRoot, "agentcore", "cdk", "node_modules"), { recursive: true }); - await expect(run(["build"])).rejects.toThrow(/npm install/); + const { core } = await run(["build"]); + + expect(core.projectCommands[0]).toEqual({ + command: ["npm", "install", "--no-audit", "--no-fund"], + cwd: join(projectRoot, "agentcore", "cdk"), + }); }); }); diff --git a/src/handlers/project/types.ts b/src/handlers/project/types.ts index a51217dc39..c43d77ea9e 100644 --- a/src/handlers/project/types.ts +++ b/src/handlers/project/types.ts @@ -212,7 +212,12 @@ export type TeardownConfirmationHandler = ( request: TeardownConfirmationRequest, ) => Promise; -export type DeployProjectInput = { +export type BuildProjectInput = { + /** Leaves agentcore/cdk/package.json alone instead of syncing it to the CLI's pins (global config). */ + disableDependencyManagement?: boolean; +}; + +export type DeployProjectInput = BuildProjectInput & { /** Name of the aws-targets.json entry to deploy. */ target: string; /** @@ -579,7 +584,7 @@ export interface ProjectManager { create(input: CreateProjectInput): AsyncGenerator; /** Compile the project's CDK app and synthesize its CloudFormation templates. */ - build(project: Project): AsyncGenerator; + build(project: Project, input?: BuildProjectInput): AsyncGenerator; /** * Re-derives runtime build settings (build, dockerfile, runtimeVersion, From c2c7af18cd0d20ae7f8cc98c37a16c782b4e71a1 Mon Sep 17 00:00:00 2001 From: "agentcore-devx-automation[bot]" <282717993+agentcore-devx-automation[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:09:36 -0500 Subject: [PATCH 4/8] chore(release): v1.2.0 (#2881) Co-authored-by: github-actions[bot] --- command.md | 78 +++++++++++++++++++++++++++++++++++-- package.json | 2 +- src/assets/cdk/package.json | 2 +- 3 files changed, 76 insertions(+), 6 deletions(-) diff --git a/command.md b/command.md index 2455cc024d..2f776407ba 100644 --- a/command.md +++ b/command.md @@ -2,7 +2,7 @@ # AgentCore CLI command reference -This reference was generated from `agentcore --help` for version `1.1.0`. +This reference was generated from `agentcore --help` for version `1.2.0`. ## Table of contents @@ -160,6 +160,11 @@ This reference was generated from `agentcore --help` for version `1.1.0`. - [`agentcore eval dataset delete`](#agentcore-eval-dataset-delete) - [`agentcore eval dataset update`](#agentcore-eval-dataset-update) - [`agentcore eval dataset publish`](#agentcore-eval-dataset-publish) + - [`agentcore eval dataset-generation`](#agentcore-eval-dataset-generation) + - [`agentcore eval dataset-generation start`](#agentcore-eval-dataset-generation-start) + - [`agentcore eval dataset-generation get`](#agentcore-eval-dataset-generation-get) + - [`agentcore eval dataset-generation list`](#agentcore-eval-dataset-generation-list) + - [`agentcore eval dataset-generation delete`](#agentcore-eval-dataset-generation-delete) - [`agentcore eval batch-evaluation`](#agentcore-eval-batch-evaluation) - [`agentcore eval batch-evaluation evaluate`](#agentcore-eval-batch-evaluation-evaluate) - [`agentcore eval batch-evaluation simulate`](#agentcore-eval-batch-evaluation-simulate) @@ -298,6 +303,7 @@ add a harness to the current project (not available in China regions) - `--execution-role-arn `: IAM role the harness assumes; a default role is created when omitted - `--authorizer-type `: inbound authorizer type (AWS\_IAM or CUSTOM\_JWT) - `--authorizer-configuration `: inbound authorizer configuration (JSON) +- `--build-config `: advanced build settings (JSON object): build (Container or ContainerLocal), dockerfile, buildContextPath, customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the current directory, copied once to app/<name>/Dockerfile (app/<name>/ is the build context). With buildContextPath (relative to the project root), dockerfile is relative to that build context and used in place. Build args are not secret: they appear in logs and image metadata #### `agentcore add runtime` @@ -327,6 +333,7 @@ add a Runtime to the current project - `--agent-id `: Bedrock Agent ID to import; translates that agent version into runtime code instead of writing docs - `--agent-alias-id `: Bedrock Agent Alias ID selecting the version to import; must point at a prepared version, not DRAFT (requires --agent-id) - `--framework `: agent framework for an imported Bedrock Agent: strands or langgraph (requires --agent-id) +- `--build-config `: advanced build settings (JSON object): build (CodeZip, Container, or ContainerLocal), dockerfile, buildContextPath, customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the current directory, copied once to app/<name>/Dockerfile (app/<name>/ is the build context). With buildContextPath (relative to the project root), dockerfile is relative to that build context and used in place. Build args are not secret: they appear in logs and image metadata #### `agentcore add runtime-endpoint` @@ -2319,13 +2326,12 @@ manage AgentCore evaluation datasets agentcore eval dataset create [options] ``` -create a dataset from JSONL examples +create a dataset, optionally seeded from JSONL examples **Options** - `--name `: the name of the dataset (required) -- `--source `: dataset examples: a JSONL file (file://<path>), an S3 JSONL object (s3://<bucket>/<key>), or - for stdin (required) -- `--schema-type `: the structure of the dataset's examples, immutable after creation (predefined | simulated) (required) +- `--source `: dataset examples: a JSONL file (file://<path>), an S3 JSONL object (s3://<bucket>/<key>), or - for stdin; omit to create an empty dataset - `--description `: a description of the dataset - `--kms-key-arn `: customer managed KMS key ARN for dataset data - `--tags `: tags as repeated key=value entries or one JSON object @@ -2395,6 +2401,70 @@ publish the current DRAFT as a new immutable version - `--id `: the ID of the dataset to publish (required) +#### `agentcore eval dataset-generation` + +```text +agentcore eval dataset-generation [options] [command] +``` + +generate dataset examples from agent traces + +##### `agentcore eval dataset-generation start` + +```text +agentcore eval dataset-generation start [options] +``` + +start an asynchronous generation into a dataset's DRAFT + +**Options** + +- `--dataset-id `: the ID of the dataset to write examples into (required) +- `--name `: the name of the generation (required) +- `--description `: a description of the generation +- `--scenario-type `: the kind of example every scenario becomes (fixed | dynamic); service defaults to dynamic when omitted +- `--generation-config `: where traces are read from and which become examples (JSON inline, file://<path>, or - for stdin) (required) + +##### `agentcore eval dataset-generation get` + +```text +agentcore eval dataset-generation get [options] +``` + +get a generation by ID + +**Options** + +- `--dataset-id `: the ID of the dataset (required) +- `--id `: the ID of the generation (required) + +##### `agentcore eval dataset-generation list` + +```text +agentcore eval dataset-generation list [options] +``` + +list a dataset's generations + +**Options** + +- `--dataset-id `: the ID of the dataset (required) +- `--next-token `: pagination token returned by a previous request +- `--max-results `: maximum number of items to return (1-100) + +##### `agentcore eval dataset-generation delete` + +```text +agentcore eval dataset-generation delete [options] +``` + +delete a generation record (its examples stay in the DRAFT) + +**Options** + +- `--dataset-id `: the ID of the dataset (required) +- `--id `: the ID of the generation (required) + #### `agentcore eval batch-evaluation` ```text diff --git a/package.json b/package.json index c29946e48f..14a1f11f90 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@aws/agentcore", - "version": "1.1.0", + "version": "1.2.0", "repository": { "type": "git", "url": "https://github.com/aws/agentcore-cli.git" diff --git a/src/assets/cdk/package.json b/src/assets/cdk/package.json index f3d44c269f..091e71a2e0 100644 --- a/src/assets/cdk/package.json +++ b/src/assets/cdk/package.json @@ -16,7 +16,7 @@ "typescript": "~5.9.3" }, "dependencies": { - "@aws/agentcore-cdk": "1.1.0", + "@aws/agentcore-cdk": "1.2.0", "aws-cdk-lib": "~2.269.0", "constructs": "~10.7.0" } From d7780a117bbab2249dd45c4f513f5e49d4ff0bd2 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 23 Nov 2026 11:56:21 -0500 Subject: [PATCH 5/8] ci: bump open-PR digest workflow pin to list every open PR (#2891) Picks up aws/agentcore-devx-devtools#24, which paginates the open-PR list instead of stopping at GitHub's default first page of 30. Co-authored-by: jariy17 --- .github/workflows/slack-open-prs-notification.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/slack-open-prs-notification.yml b/.github/workflows/slack-open-prs-notification.yml index de85fc36d2..db150364e4 100644 --- a/.github/workflows/slack-open-prs-notification.yml +++ b/.github/workflows/slack-open-prs-notification.yml @@ -12,7 +12,7 @@ permissions: jobs: call: - uses: aws/agentcore-devx-devtools/.github/workflows/reusable-slack-open-prs-notification.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 + uses: aws/agentcore-devx-devtools/.github/workflows/reusable-slack-open-prs-notification.yml@db12e119f4802fc59da3f8e48cc02c43b225d71d with: runner: codebuild secrets: inherit From 5608621bbbc2c16387513eab1dea7d819cacde91 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 23 Nov 2026 19:10:44 -0500 Subject: [PATCH 6/8] ci: run non-E2E jobs on GitHub-hosted runners (#2896) --- .github/workflows/codeql.yml | 2 +- .github/workflows/pr-automation.yml | 10 +++++----- .github/workflows/prerelease.yml | 2 +- .github/workflows/slack-issue-notification.yml | 2 +- .github/workflows/slack-open-prs-notification.yml | 2 +- .github/workflows/verify.yml | 6 ++---- 6 files changed, 11 insertions(+), 13 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 72b5b48d5e..487044fd8e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -13,7 +13,7 @@ concurrency: jobs: analyze: name: Analyze - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest timeout-minutes: 15 permissions: actions: read diff --git a/.github/workflows/pr-automation.yml b/.github/workflows/pr-automation.yml index d87ce8a421..0f24d2e73f 100644 --- a/.github/workflows/pr-automation.yml +++ b/.github/workflows/pr-automation.yml @@ -27,7 +27,7 @@ jobs: statuses: write uses: aws/agentcore-devx-devtools/.github/workflows/reusable-pr-size-title.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 with: - runner: codebuild + runner: ubuntu secrets: inherit security-review: @@ -44,7 +44,7 @@ jobs: contents: read uses: aws/agentcore-devx-devtools/.github/workflows/reusable-pr-security-review.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 with: - runner: codebuild + runner: ubuntu pr_number: ${{ inputs.pr_number || format('{0}', github.event.pull_request.number) }} allowed_base_branches: '["v0.x","v1.x"]' secrets: inherit @@ -63,7 +63,7 @@ jobs: contents: read uses: aws/agentcore-devx-devtools/.github/workflows/reusable-pr-ai-review.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 with: - runner: codebuild + runner: ubuntu model_id: us.anthropic.claude-opus-5 pr_url: >- ${{ github.event_name == 'workflow_dispatch' && @@ -81,7 +81,7 @@ jobs: github.event_name == 'pull_request_target' && contains(fromJSON('["opened","reopened","synchronize"]'), github.event.action) ) - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest permissions: id-token: write contents: read @@ -151,7 +151,7 @@ jobs: pr-tarball: needs: tarball-authorize if: needs.tarball-authorize.outputs.is_authorized == 'true' - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest timeout-minutes: 15 permissions: contents: write diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 545518409a..2a76331204 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -14,7 +14,7 @@ concurrency: jobs: prerelease: - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest timeout-minutes: 30 env: RELEASE_TAG: ${{ github.ref_name == 'v0.x' && 'prerelease' || format('prerelease-{0}', github.ref_name) }} diff --git a/.github/workflows/slack-issue-notification.yml b/.github/workflows/slack-issue-notification.yml index 5daf584981..360dc1979e 100644 --- a/.github/workflows/slack-issue-notification.yml +++ b/.github/workflows/slack-issue-notification.yml @@ -16,5 +16,5 @@ jobs: call: uses: aws/agentcore-devx-devtools/.github/workflows/reusable-slack-issue-notification.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 with: - runner: codebuild + runner: ubuntu secrets: inherit diff --git a/.github/workflows/slack-open-prs-notification.yml b/.github/workflows/slack-open-prs-notification.yml index db150364e4..6a4f7a592f 100644 --- a/.github/workflows/slack-open-prs-notification.yml +++ b/.github/workflows/slack-open-prs-notification.yml @@ -14,5 +14,5 @@ jobs: call: uses: aws/agentcore-devx-devtools/.github/workflows/reusable-slack-open-prs-notification.yml@db12e119f4802fc59da3f8e48cc02c43b225d71d with: - runner: codebuild + runner: ubuntu secrets: inherit diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 3516882bc1..31129e301d 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -29,14 +29,12 @@ jobs: fail-fast: false matrix: include: - # Per-job labels stop GitHub from routing a job to the runner CodeBuild created for another job. - # https://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-action-runners-update-labels.html - name: Linux - runner: '["codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }}", "verify-linux"]' + runner: '"ubuntu-latest"' target: linux-x64 binary: ./dist/bin/agentcore-linux-x64 - name: Windows - runner: '["codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }}", "image:windows-1.0", "verify-windows"]' + runner: '"windows-latest"' target: windows-x64 binary: ./dist/bin/agentcore-windows-x64.exe steps: From 14c0a1c7593d82a31a4d071ea988d2480450ac97 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 23 Nov 2026 19:34:19 -0500 Subject: [PATCH 7/8] ci: run E2E and canaries on GitHub-hosted runners (#2901) The agentcore-e2e CodeBuild runner can't register with GitHub (its credential lacks runner-registration permission since 2026-11-23), so E2E and canary jobs never start. Run them on GitHub-hosted runners until the CodeBuild runner is fixed. Co-authored-by: jariy17 --- .github/workflows/canary-v0.yml | 6 +++--- .github/workflows/canary.yml | 4 ++-- .github/workflows/e2e-test.yml | 8 +++----- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/.github/workflows/canary-v0.yml b/.github/workflows/canary-v0.yml index 9a5bb30817..6745f7921e 100644 --- a/.github/workflows/canary-v0.yml +++ b/.github/workflows/canary-v0.yml @@ -22,7 +22,7 @@ env: jobs: resolve_release: - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest outputs: version: ${{ steps.resolve.outputs.version }} steps: @@ -42,7 +42,7 @@ jobs: canary: needs: resolve_release - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest timeout-minutes: 30 steps: # Use the test harness from the same release as the published CLI. @@ -89,7 +89,7 @@ jobs: heartbeat: needs: [resolve_release, canary] if: ${{ !cancelled() }} - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest steps: # Use the emitter from this branch; the canary job checks out the v0 release. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 1d452fc6ae..aae411cb28 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -15,7 +15,7 @@ permissions: jobs: # Resolve the commit hash for npm's latest published version. resolve_release: - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest outputs: ref: ${{ steps.resolve.outputs.ref }} version: ${{ steps.resolve.outputs.version }} @@ -56,7 +56,7 @@ jobs: needs: [resolve_release, e2e] # A cancelled run emits no failure sample; the alarm may still breach on missing data. if: ${{ !cancelled() }} - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 3eb08e6dae..f9eb985d41 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -49,7 +49,7 @@ env: jobs: authorize: - runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }} + runs-on: ubuntu-latest permissions: id-token: write contents: read @@ -87,10 +87,8 @@ jobs: if: needs.authorize.outputs.is-authorized == 'true' runs-on: >- ${{ fromJSON( - matrix.name == 'Linux' && - format('["codebuild-agentcore-e2e-{0}-{1}","e2e-linux"]', github.run_id, github.run_attempt) - || matrix.name == 'Windows' && - format('["codebuild-agentcore-e2e-{0}-{1}","image:windows-1.0","e2e-windows"]', github.run_id, github.run_attempt) + matrix.name == 'Linux' && '["ubuntu-latest"]' + || matrix.name == 'Windows' && '["windows-latest"]' || matrix.name == 'macOS' && '["macos-latest"]' ) }} permissions: From d5f34f2e4f9f82749200c3c8f0ba8e966f76b9c0 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 23 Nov 2026 19:34:28 -0500 Subject: [PATCH 8/8] test: give the real Toolkit loading test 30s (#2900) Since verify moved to GitHub-hosted runners, the cold import of @aws-cdk/toolkit-lib in this test exceeds bun's 5s default on Windows (5015ms), failing verify / Windows on every PR. Co-authored-by: jariy17 --- src/core/project/backends/cdk/toolkit.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/project/backends/cdk/toolkit.test.ts b/src/core/project/backends/cdk/toolkit.test.ts index c0fc73d639..4a0330b02c 100644 --- a/src/core/project/backends/cdk/toolkit.test.ts +++ b/src/core/project/backends/cdk/toolkit.test.ts @@ -261,6 +261,7 @@ describe("performCdkOperation", () => { }); describe("Toolkit loading", () => { + // The cold import of @aws-cdk/toolkit-lib takes over 5 s on GitHub-hosted Windows runners. test("constructs the real Toolkit without resolving credentials", async () => { const ioHost = createCdkIoHost(createSilentLogger()); const provider = await resolveCdkCredentials(ioHost, "us-west-2"); @@ -269,7 +270,7 @@ describe("Toolkit loading", () => { expect(typeof provider).toBe("function"); expect(typeof loaded.toolkit.bootstrap).toBe("function"); expect(typeof loaded.toolkit.deploy).toBe("function"); - }); + }, 30_000); test("loads the Toolkit with the target region and deployment credentials", async () => { const { loaded } = loadedToolkit();