diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 9a28b88ca..f0689beb7 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -395,7 +395,10 @@ describe("CdkBackend.build", () => { ...(build === "CodeZip" && { runtimeVersion: "PYTHON_3_14" }), entrypoint: "main.py", codeLocation: "app/agent", - ...(projectType && { box: { version: BOX_RELEASE.version } }), + ...(projectType && { + box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, + }), ...(!otel && { instrumentation: { enableOtel: false } }), }, ], @@ -423,6 +426,7 @@ describe("CdkBackend.build", () => { codeLocation: "app/agent", envVars: [{ name: "DISABLE_ADOT_OBSERVABILITY", value: "true" }], box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, }, ], agentCoreGateways: [boxGatewaySpec("agent")], @@ -443,6 +447,7 @@ describe("CdkBackend.build", () => { entrypoint: "main.py", codeLocation: "app/agent", box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, }, ], agentCoreGateways: [boxGatewaySpec("agent")], @@ -464,6 +469,7 @@ describe("CdkBackend.build", () => { entrypoint: "main.py", codeLocation: "app/agent", box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, }, ], agentCoreGateways: [boxGatewaySpec("agent")], @@ -616,6 +622,29 @@ describe("CdkBackend.deploy", () => { expect(subject.templateLoads()).toBe(0); }); + // An old @aws/agentcore-cdk drops platformVersion without an error, so deploy checks the + // synthesized template before it runs anything. + test("refuses a runtime whose platformVersion the synthesized stack does not set, before deploying", async () => { + const input = await project(); + input.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "CodeZip", + codeLocation: "app/agent", + entrypoint: "start.py", + runtimeVersion: "PYTHON_3_14", + platformVersion: "V2", + }), + ); + await writeAssembly(input, [TARGET.name]); + const subject = harness({ outputs: { RuntimeArn: "arn:runtime" } }); + + await expect(collectDeploy(subject.backend.deploy(input, deployInput()))).rejects.toThrow( + "Could not find runtime 'agent' in the synthesized stack", + ); + expect(subject.runs).toEqual([]); + }); + test("skips Transaction Search when the config disables it", 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 06daba85c..b84896c44 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -50,6 +50,8 @@ import { type DeployedCredentials, } from "./cdk/credentials"; import { + assertPlatformVersions, + runtimePlatformVersions, assertPrivateVpcs, countDeployableResources, stackArtifactForTarget, @@ -375,6 +377,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..cec27c7fa 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,105 @@ 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: the @aws/agentcore-cdk in agentcore/cdk does not support platformVersion, and no " + + "released @aws/agentcore-cdk does yet. Deploy again once agentcore/cdk has a release that does."; + + 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..c114c72a0 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,65 @@ 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 does not support platformVersion, " + + "and no released @aws/agentcore-cdk does yet. Deploy again once agentcore/cdk has a " + + "release that does.", + ]; + }); + 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 7e4f35a4f..686863819 100644 --- a/src/core/project/boxValidation.ts +++ b/src/core/project/boxValidation.ts @@ -6,7 +6,7 @@ import { ProjectStateError, RegionUnsupportedFeatureError } from "../../errors/errors"; import { isBoxProject, type ProjectSpec } from "../../projectSchemas/project"; import { supportsRuntimeV2 } from "../partition"; -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"; @@ -103,13 +103,15 @@ export function validateBoxRuntimes(spec: ProjectSpec): void { } /** - * Throws for a Box project deployed to a region where AgentCore Runtime has no platformVersion V2, - * when one of its runtimes runs in a box: Box runs only on V2, so that runtime could not be created - * there. A Box project with no runtime is let through, as deploying it is how its stack is removed. - * `target` is a configured target, or, with `provisioning`, the default target deploy is about to - * create in that region; `otherTargets` says whether aws-targets.json has targets to deploy to. + * Throws for a deploy to a region where AgentCore Runtime has no platformVersion V2 when a runtime + * asks for V2 (`"platformVersion": "V2"`): CloudFormation could not create it there, and would fail + * only partway through the deploy. Every runtime of a Box project asks for V2, as the project schema + * requires, so this covers Box runtimes too. A project with no such runtime is let through, an + * empty one included, as deploying it is how its stack is removed. `target` is a configured + * target, or, with `provisioning`, the default target deploy is about to create in that region; + * `otherTargets` says whether aws-targets.json has targets to deploy to. */ -export function assertBoxRegionSupported( +export function assertRuntimeV2RegionSupported( spec: ProjectSpec, target: { name: string; region: string }, { @@ -118,7 +120,10 @@ export function assertBoxRegionSupported( }: { provisioning?: boolean; otherTargets?: boolean } = {}, ): void { if (supportsRuntimeV2(target.region)) return; - if (!spec.runtimes.some((runtime) => runsInBox(isBoxProject(spec), runtime))) return; + const onV2 = spec.runtimes + .filter((runtime) => runtime.platformVersion === BOX_PLATFORM_VERSION) + .map((runtime) => `'${runtime.name}'`); + if (onV2.length === 0) return; const wayOut = provisioning ? otherTargets ? "Deploy with --region set to a region that has it, or with --target set to a target in " + @@ -127,8 +132,13 @@ export function assertBoxRegionSupported( "agentcore/aws-targets.json, then retry." : `Change the region of target '${target.name}' in agentcore/aws-targets.json, or deploy ` + "with --target to a target in another region, then retry."; + const asks = onV2.length === 1 ? "it asks" : "they ask"; + const why = isBoxProject(spec) + ? "Box runs on AgentCore Runtime V2" + : `${asks} for AgentCore Runtime V2`; throw new RegionUnsupportedFeatureError( - `Cannot deploy Box project '${spec.name}' to target '${target.name}' in ${target.region}: ` + - `Box runs on AgentCore Runtime V2, which is not available in ${target.region}. ${wayOut}`, + `Cannot deploy runtime ${onV2.join(", ")} of project '${spec.name}' to target ` + + `'${target.name}' in ${target.region}: ${why} ("platformVersion": ` + + `"${BOX_PLATFORM_VERSION}"), which is not available in ${target.region}. ${wayOut}`, ); } diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 9fe6b1320..073e4d52c 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -89,6 +89,7 @@ async function createdProject( runtimeVersion: "PYTHON_3_14", protocol: "HTTP", box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, })); for (const name of runtimes) await mkdir(join(created.rootPath, "app", name), { recursive: true }); @@ -233,6 +234,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 +392,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 28ae6329b..792245af7 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -1515,6 +1515,7 @@ describe("FsProjectManager.addResource", () => { bedrockManagedAgents?: boolean; tags?: Record; additionalPolicies?: string[]; + platformVersion?: string; }[]; harnesses: unknown[]; memories?: unknown[]; @@ -1560,7 +1561,16 @@ describe("FsProjectManager.addResource", () => { expect(deployCalls).toEqual([]); }); - describe("Box projects in a region without Runtime V2", () => { + 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); + }); + + describe("runtimes on Runtime V2 in a region without it", () => { // partition.test.ts covers which regions have no Runtime V2; one is enough here. test.each(["us-west-1"])( "deploy of a Box project to %s fails before anything is written", @@ -1577,8 +1587,9 @@ describe("FsProjectManager.addResource", () => { const { error } = await deployOutcome(subject, project); expect(error).toBeInstanceOf(RegionUnsupportedFeatureError); expect(String(error)).toContain( - `Cannot deploy Box project 'example' to target 'primary' in ${region}: Box runs on ` + - `AgentCore Runtime V2, which is not available in ${region}. Change the region of ` + + `Cannot deploy runtime 'agent_python_strands_box' of project 'example' to target ` + + `'primary' in ${region}: Box runs on AgentCore Runtime V2 ("platformVersion": "V2"), ` + + `which is not available in ${region}. Change the region of ` + "target 'primary' in agentcore/aws-targets.json, or deploy with --target to a target " + "in another region, then retry.", ); @@ -1641,8 +1652,9 @@ describe("FsProjectManager.addResource", () => { await expect(deploying).rejects.toThrow( new RegionUnsupportedFeatureError( - "Cannot deploy Box project 'example' to target 'default' in us-west-1: Box runs on " + - "AgentCore Runtime V2, which is not available in us-west-1. Deploy with --region set " + + "Cannot deploy runtime 'agent_python_strands_box' of project 'example' to target " + + "'default' in us-west-1: Box runs on AgentCore Runtime V2 (\"platformVersion\": " + + '"V2"), which is not available in us-west-1. Deploy with --region set ' + "to a region that has it, or add a target in another region to " + "agentcore/aws-targets.json, then retry.", ), @@ -1660,6 +1672,24 @@ describe("FsProjectManager.addResource", () => { expect(deployCalls).toHaveLength(1); }); + // Outside a Box project too: CloudFormation could not create a V2 runtime there either. + test("refuses a runtime that asks for V2 in a project that is not a Box project, by name", async () => { + await inTempDirectory(); + const { subject, project, deployCalls } = await projectWithTarget("us-west-1"); + const specPath = join(project.rootPath, "agentcore", "agentcore.json"); + const spec = JSON.parse(await readFile(specPath, "utf8")); + spec.runtimes[0].platformVersion = "V2"; + await writeFile(specPath, JSON.stringify(spec, null, 2)); + + const { error } = await deployOutcome(subject, project); + expect(error).toBeInstanceOf(RegionUnsupportedFeatureError); + expect(String(error)).toContain( + `Cannot deploy runtime '${spec.runtimes[0].name}' of project 'example' to target ` + + "'primary' in us-west-1: it asks for AgentCore Runtime V2", + ); + expect(deployCalls).toEqual([]); + }); + test("names --target, not a new target, when aws-targets.json has targets", async () => { await inTempDirectory(); const { subject, project } = await projectWithTarget( @@ -2271,6 +2301,26 @@ 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. + // The project schema holds the rule, so every command stops when it reads agentcore.json, before + // build, deploy, or any other step writes a file. + test.each([ + ["no platformVersion", undefined, "has no platformVersion"], + ['"platformVersion": "V1"', "V1", 'has "platformVersion": "V1"'], + ])("a Box runtime with %s stops the project from loading", async (_label, version, actual) => { + const directory = await inTempDirectory(); + const { manager: subject } = 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 = version; + await writeFile(specPath, JSON.stringify(spec, null, 2)); + + await expect(subject.resolve({ filePath: project.rootPath })).rejects.toThrow( + `${actual}, but every runtime of a Box project runs on AgentCore Runtime V2.`, + ); + }); + 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 73ec9466d..a25808d34 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -81,7 +81,7 @@ import { startsInBoxOnCodeZip, } from "./templates/boxProfile"; import { defaultLogTargetNotice } from "./runtimeProfile/rules/additions"; -import { assertBoxRegionSupported, validateBoxRuntimes } from "./boxValidation"; +import { assertRuntimeV2RegionSupported, validateBoxRuntimes } from "./boxValidation"; import { BOX_INSTALL_HINT, BOX_RELEASE } from "./backends/boxRelease"; import { getRuntimeTemplateResolver } from "./templates/runtime"; import { @@ -111,7 +111,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 { @@ -1810,7 +1810,7 @@ export class FsProjectManager implements ProjectManager { // typo'd --target into a deployment somewhere unintended. if (!target && input.target === DEFAULT_TARGET_NAME) { // Box runs only on AgentCore Runtime V2, so stop before STS or aws-targets.json. - assertBoxRegionSupported( + assertRuntimeV2RegionSupported( project.spec, { name: DEFAULT_TARGET_NAME, region: input.region }, { provisioning: true, otherTargets: targets.length > 0 }, @@ -1844,7 +1844,7 @@ export class FsProjectManager implements ProjectManager { } // Box runs only on AgentCore Runtime V2, so stop before the sync rewrites agentcore.json. - assertBoxRegionSupported(project.spec, target); + assertRuntimeV2RegionSupported(project.spec, target); // 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. @@ -2155,6 +2155,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 110d60766..cb3794960 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/handlers/project/add/gateway-connector/gateway-connector.screen.test.tsx b/src/handlers/project/add/gateway-connector/gateway-connector.screen.test.tsx index f5e20d4c9..c850f75f0 100644 --- a/src/handlers/project/add/gateway-connector/gateway-connector.screen.test.tsx +++ b/src/handlers/project/add/gateway-connector/gateway-connector.screen.test.tsx @@ -52,6 +52,7 @@ describe("gateway-connector wizard helpers", () => { await writeProjectSpec(projectRoot, { ...spec, projectType: "box", + runtimes: spec.runtimes.map((runtime: object) => ({ ...runtime, platformVersion: "V2" })), agentCoreGateways: [boxGatewaySpec(spec.runtimes[0].name)], }); const screen = renderScreen("/agentcore/add/gateway-connector"); diff --git a/src/handlers/project/add/gateway-connector/index.test.ts b/src/handlers/project/add/gateway-connector/index.test.ts index 6bd00c6a8..a4adf0ad8 100644 --- a/src/handlers/project/add/gateway-connector/index.test.ts +++ b/src/handlers/project/add/gateway-connector/index.test.ts @@ -106,7 +106,12 @@ describe("project add gateway-connector", () => { const spec = await projectSpec(projectRoot); const runtime = spec.runtimes[0].name; const box = boxGatewaySpec(runtime); - await writeProjectSpec(projectRoot, { ...spec, projectType: "box", agentCoreGateways: [box] }); + await writeProjectSpec(projectRoot, { + ...spec, + projectType: "box", + runtimes: spec.runtimes.map((runtime: object) => ({ ...runtime, platformVersion: "V2" })), + agentCoreGateways: [box], + }); const note = `Gateway '${box.name}' is bound to runtime '${runtime}', so only that runtime gets its variables`; const human = await run([ diff --git a/src/handlers/project/add/gateway-target/gateway-target.screen.test.tsx b/src/handlers/project/add/gateway-target/gateway-target.screen.test.tsx index 76d343014..d9b332af7 100644 --- a/src/handlers/project/add/gateway-target/gateway-target.screen.test.tsx +++ b/src/handlers/project/add/gateway-target/gateway-target.screen.test.tsx @@ -321,6 +321,7 @@ describe("project add gateway-target wizard", () => { await writeProjectSpec(projectRoot, { ...spec, projectType: "box", + runtimes: spec.runtimes.map((runtime: object) => ({ ...runtime, platformVersion: "V2" })), agentCoreGateways: [boxGatewaySpec(spec.runtimes[0].name)], }); const screen = renderScreen("/agentcore/add/gateway-target"); @@ -469,7 +470,13 @@ describe("project add gateway-target wizard", () => { await writeProjectSpec(projectRoot, { ...spec, projectType: "box", - runtimes: [{ ...spec.runtimes[0], box: { version: BOX_RELEASE.version } }], + runtimes: [ + { + ...spec.runtimes[0], + box: { version: BOX_RELEASE.version }, + platformVersion: "V2" as const, + }, + ], agentCoreGateways: [box], }); const screen = renderScreen("/agentcore/add/gateway-target"); diff --git a/src/handlers/project/add/gateway-target/index.test.ts b/src/handlers/project/add/gateway-target/index.test.ts index f80332e6b..a41aee1d8 100644 --- a/src/handlers/project/add/gateway-target/index.test.ts +++ b/src/handlers/project/add/gateway-target/index.test.ts @@ -46,6 +46,7 @@ describe("project add gateway-target", () => { await writeProjectSpec(projectRoot, { ...spec, projectType: "box", + runtimes: spec.runtimes.map((runtime: object) => ({ ...runtime, platformVersion: "V2" })), agentCoreGateways: [box], }); await addGateway(); @@ -85,7 +86,11 @@ describe("project add gateway-target", () => { await writeProjectSpec(projectRoot, { ...spec, projectType: "box", - runtimes: [boxed ? { ...runtime, box: { version: BOX_RELEASE.version } } : runtime], + runtimes: [ + boxed + ? { ...runtime, box: { version: BOX_RELEASE.version }, platformVersion: "V2" as const } + : { ...runtime, platformVersion: "V2" as const }, + ], agentCoreGateways: [box], }); await addGateway(); diff --git a/src/handlers/project/remove/remove.screen.test.tsx b/src/handlers/project/remove/remove.screen.test.tsx index e203b28e9..662fee1df 100644 --- a/src/handlers/project/remove/remove.screen.test.tsx +++ b/src/handlers/project/remove/remove.screen.test.tsx @@ -385,6 +385,10 @@ describe("project remove screen", () => { JSON.stringify({ ...onDisk, projectType: "box", + runtimes: (onDisk.runtimes as object[]).map((runtime) => ({ + ...runtime, + platformVersion: "V2", + })), agentCoreGateways: [boxGatewaySpec(RUNTIME)], }), ); @@ -413,7 +417,15 @@ describe("project remove screen", () => { }; await writeFile( specPath, - JSON.stringify({ ...onDisk, projectType: "box", agentCoreGateways: [boxGateway] }), + JSON.stringify({ + ...onDisk, + projectType: "box", + runtimes: (onDisk.runtimes as object[]).map((runtime) => ({ + ...runtime, + platformVersion: "V2", + })), + agentCoreGateways: [boxGateway], + }), ); const project = (await core.projectManager.resolve({ filePath: created.rootPath }))!; const r = render("/agentcore/remove/runtime/0", core, project); diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index 54249b9fa..8e7d4e0f6 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -421,7 +421,7 @@ describe("containment", () => { fields: Record = {}, ) => ({ ...box, - runtimes, + runtimes: runtimes.map((entry) => ({ platformVersion: "V2", ...entry })), agentCoreGateways: runtimes.map(({ name }) => boxGatewaySpec(name)), ...fields, }); @@ -562,7 +562,7 @@ describe("gateway boundRuntime and discoveryPrefix", () => { const spec = (projectType?: string) => ({ ...minimalProject, ...(projectType && { projectType }), - runtimes: [runtime], + runtimes: [{ ...runtime, platformVersion: "V2" }], agentCoreGateways: [gateway({ boundRuntime: "agent", authorizerType: "NONE" })], }); const box = ProjectSpecSchema.safeParse(spec("box")); @@ -580,8 +580,53 @@ describe("gateway boundRuntime and discoveryPrefix", () => { }); }); +describe("Box project runtimes on AgentCore Runtime V2", () => { + const boxSpec = (platformVersion?: string, projectType = "box") => ({ + ...minimalProject, + ...(projectType && { projectType }), + runtimes: [{ ...runtime, ...(platformVersion && { platformVersion }) }], + agentCoreGateways: [boxGatewaySpec("agent")], + }); + const messages = (spec: unknown) => { + const result = ProjectSpecSchema.safeParse(spec); + return result.success ? [] : result.error.issues.map(({ message }) => message); + }; + + test("accepts a Box runtime on V2", () => { + expect(messages(boxSpec("V2"))).toEqual([]); + }); + + test.each([ + [undefined, "has no platformVersion"], + ["V1", 'has "platformVersion": "V1"'], + ])("refuses a Box runtime with platformVersion %p, and says what to set", (version, actual) => { + expect(messages(boxSpec(version))).toContain( + `Runtime "agent" ${actual}, but every runtime of a Box project runs on AgentCore Runtime ` + + 'V2. Set "platformVersion": "V2" on the runtime in agentcore.json.', + ); + }); + + test("reports a missing platformVersion with the project's other problems at once", () => { + const spec = { ...boxSpec(undefined), agentCoreGateways: [] }; + + expect(messages(spec)).toEqual([ + expect.stringContaining('Runtime "agent" has no platformVersion'), + expect.stringContaining('Runtime "agent" has no Box gateway'), + ]); + }); + + test.each([[undefined], ["V1"]])("takes platformVersion %p outside a Box project", (version) => { + expect(messages(boxSpec(version, ""))).toEqual([]); + }); +}); + describe("Box project gateways", () => { - const runtimeNamed = (name: string) => ({ ...runtime, name, codeLocation: `./${name}` }); + const runtimeNamed = (name: string) => ({ + ...runtime, + name, + codeLocation: `./${name}`, + platformVersion: "V2", + }); const parse = (runtimes: string[], gateways: unknown[]) => ProjectSpecSchema.safeParse({ ...minimalProject, diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index 4a27b74db..f150b6ffe 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -1,5 +1,10 @@ import { isReservedProjectName } from "./constants"; -import { PRIVATE_VPC_LIMIT, ProjectRuntimeSchema, type Containment } from "./runtime"; +import { + BOX_PLATFORM_VERSION, + PRIVATE_VPC_LIMIT, + ProjectRuntimeSchema, + type Containment, +} from "./runtime"; import { AgentCoreGatewaySchema, REAL_KB_ID_PATTERN, ToolRuntimeSchema } from "./gateway"; import { ConfigBundleSchema } from "./config-bundle"; import { CredentialSchema, credentialEnvironmentVariableNames } from "./credential"; @@ -174,6 +179,26 @@ export const ProjectSpecSchema = z }); } } + // 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, so every command stops on a + // Box runtime without it. + if (isBoxProject(spec)) { + 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}"`; + ctx.addIssue({ + code: "custom", + message: + `Runtime "${runtime.name}" ${actual}, 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.`, + path: ["runtimes"], + }); + } + } // A Box project keeps one Box gateway for each runtime. Without it, a deploy would delete the // deployed gateway, so every command stops here and prints the entry to add back. if (isBoxProject(spec)) { 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") {