From efe601db19d84d2db6b2183dfd95245bf9362a5b Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 23 Nov 2026 14:02:30 -0800 Subject: [PATCH] feat(box): Let a runtime's box.version choose among the box releases this CLI supports boxRelease.json pins the releases this CLI supports: box, the default that create writes, and supported, the others, each with the checksums of its Linux and macOS builds. A runtime's box.version picks one of them, and no version means the default. Build, deploy and container dev ship that release; build and deploy refuse any other version before they write anything, naming the supported ones. Build no longer rewrites box.version, so the choice stays. Checksums come only from boxRelease.json, which changes by a reviewed PR, not from a release's SHA256SUMS.txt, which anyone who can edit the release could replace. scripts/bump-box-release.ts gains --add, --remove and --keep-previous to manage the list. --- README.md | 19 +++-- docs/box-local-testing.md | 16 ++-- scripts/bump-box-release.ts | 78 ++++++++++++++----- src/core/dev/container.test.ts | 20 +++-- src/core/dev/container.ts | 6 ++ .../backends/box-release-test-support.ts | 16 +++- src/core/project/backends/boxCodeZip.test.ts | 41 +++++++--- src/core/project/backends/boxCodeZip.ts | 23 +++++- .../project/backends/boxContainer.test.ts | 19 ++++- src/core/project/backends/boxContainer.ts | 9 ++- src/core/project/backends/boxRelease.json | 3 +- src/core/project/backends/boxRelease.test.ts | 26 +++++++ src/core/project/backends/boxRelease.ts | 52 +++++++++++-- src/core/project/backends/cdk.ts | 8 +- src/core/project/boxNetworkWriters.ts | 29 ------- src/core/project/boxValidation.ts | 18 ++++- src/core/project/manager.boxNetwork.test.ts | 39 +++++----- src/projectSchemas/runtime.ts | 13 ++-- 18 files changed, 307 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index 92404f94d..7297de0ee 100644 --- a/README.md +++ b/README.md @@ -213,10 +213,13 @@ each runtime from its local profile. box comes from the public GitHub release `v is needed to download it. Use that release's build for your machine for `agentcore dev` and the profile checks of `build`: an older box cannot read the profiles that this CLI writes. -`src/core/project/backends/boxRelease.json` pins the Linux build of box that ships to AgentCore -Runtime, with its repository, version and SHA-256. It also pins the macOS arm64 build, which the e2e -workflow installs on its macOS runner. `bun scripts/bump-box-release.ts --box ` -(with `--box-repo` to move repository) rewrites the file from the release's `SHA256SUMS.txt`. +`src/core/project/backends/boxRelease.json` pins the box releases this CLI supports: `box`, the +default, and `supported`, the others. For each it pins the Linux build that ships to AgentCore +Runtime and the macOS arm64 build that the e2e workflow installs, with their repository, version and +SHA-256. `bun scripts/bump-box-release.ts --box ` makes a release the default (add +`--keep-previous` to keep the old one supported), `--add ` and `--remove ` change +the other supported releases, and `--box-repo` moves repository. The script reads each release's +`SHA256SUMS.txt`, and the checksums reach the CLI only through a reviewed change of the file. How each command uses it: @@ -224,7 +227,7 @@ How each command uses it: `~/.agentcore/box/`, check it against its pinned SHA-256, and stage box and its packs into the runtime's `.box-dist/`. - A container agent's image downloads box while it builds. `dev`, `build` and `deploy` stage the - release that `box.version` names, with its checksum, as `box-release.env` beside the Dockerfile + release that `box.version` names, with its pinned checksum, as `box-release.env` beside the Dockerfile (`.box-dist/`, or `.box-dev/` under `dev`), and the Dockerfile downloads that release with `curl`, checks its SHA-256 and unpacks it into `/opt/box`. The CLI downloads nothing for a container, so the build machine, or AWS CodeBuild on `deploy`, needs network to github.com. `agentcore dev` @@ -235,8 +238,10 @@ How each command uses it: with that instruction when `box` is not on your PATH. Container agents need no local box. Each box runtime names its release in `agentcore.json` with `"box": { "version": "" }`, -which `agentcore create` writes. Every box runtime runs the pinned version, whose checksums -`boxRelease.json` keeps: build and deploy set `box.version` to it, and say so when it named another. +which `agentcore create` writes with the default. To move a runtime to another supported release, +change its `box.version`; with no version, it runs the default. Build, deploy and container `dev` +stop on a version that `boxRelease.json` does not list, and name the supported ones, before they +write anything. Build never rewrites `box.version`. On AgentCore Runtime, box signs the agent's Bedrock and Memory calls with the execution role: the profile's bare `aws://` resolves the AWS default credential chain, which box reads and refreshes diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index e5e7ad5da..efcb7649b 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -14,8 +14,8 @@ gateway, bound to it by `boundRuntime` and named after it: the runtime `agent` g A Box project ships box inside its deploy artifact, so the agent runs in a box on AgentCore Runtime. Each box runtime names its box release in `agentcore.json` with `"box": { "version": "" }`, -which `agentcore create` writes and build keeps at the pinned release. `agentcore build` and -`agentcore deploy` download the pinned release's Linux build from +which `agentcore create` writes with the default release. `agentcore build` and `agentcore deploy` +download the Linux build of the release it names from [mquang-amazon/box-releases](https://github.com/mquang-amazon/box-releases) once into `~/.agentcore/box/`, check its SHA-256s, and stage it into the zip, for a CodeZip runtime. For a container they write the release and its checksum into `.box-dist/box-release.env` instead. A @@ -29,13 +29,15 @@ only for the box templates. The runtime's entry point and Dockerfile never decid `start.py` runs the usual way. A runtime with `box.version` in a project without `"projectType": "box"` stops dev with `agentcore.json has no "projectType": "box"`. -Every box runtime runs the box version the CLI pins in `src/core/project/backends/boxRelease.json`. -Build and deploy set each runtime's `box.version` to it, and say so when it named another; container -`dev` stages the pinned box whatever `box.version` says. To try an unreleased box build, publish it -as a GitHub pre-release with the release's file names (the `aarch64-apple-darwin` and +A runtime's `box.version` must be one of the releases that +`src/core/project/backends/boxRelease.json` supports: `box`, the default, or one of `supported`. +With no version, the runtime runs the default. Build, deploy and container `dev` stop on any other +version and name the supported ones; build never rewrites the field. To try an unreleased box build, +publish it as a GitHub pre-release with the release's file names (the `aarch64-apple-darwin` and `aarch64-unknown-linux-gnu` archives and `SHA256SUMS.txt`), for example in a fork of [mquang-amazon/box-releases](https://github.com/mquang-amazon/box-releases), then run -`bun scripts/bump-box-release.ts --box --box-repo ` in your CLI checkout. +`bun scripts/bump-box-release.ts --add --box-repo ` in your CLI checkout and +set the runtime's `box.version` to it, or `--box ` to make it the default. ## Prerequisites diff --git a/scripts/bump-box-release.ts b/scripts/bump-box-release.ts index 17feb06df..046849a7e 100644 --- a/scripts/bump-box-release.ts +++ b/scripts/bump-box-release.ts @@ -1,12 +1,20 @@ #!/usr/bin/env bun /** - Pins box to a published GitHub release, in src/core/project/backends/boxRelease.json: the Linux - arm64 build that ships to AgentCore Runtime, and the macOS arm64 build that the e2e workflow - installs on its macOS runner. It reads the release's SHA256SUMS.txt, so the file changes only to a - version whose archives are published. It imports nothing from src/. + Pins the box releases this CLI supports, in src/core/project/backends/boxRelease.json: for each, + the Linux arm64 build that ships to AgentCore Runtime and the macOS arm64 build that the e2e + workflow installs on its macOS runner. `box` is the default release, which `agentcore create` + writes; `supported` lists the other releases a runtime's box.version can name. It reads each + release's SHA256SUMS.txt, so the file changes only to versions whose archives are published, and + the checksums it pins reach the CLI only through a reviewed change of the file. It imports nothing + from src/. - bun scripts/bump-box-release.ts --box [--box-repo ] + bun scripts/bump-box-release.ts --box [--keep-previous] [--box-repo ] + bun scripts/bump-box-release.ts --add [--box-repo ] + bun scripts/bump-box-release.ts --remove + + --box makes the default; --keep-previous keeps the old default as a supported release. + --add supports beside the default, and --remove stops supporting it. **/ import { join, resolve } from "node:path"; @@ -27,11 +35,14 @@ const { values } = parseArgs({ args: Bun.argv.slice(2), options: { box: { type: "string" }, + add: { type: "string" }, + remove: { type: "string" }, + "keep-previous": { type: "boolean" }, "box-repo": { type: "string" }, }, }); -if (!values.box) { - console.error("Name a version: --box ."); +if ([values.box, values.add, values.remove].filter(Boolean).length !== 1) { + console.error("Name one change: --box , --add , or --remove ."); process.exit(2); } @@ -48,18 +59,47 @@ async function checksums(repo: string, version: string): Promise { + const sums = await checksums(repo, version); + const pin = (target: string) => { + const asset = `box-v${version}-${target}.tar.gz`; + const sha256 = sums.get(asset); + if (!sha256) throw new Error(`${repo} v${version} lists no ${asset}`); + return { target, asset, sha256 }; + }; + return { repo, version, linux: pin(LINUX_TARGET), darwin: pin(DARWIN_TARGET) }; +} + +const pinned = (await Bun.file(FILE).json()) as { box: Release; supported?: Release[] }; const repo = values["box-repo"] ?? pinned.box.repo; -const version = values.box; -const sums = await checksums(repo, version); -/** The pinned archive of `target`, which the release must list. */ -function pin(target: string): { target: string; asset: string; sha256: string } { - const asset = `box-v${version}-${target}.tar.gz`; - const sha256 = sums.get(asset); - if (!sha256) throw new Error(`${repo} v${version} lists no ${asset}`); - return { target, asset, sha256 }; +let box = pinned.box; +let supported = (pinned.supported ?? []).filter(({ version }) => version !== box.version); +if (values.box) { + const next = await release(repo, values.box); + console.log(`box: default ${box.repo} ${box.version} → ${next.repo} ${next.version}`); + if (values["keep-previous"]) supported = [box, ...supported]; + box = next; +} else if (values.add) { + if (values.add === box.version) throw new Error(`${values.add} is the default already`); + console.log(`box: supporting ${repo} ${values.add} beside the default ${box.version}`); + supported = [ + ...supported.filter(({ version }) => version !== values.add), + await release(repo, values.add), + ]; +} else if (values.remove) { + if (values.remove === box.version) + throw new Error(`${values.remove} is the default: move --box first`); + console.log(`box: no longer supporting ${values.remove}`); + supported = supported.filter(({ version }) => version !== values.remove); } -console.log(`box: ${pinned.box.repo} ${pinned.box.version} → ${repo} ${version}`); -const box = { repo, version, linux: pin(LINUX_TARGET), darwin: pin(DARWIN_TARGET) }; +supported = supported.filter(({ version }) => version !== box.version); -await Bun.write(FILE, `${JSON.stringify({ box }, null, 2)}\n`); +await Bun.write(FILE, `${JSON.stringify({ box, supported }, null, 2)}\n`); diff --git a/src/core/dev/container.test.ts b/src/core/dev/container.test.ts index f61462560..c31e793d6 100644 --- a/src/core/dev/container.test.ts +++ b/src/core/dev/container.test.ts @@ -19,7 +19,8 @@ import { type StreamProcessOptions, } from "../../io"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; -import { BOX_RELEASE } from "../project/backends/boxRelease"; +import { BOX_RELEASE, type BoxRelease } from "../project/backends/boxRelease"; +import { OTHER_BOX_RELEASE, TEST_BOX_RELEASES } from "../project/backends/box-release-test-support"; import type { ResolveAwsCredentials } from "./boxAwsCredentials"; import { ContainerDevRunner } from "./container"; @@ -76,6 +77,7 @@ function harness( processEnv?: NodeJS.ProcessEnv; resolveAwsCredentials?: ResolveAwsCredentials; platform?: NodeJS.Platform; + releases?: readonly BoxRelease[]; } = {}, ) { const calls: ProcessCall[] = []; @@ -125,6 +127,7 @@ function harness( // Never the real chain in a test: none unless the test gives some. resolveAwsCredentials: config.resolveAwsCredentials ?? (async () => undefined), ...(config.platform && { platform: config.platform }), + ...(config.releases && { releases: config.releases }), }), }; } @@ -812,7 +815,9 @@ describe("ContainerDevRunner", () => { box?: boolean; } = {}, ) { - const projectRuntime = runtime(options.box === false ? {} : { box: { version: "1.0.0" } }); + const projectRuntime = runtime( + options.box === false ? {} : { box: { version: BOX_RELEASE.version } }, + ); const root = await projectRoot(projectRuntime); const context = join(root, projectRuntime.codeLocation); await writeFile(join(context, "Dockerfile"), options.dockerfile ?? BOX_DOCKERFILE); @@ -1074,15 +1079,16 @@ describe("ContainerDevRunner", () => { expect(JSON.stringify(events)).not.toContain("reads GITHUB_TOKEN for [egress.github]"); }); - test("stages the pinned box, whatever box.version the runtime names", async () => { + test("stages the box release that the runtime's box.version names", async () => { const { projectRuntime, root, context } = await boxedScene(); - const { runner } = harness({ processEnv: credentials }); + const { runner } = harness({ processEnv: credentials, releases: TEST_BOX_RELEASES }); - await collect(runner.run(input(root, { ...projectRuntime, box: { version: "2.0.0" } }))); + await collect( + runner.run(input(root, { ...projectRuntime, box: { version: OTHER_BOX_RELEASE.version } })), + ); const env = await readFile(join(context, ".box-dist", "box-release.env"), "utf8"); - expect(env).toContain(BOX_RELEASE.version); - expect(env).not.toContain("2.0.0"); + expect(env).toContain(`BOX_VERSION=${OTHER_BOX_RELEASE.version}`); }); test("runs a runtime with no box.version without box's flags, even with a box profile", async () => { diff --git a/src/core/dev/container.ts b/src/core/dev/container.ts index 8b5ef8e45..b5aeab994 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -26,6 +26,7 @@ import { imageTakesBoxDistArg, stageBoxImage, } from "../project/backends/boxContainer"; +import { BOX_RELEASES, boxReleaseOfRuntime, type BoxRelease } from "../project/backends/boxRelease"; import { boxPolicyFileCopies } from "../project/boxNetworkSource"; import { boxLocalProfileFile, @@ -118,6 +119,8 @@ type ContainerDevRunnerConfig = { resolveAwsCredentials?: ResolveAwsCredentials; /** The platform, whose rules for variable names apply to `processEnv`; tests inject one. */ platform?: NodeJS.Platform; + /** The box releases a runtime's box.version can name; boxRelease.json's by default. */ + releases?: readonly BoxRelease[]; }; export class ContainerDevRunner implements DevRunner { @@ -127,6 +130,7 @@ export class ContainerDevRunner implements DevRunner { private readonly processEnv: NodeJS.ProcessEnv; private readonly resolveAwsCredentials: ResolveAwsCredentials; private readonly platform: NodeJS.Platform; + private readonly releases: readonly BoxRelease[]; constructor(config: ContainerDevRunnerConfig = {}) { this.streamProcess = config.streamProcess ?? streamProcess; @@ -135,6 +139,7 @@ export class ContainerDevRunner implements DevRunner { this.processEnv = config.processEnv ?? process.env; this.resolveAwsCredentials = config.resolveAwsCredentials ?? resolveDefaultAwsCredentials; this.platform = config.platform ?? process.platform; + this.releases = config.releases ?? BOX_RELEASES; } public async *run(input: DevServerInput): AsyncGenerator { @@ -390,6 +395,7 @@ export class ContainerDevRunner implements DevRunner { context, profileText, boxPolicyFileCopies(input.projectRoot, input.runtime.name), + boxReleaseOfRuntime(input.runtime.name, input.runtime.box?.version, this.releases), folder, ); return { folder, profileText }; diff --git a/src/core/project/backends/box-release-test-support.ts b/src/core/project/backends/box-release-test-support.ts index bec153079..35afdc2fd 100644 --- a/src/core/project/backends/box-release-test-support.ts +++ b/src/core/project/backends/box-release-test-support.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { BOX_BINARIES, BOX_RELEASE, boxCachePath } from "./boxRelease"; +import { BOX_BINARIES, BOX_RELEASE, boxCachePath, type BoxRelease } from "./boxRelease"; /** * Fills the cache under `home` with a stand-in of the pinned box release, so build, deploy and @@ -13,3 +13,17 @@ export async function seedBoxCache(home: string): Promise { for (const binary of BOX_BINARIES) await writeFile(join(root, binary), `#!${binary}\n`); await writeFile(join(root, "release.json"), JSON.stringify({ box_version: BOX_RELEASE.version })); } + +/** A second supported box release, for tests of a runtime whose box.version is not the default. */ +export const OTHER_BOX_RELEASE: BoxRelease = { + ...BOX_RELEASE, + version: "9.9.9-test.1", + linux: { + ...BOX_RELEASE.linux, + asset: "box-v9.9.9-test.1-aarch64-unknown-linux-gnu.tar.gz", + sha256: "1".repeat(64), + }, +}; + +/** The supported releases of those tests: the default, then {@link OTHER_BOX_RELEASE}. */ +export const TEST_BOX_RELEASES: readonly BoxRelease[] = [BOX_RELEASE, OTHER_BOX_RELEASE]; diff --git a/src/core/project/backends/boxCodeZip.test.ts b/src/core/project/backends/boxCodeZip.test.ts index 43ff085c0..f8a5aaee1 100644 --- a/src/core/project/backends/boxCodeZip.test.ts +++ b/src/core/project/backends/boxCodeZip.test.ts @@ -16,7 +16,8 @@ import { import { serializeRuntimeProfile } from "../runtimeProfile/serialize"; import type { TomlTable } from "../runtimeProfile/types"; import { BOX_DIST_GITIGNORE, stageBoxCodeZip } from "./boxCodeZip"; -import type { BoxLinuxBuild } from "./boxRelease"; +import { BOX_RELEASE, type BoxLinuxBuild, type BoxRelease } from "./boxRelease"; +import { OTHER_BOX_RELEASE, TEST_BOX_RELEASES } from "./box-release-test-support"; const directories: string[] = []; @@ -66,7 +67,7 @@ async function project( runtimeVersion, modelProvider: "Bedrock", // create writes box.version only for a box template, whose entry point is start.py. - ...(entrypoint === "start.py" && { box: { version: "1.0.0" } }), + ...(entrypoint === "start.py" && { box: { version: BOX_RELEASE.version } }), })), memories: [], projectType: "box", @@ -120,18 +121,36 @@ describe("stageBoxCodeZip", () => { expect(await readFile(join(dist, ".gitignore"), "utf8")).toBe(BOX_DIST_GITIGNORE); }); - test("asks for the pinned box once, for every runtime", async () => { + test("asks once for each supported release the runtimes name, the default for no version", async () => { const build = await linuxBuild(); - const demo = await project("start.py", "PYTHON_3_14", ["agent", "second"]); - demo.spec.runtimes[1]!.box = { version: "2.0.0" }; - let asked = 0; + const demo = await project("start.py", "PYTHON_3_14", ["agent", "second", "third"]); + demo.spec.runtimes[1]!.box = { version: OTHER_BOX_RELEASE.version }; + demo.spec.runtimes[2]!.box = {}; + const asked: string[] = []; - await stageBoxCodeZip(demo, [model([]), model([], "second")], async () => { - asked++; - return build; - }); + await stageBoxCodeZip( + demo, + [model([]), model([], "second"), model([], "third")], + async (release: BoxRelease) => { + asked.push(release.version); + return build; + }, + TEST_BOX_RELEASES, + ); - expect(asked).toBe(1); + expect(asked).toEqual([BOX_RELEASE.version, OTHER_BOX_RELEASE.version]); + }); + + test("refuses a box.version this CLI does not support, and names the supported ones", async () => { + const demo = await project("start.py"); + demo.spec.runtimes[0]!.box = { version: "0.0.1" }; + + await expect( + stageBoxCodeZip(demo, [model([])], async () => linuxBuild(), TEST_BOX_RELEASES), + ).rejects.toThrow( + 'runtime "agent" names box 0.0.1 under box.version in agentcore.json, but this CLI ' + + `supports box ${BOX_RELEASE.version}, ${OTHER_BOX_RELEASE.version}.`, + ); }); test.each([ diff --git a/src/core/project/backends/boxCodeZip.ts b/src/core/project/backends/boxCodeZip.ts index 29dc30dee..8d085ba57 100644 --- a/src/core/project/backends/boxCodeZip.ts +++ b/src/core/project/backends/boxCodeZip.ts @@ -9,7 +9,13 @@ import { writeRenderedBoxFiles, } from "../boxNetworkWriters"; import { BOX_CODEZIP_DIST, runtimeRunsInBox } from "../templates/boxProfile"; -import { BOX_BINARIES, type BoxLinuxBuild } from "./boxRelease"; +import { + BOX_BINARIES, + BOX_RELEASES, + boxReleaseOfRuntime, + type BoxLinuxBuild, + type BoxRelease, +} from "./boxRelease"; /** The `.gitignore` staged into `.box-dist/`: build and deploy rewrite the folder every time. */ export const BOX_DIST_GITIGNORE = @@ -27,7 +33,8 @@ export const BOX_DIST_GITIGNORE = export async function stageBoxCodeZip( project: Project, networks: readonly BoxNetwork[], - box: () => Promise, + box: (release: BoxRelease) => Promise, + releases: readonly BoxRelease[] = BOX_RELEASES, ): Promise { const runtimes = project.spec.runtimes.filter( (runtime) => runtime.build === "CodeZip" && runtimeRunsInBox(project.spec, runtime), @@ -47,10 +54,18 @@ export async function stageBoxCodeZip( envLocal: {}, }); const filesOf = (dist: string) => files.filter(({ path }) => path.startsWith(`${dist}/`)); - // Every runtime ships the pinned box, which downloads once. - const build = await box(); + // One build for each box release the runtimes name, so each downloads once. + const builds = new Map(); + for (const runtime of runtimes) { + const release = boxReleaseOfRuntime(runtime.name, runtime.box?.version, releases); + if (!builds.has(release.version)) builds.set(release.version, await box(release)); + } for (const { runtime, dist } of staged) { + const entry = runtimes.find(({ name }) => name === runtime)!; + const build = builds.get( + boxReleaseOfRuntime(entry.name, entry.box?.version, releases).version, + )!; const folder = join(project.rootPath, ...dist.split("/")); rmSync(folder, { recursive: true, force: true }); mkdirSync(folder, { recursive: true }); diff --git a/src/core/project/backends/boxContainer.test.ts b/src/core/project/backends/boxContainer.test.ts index 83acce279..9de08d4c9 100644 --- a/src/core/project/backends/boxContainer.test.ts +++ b/src/core/project/backends/boxContainer.test.ts @@ -10,6 +10,7 @@ import { renderAgentCorePack } from "../templates/boxProfile"; import { serializeRuntimeProfile } from "../runtimeProfile/serialize"; import { stageBoxContainers } from "./boxContainer"; import { BOX_RELEASE } from "./boxRelease"; +import { OTHER_BOX_RELEASE, TEST_BOX_RELEASES } from "./box-release-test-support"; /** The staged path of the generated @box/agentcore pack, from `.box-dist/`. */ const PACK_PATH = join("resources", "packs", "agentcore", "pack.toml"); @@ -46,7 +47,7 @@ async function project(dockerfile: string): Promise { dockerfile: "Dockerfile", modelProvider: "Bedrock", // create writes box.version only for the box container template, whose image copies box. - ...(dockerfile.includes(".box-dist") && { box: { version: "1.0.0" } }), + ...(dockerfile.includes(".box-dist") && { box: { version: BOX_RELEASE.version } }), }, ], memories: [], @@ -61,9 +62,8 @@ const BOX_DOCKERFILE = "FROM scratch\nCOPY .box-dist/profile.toml /opt/box/\n"; const STAGED = ["box-release.env", "profile.toml"]; describe("stageBoxContainers", () => { - test("stages the pinned box release, whatever box.version names, and the Runtime profile, into the build context", async () => { + test("stages the box release that box.version names, and the Runtime profile, into the build context", async () => { const demo = await project(BOX_DOCKERFILE); - demo.spec.runtimes[0]!.box = { version: "2.0.0" }; expect(await stageBoxContainers(demo, [model([])])).toEqual(["agent"]); @@ -92,6 +92,19 @@ describe("stageBoxContainers", () => { } }); + test("stages a supported release other than the default, which box.version names", async () => { + const demo = await project(BOX_DOCKERFILE); + demo.spec.runtimes[0]!.box = { version: OTHER_BOX_RELEASE.version }; + + await stageBoxContainers(demo, [model([])], TEST_BOX_RELEASES); + + const dist = join(demo.rootPath, "app", "agent", ".box-dist"); + expect(await readFile(join(dist, "box-release.env"), "utf8")).toContain( + `BOX_VERSION=${OTHER_BOX_RELEASE.version}\nBOX_ASSET=${OTHER_BOX_RELEASE.linux.asset}\n` + + `BOX_SHA256=${OTHER_BOX_RELEASE.linux.sha256}`, + ); + }); + test("replaces what an earlier build staged", async () => { const demo = await project(BOX_DOCKERFILE); const dist = join(demo.rootPath, "app", "agent", ".box-dist"); diff --git a/src/core/project/backends/boxContainer.ts b/src/core/project/backends/boxContainer.ts index 593c744b0..5edb9b9cb 100644 --- a/src/core/project/backends/boxContainer.ts +++ b/src/core/project/backends/boxContainer.ts @@ -12,7 +12,7 @@ import { } from "../boxNetworkWriters"; import { isFile } from "../runtimeBuild"; import { runtimeRunsInBox } from "../templates/boxProfile"; -import { BOX_RELEASE, type BoxRelease } from "./boxRelease"; +import { BOX_RELEASES, boxReleaseOfRuntime, type BoxRelease } from "./boxRelease"; import { assertImageCopiesPolicyFiles } from "./boxStaging"; /** The folder a box image's Dockerfile copies its box profile and policy files from. */ @@ -93,13 +93,14 @@ export async function stageBoxImage( context: string, profileText: string, policies: readonly PolicyFileCopy[], + release: BoxRelease, folder: string = BOX_IMAGE_DIST, ): Promise { const dist = join(context, folder); await rm(dist, { recursive: true, force: true }); await mkdir(dist, { recursive: true }); await writeFile(join(dist, "profile.toml"), profileText); - await writeFile(join(dist, BOX_RELEASE_ENV), boxReleaseEnv(BOX_RELEASE)); + await writeFile(join(dist, BOX_RELEASE_ENV), boxReleaseEnv(release)); for (const { from, relative } of policies) { const to = join(dist, ...relative.split("/")); await mkdir(dirname(to), { recursive: true }); @@ -118,6 +119,7 @@ export async function stageBoxImage( export async function stageBoxContainers( project: Project, networks: readonly BoxNetwork[], + releases: readonly BoxRelease[] = BOX_RELEASES, ): Promise { const runtimes = project.spec.runtimes.filter( (runtime) => runtime.build === "Container" && runtimeRunsInBox(project.spec, runtime), @@ -148,7 +150,8 @@ export async function stageBoxContainers( const folder = join(project.rootPath, ...dist.split("/")); await rm(folder, { recursive: true, force: true }); await mkdir(folder, { recursive: true }); - await writeFile(join(folder, BOX_RELEASE_ENV), boxReleaseEnv(BOX_RELEASE)); + const release = boxReleaseOfRuntime(runtime.name, runtime.box?.version, releases); + await writeFile(join(folder, BOX_RELEASE_ENV), boxReleaseEnv(release)); writeBoxNetworkFiles(project.rootPath, filesOf(dist)); writeRenderedBoxFiles(project.rootPath, runtime.name, dist, filesOf(dist)); } diff --git a/src/core/project/backends/boxRelease.json b/src/core/project/backends/boxRelease.json index 4a1217169..eb8a4cb87 100644 --- a/src/core/project/backends/boxRelease.json +++ b/src/core/project/backends/boxRelease.json @@ -12,5 +12,6 @@ "asset": "box-v0.1.11-preview.10-aarch64-apple-darwin.tar.gz", "sha256": "76a3909c5c99c435b6ead470be2f401a22c6155b5b60652263bfb1af3ef57e18" } - } + }, + "supported": [] } diff --git a/src/core/project/backends/boxRelease.test.ts b/src/core/project/backends/boxRelease.test.ts index 9f215f1d9..c42108dab 100644 --- a/src/core/project/backends/boxRelease.test.ts +++ b/src/core/project/backends/boxRelease.test.ts @@ -10,6 +10,9 @@ import { type ProcessRunner, runProcess } from "../../../io/exec"; import { BOX_INSTALL_HINT, BOX_RELEASE, + BOX_RELEASES, + boxReleaseFor, + boxReleaseOfRuntime, BOX_RELEASE_PAGE, type BoxRelease, publishInstall, @@ -275,3 +278,26 @@ describe("the pinned releases", () => { ); }); }); + +describe("the supported box releases", () => { + const other = { ...BOX_RELEASE, version: "9.9.9-test.1" }; + const releases = [BOX_RELEASE, other]; + + test("start with the default, which create writes", () => { + expect(BOX_RELEASES[0]).toBe(BOX_RELEASE); + }); + + test("give the release a box.version names, and the default for none", () => { + expect(boxReleaseFor(undefined, releases)).toBe(BOX_RELEASE); + expect(boxReleaseFor(other.version, releases)).toBe(other); + expect(boxReleaseFor("0.0.1", releases)).toBeUndefined(); + }); + + test("refuse, by runtime, a version this CLI does not support, and name the supported ones", () => { + expect(() => boxReleaseOfRuntime("agent", "0.0.1", releases)).toThrow( + 'runtime "agent" names box 0.0.1 under box.version in agentcore.json, but this CLI ' + + `supports box ${BOX_RELEASE.version}, 9.9.9-test.1. Set box.version to one of them, or ` + + `remove it to run ${BOX_RELEASE.version}, then retry.`, + ); + }); +}); diff --git a/src/core/project/backends/boxRelease.ts b/src/core/project/backends/boxRelease.ts index 59dc93fb5..5f4098067 100644 --- a/src/core/project/backends/boxRelease.ts +++ b/src/core/project/backends/boxRelease.ts @@ -11,7 +11,7 @@ import { import { homedir } from "node:os"; import { join } from "node:path"; import { z } from "zod"; -import { InvalidEnvironmentError } from "../../../errors/errors"; +import { InvalidEnvironmentError, ProjectStateError } from "../../../errors/errors"; import { type ProcessRunner, runProcess } from "../../../io/exec"; import { isFile } from "../runtimeBuild"; import pinned from "./boxRelease.json"; @@ -38,13 +38,55 @@ const BoxReleaseSchema = z.object({ export type BoxRelease = z.infer; /** - * The release this CLI pins, from boxRelease.json. The checksums are pinned there, not read - * from a release's SHA256SUMS.txt, so a changed asset fails instead of shipping. - * `scripts/bump-box-release.ts` rewrites the file. + * The box releases this CLI supports, from boxRelease.json: `box`, the default, which `agentcore + * create` writes, and `supported`, the other releases a runtime's `box.version` can name. The + * checksums are pinned there, not read from a release's SHA256SUMS.txt, which anyone who can edit + * the release could replace with its archive, so a changed asset fails instead of shipping. Only a + * release listed here ships: the profiles this CLI writes and the box that reads them change + * together. `scripts/bump-box-release.ts` rewrites the file. */ -const PINNED = z.object({ box: BoxReleaseSchema }).parse(pinned); +const PINNED = z + .object({ box: BoxReleaseSchema, supported: z.array(BoxReleaseSchema).default([]) }) + .parse(pinned); export const BOX_RELEASE: BoxRelease = PINNED.box; +/** Every release a runtime can run: the default first, then the other supported ones. */ +export const BOX_RELEASES: readonly BoxRelease[] = [ + BOX_RELEASE, + ...PINNED.supported.filter(({ version }) => version !== BOX_RELEASE.version), +]; + +/** + * The supported release that `version`, a runtime's `box.version`, names: the default when it + * names none. Undefined for a version this CLI does not support. + */ +export function boxReleaseFor( + version: string | undefined, + releases: readonly BoxRelease[] = BOX_RELEASES, +): BoxRelease | undefined { + if (version === undefined) return releases[0]; + return releases.find((release) => release.version === version); +} + +/** + * The release that runtime `name` runs, from its `box.version`. Throws, naming the supported + * versions, for a version this CLI does not support. + */ +export function boxReleaseOfRuntime( + name: string, + version: string | undefined, + releases: readonly BoxRelease[] = BOX_RELEASES, +): BoxRelease { + const release = boxReleaseFor(version, releases); + if (release) return release; + const versions = releases.map((supported) => supported.version); + throw new ProjectStateError( + `runtime "${name}" names box ${version} under box.version in agentcore.json, but this CLI ` + + `supports box ${versions.join(", ")}. Set box.version to one of them, or remove it to run ` + + `${releases[0]!.version}, then retry.`, + ); +} + /** The GitHub release page of the pinned box, with a build for each machine it supports. */ export const BOX_RELEASE_PAGE = `https://github.com/${BOX_RELEASE.repo}/releases/tag/v${BOX_RELEASE.version}`; diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 06daba85c..565223240 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -14,7 +14,7 @@ import { stageBoxCodeZip } from "./boxCodeZip"; import { stageBoxContainers } from "./boxContainer"; import { boxLocalProfileFile, otelOn, runtimeRunsInBox } from "../templates/boxProfile"; import { agentStartsUnderOtel } from "../runtimeProfile/rules/additions"; -import { BOX_RELEASE, boxDownloadMessage, resolveBoxLinuxBuild } from "./boxRelease"; +import { boxDownloadMessage, resolveBoxLinuxBuild, type BoxRelease } from "./boxRelease"; import { cdkCompatibilityWarning } from "./cdk/compatibility"; import { createLineSplitter, @@ -255,11 +255,11 @@ export class CdkBackend implements ProjectBackend { // the code. The box release downloads only when a CodeZip runtime runs in a box, and its notice // goes out when the download starts, not once staging ends. yield* withEvents(async (emit) => { - // Every box runtime ships the pinned box: build set each box.version to it. - const box = () => + // Each box runtime ships the supported release its box.version names. + const box = (release: BoxRelease) => resolveBoxLinuxBuild(this.processEnv, { runner: this.runner, - release: BOX_RELEASE, + release, onDownload: (download) => emit({ type: "step", message: boxDownloadMessage(download, "AgentCore Runtime") }), }); diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 36764b374..117110bac 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -51,7 +51,6 @@ import { isTable } from "./runtimeProfile/projectPaths"; import { serializeRuntimeProfile } from "./runtimeProfile/serialize"; import { RUNTIME_INPUTS, type TomlTable } from "./runtimeProfile/types"; import { ProjectStateError } from "../../errors/errors"; -import { BOX_RELEASE } from "./backends/boxRelease"; /** Something exactly one writer owns. */ export type BoxNetworkOutput = @@ -59,7 +58,6 @@ export type BoxNetworkOutput = | { readonly kind: "defaultTargets" } | { readonly kind: "credentials" } | { readonly kind: "runtimePolicies" } - | { readonly kind: "boxVersions" } | { readonly kind: "envLocal" } | { readonly kind: "file"; readonly path: string }; @@ -519,35 +517,8 @@ function withoutUnsentRoutes( return result; } -/** - * Sets the `box.version` of each box runtime to the box this CLI pins, which build and deploy - * stage: the box features and the profiles that the CLI writes change together, so a runtime runs - * only the pinned box. A runtime that names another version, as one created by an earlier CLI - * does, says so. - */ -export const boxVersionWriter: BoxNetworkWriter = { - name: "box versions", - writes: () => [{ kind: "boxVersions" }], - edits: (networks) => ({ - spec: [ - (copy) => - networks.flatMap(({ runtime: name }) => { - const runtime = copy.runtimes.find((candidate) => candidate.name === name); - const version = runtime?.box?.version; - if (!runtime?.box || version === BOX_RELEASE.version) return []; - runtime.box = { ...runtime.box, version: BOX_RELEASE.version }; - return [ - `updating box.version of runtime '${name}' from ${version} to ${BOX_RELEASE.version}, ` + - "the box this CLI ships", - ]; - }), - ], - }), -}; - /** The writers that build and deploy run before synth, in order. */ export const BOX_NETWORK_WRITERS: readonly BoxNetworkWriter[] = [ - boxVersionWriter, credentialsWriter, gatewayTargetsWriter, defaultTargetsWriter, diff --git a/src/core/project/boxValidation.ts b/src/core/project/boxValidation.ts index 633951403..1e5d2de6f 100644 --- a/src/core/project/boxValidation.ts +++ b/src/core/project/boxValidation.ts @@ -6,7 +6,7 @@ import { ProjectStateError } from "../../errors/errors"; import { isBoxProject, type ProjectSpec } from "../../projectSchemas/project"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; -import { BOX_RELEASE } from "./backends/boxRelease"; +import { BOX_RELEASE, boxReleaseOfRuntime } from "./backends/boxRelease"; import { BOX_CODEZIP_ENTRYPOINT, runsInBox } from "./templates/boxProfile"; /** The box template whose image starts box itself, for a runtime that needs a container build. */ @@ -93,10 +93,22 @@ export function assertBoxCodeZipRuntimesStartBox(spec: ProjectSpec): void { /** * The checks build and deploy run on the synced `spec`, before they read the box profiles or - * write anything: every runtime of a Box project has `box.version`, and each CodeZip one starts - * box. + * write anything: every runtime of a Box project has `box`, names a box release this CLI supports, + * and, for CodeZip, starts box. */ export function validateBoxRuntimes(spec: ProjectSpec): void { assertBoxRuntimesHaveBoxVersion(spec); + assertBoxVersionsSupported(spec); assertBoxCodeZipRuntimesStartBox(spec); } + +/** + * Throws, naming the supported versions, for a box runtime whose `box.version` names a release this + * CLI does not support: only a release whose checksums the CLI pins can ship. + */ +export function assertBoxVersionsSupported(spec: ProjectSpec): void { + for (const runtime of spec.runtimes) { + if (!runsInBox(isBoxProject(spec), runtime)) continue; + boxReleaseOfRuntime(runtime.name, runtime.box?.version); + } +} diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 3e0b514a2..44b41e7df 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -643,35 +643,38 @@ describe("build writes the Box network of the box profile", () => { }); }); -describe("build sets box.version to the pinned box", () => { - // The box features and the profiles that the CLI writes change together, so a project created - // by an earlier CLI builds with the box this one ships, and agentcore.json says so. - test("updates a runtime's older box.version, and says so", async () => { - const { manager, root } = await strandsProject(); +describe("build ships the box release that box.version names", () => { + test("refuses a box.version this CLI does not support, before anything is written", async () => { + const { manager, root, counter } = await strandsProject(); const spec = JSON.parse(await text(root, SPEC)); spec.runtimes[0].box = { version: "0.1.11-linux-preview.6" }; await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + const before = await text(root, SPEC); + counter.specWrites = 0; - const { steps } = await build(manager, root); - - expect(steps).toContain( - "updating box.version of runtime 'agent_python_strands' from 0.1.11-linux-preview.6 to " + - `${BOX_RELEASE.version}, the box this CLI ships`, + await expect(build(manager, root)).rejects.toThrow( + 'runtime "agent_python_strands" names box 0.1.11-linux-preview.6 under box.version in ' + + `agentcore.json, but this CLI supports box ${BOX_RELEASE.version}. Set box.version to one ` + + `of them, or remove it to run ${BOX_RELEASE.version}, then retry.`, ); - expect(JSON.parse(await text(root, SPEC)).runtimes[0].box).toEqual({ - version: BOX_RELEASE.version, - }); + expect(counter.specWrites).toBe(0); + expect(await text(root, SPEC)).toBe(before); }); - test("leaves the pinned box.version as it is, with no message", async () => { + // The user's choice stays: build does not rewrite box.version, and no version runs the default. + test.each([ + ["the default release", { version: BOX_RELEASE.version }], + ["no version", {}], + ])("keeps a box.version of %s as written", async (_label, box) => { const { manager, root } = await strandsProject(); - const before = JSON.parse(await text(root, SPEC)).runtimes[0].box; + const spec = JSON.parse(await text(root, SPEC)); + spec.runtimes[0].box = box; + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); const { steps } = await build(manager, root); - expect(before).toEqual({ version: BOX_RELEASE.version }); - expect(steps.some((step) => step.startsWith("updating box.version"))).toBe(false); - expect(JSON.parse(await text(root, SPEC)).runtimes[0].box).toEqual(before); + expect(steps.some((step) => step.includes("box.version"))).toBe(false); + expect(JSON.parse(await text(root, SPEC)).runtimes[0].box).toEqual(box); }); }); diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index 3d1f52081..6b2cbdd19 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -371,13 +371,14 @@ export const ProjectRuntimeSchema = z customDockerBuildArgs: z.record(EnvVarNameSchema, BuildArgValueSchema).optional(), runtimeVersion: RuntimeVersionSchemaFromConstants.optional(), /** - * The box release a runtime that runs its agent in a box uses on AgentCore Runtime: build and - * deploy ship its Linux build in a CodeZip runtime's zip, and a container image downloads it - * (under `agentcore dev` too). `agentcore dev` runs a CodeZip agent with the `box` on your PATH - * instead. Every runtime of a Box project needs it, and only a runtime with it runs in a box; - * `agentcore create` writes the box release this CLI pins. + * Runs the runtime's agent in a box. Every runtime of a Box project needs it, and only a runtime + * with it runs in a box. `version` is the box release it uses on AgentCore Runtime, one this CLI + * supports (`boxRelease.json`): build and deploy ship its Linux build in a CodeZip runtime's + * zip, and a container image downloads it (under `agentcore dev` too). Without a version, the + * runtime uses the default release. `agentcore create` writes the default. `agentcore dev` runs a + * CodeZip agent with the `box` on your PATH instead. */ - box: z.object({ version: BoxVersionSchema }).optional(), + box: z.object({ version: BoxVersionSchema.optional() }).optional(), envVars: z.array(EnvVarSchema).optional(), networkMode: NetworkModeSchema.optional(), networkConfig: NetworkConfigSchema.optional(),