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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/box-local-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/assets/templates/a2a-python-strands/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/assets/templates/agent-python-langchain/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/assets/templates/agent-python-langchain/model/load.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
4 changes: 4 additions & 0 deletions src/assets/templates/agent-python-strands/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 4 additions & 1 deletion src/assets/templates/agui-python-strands/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
141 changes: 141 additions & 0 deletions src/core/project/boxMemory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
addBoxGatewayTargets,
BOX_BEDROCK_POLICY_FILE,
boxBedrockPolicy,
boxBedrockScopeWarning,
} from "./boxMemory";

function spec(options: { entrypoint?: string; memories?: string[] } = {}): ProjectSpec {
Expand Down Expand Up @@ -135,6 +136,146 @@ describe("boxBedrockPolicy", () => {
});
});

describe("boxBedrockPolicy with the runtime's modelId", () => {
type Statement = Record<string, unknown> & { 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();
Expand Down
146 changes: 145 additions & 1 deletion src/core/project/boxMemory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-<date>-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`
Expand All @@ -74,7 +205,20 @@ export function boxBedrockPolicy(
spec: ProjectSpec,
region: string,
): Record<string, unknown> | 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<string, ScopedModel>();
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",
Expand Down
Loading
Loading