diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index ea65fd5ad..0069cc810 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -49,6 +49,8 @@ import { type DeployedCredentials, } from "./cdk/credentials"; import { + assertPlatformVersions, + runtimePlatformVersions, assertPrivateVpcs, countDeployableResources, stackArtifactForTarget, @@ -365,6 +367,12 @@ export class CdkBackend implements ProjectBackend { .filter((runtime) => runtime.containment === "PRIVATE_VPC") .map((runtime) => runtime.name), ); + await assertPlatformVersions( + this.json, + assemblyDirectory, + artifact, + runtimePlatformVersions(project.spec.runtimes), + ); // Only after a real deploy is confirmed: a teardown (empty assembly) returns // above, so a destroy is never blocked by Transaction Search. Never fail the diff --git a/src/core/project/backends/cdk/assembly.test.ts b/src/core/project/backends/cdk/assembly.test.ts index 6b02aa8ce..e55e0df80 100644 --- a/src/core/project/backends/cdk/assembly.test.ts +++ b/src/core/project/backends/cdk/assembly.test.ts @@ -4,7 +4,13 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import { FsReadWriteJson } from "../../../../io"; import { createSilentLogger } from "../../../../testing"; -import { assertPrivateVpcs, countDeployableResources, stackArtifactForTarget } from "./assembly"; +import { + assertPlatformVersions, + assertPrivateVpcs, + countDeployableResources, + runtimePlatformVersions, + stackArtifactForTarget, +} from "./assembly"; const temporaryDirectories: string[] = []; const json = new FsReadWriteJson({ logger: createSilentLogger() }); @@ -137,6 +143,103 @@ describe("assertPrivateVpcs", () => { }); }); +describe("runtimePlatformVersions", () => { + // Not only a Box project's runtimes: any runtime that names a version is checked, V1 too. + test("takes each runtime that names a platformVersion, V1 or V2, and skips one with none", () => { + expect( + runtimePlatformVersions([ + { name: "box_agent", platformVersion: "V2" }, + { name: "plain_v2", platformVersion: "V2" }, + { name: "plain_v1", platformVersion: "V1" }, + { name: "unset" }, + ]), + ).toEqual([ + { name: "box_agent", platformVersion: "V2" }, + { name: "plain_v2", platformVersion: "V2" }, + { name: "plain_v1", platformVersion: "V1" }, + ]); + }); +}); + +describe("assertPlatformVersions", () => { + const artifact = { id: "Stack", stackName: "AgentCore-App-default", templateFile: TEMPLATE_FILE }; + /** A runtime resource, and the RuntimeId export the CDK library writes for runtime `name`. */ + const runtime = (name: string, logicalId: string, properties: Record) => ({ + Resources: { [logicalId]: { Type: "AWS::BedrockAgentCore::Runtime", Properties: properties } }, + Outputs: { + [`${logicalId}Id`]: { + Value: { "Fn::GetAtt": [logicalId, "AgentRuntimeId"] }, + Export: { Name: `AgentCore-App-default-${name.replaceAll("_", "-")}-RuntimeId` }, + }, + }, + }); + /** One template with each runtime of `templates`. */ + const merged = (...templates: ReturnType[]) => ({ + Resources: Object.assign({}, ...templates.map(({ Resources }) => Resources)), + Outputs: Object.assign({}, ...templates.map(({ Outputs }) => Outputs)), + }); + async function check( + template: Record, + runtimes: { name: string; platformVersion: string }[], + ) { + const directory = await assembly({ Stack: stackArtifact("prod") }); + await writeFile(join(directory, TEMPLATE_FILE), JSON.stringify(template)); + return assertPlatformVersions(json, directory, artifact, runtimes); + } + const notSet = (name: string, version: string) => + `Runtime '${name}' has "platformVersion": "${version}", but the synthesized stack does not set it.`; + + test.each(["V1", "V2"])("accepts a runtime that runs on its own %s", async (version) => { + await expect( + check(runtime("my_agent", "RuntimeMyAgent", { PlatformVersion: version }), [ + { name: "my_agent", platformVersion: version }, + ]), + ).resolves.toBeUndefined(); + }); + + test("accepts a stack with no runtime to check", async () => { + await expect(check({ Resources: {} }, [])).resolves.toBeUndefined(); + }); + + test.each([ + ["no PlatformVersion, as a CDK library from before platformVersion synthesizes", {}, "V2"], + ["another PlatformVersion", { PlatformVersion: "V1" }, "V2"], + ["no PlatformVersion for an explicit V1", {}, "V1"], + ])("refuses %s", async (_name, properties, version) => { + await expect( + check(runtime("agent", "RuntimeAgent", properties), [ + { name: "agent", platformVersion: version }, + ]), + ).rejects.toThrow(notSet("agent", version)); + }); + + test("names only the runtime that does not run on its version", async () => { + const template = merged( + runtime("good", "RuntimeGood", { PlatformVersion: "V2" }), + runtime("bad", "RuntimeBad", {}), + ); + + const refused = check(template, [ + { name: "good", platformVersion: "V2" }, + { name: "bad", platformVersion: "V2" }, + ]); + + await expect(refused).rejects.toThrow(notSet("bad", "V2")); + await expect(refused).rejects.not.toThrow("'good'"); + }); + + test("refuses a runtime the stack exports no RuntimeId for, and says it is not found", async () => { + await expect( + check(runtime("other", "RuntimeOther", { PlatformVersion: "V2" }), [ + { name: "agent", platformVersion: "V2" }, + ]), + ).rejects.toThrow( + "Could not find runtime 'agent' in the synthesized stack 'AgentCore-App-default', so " + + 'deploy cannot check that it runs on "platformVersion": "V2".', + ); + }); +}); + describe("countDeployableResources", () => { const artifact = { id: "Stack", stackName: "Stack", templateFile: TEMPLATE_FILE }; diff --git a/src/core/project/backends/cdk/assembly.ts b/src/core/project/backends/cdk/assembly.ts index e337fa1d4..a6ffc3bc3 100644 --- a/src/core/project/backends/cdk/assembly.ts +++ b/src/core/project/backends/cdk/assembly.ts @@ -31,6 +31,13 @@ const AssemblyManifestSchema = z.object({ .default({}), }); +/** A stack output that exports `Fn::GetAtt` of a resource, as each runtime's `RuntimeId` does. */ +const GetAttOutputSchema = z.object({ + Value: z.object({ "Fn::GetAtt": z.tuple([z.string(), z.string()]) }), + Export: z.object({ Name: z.string() }), +}); +const PlatformVersionPropertiesSchema = z.object({ PlatformVersion: z.string() }); + const StackTemplateSchema = z .object({ Resources: z @@ -42,6 +49,7 @@ const StackTemplateSchema = z z.object({ Type: z.string().optional() }).passthrough(), ) .default({}), + Outputs: z.record(z.string(), z.unknown()).default({}), }) .passthrough(); @@ -164,6 +172,64 @@ export async function assertPrivateVpcs( } } +/** + * The runtimes whose platform deploy checks after synth: each one that names a `platformVersion`, + * in a Box project or not, `"V1"` included, since a CDK library from before the field drops it. + */ +export function runtimePlatformVersions( + runtimes: readonly { readonly name: string; readonly platformVersion?: string }[], +): { name: string; platformVersion: string }[] { + return runtimes.flatMap(({ name, platformVersion }) => + platformVersion === undefined ? [] : [{ name, platformVersion }], + ); +} + +/** + * Refuses a stack in which a runtime of `runtimes` does not run on its own `platformVersion`. A + * CDK library from before `platformVersion` drops the field without an error, and the service + * would pick the platform. The CDK library exports each runtime's ID as + * `--RuntimeId` (`_` as `-`), from `Fn::GetAtt` of its + * `AWS::BedrockAgentCore::Runtime`; a runtime with no such export is refused too, as one whose + * platform deploy cannot check. + */ +export async function assertPlatformVersions( + json: ReadWriteJson, + assemblyDirectory: string, + artifact: StackArtifact, + runtimes: readonly { readonly name: string; readonly platformVersion: string }[], +): Promise { + if (runtimes.length === 0) return; + const template = await readStackTemplate(json, assemblyDirectory, artifact); + const logicalIdByExport = new Map( + Object.values(template.Outputs).flatMap((output) => { + const parsed = GetAttOutputSchema.safeParse(output).data; + return parsed ? [[parsed.Export.Name, parsed.Value["Fn::GetAtt"][0]] as const] : []; + }), + ); + // The CDK library's exportName: each part with `_` as `-` and every other character but + // letters, digits, `:` and `-` removed, joined with `-`. + const exportName = (...parts: string[]) => + parts.map((part) => part.replace(/_/g, "-").replace(/[^a-zA-Z0-9:-]/g, "")).join("-"); + const problems = runtimes.flatMap(({ name, platformVersion }) => { + const logicalId = logicalIdByExport.get(exportName(artifact.stackName, name, "RuntimeId")); + const resource = logicalId === undefined ? undefined : template.Resources[logicalId]; + if (resource === undefined) { + return [ + `Could not find runtime '${name}' in the synthesized stack '${artifact.stackName}', so ` + + `deploy cannot check that it runs on "platformVersion": "${platformVersion}".`, + ]; + } + const synthesized = PlatformVersionPropertiesSchema.safeParse(resource.Properties).data; + if (synthesized?.PlatformVersion === platformVersion) return []; + return [ + `Runtime '${name}' has "platformVersion": "${platformVersion}", but the synthesized stack ` + + "does not set it. The @aws/agentcore-cdk in agentcore/cdk is older than platformVersion: " + + "update it to a release that has platformVersion, then deploy again.", + ]; + }); + if (problems.length > 0) throw new ProjectStateError(problems.join("\n")); +} + async function readStackTemplate( json: ReadWriteJson, assemblyDirectory: string, diff --git a/src/core/project/boxValidation.ts b/src/core/project/boxValidation.ts index 633951403..bfdc5560f 100644 --- a/src/core/project/boxValidation.ts +++ b/src/core/project/boxValidation.ts @@ -5,7 +5,7 @@ */ import { ProjectStateError } from "../../errors/errors"; import { isBoxProject, type ProjectSpec } from "../../projectSchemas/project"; -import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { BOX_PLATFORM_VERSION, type ProjectRuntime } from "../../projectSchemas/runtime"; import { BOX_RELEASE } from "./backends/boxRelease"; import { BOX_CODEZIP_ENTRYPOINT, runsInBox } from "./templates/boxProfile"; @@ -100,3 +100,25 @@ export function validateBoxRuntimes(spec: ProjectSpec): void { assertBoxRuntimesHaveBoxVersion(spec); assertBoxCodeZipRuntimesStartBox(spec); } + +/** + * Throws for a runtime of a Box project whose `platformVersion` is not `"V2"`. Box runs only on + * AgentCore Runtime V2, and without the field the service picks the platform, which can be V1. + * `agentcore create` and `add runtime` write it. Build and deploy call this before the runtime + * sync rewrites agentcore.json. + */ +export function assertBoxRuntimesOnRuntimeV2(spec: ProjectSpec): void { + if (!isBoxProject(spec)) return; + for (const runtime of spec.runtimes) { + if (runtime.platformVersion === BOX_PLATFORM_VERSION) continue; + const actual = + runtime.platformVersion === undefined + ? "has no platformVersion" + : `has "platformVersion": "${runtime.platformVersion}"`; + throw new ProjectStateError( + `runtime "${runtime.name}" ${actual} in agentcore.json, but every runtime of a Box project ` + + `runs on AgentCore Runtime ${BOX_PLATFORM_VERSION}. Set "platformVersion": ` + + `"${BOX_PLATFORM_VERSION}" on the runtime in agentcore.json, then retry.`, + ); + } +} diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 9fe6b1320..6018e85c8 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -233,6 +233,9 @@ describe("agentcore create", () => { expect((spec.agentCoreGateways ?? []).map(({ name }) => name)).toEqual( projectType ? ["agent-box-egress"] : [], ); + // Box runs only on AgentCore Runtime V2, so only a box runtime pins it. + const [runtime] = spec.runtimes as { platformVersion?: string }[]; + expect(runtime?.platformVersion).toBe(projectType ? "V2" : undefined); expect(warnings.includes(boxGatewayLogsNotice("agent-box-egress"))).toBe(projectType === "box"); }); @@ -388,6 +391,7 @@ describe("gateway targets in a Box project", () => { const spec = await parsedSpec(project); const search = spec.runtimes.find(({ name }) => name === "search")!; expect(search.box).toEqual({ version: BOX_RELEASE.version }); + expect(search.platformVersion).toBe("V2"); expect(search.entrypoint).toBe("start.py"); expect(spec.agentCoreGateways.find(({ boundRuntime }) => boundRuntime === "search")).toEqual( expect.objectContaining(boxGatewaySpec("search")), diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 99f66dc18..51851245b 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -1522,6 +1522,7 @@ describe("FsProjectManager.addResource", () => { bedrockManagedAgents?: boolean; tags?: Record; additionalPolicies?: string[]; + platformVersion?: string; }[]; harnesses: unknown[]; memories?: unknown[]; @@ -1567,6 +1568,45 @@ describe("FsProjectManager.addResource", () => { expect(deployCalls).toEqual([]); }); + test.each([ + ["no platformVersion", undefined, "has no platformVersion"], + ["V1", "V1", 'has "platformVersion": "V1"'], + ])( + "deploy of a Box project whose runtime has %s fails before anything is written", + async (_name, platformVersion, detail) => { + await inTempDirectory(); + const { subject, project, deployCalls } = await projectWithTarget( + "us-west-2", + undefined, + AGENT_PYTHON_STRANDS_BOX, + ); + await editSpec(project, (spec) => { + if (platformVersion === undefined) delete spec.runtimes[0]!.platformVersion; + else spec.runtimes[0]!.platformVersion = platformVersion; + }); + const specPath = join(project.rootPath, "agentcore", "agentcore.json"); + const before = await readFile(specPath, "utf8"); + + const { error } = await deployOutcome(subject, project); + expect(error).toBeInstanceOf(ProjectStateError); + expect(String(error)).toContain( + `runtime "agent_python_strands_box" ${detail} in agentcore.json, but every runtime of a ` + + 'Box project runs on AgentCore Runtime V2. Set "platformVersion": "V2"', + ); + expect(await readFile(specPath, "utf8")).toBe(before); + expect(deployCalls).toEqual([]); + }, + ); + + test("deploy of a project that is not a Box project needs no platformVersion", async () => { + await inTempDirectory(); + const { subject, project, deployCalls } = await projectWithTarget("us-west-2"); + + const { error } = await deployOutcome(subject, project); + expect(error).toBeUndefined(); + expect(deployCalls).toHaveLength(1); + }); + test("deploy to a China target hard-fails a Bedrock Managed Agents runtime", async () => { await inTempDirectory(); const { subject, project, deployCalls } = await projectWithTarget( @@ -2144,6 +2184,33 @@ describe("FsProjectManager.build", () => { expect(existsSync(join(aws, "resources", "shared"))).toBe(false); }); + // An existing Box project has no platformVersion, the common case; a V1 one is a hand edit. + test.each([ + ["no platformVersion", undefined, "has no platformVersion"], + ['"platformVersion": "V1"', "V1", 'has "platformVersion": "V1"'], + ])( + "refuses a Box runtime with %s, before anything is written", + async (_label, platformVersion, actual) => { + const directory = await inTempDirectory(); + const { manager: subject, commands } = manager(await boxHome()); + const project = await scaffolded(subject, directory); + const specPath = join(project.rootPath, "agentcore", "agentcore.json"); + const spec = JSON.parse(await readFile(specPath, "utf8")); + spec.runtimes[0].platformVersion = platformVersion; + await writeFile(specPath, JSON.stringify(spec, null, 2)); + const before = await readFile(specPath, "utf8"); + const edited = (await subject.resolve({ filePath: project.rootPath }))!; + commands.length = 0; + + await expect(drain(subject.build(edited))).rejects.toThrow( + `${actual} in agentcore.json, but every runtime of a Box project runs on ` + + "AgentCore Runtime V2.", + ); + expect(await readFile(specPath, "utf8")).toBe(before); + expect(commands).toEqual([]); + }, + ); + test("downloads box from the public box release when it is not cached", async () => { const directory = await inTempDirectory(); const home = await mkdtemp(join(tmpdir(), "agentcore-box-home-")); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index d7c3b9bbe..3b754d26d 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -74,7 +74,7 @@ import { startsInBoxOnCodeZip, } from "./templates/boxProfile"; import { defaultLogTargetNotice, observabilityOff } from "./runtimeProfile/rules/additions"; -import { validateBoxRuntimes } from "./boxValidation"; +import { assertBoxRuntimesOnRuntimeV2, validateBoxRuntimes } from "./boxValidation"; import { BOX_INSTALL_HINT, BOX_RELEASE } from "./backends/boxRelease"; import { getRuntimeTemplateResolver } from "./templates/runtime"; import { @@ -104,7 +104,7 @@ import { EvaluatorSchema } from "../../projectSchemas/evaluator"; import { OnlineEvalConfigSchema } from "../../projectSchemas/online-eval-config"; import { PaymentConnectorSchema, PaymentManagerSchema } from "../../projectSchemas/payment"; import { PolicyEngineSchema, PolicySchema } from "../../projectSchemas/policy"; -import { RuntimeEndpointSchema } from "../../projectSchemas/runtime"; +import { BOX_PLATFORM_VERSION, RuntimeEndpointSchema } from "../../projectSchemas/runtime"; import { defaultExportProjectName, enclosingProjectRoot, projectSpecPath } from "./fsUtils"; import { parseArn } from "../arn"; import { @@ -1631,6 +1631,8 @@ export class FsProjectManager implements ProjectManager { // 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); + // Box runs only on AgentCore Runtime V2, so stop before the sync rewrites agentcore.json. + assertBoxRuntimesOnRuntimeV2(project.spec); const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); for (const message of synced.messages) yield { type: "step", message }; // Every runtime of a Box project runs in a box, so stop before anything is written. @@ -1828,6 +1830,9 @@ export class FsProjectManager implements ProjectManager { ); } + // Box runs only on AgentCore Runtime V2, so stop before the sync rewrites agentcore.json. + assertBoxRuntimesOnRuntimeV2(project.spec); + // Synth reads agentcore.json, so it is brought up to date with the code // first; only once the target is known, so a bad --target rewrites nothing. const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); @@ -2137,6 +2142,8 @@ export class FsProjectManager implements ProjectManager { const runtime = projectSpec.runtimes.find((candidate) => candidate.name === name)!; // The box release build and deploy ship, as create pins it. runtime.box = { version: BOX_RELEASE.version }; + // Box runs only on AgentCore Runtime V2, as create pins it. + runtime.platformVersion = BOX_PLATFORM_VERSION; // start.py starts `box run` on AgentCore Runtime, and the profile runs the agent. runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; projectSpec.agentCoreGateways.push(AgentCoreGatewaySchema.parse(boxGatewaySpec(name))); diff --git a/src/core/project/templates/project.ts b/src/core/project/templates/project.ts index 289a98e30..acf7bad04 100644 --- a/src/core/project/templates/project.ts +++ b/src/core/project/templates/project.ts @@ -16,6 +16,7 @@ import { } from "./boxProfile"; import { mergeSpecEntries } from "./spec"; import { boxGatewaySpec } from "../../../projectSchemas/project"; +import { BOX_PLATFORM_VERSION } from "../../../projectSchemas/runtime"; import type { SpecEntries, Template, TemplateRenderer } from "./types"; import type { EnvLocalEntry } from "../../../handlers/project/types"; @@ -50,6 +51,11 @@ export async function createProjectTree( runtime.network = { mode: "CONTAINED" }; } } + // Box runs only on AgentCore Runtime V2, so a box runtime pins it. + if (hasBoxProfile(options.runtime)) { + for (const runtime of template.spec.runtimes ?? []) + runtime.platformVersion = BOX_PLATFORM_VERSION; + } // Only a box template (a `-box` template in the shortcut table) runs its agent in a box, so // only it makes a Box project. templates.push( diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index 967991cb1..2d9821cce 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -169,3 +169,16 @@ describe("runtime custom validation", () => { expect(ProjectRuntimeSchema.safeParse(containerAgent).success).toBe(true); }); }); + +describe("platformVersion", () => { + it.each([["V1"], ["V2"], [undefined]])("accepts %p", (platformVersion) => { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe(true); + }); + + // The casing users most likely get wrong, and a version the service does not have. + it.each([["v2"], ["V3"], [""]])("refuses %p", (platformVersion) => { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( + false, + ); + }); +}); diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index 3d1f52081..67ada4348 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -298,6 +298,16 @@ export const ContainmentSchema = z.enum(["SANDBOXED", "PRIVATE_VPC"]); export type Containment = z.infer; export const PRIVATE_VPC_LIMIT = 'A project can have only one runtime with "containment": "PRIVATE_VPC". Create a new project for each contained runtime.'; + +/** + * The AgentCore Runtime platform a runtime runs on, set as `PlatformVersion` on its + * `AWS::BedrockAgentCore::Runtime`. No field leaves the choice to the service. + */ +export const PlatformVersionSchema = z.enum(["V1", "V2"]); +export type PlatformVersion = z.infer; +/** The platform a runtime of a Box project needs: Box runs only on AgentCore Runtime V2. */ +export const BOX_PLATFORM_VERSION: PlatformVersion = "V2"; + function isVpcCidr(value: string): boolean { const [address = "", prefix = "", ...rest] = value.split("/"); const octets = address.split("."); @@ -398,6 +408,8 @@ export const ProjectRuntimeSchema = z containment: ContainmentSchema.optional(), /** Only with `"containment": "PRIVATE_VPC"`. */ network: ContainedNetworkSchema.optional(), + /** No default. Every runtime of a Box project needs `"V2"`; create writes it. */ + platformVersion: PlatformVersionSchema.optional(), }) .superRefine((data, ctx) => { if (data.network && data.containment !== "PRIVATE_VPC") {