Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/core/project/backends/cdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ import {
type DeployedCredentials,
} from "./cdk/credentials";
import {
assertPlatformVersions,
runtimePlatformVersions,
assertPrivateVpcs,
countDeployableResources,
stackArtifactForTarget,
Expand Down Expand Up @@ -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
Expand Down
105 changes: 104 additions & 1 deletion src/core/project/backends/cdk/assembly.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() });
Expand Down Expand Up @@ -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<string, unknown>) => ({
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<typeof runtime>[]) => ({
Resources: Object.assign({}, ...templates.map(({ Resources }) => Resources)),
Outputs: Object.assign({}, ...templates.map(({ Outputs }) => Outputs)),
});
async function check(
template: Record<string, unknown>,
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 };

Expand Down
66 changes: 66 additions & 0 deletions src/core/project/backends/cdk/assembly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -42,6 +49,7 @@ const StackTemplateSchema = z
z.object({ Type: z.string().optional() }).passthrough(),
)
.default({}),
Outputs: z.record(z.string(), z.unknown()).default({}),
})
.passthrough();

Expand Down Expand Up @@ -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
* `<stack>-<runtime>-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<void> {
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: " +

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No @aws/agentcore-cdk release has platformVersion yet (1.2.0 is the latest, and it doesn't). Until one does, this tells users to do something they can't. Consider naming the minimum version once it ships, or saying the support isn't released yet.

"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,
Expand Down
24 changes: 23 additions & 1 deletion src/core/project/boxValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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.`,
);
}
}
4 changes: 4 additions & 0 deletions src/core/project/manager.box.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

Expand Down Expand Up @@ -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")),
Expand Down
67 changes: 67 additions & 0 deletions src/core/project/manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,7 @@ describe("FsProjectManager.addResource", () => {
bedrockManagedAgents?: boolean;
tags?: Record<string, string>;
additionalPolicies?: string[];
platformVersion?: string;
}[];
harnesses: unknown[];
memories?: unknown[];
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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-"));
Expand Down
Loading
Loading