From b1c4fe4fc81181dc4319c3890c44cdd4b5af4bfb Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Tue, 24 Nov 2026 14:34:26 -0800 Subject: [PATCH 1/3] feat(box): Let a Box gateway call only the Bedrock model of its runtime The Box gateway's role could invoke every inference profile and every foundation model of the account: agentcore/box-bedrock-policy.json named `inference-profile/*` and `foundation-model/*`. - create records the model a box runtime's code calls in the runtime's existing `modelId` (the --model-id, or the template default), as it already does for LiteLLM. The minimal template calls no model and gets none. The LangChain template now renders `modelId` into model/load.py, as the other templates do, so the code and agentcore.json name the same model. - When every boxed runtime that calls Bedrock has a modelId, build writes a policy for those models only: an inference profile of the account in the region, and its foundation model only through that profile; or a foundation model ID in the region. - When a runtime has no modelId (a project created before this change), build keeps the every-model policy and warns, naming the runtime and the field to set. --- .../agent-python-langchain/model/load.py | 2 +- src/core/project/boxMemory.test.ts | 90 +++++++++++++++++ src/core/project/boxMemory.ts | 96 ++++++++++++++++++- src/core/project/boxNetworkWriters.ts | 8 +- src/core/project/manager.box.test.ts | 33 +++++++ src/core/project/manager.boxNetwork.test.ts | 6 +- src/core/project/manager.tsx | 4 +- src/core/project/templates/project.ts | 19 +++- src/core/project/templates/runtime.ts | 2 + src/projectSchemas/runtime.ts | 13 ++- 10 files changed, 259 insertions(+), 14 deletions(-) diff --git a/src/assets/templates/agent-python-langchain/model/load.py b/src/assets/templates/agent-python-langchain/model/load.py index 581e06e184..a2e432d701 100644 --- a/src/assets/templates/agent-python-langchain/model/load.py +++ b/src/assets/templates/agent-python-langchain/model/load.py @@ -1,7 +1,7 @@ from langchain.chat_models import init_chat_model from langchain_core.language_models import BaseChatModel -MODEL_ID = "global.anthropic.claude-sonnet-5-5" +MODEL_ID = {{safeJson modelId}} def load_model() -> BaseChatModel: diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index 56b434a9f2..efe6772641 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -6,6 +6,7 @@ import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, boxBedrockPolicy, + boxBedrockScopeWarning, } from "./boxMemory"; function spec(options: { entrypoint?: string; memories?: string[] } = {}): ProjectSpec { @@ -135,6 +136,95 @@ describe("boxBedrockPolicy", () => { }); }); +describe("boxBedrockPolicy with the runtime's modelId", () => { + type Statement = Record & { Resource: string[] }; + const ACTIONS = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]; + const withModels = (...models: { modelProvider?: string; modelId?: string }[]) => { + const project = spec(); + const [first] = project.runtimes; + project.runtimes = models.map((model, index) => ({ + ...first!, + name: `agent${index}`, + ...model, + })) as ProjectSpec["runtimes"]; + return project; + }; + const statements = (project: ProjectSpec) => + (boxBedrockPolicy(project, "us-west-2") as { Statement: Statement[] }).Statement; + + test("allows only the runtime's inference profile, and its model only through that profile", () => { + const profile = + "arn:aws:bedrock:us-west-2:${aws:PrincipalAccount}:inference-profile/global.anthropic.claude-sonnet-5-5"; + expect( + statements( + withModels({ modelProvider: "Bedrock", modelId: "global.anthropic.claude-sonnet-5-5" }), + ), + ).toEqual([ + { + Sid: "BoxedAgentInferenceProfileThroughGateway", + Effect: "Allow", + Action: ACTIONS, + Resource: [ + "arn:aws:bedrock:us-west-2:*:inference-profile/global.anthropic.claude-sonnet-5-5", + ], + Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, + }, + { + Sid: "BoxedAgentModelThroughItsInferenceProfile", + Effect: "Allow", + Action: ACTIONS, + Resource: ["arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*"], + Condition: { StringEquals: { "bedrock:InferenceProfileArn": profile } }, + }, + ]); + }); + + test("allows a model ID only as that foundation model in the region", () => { + expect( + statements(withModels({ modelProvider: "Bedrock", modelId: "amazon.nova-pro-v1:0" })), + ).toEqual([ + { + Sid: "BoxedAgentModelThroughGateway", + Effect: "Allow", + Action: ACTIONS, + Resource: ["arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-pro-v1:0"], + }, + ]); + }); + + test("allows the model of each runtime once, each statement with its own Sid", () => { + const policy = statements( + withModels( + { modelProvider: "Bedrock", modelId: "us.anthropic.claude-sonnet-5-5" }, + { modelProvider: "Bedrock", modelId: "us.anthropic.claude-sonnet-5-5" }, + { modelProvider: "LiteLLM", modelId: "bedrock/amazon.nova-pro-v1:0" }, + ), + ); + expect(policy.map(({ Sid }) => Sid)).toEqual([ + "BoxedAgentInferenceProfileThroughGateway1", + "BoxedAgentModelThroughItsInferenceProfile1", + "BoxedAgentModelThroughGateway2", + ]); + }); + + test("keeps every model, and warns, when a runtime that calls a model has no modelId", () => { + const project = withModels( + { modelProvider: "Bedrock", modelId: "global.anthropic.claude-sonnet-5-5" }, + { modelProvider: "Bedrock" }, + ); + expect(statements(project).map(({ Sid }) => Sid)).toEqual([ + "BoxedAgentInferenceProfilesThroughGateway", + "BoxedAgentModelsInRegionThroughGateway", + "BoxedAgentModelsThroughInferenceProfiles", + ]); + expect(boxBedrockScopeWarning(project)).toContain('runtime "agent1" has no modelId'); + }); + + test("gives no warning for a runtime with no model provider, which calls no model as created", () => { + expect(boxBedrockScopeWarning(withModels({}))).toBeUndefined(); + }); +}); + describe("addBoxGatewayTargets", () => { test("adds the bedrock target a boxed agent's model calls take, in the region given", () => { const project = spec(); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index 64034cb988..00d312e485 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -61,6 +61,91 @@ function boxedRuntimesCallingBedrock(spec: ProjectSpec): ProjectRuntime[] { return boxedRuntimes(spec).filter(callsBedrock); } +/** + * The Bedrock model ID or inference profile ID that `runtime`'s code calls, from its `modelId` in + * agentcore.json: the ID itself for the Bedrock provider, the ID after `bedrock/` for LiteLLM. + * Undefined when agentcore.json names no model. + */ +export function bedrockModelIdOf(runtime: ProjectRuntime): string | undefined { + if (runtime.modelId === undefined) return undefined; + if (runtime.modelProvider === "LiteLLM") { + return runtime.modelId.startsWith("bedrock/") + ? runtime.modelId.slice("bedrock/".length) + : undefined; + } + return runtime.modelId; +} + +/** The geographic prefixes of a cross-region inference profile ID, as in `global.anthropic...`. */ +const INFERENCE_PROFILE_PREFIXES = ["global", "us", "eu", "apac", "us-gov", "jp", "au", "ca"]; + +/** The foundation model behind inference profile `id`, or undefined when `id` is a model ID. */ +function modelBehindProfile(id: string): string | undefined { + const [prefix, ...rest] = id.split("."); + return INFERENCE_PROFILE_PREFIXES.includes(prefix!) && rest.length > 1 + ? rest.join(".") + : undefined; +} + +/** + * The statements that let the Box gateway's role call only `modelIds` in `region`: for an inference + * profile, the profile of the role's own account and its foundation model in any region, only + * through that profile (a cross-region profile sends the call to another region); for a model ID, + * that foundation model in `region`. + */ +function scopedBedrockStatements(modelIds: readonly string[], region: string): unknown[] { + const bedrock = `arn:${partition(region).name}:bedrock`; + // A Sid is unique in a policy, so each model's statements end in its number when there are more. + const sid = (name: string, index: number) => (modelIds.length > 1 ? `${name}${index + 1}` : name); + return modelIds.flatMap((id, index) => { + const model = modelBehindProfile(id); + if (model === undefined) { + return [ + { + Sid: sid("BoxedAgentModelThroughGateway", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [`${bedrock}:${region}::foundation-model/${id}`], + }, + ]; + } + const profile = `${bedrock}:${region}:${PRINCIPAL_ACCOUNT}:inference-profile/${id}`; + return [ + { + Sid: sid("BoxedAgentInferenceProfileThroughGateway", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [`${bedrock}:${region}:*:inference-profile/${id}`], + Condition: { StringEquals: { "aws:ResourceAccount": PRINCIPAL_ACCOUNT } }, + }, + { + Sid: sid("BoxedAgentModelThroughItsInferenceProfile", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [`${bedrock}:*::foundation-model/${model}*`], + Condition: { StringEquals: { "bedrock:InferenceProfileArn": profile } }, + }, + ]; + }); +} + +/** + * The warning build gives when the Box gateway's role can call every Bedrock model: a boxed runtime + * that calls a model has no `modelId` in agentcore.json. Undefined when every one has it. + */ +export function boxBedrockScopeWarning(spec: ProjectSpec): string | undefined { + const unnamed = boxedRuntimesCallingBedrock(spec).filter( + (runtime) => runtime.modelProvider !== undefined && bedrockModelIdOf(runtime) === undefined, + ); + if (unnamed.length === 0) return undefined; + const names = unnamed.map(({ name }) => `"${name}"`).join(", "); + return ( + `runtime ${names} has no modelId in agentcore.json, so its Box gateway can call every Bedrock ` + + `model of the account. Set "modelId" to the model ID or inference profile ID its code calls, ` + + "to let the gateway call only that model." + ); +} + /** * The IAM policy document for {@link BOX_BEDROCK_POLICY_FILE}, or undefined when no boxed runtime * calls a Bedrock model. Each ARN is in the partition of `region`, the region of the `bedrock` @@ -74,7 +159,16 @@ export function boxBedrockPolicy( spec: ProjectSpec, region: string, ): Record | undefined { - if (boxedRuntimesCallingBedrock(spec).length === 0) return undefined; + const runtimes = boxedRuntimesCallingBedrock(spec); + if (runtimes.length === 0) return undefined; + // When agentcore.json names the model of each runtime, the role can call only those models. + const modelIds = runtimes.map(bedrockModelIdOf); + if (modelIds.every((id) => id !== undefined)) { + return { + Version: "2012-10-17", + Statement: scopedBedrockStatements([...new Set(modelIds)], region), + }; + } const bedrock = `arn:${partition(region).name}:bedrock`; return { Version: "2012-10-17", diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 9051b257c1..37dffed526 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -21,7 +21,12 @@ import { } from "./boxNetwork"; import { agentCoreDataPlaneHost } from "../../handlers/project/shortcuts"; import { projectGatewayTargetFor } from "./boxNetwork/projectGateways"; -import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, boxBedrockPolicy } from "./boxMemory"; +import { + addBoxGatewayTargets, + BOX_BEDROCK_POLICY_FILE, + boxBedrockPolicy, + boxBedrockScopeWarning, +} from "./boxMemory"; import type { ReadEnvFileOptions } from "../../io/envFile"; import { boxKeyVariables, @@ -390,6 +395,7 @@ export const defaultTargetsWriter: BoxNetworkWriter = { const region = networks[0]?.region; return { spec: [(copy) => addBoxGatewayTargets(copy, region)], + warnings: [boxBedrockScopeWarning(spec)].flatMap((warning) => (warning ? [warning] : [])), files: [ { path: BOX_BEDROCK_POLICY_FILE, diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 14fb8f3480..d56eae6404 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -241,6 +241,39 @@ describe("agentcore create", () => { expect(warnings.includes(boxGatewayLogsNotice("agent-box-egress"))).toBe(projectType === "box"); }); + test.each([ + ["agent-python-strands-box", "global.anthropic.claude-sonnet-5-5"], + ["agent-python-langchain-box", "global.anthropic.claude-sonnet-5-5"], + ["agent-python-strands-box-container", "global.anthropic.claude-sonnet-5-5"], + ["agent-python-minimal-box", undefined], + ["agent-python-strands", undefined], + ] as const)( + "create --template %s records modelId %p, the model its code calls, for its Box gateway's Bedrock policy", + async (template, modelId) => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-box-")); + tempDirectories.push(directory); + process.chdir(directory); + const generator = subject().create({ + name: "example", + skipInstall: true, + skipGit: true, + scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: "agent" }), + }); + let next = await generator.next(); + while (!next.done) next = await generator.next(); + + const [runtime] = (await specOnDisk(next.value)).runtimes as { modelId?: string }[]; + expect(runtime?.modelId).toBe(modelId); + if (template === "agent-python-langchain-box") { + const load = await readFile( + join(directory, "example", "app", "agent", "model", "load.py"), + "utf8", + ); + expect(load).toContain(`MODEL_ID = "${modelId}"`); + } + }, + ); + test('a Box template writes "projectType": "box" and a Box gateway for each runtime', () => { const runtime = (name: string) => ({ name, build: "CodeZip", entrypoint: "main.py", codeLocation: `app/${name}` }) as never; diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index c838c7931e..daed73ecc5 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -1650,10 +1650,10 @@ describe("deploy writes the Box network before the backend deploys", () => { destinations: [`bedrock-agentcore.${region}.amazonaws.com`], secret: { ref: "aws://" }, }); + // create records the template's model in modelId, so the policy names only that model. const bedrockFor = (region: string) => [ - [`arn:aws:bedrock:${region}:*:inference-profile/*`], - [`arn:aws:bedrock:${region}::foundation-model/*`], - ["arn:aws:bedrock:*::foundation-model/*"], + [`arn:aws:bedrock:${region}:*:inference-profile/global.anthropic.claude-sonnet-5-5`], + ["arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*"], ]; await build(manager, root); expect(await authOf("agentcore")).toBeUndefined(); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 75ef58d740..ab5bd40072 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -66,7 +66,7 @@ import { boxNetworkEdits, writeBoxNetworkFiles, } from "./boxNetworkWriters"; -import { boxCodeZipFiles, createProjectTree } from "./templates/project"; +import { boxCodeZipFiles, createProjectTree, recordBoxModelId } from "./templates/project"; import { BOX_CODEZIP_ENTRYPOINT, boxAgentDir, @@ -2289,6 +2289,8 @@ export class FsProjectManager implements ProjectManager { runtime.box = { version: BOX_RELEASE.version }; // Box runs only on AgentCore Runtime V2, as create pins it. runtime.platformVersion = BOX_PLATFORM_VERSION; + // The model its code calls, so build lets its Box gateway call only that model. + recordBoxModelId(runtime, boxInput); // start.py starts `box run` on AgentCore Runtime, and the profile runs the agent. runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; projectSpec.agentCoreGateways.push(AgentCoreGatewaySchema.parse(boxGatewaySpec(name))); diff --git a/src/core/project/templates/project.ts b/src/core/project/templates/project.ts index cb37949608..69ef729719 100644 --- a/src/core/project/templates/project.ts +++ b/src/core/project/templates/project.ts @@ -16,7 +16,7 @@ import { } from "./boxProfile"; import { mergeSpecEntries } from "./spec"; import { boxGatewaySpec } from "../../../projectSchemas/project"; -import { BOX_PLATFORM_VERSION } from "../../../projectSchemas/runtime"; +import { BOX_PLATFORM_VERSION, DEFAULT_MODEL_IDS } from "../../../projectSchemas/runtime"; import type { SpecEntries, Template, TemplateRenderer } from "./types"; import type { EnvLocalEntry } from "../../../handlers/project/types"; @@ -53,8 +53,10 @@ export async function createProjectTree( } // Box runs only on AgentCore Runtime V2, so a box runtime pins it. if (hasBoxProfile(options.runtime)) { - for (const runtime of template.spec.runtimes ?? []) + for (const runtime of template.spec.runtimes ?? []) { runtime.platformVersion = BOX_PLATFORM_VERSION; + recordBoxModelId(runtime, options.runtime); + } } // Only a box template (a `-box` template in the shortcut table) runs its agent in a box, so // only it makes a Box project. @@ -135,6 +137,19 @@ function withBoxContainerBoxVersion(template: Template): void { runtime.box = { version: BOX_RELEASE.version }; } +/** + * Records in a box runtime that calls a Bedrock model the model ID its code renders (--model-id, or + * the template default), so build lets its Box gateway call only that model. A runtime with no + * model provider, such as the minimal template, calls no model and gets none. + */ +export function recordBoxModelId( + runtime: { modelProvider?: string; modelId?: string }, + input: Pick, +): void { + if (runtime.modelId !== undefined || runtime.modelProvider !== "Bedrock") return; + runtime.modelId = input.modelId ?? DEFAULT_MODEL_IDS.Bedrock; +} + const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`; /** diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 15e2a20473..30e8750493 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -260,6 +260,8 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa transformContent: (raw) => templateRenderer.render(raw, { name: toPythonPackageName(input.name), + // The Bedrock model the code calls: --model-id, else the default. + modelId: renderedModelId(input.scaffoldRuntimeInput), // The README says whether traces are collected, which they are not in a box. box: input.scaffoldRuntimeInput.boxTemplate === true, }), diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index a45c8f3fce..f201bdf11f 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -364,11 +364,14 @@ export const ProjectRuntimeSchema = z */ modelProvider: ModelProviderSchema.optional(), /** - * The model id the scaffold rendered into a LiteLLM runtime's code - * (explicit --model-id or the template default). Read by the China - * deploy gate to detect LiteLLM's Bedrock route ('bedrock/' prefix); - * ignored by the CDK app. Delete it together with modelProvider if you - * replace the model wiring by hand. + * The model id the scaffold rendered into the runtime's code (explicit + * --model-id or the template default), for a LiteLLM runtime and for a + * box runtime that calls a Bedrock model. The China deploy gate reads it + * to detect LiteLLM's Bedrock route ('bedrock/' prefix). For a box runtime, + * build lets its Box gateway call only this Bedrock model or inference + * profile; change it when the code calls another model. Ignored by the CDK + * app. Delete it together with modelProvider if you replace the model + * wiring by hand. */ modelId: z.string().min(1).optional(), description: z.string().max(200).optional(), From 5e070e4daa3efbd212ec32232a4dea42966aa918 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Tue, 24 Nov 2026 16:19:20 -0800 Subject: [PATCH 2/3] fix(box): Address the review of the per-model Bedrock policy - A modelId that build cannot scope to falls back, with a warning, instead of writing a policy that matches nothing: build reads a model ID or system inference profile ID (provider.model), a foundation model ARN or a system inference profile ARN (in the ARN's region), and LiteLLM's bedrock/, bedrock/converse/ and bedrock/invoke/ routes. An application inference profile, provisioned, custom or imported model ARN, or an ID that is not provider.model, keeps the every-model policy and the warning. - No list of geographic prefixes: every plain ID gets the profile statement, the model statement through that profile, and the in-region model statement. A model ID's profile statements and a profile ID's model statement name resources that cannot exist, so nothing widens, and in. or a future prefix needs no change. - The warning and the fallback agree: a boxed runtime with no modelProvider (minimal-box, or an added runtime) counts as calling Bedrock in both, so the project keeps every model and build says which runtime to give a modelId. The warning names several runtimes in one sentence. - The no-op recordBoxModelId call in add runtime is removed. - docs/box-local-testing.md and the strands and LangChain READMEs of a box runtime say that the Box gateway calls only the model in modelId, so the code and modelId change together. - The comment on foundation-model/* says why it ends in *. - Tests: an in. profile, a plain model ID, a profile ARN in another region, a foundation model ARN, each LiteLLM route (asserting the resource), the three kinds that fall back, a mixed project, the plural warning; create with a non-default model for strands-box and langchain-box (the code and modelId match), a2a-python-strands-box and agui-python-strands-box; build rewrites the policy to a changed modelId and warns when it is missing. --- docs/box-local-testing.md | 5 + .../agent-python-langchain/README.md | 2 +- .../templates/agent-python-strands/README.md | 4 + src/core/project/boxMemory.test.ts | 137 ++++++++++----- src/core/project/boxMemory.ts | 166 +++++++++++------- src/core/project/manager.box.test.ts | 28 +-- src/core/project/manager.boxNetwork.test.ts | 45 +++++ src/core/project/manager.tsx | 4 +- src/core/project/templates/project.ts | 6 +- src/core/project/templates/runtime.test.ts | 22 ++- src/core/project/templates/runtime.ts | 2 + 11 files changed, 291 insertions(+), 130 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index 8b57579b68..3000ac6ea9 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -483,6 +483,11 @@ Local checks, in `agentcore/agentcore.json`: - `"projectType": "box"`. - A gateway named `agent-box-egress` with a `bedrock` passthrough target in the deploy region, and an `egress-github` target for `https://api.github.com`. +- The runtime's `"modelId"`, the Bedrock model its code calls. Build writes + `agentcore/box-bedrock-policy.json` for the Box gateways' roles with that model only. To use + another model, change `model/load.py` and `modelId` together, then deploy again; otherwise Bedrock + denies the call. Without a `modelId` build can scope to, the policy allows every model of the + account and build warns. - A credential named `github` with `authorizerType: ApiKeyCredentialProvider`. Live checks, after deploy. Deploy names each AWS resource after the project and the deploy target diff --git a/src/assets/templates/agent-python-langchain/README.md b/src/assets/templates/agent-python-langchain/README.md index 280f2ce6ad..50a0a26d34 100644 --- a/src/assets/templates/agent-python-langchain/README.md +++ b/src/assets/templates/agent-python-langchain/README.md @@ -11,7 +11,7 @@ session, and streams its response. completed model message back as a JSON event of content blocks. An `InMemorySaver` checkpointer keyed on the Runtime session id carries history between turns. -- `model/load.py`: creates the Bedrock chat model with `init_chat_model`. +- `model/load.py`: creates the Bedrock chat model with `init_chat_model`.{{#if box}} On AgentCore Runtime the Box gateway may call only the Bedrock model in this runtime's `modelId` in `agentcore/agentcore.json`. To use another model, change `model/load.py` and `modelId` together, then deploy again; otherwise Bedrock denies the call.{{/if}} - `pyproject.toml`: Python dependencies, managed with [uv](https://docs.astral.sh/uv/). `agentcore create` has already run `uv sync` for you (unless you passed `--skip-install`), so `.venv/` is ready. diff --git a/src/assets/templates/agent-python-strands/README.md b/src/assets/templates/agent-python-strands/README.md index 214088ffcb..ddd05f4b01 100644 --- a/src/assets/templates/agent-python-strands/README.md +++ b/src/assets/templates/agent-python-strands/README.md @@ -12,6 +12,10 @@ The main entrypoint to your app is defined in `main.py`. Using the AgentCore SDK file defines a Starlette ASGI app with the Strands Agent SDK running within. `model/load.py` instantiates the chosen model provider. +{{#if box}} + +On AgentCore Runtime the Box gateway may call only the Bedrock model in this runtime's `modelId` in `agentcore/agentcore.json`. To use another model, change `model/load.py` and `modelId` together, then deploy again; otherwise Bedrock denies the call. +{{/if}} ## Memory diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index efe6772641..7d644f303c 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -138,7 +138,6 @@ describe("boxBedrockPolicy", () => { describe("boxBedrockPolicy with the runtime's modelId", () => { type Statement = Record & { Resource: string[] }; - const ACTIONS = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]; const withModels = (...models: { modelProvider?: string; modelId?: string }[]) => { const project = spec(); const [first] = project.runtimes; @@ -149,79 +148,121 @@ describe("boxBedrockPolicy with the runtime's modelId", () => { })) as ProjectSpec["runtimes"]; return project; }; - const statements = (project: ProjectSpec) => + const policy = (project: ProjectSpec) => (boxBedrockPolicy(project, "us-west-2") as { Statement: Statement[] }).Statement; + const resources = (project: ProjectSpec) => policy(project).map(({ Resource }) => Resource[0]); + const bedrock = (modelId: string) => withModels({ modelProvider: "Bedrock", modelId }); + const EVERY_MODEL = [ + "arn:aws:bedrock:us-west-2:*:inference-profile/*", + "arn:aws:bedrock:us-west-2::foundation-model/*", + "arn:aws:bedrock:*::foundation-model/*", + ]; - test("allows only the runtime's inference profile, and its model only through that profile", () => { - const profile = - "arn:aws:bedrock:us-west-2:${aws:PrincipalAccount}:inference-profile/global.anthropic.claude-sonnet-5-5"; + test("allows a system inference profile of the account, and its model only through that profile", () => { + const statements = policy(bedrock("global.anthropic.claude-sonnet-5-5")); + expect(statements.map(({ Resource }) => Resource[0])).toEqual([ + "arn:aws:bedrock:us-west-2:*:inference-profile/global.anthropic.claude-sonnet-5-5", + "arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*", + "arn:aws:bedrock:us-west-2::foundation-model/global.anthropic.claude-sonnet-5-5", + ]); + expect(statements[0]!.Condition).toEqual({ + StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" }, + }); + expect(statements[1]!.Condition).toEqual({ + StringEquals: { + "bedrock:InferenceProfileArn": + "arn:aws:bedrock:us-west-2:${aws:PrincipalAccount}:inference-profile/global.anthropic.claude-sonnet-5-5", + }, + }); + expect(statements[2]!.Condition).toBeUndefined(); + }); + + test("needs no list of geographic prefixes: an in. profile scopes like any other", () => { + expect(resources(bedrock("in.anthropic.claude-sonnet-5"))).toContain( + "arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5*", + ); + }); + + test("allows a plain model ID as that foundation model in the region", () => { + expect(resources(bedrock("amazon.nova-pro-v1:0"))).toContain( + "arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-pro-v1:0", + ); + }); + + test("allows a system inference profile ARN in its own region, and no model by itself", () => { expect( - statements( - withModels({ modelProvider: "Bedrock", modelId: "global.anthropic.claude-sonnet-5-5" }), + resources( + bedrock( + "arn:aws:bedrock:eu-west-1:123456789012:inference-profile/eu.anthropic.claude-sonnet-5-5", + ), ), ).toEqual([ - { - Sid: "BoxedAgentInferenceProfileThroughGateway", - Effect: "Allow", - Action: ACTIONS, - Resource: [ - "arn:aws:bedrock:us-west-2:*:inference-profile/global.anthropic.claude-sonnet-5-5", - ], - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }, - { - Sid: "BoxedAgentModelThroughItsInferenceProfile", - Effect: "Allow", - Action: ACTIONS, - Resource: ["arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*"], - Condition: { StringEquals: { "bedrock:InferenceProfileArn": profile } }, - }, + "arn:aws:bedrock:eu-west-1:*:inference-profile/eu.anthropic.claude-sonnet-5-5", + "arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*", ]); }); - test("allows a model ID only as that foundation model in the region", () => { + test("allows a foundation model ARN as that model in its own region only", () => { expect( - statements(withModels({ modelProvider: "Bedrock", modelId: "amazon.nova-pro-v1:0" })), - ).toEqual([ - { - Sid: "BoxedAgentModelThroughGateway", - Effect: "Allow", - Action: ACTIONS, - Resource: ["arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-pro-v1:0"], - }, - ]); + resources(bedrock("arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0")), + ).toEqual(["arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0"]); + }); + + test.each([ + "bedrock/us.anthropic.claude-sonnet-5-5", + "bedrock/converse/us.anthropic.claude-sonnet-5-5", + "bedrock/invoke/us.anthropic.claude-sonnet-5-5", + ])("scopes LiteLLM's Bedrock route %s to the model after it", (modelId) => { + expect(resources(withModels({ modelProvider: "LiteLLM", modelId }))[0]).toBe( + "arn:aws:bedrock:us-west-2:*:inference-profile/us.anthropic.claude-sonnet-5-5", + ); + }); + + test.each([ + [ + "an application inference profile ARN", + "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abc123", + ], + ["a provisioned model ARN", "arn:aws:bedrock:us-west-2:123456789012:provisioned-model/abc123"], + ["an ID that is not provider.model", "my-model"], + ])("keeps every model, and warns, for %s", (_kind, modelId) => { + const project = bedrock(modelId); + expect(resources(project)).toEqual(EVERY_MODEL); + expect(boxBedrockScopeWarning(project)).toContain('runtime "agent0" has no modelId'); }); test("allows the model of each runtime once, each statement with its own Sid", () => { - const policy = statements( + const statements = policy( withModels( { modelProvider: "Bedrock", modelId: "us.anthropic.claude-sonnet-5-5" }, { modelProvider: "Bedrock", modelId: "us.anthropic.claude-sonnet-5-5" }, { modelProvider: "LiteLLM", modelId: "bedrock/amazon.nova-pro-v1:0" }, ), ); - expect(policy.map(({ Sid }) => Sid)).toEqual([ - "BoxedAgentInferenceProfileThroughGateway1", - "BoxedAgentModelThroughItsInferenceProfile1", - "BoxedAgentModelThroughGateway2", - ]); + const sids = statements.map(({ Sid }) => Sid); + expect(new Set(sids).size).toBe(sids.length); + expect(statements.filter(({ Sid }) => String(Sid).endsWith("1"))).toHaveLength(3); + expect(statements.filter(({ Sid }) => String(Sid).endsWith("2"))).toHaveLength(3); }); - test("keeps every model, and warns, when a runtime that calls a model has no modelId", () => { + test("keeps every model, and warns, when a runtime with no model provider calls Bedrock with no modelId", () => { + // A minimal-box or an added runtime has no modelProvider, and build counts it as calling Bedrock. const project = withModels( { modelProvider: "Bedrock", modelId: "global.anthropic.claude-sonnet-5-5" }, - { modelProvider: "Bedrock" }, + {}, ); - expect(statements(project).map(({ Sid }) => Sid)).toEqual([ - "BoxedAgentInferenceProfilesThroughGateway", - "BoxedAgentModelsInRegionThroughGateway", - "BoxedAgentModelsThroughInferenceProfiles", - ]); + expect(resources(project)).toEqual(EVERY_MODEL); expect(boxBedrockScopeWarning(project)).toContain('runtime "agent1" has no modelId'); }); - test("gives no warning for a runtime with no model provider, which calls no model as created", () => { - expect(boxBedrockScopeWarning(withModels({}))).toBeUndefined(); + test("names each unscoped runtime in one sentence", () => { + expect(boxBedrockScopeWarning(withModels({}, {}, {}))).toContain( + 'runtimes "agent0", "agent1" and "agent2" have no modelId', + ); + }); + + test("gives no warning when the policy is scoped", () => { + expect(boxBedrockScopeWarning(bedrock("global.anthropic.claude-sonnet-5-5"))).toBeUndefined(); }); }); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index 00d312e485..8207c3e38b 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -61,88 +61,127 @@ function boxedRuntimesCallingBedrock(spec: ProjectSpec): ProjectRuntime[] { return boxedRuntimes(spec).filter(callsBedrock); } +/** A Bedrock model a Box gateway may call: its ID, and the region its ARN names, if any. */ +interface ScopedModel { + readonly id: string; + /** The region of the ARN the runtime names; the build region when the runtime names a plain ID. */ + readonly region?: string; + /** What the ARN names, when the runtime names an ARN. */ + readonly kind?: "inference-profile" | "foundation-model"; +} + +/** A Bedrock model ID or system inference profile ID: `provider.model` or `geo.provider.model`. */ +const MODEL_ID_PATTERN = /^[a-z0-9-]+\.[A-Za-z0-9._:-]+$/; + +/** An ARN of a system inference profile or a foundation model: the two a Box gateway can scope. */ +const SCOPED_ARN_PATTERN = + /^arn:[a-z-]+:bedrock:([a-z0-9-]*):[0-9]*:(inference-profile|foundation-model)\/(.+)$/; + /** - * The Bedrock model ID or inference profile ID that `runtime`'s code calls, from its `modelId` in - * agentcore.json: the ID itself for the Bedrock provider, the ID after `bedrock/` for LiteLLM. - * Undefined when agentcore.json names no model. + * The Bedrock model that `runtime`'s code calls, from its `modelId` in agentcore.json, or undefined + * when build cannot scope a policy to it: no `modelId`, a LiteLLM model that does not route to + * Bedrock, or an ID or ARN of another kind (application inference profile, provisioned, custom or + * imported model). LiteLLM's `bedrock/`, `bedrock/converse/` and `bedrock/invoke/` routes give the ID + * after them. A system inference profile ARN or a foundation model ARN gives its ID and region. */ -export function bedrockModelIdOf(runtime: ProjectRuntime): string | undefined { - if (runtime.modelId === undefined) return undefined; +export function bedrockModelOf(runtime: ProjectRuntime): ScopedModel | undefined { + let id = runtime.modelId; + if (id === undefined) return undefined; if (runtime.modelProvider === "LiteLLM") { - return runtime.modelId.startsWith("bedrock/") - ? runtime.modelId.slice("bedrock/".length) - : undefined; + if (!id.startsWith("bedrock/")) return undefined; + id = id.slice("bedrock/".length).replace(/^(converse|invoke)\//, ""); } - return runtime.modelId; -} - -/** The geographic prefixes of a cross-region inference profile ID, as in `global.anthropic...`. */ -const INFERENCE_PROFILE_PREFIXES = ["global", "us", "eu", "apac", "us-gov", "jp", "au", "ca"]; - -/** The foundation model behind inference profile `id`, or undefined when `id` is a model ID. */ -function modelBehindProfile(id: string): string | undefined { - const [prefix, ...rest] = id.split("."); - return INFERENCE_PROFILE_PREFIXES.includes(prefix!) && rest.length > 1 - ? rest.join(".") - : undefined; + const arn = SCOPED_ARN_PATTERN.exec(id); + if (arn) { + const [, region, kind, rest] = arn; + if (!MODEL_ID_PATTERN.test(rest!)) return undefined; + return { + id: rest!, + ...(region && { region }), + kind: kind as "inference-profile" | "foundation-model", + }; + } + return MODEL_ID_PATTERN.test(id) ? { id } : undefined; } /** - * The statements that let the Box gateway's role call only `modelIds` in `region`: for an inference - * profile, the profile of the role's own account and its foundation model in any region, only - * through that profile (a cross-region profile sends the call to another region); for a model ID, - * that foundation model in `region`. + * The statements that let the Box gateway's role call only `models`. A call through an inference + * profile is authorized twice: on the profile, and on the foundation model in the region the + * profile sends it to, so for a profile the role gets the profile of its own account and the model + * behind it in any region, only through that profile. A plain ID gets all three statements, with + * no list of geographic prefixes to keep current: for a model ID the profile statements name a + * profile that cannot exist, and for a profile ID the in-region model statement a model that cannot + * exist, so nothing widens. An ARN gets only the statements of its kind, in its region. */ -function scopedBedrockStatements(modelIds: readonly string[], region: string): unknown[] { - const bedrock = `arn:${partition(region).name}:bedrock`; +function scopedBedrockStatements(models: readonly ScopedModel[], buildRegion: string): unknown[] { + const bedrock = `arn:${partition(buildRegion).name}:bedrock`; // A Sid is unique in a policy, so each model's statements end in its number when there are more. - const sid = (name: string, index: number) => (modelIds.length > 1 ? `${name}${index + 1}` : name); - return modelIds.flatMap((id, index) => { - const model = modelBehindProfile(id); - if (model === undefined) { - return [ + const sid = (name: string, index: number) => (models.length > 1 ? `${name}${index + 1}` : name); + return models.flatMap(({ id, region = buildRegion, kind }, index) => { + const statements: unknown[] = []; + if (kind !== "foundation-model") { + // The model ID behind a profile ID: the ID without its geographic prefix, as `global.`. + const model = id.split(".").slice(1).join("."); + statements.push( + { + Sid: sid("BoxedAgentInferenceProfileThroughGateway", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + Resource: [`${bedrock}:${region}:*:inference-profile/${id}`], + Condition: { StringEquals: { "aws:ResourceAccount": PRINCIPAL_ACCOUNT } }, + }, { - Sid: sid("BoxedAgentModelThroughGateway", index), + Sid: sid("BoxedAgentModelThroughItsInferenceProfile", index), Effect: "Allow", Action: BEDROCK_INVOKE_ACTIONS, - Resource: [`${bedrock}:${region}::foundation-model/${id}`], + // The foundation model's ID carries a version that the profile's does not + // (`anthropic.claude-sonnet-5-5` serves `anthropic.claude-sonnet-5-5--v1:0`), so the + // ID ends in `*`. The condition holds it to the one profile, so the prefix widens nothing. + Resource: [`${bedrock}:*::foundation-model/${model}*`], + Condition: { + StringEquals: { + "bedrock:InferenceProfileArn": `${bedrock}:${region}:${PRINCIPAL_ACCOUNT}:inference-profile/${id}`, + }, + }, }, - ]; + ); } - const profile = `${bedrock}:${region}:${PRINCIPAL_ACCOUNT}:inference-profile/${id}`; - return [ - { - Sid: sid("BoxedAgentInferenceProfileThroughGateway", index), - Effect: "Allow", - Action: BEDROCK_INVOKE_ACTIONS, - Resource: [`${bedrock}:${region}:*:inference-profile/${id}`], - Condition: { StringEquals: { "aws:ResourceAccount": PRINCIPAL_ACCOUNT } }, - }, - { - Sid: sid("BoxedAgentModelThroughItsInferenceProfile", index), + if (kind !== "inference-profile") { + statements.push({ + Sid: sid("BoxedAgentModelThroughGateway", index), Effect: "Allow", Action: BEDROCK_INVOKE_ACTIONS, - Resource: [`${bedrock}:*::foundation-model/${model}*`], - Condition: { StringEquals: { "bedrock:InferenceProfileArn": profile } }, - }, - ]; + Resource: [`${bedrock}:${region}::foundation-model/${id}`], + }); + } + return statements; }); } +/** The boxed runtimes that call Bedrock with no model build can scope the Box gateways' policy to. */ +function unscopedRuntimes(spec: ProjectSpec): ProjectRuntime[] { + return boxedRuntimesCallingBedrock(spec).filter( + (runtime) => bedrockModelOf(runtime) === undefined, + ); +} + /** - * The warning build gives when the Box gateway's role can call every Bedrock model: a boxed runtime - * that calls a model has no `modelId` in agentcore.json. Undefined when every one has it. + * The warning build gives when the Box gateways can call every Bedrock model of the account, as + * {@link boxBedrockPolicy} falls back: a boxed runtime that calls Bedrock has no `modelId` that build + * can scope to. Undefined when the policy is scoped. */ export function boxBedrockScopeWarning(spec: ProjectSpec): string | undefined { - const unnamed = boxedRuntimesCallingBedrock(spec).filter( - (runtime) => runtime.modelProvider !== undefined && bedrockModelIdOf(runtime) === undefined, - ); - if (unnamed.length === 0) return undefined; - const names = unnamed.map(({ name }) => `"${name}"`).join(", "); + const unscoped = unscopedRuntimes(spec).map(({ name }) => `"${name}"`); + if (unscoped.length === 0) return undefined; + const names = + unscoped.length === 1 + ? `runtime ${unscoped[0]} has` + : `runtimes ${unscoped.slice(0, -1).join(", ")} and ${unscoped.at(-1)} have`; return ( - `runtime ${names} has no modelId in agentcore.json, so its Box gateway can call every Bedrock ` + - `model of the account. Set "modelId" to the model ID or inference profile ID its code calls, ` + - "to let the gateway call only that model." + `${names} no modelId in agentcore.json that build can scope to (a Bedrock model ID or ` + + "inference profile ID, or the ARN of a foundation model or system inference profile), so the " + + 'Box gateways of this project can call every Bedrock model of the account. Set "modelId" ' + + "to the model its code calls, then build again." ); } @@ -162,11 +201,14 @@ export function boxBedrockPolicy( const runtimes = boxedRuntimesCallingBedrock(spec); if (runtimes.length === 0) return undefined; // When agentcore.json names the model of each runtime, the role can call only those models. - const modelIds = runtimes.map(bedrockModelIdOf); - if (modelIds.every((id) => id !== undefined)) { + if (unscopedRuntimes(spec).length === 0) { + const models = new Map(); + for (const model of runtimes.map(bedrockModelOf)) { + models.set(JSON.stringify([model!.id, model!.region, model!.kind]), model!); + } return { Version: "2012-10-17", - Statement: scopedBedrockStatements([...new Set(modelIds)], region), + Statement: scopedBedrockStatements([...models.values()], region), }; } const bedrock = `arn:${partition(region).name}:bedrock`; diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index d56eae6404..69b9624660 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -241,15 +241,19 @@ describe("agentcore create", () => { expect(warnings.includes(boxGatewayLogsNotice("agent-box-egress"))).toBe(projectType === "box"); }); + const DEFAULT_MODEL = "global.anthropic.claude-sonnet-5-5"; test.each([ - ["agent-python-strands-box", "global.anthropic.claude-sonnet-5-5"], - ["agent-python-langchain-box", "global.anthropic.claude-sonnet-5-5"], - ["agent-python-strands-box-container", "global.anthropic.claude-sonnet-5-5"], - ["agent-python-minimal-box", undefined], - ["agent-python-strands", undefined], + ["agent-python-strands-box", undefined, DEFAULT_MODEL], + ["agent-python-strands-box", "us.amazon.nova-pro-v1:0", "us.amazon.nova-pro-v1:0"], + ["agent-python-langchain-box", "us.amazon.nova-pro-v1:0", "us.amazon.nova-pro-v1:0"], + ["agent-python-strands-box-container", undefined, DEFAULT_MODEL], + ["a2a-python-strands-box", undefined, DEFAULT_MODEL], + ["agui-python-strands-box", undefined, DEFAULT_MODEL], + ["agent-python-minimal-box", undefined, undefined], + ["agent-python-strands", undefined, undefined], ] as const)( - "create --template %s records modelId %p, the model its code calls, for its Box gateway's Bedrock policy", - async (template, modelId) => { + "create --template %s with model %p records modelId %p, the model its code calls", + async (template, inputModelId, modelId) => { const directory = await mkdtemp(join(tmpdir(), "agentcore-box-")); tempDirectories.push(directory); process.chdir(directory); @@ -257,19 +261,23 @@ describe("agentcore create", () => { name: "example", skipInstall: true, skipGit: true, - scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: "agent" }), + scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { + runtimeName: "agent", + ...(inputModelId && { modelId: inputModelId }), + }), }); let next = await generator.next(); while (!next.done) next = await generator.next(); const [runtime] = (await specOnDisk(next.value)).runtimes as { modelId?: string }[]; expect(runtime?.modelId).toBe(modelId); - if (template === "agent-python-langchain-box") { + if (modelId !== undefined && template.endsWith("-box") && !template.includes("container")) { + // The code calls the same model that agentcore.json records. const load = await readFile( join(directory, "example", "app", "agent", "model", "load.py"), "utf8", ); - expect(load).toContain(`MODEL_ID = "${modelId}"`); + expect(load).toContain(`"${modelId}"`); } }, ); diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index daed73ecc5..8e7318a585 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -1061,6 +1061,50 @@ describe("build routes the other gateways of the project for the boxed agent", ( }); }); +describe("build scopes the Box gateways' Bedrock policy to the runtime's modelId", () => { + const policyResources = async (root: string) => + JSON.parse(await text(root, "agentcore/box-bedrock-policy.json")).Statement.map( + ({ Resource }: { Resource: string[] }) => Resource[0], + ); + const setModelId = async (root: string, modelId: string | undefined) => { + const spec = JSON.parse(await text(root, SPEC)); + spec.runtimes[0].modelId = modelId; + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + }; + + test("rewrites the policy to a changed modelId, with no grant of the old model left", async () => { + const { manager, root } = await strandsProject(); + await build(manager, root); + expect(await policyResources(root)).toContain( + "arn:aws:bedrock:us-west-2:*:inference-profile/global.anthropic.claude-sonnet-5-5", + ); + + await setModelId(root, "us.amazon.nova-pro-v1:0"); + const { warnings } = await build(manager, root); + + const resources = await policyResources(root); + expect(resources).toContain( + "arn:aws:bedrock:us-west-2:*:inference-profile/us.amazon.nova-pro-v1:0", + ); + expect(JSON.stringify(resources)).not.toContain("claude-sonnet-5-5"); + expect(warnings.some((warning) => warning.includes("no modelId"))).toBe(false); + }); + + test("keeps every model, and warns, when the runtime has no modelId", async () => { + const { manager, root } = await strandsProject(); + await setModelId(root, undefined); + + const { warnings } = await build(manager, root); + + expect(await policyResources(root)).toEqual([ + "arn:aws:bedrock:us-west-2:*:inference-profile/*", + "arn:aws:bedrock:us-west-2::foundation-model/*", + "arn:aws:bedrock:*::foundation-model/*", + ]); + expect(warnings).toContainEqual(expect.stringContaining("has no modelId in agentcore.json")); + }); +}); + 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. @@ -1654,6 +1698,7 @@ describe("deploy writes the Box network before the backend deploys", () => { const bedrockFor = (region: string) => [ [`arn:aws:bedrock:${region}:*:inference-profile/global.anthropic.claude-sonnet-5-5`], ["arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-5-5*"], + [`arn:aws:bedrock:${region}::foundation-model/global.anthropic.claude-sonnet-5-5`], ]; await build(manager, root); expect(await authOf("agentcore")).toBeUndefined(); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index ab5bd40072..75ef58d740 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -66,7 +66,7 @@ import { boxNetworkEdits, writeBoxNetworkFiles, } from "./boxNetworkWriters"; -import { boxCodeZipFiles, createProjectTree, recordBoxModelId } from "./templates/project"; +import { boxCodeZipFiles, createProjectTree } from "./templates/project"; import { BOX_CODEZIP_ENTRYPOINT, boxAgentDir, @@ -2289,8 +2289,6 @@ export class FsProjectManager implements ProjectManager { runtime.box = { version: BOX_RELEASE.version }; // Box runs only on AgentCore Runtime V2, as create pins it. runtime.platformVersion = BOX_PLATFORM_VERSION; - // The model its code calls, so build lets its Box gateway call only that model. - recordBoxModelId(runtime, boxInput); // start.py starts `box run` on AgentCore Runtime, and the profile runs the agent. runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; projectSpec.agentCoreGateways.push(AgentCoreGatewaySchema.parse(boxGatewaySpec(name))); diff --git a/src/core/project/templates/project.ts b/src/core/project/templates/project.ts index 69ef729719..ce97daa0e1 100644 --- a/src/core/project/templates/project.ts +++ b/src/core/project/templates/project.ts @@ -138,11 +138,11 @@ function withBoxContainerBoxVersion(template: Template): void { } /** - * Records in a box runtime that calls a Bedrock model the model ID its code renders (--model-id, or - * the template default), so build lets its Box gateway call only that model. A runtime with no + * Records in a box runtime that calls a Bedrock model the model ID its code renders (the template + * default, or the scaffold input's modelId), so build lets its Box gateway call only that model. A runtime with no * model provider, such as the minimal template, calls no model and gets none. */ -export function recordBoxModelId( +function recordBoxModelId( runtime: { modelProvider?: string; modelId?: string }, input: Pick, ): void { diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index 67efb16d70..1158ebf3a5 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -112,7 +112,8 @@ describe("runtime templates", () => { expect(runtime.instrumentation).toBeUndefined(); }); - // A box template is the Strands template with two files of agent-python-strands-box in place. + // A box template is the Strands template with two files of agent-python-strands-box in place, + // and one more README paragraph. test("agent-python-strands-box-container writes the Strands files, with its own Dockerfile and .gitignore", async () => { const files = async (dir: string) => Object.fromEntries( @@ -133,9 +134,24 @@ describe("runtime templates", () => { ); expect(Object.keys(box).sort()).toEqual(Object.keys(plain).sort()); - const { Dockerfile: boxDockerfile, ".gitignore": boxGitignore, ...rest } = box; - const { Dockerfile: plainDockerfile, ".gitignore": plainGitignore, ...plainRest } = plain; + const { + Dockerfile: boxDockerfile, + ".gitignore": boxGitignore, + "README.md": boxReadme, + ...rest + } = box; + const { + Dockerfile: plainDockerfile, + ".gitignore": plainGitignore, + "README.md": plainReadme, + ...plainRest + } = plain; expect(rest).toEqual(plainRest); + // The box README adds one paragraph: its Box gateway calls only the model in modelId. + const modelParagraph = boxReadme!.match( + /\n\nOn AgentCore Runtime the Box gateway may call only[^\n]*\n/, + )!; + expect(boxReadme!.replace(modelParagraph[0], "\n")).toEqual(plainReadme!); expect(boxDockerfile).toContain("box run"); expect(plainDockerfile).not.toContain("box run"); expect(boxGitignore).toContain(".box-dist/"); diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 30e8750493..91fd032b06 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -287,6 +287,8 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa memoryEnvVarName: memoryEnvVarName(memory?.name ?? defaultMemoryName(input.name)), ...modelScaffold.templateRenderContext, enableOtel: true, + // The README says that the Box gateway calls only the model in modelId. + box: input.scaffoldRuntimeInput.boxTemplate === true, // The strands template's entrypoint is fixed to main.py; the container Dockerfile launches it as the `main` module. entrypoint: "main", }; From b04d4874110aa3e3fba6241357e2ccb415b0402b Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Tue, 24 Nov 2026 23:08:06 -0800 Subject: [PATCH 3/3] fix(box): Address the follow-ups of the review of the per-model Bedrock policy - An ARN of another partition than the build's falls back to the every-model policy with the warning: it names a model the gateway's role can never call. - The warning says that a runtime whose code calls no model needs no modelId. - The A2A and AG-UI box READMEs get the paragraph that ties the model to modelId, as the strands and LangChain ones do. - Tests: a foundation model ARN with a wildcard, a wildcard model ID and an ARN of another partition fall back; the multi-runtime policy has the deduplicated statement count; create renders the modelId paragraph in the README of strands-box, langchain-box, a2a-strands-box and agui-strands-box. Removing the ARN ID check, the dedupe, or the LangChain README paragraph now fails a test. --- .../templates/a2a-python-strands/README.md | 5 +++- .../templates/agui-python-strands/README.md | 5 +++- src/core/project/boxMemory.test.ts | 12 +++++++- src/core/project/boxMemory.ts | 28 ++++++++++------- src/core/project/boxNetworkWriters.ts | 4 ++- src/core/project/manager.box.test.ts | 30 +++++++++++++++++++ src/core/project/templates/runtime.ts | 4 +++ 7 files changed, 74 insertions(+), 14 deletions(-) diff --git a/src/assets/templates/a2a-python-strands/README.md b/src/assets/templates/a2a-python-strands/README.md index feef497dc6..aab75d9a47 100644 --- a/src/assets/templates/a2a-python-strands/README.md +++ b/src/assets/templates/a2a-python-strands/README.md @@ -8,7 +8,10 @@ This agent speaks the A2A protocol. Other agents discover it via its agent card `/.well-known/agent-card.json` and invoke it with JSON-RPC (`message/send`, `message/stream`) at the server root, matching the AgentCore Runtime A2A service contract. -## Memory +{{#if box}} +On AgentCore Runtime the Box gateway may call only the Bedrock model in this runtime's `modelId` in `agentcore/agentcore.json`. To use another model, change `model/load.py` and `modelId` together, then deploy again; otherwise Bedrock denies the call. + +{{/if}}## 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 diff --git a/src/assets/templates/agui-python-strands/README.md b/src/assets/templates/agui-python-strands/README.md index 5a0918afe0..b5fd30404f 100644 --- a/src/assets/templates/agui-python-strands/README.md +++ b/src/assets/templates/agui-python-strands/README.md @@ -9,7 +9,10 @@ streams agent-to-UI events over HTTP. It exposes an `/invocations` endpoint that an AG-UI `RunAgentInput` body and streams the response back as AG-UI server-sent events, matching the AgentCore Runtime HTTP service contract. -## Memory +{{#if box}} +On AgentCore Runtime the Box gateway may call only the Bedrock model in this runtime's `modelId` in `agentcore/agentcore.json`. To use another model, change `model/load.py` and `modelId` together, then deploy again; otherwise Bedrock denies the call. + +{{/if}}## 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 diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index 7d644f303c..fc0640bccf 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -225,10 +225,18 @@ describe("boxBedrockPolicy with the runtime's modelId", () => { ], ["a provisioned model ARN", "arn:aws:bedrock:us-west-2:123456789012:provisioned-model/abc123"], ["an ID that is not provider.model", "my-model"], + ["a foundation model ARN with a wildcard", "arn:aws:bedrock:us-west-2::foundation-model/*"], + ["a wildcard model ID", "anthropic.*"], + [ + "an ARN of another partition", + "arn:aws-cn:bedrock:cn-north-1::foundation-model/amazon.nova-pro-v1:0", + ], ])("keeps every model, and warns, for %s", (_kind, modelId) => { const project = bedrock(modelId); expect(resources(project)).toEqual(EVERY_MODEL); - expect(boxBedrockScopeWarning(project)).toContain('runtime "agent0" has no modelId'); + expect(boxBedrockScopeWarning(project, "us-west-2")).toContain( + 'runtime "agent0" has no modelId', + ); }); test("allows the model of each runtime once, each statement with its own Sid", () => { @@ -241,6 +249,8 @@ describe("boxBedrockPolicy with the runtime's modelId", () => { ); const sids = statements.map(({ Sid }) => Sid); expect(new Set(sids).size).toBe(sids.length); + // Two models, three statements each: the repeated profile is written once. + expect(statements).toHaveLength(6); expect(statements.filter(({ Sid }) => String(Sid).endsWith("1"))).toHaveLength(3); expect(statements.filter(({ Sid }) => String(Sid).endsWith("2"))).toHaveLength(3); }); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index 8207c3e38b..0517d4b51b 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -75,7 +75,7 @@ const MODEL_ID_PATTERN = /^[a-z0-9-]+\.[A-Za-z0-9._:-]+$/; /** An ARN of a system inference profile or a foundation model: the two a Box gateway can scope. */ const SCOPED_ARN_PATTERN = - /^arn:[a-z-]+:bedrock:([a-z0-9-]*):[0-9]*:(inference-profile|foundation-model)\/(.+)$/; + /^arn:([a-z-]+):bedrock:([a-z0-9-]*):[0-9]*:(inference-profile|foundation-model)\/(.+)$/; /** * The Bedrock model that `runtime`'s code calls, from its `modelId` in agentcore.json, or undefined @@ -84,7 +84,10 @@ const SCOPED_ARN_PATTERN = * imported model). LiteLLM's `bedrock/`, `bedrock/converse/` and `bedrock/invoke/` routes give the ID * after them. A system inference profile ARN or a foundation model ARN gives its ID and region. */ -export function bedrockModelOf(runtime: ProjectRuntime): ScopedModel | undefined { +export function bedrockModelOf( + runtime: ProjectRuntime, + buildPartition?: string, +): ScopedModel | undefined { let id = runtime.modelId; if (id === undefined) return undefined; if (runtime.modelProvider === "LiteLLM") { @@ -93,7 +96,9 @@ export function bedrockModelOf(runtime: ProjectRuntime): ScopedModel | undefined } const arn = SCOPED_ARN_PATTERN.exec(id); if (arn) { - const [, region, kind, rest] = arn; + const [, arnPartition, region, kind, rest] = arn; + // An ARN of another partition names a model the gateway's role can never call. + if (buildPartition !== undefined && arnPartition !== buildPartition) return undefined; if (!MODEL_ID_PATTERN.test(rest!)) return undefined; return { id: rest!, @@ -159,9 +164,10 @@ function scopedBedrockStatements(models: readonly ScopedModel[], buildRegion: st } /** The boxed runtimes that call Bedrock with no model build can scope the Box gateways' policy to. */ -function unscopedRuntimes(spec: ProjectSpec): ProjectRuntime[] { +function unscopedRuntimes(spec: ProjectSpec, region?: string): ProjectRuntime[] { + const buildPartition = region === undefined ? undefined : partition(region).name; return boxedRuntimesCallingBedrock(spec).filter( - (runtime) => bedrockModelOf(runtime) === undefined, + (runtime) => bedrockModelOf(runtime, buildPartition) === undefined, ); } @@ -170,8 +176,8 @@ function unscopedRuntimes(spec: ProjectSpec): ProjectRuntime[] { * {@link boxBedrockPolicy} falls back: a boxed runtime that calls Bedrock has no `modelId` that build * can scope to. Undefined when the policy is scoped. */ -export function boxBedrockScopeWarning(spec: ProjectSpec): string | undefined { - const unscoped = unscopedRuntimes(spec).map(({ name }) => `"${name}"`); +export function boxBedrockScopeWarning(spec: ProjectSpec, region?: string): string | undefined { + const unscoped = unscopedRuntimes(spec, region).map(({ name }) => `"${name}"`); if (unscoped.length === 0) return undefined; const names = unscoped.length === 1 @@ -181,7 +187,8 @@ export function boxBedrockScopeWarning(spec: ProjectSpec): string | undefined { `${names} no modelId in agentcore.json that build can scope to (a Bedrock model ID or ` + "inference profile ID, or the ARN of a foundation model or system inference profile), so the " + 'Box gateways of this project can call every Bedrock model of the account. Set "modelId" ' + - "to the model its code calls, then build again." + "to the model its code calls, then build again. A runtime whose code calls no model needs " + + "no modelId; for it, the warning only says that the policy is not scoped." ); } @@ -201,9 +208,10 @@ export function boxBedrockPolicy( const runtimes = boxedRuntimesCallingBedrock(spec); if (runtimes.length === 0) return undefined; // When agentcore.json names the model of each runtime, the role can call only those models. - if (unscopedRuntimes(spec).length === 0) { + if (unscopedRuntimes(spec, region).length === 0) { const models = new Map(); - for (const model of runtimes.map(bedrockModelOf)) { + const buildPartition = partition(region).name; + for (const model of runtimes.map((runtime) => bedrockModelOf(runtime, buildPartition))) { models.set(JSON.stringify([model!.id, model!.region, model!.kind]), model!); } return { diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 37dffed526..9d68935ec8 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -395,7 +395,9 @@ export const defaultTargetsWriter: BoxNetworkWriter = { const region = networks[0]?.region; return { spec: [(copy) => addBoxGatewayTargets(copy, region)], - warnings: [boxBedrockScopeWarning(spec)].flatMap((warning) => (warning ? [warning] : [])), + warnings: [boxBedrockScopeWarning(spec, region)].flatMap((warning) => + warning ? [warning] : [], + ), files: [ { path: BOX_BEDROCK_POLICY_FILE, diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 69b9624660..a2b15e4b31 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -282,6 +282,36 @@ describe("agentcore create", () => { }, ); + test.each([ + "agent-python-strands-box", + "agent-python-langchain-box", + "a2a-python-strands-box", + "agui-python-strands-box", + ] as const)( + "create --template %s writes a README that ties the model to modelId", + async (template) => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-box-")); + tempDirectories.push(directory); + process.chdir(directory); + const generator = subject().create({ + name: "example", + skipInstall: true, + skipGit: true, + scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: "agent" }), + }); + let next = await generator.next(); + while (!next.done) next = await generator.next(); + + const readme = await readFile( + join(directory, "example", "app", "agent", "README.md"), + "utf8", + ); + expect(readme).toContain( + "the Box gateway may call only the Bedrock model in this runtime's `modelId`", + ); + }, + ); + test('a Box template writes "projectType": "box" and a Box gateway for each runtime', () => { const runtime = (name: string) => ({ name, build: "CodeZip", entrypoint: "main.py", codeLocation: `app/${name}` }) as never; diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 91fd032b06..98596c2f22 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -486,6 +486,8 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa sessionStorageMountPath, efsMounts, s3Mounts, + // The README says that the Box gateway calls only the model in modelId. + box: input.scaffoldRuntimeInput.boxTemplate === true, needsOs: filesystemConfigurations.length > 0, // The AgentCore Runtime requires OTEL dependencies to be present; the // container launches main.py as the `main` module under @@ -530,6 +532,8 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa // memory's env var so adding a memory later needs no code edit. memoryEnvVarName: memoryEnvVarName(memory?.name ?? defaultMemoryName(input.name)), ...modelScaffold.templateRenderContext, + // The README says that the Box gateway calls only the model in modelId. + box: input.scaffoldRuntimeInput.boxTemplate === true, // The AgentCore Runtime requires OTEL dependencies to be present; the AG-UI // app binds uvicorn on port 8080 under opentelemetry-instrument. enableOtel: true,