From 24d7002a52e5c22242544a44bedf83e57be4c7b4 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 13:49:07 -0800 Subject: [PATCH 1/9] fix(box): Build for --region, stream the box download notice, and drop BOX_MINIMUM_VERSION Addresses the review of #2850: - agentcore build --region ignored the flag: the handler passed no region and boxBuildRegion read only the environment. build takes the region now, and resolveRegion takes an environment, so boxBuildRegion goes. - The box download notice waited until staging ended; eventsWhile yields it when the download starts. - BOX_MINIMUM_VERSION goes: the box features and the profiles the CLI writes change together, so only the pinned box is supported. --- README.md | 5 +- docs/box-local-testing.md | 17 +++-- src/core/project/backends/boxRelease.test.ts | 10 +-- src/core/project/backends/boxRelease.ts | 21 +----- src/core/project/backends/cdk.test.ts | 37 +++++++++- src/core/project/backends/cdk.ts | 74 ++++++++++++++------ src/core/project/boxProfileResolver.test.ts | 11 +-- src/core/project/boxProfileResolver.ts | 14 ++-- src/core/project/manager.boxNetwork.test.ts | 11 +++ src/core/project/manager.tsx | 33 ++++----- src/core/region.ts | 14 ++-- src/handlers/project/build/index.test.ts | 16 +++++ src/handlers/project/build/index.ts | 6 +- src/handlers/project/shortcuts.ts | 2 +- src/handlers/project/types.ts | 8 ++- 15 files changed, 170 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index 65dab78c2b..6691613152 100644 --- a/README.md +++ b/README.md @@ -210,9 +210,8 @@ to a Box project, and refuses a TypeScript runtime and a Bedrock Agent import th box profile; build and deploy stop without them. Build derives the AgentCore Runtime profile of each runtime from its local profile. box comes from the public GitHub release `v0.1.11-preview.10` of [mquang-amazon/box-releases](https://github.com/mquang-amazon/box-releases). No token or account -is needed to download it. When that release has no build for your machine, use the build of -`v0.1.11-linux-preview.7`, or of a later release that has one, for `agentcore dev` and the profile -checks of `build`. +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. `bun scripts/bump-box-release.ts --box ` diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index adf6f7c225..343ca04216 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -41,10 +41,9 @@ to it. [aws/agentcore-l3-cdk-constructs#470](https://github.com/aws/agentcore-l3-cdk-constructs/pull/470), as its `box-integration` branch does. The Box gateway that `create` writes has `enableApplicationLogs`, and an older L3 refuses it at synth with a `ConfigValidationError`. -- `box` `0.1.11-preview.10` on your `PATH`, the release the CLI pins. The oldest box that - works is `0.1.11-linux-preview.7`, the first release with - [strands-agents/staging-boxy#625](https://github.com/strands-agents/staging-boxy/pull/625), which - the default telemetry target of the AgentCore Runtime profile needs. Build, deploy and dev run it +- `box` `0.1.11-preview.10` on your `PATH`, the release the CLI pins. Use that release: the box + features and the profiles that the CLI writes change together, so an older box can refuse the + profiles. The CLI does not check the version of the box on your `PATH` yet. Build, deploy and dev run it to read the box profile with `box profile show --format json --full`, and CodeZip dev runs the agent with it. See [Install box](#install-box). - AWS credentials for a **dev or test** account. Build writes the Box gateway's Bedrock and @@ -104,8 +103,8 @@ box --version - `which box` must name the folder you unpacked into. An older `box` earlier on your `PATH` (a source build, or Box Core's `box` in `/usr/local/bin`) wins otherwise. - `box --version` should print the pinned `box 0.1.11-preview.10` (from - `src/core/project/backends/boxRelease.json`). Build, deploy and dev accept - `0.1.11-linux-preview.7` or later. + `src/core/project/backends/boxRelease.json`). An older box can refuse the profiles that the CLI + writes. - On macOS, if Gatekeeper refuses to run `box`, clear the download flag with `xattr -dr com.apple.quarantine "$HOME/.local/share/box/0.1.11-preview.10"`. @@ -320,10 +319,10 @@ box --version aws sts get-caller-identity ``` -- `box --version` must print `0.1.11-linux-preview.7` or later. Dev and build read the profile with +- `box --version` must print the pinned version. Dev and build read the profile with `box profile show --format json --full`. The AgentCore Runtime profile signs each Box gateway backend for `${{ inputs.aws.region }}`, and its default telemetry target reads one key of - `OTEL_EXPORTER_OTLP_LOGS_HEADERS`. A box release before it cannot do all of these. + `OTEL_EXPORTER_OTLP_LOGS_HEADERS`. An older box release cannot do all of these. - The `[default]` profile must hold fresh credentials, because box reads them when dev starts. After you refresh them, restart dev. @@ -593,7 +592,7 @@ These outlive the stack. Delete them too: - **Dev says `'box' was not found on your PATH`.** Download the build for your machine from the box release, unpack it into a folder, add that folder to your `PATH`, then retry. - **Dev or build says Box `cannot print the profile ... as JSON`.** The `box` on your `PATH` is - older than `0.1.11-linux-preview.7`. Install that release or later. + older than the pinned release. Install the pinned release. - **Box says `box's own packs were not found; set BOX_RESOURCES`.** A stale `BOX_RESOURCES` is set. Run `unset BOX_RESOURCES`, or open a new terminal. - **Dev starts but model calls fail with `ExpiredTokenException`.** Your `[default]` credentials diff --git a/src/core/project/backends/boxRelease.test.ts b/src/core/project/backends/boxRelease.test.ts index 02fb2b3866..953656de7f 100644 --- a/src/core/project/backends/boxRelease.test.ts +++ b/src/core/project/backends/boxRelease.test.ts @@ -9,7 +9,6 @@ import { InvalidEnvironmentError } from "../../../errors/errors"; import { type ProcessRunner, runProcess } from "../../../io/exec"; import { BOX_INSTALL_HINT, - BOX_MINIMUM_VERSION, BOX_RELEASE, BOX_RELEASE_PAGE, type BoxRelease, @@ -275,7 +274,6 @@ describe("publishInstall", () => { describe("the pinned releases", () => { test("pins one box, with the asset of its own version and a SHA-256", () => { - expect(BOX_MINIMUM_VERSION).toBe("0.1.11-linux-preview.7"); expect(BOX_RELEASE.linux.asset).toBe( `box-v${BOX_RELEASE.version}-aarch64-unknown-linux-gnu.tar.gz`, ); @@ -285,15 +283,11 @@ describe("the pinned releases", () => { ); }); - test("the install hint names the pinned release, and the first release for a machine it has no build for", () => { - // 0.1.11-linux-preview.7 is the first release that reads the profiles the CLI writes. + test("the install hint names the pinned release", () => { expect(BOX_INSTALL_HINT).toBe( "Install box: download the build for your machine from " + `https://github.com/mquang-amazon/box-releases/releases/tag/v${BOX_RELEASE.version}, unpack it ` + - "into a folder (tar -xzf -C ), and add that folder to your PATH. When that " + - "release has no build for your machine, use box 0.1.11-linux-preview.7 " + - "(https://github.com/mquang-amazon/box-releases/releases/tag/v0.1.11-linux-preview.7) or a " + - "later release that has one.", + "into a folder (tar -xzf -C ), and add that folder to your PATH.", ); }); }); diff --git a/src/core/project/backends/boxRelease.ts b/src/core/project/backends/boxRelease.ts index c2ea0aa8cb..fac45660d7 100644 --- a/src/core/project/backends/boxRelease.ts +++ b/src/core/project/backends/boxRelease.ts @@ -43,27 +43,9 @@ export type BoxRelease = z.infer; const PINNED = z.object({ box: BoxReleaseSchema }).parse(pinned); export const BOX_RELEASE: BoxRelease = PINNED.box; -/** - * The first box release that reads the profiles that the CLI writes: their `@box/` packs, and - * the `key` of an input of the `@box/agentcore` pack. - */ -export const BOX_MINIMUM_VERSION = "0.1.11-linux-preview.7"; - /** 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}`; -/** - * The GitHub release page of {@link BOX_MINIMUM_VERSION}, which has a macOS build. A local box runs - * only `agentcore dev` and the profile checks of build, so a box of this release or a later one - * does, also when the pinned release has no build for the machine. - */ -export const BOX_MINIMUM_RELEASE_PAGE = `https://github.com/${BOX_RELEASE.repo}/releases/tag/v${BOX_MINIMUM_VERSION}`; - -/** What to install when the pinned release has no build for the machine. */ -export const BOX_OTHER_MACHINE_HINT = - `When that release has no build for your machine, use box ${BOX_MINIMUM_VERSION} ` + - `(${BOX_MINIMUM_RELEASE_PAGE}) or a later release that has one.`; - /** Where a release's asset downloads from: the public GitHub release, no token needed. */ export function boxReleaseAssetUrl( release: Pick, @@ -85,8 +67,7 @@ export const BOX_BINARIES = [ */ export const BOX_INSTALL_HINT = `Install box: download the build for your machine from ${BOX_RELEASE_PAGE}, unpack it into ` + - "a folder (tar -xzf -C ), and add that folder to your PATH. " + - BOX_OTHER_MACHINE_HINT; + "a folder (tar -xzf -C ), and add that folder to your PATH."; /** A Linux arm64 box for AgentCore Runtime. */ export type BoxLinuxBuild = { diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 8466da265f..cf3b5011cf 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -10,7 +10,7 @@ import { BOX_RELEASE } from "./boxRelease"; import { ProjectRuntimeSchema } from "../../../projectSchemas/runtime"; import { createSilentLogger } from "../../../testing"; import { TransactionSearchSetupError } from "../../../errors"; -import { boxOtelWarnings, CdkBackend } from "./cdk"; +import { boxOtelWarnings, CdkBackend, eventsWhile } from "./cdk"; import type { CredentialProviderCalls, CredentialProvisionInput, @@ -1790,3 +1790,38 @@ describe("CdkBackend.resolveProjectResources", () => { ).toEqual([["gateway", "gw", ["owned", "second"]]]); }); }); + +describe("eventsWhile", () => { + test("yields an event as soon as the work emits it, before the work ends", async () => { + let finish!: () => void; + const events = eventsWhile(async (emit) => { + emit({ type: "step", message: "downloading box" }); + await new Promise((resolve) => (finish = resolve)); + }); + + // The work is still waiting, so the first event arrives without it. + expect(await events.next()).toEqual({ + done: false, + value: { type: "step", message: "downloading box" }, + }); + finish(); + expect(await events.next()).toEqual({ done: true, value: undefined }); + }); + + test("throws the work's error after the events it emitted first", async () => { + const seen: ProjectEvent[] = []; + const failure = new Error("download failed"); + + const run = async () => { + for await (const event of eventsWhile(async (emit) => { + emit({ type: "step", message: "downloading box" }); + throw failure; + })) { + seen.push(event); + } + }; + + await expect(run()).rejects.toBe(failure); + expect(seen).toEqual([{ type: "step", message: "downloading box" }]); + }); +}); diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index ea65fd5ad2..c4737d59c6 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -228,10 +228,10 @@ export class CdkBackend implements ProjectBackend { // Local prerequisites for synth. Checked before any AWS mutation so a missing // toolchain or dependencies fails without having provisioned credentials. - private async ensureCdkDependencies( + private async *ensureCdkDependencies( project: Project, boxNetworks: BuildBackendInput["boxNetworks"], - ): Promise { + ): AsyncGenerator { const cdkDir = this.cdkDirectory(project); if (!existsSync(join(cdkDir, "node_modules"))) { throw new ProjectStateError( @@ -241,23 +241,21 @@ export class CdkBackend implements ProjectBackend { } await this.checkTool("npm", "Install Node.js: https://nodejs.org/"); // The zip carries box and the image its box profile, so both are staged before synth packages - // the code. The box release downloads only when a CodeZip runtime runs in a box. - const events: ProjectEvent[] = []; - const box = async (version: string | undefined) => { - const release = await boxReleaseFor(version); - return resolveBoxLinuxBuild(this.processEnv, { - runner: this.runner, - release, - onDownload: (download) => - events.push({ - type: "step", - message: boxDownloadMessage(download, "AgentCore Runtime"), - }), - }); - }; - await stageBoxCodeZip(project, boxNetworks, box); - await stageBoxContainers(project, boxNetworks, boxReleaseFor); - return events; + // 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* eventsWhile(async (emit) => { + const box = async (version: string | undefined) => { + const release = await boxReleaseFor(version); + return resolveBoxLinuxBuild(this.processEnv, { + runner: this.runner, + release, + onDownload: (download) => + emit({ type: "step", message: boxDownloadMessage(download, "AgentCore Runtime") }), + }); + }; + await stageBoxCodeZip(project, boxNetworks, box); + await stageBoxContainers(project, boxNetworks, boxReleaseFor); + }); } private async *synthesize( @@ -265,7 +263,7 @@ export class CdkBackend implements ProjectBackend { explainUndeployedCredentials: boolean, boxNetworks: BuildBackendInput["boxNetworks"], ): AsyncGenerator { - yield* await this.ensureCdkDependencies(project, boxNetworks); + yield* this.ensureCdkDependencies(project, boxNetworks); for (const message of boxOtelWarnings(project.spec)) yield { type: "warning", message }; @@ -321,7 +319,7 @@ export class CdkBackend implements ProjectBackend { // Fail on local setup errors (missing toolchain/deps) and malformed state // before any AWS mutation, so a local problem never leaves credentials // provisioned or the stack ARN unrecorded. - yield* await this.ensureCdkDependencies(project, input.boxNetworks); + yield* this.ensureCdkDependencies(project, input.boxNetworks); // Read before provisioning rewrites the credentials map: it is the only record // of what this target provisioned, so it is the only way to find a provider whose @@ -807,3 +805,37 @@ export class CdkBackend implements ProjectBackend { return join(this.cdkDirectory(project), "cdk.out"); } } + +/** + * Runs `work`, yielding each event it emits as soon as it emits it, then ends when `work` does. + * An error of `work` is thrown after the events it emitted first. + */ +export async function* eventsWhile( + work: (emit: (event: ProjectEvent) => void) => Promise, +): AsyncGenerator { + const queue: ProjectEvent[] = []; + let wake: (() => void) | undefined; + let done = false; + const notify = () => { + wake?.(); + wake = undefined; + }; + const running = work((event) => { + queue.push(event); + notify(); + }); + const finish = () => { + done = true; + notify(); + }; + running.then(finish, finish); + for (;;) { + while (queue.length > 0) yield queue.shift()!; + if (done) break; + await new Promise((resolve) => { + wake = resolve; + if (queue.length > 0 || done) notify(); + }); + } + await running; +} diff --git a/src/core/project/boxProfileResolver.test.ts b/src/core/project/boxProfileResolver.test.ts index db877f7391..1fa99c31ba 100644 --- a/src/core/project/boxProfileResolver.test.ts +++ b/src/core/project/boxProfileResolver.test.ts @@ -97,11 +97,7 @@ const SHOWN_POLICY = boxReachRules("mcp", "docs", ["docs.example.com"]); /** The last sentence of each error that says to install another box: the pinned release. */ -const INSTALL = - `Install box ${BOX_RELEASE.version} (https://github.com/mquang-amazon/box-releases/releases/tag/v${BOX_RELEASE.version}), then retry. ` + - "When that release has no build for your machine, use box 0.1.11-linux-preview.7 " + - "(https://github.com/mquang-amazon/box-releases/releases/tag/v0.1.11-linux-preview.7) or a later " + - "release that has one."; +const INSTALL = `Install box ${BOX_RELEASE.version} (https://github.com/mquang-amazon/box-releases/releases/tag/v${BOX_RELEASE.version}), then retry.`; /** * `box profile show open --format json --full` for a profile with the routes `auth` and `github` @@ -319,7 +315,7 @@ describe("BoxCliProfileResolver", () => { ); }); - test("says to install the pinned box when a box older than preview.7 refuses an @box/ pack", async () => { + test("says to install the pinned box when an older box refuses an @box/ pack", async () => { // Box 0.1.11-linux-preview.6 wraps its error, here inside the pack name's line. const error = await failure( refusal([ @@ -333,8 +329,7 @@ describe("BoxCliProfileResolver", () => { "Box refused the profile .box/profile.toml:\n" + ' box: error: /work/demo/.box/profile.toml: "@box/base" is\n' + " not a pack name\n" + - "This box is older than 0.1.11-linux-preview.7, the first box that names its packs " + - `@box/. ${INSTALL}`, + `This box is older than the pinned box, which names its packs @box/. ${INSTALL}`, ); }); diff --git a/src/core/project/boxProfileResolver.ts b/src/core/project/boxProfileResolver.ts index 25ccbfbe14..c12e939397 100644 --- a/src/core/project/boxProfileResolver.ts +++ b/src/core/project/boxProfileResolver.ts @@ -9,12 +9,7 @@ import { z } from "zod"; import { InvalidEnvironmentError } from "../../errors/errors"; import { ProcessFailedError, streamProcess, type ProcessStreamer } from "../../io"; import { resolveExecutable } from "../../io/exec"; -import { - BOX_MINIMUM_VERSION, - BOX_OTHER_MACHINE_HINT, - BOX_RELEASE, - BOX_RELEASE_PAGE, -} from "./backends/boxRelease"; +import { BOX_RELEASE, BOX_RELEASE_PAGE } from "./backends/boxRelease"; /** A pack of the profile, at the version Box resolves it to. */ export interface BoxPack { @@ -51,9 +46,9 @@ export interface BoxProfileResolver { } /** What to install, which each error names when the `box` on PATH cannot resolve a profile. */ -const INSTALL_BOX = `Install box ${BOX_RELEASE.version} (${BOX_RELEASE_PAGE}), then retry. ${BOX_OTHER_MACHINE_HINT}`; +const INSTALL_BOX = `Install box ${BOX_RELEASE.version} (${BOX_RELEASE_PAGE}), then retry.`; -/** The refusal of an `@box/` pack by a box older than {@link BOX_MINIMUM_VERSION}. */ +/** The refusal of an `@box/` pack by a box from before those names. */ const OLD_BOX_PACK_NAME = /"@box\/[^"\s]+" is not a pack name/; /** The error of a box that has no `--format` or `--full` option, as clap prints it. */ @@ -190,8 +185,7 @@ export class BoxCliProfileResolver implements BoxProfileResolver { `Box refused the profile ${profilePath}:`, ...lines.map((line) => ` ${line}`), oldBox - ? `This box is older than ${BOX_MINIMUM_VERSION}, the first box that names its packs ` + - `@box/. ${INSTALL_BOX}` + ? `This box is older than the pinned box, which names its packs @box/. ${INSTALL_BOX}` : agent === undefined ? "Fix what Box reports, then retry." : `Run 'uv sync' in ${agent}, then retry.`, diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 006c052d4c..60c8a0b49a 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -922,6 +922,17 @@ describe("build writes the Bedrock and Memory targets for the region it builds f ); }); + test("takes the region build is given over AWS_REGION, as --region does", async () => { + const { manager, root } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } }); + const project = (await manager.resolve({ filePath: root })) as Project; + + await drain(manager.build(project, { region: "ap-northeast-1" })); + + const { targets } = await boxGateway(root); + expect(targets.find(({ name }) => name === "bedrock")).toEqual(bedrockTarget("ap-northeast-1")); + expect((await runtimeProfile(root)).options).toEqual({ bedrock: { region: "ap-northeast-1" } }); + }); + test("has box resolve the profile for that region, from a copy it then removes", async () => { // create wrote the profile for us-west-2, the region `agentcore dev` calls Bedrock in. const { manager, root, box } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } }); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index d7c3b9bbef..6564c75582 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -56,7 +56,7 @@ import { } from "./templates/harness"; import { boxGatewayIamWarnings, type BoxNetwork } from "./boxNetwork"; import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; -import { DEFAULT_REGION, regionFromConfigFile } from "../region"; +import { resolveRegion } from "../region"; import { BoxCliProfileResolver, type BoxProfileResolver } from "./boxProfileResolver"; import { BOX_NETWORK_WRITERS, boxNetworkEdits, writeBoxNetworkFiles } from "./boxNetworkWriters"; import { createProjectTree } from "./templates/project"; @@ -895,7 +895,7 @@ export class FsProjectManager implements ProjectManager { projectSpec, boxInput, scaffoldedPaths, - options.region ?? (await this.boxBuildRegion()), + await resolveRegion(options.region, this.processEnv), ); } catch (err) { await this.discardStaged(scaffoldedPaths); @@ -1626,7 +1626,10 @@ export class FsProjectManager implements ProjectManager { return { spec: result.spec, envEntries: result.envEntries ?? [] }; } - public async *build(project: Project): AsyncGenerator { + public async *build( + project: Project, + options: { region?: string } = {}, + ): AsyncGenerator { assertV1Project(project, "build"); // Half-written project files from an interrupted `agentcore migrate` must not // be synced or synthesized; build has no target, so only that state stops it. @@ -1635,26 +1638,18 @@ export class FsProjectManager implements ProjectManager { for (const message of synced.messages) yield { type: "step", message }; // Every runtime of a Box project runs in a box, so stop before anything is written. validateBoxRuntimes(synced.project.spec); - const boxed = await this.applyBoxNetwork(synced.project, "build", await this.boxBuildRegion()); + // The region build writes the Box gateway's `bedrock` and `agentcore` targets and the + // AgentCore Runtime profiles for: --region, else AWS_REGION, AWS_DEFAULT_REGION, the AWS config + // file, then DEFAULT_REGION. Deploy uses its target's region instead. + const boxed = await this.applyBoxNetwork( + synced.project, + "build", + await resolveRegion(options.region, this.processEnv), + ); yield* boxed.events; yield* this.backendFor(project).build(boxed.project, { boxNetworks: boxed.networks }); } - /** - * The region `agentcore build` writes the Box gateway's `bedrock` and `agentcore` targets and the - * AgentCore Runtime profile for, as the first deploy picks the default target's: AWS_REGION, - * then AWS_DEFAULT_REGION, then the active profile's region in the shared AWS config file, then - * DEFAULT_REGION. Deploy uses its target's region instead. - */ - private async boxBuildRegion(): Promise { - return ( - this.processEnv.AWS_REGION || - this.processEnv.AWS_DEFAULT_REGION || - (await regionFromConfigFile(this.processEnv)) || - DEFAULT_REGION - ); - } - /** * Builds the Box network model of each box runtime from the box profile as Box resolves it * (`box profile show --format json --full`) for `region`, then writes what the Box network diff --git a/src/core/region.ts b/src/core/region.ts index afc4b223e2..40293521ea 100644 --- a/src/core/region.ts +++ b/src/core/region.ts @@ -47,14 +47,18 @@ export async function regionFromConfigFile( /** * Picks the effective AWS region: an explicit --region value, then * AWS_REGION / AWS_DEFAULT_REGION, then the shared config file, finally - * DEFAULT_REGION. It always resolves to a value. + * DEFAULT_REGION. The variables and the config file come from `env`. It always + * resolves to a value. */ -export async function resolveRegion(flagRegion: string | undefined): Promise { +export async function resolveRegion( + flagRegion: string | undefined, + env: NodeJS.ProcessEnv = process.env, +): Promise { return ( flagRegion || - process.env.AWS_REGION || - process.env.AWS_DEFAULT_REGION || - (await regionFromConfigFile()) || + env.AWS_REGION || + env.AWS_DEFAULT_REGION || + (await regionFromConfigFile(env)) || DEFAULT_REGION ); } diff --git a/src/handlers/project/build/index.test.ts b/src/handlers/project/build/index.test.ts index a538889f88..298e0af576 100644 --- a/src/handlers/project/build/index.test.ts +++ b/src/handlers/project/build/index.test.ts @@ -43,6 +43,7 @@ function testBuildCommand(options: TestBuildOptions = {}) { return { io, + core, run: (args: string[] = []) => root.route(["node", "agentcore", "build", ...args]), }; } @@ -75,6 +76,21 @@ describe("project build handler", () => { expect(subject.io.stdout()).toBe(""); }); + test("builds for the region --region names", async () => { + const subject = testBuildCommand(); + const build = subject.core.projectManager.build.bind(subject.core.projectManager); + const regions: (string | undefined)[] = []; + subject.core.projectManager.build = (project, options) => { + regions.push(options?.region); + return build(project, options); + }; + await inProject(); + + await subject.run(["--region", "eu-west-1"]); + + expect(regions).toEqual(["eu-west-1"]); + }); + test("renders the success message as JSON with --json", async () => { const subject = testBuildCommand(); await inProject(); diff --git a/src/handlers/project/build/index.ts b/src/handlers/project/build/index.ts index 30fc419e49..ca8001c223 100644 --- a/src/handlers/project/build/index.ts +++ b/src/handlers/project/build/index.ts @@ -1,7 +1,7 @@ import { createHandler, ProjectKey, type Middleware } from "../../../router"; import type { AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; -import { JsonKey } from "../../keys"; +import { JsonKey, RegionKey } from "../../keys"; import { renderJsonError, reportMessage } from "../../utils"; import type { Project, ProjectManager } from "../types"; @@ -32,7 +32,9 @@ export const createBuildProjectHandler = (config: BuildProjectHandlerConfig) => // carries it on failure). --json forces the plain path so no ANSI // reaches a scripted caller's stderr. try { - await runWithProgress(config.projectManager.build(project), { + // withRegion resolved --region, else the environment and the AWS config file. + const region = ctx.value(RegionKey); + await runWithProgress(config.projectManager.build(project, { region }), { io: config.io, interactive: jsonOutput ? false : undefined, }); diff --git a/src/handlers/project/shortcuts.ts b/src/handlers/project/shortcuts.ts index 4fc90438e6..cd2f84a3fc 100644 --- a/src/handlers/project/shortcuts.ts +++ b/src/handlers/project/shortcuts.ts @@ -31,7 +31,7 @@ export function getDefaultMemorySpec(runtimeName: string): Memory { * The Bedrock region of the box profile `agentcore create` writes when the caller passes no * region. Both create paths pass the region they resolved. Build and deploy write the Box * gateway's `bedrock` and `agentcore` targets, and the AgentCore Runtime profile, for the region - * they build for instead (see `boxBuildRegion`). + * they build for instead (`--region`, else `resolveRegion`). */ export const DEFAULT_EGRESS_BEDROCK_REGION = "us-west-2"; diff --git a/src/handlers/project/types.ts b/src/handlers/project/types.ts index ccdd53e199..43a22f2810 100644 --- a/src/handlers/project/types.ts +++ b/src/handlers/project/types.ts @@ -569,8 +569,12 @@ export interface ProjectManager { /** Scaffold a new AgentCore project from the given template. */ create(input: CreateProjectInput): AsyncGenerator; - /** Compile the project's CDK app and synthesize its CloudFormation templates. */ - build(project: Project): AsyncGenerator; + /** + * Compile the project's CDK app and synthesize its CloudFormation templates. `region` is the + * region build builds for, which the Box gateway's targets and Runtime profiles take; without + * it, build resolves the region as `--region` does with no flag. + */ + build(project: Project, options?: { region?: string }): AsyncGenerator; /** * Re-derives runtime build settings (build, dockerfile, runtimeVersion, From e485dcbda5adae01fd2c4856a4fbb57ad5b6a309 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 13:50:08 -0800 Subject: [PATCH 2/9] test(region): Pass every input of regionFromConfigFile through env, with static imports Addresses the review of #2852: the tests now give AWS_CONFIG_FILE, AWS_PROFILE, and both home variables through env, check that process.env is not read and that HOME comes before USERPROFILE, and cover the order resolveRegion takes. --- src/core/region.test.ts | 127 ++++++++++++++++++++++++++++++---------- 1 file changed, 96 insertions(+), 31 deletions(-) diff --git a/src/core/region.test.ts b/src/core/region.test.ts index cd3d0b125e..643596b20c 100644 --- a/src/core/region.test.ts +++ b/src/core/region.test.ts @@ -1,5 +1,8 @@ -import { describe, expect, test } from "bun:test"; -import { regionFlagFromArgv } from "./region"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DEFAULT_REGION, regionFlagFromArgv, regionFromConfigFile, resolveRegion } from "./region"; describe("regionFlagFromArgv", () => { test("extracts --region ", () => { @@ -23,45 +26,107 @@ describe("regionFlagFromArgv", () => { }); }); +const folders: string[] = []; +afterEach(() => Promise.all(folders.splice(0).map((f) => rm(f, { recursive: true, force: true })))); + +/** A new folder that afterEach removes. */ +async function folder(): Promise { + const path = await mkdtemp(join(tmpdir(), "agentcore-region-")); + folders.push(path); + return path; +} + +/** An AWS config file with `text`, in a new folder. */ +async function configFile(text: string): Promise { + const path = join(await folder(), "config"); + await writeFile(path, text); + return path; +} + +/** A home folder whose ~/.aws/config holds `text`. */ +async function homeWithConfig(text: string): Promise { + const home = await folder(); + await mkdir(join(home, ".aws")); + await writeFile(join(home, ".aws", "config"), text); + return home; +} + +const CONFIG = "[default]\nregion = us-east-1\n\n[profile work]\nregion = eu-west-2\n"; + describe("regionFromConfigFile", () => { test("returns undefined when the config file lacks the profile's region", async () => { - const { mkdtemp, rm, writeFile } = await import("node:fs/promises"); - const { tmpdir } = await import("node:os"); - const { join } = await import("node:path"); - const dir = await mkdtemp(join(tmpdir(), "agentcore-region-")); - const savedConfigFile = process.env.AWS_CONFIG_FILE; - const savedProfile = process.env.AWS_PROFILE; + const config = await configFile( + "[profile other]\nregion = eu-west-1\n\n[default]\noutput = json\n", + ); + + expect(await regionFromConfigFile({ AWS_CONFIG_FILE: config })).toBeUndefined(); + }); + + test("reads the default profile of the AWS_CONFIG_FILE of the environment it is given", async () => { + const config = await configFile(CONFIG); + + expect(await regionFromConfigFile({ AWS_CONFIG_FILE: config })).toBe("us-east-1"); + }); + + test("reads the AWS_PROFILE of the environment it is given", async () => { + const config = await configFile(CONFIG); + + expect(await regionFromConfigFile({ AWS_CONFIG_FILE: config, AWS_PROFILE: "work" })).toBe( + "eu-west-2", + ); + }); + + test("reads none of AWS_CONFIG_FILE, AWS_PROFILE, and the home folder from process.env", async () => { + const saved = { ...process.env }; try { - const path = join(dir, "config"); - await writeFile(path, "[profile other]\nregion = eu-west-1\n\n[default]\noutput = json\n"); - process.env.AWS_CONFIG_FILE = path; - delete process.env.AWS_PROFILE; - const { regionFromConfigFile } = await import("./region"); - expect(await regionFromConfigFile()).toBeUndefined(); + process.env.AWS_CONFIG_FILE = await configFile("[profile work]\nregion = ap-south-1\n"); + process.env.AWS_PROFILE = "work"; + process.env.HOME = await homeWithConfig("[default]\nregion = ap-south-1\n"); + const home = await homeWithConfig("[default]\nregion = sa-east-1\n"); + + expect(await regionFromConfigFile({ HOME: home })).toBe("sa-east-1"); } finally { - if (savedConfigFile === undefined) delete process.env.AWS_CONFIG_FILE; - else process.env.AWS_CONFIG_FILE = savedConfigFile; - if (savedProfile === undefined) delete process.env.AWS_PROFILE; - else process.env.AWS_PROFILE = savedProfile; - await rm(dir, { recursive: true, force: true }); + for (const name of ["AWS_CONFIG_FILE", "AWS_PROFILE", "HOME"]) { + if (saved[name] === undefined) delete process.env[name]; + else process.env[name] = saved[name]; + } } }); test.each(["HOME", "USERPROFILE"] as const)( "reads ~/.aws/config under the %s of the environment it is given", async (variable) => { - const { mkdir, mkdtemp, rm, writeFile } = await import("node:fs/promises"); - const { tmpdir } = await import("node:os"); - const { join } = await import("node:path"); - const home = await mkdtemp(join(tmpdir(), "agentcore-region-home-")); - try { - await mkdir(join(home, ".aws")); - await writeFile(join(home, ".aws", "config"), "[default]\nregion = eu-west-2\n"); - const { regionFromConfigFile } = await import("./region"); - expect(await regionFromConfigFile({ [variable]: home })).toBe("eu-west-2"); - } finally { - await rm(home, { recursive: true, force: true }); - } + const home = await homeWithConfig("[default]\nregion = eu-west-2\n"); + + expect(await regionFromConfigFile({ [variable]: home })).toBe("eu-west-2"); }, ); + + test("takes HOME over USERPROFILE", async () => { + const home = await homeWithConfig("[default]\nregion = eu-west-2\n"); + const profile = await homeWithConfig("[default]\nregion = us-east-2\n"); + + expect(await regionFromConfigFile({ HOME: home, USERPROFILE: profile })).toBe("eu-west-2"); + }); +}); + +describe("resolveRegion", () => { + test("takes the flag, then AWS_REGION, AWS_DEFAULT_REGION, and the config file", async () => { + const env = { + AWS_REGION: "us-east-2", + AWS_DEFAULT_REGION: "eu-central-1", + AWS_CONFIG_FILE: await configFile(CONFIG), + }; + + expect(await resolveRegion("ap-northeast-1", env)).toBe("ap-northeast-1"); + expect(await resolveRegion(undefined, env)).toBe("us-east-2"); + expect(await resolveRegion(undefined, { ...env, AWS_REGION: undefined })).toBe("eu-central-1"); + expect(await resolveRegion(undefined, { AWS_CONFIG_FILE: env.AWS_CONFIG_FILE })).toBe( + "us-east-1", + ); + }); + + test("falls back to DEFAULT_REGION when the environment names no region", async () => { + expect(await resolveRegion(undefined, { HOME: await folder() })).toBe(DEFAULT_REGION); + }); }); From 08fb943206eed0a256d94fe42bc5d7edc802e957 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 14:15:34 -0800 Subject: [PATCH 3/9] fix(box): Address the review of #2857 - Revert the trailing newline five non-box gitignore.template files gained, so their output matches v1.x. - agent-python-strands-box keeps only the two files that differ (its Dockerfile and .gitignore); the resolver lays them over agent-python-strands. - Each box shortcut is a spread of its twin, so a change to one reaches both. - The empty .venv is part of the box CodeZip files (boxCodeZipFiles), which create and add runtime both write, not a --skip-install branch of create. - The LangChain README says traces are not collected when the agent runs in a box. - renderBoxProfile takes its region; the unused us-west-2 fallback goes, and its JSDoc says where box starts for a CodeZip agent. - Two tests use test.each. --- .../a2a-python-strands/gitignore.template | 2 +- .../agent-python-langchain/README.md | 5 + .../agent-python-langchain/gitignore.template | 2 +- .../agent-python-strands-box/README.md | 68 ----- .../dockerignore.template | 27 -- .../agent-python-strands-box/main.py | 65 ----- .../memory/__init__.py | 0 .../memory/session.py | 29 --- .../model/__init__.py | 1 - .../agent-python-strands-box/model/load.py | 169 ------------ .../agent-python-strands-box/parse.py | 41 --- .../agent-python-strands-box/pyproject.toml | 19 -- .../agent-python-strands/gitignore.template | 2 +- .../agui-python-strands/gitignore.template | 2 +- .../mcp-python-fastmcp/gitignore.template | 2 +- src/core/dev/box.test.ts | 2 +- src/core/project/manager.boxNetwork.test.ts | 2 + src/core/project/manager.test.ts | 33 +-- src/core/project/manager.tsx | 47 ++-- src/core/project/templates/boxProfile.test.ts | 53 ++-- src/core/project/templates/boxProfile.ts | 17 +- src/core/project/templates/fsTree.ts | 12 + src/core/project/templates/project.ts | 25 +- src/core/project/templates/runtime.test.ts | 44 +++- src/core/project/templates/runtime.ts | 47 ++-- src/handlers/project/shortcuts.ts | 244 ++++++++---------- 26 files changed, 288 insertions(+), 672 deletions(-) delete mode 100644 src/assets/templates/agent-python-strands-box/README.md delete mode 100644 src/assets/templates/agent-python-strands-box/dockerignore.template delete mode 100644 src/assets/templates/agent-python-strands-box/main.py delete mode 100644 src/assets/templates/agent-python-strands-box/memory/__init__.py delete mode 100644 src/assets/templates/agent-python-strands-box/memory/session.py delete mode 100644 src/assets/templates/agent-python-strands-box/model/__init__.py delete mode 100644 src/assets/templates/agent-python-strands-box/model/load.py delete mode 100644 src/assets/templates/agent-python-strands-box/parse.py delete mode 100644 src/assets/templates/agent-python-strands-box/pyproject.toml diff --git a/src/assets/templates/a2a-python-strands/gitignore.template b/src/assets/templates/a2a-python-strands/gitignore.template index fa1c60aeac..f36f968a0f 100644 --- a/src/assets/templates/a2a-python-strands/gitignore.template +++ b/src/assets/templates/a2a-python-strands/gitignore.template @@ -38,4 +38,4 @@ env/ # OS .DS_Store -Thumbs.db +Thumbs.db \ No newline at end of file diff --git a/src/assets/templates/agent-python-langchain/README.md b/src/assets/templates/agent-python-langchain/README.md index edda56d76b..280f2ce6ad 100644 --- a/src/assets/templates/agent-python-langchain/README.md +++ b/src/assets/templates/agent-python-langchain/README.md @@ -35,9 +35,14 @@ agentcore deploy agentcore invoke --runtime {{name}} --payload '{"prompt":"Hello!"}' ``` +{{#if box}} +Traces are not collected yet: the agent runs in a box, which `opentelemetry-instrument` does not +reach, so `agentcore create` sets `instrumentation.enableOtel` to `false` for this runtime. +{{else}} Traces are collected automatically: AgentCore Runtime starts the agent under `opentelemetry-instrument`, which picks up `opentelemetry-instrumentation-langchain` from the dependencies. +{{/if}} ## Extending diff --git a/src/assets/templates/agent-python-langchain/gitignore.template b/src/assets/templates/agent-python-langchain/gitignore.template index fa1c60aeac..f36f968a0f 100644 --- a/src/assets/templates/agent-python-langchain/gitignore.template +++ b/src/assets/templates/agent-python-langchain/gitignore.template @@ -38,4 +38,4 @@ env/ # OS .DS_Store -Thumbs.db +Thumbs.db \ No newline at end of file diff --git a/src/assets/templates/agent-python-strands-box/README.md b/src/assets/templates/agent-python-strands-box/README.md deleted file mode 100644 index 214088ffcb..0000000000 --- a/src/assets/templates/agent-python-strands-box/README.md +++ /dev/null @@ -1,68 +0,0 @@ -This is a project generated by the AgentCore CLI! - -# Layout - -The generated application code lives at the agent root directory. At the root, there is a `.gitignore` file, an -`agentcore/` folder which represents the configurations and state associated with this project. Other `agentcore` -commands like `deploy`, `dev`, and `invoke` rely on the configuration stored here. - -## Agent Root - -The main entrypoint to your app is defined in `main.py`. Using the AgentCore SDK `@app.entrypoint` decorator, this -file defines a Starlette ASGI app with the Strands Agent SDK running within. - -`model/load.py` instantiates the chosen model provider. - -## Memory - -The template provisions semantic and episodic memory. `memory/session.py` retrieves up to three -semantic facts for the actor and five episodes for the current session. The default -`relevance_score=0.0` selects results by `top_k` without score filtering. To opt into score -filtering, increase `relevance_score` in the retrieval configuration. - -## Input Validation - -Validate invocation input before forwarding it to Strands. Keep plain prompts typed as strings. If the app accepts a -caller-supplied message history, retain `_strip_trailing_tool_use()` in `parse.py`, which normalizes the history tail -before invoking the agent. - -## Payload - -The Runtime accepts a JSON object. `parse_payload()` reads: - -- `prompt` (string) — a single user message. Used when `messages` is absent; defaults to `""`. -- `messages` (array) — a full conversation history (`[{"role": ..., "content": [...]}]`). Takes precedence over `prompt`; trailing `toolUse` blocks are stripped before the agent runs. -- `actorId` (string, optional) — identifies the end user for Memory scoping (e.g. `/users/{actorId}/facts`). Defaults to `"default"`. - -Provide either `prompt` or `messages`. The `session_id` is not in the body — it comes from the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header (`context.session_id`); reuse it to continue a conversation. - -```json -{ "prompt": "What's the weather?", "actorId": "user-123" } -``` - -## Environment Variables - -| Variable | Required | Description | -| --- | --- | --- | -{{#if identityProviders.[0]}}| `{{identityProviders.[0].envVarName}}` | Local only | {{modelProvider}} API key read from `.env.local` | -| `{{identityProviders.[0].providerNameEnvVarName}}` | Deployed only | Identity provider name injected by deployment | -{{/if}}| `LOCAL_DEV` | No | Set to `1` to use `.env.local` instead of AgentCore Identity | - -# Developing locally - -If installation was successful, a virtual environment is already created with dependencies installed. - -Activate the environment with `source .venv/bin/activate` on macOS/Linux, `.venv\Scripts\activate.bat` in Windows -Command Prompt, or `.\.venv\Scripts\activate.ps1` in Windows PowerShell. - -`agentcore dev` will start a local server on 0.0.0.0:8080. - -# Deployment - -After providing credentials, `agentcore deploy` will deploy your project into Amazon Bedrock AgentCore. - -Invoke the deployed Runtime with its native payload: - -```bash -agentcore invoke --runtime {{name}} --payload '{"prompt":"Hello!"}' -``` diff --git a/src/assets/templates/agent-python-strands-box/dockerignore.template b/src/assets/templates/agent-python-strands-box/dockerignore.template deleted file mode 100644 index a0c4eb6584..0000000000 --- a/src/assets/templates/agent-python-strands-box/dockerignore.template +++ /dev/null @@ -1,27 +0,0 @@ -# Python -__pycache__/ -*.py[cod] -*.egg-info/ -.venv/ -dist/ -build/ - -# IDE -.vscode/ -.idea/ - -# Testing -.pytest_cache/ -.coverage -htmlcov/ - -# Secrets and environment files -.env -.env.* - -# Version control -.git/ - -# AgentCore build artifacts -.agentcore/artifacts/ -*.zip diff --git a/src/assets/templates/agent-python-strands-box/main.py b/src/assets/templates/agent-python-strands-box/main.py deleted file mode 100644 index ffd55b88ec..0000000000 --- a/src/assets/templates/agent-python-strands-box/main.py +++ /dev/null @@ -1,65 +0,0 @@ -from functools import lru_cache - -from strands import Agent, tool -from strands.agent.conversation_manager.null_conversation_manager import NullConversationManager -from bedrock_agentcore.runtime import BedrockAgentCoreApp -from model.load import load_model -from parse import parse_payload -from memory.session import get_memory_session_manager - -DEFAULT_SYSTEM_PROMPT = "You are a helpful assistant. Use tools when appropriate." - -# Define a collection of tools used by the model -tools = [] - -# Define a simple function tool -@tool -def add_numbers(a: int, b: int) -> int: - """Return the sum of two numbers""" - return a + b - -tools.append(add_numbers) - -def _make_conversation_manager(): - return NullConversationManager() - -@lru_cache(maxsize=128) -def _get_agent(session_id: str, actor_id: str) -> Agent: - """Given a session_id and actor_id, return or construct the corresponding Strands agent. - Note: caching helps avoid repeated identity fetches on non-bedrock model loads - and supports in-memory session management for local dev.""" - return Agent( - model=load_model(), - session_manager=get_memory_session_manager(session_id, actor_id), - conversation_manager=_make_conversation_manager(), - system_prompt=DEFAULT_SYSTEM_PROMPT, - tools=tools, - ) - -def create_app(): - app = BedrockAgentCoreApp() - log = app.logger - - @app.entrypoint - async def invoke(payload, context): - log.info("Invoking Agent.....") - - session_id = getattr(context, "session_id", None) or "default-session" - prompt, actor_id = parse_payload(payload) - - log.info(f"Invoking with session_id={session_id} and actor_id={actor_id}") - agent = _get_agent(session_id, actor_id) - - async for event in agent.stream_async(prompt): - if not isinstance(event, dict) or "event" not in event: - continue - cbs = event["event"].get("contentBlockStart") - if cbs is not None and not cbs.get("start"): - continue - yield event - - return app - -app = create_app() -if __name__ == "__main__": - app.run() diff --git a/src/assets/templates/agent-python-strands-box/memory/__init__.py b/src/assets/templates/agent-python-strands-box/memory/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/assets/templates/agent-python-strands-box/memory/session.py b/src/assets/templates/agent-python-strands-box/memory/session.py deleted file mode 100644 index baa569eb90..0000000000 --- a/src/assets/templates/agent-python-strands-box/memory/session.py +++ /dev/null @@ -1,29 +0,0 @@ -import os -from typing import Optional - -from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig -from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager - -MEMORY_ID = os.getenv("{{memoryEnvVarName}}") -REGION = os.getenv("AWS_REGION") - -def get_memory_session_manager( - session_id: str, actor_id: str, -) -> Optional[AgentCoreMemorySessionManager]: - if not MEMORY_ID: - return None - - retrieval_config = { - f"/users/{actor_id}/facts": RetrievalConfig(top_k=3, relevance_score=0.0), - f"/episodes/{actor_id}/{session_id}": RetrievalConfig(top_k=5, relevance_score=0.0), - } - - return AgentCoreMemorySessionManager( - AgentCoreMemoryConfig( - memory_id=MEMORY_ID, - session_id=session_id, - actor_id=actor_id, - retrieval_config=retrieval_config, - ), - REGION, - ) diff --git a/src/assets/templates/agent-python-strands-box/model/__init__.py b/src/assets/templates/agent-python-strands-box/model/__init__.py deleted file mode 100644 index 0e632e10c6..0000000000 --- a/src/assets/templates/agent-python-strands-box/model/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Package marker diff --git a/src/assets/templates/agent-python-strands-box/model/load.py b/src/assets/templates/agent-python-strands-box/model/load.py deleted file mode 100644 index 20d92388d2..0000000000 --- a/src/assets/templates/agent-python-strands-box/model/load.py +++ /dev/null @@ -1,169 +0,0 @@ -{{#if (eq modelProvider "Bedrock")}} -from strands.models.bedrock import BedrockModel - - -def load_model() -> BedrockModel: - """Get Bedrock model client using IAM credentials.""" - return BedrockModel(model_id={{safeJson modelId}}) -{{/if}} -{{#if (eq modelProvider "Anthropic")}} -import os - -from strands.models.anthropic import AnthropicModel -from bedrock_agentcore.identity.auth import requires_api_key - -IDENTITY_PROVIDER_NAME = os.environ.get("{{identityProviders.[0].providerNameEnvVarName}}", "{{identityProviders.[0].name}}") -IDENTITY_ENV_VAR = "{{identityProviders.[0].envVarName}}" - - -@requires_api_key(provider_name=IDENTITY_PROVIDER_NAME) -def _agentcore_identity_api_key_provider(api_key: str) -> str: - """Fetch API key from AgentCore Identity.""" - return api_key - - -def _get_api_key() -> str: - """ - Uses AgentCore Identity for API key management in deployed environments. - For local development, run via 'agentcore dev' which loads agentcore/.env. - """ - if os.getenv("LOCAL_DEV") == "1": - api_key = os.getenv(IDENTITY_ENV_VAR) - if not api_key: - raise RuntimeError( - f"{IDENTITY_ENV_VAR} not found. Add {IDENTITY_ENV_VAR}=your-key to .env.local" - ) - return api_key - return _agentcore_identity_api_key_provider() - - -def load_model() -> AnthropicModel: - """Get authenticated Anthropic model client.""" - return AnthropicModel( - client_args={"api_key": _get_api_key()}, - model_id={{safeJson modelId}}, - max_tokens=5000, - ) -{{/if}} -{{#if (or (eq modelProvider "OpenAI") (eq modelProvider "OpenAICompatible"))}} -import os - -from strands.models.openai import OpenAIModel -from bedrock_agentcore.identity.auth import requires_api_key - -IDENTITY_PROVIDER_NAME = os.environ.get("{{identityProviders.[0].providerNameEnvVarName}}", "{{identityProviders.[0].name}}") -IDENTITY_ENV_VAR = "{{identityProviders.[0].envVarName}}" - - -@requires_api_key(provider_name=IDENTITY_PROVIDER_NAME) -def _agentcore_identity_api_key_provider(api_key: str) -> str: - """Fetch API key from AgentCore Identity.""" - return api_key - - -def _get_api_key() -> str: - """ - Uses AgentCore Identity for API key management in deployed environments. - For local development, run via 'agentcore dev' which loads agentcore/.env. - """ - if os.getenv("LOCAL_DEV") == "1": - api_key = os.getenv(IDENTITY_ENV_VAR) - if not api_key: - raise RuntimeError( - f"{IDENTITY_ENV_VAR} not found. Add {IDENTITY_ENV_VAR}=your-key to .env.local" - ) - return api_key - return _agentcore_identity_api_key_provider() - - -def load_model() -> OpenAIModel: - """Get authenticated OpenAI model client.""" - return OpenAIModel( - client_args={"api_key": _get_api_key(){{#if apiBase}}, "base_url": {{safeJson apiBase}}{{/if~}} }, - model_id={{safeJson modelId}}, - ) -{{/if}} -{{#if (eq modelProvider "Gemini")}} -import os - -from strands.models.gemini import GeminiModel -from bedrock_agentcore.identity.auth import requires_api_key - -IDENTITY_PROVIDER_NAME = os.environ.get("{{identityProviders.[0].providerNameEnvVarName}}", "{{identityProviders.[0].name}}") -IDENTITY_ENV_VAR = "{{identityProviders.[0].envVarName}}" - - -@requires_api_key(provider_name=IDENTITY_PROVIDER_NAME) -def _agentcore_identity_api_key_provider(api_key: str) -> str: - """Fetch API key from AgentCore Identity.""" - return api_key - - -def _get_api_key() -> str: - """ - Uses AgentCore Identity for API key management in deployed environments. - For local development, run via 'agentcore dev' which loads agentcore/.env. - """ - if os.getenv("LOCAL_DEV") == "1": - api_key = os.getenv(IDENTITY_ENV_VAR) - if not api_key: - raise RuntimeError( - f"{IDENTITY_ENV_VAR} not found. Add {IDENTITY_ENV_VAR}=your-key to .env.local" - ) - return api_key - return _agentcore_identity_api_key_provider() - - -def load_model() -> GeminiModel: - """Get authenticated Gemini model client.""" - return GeminiModel( - client_args={"api_key": _get_api_key()}, - model_id={{safeJson modelId}}, - ) -{{/if}} -{{#if (eq modelProvider "LiteLLM")}} -{{#if identityProviders.[0].name}} -import os - -{{/if}} -from strands.models.litellm import LiteLLMModel -{{#if identityProviders.[0].name}} -from bedrock_agentcore.identity.auth import requires_api_key - -IDENTITY_PROVIDER_NAME = os.environ.get("{{identityProviders.[0].providerNameEnvVarName}}", "{{identityProviders.[0].name}}") -IDENTITY_ENV_VAR = "{{identityProviders.[0].envVarName}}" - - -@requires_api_key(provider_name=IDENTITY_PROVIDER_NAME) -def _agentcore_identity_api_key_provider(api_key: str) -> str: - """Fetch API key from AgentCore Identity.""" - return api_key - - -def _get_api_key() -> str: - """ - Uses AgentCore Identity for API key management in deployed environments. - For local development, run via 'agentcore dev' which loads agentcore/.env. - """ - if os.getenv("LOCAL_DEV") == "1": - api_key = os.getenv(IDENTITY_ENV_VAR) - if not api_key: - raise RuntimeError( - f"{IDENTITY_ENV_VAR} not found. Add {IDENTITY_ENV_VAR}=your-key to .env.local" - ) - return api_key - return _agentcore_identity_api_key_provider() -{{/if}} - - -def load_model() -> LiteLLMModel: - """Get a LiteLLM model client (proxies to the provider encoded in model_id).""" - client_args = {} - {{#if identityProviders.[0].name}} - client_args["api_key"] = _get_api_key() - {{/if}} - return LiteLLMModel( - client_args=client_args, - model_id={{safeJson modelId}}, - ) -{{/if}} diff --git a/src/assets/templates/agent-python-strands-box/parse.py b/src/assets/templates/agent-python-strands-box/parse.py deleted file mode 100644 index e0b63f729e..0000000000 --- a/src/assets/templates/agent-python-strands-box/parse.py +++ /dev/null @@ -1,41 +0,0 @@ -from typing import Any - -def _strip_trailing_tool_use(messages: Any) -> list[dict]: - """Strip toolUse blocks from the tail until the last message has none.""" - if not isinstance(messages, list): - raise ValueError("messages must be a list") - - messages = list(messages) - while messages: - last = messages[-1] - if not isinstance(last, dict): - raise ValueError("each message must be an object") - original_content = last.get("content", []) - if not isinstance(original_content, list) or not all(isinstance(block, dict) for block in original_content): - raise ValueError("each message content value must be a list of content blocks") - - content = [block for block in original_content if "toolUse" not in block] - if len(content) == len(original_content): - break - if content: - messages[-1] = {**last, "content": content} - break - messages.pop() - - return messages - -def parse_payload(payload: dict): - """Accept a caller-supplied message history or a plain prompt string.""" - if not isinstance(payload, dict): - raise ValueError("payload must be a JSON object") - actor_id = payload.get("actorId", "default") - if not isinstance(actor_id, str): - raise ValueError("actorId must be a string") - if not actor_id: - actor_id = "default" - if "messages" in payload: - return _strip_trailing_tool_use(payload["messages"]), actor_id - prompt = payload.get("prompt", "") - if not isinstance(prompt, str): - raise ValueError("prompt must be a string") - return prompt, actor_id diff --git a/src/assets/templates/agent-python-strands-box/pyproject.toml b/src/assets/templates/agent-python-strands-box/pyproject.toml deleted file mode 100644 index 2ded30441e..0000000000 --- a/src/assets/templates/agent-python-strands-box/pyproject.toml +++ /dev/null @@ -1,19 +0,0 @@ -[build-system] -requires = ["hatchling ~= 1.27.0"] -build-backend = "hatchling.build" - -[project] -name = "{{ name }}" -version = "0.1.0" -description = "AgentCore Runtime Application using Strands SDK" -readme = "README.md" -requires-python = ">=3.10" -dependencies = [ - "aws-opentelemetry-distro ~= 0.21.0", - "bedrock-agentcore[strands-agents] >= 1.18.1, < 2.0.0", - "botocore[crt] ~= 1.43.0", - "strands-agents{{#if (eq modelProvider "Anthropic")}}[anthropic]{{else}}{{#if (or (eq modelProvider "OpenAI") (eq modelProvider "OpenAICompatible"))}}[openai]{{else}}{{#if (eq modelProvider "Gemini")}}[gemini]{{else}}{{#if (eq modelProvider "LiteLLM")}}[litellm]{{/if}}{{/if}}{{/if}}{{/if}} >= 1.62.0, < 2.0.0", -] - -[tool.hatch.build.targets.wheel] -packages = ["."] diff --git a/src/assets/templates/agent-python-strands/gitignore.template b/src/assets/templates/agent-python-strands/gitignore.template index fa1c60aeac..f36f968a0f 100644 --- a/src/assets/templates/agent-python-strands/gitignore.template +++ b/src/assets/templates/agent-python-strands/gitignore.template @@ -38,4 +38,4 @@ env/ # OS .DS_Store -Thumbs.db +Thumbs.db \ No newline at end of file diff --git a/src/assets/templates/agui-python-strands/gitignore.template b/src/assets/templates/agui-python-strands/gitignore.template index fa1c60aeac..f36f968a0f 100644 --- a/src/assets/templates/agui-python-strands/gitignore.template +++ b/src/assets/templates/agui-python-strands/gitignore.template @@ -38,4 +38,4 @@ env/ # OS .DS_Store -Thumbs.db +Thumbs.db \ No newline at end of file diff --git a/src/assets/templates/mcp-python-fastmcp/gitignore.template b/src/assets/templates/mcp-python-fastmcp/gitignore.template index fa1c60aeac..f36f968a0f 100644 --- a/src/assets/templates/mcp-python-fastmcp/gitignore.template +++ b/src/assets/templates/mcp-python-fastmcp/gitignore.template @@ -38,4 +38,4 @@ env/ # OS .DS_Store -Thumbs.db +Thumbs.db \ No newline at end of file diff --git a/src/core/dev/box.test.ts b/src/core/dev/box.test.ts index 7acbb9bccf..faed731363 100644 --- a/src/core/dev/box.test.ts +++ b/src/core/dev/box.test.ts @@ -194,7 +194,7 @@ describe("BoxDevRunner", () => { const runtime = resolveRuntimeTemplateShortcut("agent-python-strands-box", { runtimeName: "agent", }); - const noComments = renderBoxProfile("Demo", runtime)! + const noComments = renderBoxProfile("Demo", runtime, "us-west-2")! .split("\n") .filter((line) => !line.startsWith("#")) .join("\n"); diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 60c8a0b49a..fcb2f5f819 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -169,6 +169,8 @@ async function strandsProject( scaffoldRuntimeInput: resolveRuntimeTemplateShortcut("agent-python-strands-box", { runtimeName: "agent_python_strands", }), + // As the create command does: the profile calls Bedrock in the region create resolved. + region: "us-west-2", skipInstall: true, skipGit: true, }), diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 99f66dc187..2ec6006f60 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -626,32 +626,25 @@ describe("FsProjectManager.create", () => { expect(skipInstall.checkedTools).toEqual(["git"]); }); - test("with --skip-install, makes an empty .venv only for a CodeZip box agent", async () => { + // box drops the profile's optional .venv deny_write while the folder is missing, and then refuses + // the profile, as the venv's Python would be under the project's write grant. A container's image + // builds its own venv, and an agent outside a box has no profile. + test.each([ + ["a CodeZip box agent", AGENT_PYTHON_STRANDS_BOX, true], + ["a container box agent", AGENT_PYTHON_STRANDS_BOX_CONTAINER, false], + ["an agent outside a box", AGENT_PYTHON, false], + ] as const)("makes an empty .venv for %s: %p", async (_, runtime, made) => { const directory = await inTempDirectory(); - const venv = (name: string, runtime: { runtimeName: string }) => - join(directory, name, "app", runtime.runtimeName, ".venv"); - // box drops the profile's optional .venv deny_write while the folder is missing, and then - // refuses the profile, as the venv's Python would be under the project's write grant. await runCreate(manager().manager, { - name: "codezip", - scaffoldRuntimeInput: AGENT_PYTHON_STRANDS_BOX, + name: "demo", + scaffoldRuntimeInput: runtime, skipInstall: true, }); - expect(readdirSync(venv("codezip", AGENT_PYTHON_STRANDS_BOX))).toEqual([]); - // A container's image builds its own venv, and an agent outside a box has no profile. - for (const [name, runtime] of [ - ["container", AGENT_PYTHON_STRANDS_BOX_CONTAINER], - ["plain", AGENT_PYTHON], - ] as const) { - await runCreate(manager().manager, { - name, - scaffoldRuntimeInput: runtime, - skipInstall: true, - }); - expect(existsSync(venv(name, runtime))).toBe(false); - } + const venv = join(directory, "demo", "app", runtime.runtimeName, ".venv"); + expect(existsSync(venv)).toBe(made); + if (made) expect(readdirSync(venv)).toEqual([]); }); test("fails before writing files when box is not on PATH, with the install hint", async () => { diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 6564c75582..67f6497dde 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1,7 +1,7 @@ import { existsSync } from "node:fs"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; -import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { isDeepStrictEqual } from "node:util"; import semver from "semver"; import type { @@ -59,7 +59,7 @@ import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; import { resolveRegion } from "../region"; import { BoxCliProfileResolver, type BoxProfileResolver } from "./boxProfileResolver"; import { BOX_NETWORK_WRITERS, boxNetworkEdits, writeBoxNetworkFiles } from "./boxNetworkWriters"; -import { createProjectTree } from "./templates/project"; +import { boxCodeZipFiles, createProjectTree } from "./templates/project"; import { BOX_CODEZIP_ENTRYPOINT, boxAgentDir, @@ -603,18 +603,15 @@ export class FsProjectManager implements ProjectManager { const appDir = join(destination, "app", scaffoldRuntimeInput.runtimeName); yield* this.ensureLockFileExists(appDir); } - if (input.skipInstall && scaffoldRuntimeInput && startsInBoxOnCodeZip(scaffoldRuntimeInput)) { - // The box profile keeps the venv out of the project's write grant with an optional - // deny_write, which box drops while `.venv` is missing; box then refuses the profile, as the - // venv's Python would be writable. An empty `.venv` keeps the profile valid, and `uv sync` - // fills it later. - await mkdir(join(destination, "app", scaffoldRuntimeInput.runtimeName, ".venv"), { - recursive: true, - }); - } - if (scaffoldRuntimeInput) { - yield* this.writeBoxProfile(destination, input.name, scaffoldRuntimeInput, input.region); + // Both create paths pass the region they resolved; without one, create resolves it as + // --region does with no flag. + yield* this.writeBoxProfile( + destination, + input.name, + scaffoldRuntimeInput, + input.region ?? (await resolveRegion(undefined, this.processEnv)), + ); } if (!input.skipGit) { @@ -2136,24 +2133,14 @@ export class FsProjectManager implements ProjectManager { runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; projectSpec.agentCoreGateways.push(AgentCoreGatewaySchema.parse(boxGatewaySpec(name))); + // start.py and an empty .venv, as create writes them. A file or folder the user has stays. const appDir = join(projectRoot, ...runtime.codeLocation.split("/")); - const startScript = join(appDir, BOX_CODEZIP_ENTRYPOINT); - if (!existsSync(startScript)) { - scaffoldedPaths.push(startScript); - await writeFile( - startScript, - await this.assetSource.read(`templates/box-codezip/${BOX_CODEZIP_ENTRYPOINT}`), - { flag: "wx" }, - ); - } - // The profile keeps the venv out of the write grant with an optional deny_write, which box - // drops while `.venv` is missing, and then refuses the profile. An empty `.venv` keeps the - // profile valid until `uv sync` fills it. const venv = join(appDir, ".venv"); - if (!existsSync(venv)) { - scaffoldedPaths.push(venv); - await mkdir(venv, { recursive: true }); - } + if (!existsSync(venv)) scaffoldedPaths.push(venv); + await FsTreeNode.createDirectory(basename(appDir), boxCodeZipFiles(this.assetSource)).write( + dirname(appDir), + { skipExisting: true, written: scaffoldedPaths }, + ); const boxFolder = join(projectRoot, ...boxAgentDir(name).split("/")); if (!existsSync(boxFolder)) scaffoldedPaths.push(boxFolder); yield* this.writeBoxProfile(projectRoot, projectSpec.name, boxInput, region); @@ -2188,7 +2175,7 @@ export class FsProjectManager implements ProjectManager { projectRoot: string, projectName: string, runtime: ScaffoldRuntimeInput, - region: string | undefined, + region: string, ): AsyncGenerator { const text = renderBoxProfile(projectName, runtime, region); if (text === undefined) return; diff --git a/src/core/project/templates/boxProfile.test.ts b/src/core/project/templates/boxProfile.test.ts index b4f65b42a3..a3fe500f1f 100644 --- a/src/core/project/templates/boxProfile.test.ts +++ b/src/core/project/templates/boxProfile.test.ts @@ -18,6 +18,9 @@ import { } from "./boxProfile"; /** The scaffold input of a box template, as create resolves it from the shortcut table. */ +/** The region create resolves in these tests, where `agentcore dev` calls Bedrock. */ +const REGION = "us-west-2"; + function template(name: RuntimeTemplateShortcutName, overrides: Record = {}) { const runtime = resolveRuntimeTemplateShortcut(name, { runtimeName: "agent", ...overrides }); // The shortcut entry itself marks it a box template; the tests do not force it. @@ -26,7 +29,10 @@ function template(name: RuntimeTemplateShortcutName, overrides: Record = {}) { - return parse(renderBoxProfile("V3Demo", template(name, overrides))!) as Record; + return parse(renderBoxProfile("V3Demo", template(name, overrides), REGION)!) as Record< + string, + any + >; } const STRANDS = template("agent-python-strands-box"); @@ -62,7 +68,7 @@ const UVICORN = [ describe("renderBoxProfile", () => { test("runs the Strands agent from the project's venv, reached through ingress", () => { - expect(parse(renderBoxProfile("V3Demo", STRANDS)!) as unknown).toEqual({ + expect(parse(renderBoxProfile("V3Demo", STRANDS, REGION)!) as unknown).toEqual({ packs: ["@box/base", "@box/bedrock"], profile: { name: "V3Demo-agent" }, project: { access: "write" }, @@ -81,7 +87,7 @@ describe("renderBoxProfile", () => { test("names itself after the project and the runtime, and the folder `agentcore dev` starts box in", () => { // box keeps one profile of each name on a machine, and each runtime has its own local profile. expect(profile("agent-python-minimal-box").profile).toEqual({ name: "V3Demo-agent" }); - const text = renderBoxProfile("V3Demo", STRANDS)!; + const text = renderBoxProfile("V3Demo", STRANDS, REGION)!; expect(text).toContain("runs `box run ../../.box/agent/local/profile.toml` there"); }); @@ -109,7 +115,7 @@ describe("renderBoxProfile", () => { }); test("names no host path, so the profile works on any machine and after a move", () => { - const text = renderBoxProfile("V3Demo", STRANDS)!; + const text = renderBoxProfile("V3Demo", STRANDS, REGION)!; expect(text).not.toContain(process.cwd()); expect(text).not.toMatch(/"\/(Users|home)\//); }); @@ -236,7 +242,7 @@ describe("renderBoxProfile", () => { "reads a LiteLLM %s key created without --api-key from LiteLLM's own variable", (modelId, route, variable) => { const runtime = template("agent-python-strands-box", { modelProvider: "LiteLLM", modelId }); - const { egress } = parse(renderBoxProfile("V3Demo", runtime)!) as { + const { egress } = parse(renderBoxProfile("V3Demo", runtime, REGION)!) as { egress: Record; }; expect(egress[route]?.secret.ref).toBe(`env://${variable}`); @@ -294,7 +300,7 @@ describe("renderBoxProfile", () => { }), apiBase: undefined, }; - const text = renderBoxProfile("V3Demo", runtime)!; + const text = renderBoxProfile("V3Demo", runtime, REGION)!; expect(text).not.toContain("api.openai.com"); expect((parse(text) as { egress?: unknown }).egress).toBeUndefined(); }); @@ -323,7 +329,7 @@ describe("renderBoxProfile", () => { ] as const)("writes no profile for %s, which is not a box template", (name) => { const runtime = resolveRuntimeTemplateShortcut(name); expect(hasBoxProfile(runtime)).toBe(false); - expect(renderBoxProfile("V3Demo", runtime)).toBeUndefined(); + expect(renderBoxProfile("V3Demo", runtime, REGION)).toBeUndefined(); }); }); @@ -381,22 +387,23 @@ describe("runtimeAgentTemplate", () => { }); describe("startsInBoxOnCodeZip", () => { - test("starts only the CodeZip box template in a box", () => { - const plain = (name: RuntimeTemplateShortcutName) => resolveRuntimeTemplateShortcut(name); - expect(startsInBoxOnCodeZip(plain("agent-python-strands-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("agent-python-minimal-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("agent-python-minimal"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("agent-python-langchain-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("agent-python-langchain"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("a2a-python-strands-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("a2a-python-strands"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("agui-python-strands-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("agui-python-strands"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("agent-python-strands"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("mcp-python-fastmcp"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("mcp-python-fastmcp-box"))).toBe(true); - expect(startsInBoxOnCodeZip(plain("agent-python-strands-box-container"))).toBe(false); - expect(startsInBoxOnCodeZip(plain("agent-typescript-strands"))).toBe(false); + test.each<[RuntimeTemplateShortcutName, boolean]>([ + ["agent-python-strands-box", true], + ["agent-python-minimal-box", true], + ["agent-python-langchain-box", true], + ["a2a-python-strands-box", true], + ["agui-python-strands-box", true], + ["mcp-python-fastmcp-box", true], + ["agent-python-strands-box-container", false], + ["agent-python-minimal", false], + ["agent-python-langchain", false], + ["a2a-python-strands", false], + ["agui-python-strands", false], + ["agent-python-strands", false], + ["mcp-python-fastmcp", false], + ["agent-typescript-strands", false], + ])("%s starts in a box on CodeZip: %p", (name, starts) => { + expect(startsInBoxOnCodeZip(resolveRuntimeTemplateShortcut(name))).toBe(starts); }); }); diff --git a/src/core/project/templates/boxProfile.ts b/src/core/project/templates/boxProfile.ts index 231f59ed81..c89b77844e 100644 --- a/src/core/project/templates/boxProfile.ts +++ b/src/core/project/templates/boxProfile.ts @@ -1,8 +1,5 @@ import { join, posix } from "node:path"; -import { - DEFAULT_EGRESS_BEDROCK_REGION, - callsBedrockModel, -} from "../../../handlers/project/shortcuts"; +import { callsBedrockModel } from "../../../handlers/project/shortcuts"; import type { ScaffoldRuntimeInput } from "../../../handlers/project/types"; import { credentialEnvVarName } from "../../../projectSchemas/credential"; import { memoryEnvVarName } from "../../../projectSchemas/memory"; @@ -431,16 +428,16 @@ function runtimeCodeZipRunner(protocol: Protocol, appDir: string, workloadPort: /** * The box profile that `agentcore dev` runs for the scaffolded agent, or `undefined` when the * template has none. It holds no host path: box fills `${{ workspace }}` (the folder `box run` - * starts in) and `${{ home }}` at run time. On a Mac, box starts in the project root and names no - * interpreter, only the folder of every uv-managed Python, so it is the same with and without - * `--skip-install`. The agent calls Bedrock in `region`, the one create resolved. The container - * template's runs in its dev image, in /app. Build and deploy derive the AgentCore Runtime profile - * from it (runtimeProfile/derive.ts). + * starts in) and `${{ home }}` at run time. For a CodeZip agent, box starts in the runtime's + * folder, `app/`, and the profile names no interpreter, only the folder of every + * uv-managed Python, so it is the same with and without `--skip-install`. The agent calls Bedrock + * in `region`, the one create resolved. The container template's runs in its dev image, in /app. + * Build and deploy derive the AgentCore Runtime profile from it (runtimeProfile/derive.ts). */ export function renderBoxProfile( projectName: string, runtime: ScaffoldRuntimeInput, - region: string = DEFAULT_EGRESS_BEDROCK_REGION, + region: string, ) { if (!hasBoxProfile(runtime)) return undefined; diff --git a/src/core/project/templates/fsTree.ts b/src/core/project/templates/fsTree.ts index f1c5e7cbed..0bc3b68137 100644 --- a/src/core/project/templates/fsTree.ts +++ b/src/core/project/templates/fsTree.ts @@ -72,6 +72,18 @@ export class FsTreeNode { return written; } + /** + * Puts each node of `nodes` in place of the child of its name, or after the children when no + * child has its name. + */ + replaceChildren(nodes: readonly FsTreeNode[]): void { + for (const node of nodes) { + const index = this.children.findIndex((child) => child.name === node.name); + if (index === -1) this.children.push(node); + else this.children[index] = node; + } + } + static createFile(name: string, bytes: () => Promise): FsTreeNode { return new FsTreeNode(name, false, [], bytes); } diff --git a/src/core/project/templates/project.ts b/src/core/project/templates/project.ts index 289a98e30f..110d607665 100644 --- a/src/core/project/templates/project.ts +++ b/src/core/project/templates/project.ts @@ -92,18 +92,25 @@ export async function createProjectTree( } /** - * Starts the runtime's agent in a box on a CodeZip deploy: start.py, the - * entry point, runs `box run` with what deploy stages. Create alone writes it, - * because only create writes the box profiles. + * The files a CodeZip box runtime's folder needs, which create and add runtime write: + * - start.py, the Runtime's entry point: it sets HOME and a writable workspace, exports the Python + * and code paths the @box/agentcore-codezip pack reads, then execs `box run`. No start.sh. + * - an empty `.venv`. The box profile keeps the venv out of the write grant with an optional + * deny_write, which box drops while `.venv` is missing, and box then refuses the profile, as the + * venv's Python would be writable. `uv sync` fills the empty folder. */ -function withBoxStartScript(config: CreateProjectConfig, template: Template): void { - // start.py is the Runtime's entry point: it sets HOME and a writable workspace, exports the - // Python and code paths the @box/agentcore-codezip pack reads, then execs `box run`. No start.sh. - template.tree.children.push( +export function boxCodeZipFiles(assetSource: AssetSource): FsTreeNode[] { + return [ FsTreeNode.createFile(BOX_CODEZIP_ENTRYPOINT, () => - config.assetSource.read(`templates/box-codezip/${BOX_CODEZIP_ENTRYPOINT}`), + assetSource.read(`templates/box-codezip/${BOX_CODEZIP_ENTRYPOINT}`), ), - ); + FsTreeNode.createDirectory(".venv", []), + ]; +} + +/** Starts the runtime's agent in a box on a CodeZip deploy, with {@link boxCodeZipFiles}. */ +function withBoxStartScript(config: CreateProjectConfig, template: Template): void { + template.tree.children.push(...boxCodeZipFiles(config.assetSource)); for (const runtime of template.spec.runtimes ?? []) { runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; // The box release build and deploy ship; change it to move to another release. dev runs the diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index e7632bf00e..036a2951f1 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { join } from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import { join, relative } from "node:path"; import { initProject, TestCoreClient } from "../../../testing"; import { toAddRuntimeInput, type RuntimeInput } from "../../../handlers/project/add/runtime"; import { @@ -112,6 +113,47 @@ describe("runtime templates", () => { expect(runtime.instrumentation?.enableOtel ?? true).toBe(enableOtel); }); + // A box template is the Strands template with two files of agent-python-strands-box in place. + test("agent-python-strands-box-container writes the Strands files, with its own Dockerfile and .gitignore", async () => { + const files = async (dir: string) => + Object.fromEntries( + await Promise.all( + (await readdir(dir, { recursive: true, withFileTypes: true })) + .filter((entry) => entry.isFile()) + .map(async (entry) => { + const path = relative(dir, join(entry.parentPath, entry.name)).replaceAll("\\", "/"); + return [path, await readFile(join(dir, path), "utf8")] as const; + }), + ), + ); + const plain = await files( + (await addTemplate("my_agent", "agent-python-strands-container")).appDir, + ); + const box = await files( + (await addTemplate("my_agent", "agent-python-strands-box-container")).appDir, + ); + + expect(Object.keys(box).sort()).toEqual(Object.keys(plain).sort()); + const { Dockerfile: boxDockerfile, ".gitignore": boxGitignore, ...rest } = box; + const { Dockerfile: plainDockerfile, ".gitignore": plainGitignore, ...plainRest } = plain; + expect(rest).toEqual(plainRest); + expect(boxDockerfile).toContain("box run"); + expect(plainDockerfile).not.toContain("box run"); + expect(boxGitignore).toContain(".box-dist/"); + expect(plainGitignore).not.toContain(".box-dist/"); + }); + + test.each<[RuntimeTemplateShortcutName, string]>([ + ["agent-python-langchain", "Traces are collected automatically"], + ["agent-python-langchain-box", "Traces are not collected yet"], + ])("%s's README says whether traces are collected", async (template, sentence) => { + const { appDir } = await addTemplate("my_agent", template); + const readme = await readFile(join(appDir, "README.md"), "utf8"); + + expect(readme).toContain(sentence); + expect(readme).not.toContain("{{"); + }); + test("Bedrock Managed Agents keeps infrastructure overrides and its required policy", async () => { const { runtime, appDir, core } = await addTemplate("my_bma", "environment-python-bma", { infra: { diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 05722b94da..10e9315288 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -262,7 +262,11 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa { rootDirName: input.name, transformContent: (raw) => - templateRenderer.render(raw, { name: toPythonPackageName(input.name) }), + templateRenderer.render(raw, { + name: toPythonPackageName(input.name), + // The README says whether traces are collected, which they are not in a box. + box: input.scaffoldRuntimeInput.boxTemplate === true, + }), }, ); return { @@ -289,26 +293,33 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa entrypoint: "main", }; const isContainer = input.scaffoldRuntimeInput.build === "Container"; + const options = { + rootDirName: input.name, + transformContent: (raw: string) => templateRenderer.render(raw, context), + filter: (name: string) => { + // The memory module is always included: main.py imports it + // unconditionally and it degrades to no memory when its env var is + // absent (the China scaffold omits the memory resource). + if (name === "Dockerfile" || name === ".dockerignore") return isContainer; + return true; + }, + }; const tree = await FsTreeNode.fromAssetSource( { assetSource }, - { - // The box templates have their own folder: its Dockerfile runs the agent with `box run`. - assetDir: input.scaffoldRuntimeInput.boxTemplate - ? "templates/agent-python-strands-box" - : "templates/agent-python-strands", - }, - { - rootDirName: input.name, - transformContent: (raw) => templateRenderer.render(raw, context), - filter: (name) => { - // The memory module is always included: main.py imports it - // unconditionally and it degrades to no memory when its env var is - // absent (the China scaffold omits the memory resource). - if (name === "Dockerfile" || name === ".dockerignore") return isContainer; - return true; - }, - }, + { assetDir: "templates/agent-python-strands" }, + options, ); + if (input.scaffoldRuntimeInput.boxTemplate) { + // A box template is the Strands template with the files of agent-python-strands-box in + // place of its own: a Dockerfile that runs the agent with `box run`, and a .gitignore that + // keeps the staged box out of git. + const box = await FsTreeNode.fromAssetSource( + { assetSource }, + { assetDir: "templates/agent-python-strands-box" }, + options, + ); + tree.replaceChildren(box.children); + } return { tree, spec: mergeSpecEntries([ diff --git a/src/handlers/project/shortcuts.ts b/src/handlers/project/shortcuts.ts index cd2f84a3fc..a1e4e706e8 100644 --- a/src/handlers/project/shortcuts.ts +++ b/src/handlers/project/shortcuts.ts @@ -115,84 +115,128 @@ type RuntimeTemplateShortcut = { profile?: RuntimeTemplateProfile; }; +/** The templates that each have a box twin: the same template, run in Strands Box. */ +const AGENT_PYTHON_MINIMAL = { + runtimeName: "agent_python_minimal", + description: "minimal Python project, no agent framework", + build: "CodeZip", + language: "Python", + framework: "none", + modelProvider: "Bedrock", + includesMemory: false, + box: false, + supportsModelProviderOverride: false, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + +const AGENT_PYTHON_STRANDS = { + runtimeName: "agent_python_strands", + description: "Strands agent with AgentCore Memory, Bedrock or another model provider", + build: "CodeZip", + language: "Python", + framework: "strands", + modelProvider: "Bedrock", + includesMemory: true, + box: false, + supportsModelProviderOverride: true, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + +const AGENT_PYTHON_STRANDS_CONTAINER = { + runtimeName: "agent_python_strands_container", + description: + "Strands agent with AgentCore Memory, Bedrock or another model provider, container-based deployment", + build: "Container", + language: "Python", + framework: "strands", + modelProvider: "Bedrock", + includesMemory: true, + box: false, + supportsModelProviderOverride: true, +} as const satisfies RuntimeTemplateShortcut; + +const AGENT_PYTHON_LANGCHAIN = { + runtimeName: "agent_python_langchain", + description: "LangChain agent with Bedrock for inference", + build: "CodeZip", + language: "Python", + framework: "langchain", + modelProvider: "Bedrock", + includesMemory: false, + box: false, + supportsModelProviderOverride: false, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + +const MCP_PYTHON_FASTMCP = { + runtimeName: "mcp_python_fastmcp", + description: "MCP server exposing tools with FastMCP", + build: "CodeZip", + language: "Python", + framework: "none", + protocol: "MCP", + includesMemory: false, + box: false, + supportsModelProviderOverride: false, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + +const A2A_PYTHON_STRANDS = { + runtimeName: "a2a_python_strands", + description: "Strands agent speaking the A2A protocol, Bedrock or another model provider", + build: "CodeZip", + language: "Python", + framework: "strands", + protocol: "A2A", + modelProvider: "Bedrock", + includesMemory: true, + box: false, + supportsModelProviderOverride: true, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + +const AGUI_PYTHON_STRANDS = { + runtimeName: "agui_python_strands", + description: "Strands agent speaking AG-UI, Bedrock or another model provider", + build: "CodeZip", + language: "Python", + framework: "strands", + protocol: "AGUI", + modelProvider: "Bedrock", + includesMemory: true, + box: false, + supportsModelProviderOverride: true, + runtimeVersion: "PYTHON_3_14", +} as const satisfies RuntimeTemplateShortcut; + /** * The runtime templates. agent-python-strands offers both CodeZip and container * builds; Bedrock Managed Agents is a specialized container-only environment. * Every other template is CodeZip-only. */ export const RUNTIME_TEMPLATE_SHORTCUTS = { - "agent-python-minimal": { - runtimeName: "agent_python_minimal", - description: "minimal Python project, no agent framework", - build: "CodeZip", - language: "Python", - framework: "none", - modelProvider: "Bedrock", - includesMemory: false, - box: false, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", - }, + "agent-python-minimal": AGENT_PYTHON_MINIMAL, "agent-python-minimal-box": { + ...AGENT_PYTHON_MINIMAL, runtimeName: "agent_python_minimal_box", description: "minimal Python project in Strands Box, no agent framework", - build: "CodeZip", - language: "Python", - framework: "none", - modelProvider: "Bedrock", - includesMemory: false, box: true, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", - }, - "agent-python-strands": { - runtimeName: "agent_python_strands", - description: "Strands agent with AgentCore Memory, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - modelProvider: "Bedrock", - includesMemory: true, - box: false, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", - }, - "agent-python-strands-container": { - runtimeName: "agent_python_strands_container", - description: - "Strands agent with AgentCore Memory, Bedrock or another model provider, container-based deployment", - build: "Container", - language: "Python", - framework: "strands", - modelProvider: "Bedrock", - includesMemory: true, - box: false, - supportsModelProviderOverride: true, }, + "agent-python-strands": AGENT_PYTHON_STRANDS, + "agent-python-strands-container": AGENT_PYTHON_STRANDS_CONTAINER, "agent-python-strands-box": { + ...AGENT_PYTHON_STRANDS, runtimeName: "agent_python_strands_box", description: "Strands agent in Strands Box with AgentCore Memory, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - modelProvider: "Bedrock", - includesMemory: true, box: true, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", }, "agent-python-strands-box-container": { + ...AGENT_PYTHON_STRANDS_CONTAINER, runtimeName: "agent_python_strands_box_container", description: "Strands agent in Strands Box with AgentCore Memory, Bedrock or another model provider, container-based deployment", - build: "Container", - language: "Python", - framework: "strands", - modelProvider: "Bedrock", - includesMemory: true, box: true, - supportsModelProviderOverride: true, }, "agent-typescript-strands": { runtimeName: "agent_typescript_strands", @@ -207,29 +251,12 @@ export const RUNTIME_TEMPLATE_SHORTCUTS = { supportsModelProviderOverride: true, runtimeVersion: "NODE_22", }, - "agent-python-langchain": { - runtimeName: "agent_python_langchain", - description: "LangChain agent with Bedrock for inference", - build: "CodeZip", - language: "Python", - framework: "langchain", - modelProvider: "Bedrock", - includesMemory: false, - box: false, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", - }, + "agent-python-langchain": AGENT_PYTHON_LANGCHAIN, "agent-python-langchain-box": { + ...AGENT_PYTHON_LANGCHAIN, runtimeName: "agent_python_langchain_box", description: "LangChain agent in Strands Box with Bedrock for inference", - build: "CodeZip", - language: "Python", - framework: "langchain", - modelProvider: "Bedrock", - includesMemory: false, box: true, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", }, "agent-typescript-vercel": { runtimeName: "agent_typescript_vercel", @@ -255,82 +282,27 @@ export const RUNTIME_TEMPLATE_SHORTCUTS = { supportsModelProviderOverride: false, profile: BMA_TEMPLATE_PROFILE, }, - "mcp-python-fastmcp": { - runtimeName: "mcp_python_fastmcp", - description: "MCP server exposing tools with FastMCP", - build: "CodeZip", - language: "Python", - framework: "none", - protocol: "MCP", - includesMemory: false, - box: false, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", - }, + "mcp-python-fastmcp": MCP_PYTHON_FASTMCP, "mcp-python-fastmcp-box": { + ...MCP_PYTHON_FASTMCP, runtimeName: "mcp_python_fastmcp_box", description: "MCP server exposing tools with FastMCP, in Strands Box", - build: "CodeZip", - language: "Python", - framework: "none", - protocol: "MCP", - includesMemory: false, box: true, - supportsModelProviderOverride: false, - runtimeVersion: "PYTHON_3_14", - }, - "a2a-python-strands": { - runtimeName: "a2a_python_strands", - description: "Strands agent speaking the A2A protocol, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - protocol: "A2A", - modelProvider: "Bedrock", - includesMemory: true, - box: false, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", }, + "a2a-python-strands": A2A_PYTHON_STRANDS, "a2a-python-strands-box": { + ...A2A_PYTHON_STRANDS, runtimeName: "a2a_python_strands_box", description: "Strands agent speaking the A2A protocol in Strands Box, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - protocol: "A2A", - modelProvider: "Bedrock", - includesMemory: true, box: true, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", - }, - "agui-python-strands": { - runtimeName: "agui_python_strands", - description: "Strands agent speaking AG-UI, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - protocol: "AGUI", - modelProvider: "Bedrock", - includesMemory: true, - box: false, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", }, + "agui-python-strands": AGUI_PYTHON_STRANDS, "agui-python-strands-box": { + ...AGUI_PYTHON_STRANDS, runtimeName: "agui_python_strands_box", description: "Strands agent speaking AG-UI in Strands Box, Bedrock or another model provider", - build: "CodeZip", - language: "Python", - framework: "strands", - protocol: "AGUI", - modelProvider: "Bedrock", - includesMemory: true, box: true, - supportsModelProviderOverride: true, - runtimeVersion: "PYTHON_3_14", }, } as const satisfies Record; From 0a84859cb45058e3257a2874933deec0b3b59571 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 14:24:17 -0800 Subject: [PATCH 4/9] fix(box): Say when the shell's credential key differs from the route's, and when build fills a blank one Addresses the review of #2862: - With the credential's reserved variable (AGENTCORE_CREDENTIAL_) set in the environment, deploy provisions it while dev hands box the route's variable. Build now says so when the two hold different keys. - Build filled a blank stored key in .env.local with no message; it says so now, as it does for a different key. --- .../project/boxProfileCredentials.test.ts | 34 +++++++++++++++++-- src/core/project/boxProfileCredentials.ts | 28 +++++++++++---- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index 6c5ec70812..e173efc041 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -131,14 +131,44 @@ describe("planBoxProfileCredentials", () => { } }); - test("leaves the stored key alone when the shell sets the credential's own variable", () => { - // Deploy provisions that one, so the route's variable has nothing to change. + test("fills a blank stored key, and says so", () => { + const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { + env: { GITHUB_TOKEN: "ghp_new" }, + envLocal: { [RESERVED]: " " }, + }); + + expect(plan.entries.map(({ key, value }) => [key, value])).toEqual([[RESERVED, "ghp_new"]]); + expect(plan.messages).toEqual([ + `setting ${RESERVED} in ${ENV_LOCAL_RELATIVE_PATH}, which is blank there, to the key in ` + + "GITHUB_TOKEN, which agentcore dev uses, so deploy provisions it too", + ]); + }); + + test("leaves the stored key alone when the shell sets the credential's own variable, and names a different key", () => { + // Deploy provisions that one, so build stores nothing, but dev hands box the route's variable. const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { env: { GITHUB_TOKEN: "ghp_new", [RESERVED]: "ghp_explicit" }, envLocal: { [RESERVED]: "ghp_old" }, }); expect(plan.entries).toEqual([]); + expect(plan.messages).toEqual([ + `${RESERVED} and GITHUB_TOKEN hold different keys: agentcore dev uses GITHUB_TOKEN, and ` + + `deploy provisions ${RESERVED}, which your environment sets. Unset ${RESERVED}, or give ` + + "both the same key.", + ]); + }); + + test("says nothing when the shell sets the credential's own variable to the route's key", () => { + for (const env of [ + { GITHUB_TOKEN: "ghp_same", [RESERVED]: "ghp_same" }, + { [RESERVED]: "ghp_explicit" }, + ]) { + const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { env, envLocal: {} }); + + expect(plan.entries).toEqual([]); + expect(plan.messages).toEqual([]); + } }); test("keeps an earlier build's credential and says what to set when its key has gone", () => { diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index b289357d47..9f33944320 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -93,24 +93,38 @@ export function planBoxProfileCredentials( const entries: EnvLocalEntry[] = []; /** * Stores the route's key under `credential`'s reserved variable, as `agentcore dev` reads it: the - * route's variable from the environment, else from `.env.local`. A stored key that differs is - * replaced, so dev and deploy use the same key after a rotation. False when there is none. + * route's variable from the environment, else from `.env.local`. A stored key that differs, or a + * blank one, is replaced, so dev and deploy use the same key after a rotation, and says so. When + * the environment sets the reserved variable, deploy provisions that, and a different key in the + * route's variable gets a message. False when there is no key. */ const seed = ({ variable }: BoxEnvRoute, credential: string): boolean => { const key = credentialEnvVarName(credential); - // Set in the environment itself, it is what deploy provisions; nothing to store. - if (hasValue(sources.env[key])) return true; if (entries.some((entry) => entry.key === key)) return true; const value = hasValue(sources.env[variable]) ? sources.env[variable] : sources.envLocal[variable]; + const exported = sources.env[key]; + // Set in the environment itself, it is what deploy provisions; nothing to store. + if (hasValue(exported)) { + if (variable !== key && hasValue(value) && value !== exported) { + messages.push( + `${key} and ${variable} hold different keys: agentcore dev uses ${variable}, and deploy ` + + `provisions ${key}, which your environment sets. Unset ${key}, or give both the same key.`, + ); + } + return true; + } const stored = sources.envLocal[key]; if (!hasValue(value)) return hasValue(stored); if (value === stored) return true; - if (hasValue(stored)) { + if (stored !== undefined) { messages.push( - `updating ${key} in ${ENV_LOCAL_RELATIVE_PATH}: ${variable} holds a different key, which ` + - "agentcore dev uses, so deploy provisions it too", + hasValue(stored) + ? `updating ${key} in ${ENV_LOCAL_RELATIVE_PATH}: ${variable} holds a different key, ` + + "which agentcore dev uses, so deploy provisions it too" + : `setting ${key} in ${ENV_LOCAL_RELATIVE_PATH}, which is blank there, to the key in ` + + `${variable}, which agentcore dev uses, so deploy provisions it too`, ); } entries.push({ From 89b4acff4400e7314ec56611541b91293ed62d3d Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 14:30:02 -0800 Subject: [PATCH 5/9] test(e2e): Address the review of #2865 - Add the egress test on AgentCore Runtime: the egress agent deployed in a box reaches the profile's host through the Box gateway, and box refuses any other. It shares its agent and checks with the dev test. - Install the AGENTCORE_E2E_BOX_CDK build only in projects that deploy; the dev and dev-egress cases have no use for it. - Drop the README sentence that the per-Python cases wait for #2867, which has merged. --- e2eTest/README.md | 16 ++--- e2eTest/project/templates.test.ts | 113 +++++++++++++++++++++++++----- 2 files changed, 105 insertions(+), 24 deletions(-) diff --git a/e2eTest/README.md b/e2eTest/README.md index 2910594f9b..7cab9653b8 100644 --- a/e2eTest/README.md +++ b/e2eTest/README.md @@ -33,8 +33,8 @@ The tests that deploy also need `AGENTCORE_E2E_BOX_CDK`: the pinned `@aws/agentc cannot deploy a Box project yet. Set it to an `@aws/agentcore-cdk` version or a `file:` tarball that can, for example one packed from the `box-integration` branch of [agentcore-l3-cdk-constructs](https://github.com/aws/agentcore-l3-cdk-constructs) with -`npm run build && npm pack --ignore-scripts`. The tests install it in each Box project's -`agentcore/cdk`. Without it, as in CI, they skip. +`npm run build && npm pack --ignore-scripts`. The tests install it in the `agentcore/cdk` of each +Box project that deploys. Without it, as in CI, they skip. The `dev` tests also need a machine where `box run` can start its sandbox, and for the container template a container tool. Box listens on the protocol's fixed port (8080, 8000 or 9000), so the @@ -46,13 +46,13 @@ AGENTCORE_E2E_BOX_CDK=file:/path/to/aws-agentcore-cdk-1.1.0.tgz bun run test:e2e That runs each Box template on its default Python. The CodeZip box template on Python 3.10 to 3.13 (`py_strands_box_3_10` to `py_strands_box_3_13`) is in the runtime templates describe, so it runs -with `--tagsFilter='runtime'` or a full run, given `box` and the same opt-in. Those four cases -pass only once box runs CodeZip agents without the ffi shim (#2867): until then `boxRelease.json` -pins a shim for `PYTHON_3_14` only, so they fail on any machine. +with `--tagsFilter='runtime'` or a full run, given `box` and the same opt-in. -The `box-egress` test checks that box, under `agentcore dev`, lets the agent reach the host its -profile allows (`checkip.amazonaws.com`) and blocks any other (`example.com`). It reaches public -hosts, so the network can make it fail. It retries twice, and `--tagsFilter='box'` leaves it out: +The `box-egress` tests check that box lets the agent reach the host its profile allows +(`checkip.amazonaws.com`) and blocks any other (`example.com`): one under `agentcore dev`, and one +on AgentCore Runtime, where the allowed host's calls go through the runtime's Box gateway. The +second deploys, so it also needs `AGENTCORE_E2E_BOX_CDK`. They reach public hosts, so the network +can make them fail. They retry twice, and `--tagsFilter='box'` leaves them out: ```sh bun run test:e2e -- --tagsFilter='box-egress' diff --git a/e2eTest/project/templates.test.ts b/e2eTest/project/templates.test.ts index 9a1ca5478b..ba58513a47 100644 --- a/e2eTest/project/templates.test.ts +++ b/e2eTest/project/templates.test.ts @@ -276,7 +276,7 @@ describe( TIMEOUT_MS.PROJECT_REMOVE, }, async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime); + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); let scenarioCompleted = false; try { if (!runtime.skipDev) { @@ -363,7 +363,7 @@ describe.skipIf(!BOX_DEPLOYS)( TIMEOUT_MS.PROJECT_REMOVE, }, async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime); + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); let scenarioCompleted = false; try { const deployment = parseResult( @@ -425,7 +425,7 @@ describe.skipIf(!BOX_ON_PATH)( "$name", { timeout: TIMEOUT_MS.PROJECT_CREATE + TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE }, async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime); + const projectDir = await createTemplateProject(cli, runtime, { deploys: false }); const { devOutput } = await invokeLocally( cli, runtime, @@ -489,14 +489,8 @@ describe.skipIf(!BOX_ON_PATH)( }, async () => { const template = runtime; - const projectDir = await createTemplateProject(cli, template); - await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), EGRESS_AGENT); - const profile = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local", "profile.toml"); - const host = new URL(EGRESS_ALLOWED_URL).host; - await writeFile( - profile, - `${await readFile(profile, "utf8")}\n[egress.checkip]\ndestinations = ["${host}"]\n`, - ); + const projectDir = await createTemplateProject(cli, template, { deploys: false }); + await useEgressAgent(projectDir); const { response } = await invokeLocally( cli, @@ -504,14 +498,96 @@ describe.skipIf(!BOX_ON_PATH)( projectDir, BOX_DEV_PORTS[template.protocol], ); - const reply = EgressReplySchema.parse(JSON.parse(response.body)); - expect(reply.allowed).toEqual({ status: 200 }); - expect(reply.blocked.error).toMatch(/403/); + assertEgressReply(response.body); + }, + ); + }, +); + +// The same egress check on AgentCore Runtime, where box sends the allowed host's calls through the +// runtime's Box gateway. It deploys, so it needs the AGENTCORE_E2E_BOX_CDK opt-in as well. +describe.skipIf(!BOX_DEPLOYS)( + "egress on AgentCore Runtime for a Strands Box template", + { tags: [TAGS.BOX_EGRESS] }, + () => { + const cli = new CliRunner(); + const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); + if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case"); + + test( + "allows the profile's host through the Box gateway and blocks any other", + { + retry: 2, + timeout: + TIMEOUT_MS.PROJECT_CREATE + + TIMEOUT_MS.PROJECT_INVOKE + + 2 * TIMEOUT_MS.PROJECT_DEPLOY + + TIMEOUT_MS.PROJECT_REMOVE, + }, + async () => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + await useEgressAgent(projectDir); + let scenarioCompleted = false; + try { + const deployment = parseResult( + DeployResponseSchema, + await cli.run(["deploy", "--yes", "--json"], projectDir), + ); + expect(deployment.message).toContain("deployed project"); + + const response = parseResult( + RuntimeInvokeResponseSchema, + await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--session-id", + getSessionId(`${runtime.name}-egress`), + "--payload", + JSON.stringify(runtime.payload), + "--json", + ], + projectDir, + ), + ); + expect(response.statusCode).toBeGreaterThanOrEqual(200); + expect(response.statusCode).toBeLessThan(300); + assertEgressReply(response.body); + scenarioCompleted = true; + } finally { + // Tear the stack down even when a step above failed. + await cli.run(["remove", "all", "--yes", "--json"], projectDir); + const cleanup = await cli.run(["deploy", "--yes", "--json"], projectDir); + // A cleanup error must not replace the scenario's primary diagnostic. + if (scenarioCompleted) parseResult(JsonObjectSchema, cleanup); + } }, ); }, ); +/** + * Gives the project in `projectDir` the egress agent, and allows its one host, with no credential, + * in the runtime's local box profile, which build derives the AgentCore Runtime profile from. + */ +async function useEgressAgent(projectDir: string): Promise { + await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), EGRESS_AGENT); + const profile = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local", "profile.toml"); + const host = new URL(EGRESS_ALLOWED_URL).host; + await writeFile( + profile, + `${await readFile(profile, "utf8")}\n[egress.checkip]\ndestinations = ["${host}"]\n`, + ); +} + +/** Checks the egress agent's reply: the allowed host answers, and box refuses the other one. */ +function assertEgressReply(body: string): void { + const reply = EgressReplySchema.parse(JSON.parse(body)); + expect(reply.allowed).toEqual({ status: 200 }); + expect(reply.blocked.error).toMatch(/403/); +} + /** * Given a deployed Box project, waits for the Runtime's logs to show that box started the agent, * then checks they show no box error. The logs arrive a little after the invoke, so it retries. @@ -558,10 +634,15 @@ async function assertRunsInBox(cli: CliRunner, projectDir: string): Promise { const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-")); // A per-template suffix keeps concurrent projects (and their stacks) apart; @@ -582,7 +663,7 @@ async function createTemplateProject( for (const entry of spec.runtimes) entry.runtimeVersion = runtime.runtimeVersion; await writeFile(specPath, `${JSON.stringify(spec, null, 2)}\n`); } - if (runtime.box && BOX_CDK) { + if (deploys && runtime.box && BOX_CDK) { // The pinned @aws/agentcore-cdk cannot deploy a Box project yet; use the opted-in build. const installed = await runCommand( "npm", From 9e09dcff05d8f667877940305c23e61ffdff1395 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 14:39:00 -0800 Subject: [PATCH 6/9] fix(box): Build sets box.version to the pinned box, and drop the per-version plumbing Addresses the review of #2867: - A pin bump stopped every existing Box project: build refused any box.version but the pin, and nothing rewrote the field. Build and deploy now set each box runtime's box.version to the pinned box (boxVersionWriter) and say so, since the box features and the profiles the CLI writes change together. The late stop in staging goes with it. - boxReleaseFor, the per-version build Map, and the release getters of the staging functions and the container dev runner go: each stages BOX_RELEASE. Tests no longer stage 1.0.0 and 2.0.0 through fakes, and a build test covers the update. - The testing guide is rewrapped to 100 columns and says how to publish an unreleased box; the pinned-release test title matches its assertions. --- README.md | 4 +- docs/box-local-testing.md | 241 +++++++++--------- src/core/dev/container.test.ts | 16 +- src/core/dev/container.ts | 12 +- src/core/project/backends/boxCodeZip.test.ts | 22 +- src/core/project/backends/boxCodeZip.ts | 12 +- .../project/backends/boxContainer.test.ts | 38 +-- src/core/project/backends/boxContainer.ts | 7 +- src/core/project/backends/boxRelease.test.ts | 23 +- src/core/project/backends/boxRelease.ts | 15 -- src/core/project/backends/cdk.ts | 13 +- src/core/project/boxNetworkWriters.ts | 29 +++ src/core/project/manager.boxNetwork.test.ts | 33 +++ 13 files changed, 232 insertions(+), 233 deletions(-) diff --git a/README.md b/README.md index 6691613152..6b87297e42 100644 --- a/README.md +++ b/README.md @@ -234,8 +234,8 @@ 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. It must be the pinned version, whose checksums `boxRelease.json` -keeps; build, deploy and container `dev` stop on any other version and say to set the pinned one. +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. 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 343ca04216..dea630defd 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -1,27 +1,27 @@ # Local testing: a Box project with a workspace CLI and L3 constructs This guide creates, builds, and deploys a Box project with the AgentCore CLI and the -`@aws/agentcore-cdk` L3 constructs taken from your local workspace, not the published -packages. Use it to test the Box gateway, its egress targets, and API key credentials -end to end before you publish. +`@aws/agentcore-cdk` L3 constructs taken from your local workspace, not the published packages. Use +it to test the Box gateway, its egress targets, and API key credentials end to end before you +publish. -A "Box project" (`"projectType": "box"` in `agentcore.json`) runs its agent in a _box_: -a sandbox that controls the agent's network egress and filesystem access. Each runtime -gets its own Box gateway, bound to it by `boundRuntime` and named after it: the runtime `agent` -gets `agent-box-egress`. +A "Box project" (`"projectType": "box"` in `agentcore.json`) runs its agent in a _box_: a sandbox +that controls the agent's network egress and filesystem access. Each runtime gets its own Box +gateway, bound to it by `boundRuntime` and named after it: the runtime `agent` gets +`agent-box-egress`. ## Where box comes from -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. `agentcore build` and -`agentcore deploy` download that release's Linux build from +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 [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 container image downloads the Linux build while it builds, under `agentcore dev` too. For a -CodeZip agent, `agentcore dev` runs the `box` on your PATH: install it as in -[Install box](#install-box). No local box checkout is needed. +container they write the release and its checksum into `.box-dist/box-release.env` instead. A +container image downloads the Linux build while it builds, under `agentcore dev` too. For a CodeZip +agent, `agentcore dev` runs the `box` on your PATH: install it as in [Install box](#install-box). No +local box checkout is needed. Dev, build and deploy run a runtime's agent in a box only when `agentcore.json` has `"projectType": "box"` and the runtime has `"box": { "version": ... }`. `create` writes both, and @@ -29,11 +29,13 @@ 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"`. -`box.version` must be the box version the CLI pins in -`src/core/project/backends/boxRelease.json`; build, deploy and container `dev` stop on any other -version. To try an unreleased box build, publish it as a pre-release with the same file names and -run `bun scripts/bump-box-release.ts --box ` in your CLI checkout, then set `box.version` -to it. +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 +`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. ## Prerequisites @@ -43,12 +45,11 @@ to it. `enableApplicationLogs`, and an older L3 refuses it at synth with a `ConfigValidationError`. - `box` `0.1.11-preview.10` on your `PATH`, the release the CLI pins. Use that release: the box features and the profiles that the CLI writes change together, so an older box can refuse the - profiles. The CLI does not check the version of the box on your `PATH` yet. Build, deploy and dev run it - to read the box profile with `box profile show --format json --full`, and CodeZip dev runs the - agent with it. See [Install box](#install-box). -- AWS credentials for a **dev or test** account. Build writes the Box gateway's Bedrock and - Memory targets for `AWS_REGION` (else your AWS profile's region), and deploy for its target's - region. + profiles. The CLI does not check the version of the box on your `PATH` yet. Build, deploy and dev + run it to read the box profile with `box profile show --format json --full`, and CodeZip dev runs + the agent with it. See [Install box](#install-box). +- AWS credentials for a **dev or test** account. Build writes the Box gateway's Bedrock and Memory + targets for `AWS_REGION` (else your AWS profile's region), and deploy for its target's region. - `bun` for the CLI, `npm` for the generated CDK app. ## Install box @@ -108,16 +109,17 @@ box --version - On macOS, if Gatekeeper refuses to run `box`, clear the download flag with `xattr -dr com.apple.quarantine "$HOME/.local/share/box/0.1.11-preview.10"`. -To move to a newer release, unpack it into its own folder the same way and change the `PATH` line -to that folder. +To move to a newer release, unpack it into its own folder the same way and change the `PATH` line to +that folder. ## Settings Set these once per shell. Change the values for your machine: `CLI` is the CLI run from source in your workspace checkout, `L3` is the local L3 constructs checkout, and `DEMO` and `PROJECT` say where the demo project goes. Use absolute paths: the steps below `cd` into other folders, where a -relative path no longer resolves (`bun` then says `Module not found "./agentcore-cli/src/index.ts"`). -Replace `/path/to/workspace` with the folder that holds both checkouts: +relative path no longer resolves (`bun` then says +`Module not found "./agentcore-cli/src/index.ts"`). Replace `/path/to/workspace` with the folder +that holds both checkouts: ``` CLI=/path/to/workspace/agentcore-cli/src/index.ts @@ -137,9 +139,9 @@ makes bun look for a folder named `~`. ## Install the CLI's dependencies -The CLI runs from source, so it needs its own `node_modules`. Install them once in the -CLI checkout before the first `bun run "$CLI"`. Without this, `bun` falls back to its global -cache and `create` fails with `ENOENT while resolving package '@opentelemetry/core'`. +The CLI runs from source, so it needs its own `node_modules`. Install them once in the CLI checkout +before the first `bun run "$CLI"`. Without this, `bun` falls back to its global cache and `create` +fails with `ENOENT while resolving package '@opentelemetry/core'`. ``` cd "$(dirname "$CLI")/.." @@ -148,8 +150,8 @@ bun install ## 1. Get AWS credentials -Deploy creates real resources, so it needs write access. This example uses `ada` with an -Isengard dev account; use whatever grants credentials for your dev account. +Deploy creates real resources, so it needs write access. This example uses `ada` with an Isengard +dev account; use whatever grants credentials for your dev account. ``` ada credentials update --account --provider isengard --role Admin @@ -184,9 +186,9 @@ This adds an `[egress]` entry for `api.github.com` with a `github` API key crede needs `destinations`. Build declares the credential from the `env://` secret, adds the `egress-github` gateway target, and deploy provisions the credential in AgentCore Identity. -The `destinations` key lists the hosts the credential may reach. The box blocks the -credential's egress to any host not in the list. Each entry is a `` or -`:` string. The default port is 443. A port must be 1 to 65535. +The `destinations` key lists the hosts the credential may reach. The box blocks the credential's +egress to any host not in the list. Each entry is a `` or `:` string. The default +port is 443. A port must be 1 to 65535. ``` printf '\n[egress.github]\ndestinations = ["api.github.com"]\nsecret.ref = "env://GITHUB_TOKEN"\n' >> "$DEMO/$PROJECT/.box/agent/local/profile.toml" @@ -202,33 +204,32 @@ Runtime profile, its policy files, and box in the `.box-dist/` folder of the cod build context, and write a copy of the profile, the generated packs, and the policy files into `.box//aws/` for you to read. -Box `0.1.11-linux-preview.7` names its packs `@box/base`, `@box/bedrock`, and `@box/agentcore`. -A profile that names a pack `box/` fails: box refuses it and names the `@box/` pack. +Box `0.1.11-linux-preview.7` names its packs `@box/base`, `@box/bedrock`, and `@box/agentcore`. A +profile that names a pack `box/` fails: box refuses it and names the `@box/` pack. -- **Gateway targets.** Each host or `host:port` that an `[egress]` entry, an `[mcp]` server - with `type = "http"`, or a policy permit names, and that the policy allows at least one - request to, gets one passthrough target on `-box-egress`. The target of an MCP server is +- **Gateway targets.** Each host or `host:port` that an `[egress]` entry, an `[mcp]` server with + `type = "http"`, or a policy permit names, and that the policy allows at least one request to, + gets one passthrough target on `-box-egress`. The target of an MCP server is `egress-`. Its `protocolType` is `CUSTOM`, thus only Box makes the decision on each - `mcp:call`. A host the gateway already has a target for keeps that target. Build owns - only the targets whose name starts with `egress-`: it adds them, changes them, and removes - one when no host needs it. It never changes another target. -- **Outbound auth.** An `aws://` secret signs with the gateway's role, an `env://` secret - sends an API key from AgentCore Identity, and an entry with no secret sends no credential. -- **Failures.** A profile Box refuses stops build and deploy with box's own error. A wildcard - host, a plain-HTTP-only host, an unsupported secret, an MCP server that names more than one - host, a path, or a port other than 443, and similar cases stop them too. The error starts with `Build stopped:` or `Deploy stopped:` and the - number of problems, then gives one line for each problem: its `file:line:column` in your - profile or policy file, what is wrong, and how to fix it. A rule of your policy file is found - by its `@id`. For a rule that Box adds, the line names the entry that makes Box add it, such as - `[egress.github]`. Nothing is written. -- **Warnings.** Build warns when Box enforces rules that the gateway does not (a path, - method, or forbid), when an entry's host gets no target, and when a target is signed for an - AWS service that no policy of the gateway's role grants. It also warns for a `.json` file in - the gateway's `additionalPolicies` that does not exist, cannot be read, or is not a JSON - object, as it counts none of its actions. -- **The AgentCore Runtime profile.** Build derives `.box-dist/profile.toml` from the local - profile. Each key of the local profile stays, and build changes only what must differ on - AgentCore Runtime: + `mcp:call`. A host the gateway already has a target for keeps that target. Build owns only the + targets whose name starts with `egress-`: it adds them, changes them, and removes one when no host + needs it. It never changes another target. +- **Outbound auth.** An `aws://` secret signs with the gateway's role, an `env://` secret sends an + API key from AgentCore Identity, and an entry with no secret sends no credential. +- **Failures.** A profile Box refuses stops build and deploy with box's own error. A wildcard host, + a plain-HTTP-only host, an unsupported secret, an MCP server that names more than one host, a + path, or a port other than 443, and similar cases stop them too. The error starts with + `Build stopped:` or `Deploy stopped:` and the number of problems, then gives one line for each + problem: its `file:line:column` in your profile or policy file, what is wrong, and how to fix it. + A rule of your policy file is found by its `@id`. For a rule that Box adds, the line names the + entry that makes Box add it, such as `[egress.github]`. Nothing is written. +- **Warnings.** Build warns when Box enforces rules that the gateway does not (a path, method, or + forbid), when an entry's host gets no target, and when a target is signed for an AWS service that + no policy of the gateway's role grants. It also warns for a `.json` file in the gateway's + `additionalPolicies` that does not exist, cannot be read, or is not a JSON object, as it counts + none of its actions. +- **The AgentCore Runtime profile.** Build derives `.box-dist/profile.toml` from the local profile. + Each key of the local profile stays, and build changes only what must differ on AgentCore Runtime: - each `[egress]` host with a gateway target becomes one route to `-box-egress`: the first host of an entry keeps the name of the entry, so a pack's own entry of that name merges with it, and each other host gets `[egress.]`; an HTTP `[mcp.]` server gets the @@ -254,8 +255,8 @@ A profile that names a pack `box/` fails: box refuses it and names the `@b runtime. Build stops, and names the key and its line, for a value that cannot work on the Runtime: a - required grant or a command path in the project outside the code folder, in the venv, or in a - home folder (`${{ home }}`, `~`, `/Users`, `/home`); a CodeZip program that `PATH` finds, such as + required grant or a command path in the project outside the code folder, in the venv, or in a home + folder (`${{ home }}`, `~`, `/Users`, `/home`); a CodeZip program that `PATH` finds, such as `npx`; a CodeZip write grant in the code folder; `network.contain_egress = false`; a CloudWatch target that box refuses; or a telemetry target that is not CloudWatch or `file`. Build warns, and goes on, for what the Runtime does without: a `deny` entry or an optional grant with no place @@ -267,9 +268,9 @@ A profile that names a pack `box/` fails: box refuses it and names the `@b then refuses a stdio server or a tool whose program is the venv's Python ("a link out of a folder the box can write"). To run one, set `access = "read"` in `[project]` of the local profile. -- **No-auth targets need a newer L3.** A passthrough target with no outbound auth synthesizes - only with an `@aws/agentcore-cdk` that accepts it. Until that release is pinned, use a - local L3 build, as in step 5. +- **No-auth targets need a newer L3.** A passthrough target with no outbound auth synthesizes only + with an `@aws/agentcore-cdk` that accepts it. Until that release is pinned, use a local L3 build, + as in step 5. ## 5. Point the generated CDK app at the local L3 tarball @@ -287,9 +288,9 @@ deploy. It deploys nothing. The agent signs its Bedrock calls with your `[defaul (`secret.ref = "aws://default"` in `.box/agent/local/profile.toml`), and Memory is off (`LOCAL_DEV=1`). -Dev runs an agent in a box only in a Box project, as build and deploy do: `agentcore.json` must -have `"projectType": "box"`, which `create` writes for the box templates. Without it, dev runs a -runtime the usual way, and stops on one that has `box.version` with +Dev runs an agent in a box only in a Box project, as build and deploy do: `agentcore.json` must have +`"projectType": "box"`, which `create` writes for the box templates. Without it, dev runs a runtime +the usual way, and stops on one that has `box.version` with `agentcore.json has no "projectType": "box"`. ### Which box builds exist @@ -302,11 +303,11 @@ The box release has these builds: | Linux, arm64 | `box-v-aarch64-unknown-linux-gnu` | yes | yes | | Linux or macOS, x86 | none | no | no | -- The **container** image always uses the Linux arm64 build, because AgentCore Runtime is arm64. - It runs on an Apple chip Mac through Finch or Docker, and on an arm64 Linux host. An x86 host - would need to emulate arm64. -- **CodeZip** dev runs the `box` on your `PATH` natively, so it needs the build for your machine. - On an arm64 Linux host it uses the same Linux build as the Runtime. +- The **container** image always uses the Linux arm64 build, because AgentCore Runtime is arm64. It + runs on an Apple chip Mac through Finch or Docker, and on an arm64 Linux host. An x86 host would + need to emulate arm64. +- **CodeZip** dev runs the `box` on your `PATH` natively, so it needs the build for your machine. On + an arm64 Linux host it uses the same Linux build as the Runtime. - Build and deploy need a `box` on your `PATH` on every machine, to read the profile. So for now build and deploy work only on an Apple chip Mac or an arm64 Linux host. @@ -323,8 +324,8 @@ aws sts get-caller-identity `box profile show --format json --full`. The AgentCore Runtime profile signs each Box gateway backend for `${{ inputs.aws.region }}`, and its default telemetry target reads one key of `OTEL_EXPORTER_OTLP_LOGS_HEADERS`. An older box release cannot do all of these. -- The `[default]` profile must hold fresh credentials, because box reads them when dev starts. - After you refresh them, restart dev. +- The `[default]` profile must hold fresh credentials, because box reads them when dev starts. After + you refresh them, restart dev. ### Run dev @@ -340,8 +341,8 @@ bun run "$CLI" dev Dev hands each `env://` key of the box profile (an `[egress]` route's or an `[mcp]` server's) to `box run` from your shell, and writes it nowhere. A value you put in `agentcore/.env.local` is used -when the shell has none. If neither has it, dev warns, naming the variable and how to set it, and box -then refuses to start (`credential variable GITHUB_TOKEN is not set`). A variable set without +when the shell has none. If neither has it, dev warns, naming the variable and how to set it, and +box then refuses to start (`credential variable GITHUB_TOKEN is not set`). A variable set without `export` stays in the shell and does not reach dev: export it, or set it on the same line (`GITHUB_TOKEN=... bun run "$CLI" dev`). @@ -381,8 +382,8 @@ bun run "$CLI" invoke --local --runtime agent --payload '{"prompt":"What is 17 t ### What to check - The answer comes back from `invoke --local`. -- The dev output shows box starting the agent: `box: running profile cliDemo` (your `$PROJECT`) and the - `[agent]` filesystem summary, with `deny_write .../.venv (read-only)` for CodeZip. +- The dev output shows box starting the agent: `box: running profile cliDemo` (your `$PROJECT`) and + the `[agent]` filesystem summary, with `deny_write .../.venv (read-only)` for CodeZip. - With the step 4 `[egress]` entry, calls to its host go out, and calls to other hosts are blocked (`ProxyConnectionError ... 127.0.0.1:` in the agent's log means box blocked the host). @@ -390,13 +391,13 @@ Stop dev with Ctrl+C before you build. ## 7. Build -Export `GITHUB_TOKEN` before build. Build reads it and writes its value into -`agentcore/.env.local` under the credential's reserved name `AGENTCORE_CREDENTIAL_GITHUB`. -On a later build it replaces that value when `GITHUB_TOKEN` holds a different key, as after a -rotation, so deploy provisions the key `agentcore dev` uses. Build reads `GITHUB_TOKEN` as dev -does: from your shell, or from `agentcore/.env.local` when the shell has none. So a -`GITHUB_TOKEN` line in `agentcore/.env.local` replaces the stored key too, even with an older -key; keep the key in one place. With `GITHUB_TOKEN` in neither, build keeps the stored key. +Export `GITHUB_TOKEN` before build. Build reads it and writes its value into `agentcore/.env.local` +under the credential's reserved name `AGENTCORE_CREDENTIAL_GITHUB`. On a later build it replaces +that value when `GITHUB_TOKEN` holds a different key, as after a rotation, so deploy provisions the +key `agentcore dev` uses. Build reads `GITHUB_TOKEN` as dev does: from your shell, or from +`agentcore/.env.local` when the shell has none. So a `GITHUB_TOKEN` line in `agentcore/.env.local` +replaces the stored key too, even with an older key; keep the key in one place. With `GITHUB_TOKEN` +in neither, build keeps the stored key. ``` cd "$DEMO/$PROJECT" @@ -405,8 +406,8 @@ bun run "$CLI" build grep AGENTCORE_CREDENTIAL_GITHUB agentcore/.env.local ``` -If you added the `github` egress credential in step 4, this first standalone `build` stops -after writing the targets, policies, and `.env.local`, with: +If you added the `github` egress credential in step 4, this first standalone `build` stops after +writing the targets, policies, and `.env.local`, with: ``` Project build cannot resolve credential "github" before its first deployment. @@ -414,8 +415,8 @@ Run 'agentcore deploy' to provision the credential and build the project. ``` This is expected. An `env://` credential must exist in AgentCore Identity before synthesis can -resolve it, and only `deploy` provisions it. So on the **first** run with an egress credential, -skip straight to step 8: `deploy` provisions the credential and then builds in one step (keep +resolve it, and only `deploy` provisions it. So on the **first** run with an egress credential, skip +straight to step 8: `deploy` provisions the credential and then builds in one step (keep `GITHUB_TOKEN` exported). After that first deploy, `build` runs standalone as above. ## 8. Deploy @@ -424,8 +425,8 @@ skip straight to step 8: `deploy` provisions the credential and then builds in o bun run "$CLI" deploy ``` -Deploy synthesizes the CDK app you linked in step 5, so the stack uses your local L3 constructs. -The first deploy makes the `default` target from your account and region. +Deploy synthesizes the CDK app you linked in step 5, so the stack uses your local L3 constructs. The +first deploy makes the `default` target from your account and region. ## 9. Verify the gateway, its targets, and the credential @@ -440,10 +441,10 @@ Live checks, after deploy. Deploy names each AWS resource after the project and (`default`), so the names differ from those in `agentcore.json`: - The Box gateway `agent-box-egress` deploys as `-default-agent-box-egress`, for example - `cliDemo-default-agent-box-egress`. Its ID is that name in lowercase with a suffix, and is a - stack output. -- The credential `github` deploys as the API key credential provider `_default_github`, - for example `cliDemo_default_github`. + `cliDemo-default-agent-box-egress`. Its ID is that name in lowercase with a suffix, and is a stack + output. +- The credential `github` deploys as the API key credential provider `_default_github`, for + example `cliDemo_default_github`. ``` GATEWAY_ID=$(aws cloudformation describe-stacks --stack-name "AgentCore-$PROJECT-default" --query "Stacks[0].Outputs[?starts_with(OutputKey, 'ApplicationGatewayAgentBoxEgressIdOutput')].OutputValue" --output text) @@ -452,8 +453,8 @@ bun run "$CLI" gateway get --id "$GATEWAY_ID" bun run "$CLI" identity api-key-credential-provider get --name "${PROJECT}_default_github" ``` -`gateway list` shows every gateway in the account and region, not only this project's, so look -the Box gateway up by its ID as above. +`gateway list` shows every gateway in the account and region, not only this project's, so look the +Box gateway up by its ID as above. ## 10. Read box telemetry and gateway logs in CloudWatch @@ -465,9 +466,9 @@ to the Runtime profile. If the profile has a target with the name `agentcore`, t `AWS_REGION`, and its log group and stream from `OTEL_EXPORTER_OTLP_LOGS_HEADERS`. The target sends the deny, permit, and trace records, and box signs it with the execution role. -The CLI and the L3 constructs make no log group for box. The role that the CDK makes for the -runtime can write to the log group of the Runtime, thus build adds no grant for it. A runtime that -names an `executionRoleArn` must have `logs:CreateLogStream` and `logs:PutLogEvents` on +The CLI and the L3 constructs make no log group for box. The role that the CDK makes for the runtime +can write to the log group of the Runtime, thus build adds no grant for it. A runtime that names an +`executionRoleArn` must have `logs:CreateLogStream` and `logs:PutLogEvents` on `/aws/bedrock-agentcore/runtimes/*`. The `logs runtime` command finds that log group from the runtime name: @@ -589,12 +590,12 @@ These outlive the stack. Delete them too: ## Troubleshooting -- **Dev says `'box' was not found on your PATH`.** Download the build for your machine from the - box release, unpack it into a folder, add that folder to your `PATH`, then retry. +- **Dev says `'box' was not found on your PATH`.** Download the build for your machine from the box + release, unpack it into a folder, add that folder to your `PATH`, then retry. - **Dev or build says Box `cannot print the profile ... as JSON`.** The `box` on your `PATH` is older than the pinned release. Install the pinned release. -- **Box says `box's own packs were not found; set BOX_RESOURCES`.** A stale `BOX_RESOURCES` is - set. Run `unset BOX_RESOURCES`, or open a new terminal. +- **Box says `box's own packs were not found; set BOX_RESOURCES`.** A stale `BOX_RESOURCES` is set. + Run `unset BOX_RESOURCES`, or open a new terminal. - **Dev starts but model calls fail with `ExpiredTokenException`.** Your `[default]` credentials expired. Refresh them and restart dev. - **Dev warns that the box profile `reads GITHUB_TOKEN for [egress.github], but it is not set`, and @@ -604,19 +605,19 @@ These outlive the stack. Delete them too: `agentcore/.env.local`, then restart dev. A variable set without `export` does not reach dev. - **Dev on macOS fails with `sandbox initialization failed: Operation not permitted`.** Dev is running inside another sandbox. Run it from a normal terminal. -- **Build says Box is not installed or not on PATH.** Install `box` and put it on your `PATH`, - then build again. -- **Build says Box refused the profile.** The lines under it are box's own error. A fresh - checkout often has no agent venv yet, and box then names `.venv/bin/python` under a write - grant. The error then says to run `uv sync` in the agent's folder (`app/`). -- **Build cannot download box.** The error names the release URL. Check your network; a 404 - means the pinned version is not published in `mquang-amazon/box-releases`. +- **Build says Box is not installed or not on PATH.** Install `box` and put it on your `PATH`, then + build again. +- **Build says Box refused the profile.** The lines under it are box's own error. A fresh checkout + often has no agent venv yet, and box then names `.venv/bin/python` under a write grant. The error + then says to run `uv sync` in the agent's folder (`app/`). +- **Build cannot download box.** The error names the release URL. Check your network; a 404 means + the pinned version is not published in `mquang-amazon/box-releases`. - **`create` fails with `ENOENT while resolving package '@opentelemetry/core'`.** The CLI's - dependencies are not installed, so `bun` fell back to its global cache. Run `bun install` in - the CLI checkout (see "Install the CLI's dependencies"). -- **Build says it cannot resolve credential "github" before its first deployment.** Expected - when step 4's egress credential has never been deployed. Run `agentcore deploy` instead; it - provisions the credential and builds. Standalone `build` works after that. See step 7. + dependencies are not installed, so `bun` fell back to its global cache. Run `bun install` in the + CLI checkout (see "Install the CLI's dependencies"). +- **Build says it cannot resolve credential "github" before its first deployment.** Expected when + step 4's egress credential has never been deployed. Run `agentcore deploy` instead; it provisions + the credential and builds. Standalone `build` works after that. See step 7. - **Deploy says a credential has no secret.** The credential's value did not reach `agentcore/.env.local`. Export `GITHUB_TOKEN` and run build again, or set `AGENTCORE_CREDENTIAL_GITHUB` in the deploy environment. diff --git a/src/core/dev/container.test.ts b/src/core/dev/container.test.ts index 0cbecf1787..f614625603 100644 --- a/src/core/dev/container.test.ts +++ b/src/core/dev/container.test.ts @@ -108,10 +108,8 @@ function harness( if (config.stream) yield* config.stream(command, options); }; - const boxVersions: (string | undefined)[] = []; return { calls, - boxVersions, runner: new ContainerDevRunner({ streamProcess: fakeStreamProcess, toolAvailable: @@ -120,10 +118,6 @@ function harness( return tool === "docker"; }), awsDirectory: config.awsDirectory ?? join(tmpdir(), "agentcore-container-no-aws"), - releaseFor: async (version) => { - boxVersions.push(version); - return { ...BOX_RELEASE, version: version ?? BOX_RELEASE.version }; - }, processEnv: config.processEnv ?? { AWS_ACCESS_KEY_ID: "test-access-key", AWS_SECRET_ACCESS_KEY: "test-secret-key", @@ -1080,13 +1074,15 @@ describe("ContainerDevRunner", () => { expect(JSON.stringify(events)).not.toContain("reads GITHUB_TOKEN for [egress.github]"); }); - test("stages box of the runtime's box.version", async () => { - const { projectRuntime, root } = await boxedScene(); - const { boxVersions, runner } = harness({ processEnv: credentials }); + test("stages the pinned box, whatever box.version the runtime names", async () => { + const { projectRuntime, root, context } = await boxedScene(); + const { runner } = harness({ processEnv: credentials }); await collect(runner.run(input(root, { ...projectRuntime, box: { version: "2.0.0" } }))); - expect(boxVersions).toEqual(["2.0.0"]); + 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"); }); 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 bb386e78f6..017f258472 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -26,7 +26,7 @@ import { imageTakesBoxDistArg, stageBoxImage, } from "../project/backends/boxContainer"; -import { boxReleaseFor, type BoxRelease } from "../project/backends/boxRelease"; +import { BOX_RELEASE, type BoxRelease } from "../project/backends/boxRelease"; import { boxPolicyFileCopies } from "../project/boxNetworkSource"; import { boxLocalProfileFile, @@ -115,8 +115,8 @@ type ContainerDevRunnerConfig = { toolAvailable?: ToolAvailable; awsDirectory?: string; processEnv?: NodeJS.ProcessEnv; - /** The box release of the runtime's `box.version`, which the image downloads. Tests inject one. */ - releaseFor?: (version: string | undefined) => Promise; + /** The box release the image downloads: the pinned one. Tests inject another. */ + release?: BoxRelease; /** Resolves the credentials a boxed container signs with; the default AWS SDK chain by default. */ resolveAwsCredentials?: ResolveAwsCredentials; /** The platform, whose rules for variable names apply to `processEnv`; tests inject one. */ @@ -128,7 +128,7 @@ export class ContainerDevRunner implements DevRunner { private readonly toolAvailable: ToolAvailable; private readonly awsDirectory: string; private readonly processEnv: NodeJS.ProcessEnv; - private readonly releaseFor: (version: string | undefined) => Promise; + private readonly release: BoxRelease; private readonly resolveAwsCredentials: ResolveAwsCredentials; private readonly platform: NodeJS.Platform; @@ -137,7 +137,7 @@ export class ContainerDevRunner implements DevRunner { this.toolAvailable = config.toolAvailable ?? toolAvailable; this.awsDirectory = config.awsDirectory ?? join(homedir(), ".aws"); this.processEnv = config.processEnv ?? process.env; - this.releaseFor = config.releaseFor ?? boxReleaseFor; + this.release = config.release ?? BOX_RELEASE; this.resolveAwsCredentials = config.resolveAwsCredentials ?? resolveDefaultAwsCredentials; this.platform = config.platform ?? process.platform; } @@ -395,7 +395,7 @@ export class ContainerDevRunner implements DevRunner { context, profileText, boxPolicyFileCopies(input.projectRoot, input.runtime.name), - await this.releaseFor(input.runtime.box?.version), + this.release, folder, ); return { folder, profileText }; diff --git a/src/core/project/backends/boxCodeZip.test.ts b/src/core/project/backends/boxCodeZip.test.ts index 36f99bc4de..60ec1010b5 100644 --- a/src/core/project/backends/boxCodeZip.test.ts +++ b/src/core/project/backends/boxCodeZip.test.ts @@ -120,18 +120,18 @@ describe("stageBoxCodeZip", () => { expect(await readFile(join(dist, ".gitignore"), "utf8")).toBe(BOX_DIST_GITIGNORE); }); - test("asks for the box of the runtime's box.version", async () => { + test("asks for the pinned box once, for every runtime", async () => { const build = await linuxBuild(); - const demo = await project("start.py"); - demo.spec.runtimes[0]!.box = { version: "2.0.0" }; - const versions: (string | undefined)[] = []; + const demo = await project("start.py", "PYTHON_3_14", ["agent", "second"]); + demo.spec.runtimes[1]!.box = { version: "2.0.0" }; + let asked = 0; - await stageBoxCodeZip(demo, [model([])], async (version) => { - versions.push(version); + await stageBoxCodeZip(demo, [model([]), model([], "second")], async () => { + asked++; return build; }); - expect(versions).toEqual(["2.0.0"]); + expect(asked).toBe(1); }); test.each([ @@ -142,15 +142,15 @@ describe("stageBoxCodeZip", () => { const runtime = demo.spec.runtimes[0]!; if (!boxVersion) delete runtime.box; (demo.spec as { projectType?: string }).projectType = projectType; - const asked: (string | undefined)[] = []; + let asked = 0; expect( - await stageBoxCodeZip(demo, [model([])], async (version) => { - asked.push(version); + await stageBoxCodeZip(demo, [model([])], async () => { + asked++; return linuxBuild(); }), ).toEqual([]); - expect(asked).toEqual([]); + expect(asked).toBe(0); expect(existsSync(join(demo.rootPath, "app", "agent", ".box-dist"))).toBe(false); }); diff --git a/src/core/project/backends/boxCodeZip.ts b/src/core/project/backends/boxCodeZip.ts index 2f2e7b7a71..29dc30dee8 100644 --- a/src/core/project/backends/boxCodeZip.ts +++ b/src/core/project/backends/boxCodeZip.ts @@ -27,7 +27,7 @@ export const BOX_DIST_GITIGNORE = export async function stageBoxCodeZip( project: Project, networks: readonly BoxNetwork[], - box: (version: string | undefined) => Promise, + box: () => Promise, ): Promise { const runtimes = project.spec.runtimes.filter( (runtime) => runtime.build === "CodeZip" && runtimeRunsInBox(project.spec, runtime), @@ -47,16 +47,10 @@ export async function stageBoxCodeZip( envLocal: {}, }); const filesOf = (dist: string) => files.filter(({ path }) => path.startsWith(`${dist}/`)); - // One build for each box version the runtimes name, so each downloads once. - const builds = new Map(); - for (const runtime of runtimes) { - const version = runtime.box?.version; - if (!builds.has(version)) builds.set(version, await box(version)); - } + // Every runtime ships the pinned box, which downloads once. + const build = await box(); for (const { runtime, dist } of staged) { - const entry = runtimes.find(({ name }) => name === runtime)!; - const build = builds.get(entry.box?.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 2bb9f1a037..abfd2cf741 100644 --- a/src/core/project/backends/boxContainer.test.ts +++ b/src/core/project/backends/boxContainer.test.ts @@ -9,7 +9,7 @@ import type { BoxNetwork } from "../boxNetwork"; import { renderAgentCorePack } from "../templates/boxProfile"; import { serializeRuntimeProfile } from "../runtimeProfile/serialize"; import { stageBoxContainers } from "./boxContainer"; -import { BOX_RELEASE, type BoxRelease } from "./boxRelease"; +import { BOX_RELEASE } from "./boxRelease"; /** The staged path of the generated @box/agentcore pack, from `.box-dist/`. */ const PACK_PATH = join("resources", "packs", "agentcore", "pack.toml"); @@ -60,25 +60,13 @@ const BOX_DOCKERFILE = "FROM scratch\nCOPY .box-dist/profile.toml /opt/box/\n"; /** What build and deploy stage beside the Dockerfile. */ const STAGED = ["box-release.env", "profile.toml"]; -/** The release getter build and deploy pass, which records the version each runtime asks for. */ -function releaseOf() { - const versions: (string | undefined)[] = []; - const releaseFor = async (version: string | undefined): Promise => { - versions.push(version); - return { ...BOX_RELEASE, version: version ?? BOX_RELEASE.version }; - }; - return { releaseFor, versions }; -} - describe("stageBoxContainers", () => { - test("stages the box release of the runtime's box.version, and the Runtime profile, into the build context", async () => { + test("stages the pinned box release, whatever 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" }; - const { releaseFor, versions } = releaseOf(); - expect(await stageBoxContainers(demo, [model([])], releaseFor)).toEqual(["agent"]); + expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual(["agent"]); - expect(versions).toEqual(["2.0.0"]); const dist = join(demo.rootPath, "app", "agent", ".box-dist"); // The Runtime profile is the one build derived from the local profile. const { runtimeProfile, runtimeProfileHeader } = model([]); @@ -86,7 +74,7 @@ describe("stageBoxContainers", () => { serializeRuntimeProfile(runtimeProfile!, runtimeProfileHeader), ); expect(await readFile(join(dist, "box-release.env"), "utf8")).toBe( - `BOX_REPO=${BOX_RELEASE.repo}\nBOX_VERSION=2.0.0\nBOX_ASSET=${BOX_RELEASE.linux.asset}\n` + + `BOX_REPO=${BOX_RELEASE.repo}\nBOX_VERSION=${BOX_RELEASE.version}\nBOX_ASSET=${BOX_RELEASE.linux.asset}\n` + `BOX_SHA256=${BOX_RELEASE.linux.sha256}\n`, ); // The container also stages the @box/agentcore pack, beside box's own packs in the image. @@ -109,7 +97,7 @@ describe("stageBoxContainers", () => { await writeFile(join(dist, "box"), "old"); await writeFile(join(dist, "stale.dw"), "old"); - await stageBoxContainers(demo, [model([])], releaseOf().releaseFor); + await stageBoxContainers(demo, [model([])], BOX_RELEASE); expect((await readdir(dist)).sort()).toEqual([...STAGED, "resources"].sort()); }); @@ -118,17 +106,13 @@ describe("stageBoxContainers", () => { const demo = await project(BOX_DOCKERFILE); delete demo.spec.runtimes[0]!.box; - const { releaseFor, versions } = releaseOf(); - expect(await stageBoxContainers(demo, [model([])], releaseFor)).toEqual([]); - expect(versions).toEqual([]); + expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual([]); }); test("stages nothing for a runtime with no box.version", async () => { const demo = await project("FROM scratch\n"); - const { releaseFor, versions } = releaseOf(); - expect(await stageBoxContainers(demo, [model([])], releaseFor)).toEqual([]); - expect(versions).toEqual([]); + expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual([]); expect(existsSync(join(demo.rootPath, "app", "agent", ".box-dist"))).toBe(false); }); @@ -137,7 +121,7 @@ describe("stageBoxContainers", () => { await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true }); await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n"); - await stageBoxContainers(demo, [model(["policy.dw"])], releaseOf().releaseFor); + await stageBoxContainers(demo, [model(["policy.dw"])], BOX_RELEASE); const dist = join(demo.rootPath, "app", "agent", ".box-dist"); expect((await readdir(dist)).sort()).toEqual(["policy.dw", ...STAGED, "resources"].sort()); @@ -149,9 +133,9 @@ describe("stageBoxContainers", () => { await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true }); await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n"); - await expect( - stageBoxContainers(demo, [model(["policy.dw"])], releaseOf().releaseFor), - ).rejects.toThrow("does not copy .box-dist/ whole into the image"); + await expect(stageBoxContainers(demo, [model(["policy.dw"])], BOX_RELEASE)).rejects.toThrow( + "does not copy .box-dist/ whole into the image", + ); expect(existsSync(join(demo.rootPath, "app", "agent", ".box-dist"))).toBe(false); }); }); diff --git a/src/core/project/backends/boxContainer.ts b/src/core/project/backends/boxContainer.ts index 8007693617..6858331582 100644 --- a/src/core/project/backends/boxContainer.ts +++ b/src/core/project/backends/boxContainer.ts @@ -110,8 +110,8 @@ export async function stageBoxImage( /** * Stages box for build and deploy into each container runtime that runs in a box - * ({@link runtimeRunsInBox}): the build context's `.box-dist/` gets the box release its - * `box.version` names, and what the runtime profile writer writes from the runtime's Box network + * ({@link runtimeRunsInBox}): the build context's `.box-dist/` gets `release`, the pinned box, and + * what the runtime profile writer writes from the runtime's Box network * model (the Runtime profile and a byte copy of each policy file it names). `.box//aws/` * gets only what the writer writes, for people to read. Returns the names of the runtimes it * staged. @@ -119,7 +119,7 @@ export async function stageBoxImage( export async function stageBoxContainers( project: Project, networks: readonly BoxNetwork[], - releaseFor: (version: string | undefined) => Promise, + release: BoxRelease, ): Promise { const runtimes = project.spec.runtimes.filter( (runtime) => runtime.build === "Container" && runtimeRunsInBox(project.spec, runtime), @@ -150,7 +150,6 @@ export async function stageBoxContainers( const folder = join(project.rootPath, ...dist.split("/")); await rm(folder, { recursive: true, force: true }); await mkdir(folder, { recursive: true }); - const release = await releaseFor(runtime.box?.version); 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.test.ts b/src/core/project/backends/boxRelease.test.ts index 953656de7f..b3d6157529 100644 --- a/src/core/project/backends/boxRelease.test.ts +++ b/src/core/project/backends/boxRelease.test.ts @@ -12,7 +12,6 @@ import { BOX_RELEASE, BOX_RELEASE_PAGE, type BoxRelease, - boxReleaseFor, publishInstall, resolveBoxLinuxBuild, } from "./boxRelease"; @@ -208,26 +207,6 @@ describe("resolveBoxLinuxBuild from the box release", () => { }); }); -describe("boxReleaseFor a runtime's box.version", () => { - test("is the pinned release for no version or the pinned one", async () => { - expect(await boxReleaseFor(undefined)).toBe(BOX_RELEASE); - expect(await boxReleaseFor(BOX_RELEASE.version)).toBe(BOX_RELEASE); - }); - - test.each(["0.1.11-linux-preview.6", "2.0.0"])( - "refuses %s, a box this CLI does not pin, and says to set the pinned one", - async (version) => { - await expect(boxReleaseFor(version)).rejects.toThrow( - new InvalidEnvironmentError( - `agentcore.json names box ${version} under box.version, but this CLI ships box ` + - `${BOX_RELEASE.version}, the one box it pins. Set box.version to ` + - `${BOX_RELEASE.version}, then retry.`, - ), - ); - }, - ); -}); - describe("publishInstall", () => { /** A payload and a cache folder `root` beside it, each holding `file` with its folder's text. */ async function folders(rootText?: string) { @@ -273,7 +252,7 @@ describe("publishInstall", () => { }); describe("the pinned releases", () => { - test("pins one box, with the asset of its own version and a SHA-256", () => { + test("pins one box: the asset of its own version, its SHA-256, and its release page", () => { expect(BOX_RELEASE.linux.asset).toBe( `box-v${BOX_RELEASE.version}-aarch64-unknown-linux-gnu.tar.gz`, ); diff --git a/src/core/project/backends/boxRelease.ts b/src/core/project/backends/boxRelease.ts index fac45660d7..414d4889ec 100644 --- a/src/core/project/backends/boxRelease.ts +++ b/src/core/project/backends/boxRelease.ts @@ -270,18 +270,3 @@ async function download( ); } } - -/** - * The box release that `version`, a runtime's `box.version`, names. It must be the pinned one, - * BOX_RELEASE, whose checksums `boxRelease.json` pins: another box is untested with this CLI (box - * 0.1.11-linux-preview.6, for one, refuses the `@box/` packs the CLI writes), and build cannot - * see that, since it checks the profile with the box on PATH. No version means BOX_RELEASE. - */ -export async function boxReleaseFor(version: string | undefined): Promise { - if (version === undefined || version === BOX_RELEASE.version) return BOX_RELEASE; - throw new InvalidEnvironmentError( - `agentcore.json names box ${version} under box.version, but this CLI ships box ` + - `${BOX_RELEASE.version}, the one box it pins. Set box.version to ${BOX_RELEASE.version}, ` + - "then retry.", - ); -} diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index c4737d59c6..5746ac79b5 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -13,7 +13,7 @@ import type { import { stageBoxCodeZip } from "./boxCodeZip"; import { stageBoxContainers } from "./boxContainer"; import { runtimeRunsInBox } from "../templates/boxProfile"; -import { boxDownloadMessage, boxReleaseFor, resolveBoxLinuxBuild } from "./boxRelease"; +import { BOX_RELEASE, boxDownloadMessage, resolveBoxLinuxBuild } from "./boxRelease"; import { cdkCompatibilityWarning } from "./cdk/compatibility"; import { createLineSplitter, @@ -244,17 +244,16 @@ 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* eventsWhile(async (emit) => { - const box = async (version: string | undefined) => { - const release = await boxReleaseFor(version); - return resolveBoxLinuxBuild(this.processEnv, { + // Every box runtime ships the pinned box: build set each box.version to it. + const box = () => + resolveBoxLinuxBuild(this.processEnv, { runner: this.runner, - release, + release: BOX_RELEASE, onDownload: (download) => emit({ type: "step", message: boxDownloadMessage(download, "AgentCore Runtime") }), }); - }; await stageBoxCodeZip(project, boxNetworks, box); - await stageBoxContainers(project, boxNetworks, boxReleaseFor); + await stageBoxContainers(project, boxNetworks, BOX_RELEASE); }); } diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index cd8b28324e..810e169627 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -46,6 +46,7 @@ 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 = @@ -53,6 +54,7 @@ export type BoxNetworkOutput = | { readonly kind: "defaultTargets" } | { readonly kind: "credentials" } | { readonly kind: "runtimePolicies" } + | { readonly kind: "boxVersions" } | { readonly kind: "envLocal" } | { readonly kind: "file"; readonly path: string }; @@ -482,7 +484,34 @@ function withoutUnsentRoutes( } /** The writers that build and deploy run before synth, in order. */ +/** + * 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", + ]; + }), + ], + }), +}; + export const BOX_NETWORK_WRITERS: readonly BoxNetworkWriter[] = [ + boxVersionWriter, credentialsWriter, gatewayTargetsWriter, defaultTargetsWriter, diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index fcb2f5f819..69f8386177 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -13,6 +13,7 @@ import type { DeployBackendInput, ProjectBackend } from "./backends/types"; import { boxShowOf, FakeBoxProfileResolver } from "./boxProfileResolver-test-support"; import type { ResolvedBoxProfile } from "./boxProfileResolver"; import { seedBoxCache } from "./backends/box-release-test-support"; +import { BOX_RELEASE } from "./backends/boxRelease"; import { boxGatewayLogsNotice, FsProjectManager } from "./manager"; /** The golden files of this suite; `RECORD=1 bun test ` rewrites them, with no AWS call. */ @@ -628,6 +629,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(); + 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 { 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`, + ); + expect(JSON.parse(await text(root, SPEC)).runtimes[0].box).toEqual({ + version: BOX_RELEASE.version, + }); + }); + + test("leaves the pinned box.version as it is, with no message", async () => { + const { manager, root } = await strandsProject(); + const before = JSON.parse(await text(root, SPEC)).runtimes[0].box; + + 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); + }); +}); + describe("build writes the telemetry policy of the box profile", () => { const TELEMETRY_POLICY = "agentcore/box-telemetry-policy-agent_python_strands.json"; const ENTRY = "../../agentcore/box-telemetry-policy-agent_python_strands.json"; From 6072b2c170340426cd7974afd65d44e8f96df2c0 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 15:31:16 -0800 Subject: [PATCH 7/9] fix(box): Scope the Box gateway role's Bedrock grant to the build region Addresses the review of #2850: the role could invoke any Bedrock model in any region. It may now invoke an inference profile of its own account in the region build builds for, a foundation model there, and a foundation model in another region only through an inference profile in that region, which is how a cross-region (us., global.) profile reaches it. --- src/core/project/boxMemory.test.ts | 34 ++++++++++++++------ src/core/project/boxMemory.ts | 35 ++++++++++++++++----- src/core/project/boxNetworkWriters.ts | 5 ++- src/core/project/manager.boxNetwork.test.ts | 15 +++++++++ 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index 34fb1090b9..fc5ec12976 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -182,7 +182,7 @@ describe("addBoxBedrockTarget", () => { for (const project of [mcp, openai, plain]) { expect(addBoxBedrockTarget(project)).toEqual([]); - expect(boxBedrockPolicy(project)).toBeUndefined(); + expect(boxBedrockPolicy(project, "us-west-2")).toBeUndefined(); } }); @@ -196,18 +196,34 @@ describe("addBoxBedrockTarget", () => { expect(gateway(project).additionalPolicies).toBeUndefined(); }); - test("grants the gateway role the model invoke actions in any region", () => { - expect(boxBedrockPolicy(spec())).toEqual({ + test("grants the gateway role the model invoke actions in the build region, and other regions only through a profile there", () => { + const actions = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]; + expect(boxBedrockPolicy(spec(), "eu-central-1")).toEqual({ Version: "2012-10-17", Statement: [ { - Sid: "BoxedAgentModelCallsThroughGateway", + Sid: "BoxedAgentInferenceProfilesThroughGateway", Effect: "Allow", - Action: ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"], - Resource: [ - "arn:aws:bedrock:*:*:inference-profile/*", - "arn:aws:bedrock:*::foundation-model/*", - ], + Action: actions, + Resource: ["arn:aws:bedrock:eu-central-1:*:inference-profile/*"], + Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, + }, + { + Sid: "BoxedAgentModelsThroughGateway", + Effect: "Allow", + Action: actions, + Resource: ["arn:aws:bedrock:eu-central-1::foundation-model/*"], + }, + { + Sid: "BoxedAgentModelsThroughInferenceProfiles", + Effect: "Allow", + Action: actions, + Resource: ["arn:aws:bedrock:*::foundation-model/*"], + Condition: { + StringLike: { + "bedrock:InferenceProfileArn": "arn:aws:bedrock:eu-central-1:*:inference-profile/*", + }, + }, }, ], }); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index ce970bbb95..cd926245b1 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -114,22 +114,41 @@ export function boxMemoryPolicy( /** * The IAM policy document for {@link BOX_BEDROCK_POLICY_FILE}, or undefined when no boxed runtime - * calls a Bedrock model. A cross-region (`us.`, `global.`) inference profile invokes the model in - * other regions, so both the profiles and the foundation models match any region. + * calls a Bedrock model. The gateway's `bedrock` target calls Bedrock in `region`, the region build + * builds for, so the role may invoke: + * - an inference profile of the project's own account in `region`; + * - a foundation model in `region`; + * - a foundation model in any region only through an inference profile in `region`, which is how + * a cross-region (`us.`, `global.`) profile reaches the models of other regions. */ -export function boxBedrockPolicy(spec: ProjectSpec): Record | undefined { +export function boxBedrockPolicy( + spec: ProjectSpec, + region: string, +): Record | undefined { if (boxedRuntimesCallingBedrock(spec).length === 0) return undefined; + const profiles = `arn:aws:bedrock:${region}:*:inference-profile/*`; return { Version: "2012-10-17", Statement: [ { - Sid: "BoxedAgentModelCallsThroughGateway", + Sid: "BoxedAgentInferenceProfilesThroughGateway", + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [profiles], + Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, + }, + { + Sid: "BoxedAgentModelsThroughGateway", + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [`arn:aws:bedrock:${region}::foundation-model/*`], + }, + { + Sid: "BoxedAgentModelsThroughInferenceProfiles", Effect: "Allow", Action: BEDROCK_INVOKE_ACTIONS, - Resource: [ - "arn:aws:bedrock:*:*:inference-profile/*", - "arn:aws:bedrock:*::foundation-model/*", - ], + Resource: ["arn:aws:bedrock:*::foundation-model/*"], + Condition: { StringLike: { "bedrock:InferenceProfileArn": profiles } }, }, ], }; diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 810e169627..45793bff1b 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -302,7 +302,10 @@ export const defaultTargetsWriter: BoxNetworkWriter = { return { spec: [(copy) => addBoxGatewayTargets(copy, region)], files: [ - { path: BOX_BEDROCK_POLICY_FILE, policy: boxBedrockPolicy(spec) }, + { + path: BOX_BEDROCK_POLICY_FILE, + policy: region === undefined ? undefined : boxBedrockPolicy(spec, region), + }, { path: BOX_MEMORY_POLICY_FILE, policy: region === undefined ? undefined : boxMemoryPolicy(spec, region), diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 69f8386177..432838733f 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -968,6 +968,21 @@ describe("build writes the Bedrock and Memory targets for the region it builds f expect((await runtimeProfile(root)).options).toEqual({ bedrock: { region: "ap-northeast-1" } }); }); + test("writes the gateway role's Bedrock grant for that region", async () => { + const { manager, root } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } }); + + await build(manager, root); + + const policy = JSON.parse(await text(root, "agentcore/box-bedrock-policy.json")) as { + Statement: { Resource: string[] }[]; + }; + expect(policy.Statement.map(({ Resource }) => Resource)).toEqual([ + ["arn:aws:bedrock:eu-central-1:*:inference-profile/*"], + ["arn:aws:bedrock:eu-central-1::foundation-model/*"], + ["arn:aws:bedrock:*::foundation-model/*"], + ]); + }); + test("has box resolve the profile for that region, from a copy it then removes", async () => { // create wrote the profile for us-west-2, the region `agentcore dev` calls Bedrock in. const { manager, root, box } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } }); From ba28e29e69e5cbd0f41a9ffd4f441424c1f2631c Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 15:53:04 -0800 Subject: [PATCH 8/9] fix(build): Build for --region from the TUI too, and keep the writers' JSDoc on BOX_NETWORK_WRITERS Addresses the review of #2886: the build screen called build with no region, so a global --region was ignored there; it passes the region withRegion resolved, as the command does. --- src/core/project/boxNetworkWriters.ts | 2 +- src/handlers/project/build/screen.tsx | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 45793bff1b..412a4eb371 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -486,7 +486,6 @@ function withoutUnsentRoutes( return result; } -/** The writers that build and deploy run before synth, in order. */ /** * 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 @@ -513,6 +512,7 @@ export const boxVersionWriter: BoxNetworkWriter = { }), }; +/** The writers that build and deploy run before synth, in order. */ export const BOX_NETWORK_WRITERS: readonly BoxNetworkWriter[] = [ boxVersionWriter, credentialsWriter, diff --git a/src/handlers/project/build/screen.tsx b/src/handlers/project/build/screen.tsx index 7c7298cf40..17f1441f23 100644 --- a/src/handlers/project/build/screen.tsx +++ b/src/handlers/project/build/screen.tsx @@ -1,6 +1,7 @@ import { useNavigate } from "react-router"; import { ConfirmAction } from "../../../components/ConfirmAction"; import { ProjectKey } from "../../../router"; +import { RegionKey } from "../../keys"; import type { ScreenProps } from "../../types"; import { ProjectGate } from "../ProjectGate"; import type { Project } from "../types"; @@ -22,12 +23,21 @@ export function BuildProjectScreen({ ctx, core }: ScreenProps) { seed={ctx.value(ProjectKey)} onBack={() => navigate(PROJECT_MENU)} > - {(project) => } + {(project) => } ); } -function BuildConfirm({ project, core }: { project: Project; core: ScreenProps["core"] }) { +function BuildConfirm({ + project, + core, + region, +}: { + project: Project; + core: ScreenProps["core"]; + /** The region withRegion resolved, as the build command passes it. */ + region: string | undefined; +}) { const navigate = useNavigate(); // No confirmation: a build changes nothing outside the project directory. @@ -39,7 +49,7 @@ function BuildConfirm({ project, core }: { project: Project; core: ScreenProps[" isPending={false} error={null} action={async function* () { - yield* core.projectManager.build(project); + yield* core.projectManager.build(project, { region }); return { rows: {} }; }} successTitle={builtMessage(project)} From 9b179c8faaf95a45cf5264fa62aa1e57cb3d8458 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Fri, 20 Nov 2026 15:53:05 -0800 Subject: [PATCH 9/9] Revert "fix(box): Scope the Box gateway role's Bedrock grant to the build region" This reverts commit 6072b2c1. #2883 makes the same change and more (the region's partition, and the account in the inference-profile condition), and the two conflict, so the grant lands with #2883. --- src/core/project/boxMemory.test.ts | 34 ++++++-------------- src/core/project/boxMemory.ts | 35 +++++---------------- src/core/project/boxNetworkWriters.ts | 5 +-- src/core/project/manager.boxNetwork.test.ts | 15 --------- 4 files changed, 18 insertions(+), 71 deletions(-) diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index fc5ec12976..34fb1090b9 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -182,7 +182,7 @@ describe("addBoxBedrockTarget", () => { for (const project of [mcp, openai, plain]) { expect(addBoxBedrockTarget(project)).toEqual([]); - expect(boxBedrockPolicy(project, "us-west-2")).toBeUndefined(); + expect(boxBedrockPolicy(project)).toBeUndefined(); } }); @@ -196,34 +196,18 @@ describe("addBoxBedrockTarget", () => { expect(gateway(project).additionalPolicies).toBeUndefined(); }); - test("grants the gateway role the model invoke actions in the build region, and other regions only through a profile there", () => { - const actions = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]; - expect(boxBedrockPolicy(spec(), "eu-central-1")).toEqual({ + test("grants the gateway role the model invoke actions in any region", () => { + expect(boxBedrockPolicy(spec())).toEqual({ Version: "2012-10-17", Statement: [ { - Sid: "BoxedAgentInferenceProfilesThroughGateway", + Sid: "BoxedAgentModelCallsThroughGateway", Effect: "Allow", - Action: actions, - Resource: ["arn:aws:bedrock:eu-central-1:*:inference-profile/*"], - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }, - { - Sid: "BoxedAgentModelsThroughGateway", - Effect: "Allow", - Action: actions, - Resource: ["arn:aws:bedrock:eu-central-1::foundation-model/*"], - }, - { - Sid: "BoxedAgentModelsThroughInferenceProfiles", - Effect: "Allow", - Action: actions, - Resource: ["arn:aws:bedrock:*::foundation-model/*"], - Condition: { - StringLike: { - "bedrock:InferenceProfileArn": "arn:aws:bedrock:eu-central-1:*:inference-profile/*", - }, - }, + Action: ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"], + Resource: [ + "arn:aws:bedrock:*:*:inference-profile/*", + "arn:aws:bedrock:*::foundation-model/*", + ], }, ], }); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index cd926245b1..ce970bbb95 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -114,41 +114,22 @@ export function boxMemoryPolicy( /** * The IAM policy document for {@link BOX_BEDROCK_POLICY_FILE}, or undefined when no boxed runtime - * calls a Bedrock model. The gateway's `bedrock` target calls Bedrock in `region`, the region build - * builds for, so the role may invoke: - * - an inference profile of the project's own account in `region`; - * - a foundation model in `region`; - * - a foundation model in any region only through an inference profile in `region`, which is how - * a cross-region (`us.`, `global.`) profile reaches the models of other regions. + * calls a Bedrock model. A cross-region (`us.`, `global.`) inference profile invokes the model in + * other regions, so both the profiles and the foundation models match any region. */ -export function boxBedrockPolicy( - spec: ProjectSpec, - region: string, -): Record | undefined { +export function boxBedrockPolicy(spec: ProjectSpec): Record | undefined { if (boxedRuntimesCallingBedrock(spec).length === 0) return undefined; - const profiles = `arn:aws:bedrock:${region}:*:inference-profile/*`; return { Version: "2012-10-17", Statement: [ { - Sid: "BoxedAgentInferenceProfilesThroughGateway", - Effect: "Allow", - Action: BEDROCK_INVOKE_ACTIONS, - Resource: [profiles], - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }, - { - Sid: "BoxedAgentModelsThroughGateway", - Effect: "Allow", - Action: BEDROCK_INVOKE_ACTIONS, - Resource: [`arn:aws:bedrock:${region}::foundation-model/*`], - }, - { - Sid: "BoxedAgentModelsThroughInferenceProfiles", + Sid: "BoxedAgentModelCallsThroughGateway", Effect: "Allow", Action: BEDROCK_INVOKE_ACTIONS, - Resource: ["arn:aws:bedrock:*::foundation-model/*"], - Condition: { StringLike: { "bedrock:InferenceProfileArn": profiles } }, + Resource: [ + "arn:aws:bedrock:*:*:inference-profile/*", + "arn:aws:bedrock:*::foundation-model/*", + ], }, ], }; diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 412a4eb371..6efc7e3c6e 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -302,10 +302,7 @@ export const defaultTargetsWriter: BoxNetworkWriter = { return { spec: [(copy) => addBoxGatewayTargets(copy, region)], files: [ - { - path: BOX_BEDROCK_POLICY_FILE, - policy: region === undefined ? undefined : boxBedrockPolicy(spec, region), - }, + { path: BOX_BEDROCK_POLICY_FILE, policy: boxBedrockPolicy(spec) }, { path: BOX_MEMORY_POLICY_FILE, policy: region === undefined ? undefined : boxMemoryPolicy(spec, region), diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 432838733f..69f8386177 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -968,21 +968,6 @@ describe("build writes the Bedrock and Memory targets for the region it builds f expect((await runtimeProfile(root)).options).toEqual({ bedrock: { region: "ap-northeast-1" } }); }); - test("writes the gateway role's Bedrock grant for that region", async () => { - const { manager, root } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } }); - - await build(manager, root); - - const policy = JSON.parse(await text(root, "agentcore/box-bedrock-policy.json")) as { - Statement: { Resource: string[] }[]; - }; - expect(policy.Statement.map(({ Resource }) => Resource)).toEqual([ - ["arn:aws:bedrock:eu-central-1:*:inference-profile/*"], - ["arn:aws:bedrock:eu-central-1::foundation-model/*"], - ["arn:aws:bedrock:*::foundation-model/*"], - ]); - }); - test("has box resolve the profile for that region, from a copy it then removes", async () => { // create wrote the profile for us-west-2, the region `agentcore dev` calls Bedrock in. const { manager, root, box } = await strandsProject({ env: { AWS_REGION: "eu-central-1" } });