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/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/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-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/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/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 56b434a9f2..fc0640bccf 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,146 @@ describe("boxBedrockPolicy", () => { }); }); +describe("boxBedrockPolicy with the runtime's modelId", () => { + type Statement = Record & { Resource: string[] }; + 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 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 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( + resources( + bedrock( + "arn:aws:bedrock:eu-west-1:123456789012:inference-profile/eu.anthropic.claude-sonnet-5-5", + ), + ), + ).toEqual([ + "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 foundation model ARN as that model in its own region only", () => { + expect( + 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"], + ["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, "us-west-2")).toContain( + 'runtime "agent0" has no modelId', + ); + }); + + test("allows the model of each runtime once, each statement with its own Sid", () => { + 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" }, + ), + ); + 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); + }); + + 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" }, + {}, + ); + expect(resources(project)).toEqual(EVERY_MODEL); + expect(boxBedrockScopeWarning(project)).toContain('runtime "agent1" has no modelId'); + }); + + 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(); + }); +}); + 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..0517d4b51b 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -61,6 +61,137 @@ 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 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 bedrockModelOf( + runtime: ProjectRuntime, + buildPartition?: string, +): ScopedModel | undefined { + let id = runtime.modelId; + if (id === undefined) return undefined; + if (runtime.modelProvider === "LiteLLM") { + if (!id.startsWith("bedrock/")) return undefined; + id = id.slice("bedrock/".length).replace(/^(converse|invoke)\//, ""); + } + const arn = SCOPED_ARN_PATTERN.exec(id); + if (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!, + ...(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 `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(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) => (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("BoxedAgentModelThroughItsInferenceProfile", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + // 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}`, + }, + }, + }, + ); + } + if (kind !== "inference-profile") { + statements.push({ + Sid: sid("BoxedAgentModelThroughGateway", index), + Effect: "Allow", + Action: BEDROCK_INVOKE_ACTIONS, + 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, region?: string): ProjectRuntime[] { + const buildPartition = region === undefined ? undefined : partition(region).name; + return boxedRuntimesCallingBedrock(spec).filter( + (runtime) => bedrockModelOf(runtime, buildPartition) === undefined, + ); +} + +/** + * 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, region?: string): string | undefined { + const unscoped = unscopedRuntimes(spec, region).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 ( + `${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. A runtime whose code calls no model needs " + + "no modelId; for it, the warning only says that the policy is not scoped." + ); +} + /** * 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 +205,20 @@ 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. + if (unscopedRuntimes(spec, region).length === 0) { + const models = new Map(); + 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 { + Version: "2012-10-17", + Statement: scopedBedrockStatements([...models.values()], 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..9d68935ec8 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,9 @@ export const defaultTargetsWriter: BoxNetworkWriter = { const region = networks[0]?.region; return { spec: [(copy) => addBoxGatewayTargets(copy, region)], + 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 14fb8f3480..a2b15e4b31 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -241,6 +241,77 @@ 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", 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 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); + const generator = subject().create({ + name: "example", + skipInstall: true, + skipGit: true, + 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 (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(`"${modelId}"`); + } + }, + ); + + 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/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index c838c7931e..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. @@ -1650,10 +1694,11 @@ 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*"], + [`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/templates/project.ts b/src/core/project/templates/project.ts index cb37949608..ce97daa0e1 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 (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. + */ +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.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 15e2a20473..98596c2f22 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, }), @@ -285,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", }; @@ -482,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 @@ -526,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, 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(),