diff --git a/README.md b/README.md index 541f2ef31..ee3fc2697 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,15 @@ second answer should say teal, and the runtime log shows `running profile ...` w A boxed agent gets the deployed Memory IDs and the Runtime's region inside the box. It does not get the `AGENTCORE_GATEWAY__URL` variables of gateways you add yourself: its calls go out through -its Box gateway. +its Box gateway. With its default Memory, its calls to the AgentCore host +(`bedrock-agentcore..amazonaws.com`) are the exception: box signs them with the execution +role and sends them to that host directly, so Memory can hold each call to the session of the +runtime. Box routes a connection by its host alone, and Code Interpreter, Browser, and the other +AgentCore APIs share that host, so their calls go there directly too. A `PRIVATE_VPC` runtime +reaches that host through the AgentCore endpoint of its private VPC, which only the runtime's role +may call through. Code in the box can make any AgentCore call on that host that the +execution role allows, so a `bedrock-agentcore` grant added through `additionalPolicies` is open +to it. A runtime in a VPC of your own needs a `bedrock-agentcore` VPC endpoint. A Box project that an older CLI created still has `start.sh`, or a Dockerfile that runs it. Build and deploy now render profiles that those files cannot start. Create the project again, or copy diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index 3ed089a72..8b57579b6 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -44,14 +44,19 @@ fork of [strands-agents/box](https://github.com/strands-agents/box), then run [aws/agentcore-l3-cdk-constructs#470](https://github.com/aws/agentcore-l3-cdk-constructs/pull/470), as its `box-integration` branch does. The Box gateway that `create` writes has `enableApplicationLogs`, and an older L3 refuses it at synth with a `ConfigValidationError`. + A boxed runtime with Memory also needs + [aws/agentcore-l3-cdk-constructs#481](https://github.com/aws/agentcore-l3-cdk-constructs/pull/481): it gives the + runtime's role its Memory grant, and a `PRIVATE_VPC` runtime the AgentCore endpoint of its private VPC. Without it, + the box cannot reach Memory. - `box` `0.3.0` on your `PATH` (`0.3.0-preview.1` on macOS), the release the CLI pins. Use that release: the box features and the profiles that the CLI writes change together, so an older box can refuse the profiles. The CLI does not check the version of the box on your `PATH` yet. Build, deploy and dev run it to read the box profile with `box profile show --format json --full`, and CodeZip dev runs the agent with it. See [Install box](#install-box). -- AWS credentials for a **dev or test** account. Build writes the Box gateway's Bedrock and Memory - targets for `AWS_REGION` (else your AWS profile's region), and deploy for its target's region. +- AWS credentials for a **dev or test** account. Build writes the Box gateway's Bedrock target and + the Runtime profile's direct AgentCore route for `AWS_REGION` (else your AWS profile's region), and + deploy for its target's region. - `bun` for the CLI, `npm` for the generated CDK app. ## Install box diff --git a/src/core/project/boxMemory.test.ts b/src/core/project/boxMemory.test.ts index 96dfbfb43..56b434a9f 100644 --- a/src/core/project/boxMemory.test.ts +++ b/src/core/project/boxMemory.test.ts @@ -1,18 +1,11 @@ import { describe, expect, test } from "bun:test"; -import { InputValidationError } from "../../errors/errors"; -import { - getBoxGatewayAgentCoreTargetSpec, - getBoxGatewayBedrockTargetSpec, -} from "../../handlers/project/shortcuts"; +import { getBoxGatewayBedrockTargetSpec } from "../../handlers/project/shortcuts"; import { boxGatewaySpec, type ProjectSpec } from "../../projectSchemas/project"; import { addBoxBedrockTarget, addBoxGatewayTargets, - addBoxMemoryTarget, BOX_BEDROCK_POLICY_FILE, - BOX_MEMORY_POLICY_FILE, boxBedrockPolicy, - boxMemoryPolicy, } from "./boxMemory"; function spec(options: { entrypoint?: string; memories?: string[] } = {}): ProjectSpec { @@ -45,132 +38,6 @@ const gateway = (project: ProjectSpec) => const targets = (project: ProjectSpec) => gateway(project).targets.map(({ name }) => name); -describe("addBoxMemoryTarget", () => { - test("adds the agentcore target to the runtime's Box gateway for its default Memory", () => { - const project = spec(); - - expect(addBoxMemoryTarget(project)).toEqual([ - `adding target 'agentcore' to gateway '${GATEWAY}' in agentcore.json, for the boxed agent's Memory calls`, - `adding 'agentcore/box-memory-policy.json' to gateway '${GATEWAY}' additionalPolicies in agentcore.json, so its role can call Memory`, - ]); - expect(gateway(project).additionalPolicies).toEqual([BOX_MEMORY_POLICY_FILE]); - expect(gateway(project).targets).toEqual([getBoxGatewayAgentCoreTargetSpec()]); - }); - - test("changes nothing when the target is already there", () => { - const project = spec(); - addBoxMemoryTarget(project); - - expect(addBoxMemoryTarget(project)).toEqual([]); - expect(targets(project)).toEqual(["agentcore"]); - }); - - test("changes nothing for another Memory, or for a runtime that does not run in a box", () => { - const otherMemory = spec({ memories: ["ordersMemory"] }); - const unboxed = spec({ entrypoint: "main.py" }); - - expect(addBoxMemoryTarget(otherMemory)).toEqual([]); - expect(addBoxMemoryTarget(unboxed)).toEqual([]); - expect(targets(otherMemory)).toEqual([]); - expect(targets(unboxed)).toEqual([]); - }); - - test("changes nothing in a project that is not a Box project", () => { - const { projectType: _omitted, ...rest } = spec(); - const project = { ...rest, agentCoreGateways: [] } as ProjectSpec; - - expect(addBoxMemoryTarget(project)).toEqual([]); - expect(project.agentCoreGateways).toEqual([]); - expect(project.projectType).toBeUndefined(); - }); - - test("adds no agentcore target where another target serves its endpoint", () => { - const project = spec(); - gateway(project).targets = [{ ...getBoxGatewayAgentCoreTargetSpec(), name: "mem" }]; - - addBoxMemoryTarget(project); - - expect(targets(project)).toEqual(["mem"]); - expect(gateway(project).additionalPolicies).toEqual([BOX_MEMORY_POLICY_FILE]); - }); - - test("refuses the target name on a gateway that is not a Box gateway", () => { - const project = spec(); - project.agentCoreGateways.push({ - name: "tools", - authorizerType: "AWS_IAM", - targets: [getBoxGatewayAgentCoreTargetSpec()], - } as ProjectSpec["agentCoreGateways"][number]); - - expect(() => addBoxMemoryTarget(project)).toThrow(InputValidationError); - }); - - test("lists the policy file on a gateway that already has the target", () => { - const project = spec(); - gateway(project).targets.push(getBoxGatewayAgentCoreTargetSpec()); - - expect(addBoxMemoryTarget(project)).toEqual([ - `adding 'agentcore/box-memory-policy.json' to gateway '${GATEWAY}' additionalPolicies in agentcore.json, so its role can call Memory`, - ]); - expect(targets(project)).toEqual(["agentcore"]); - }); - - test("leaves the policies of a gateway that imports its role", () => { - const project = spec(); - gateway(project).executionRoleArn = "arn:aws:iam::123456789012:role/mine"; - - addBoxMemoryTarget(project); - - expect(gateway(project).additionalPolicies).toBeUndefined(); - }); -}); - -describe("boxMemoryPolicy", () => { - type Policy = { - Statement: Array<{ Action: string[]; Resource: string[]; Condition: unknown }>; - }; - const SAME_ACCOUNT = { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }; - - test("allows the Memory data plane on the default Memory in any target, in the gateway role's account", () => { - const policy = boxMemoryPolicy(spec(), "us-west-2") as Policy; - - expect(policy.Statement[0]!.Resource).toEqual([ - "arn:aws:bedrock-agentcore:us-west-2:*:memory/demo_*agentMemory-*", - ]); - expect(policy.Statement[0]!.Condition).toEqual(SAME_ACCOUNT); - expect(policy.Statement[0]!.Action).toContain("bedrock-agentcore:ListEvents"); - expect(policy.Statement[0]!.Action).toContain("bedrock-agentcore:CreateEvent"); - }); - - test("names the region it is given, and no other", () => { - const policy = boxMemoryPolicy(spec(), "eu-central-1") as Policy; - - expect(policy.Statement).toEqual([ - expect.objectContaining({ - Resource: ["arn:aws:bedrock-agentcore:eu-central-1:*:memory/demo_*agentMemory-*"], - Condition: SAME_ACCOUNT, - }), - ]); - }); - - test("names the partition of the region it is given", () => { - const resources = (region: string) => - (boxMemoryPolicy(spec(), region) as Policy).Statement[0]!.Resource; - - expect(resources("cn-north-1")).toEqual([ - "arn:aws-cn:bedrock-agentcore:cn-north-1:*:memory/demo_*agentMemory-*", - ]); - expect(resources("us-gov-west-1")).toEqual([ - "arn:aws-us-gov:bedrock-agentcore:us-gov-west-1:*:memory/demo_*agentMemory-*", - ]); - }); - - test("is undefined when no boxed runtime has its default Memory", () => { - expect(boxMemoryPolicy(spec({ memories: ["ordersMemory"] }), "us-west-2")).toBeUndefined(); - expect(boxMemoryPolicy(spec({ entrypoint: "main.py" }), "us-west-2")).toBeUndefined(); - }); -}); - describe("addBoxBedrockTarget", () => { test("adds the bedrock target and its policy for a boxed agent that calls Bedrock", () => { const project = spec({ memories: [] }); @@ -269,30 +136,39 @@ describe("boxBedrockPolicy", () => { }); describe("addBoxGatewayTargets", () => { - test("adds the bedrock and agentcore targets a boxed agent's calls take, in the region given", () => { + test("adds the bedrock target a boxed agent's model calls take, in the region given", () => { const project = spec(); addBoxGatewayTargets(project, "eu-central-1"); - expect(gateway(project).targets).toEqual([ - getBoxGatewayBedrockTargetSpec("eu-central-1"), - getBoxGatewayAgentCoreTargetSpec("eu-central-1"), - ]); + expect(gateway(project).targets).toEqual([getBoxGatewayBedrockTargetSpec("eu-central-1")]); + }); + + test("adds no target and no policy for the default Memory: its calls go to Memory directly", () => { + const project = spec(); + project.runtimes[0]!.modelProvider = "OpenAI"; + + expect(addBoxGatewayTargets(project)).toEqual([]); + expect(targets(project)).toEqual([]); + expect(gateway(project).additionalPolicies).toBeUndefined(); }); test("moves a target it wrote for another region, and keeps one the user changed", () => { const project = spec(); addBoxGatewayTargets(project, "us-west-2"); - const memory = gateway(project).targets[1]!; - gateway(project).targets[1] = { - ...memory, - outboundAuth: { ...memory.outboundAuth!, region: "eu-west-1" }, - }; expect(addBoxGatewayTargets(project, "us-east-1")).toEqual([ `updating target 'bedrock' of gateway '${GATEWAY}' in agentcore.json from us-west-2 to us-east-1`, ]); - expect(gateway(project).targets[0]).toEqual(getBoxGatewayBedrockTargetSpec("us-east-1")); - expect(gateway(project).targets[1]!.outboundAuth?.region).toBe("eu-west-1"); + expect(gateway(project).targets).toEqual([getBoxGatewayBedrockTargetSpec("us-east-1")]); + + const bedrock = gateway(project).targets[0]!; + // The user signs for another service, so the target is no longer the one build wrote. + gateway(project).targets[0] = { + ...bedrock, + outboundAuth: { ...bedrock.outboundAuth!, service: "bedrock-runtime" }, + }; + expect(addBoxGatewayTargets(project, "eu-west-1")).toEqual([]); + expect(gateway(project).targets[0]!.outboundAuth?.region).toBe("us-east-1"); }); }); diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index 362c32a79..64034cb98 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -1,12 +1,9 @@ import { isDeepStrictEqual } from "node:util"; import { partition } from "@aws-sdk/util-endpoints"; -import { InputValidationError } from "../../errors/errors"; import { - BOX_GATEWAY_AGENTCORE_TARGET_NAME, BOX_GATEWAY_BEDROCK_TARGET_NAME, DEFAULT_EGRESS_BEDROCK_REGION, callsBedrockModel, - getBoxGatewayAgentCoreTargetSpec, getBoxGatewayBedrockTargetSpec, } from "../../handlers/project/shortcuts"; import type { AgentCoreGateway, AgentCoreGatewayTarget } from "../../projectSchemas/gateway"; @@ -16,15 +13,6 @@ import type { ProjectRuntime } from "../../projectSchemas/runtime"; import { BOX_EGRESS_TARGET_PREFIX } from "./boxNetwork/egress"; import { runtimeRunsInBox } from "./templates/boxProfile"; -/** The Box gateway's target, and the box route, that the agent's AgentCore Memory calls take. */ -export const BOX_MEMORY_TARGET = BOX_GATEWAY_AGENTCORE_TARGET_NAME; - -/** - * The policy file, relative to the project root, that lets the Box gateway's - * role call AgentCore Memory for the boxed agents. The CLI rewrites it on build. - */ -export const BOX_MEMORY_POLICY_FILE = "agentcore/box-memory-policy.json"; - /** * The policy file, relative to the project root, that lets the Box gateway's role call the Bedrock * model for the boxed agents: the gateway's `bedrock` target signs the model calls with that role, @@ -32,27 +20,18 @@ export const BOX_MEMORY_POLICY_FILE = "agentcore/box-memory-policy.json"; */ export const BOX_BEDROCK_POLICY_FILE = "agentcore/box-bedrock-policy.json"; +/** + * The name of the Runtime profile route of the agent's Memory calls, which go to Memory directly + * (runtimeProfile/rules/additions.ts). + */ +export const BOX_MEMORY_ROUTE_NAME = "agentcore"; + /** The Bedrock actions behind Converse and ConverseStream, which the agent's model calls make. */ const BEDROCK_INVOKE_ACTIONS = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]; /** The IAM policy variable for the account of the gateway role. */ const PRINCIPAL_ACCOUNT = "${aws:PrincipalAccount}"; -/** The Memory data-plane actions the agent's session manager calls, as the L3 grants a runtime. */ -const MEMORY_DATA_PLANE_ACTIONS = [ - "bedrock-agentcore:ListMemoryRecords", - "bedrock-agentcore:RetrieveMemoryRecords", - "bedrock-agentcore:GetEvent", - "bedrock-agentcore:GetMemory", - "bedrock-agentcore:GetMemoryRecord", - "bedrock-agentcore:ListActors", - "bedrock-agentcore:ListEvents", - "bedrock-agentcore:ListSessions", - "bedrock-agentcore:CreateEvent", - "bedrock-agentcore:DeleteEvent", - "bedrock-agentcore:DeleteMemoryRecord", -]; - /** Whether the project has the default Memory create scaffolds for `runtime`. */ export function hasDefaultMemory(spec: ProjectSpec, runtime: ProjectRuntime): boolean { return spec.memories.some((memory) => memory.name === defaultMemoryName(runtime.name)); @@ -66,11 +45,6 @@ function boxedRuntimes(spec: ProjectSpec): ProjectRuntime[] { return spec.runtimes.filter((runtime) => runtimeRunsInBox(spec, runtime)); } -/** The runtimes of a Box project that run their agent in a box and have their default Memory. */ -function boxedRuntimesWithMemory(spec: ProjectSpec): ProjectRuntime[] { - return boxedRuntimes(spec).filter((runtime) => hasDefaultMemory(spec, runtime)); -} - /** * Whether a runtime's agent calls a Bedrock model, as its box profile routes it: a protocol other * than MCP, and the Bedrock provider (the default) or a `bedrock/` LiteLLM model. @@ -87,38 +61,6 @@ function boxedRuntimesCallingBedrock(spec: ProjectSpec): ProjectRuntime[] { return boxedRuntimes(spec).filter(callsBedrock); } -/** - * The IAM policy document for {@link BOX_MEMORY_POLICY_FILE}, or undefined when - * no boxed runtime has its default Memory. The Memory ARN is known only after - * deploy, so each resource matches the physical name the L3 gives the Memory, - * `__-`, in any target, in `region`, the region of - * the `agentcore` target that build writes, and in the partition of `region`. One file - * serves every deploy target, so the ARN names no account, and the condition holds the - * Memory to the gateway role's own account. - */ -export function boxMemoryPolicy( - spec: ProjectSpec, - region: string, -): Record | undefined { - const memories = boxedRuntimesWithMemory(spec).map(({ name }) => defaultMemoryName(name)); - if (memories.length === 0) return undefined; - return { - Version: "2012-10-17", - Statement: [ - { - Sid: "BoxedAgentMemoryThroughGateway", - Effect: "Allow", - Action: MEMORY_DATA_PLANE_ACTIONS, - Resource: memories.map( - (memory) => - `arn:${partition(region).name}:bedrock-agentcore:${region}:*:memory/${spec.name}_*${memory}-*`, - ), - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }, - ], - }; -} - /** * 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` @@ -166,33 +108,22 @@ export function boxBedrockPolicy( } /** - * Refuses a target named `name` on a gateway that is not a Box gateway: the Box gateways need the - * name for `calls`. + * The names that build owns on a Box gateway: the `bedrock` target of the agent's model calls, and + * the name of the agent's Memory route. A target of that name would give the Runtime profile a + * route that takes the Memory route's name. */ -function refuseTargetNameOutsideBoxGateways(spec: ProjectSpec, name: string, calls: string): void { - const owner = spec.agentCoreGateways.find( - (gateway) => !isBoundGateway(gateway) && gateway.targets.some((target) => target.name === name), - ); - if (owner) { - throw new InputValidationError( - `gateway '${owner.name}' has a target named '${name}', the name the Box gateways need for ` + - `${calls}. Rename that target.`, - ); - } -} - -/** The names of the Box gateway targets that build writes for the agent's model and Memory calls. */ const BOX_DEFAULT_TARGET_NAMES: readonly string[] = [ BOX_GATEWAY_BEDROCK_TARGET_NAME, - BOX_GATEWAY_AGENTCORE_TARGET_NAME, + BOX_MEMORY_ROUTE_NAME, ]; /** * The refusal of a user target named `name` on `gateway`, or `undefined` when build does not own * the name there. On the Box gateway of a runtime that runs in a box, build writes the `bedrock` - * and `agentcore` targets, and names each egress target it writes with the `egress-` prefix. A - * user target of such a name would take the agent's Bedrock or Memory route, or the name of an - * egress target that build writes. Build writes none of these for another runtime. + * target, owns the `agentcore` name for the Memory route, and names each egress target it writes + * with the `egress-` prefix. A + * user target of such a name would take the agent's Bedrock route, the name of its direct Memory + * route, or the name of an egress target that build writes. Build writes none of these for another runtime. */ export function reservedBoxTargetNameProblem( spec: ProjectSpec, @@ -209,8 +140,8 @@ export function reservedBoxTargetNameProblem( `'${BOX_EGRESS_TARGET_PREFIX}*'`, ]; return ( - `the gateway target name '${name}' is reserved on Box gateway '${gateway.name}': build writes the ` + - `targets ${reserved.join(", ")} for the agent's model, Memory, and egress calls. Choose another name.` + `the gateway target name '${name}' is reserved on Box gateway '${gateway.name}': build owns the ` + + `names ${reserved.join(", ")} for the agent's model calls, Memory route, and egress targets. Choose another name.` ); } @@ -232,32 +163,6 @@ function grantPolicyFile( ); } -/** - * Adds the `agentcore` passthrough target, in `region`, to the Box gateway (the gateway bound to - * the runtime) of each runtime that runs its agent in a box and has its default Memory, so the box - * can send the agent's Memory calls through the gateway, and lists {@link BOX_MEMORY_POLICY_FILE} - * in that gateway's `additionalPolicies` so its role may make them. Changes nothing outside a Box - * project. Changes `spec` in place, and returns the step messages; none when nothing changed. The - * target name on a gateway that is not a Box gateway is an error. - */ -export function addBoxMemoryTarget( - spec: ProjectSpec, - region: string = DEFAULT_EGRESS_BEDROCK_REGION, -): string[] { - const runtimes = boxedRuntimesWithMemory(spec); - if (runtimes.length === 0) return []; - refuseTargetNameOutsideBoxGateways(spec, BOX_MEMORY_TARGET, "the agent's Memory calls"); - - const messages: string[] = []; - for (const runtime of runtimes) { - const gateway = boxGatewayFor(spec, runtime); - if (!gateway) continue; - placeTarget(gateway, getBoxGatewayAgentCoreTargetSpec, region, messages, "Memory calls"); - grantPolicyFile(gateway, BOX_MEMORY_POLICY_FILE, messages, "Memory"); - } - return messages; -} - /** * Adds the `bedrock` passthrough target, in `region`, to the Box gateway of each runtime that runs * its agent in a box and calls a Bedrock model, so the Runtime profile has a route for the model @@ -281,14 +186,16 @@ export function addBoxBedrockTarget( } /** - * Adds the Box gateway targets that the boxed agents' calls need, the Bedrock model and the default - * Memory, in `region`, before build renders the Runtime profiles from those targets. + * Adds the Box gateway targets that the boxed agents' calls need, in `region`, before build renders + * the Runtime profiles from those targets: the Bedrock model's. The agent's Memory calls take no + * target: box signs them with the execution role and sends them to Memory itself, so Memory can + * hold each call to the session of the runtime (runtimeProfile/rules/additions.ts). */ export function addBoxGatewayTargets( spec: ProjectSpec, region: string = DEFAULT_EGRESS_BEDROCK_REGION, ): string[] { - return [...addBoxBedrockTarget(spec, region), ...addBoxMemoryTarget(spec, region)]; + return addBoxBedrockTarget(spec, region); } /** diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 684ab65dc..e098e1450 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -1,9 +1,6 @@ import { describe, expect, test } from "bun:test"; import { createHash } from "node:crypto"; -import { - getBoxGatewayAgentCoreTargetSpec, - getBoxGatewayBedrockTargetSpec, -} from "../../../handlers/project/shortcuts"; +import { getBoxGatewayBedrockTargetSpec } from "../../../handlers/project/shortcuts"; import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import { boxGatewaySpec, type ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; @@ -913,18 +910,14 @@ describe("HTTP MCP servers", () => { }); describe("the default targets", () => { - test("gives the Memory endpoint to the agentcore target build adds, and no egress- target", () => { - const r = model( - "", - { - memory: { - destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], - secret: { ref: "aws://default" }, - }, + test("gives the Memory endpoint of an entry an egress- target: build adds no target for Memory", () => { + const r = model("", { + memory: { + destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], + secret: { ref: "aws://default" }, }, - { targets: [getBoxGatewayAgentCoreTargetSpec()] }, - ); - expect(r.targets()).toEqual(["bedrock-agentcore.us-west-2.amazonaws.com -> agentcore"]); + }); + expect(r.targets()).toEqual(["bedrock-agentcore.us-west-2.amazonaws.com -> egress-memory"]); expect(r.failures()).toEqual([]); }); @@ -949,14 +942,14 @@ describe("the default targets", () => { const r = model( "", { - memory: { - destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], + models: { + destinations: ["bedrock-runtime.us-west-2.amazonaws.com"], secret: { ref: "env://KEY" }, }, }, - { targets: [getBoxGatewayAgentCoreTargetSpec()] }, + { targets: [getBoxGatewayBedrockTargetSpec()] }, ); - expect(r.failures()).toEqual([["EXISTING_TARGET_CONFLICT", "memory"]]); + expect(r.failures()).toEqual([["EXISTING_TARGET_CONFLICT", "models"]]); }); }); @@ -1039,9 +1032,11 @@ describe("warnings", () => { const control = passthrough("egress-control", "https://bedrock.us-west-2.amazonaws.com", { outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock", region: "us-west-2" }, }); - const memory = getBoxGatewayAgentCoreTargetSpec(); - const r = model("", egress, { targets: [control, memory] }); - r.spec.agentCoreGateways[0]!.additionalPolicies = ["agentcore/box-memory-policy.json"]; + // A Memory target of the user: build writes no policy file for one. + const memory = passthrough("agentcore", "https://bedrock-agentcore.us-west-2.amazonaws.com", { + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + }); + const r = model("", egress, { targets: [control] }); expect(boxGatewayIamWarnings(r.spec, r.network)).toEqual([ "Target 'egress-control' calls bedrock with the gateway's role, which has no bedrock " + "permissions. Add an IAM policy file to additionalPolicies of the 'agent-box-egress' gateway.", @@ -1074,7 +1069,6 @@ describe("warnings", () => { describe("the grant each endpoint of a target needs", () => { const BEDROCK_FILE = "agentcore/box-bedrock-policy.json"; - const MEMORY_FILE = "agentcore/box-memory-policy.json"; const signed = (name: string, host: string, service: string) => passthrough(name, `https://${host}`, { outboundAuth: { type: "GATEWAY_IAM_ROLE", service, region: "us-west-2" }, @@ -1161,21 +1155,21 @@ describe("warnings", () => { expect(warningsFor(functionUrl, ["bedrock:*"])).toEqual([forService("egress-fn", "lambda")]); }); - test("an AgentCore target needs an AgentCore grant, and the Memory file covers only Memory", () => { - expect(warningsFor(getBoxGatewayAgentCoreTargetSpec(), [], [MEMORY_FILE])).toEqual([]); - expect(warningsFor(agentcoreControl, [], [MEMORY_FILE])).toEqual([ - forHost("egress-agentcore-control", AGENTCORE_CONTROL_HOST, "bedrock-agentcore"), - ]); - expect(warningsFor(agentcoreControl, ["bedrock-agentcore:*"], [MEMORY_FILE])).toEqual([]); - expect(warningsFor(getBoxGatewayAgentCoreTargetSpec("us-east-1"), [], [MEMORY_FILE])).toEqual( - [forHost("agentcore", "bedrock-agentcore.us-east-1.amazonaws.com", "bedrock-agentcore")], + test("an AgentCore target needs an AgentCore grant", () => { + const memory = signed( + "agentcore", + "bedrock-agentcore.us-west-2.amazonaws.com", + "bedrock-agentcore", ); + expect(warningsFor(memory)).toEqual([forService("agentcore", "bedrock-agentcore")]); + expect(warningsFor(memory, ["bedrock-agentcore:*"])).toEqual([]); + expect(warningsFor(agentcoreControl, ["bedrock-agentcore:*"])).toEqual([]); expect(warningsFor(agentcoreControl)).toEqual([ forService("egress-agentcore-control", "bedrock-agentcore"), ]); }); - test("the Bedrock and Memory files grant the amazonaws.com.cn hosts of a build for China", () => { + test("the Bedrock file grants the amazonaws.com.cn host of a build for China", () => { const china = (name: string, host: string, service: string) => passthrough(name, `https://${host}`, { outboundAuth: { type: "GATEWAY_IAM_ROLE", service, region: "cn-north-1" }, @@ -1186,15 +1180,10 @@ describe("warnings", () => { { targets: [ china("egress-models", "bedrock-runtime.cn-north-1.amazonaws.com.cn", "bedrock"), - china( - "egress-memory", - "bedrock-agentcore.cn-north-1.amazonaws.com.cn", - "bedrock-agentcore", - ), ], }, ); - r.spec.agentCoreGateways[0]!.additionalPolicies = [BEDROCK_FILE, MEMORY_FILE]; + r.spec.agentCoreGateways[0]!.additionalPolicies = [BEDROCK_FILE]; expect(boxGatewayIamWarnings(r.spec, { ...r.network, region: "cn-north-1" })).toEqual([]); }); @@ -1433,13 +1422,15 @@ describe("boxGatewayIamWarnings for a gateway of the project", () => { }, }), ], - additionalPolicies: ["agentcore/box-memory-policy.json"], }, ], } as unknown as ProjectSpec; const network = { runtime: "agent", gateway: "agent-box-egress", region: "us-west-2" }; - expect(boxGatewayIamWarnings(spec, { ...network, grantedActions: [] })).toEqual([ + // The role holds an AgentCore grant, but not InvokeGateway on that gateway. + expect( + boxGatewayIamWarnings(spec, { ...network, grantedActions: ["bedrock-agentcore:ListEvents"] }), + ).toEqual([ `Target 'mine' calls ${GATEWAY_HOST} with the gateway's role, which has no bedrock-agentcore ` + "permissions for that host. Add an IAM policy file to additionalPolicies of the " + "'agent-box-egress' gateway.", diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index d02e02839..5be477a72 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -4,14 +4,11 @@ * the policy files to stage, and every warning and failure. Build, deploy, and staging write from * it. */ -import { - boxGatewayAgentCoreHost, - boxGatewayBedrockHost, -} from "../../../handlers/project/shortcuts"; +import { boxGatewayBedrockHost } from "../../../handlers/project/shortcuts"; import type { AgentCoreGateway, AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import type { ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; -import { BOX_BEDROCK_POLICY_FILE, BOX_MEMORY_POLICY_FILE } from "../boxMemory"; +import { BOX_BEDROCK_POLICY_FILE } from "../boxMemory"; import { boxEgressCredentialName } from "../boxProfileCredentials"; import type { BoxEnvRoute } from "../boxProfileEgress"; import { buildHostMap, entryLabel, entryRef, type MappedHost } from "./hostMap"; @@ -110,7 +107,7 @@ export interface BoxNetwork { readonly runtime: string; /** The runtime's Box gateway, as agentcore.json names it. */ readonly gateway: string; - /** The region build builds for: of the Box gateway, its `bedrock` and `agentcore` targets. */ + /** The region build builds for: of the Box gateway and its `bedrock` target. */ readonly region: string; /** * The `[egress]` entries' hosts in profile order, then the HTTP `[mcp]` servers' hosts, then the @@ -161,8 +158,8 @@ export interface BoxNetworkProject { /** The region build builds for. */ readonly region: string; /** - * The gateway's targets, with the `bedrock` and `agentcore` targets that build adds for the - * runtime's model and Memory calls (`addBoxGatewayTargets`). + * The gateway's targets, with the `bedrock` target that build adds for the runtime's model calls + * (`addBoxGatewayTargets`). */ readonly targets: readonly AgentCoreGatewayTarget[]; /** The IAM actions that the gateway's `additionalPolicies` files grant, except build's own. */ @@ -676,9 +673,8 @@ function sourceLabel(source: EntrySource): string { /** * A warning for each target of the network's Box gateway in `spec`, as build writes it, that the * gateway signs with its own role for an endpoint that no policy of that role allows. The Bedrock - * policy file that build writes allows the Bedrock runtime host of the build region, and the Memory - * policy file the Memory host of that region; a gateway that imports its role is the user's to - * grant. + * policy file that build writes allows the Bedrock runtime host of the build region; a gateway that + * imports its role is the user's to grant. */ export function boxGatewayIamWarnings( spec: ProjectSpec, @@ -686,18 +682,15 @@ export function boxGatewayIamWarnings( ): string[] { const gateway = boxGatewayOf(spec, network.runtime); if (!gateway || gateway.executionRoleArn) return []; - // Build writes these two files, so each one counts when it is listed, not by its actions. + // Build writes this file, so it counts when it is listed, not by its actions. const listed = gateway.additionalPolicies ?? []; - const memoryListed = listed.includes(BOX_MEMORY_POLICY_FILE); const bedrockListed = listed.includes(BOX_BEDROCK_POLICY_FILE); const granted = network.grantedActions; const grantsService = (service: string) => granted.some((action) => action === "*" || action.toLowerCase().startsWith(`${service}:`)); /** Whether the role has a permission for `service`, whatever its endpoint. */ const holds = (service: string) => - (service === "bedrock" && bedrockListed) || - (service === "bedrock-agentcore" && memoryListed) || - grantsService(service); + (service === "bedrock" && bedrockListed) || grantsService(service); const grants = (action: string) => granted.some((pattern) => actionMatches(pattern, action)); const allows = (api: AwsEndpointApi, host: string): boolean => { switch (api) { @@ -709,10 +702,7 @@ export function boxGatewayIamWarnings( case "bedrock-control": return granted.some(grantsBedrockControlPlane); case "bedrock-agentcore": - return ( - (memoryListed && host === boxGatewayAgentCoreHost(network.region)) || - grantsService("bedrock-agentcore") - ); + return grantsService("bedrock-agentcore"); case "lambda-url": return grants("lambda:InvokeFunctionUrl"); case "gateway": diff --git a/src/core/project/boxNetworkSource.test.ts b/src/core/project/boxNetworkSource.test.ts index 695fcb44b..690f7e1f9 100644 --- a/src/core/project/boxNetworkSource.test.ts +++ b/src/core/project/boxNetworkSource.test.ts @@ -596,12 +596,12 @@ describe("the IAM policy files of the Box gateway", () => { ]); }); - test("gives no warning for the Memory policy file that build writes before it writes it", async () => { + test("gives no warning for the Bedrock policy file that build writes before it writes it", async () => { const root = await project([]); const spec = { ...SPEC, agentCoreGateways: [ - { ...boxGatewaySpec("agent"), additionalPolicies: ["agentcore/box-memory-policy.json"] }, + { ...boxGatewaySpec("agent"), additionalPolicies: ["agentcore/box-bedrock-policy.json"] }, ], } as unknown as ProjectSpec; @@ -616,15 +616,9 @@ describe("the IAM policy files of the Box gateway", () => { await mkdir(join(root, "agentcore")); const grant = (action: string) => JSON.stringify({ Statement: [{ Effect: "Allow", Action: [action] }] }); - await writeFile( - join(root, "agentcore", "box-memory-policy.json"), - grant("bedrock-agentcore:GetEvent"), - ); await writeFile(join(root, "agentcore", "box-bedrock-policy.json"), "{ not json"); await writeFile(join(root, "agentcore", "grants.json"), grant("lambda:InvokeFunctionUrl")); - const listed = ["box-memory-policy", "box-bedrock-policy", "grants"].map( - (name) => `agentcore/${name}.json`, - ); + const listed = ["box-bedrock-policy", "grants"].map((name) => `agentcore/${name}.json`); const spec = { ...SPEC, agentCoreGateways: [{ ...boxGatewaySpec("agent"), additionalPolicies: listed }], diff --git a/src/core/project/boxNetworkSource.ts b/src/core/project/boxNetworkSource.ts index 477c3a6ab..4a2e27e00 100644 --- a/src/core/project/boxNetworkSource.ts +++ b/src/core/project/boxNetworkSource.ts @@ -14,7 +14,7 @@ import { InvalidEnvironmentError, ProjectStateError } from "../../errors/errors" import type { PolicyFileCopy } from "./backends/boxContainer"; import type { PassthroughGatewayCheck } from "./backends/cdk/compatibility"; import { DEFAULT_EGRESS_BEDROCK_REGION } from "../../handlers/project/shortcuts"; -import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, BOX_MEMORY_POLICY_FILE } from "./boxMemory"; +import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE } from "./boxMemory"; import { BOX_BEDROCK_PACK, boxLocalDir, @@ -62,8 +62,8 @@ export async function readBoxNetworks( const runtimes = spec.runtimes.filter((runtime) => runtimeRunsInBox(spec, runtime)); if (runtimes.length === 0) return []; assertBoxRuntimesHaveProfiles(projectRoot, runtimes); - // The model sees the targets build adds for the model and Memory calls, so no host takes a - // second target for their endpoints. + // The model sees the target build adds for the model calls, so no host takes a second target for + // its endpoint. const withDefaults = structuredClone(spec); addBoxGatewayTargets(withDefaults, region); const networks: BoxNetwork[] = []; @@ -424,10 +424,7 @@ function policyFileProblem( } /** The policy files that build writes for the gateway's role. */ -const BUILD_POLICY_FILES: ReadonlySet = new Set([ - BOX_BEDROCK_POLICY_FILE, - BOX_MEMORY_POLICY_FILE, -]); +const BUILD_POLICY_FILES: ReadonlySet = new Set([BOX_BEDROCK_POLICY_FILE]); /** * The actions that the Allow statements of the `.json` policy files of `policies` grant, and a diff --git a/src/core/project/boxNetworkWriters.test.ts b/src/core/project/boxNetworkWriters.test.ts index c0c63ac69..d353d9082 100644 --- a/src/core/project/boxNetworkWriters.test.ts +++ b/src/core/project/boxNetworkWriters.test.ts @@ -1,9 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { getBoxGatewayAgentCoreTargetSpec } from "../../handlers/project/shortcuts"; import type { AgentCoreGatewayTarget } from "../../projectSchemas/gateway"; import { boxGatewaySpec, type ProjectSpec } from "../../projectSchemas/project"; import type { BoxNetwork, BoxNetworkHost } from "./boxNetwork"; -import { BOX_BEDROCK_POLICY_FILE, BOX_MEMORY_POLICY_FILE } from "./boxMemory"; +import { BOX_BEDROCK_POLICY_FILE } from "./boxMemory"; import { BOX_NETWORK_WRITERS, boxNetworkEdits, @@ -18,7 +17,24 @@ import { AGENTCORE_CODEZIP_PACK_PATH, AGENTCORE_PACK_PATH } from "./templates/bo import { serializeRuntimeProfile } from "./runtimeProfile/serialize"; /** A hand-built model of runtime `agent`, which each test changes as it needs. */ +/** + * A network of the runtime `agent`. Its Runtime profile routes each host with a target through the + * gateway, as the gateway rule writes it, unless `overrides` gives another profile. + */ function network(overrides: Partial = {}): BoxNetwork { + const routes = (overrides.hosts ?? []).flatMap((each) => + each.target === undefined + ? [] + : [ + [ + each.target, + { + destinations: [each.authority], + backends: [{ url: `\${{ inputs.gateway.url }}/${each.target}` }], + }, + ], + ], + ); return { runtime: "agent", gateway: "agent-box-egress", @@ -26,7 +42,11 @@ function network(overrides: Partial = {}): BoxNetwork { hosts: [], envRoutes: [], policyFiles: [], - runtimeProfile: { packs: ["@box/base", "@box/agentcore"], profile: { name: "demo" } }, + runtimeProfile: { + packs: ["@box/base", "@box/agentcore"], + profile: { name: "demo" }, + ...(routes.length > 0 && { egress: Object.fromEntries(routes) }), + }, runtimeProfileHeader: ["Derived from .box/agent/local/profile.toml."], grantedActions: [], warnings: [], @@ -143,6 +163,44 @@ describe("boxNetworkEdits", () => { }); describe("gatewayTargetsWriter", () => { + test("writes no target for a host that the Runtime profile sends directly, and removes a managed one it holds", () => { + const MEMORY_HOST = "bedrock-agentcore.us-west-2.amazonaws.com"; + // The additions rule sends a route to the AgentCore host directly when the runtime has its + // default Memory, so the route has no backend to the host's target. + const direct = (targets: AgentCoreGatewayTarget[]) => + run( + [gatewayTargetsWriter], + [ + network({ + hosts: [host(MEMORY_HOST, "egress-tools"), host("httpbin.org", "egress-httpbin-org")], + runtimeProfile: { + egress: { + tools: { destinations: [MEMORY_HOST], secret: { ref: "aws://" } }, + "egress-httpbin-org": { + destinations: ["httpbin.org"], + backends: [{ url: "${{ inputs.gateway.url }}/egress-httpbin-org" }], + }, + }, + }, + }), + ], + spec(targets), + ); + + const first = direct([MINE]); + expect(targetNames(first.spec)).toEqual(["mine", "egress-httpbin-org"]); + expect(first.messages).toEqual([ + "adding gateway target 'egress-httpbin-org' to 'agent-box-egress' for httpbin.org", + ]); + + const held = direct([MINE, passthrough("egress-tools", `https://${MEMORY_HOST}`)]); + expect(targetNames(held.spec)).toEqual(["mine", "egress-httpbin-org"]); + expect(held.messages).toContain( + "removing gateway target 'egress-tools' from 'agent-box-egress': on AgentCore Runtime the " + + `box sends the calls to ${MEMORY_HOST} directly, not through the gateway`, + ); + }); + test("adds a host's target, rewrites a managed one, removes a stale one, and keeps the user's", () => { const project = spec([ passthrough("ours", "https://ours.example.com"), @@ -340,7 +398,7 @@ describe("credentialsWriter", () => { }); describe("defaultTargetsWriter", () => { - test("adds the model and Memory targets and writes the role policies, as addBoxGatewayTargets does", () => { + test("adds the model target and writes its role policy, and none for the default Memory, as addBoxGatewayTargets does", () => { const project = spec(); project.memories.push({ name: "agentMemory", @@ -350,34 +408,9 @@ describe("defaultTargetsWriter", () => { const edits = run([defaultTargetsWriter], [network()], project); - expect(targetNames(edits.spec)).toEqual(["mine", "bedrock", "agentcore"]); - expect(edits.files.map(({ path }) => path)).toEqual([ - BOX_BEDROCK_POLICY_FILE, - BOX_MEMORY_POLICY_FILE, - ]); - }); - - test("writes the Memory policy for the region of the agentcore target it writes", () => { - const project = spec(); - project.memories.push({ - name: "agentMemory", - eventExpiryDuration: 30, - strategies: [], - } as never); - - const edits = run([defaultTargetsWriter], [network({ region: "eu-central-1" })], project); - - const agentcore = edits.spec.agentCoreGateways[0]!.targets.find( - ({ name }) => name === "agentcore", - ); - expect(agentcore?.outboundAuth?.region).toBe("eu-central-1"); - const memory = edits.files.find(({ path }) => path === BOX_MEMORY_POLICY_FILE); - expect(JSON.parse((memory as { text: string }).text).Statement).toEqual([ - expect.objectContaining({ - Resource: ["arn:aws:bedrock-agentcore:eu-central-1:*:memory/demo_*agentMemory-*"], - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }), - ]); + // The agent's Memory calls go to Memory directly, so they take no target and no gateway policy. + expect(targetNames(edits.spec)).toEqual(["mine", "bedrock"]); + expect(edits.files.map(({ path }) => path)).toEqual([BOX_BEDROCK_POLICY_FILE]); }); test("writes the Bedrock policy for the region of the bedrock target it writes", () => { @@ -396,40 +429,24 @@ describe("defaultTargetsWriter", () => { ]); }); - test("writes the model and Memory targets for the region of the build", () => { - const project = spec(); - project.memories.push({ - name: "agentMemory", - eventExpiryDuration: 30, - strategies: [], - } as never); - - const edits = run([defaultTargetsWriter], [network({ region: "eu-central-1" })], project); + test("writes the model target for the region of the build", () => { + const edits = run([defaultTargetsWriter], [network({ region: "eu-central-1" })]); const regions = edits.spec.agentCoreGateways[0]!.targets.map( ({ name, outboundAuth }) => `${name}:${outboundAuth?.region}`, ); - expect(regions).toEqual(["mine:undefined", "bedrock:eu-central-1", "agentcore:eu-central-1"]); + expect(regions).toEqual(["mine:undefined", "bedrock:eu-central-1"]); }); test("adds no default target for an endpoint a target serves already", () => { const project = spec([ - { ...getBoxGatewayAgentCoreTargetSpec(), name: "mem" }, passthrough("egress-models", "https://bedrock-runtime.us-west-2.amazonaws.com"), ]); - project.memories.push({ - name: "agentMemory", - eventExpiryDuration: 30, - strategies: [], - } as never); const edits = run([defaultTargetsWriter], [network()], project); - expect(targetNames(edits.spec)).toEqual(["mem", "egress-models"]); - expect(edits.spec.agentCoreGateways[0]!.additionalPolicies).toEqual([ - BOX_BEDROCK_POLICY_FILE, - BOX_MEMORY_POLICY_FILE, - ]); + expect(targetNames(edits.spec)).toEqual(["egress-models"]); + expect(edits.spec.agentCoreGateways[0]!.additionalPolicies).toEqual([BOX_BEDROCK_POLICY_FILE]); }); }); diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 03f1b22cb..9051b257c 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -19,14 +19,9 @@ import { type BoxNetwork, type BoxNetworkHost, } from "./boxNetwork"; +import { agentCoreDataPlaneHost } from "../../handlers/project/shortcuts"; import { projectGatewayTargetFor } from "./boxNetwork/projectGateways"; -import { - addBoxGatewayTargets, - BOX_BEDROCK_POLICY_FILE, - BOX_MEMORY_POLICY_FILE, - boxBedrockPolicy, - boxMemoryPolicy, -} from "./boxMemory"; +import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, boxBedrockPolicy } from "./boxMemory"; import type { ReadEnvFileOptions } from "../../io/envFile"; import { boxKeyVariables, @@ -257,8 +252,17 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { ? [] : [{ ...host, target: host.target }], ); - const sent = served.filter((host) => undeclaredKey(spec, host) === undefined); - const unsent = served.filter((host) => undeclaredKey(spec, host) !== undefined); + // The AgentCore host takes no target when the Runtime profile sends its calls directly: with the + // default Memory, every call of the box to that host goes there (runtimeProfile/rules/additions.ts). + // Only that host, so a rule that drops another route never removes its target with this message. + const routed = gatewayRoutedTargets(network.runtimeProfile); + const agentCoreHost = agentCoreDataPlaneHost(network.region); + const direct = served.filter( + (host) => host.host === agentCoreHost && routed !== undefined && !routed.has(host.target), + ); + const used = served.filter((host) => !direct.includes(host)); + const sent = used.filter((host) => undeclaredKey(spec, host) === undefined); + const unsent = used.filter((host) => undeclaredKey(spec, host) !== undefined); const existing = gateway.targets; const messages: string[] = []; const targets: AgentCoreGatewayTarget[] = []; @@ -284,6 +288,14 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { const host = sent.find((candidate) => candidate.target === target.name); if (!host) { if (unsent.some((candidate) => candidate.target === target.name)) continue; + const directHost = direct.find((candidate) => candidate.target === target.name); + if (directHost) { + messages.push( + `removing gateway target '${target.name}' from ${gatewayName}: on AgentCore Runtime the ` + + `box sends the calls to ${directHost.authority} directly, not through the gateway`, + ); + continue; + } const named = target.passthrough?.gateway; const at = target.passthrough?.endpoint && parseEndpoint(target.passthrough.endpoint); messages.push( @@ -330,6 +342,29 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { return messages; } +/** + * The names of the gateway targets that a route or MCP server of `profile` sends calls to, through + * a backend at `${{ inputs.gateway.url }}/`; `undefined` when build has no Runtime profile + * for the network. + */ +function gatewayRoutedTargets(profile: Readonly | undefined): Set | undefined { + if (profile === undefined) return undefined; + const prefix = `${RUNTIME_INPUTS.gatewayUrl}/`; + const names = new Set(); + for (const key of ["egress", "mcp"]) { + const table = profile[key]; + if (!isTable(table)) continue; + for (const entry of Object.values(table)) { + if (!isTable(entry) || !Array.isArray(entry.backends)) continue; + for (const backend of entry.backends) { + const url = isTable(backend) ? backend.url : undefined; + if (typeof url === "string" && url.startsWith(prefix)) names.add(url.slice(prefix.length)); + } + } + } + return names; +} + /** The API key that a host's target sends, when agentcore.json declares no credential for it. */ function undeclaredKey( spec: ProjectSpec, @@ -344,16 +379,12 @@ function undeclaredKey( } /** - * The `bedrock` and `agentcore` targets that each box runtime's model and Memory calls take, and - * the Bedrock and Memory policies of the gateways' role, as `addBoxGatewayTargets` adds them. + * The `bedrock` target that each box runtime's model calls take, and the Bedrock policy of the + * gateways' role, as `addBoxGatewayTargets` adds them. */ export const defaultTargetsWriter: BoxNetworkWriter = { name: "default targets", - writes: () => [ - { kind: "defaultTargets" }, - { kind: "file", path: BOX_BEDROCK_POLICY_FILE }, - { kind: "file", path: BOX_MEMORY_POLICY_FILE }, - ], + writes: () => [{ kind: "defaultTargets" }, { kind: "file", path: BOX_BEDROCK_POLICY_FILE }], edits: (networks, { spec }) => { // Every network of one build has the region build builds for. const region = networks[0]?.region; @@ -364,11 +395,7 @@ export const defaultTargetsWriter: BoxNetworkWriter = { path: BOX_BEDROCK_POLICY_FILE, policy: region === undefined ? undefined : boxBedrockPolicy(spec, region), }, - { - path: BOX_MEMORY_POLICY_FILE, - policy: region === undefined ? undefined : boxMemoryPolicy(spec, region), - }, - ].flatMap(({ path, policy }) => + ].flatMap(({ path, policy }): BoxNetworkFile[] => policy ? [{ path, text: `${JSON.stringify(policy, undefined, 2)}\n` }] : [], ), }; diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 52ea781a7..c838c7931 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -10,6 +10,7 @@ import type { Project } from "../../handlers/project/types"; import { FsReadWriteJson, type ReadWriteJson } from "../../io"; import { createSilentLogger, matchGolden, TestIdentityClient } from "../../testing"; import type { DeployBackendInput, ProjectBackend } from "./backends/types"; +import type { BoxNetwork } from "./boxNetwork"; import { boxShowOf, FakeBoxProfileResolver } from "./boxProfileResolver-test-support"; import type { ResolvedBoxProfile } from "./boxProfileResolver"; import { seedBoxCache } from "./backends/box-release-test-support"; @@ -253,6 +254,7 @@ async function boxGateway(root: string) { const spec = JSON.parse(await text(root, SPEC)); return spec.agentCoreGateways.find(({ name }: { name: string }) => name === GATEWAY) as { targets: Record[]; + additionalPolicies?: string[]; enableApplicationLogs?: boolean; }; } @@ -301,13 +303,9 @@ describe("build writes the Box network of the box profile", () => { const { steps } = await build(manager, root); expect(counter.specWrites).toBe(1); - // create declares no target, so build adds the egress targets first, then bedrock and Memory. - expect(await targetNames(root)).toEqual([ - "egress-github", - "egress-httpbin-org", - "bedrock", - "agentcore", - ]); + // create declares no target, so build adds the egress targets first, then bedrock. The agent's + // Memory calls take no target: they go to Memory directly. + expect(await targetNames(root)).toEqual(["egress-github", "egress-httpbin-org", "bedrock"]); const { targets } = await boxGateway(root); expect(targets.slice(0, 2)).toEqual([ userTarget("egress-github", "https://api.github.com", { outboundAuth: GITHUB_KEY }), @@ -340,6 +338,11 @@ describe("build writes the Box network of the box profile", () => { ]); expect(egress.github).toEqual(gatewayRoute("egress-github", "api.github.com")); expect(egress["egress-httpbin-org"]).toEqual(gatewayRoute("egress-httpbin-org", "httpbin.org")); + // The Memory route has no backend: box signs it with the execution role, for Memory itself. + expect(egress.agentcore).toEqual({ + destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], + secret: { ref: "aws://" }, + }); expect(egress["bedrock-api-key"]).toEqual( gatewayRoute("bedrock", "bedrock-runtime.us-west-2.amazonaws.com"), ); @@ -411,7 +414,7 @@ describe("build writes the Box network of the box profile", () => { const { steps } = await build(manager, root); - expect(await targetNames(root)).toEqual(["bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["bedrock"]); expect(JSON.parse(await text(root, SPEC)).credentials ?? []).toEqual([]); expect(steps).toContain( `not adding gateway target 'egress-github' of '${GATEWAY}' for api.github.com: it sends ` + @@ -461,7 +464,7 @@ describe("build writes the Box network of the box profile", () => { const { steps, warnings } = await build(manager, root); - expect(await targetNames(root)).toEqual(["egress-tools", "bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["egress-tools", "bedrock"]); const { targets } = await boxGateway(root); // A CUSTOM passthrough target, so Box alone decides each mcp:call. expect(targets[0]).toEqual( @@ -501,7 +504,7 @@ describe("build writes the Box network of the box profile", () => { const { steps } = await build(manager, root); - expect(await targetNames(root)).toEqual(["bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["bedrock"]); expect(steps).toContain( `not adding gateway target 'egress-tools' of '${GATEWAY}' for tools.example.com: it sends ` + "the key of env://TOOLS_TOKEN, and agentcore.json has no API key credential 'tools' " + @@ -524,7 +527,7 @@ describe("build writes the Box network of the box profile", () => { await build(manager, root); - expect(await targetNames(root)).toEqual(["gh", "weather", "bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["gh", "weather", "bedrock"]); const egress = (await runtimeProfile(root)).egress as Record; expect(egress.github).toEqual(gatewayRoute("gh", "api.github.com")); }); @@ -540,36 +543,133 @@ describe("build writes the Box network of the box profile", () => { const { steps } = await build(manager, root); - expect(await targetNames(root)).toEqual(["bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["bedrock"]); expect(steps).toContain( `removing gateway target 'egress-github' from '${GATEWAY}': the Box profile no longer ` + "allows api.github.com", ); }); - test("gives the Memory endpoint to the agentcore target, and adds no second target for it", async () => { + test("sends an entry of the profile for the AgentCore host directly on the Runtime, with its name", async () => { const { manager, root, box } = await strandsProject(); + const host = "bedrock-agentcore.us-west-2.amazonaws.com"; await editProfile(root, { - tables: - '\n[egress.memory]\ndestinations = ["bedrock-agentcore.us-west-2.amazonaws.com"]\n' + - 'secret.ref = "aws://default"\n', - }); - box.answer = shows({ - memory: { - destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], - secret: { ref: "aws://default" }, - }, + tables: `\n[egress.tools]\ndestinations = ["${host}"]\nsecret.ref = "aws://default"\n`, }); + box.answer = shows({ tools: { destinations: [host], secret: { ref: "aws://default" } } }); - await build(manager, root); + const { warnings } = await build(manager, root); - expect(await targetNames(root)).toEqual(["bedrock", "agentcore"]); + // Code Interpreter, Browser, and Memory share that host, and box routes a connection by host + // alone. So on the Runtime the entry goes to the host directly, signed with the execution + // role, and it carries the Memory calls too. const egress = (await runtimeProfile(root)).egress as Record; - // The route of [egress.memory] keeps the name of its entry, and goes to the agentcore target. - expect(Object.keys(egress)).toEqual(["bedrock-api-key", "memory"]); - expect(egress.memory).toEqual( - gatewayRoute("agentcore", "bedrock-agentcore.us-west-2.amazonaws.com"), + expect(Object.keys(egress)).toEqual(["bedrock-api-key", "tools"]); + expect(egress.tools).toEqual({ destinations: [host], secret: { ref: "aws://" } }); + // The Runtime does not use a gateway target for the host, so build writes none, and gives no + // warning about the gateway role's grants for one. + expect(await targetNames(root)).toEqual(["bedrock"]); + expect(warnings).not.toContainEqual(expect.stringContaining("Target 'egress-")); + + // A second build changes nothing. + const spec = await text(root, SPEC); + const again = await build(manager, root); + expect(again.steps.filter((step) => step.includes("gateway target"))).toEqual([]); + expect(await text(root, SPEC)).toBe(spec); + }); + + const AGENTCORE_HOST = "bedrock-agentcore.us-west-2.amazonaws.com"; + test.each([ + { + form: "an HTTP [mcp] server", + label: "[mcp.tools]", + tables: `\n[mcp.tools]\ntype = "http"\ndestinations = ["${AGENTCORE_HOST}"]\nsecret.ref = "env://TOOLS_TOKEN"\n`, + answer: { + egress: { bedrock: BEDROCK }, + mcp: { + tools: { + type: "http", + destinations: [AGENTCORE_HOST], + secret: { ref: "env://TOOLS_TOKEN" }, + }, + }, + }, + }, + { + form: "an [egress] entry", + label: "[egress.tools]", + tables: `\n[egress.tools]\ndestinations = ["${AGENTCORE_HOST}"]\nsecret.ref = "env://TOOLS_TOKEN"\n`, + answer: { + egress: { + bedrock: BEDROCK, + tools: { destinations: [AGENTCORE_HOST], secret: { ref: "env://TOOLS_TOKEN" } }, + }, + }, + }, + { + form: "an [egress] entry with another host too", + label: "[egress.tools]", + tables: `\n[egress.tools]\ndestinations = ["${AGENTCORE_HOST}", "api.github.com"]\nsecret.ref = "env://TOOLS_TOKEN"\n`, + answer: { + egress: { + bedrock: BEDROCK, + tools: { + destinations: [AGENTCORE_HOST, "api.github.com"], + secret: { ref: "env://TOOLS_TOKEN" }, + }, + }, + }, + }, + ])( + "stops for $form that sends an env:// key to the AgentCore host, and writes nothing", + async ({ label, tables, answer }) => { + const { manager, root, box } = await strandsProject({ env: { TOOLS_TOKEN: "tools-123" } }); + await editProfile(root, { tables }); + box.answer = boxShowOf(answer); + const spec = await text(root, SPEC); + + const error = await build(manager, root).then( + () => undefined, + (caught: unknown) => caught, + ); + + // With the default Memory, box sends every call to the AgentCore host directly, signed with + // the execution role, so the key would never reach the server. + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toContain( + `${label} sends env://TOOLS_TOKEN to ${AGENTCORE_HOST}. On AgentCore Runtime, runtime ` + + "'agent_python_strands' has its default Memory, so box sends every call to that host " + + "directly, signed with the execution role", + ); + // Build provisions no credential that nothing would send. + expect(await text(root, SPEC)).toBe(spec); + }, + ); + + test("stops for a user target named agentcore, the name of the Memory route, and keeps it", async () => { + const { manager, root, box } = await strandsProject(); + const mine = { + name: "agentcore", + targetType: "passthrough", + passthrough: { endpoint: "https://memory.example.com", protocolType: "CUSTOM" }, + outboundAuth: { type: "NONE" }, + }; + await editGateway(root, (gateway) => gateway.targets.push(mine)); + box.answer = shows({}); + + const error = await build(manager, root).then( + () => undefined, + (caught: unknown) => caught, + ); + + // Build does not remove a target of the user, and its route would take the Memory route's name. + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toContain( + `agentcore/agentcore.json [egress.agentcore] is the name of the route that the agent's ` + + "Memory calls take on AgentCore Runtime, to bedrock-agentcore.us-west-2.amazonaws.com. " + + `Rename the 'agentcore' target of gateway '${GATEWAY}'.`, ); + expect((await boxGateway(root)).targets).toContainEqual(mine); }); test("on a first build, stops with every problem, where it is, and writes nothing", async () => { @@ -1339,7 +1439,7 @@ describe("build reads the box profile as box resolves it", () => { }); }); -describe("build writes the Bedrock and Memory targets for the region it builds for", () => { +describe("build writes the Bedrock target and the Memory route for the region it builds for", () => { const bedrockTarget = (region: string) => ({ name: "bedrock", targetType: "passthrough", @@ -1357,10 +1457,7 @@ describe("build writes the Bedrock and Memory targets for the region it builds f const { targets } = await boxGateway(root); expect(targets.find(({ name }) => name === "bedrock")).toEqual(bedrockTarget("eu-central-1")); - expect(targets.find(({ name }) => name === "agentcore")).toMatchObject({ - passthrough: { endpoint: "https://bedrock-agentcore.eu-central-1.amazonaws.com" }, - outboundAuth: { region: "eu-central-1" }, - }); + expect(targets.find(({ name }) => name === "agentcore")).toBeUndefined(); const profile = await runtimeProfile(root); expect(profile.options).toEqual({ bedrock: { region: "eu-central-1", "sign-in": "api-key" } }); const egress = profile.egress as Record; @@ -1371,6 +1468,11 @@ describe("build writes the Bedrock and Memory targets for the region it builds f expect(JSON.stringify(egress["bedrock-api-key"]!.backends)).toContain( '"region":"${{ inputs.aws.region }}"', ); + // The Memory route goes to the Memory host of that region, with no backend. + expect(egress.agentcore as unknown).toEqual({ + destinations: ["bedrock-agentcore.eu-central-1.amazonaws.com"], + secret: { ref: "aws://" }, + }); }); test("takes the region build is given over AWS_REGION, as --region does", async () => { @@ -1395,7 +1497,7 @@ describe("build writes the Bedrock and Memory targets for the region it builds f // @box/bedrock's route is for eu-central-1, so the bedrock target serves it, and no // egress-bedrock target is added for the us-west-2 host that `agentcore dev` calls. - expect(await targetNames(root)).toEqual(["bedrock", "agentcore"]); + expect(await targetNames(root)).toEqual(["bedrock"]); const [call] = box.calls; expect(isAbsolute(call!.profilePath)).toBe(true); expect(existsSync(call!.profilePath)).toBe(false); @@ -1442,26 +1544,13 @@ describe("build writes the Bedrock and Memory targets for the region it builds f expect(targets.find(({ name }) => name === "bedrock")).toEqual(bedrockTarget("eu-west-2")); }); - test("moves a target it wrote for another region, and keeps one the user changed", async () => { + test("moves a target it wrote for another region", async () => { const { manager, root } = await strandsProject(); await build(manager, root); await editGateway(root, (gateway) => { - gateway.targets = gateway.targets.map((target) => { - const { name } = target as { name: string }; - if (name === "bedrock") return bedrockTarget("us-east-1"); - if (name === "agentcore") { - return { - ...(target as object), - passthrough: { endpoint: "https://memory.example.com", protocolType: "CUSTOM" }, - outboundAuth: { - type: "GATEWAY_IAM_ROLE", - service: "bedrock-agentcore", - region: "eu-west-1", - }, - }; - } - return target; - }); + gateway.targets = gateway.targets.map((target) => + (target as { name: string }).name === "bedrock" ? bedrockTarget("us-east-1") : target, + ); }); const { steps } = await build(manager, root); @@ -1471,9 +1560,6 @@ describe("build writes the Bedrock and Memory targets for the region it builds f expect(steps).toContain( `updating target 'bedrock' of gateway '${GATEWAY}' in agentcore.json from us-east-1 to us-west-2`, ); - expect(targets.find(({ name }) => name === "agentcore")).toMatchObject({ - passthrough: { endpoint: "https://memory.example.com" }, - }); }); }); @@ -1517,11 +1603,7 @@ describe("deploy writes the Box network before the backend deploys", () => { expect(calls).toHaveLength(1); const { spec } = calls[0]!.project; const gateway = spec.agentCoreGateways.find(({ name }) => name === GATEWAY); - expect(gateway?.targets.map(({ name }) => name)).toEqual([ - "egress-github", - "bedrock", - "agentcore", - ]); + expect(gateway?.targets.map(({ name }) => name)).toEqual(["egress-github", "bedrock"]); // Deploy writes the targets for its target's region, not the AWS_REGION build would take. expect(gateway?.targets.find(({ name }) => name === "bedrock")?.outboundAuth?.region).toBe( "eu-west-1", @@ -1535,10 +1617,16 @@ describe("deploy writes the Box network before the backend deploys", () => { expect(await text(root, "agentcore/.env.local")).toMatch(/^AGENTCORE_CREDENTIAL_GITHUB=./m); }); - test("moves the Memory and Bedrock policies with their targets to the region of the targets", async () => { + test("moves the Bedrock policy with its target, and the Memory route, to the region of the targets", async () => { + // The networks build and deploy hand the backend, which this one does not stage. + const networks: (readonly BoxNetwork[])[] = []; const backend: ProjectBackend = { - async *build() {}, - async *deploy() { + async *build(_project, input) { + networks.push(input?.boxNetworks ?? []); + yield { type: "step", message: "building" }; + }, + async *deploy(_project, input) { + networks.push(input.boxNetworks); yield { type: "step", message: "deploying" }; return { outputs: {} }; }, @@ -1550,31 +1638,28 @@ describe("deploy writes the Box network before the backend deploys", () => { }, }; const { manager, root } = await strandsProject({ backends: { CDK: backend } }); - const memoryStatements = async () => - JSON.parse(await text(root, "agentcore/box-memory-policy.json")).Statement as unknown[]; + const memoryRoute = () => + (networks.at(-1)![0]!.runtimeProfile!.egress as Record).agentcore; const bedrockResources = async () => JSON.parse(await text(root, "agentcore/box-bedrock-policy.json")).Statement.map( ({ Resource }: { Resource: string[] }) => Resource, ); const authOf = async (target: string) => (await boxGateway(root)).targets.find(({ name }) => name === target)?.outboundAuth; - const statementsFor = (region: string) => [ - expect.objectContaining({ - Resource: [ - `arn:aws:bedrock-agentcore:${region}:*:memory/demo_*agent_python_strandsMemory-*`, - ], - Condition: { StringEquals: { "aws:ResourceAccount": "${aws:PrincipalAccount}" } }, - }), - ]; + const routeFor = (region: string) => ({ + destinations: [`bedrock-agentcore.${region}.amazonaws.com`], + secret: { ref: "aws://" }, + }); const bedrockFor = (region: string) => [ [`arn:aws:bedrock:${region}:*:inference-profile/*`], [`arn:aws:bedrock:${region}::foundation-model/*`], ["arn:aws:bedrock:*::foundation-model/*"], ]; await build(manager, root); - expect(await authOf("agentcore")).toMatchObject({ region: "us-west-2" }); + expect(await authOf("agentcore")).toBeUndefined(); expect(await authOf("bedrock")).toMatchObject({ region: "us-west-2" }); - expect(await memoryStatements()).toEqual(statementsFor("us-west-2")); + expect(existsSync(path(root, "agentcore/box-memory-policy.json"))).toBe(false); + expect(memoryRoute()).toEqual(routeFor("us-west-2")); expect(await bedrockResources()).toEqual(bedrockFor("us-west-2")); await writeFile( path(root, "agentcore/aws-targets.json"), @@ -1590,9 +1675,8 @@ describe("deploy writes the Box network before the backend deploys", () => { }), ); - expect(await authOf("agentcore")).toMatchObject({ region: "eu-west-1" }); expect(await authOf("bedrock")).toMatchObject({ region: "eu-west-1" }); - expect(await memoryStatements()).toEqual(statementsFor("eu-west-1")); + expect(memoryRoute()).toEqual(routeFor("eu-west-1")); expect(await bedrockResources()).toEqual(bedrockFor("eu-west-1")); }); }); diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 12751548a..15959e228 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; +import { parse } from "smol-toml"; import { existsSync, readdirSync } from "node:fs"; import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { writeMigrationState } from "./migrate/journal"; @@ -2272,9 +2273,10 @@ describe("FsProjectManager.build", () => { cwd: join(directory, "example", "agentcore", "cdk"), }, ]); - // Build adds the Bedrock and Memory targets, and grants the Box gateway's role each, since the - // gateway signs the agent's calls with that role. With OTEL on, it grants the execution role - // X-Ray for the default traces target of the Runtime profile. + // Build adds the Bedrock target, and grants it to the Box gateway's role, since the gateway signs + // the agent's model calls with that role. The Memory calls take no target: they go to Memory + // directly, signed with the execution role. With OTEL on, build grants the execution role X-Ray + // for the default traces target of the Runtime profile. expect(events).toEqual([ { type: "step", @@ -2286,23 +2288,12 @@ describe("FsProjectManager.build", () => { message: "adding 'agentcore/box-bedrock-policy.json' to gateway 'agent-python-strands-box-box-egress' additionalPolicies in agentcore.json, so its role can call the Bedrock model", }, - { - type: "step", - message: - "adding target 'agentcore' to gateway 'agent-python-strands-box-box-egress' in agentcore.json, for the boxed agent's Memory calls", - }, - { - type: "step", - message: - "adding 'agentcore/box-memory-policy.json' to gateway 'agent-python-strands-box-box-egress' additionalPolicies in agentcore.json, so its role can call Memory", - }, { type: "step", message: "adding agentcore/box-telemetry-policy-agent_python_strands_box.json to additionalPolicies of 'agent_python_strands_box', so its box can send telemetry to CloudWatch", }, { type: "step", message: "writing agentcore/box-bedrock-policy.json" }, - { type: "step", message: "writing agentcore/box-memory-policy.json" }, { type: "step", message: "writing agentcore/box-telemetry-policy-agent_python_strands_box.json", @@ -2402,7 +2393,7 @@ describe("FsProjectManager.build", () => { expect(commands).toEqual([]); }); - test("routes a boxed agent's default Memory through the Box gateway before synth", async () => { + test("sends a boxed agent's default Memory calls to Memory directly, not through the Box gateway", async () => { const directory = await inTempDirectory(); const { manager: subject } = manager(await boxHome()); const project = await scaffolded(subject, directory); @@ -2415,22 +2406,27 @@ describe("FsProjectManager.build", () => { const box = spec.agentCoreGateways.find( ({ name }: { name: string }) => name === boxGatewayName, ); - expect(box.targets.map(({ name }: { name: string }) => name)).toEqual(["bedrock", "agentcore"]); - expect(box.additionalPolicies).toEqual([ - "agentcore/box-bedrock-policy.json", - "agentcore/box-memory-policy.json", - ]); - expect(existsSync(join(root, "agentcore", "box-memory-policy.json"))).toBe(true); - expect(events).toContainEqual({ + // The gateway gets no Memory target, and its role no Memory policy. + expect(box.targets.map(({ name }: { name: string }) => name)).toEqual(["bedrock"]); + expect(box.additionalPolicies).toEqual(["agentcore/box-bedrock-policy.json"]); + expect(existsSync(join(root, "agentcore", "box-memory-policy.json"))).toBe(false); + expect(events).not.toContainEqual({ type: "step", message: "writing agentcore/box-memory-policy.json", }); - // The Runtime profile routes the Memory calls to that target. - const profile = await readFile( - join(root, "app", "agent_python_strands_box", ".box-dist", "profile.toml"), - "utf8", - ); - expect(profile).toContain('url = "${{ inputs.gateway.url }}/agentcore"'); + // The Runtime profile sends the Memory calls to Memory, signed with the execution role. + const profile = parse( + await readFile( + join(root, "app", "agent_python_strands_box", ".box-dist", "profile.toml"), + "utf8", + ), + ) as { egress: Record }; + // Build writes both for the region it builds for, which the environment of the test sets. + const region = box.targets[0].outboundAuth.region as string; + expect(profile.egress.agentcore).toEqual({ + destinations: [`bedrock-agentcore.${region}.amazonaws.com`], + secret: { ref: "aws://" }, + }); // A second build, of the project as it now reads, changes nothing in agentcore.json. const reread = await subject.resolve({ filePath: root }); diff --git a/src/core/project/runtimeProfile/derive.test.ts b/src/core/project/runtimeProfile/derive.test.ts index eeddcc14b..c9513c372 100644 --- a/src/core/project/runtimeProfile/derive.test.ts +++ b/src/core/project/runtimeProfile/derive.test.ts @@ -18,7 +18,7 @@ const CODEZIP = { box: { version: "1.0.0" }, } as ProjectRuntime; const CONTAINER = { ...CODEZIP, build: "Container", entrypoint: "main.py" } as ProjectRuntime; -const SPEC = { name: "demo", runtimes: [CODEZIP] } as unknown as ProjectSpec; +const SPEC = { name: "demo", runtimes: [CODEZIP], memories: [] } as unknown as ProjectSpec; const context = (runtime: ProjectRuntime, places = new Map()) => runtimeProfileContext({ diff --git a/src/core/project/runtimeProfile/derive.ts b/src/core/project/runtimeProfile/derive.ts index d0d4581c1..bc3bdb7e9 100644 --- a/src/core/project/runtimeProfile/derive.ts +++ b/src/core/project/runtimeProfile/derive.ts @@ -8,7 +8,7 @@ * | --- | --- | * | `refusals` | stops for a key that cannot work on the Runtime whatever its paths are | * | `gateway` | sends each call of the box through the runtime's Box gateway | - * | `additions` | adds what only the Runtime needs, and replaces each value that works only under dev | + * | `additions` | adds what only the Runtime needs, the direct Memory route included, and replaces each value that works only under dev | * | `paths` | moves each path of the project to where the code is on the Runtime | */ import * as additions from "./rules/additions"; diff --git a/src/core/project/runtimeProfile/rules/additions.test.ts b/src/core/project/runtimeProfile/rules/additions.test.ts index 5ec2689cf..16f5d3320 100644 --- a/src/core/project/runtimeProfile/rules/additions.test.ts +++ b/src/core/project/runtimeProfile/rules/additions.test.ts @@ -24,12 +24,14 @@ import { runtimeProfileContext } from "../context"; import { deriveRuntimeProfile } from "../derive"; import { serializeRuntimeProfile } from "../serialize"; import type { TomlTable } from "../types"; +import { defaultMemoryName } from "../../../../projectSchemas/memory"; import { agentStartsUnderOtel, apply, DEFAULT_TELEMETRY_TARGET, DEFAULT_TRACES_TARGET, defaultTracesTelemetry, + MEMORY_ROUTE, runtimeProfileHeader, } from "./additions"; @@ -38,6 +40,26 @@ const PROFILE_FILE = ".box/agent/local/profile.toml"; const CREATE_REGION = "us-east-1"; const BUILD_REGION = "us-west-2"; +/** + * The Runtime form of `recorded`, a profile the old renderer wrote for a runtime with its default + * Memory: the Memory route goes to the AgentCore host directly, under the same name, in the same + * place. + */ +function withDirectMemory(recorded: TomlTable): TomlTable { + const result = structuredClone(recorded); + if (isTableValue(result.egress)) result.egress[MEMORY_ROUTE] = DIRECT_MEMORY_ROUTE; + return result; +} + +const isTableValue = (value: unknown): value is TomlTable => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** The route of the agent's Memory calls: to Memory directly, signed with the execution role. */ +const DIRECT_MEMORY_ROUTE = { + destinations: [`bedrock-agentcore.${BUILD_REGION}.amazonaws.com`], + secret: { ref: "aws://" }, +}; + type Build = "CodeZip" | "Container"; type Protocol = NonNullable; @@ -72,14 +94,12 @@ function passthrough(name: string, endpoint: string): AgentCoreGatewayTarget { } as AgentCoreGatewayTarget; } -/** A Box project with `runtime`, its Box gateway with the targets build adds, and `memories`. */ +/** + * A Box project with `runtime`, its Box gateway with the target build adds, and `memories`. Build + * adds no target for Memory: the agent's Memory calls go to Memory directly. + */ function specOf(runtime: ProjectRuntime, memories: readonly string[] = []) { - const targets = [ - passthrough("bedrock", `https://bedrock-runtime.${BUILD_REGION}.amazonaws.com`), - ...(memories.length > 0 - ? [passthrough("agentcore", `https://bedrock-agentcore.${BUILD_REGION}.amazonaws.com`)] - : []), - ]; + const targets = [passthrough("bedrock", `https://bedrock-runtime.${BUILD_REGION}.amazonaws.com`)]; return { name: "demo", runtimes: [runtime], @@ -303,13 +323,14 @@ describe("deriveRuntimeProfile on the created templates", () => { contextOf(runtime, { memories, telemetry }), ); - const recorded = withApiKeySignIn( + const old = withApiKeySignIn( withCreatePolicy( OLD_RENDERER.templates[ `${build} ${protocol} ${provider} memories=${memories.length} telemetry=${telemetryCase}` ] as TomlTable, ), ); + const recorded = memories.length > 0 ? withDirectMemory(old) : old; const expected = otel ? withOtel(recorded, build) : recorded; expect(problems).toEqual([]); for (const key of OWNED) @@ -377,14 +398,19 @@ describe("deriveRuntimeProfile on each box template of create", () => { const { profile, problems } = deriveRuntimeProfile( local, - contextOf(runtime, { memories, telemetry }), + contextOf(runtime, { + memories: memories.length > 0 ? [defaultMemoryName(runtime.name)] : [], + telemetry, + }), ); - const recorded = withCreatePolicy( + // The old renderer sent the Memory calls through the gateway's `agentcore` target. + const old = withCreatePolicy( OLD_RENDERER.boxTemplates[ `${template} provider=${provider} memories=${memories.length} telemetry=${telemetryCase}` ]!, ); + const recorded = memories.length > 0 ? withDirectMemory(old) : old; expect(problems).toEqual([]); const signedIn = withApiKeySignIn(recorded); expect(profile).toEqual(otel ? withOtel(signedIn, input.build as Build) : signedIn); @@ -1098,6 +1124,217 @@ describe("the additions rule", () => { }); }); + describe("the Memory route", () => { + const MEMORY = defaultMemoryName("agent"); + + test("sends the Memory calls of a runtime with its default Memory to Memory directly, signed with the execution role", () => { + const { table, problems } = apply( + createdProfile(CODEZIP), + contextOf(CODEZIP, { memories: [MEMORY] }), + ); + + expect(problems).toEqual([]); + const route = (table.egress as TomlTable)[MEMORY_ROUTE]; + expect(route).toEqual(DIRECT_MEMORY_ROUTE); + // No backend: the Box gateway would sign the calls with its own role. + expect(route).not.toHaveProperty("backends"); + }); + + test("keeps each route of the profile, and adds the Memory route after them", () => { + const local = { + ...createdProfile(CONTAINER), + egress: { github: { destinations: ["api.github.com"] } }, + }; + + const egress = apply(local, contextOf(CONTAINER, { memories: [MEMORY] })).table + .egress as TomlTable; + + expect(Object.keys(egress)).toEqual(["github", MEMORY_ROUTE]); + expect(egress.github).toEqual({ destinations: ["api.github.com"] }); + }); + + test("adds no Memory route for a runtime with no default Memory", () => { + const none = apply(createdProfile(CODEZIP), contextOf(CODEZIP)).table; + const other = apply(createdProfile(CODEZIP), contextOf(CODEZIP, { memories: ["shared"] })); + expect(none.egress).not.toHaveProperty(MEMORY_ROUTE); + expect(other.table.egress).not.toHaveProperty(MEMORY_ROUTE); + }); + + test("sends a route or HTTP MCP server of the profile to the AgentCore host directly, with its name, and adds no second route", () => { + const host = `bedrock-agentcore.${BUILD_REGION}.amazonaws.com`; + const backends = [{ url: "${{ inputs.gateway.url }}/egress-tools" }]; + const local = { + egress: { tools: { destinations: [host], backends, when: "true" } }, + mcp: { recall: { type: "http", destinations: [host], backends } }, + }; + + const { table, problems, warnings } = apply( + local, + contextOf(CODEZIP, { memories: [MEMORY] }), + ); + + // Box chooses where a connection goes from its host alone, so every call to the AgentCore + // host goes there directly. Box refuses two signed routes for one host. + expect([problems, warnings]).toEqual([[], []]); + expect(table.egress).toEqual({ + tools: { destinations: [host], when: "true", secret: { ref: "aws://" } }, + }); + expect(table.mcp).toEqual({ + recall: { type: "http", destinations: [host], secret: { ref: "aws://" } }, + }); + }); + + test.each([ + { kind: "egress", entry: {} }, + { kind: "mcp", entry: { type: "http" } }, + ] as const)( + "stops build for an [$kind] entry that sends an env:// key to the AgentCore host", + ({ kind, entry }) => { + const host = `bedrock-agentcore.${BUILD_REGION}.amazonaws.com`; + const context = { + ...contextOf(CODEZIP, { memories: [MEMORY] }), + hosts: [ + { + host, + authority: host, + target: "egress-tools", + outboundAuth: { + kind: "apiKey", + credentialName: "tools", + variable: "TOOLS_TOKEN", + header: "Authorization", + }, + sources: [ + kind === "egress" + ? { kind: "entry", egressEntry: "tools", destinations: [host] } + : { kind: "mcp", mcpEntry: "tools", destinations: [host] }, + ], + }, + ], + } as unknown as Parameters[1]; + // As the gateway rule writes it: a backend to the target that sends the key. + const local = { + [kind]: { + tools: { + ...entry, + destinations: [host], + backends: [{ url: "${{ inputs.gateway.url }}/egress-tools" }], + }, + }, + }; + + const { problems } = apply(local, context); + + expect(problems).toEqual([ + { + code: "RUNTIME_AGENTCORE_HOST_CREDENTIAL", + key: [kind, "tools"], + place: PROFILE_FILE, + reason: + `[${kind}.tools] sends env://TOOLS_TOKEN to ${host}. On AgentCore Runtime, runtime ` + + "'agent' has its default Memory, so box sends every call to that host directly, " + + "signed with the execution role, and not through the Box gateway. Box cannot route " + + "one host both ways, so the key would not be sent. Remove the secret from " + + `[${kind}.tools] if the service takes the execution role's signature, or remove the ` + + "default Memory of runtime 'agent' from agentcore.json.", + }, + ]); + }, + ); + + test("stops build for a route to the AgentCore host that still holds a secret other than aws://", () => { + const host = `bedrock-agentcore.${BUILD_REGION}.amazonaws.com`; + const local = { + mcp: { + tools: { type: "http", destinations: [host], secret: { ref: "env://TOOLS_TOKEN" } }, + }, + }; + + const { problems } = apply(local, contextOf(CODEZIP, { memories: [MEMORY] })); + + expect(problems.map(({ code, key }) => [code, key])).toEqual([ + ["RUNTIME_AGENTCORE_HOST_CREDENTIAL", ["mcp", "tools"]], + ]); + }); + + test("counts a route to the AgentCore host with :443, in another case, or as a wildcard", () => { + const context = contextOf(CODEZIP, { memories: [MEMORY] }); + for (const destination of [ + `bedrock-agentcore.${BUILD_REGION}.amazonaws.com:443`, + `Bedrock-AgentCore.${BUILD_REGION}.amazonaws.com`, + "*.amazonaws.com", + ]) { + const local = { egress: { tools: { destinations: [destination] } } }; + + expect([destination, apply(local, context).table.egress]).toEqual([ + destination, + { tools: { destinations: [destination], secret: { ref: "aws://" } } }, + ]); + } + // Another port, or a wildcard of another domain, is not the AgentCore host. + const other = { + egress: { + tools: { + destinations: ["*.example.com", `bedrock-agentcore.${BUILD_REGION}.amazonaws.com:8443`], + }, + }, + }; + expect(Object.keys(apply(other, context).table.egress as TomlTable)).toEqual([ + "tools", + MEMORY_ROUTE, + ]); + }); + + test("leaves a gateway route to the Memory host alone for a runtime with no default Memory", () => { + const host = `bedrock-agentcore.${BUILD_REGION}.amazonaws.com`; + const local = { egress: { memory: { destinations: [host], backends: [{ url: "x" }] } } }; + + const { table, problems, warnings } = apply(local, contextOf(CODEZIP)); + expect([problems, warnings]).toEqual([[], []]); + expect(table.egress).toEqual(local.egress); + }); + + test("names the gateway target when a target of the user takes the Memory route's name", () => { + const context = contextOf(CODEZIP, { memories: [MEMORY] }); + const withTarget = { + ...context, + gateway: { + ...context.gateway, + targets: [ + ...context.gateway.targets, + passthrough("agentcore", "https://memory.example.com"), + ], + }, + }; + const local = { egress: { [MEMORY_ROUTE]: { destinations: ["memory.example.com"] } } }; + + const [problem] = apply(local, withTarget).problems; + + expect(problem?.place).toBe("agentcore/agentcore.json"); + expect(problem?.reason).toEndWith( + `Rename the 'agentcore' target of gateway '${context.gateway.name}'.`, + ); + }); + + test("stops build for a route of the user under the name of the Memory route", () => { + const local = { egress: { [MEMORY_ROUTE]: { destinations: ["api.example.com"] } } }; + + const { problems } = apply(local, contextOf(CODEZIP, { memories: [MEMORY] })); + + expect(problems).toEqual([ + { + code: "RUNTIME_ROUTE_NAME_TAKEN", + key: ["egress", MEMORY_ROUTE], + place: PROFILE_FILE, + reason: + `[egress.${MEMORY_ROUTE}] is the name of the route that the agent's Memory calls ` + + `take on AgentCore Runtime, to bedrock-agentcore.${BUILD_REGION}.amazonaws.com. ` + + "Rename that entry.", + }, + ]); + }); + }); + describe("with OTEL on", () => { const OTEL_CODEZIP = runtimeOf("CodeZip", "HTTP", "Bedrock", true); const OTEL_CONTAINER = runtimeOf("Container", "HTTP", "Bedrock", true); @@ -1331,6 +1568,19 @@ describe("the additions rule", () => { expect(derived).toContain("@box/agentcore and @box/agentcore-codezip packs"); expect(runtimeProfileHeader(contextOf(CONTAINER))[1]).not.toContain("@box/agentcore-codezip"); expect(standIns).toContain("AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are stand-ins"); + expect(standIns).toEndWith("Every AWS route goes to the Box gateway."); + const context = contextOf(CODEZIP, { memories: [defaultMemoryName("agent")] }); + const withMemory = runtimeProfileHeader(context, apply(createdProfile(CODEZIP), context).table); + const host = `bedrock-agentcore.${BUILD_REGION}.amazonaws.com`; + expect(withMemory[2]).toEndWith( + `except [egress.${MEMORY_ROUTE}], to ${host}: box sends the calls to that host directly, so ` + + "Memory can hold each call to the session of the runtime.", + ); + // A route of the user that replaces [egress.agentcore] is the one the header names. + const routed = apply({ egress: { tools: { destinations: [host] } } }, context).table; + expect(runtimeProfileHeader(context, routed)[2]).toContain( + `except [egress.tools], to ${host}:`, + ); const text = serializeRuntimeProfile( apply(createdProfile(CODEZIP), contextOf(CODEZIP)).table, runtimeProfileHeader(contextOf(CODEZIP)), diff --git a/src/core/project/runtimeProfile/rules/additions.ts b/src/core/project/runtimeProfile/rules/additions.ts index 412116190..b1b0294f9 100644 --- a/src/core/project/runtimeProfile/rules/additions.ts +++ b/src/core/project/runtimeProfile/rules/additions.ts @@ -16,10 +16,15 @@ * | `[telemetry.]` | each CloudWatch target that box takes is signed with a bare `aws://`, in the deploy region when it names none; one that box refuses goes; a `file` target goes, with a warning | * | `[telemetry.agentcore]` | added when no target is `cloudwatch_logs`: the runtime's own log group and log stream | * | `[telemetry.agentcore_traces]` | added with OTEL on when no target is `cloudwatch_traces`: X-Ray in the Runtime's region | + * | `[egress.agentcore]` | added when the runtime has its default Memory and no route of the profile has the AgentCore host: that host, which box signs with a bare `aws://` and sends to directly, not through the Box gateway | + * | a route to the AgentCore host | with a default Memory, it goes to the host directly, signed with a bare `aws://`, with its name and other keys | * * It moves no path: the paths rule runs after it and moves each path of the user. */ import { posix } from "node:path"; +import { agentCoreDataPlaneHost } from "../../../../handlers/project/shortcuts"; +import { BOX_MEMORY_ROUTE_NAME, hasDefaultMemory } from "../../boxMemory"; +import { parseDestination } from "../../boxNetwork/egress"; import { AGENTCORE_CODEZIP_PACK_NAME, AGENTCORE_PACK_NAME, @@ -41,9 +46,17 @@ import { type RuleResult, type RuntimePaths, type RuntimeProfileContext, + type RuntimeProfileProblem, type TomlTable, } from "../types"; +/** + * The `[egress]` route of the agent's Memory calls. Box signs them with the execution role and + * sends them to AgentCore Memory directly. The Box gateway would sign them with its own role, and + * Memory could then not hold each call to the session of the runtime by its context keys. + */ +export const MEMORY_ROUTE = BOX_MEMORY_ROUTE_NAME; + /** The variables of the region of the agent, which get the region of the Runtime. */ const REGION_ENV_NAMES: ReadonlySet = new Set(["AWS_REGION", "AWS_DEFAULT_REGION"]); @@ -57,8 +70,8 @@ const LOCAL_DEV = "LOCAL_DEV"; const CLOUDWATCH_KINDS: ReadonlySet = new Set(["cloudwatch_logs", "cloudwatch_traces"]); /** - * Stand-in AWS keys for boto3 in the box on AgentCore Runtime. They authenticate nothing: each AWS - * route goes to the Box gateway, and box signs each call for it with the execution role. + * Stand-in AWS keys for boto3 in the box on AgentCore Runtime. They authenticate nothing: box signs + * each AWS call with the execution role, for the Box gateway or, on the Memory route, for Memory. */ const RUNTIME_AWS_STAND_INS: Readonly> = { AWS_ACCESS_KEY_ID: "box-stand-in", @@ -149,8 +162,13 @@ export function runtimeProfileHeader( `Runs the agent of the AgentCore project '${context.spec.name}' in a box.`, `Derived by agentcore build and deploy from ${context.profileFile}, for AgentCore Runtime. ${packs}`, `${Object.keys(RUNTIME_AWS_STAND_INS).join(" and ")} are stand-ins so boto3 in the box can ` + - "build its requests. They authenticate nothing: every AWS route goes to the Box gateway, " + - "and box signs each request for it with the execution role.", + "build its requests. They authenticate nothing: box signs each request with the execution " + + "role. Every AWS route goes to the Box gateway" + + (hasDefaultMemory(context.spec, context.runtime) + ? `, except ${routesToHost(profile, agentCoreDataPlaneHost(context.region))}: box sends ` + + "the calls to that host directly, so Memory can hold each call to the session of the " + + "runtime." + : "."), ...Object.entries(tableOf(profile.telemetry)) .filter(([, target]) => sameValue(target, DEFAULT_TELEMETRY_TARGET)) .map( @@ -213,7 +231,165 @@ export function apply(table: Readonly, context: RuntimeProfileContext else result.tool = tool; } result.telemetry = runtimeTelemetry(result.telemetry, context, warnings); - return { table: result, problems: [], warnings }; + const problems: RuntimeProfileProblem[] = []; + const routes = memoryRoutes(result, context, problems); + if (routes.egress !== undefined) result.egress = routes.egress; + if (routes.mcp !== undefined) result.mcp = routes.mcp; + return { table: result, problems, warnings }; +} + +/** + * `[egress]` and `[mcp]` for the agent's Memory calls when the runtime has its default Memory. They + * go to the AgentCore data-plane host directly, signed with the execution role, not through the Box + * gateway, whose role would sign them and keep Memory from holding each call to the session of the + * runtime. Box chooses where a connection goes from its host alone, before it sees a path, and the + * other AgentCore APIs (Code Interpreter, Browser, and more) share that host. So every call of the + * box to the host goes there directly. + * + * - With no route of the profile to the AgentCore host, build adds {@link MEMORY_ROUTE}: that host, + * signed with a bare `aws://`. + * - A route or HTTP MCP server of the profile to that host, which the gateway rule sends through the + * gateway, goes to the host directly, signed with a bare `aws://`, with its name and other keys. + * Build adds no {@link MEMORY_ROUTE} beside it: box refuses two signed routes for one host. + * - A route of the user named {@link MEMORY_ROUTE} for another host is a problem. + */ +function memoryRoutes( + table: Readonly, + context: RuntimeProfileContext, + problems: RuntimeProfileProblem[], +): Pick { + const { egress, mcp } = table; + if (!hasDefaultMemory(context.spec, context.runtime)) return { egress, mcp }; + // box refuses `[egress]` or `[mcp]` that is not a table before build gets the profile. + if ((egress !== undefined && !isTable(egress)) || (mcp !== undefined && !isTable(mcp))) { + return { egress, mcp }; + } + const host = agentCoreDataPlaneHost(context.region); + credentialProblems(host, egress, mcp, context, problems); + const tables = { egress: { ...egress }, mcp: { ...mcp } } as Record<"egress" | "mcp", TomlTable>; + let routed = false; + for (const kind of ["egress", "mcp"] as const) { + for (const [name, entry] of Object.entries(tables[kind])) { + if (!isTable(entry) || !hasDestination(entry.destinations, host)) continue; + routed = true; + const { backends: _backends, secret: _secret, ...kept } = entry; + tables[kind][name] = { ...kept, secret: { ref: RUNTIME_AWS_SIGNER } }; + } + } + const result = { + egress: Object.keys(tables.egress).length > 0 ? tables.egress : egress, + mcp: Object.keys(tables.mcp).length > 0 ? tables.mcp : mcp, + }; + if (routed) return result; + if (Object.hasOwn(tables.egress, MEMORY_ROUTE)) { + const key = ["egress", MEMORY_ROUTE]; + // The gateway rule names a route for a target that no entry of the profile names after it. + const target = context.gateway.targets.some(({ name }) => name === MEMORY_ROUTE); + problems.push({ + code: "RUNTIME_ROUTE_NAME_TAKEN", + key, + place: target ? "agentcore/agentcore.json" : context.placeOf(key), + reason: + `[egress.${MEMORY_ROUTE}] is the name of the route that the agent's Memory calls take ` + + `on AgentCore Runtime, to ${host}. ` + + (target + ? `Rename the '${MEMORY_ROUTE}' target of gateway '${context.gateway.name}'.` + : "Rename that entry."), + }); + return result; + } + return { + ...result, + egress: { + ...tables.egress, + [MEMORY_ROUTE]: { destinations: [host], secret: { ref: RUNTIME_AWS_SIGNER } }, + }, + }; +} + +/** + * A problem for each entry of the profile that sends a credential of its own to the AgentCore host, + * such as the `env://` API key of an MCP server on another AgentCore Runtime. With the default + * Memory, every call of the box to that host goes there directly, signed with the execution role, + * and box cannot route one host both ways. So the key would never be sent, and the server would + * refuse the call. The Box network model records the API key of the host; an entry that still + * holds a secret other than `aws://` names one too. + */ +function credentialProblems( + host: string, + egress: TomlTable | undefined, + mcp: TomlTable | undefined, + context: RuntimeProfileContext, + problems: RuntimeProfileProblem[], +): void { + const named = new Map(); + for (const record of context.hosts) { + if (record.host !== host || record.outboundAuth.kind !== "apiKey") continue; + const secret = `env://${record.outboundAuth.variable}`; + for (const source of record.sources) { + if (source.kind === "entry") { + named.set(`egress.${source.egressEntry}`, { key: ["egress", source.egressEntry], secret }); + } else if (source.kind === "mcp") { + named.set(`mcp.${source.mcpEntry}`, { key: ["mcp", source.mcpEntry], secret }); + } + } + } + for (const [kind, table] of [ + ["egress", egress], + ["mcp", mcp], + ] as const) { + for (const [name, entry] of Object.entries(table ?? {})) { + if (!isTable(entry) || !hasDestination(entry.destinations, host)) continue; + const ref = isTable(entry.secret) ? entry.secret.ref : undefined; + if (typeof ref !== "string" || ref.startsWith("aws://")) continue; + if (!named.has(`${kind}.${name}`)) + named.set(`${kind}.${name}`, { key: [kind, name], secret: ref }); + } + } + for (const { key, secret } of named.values()) { + const label = `[${key.join(".")}]`; + problems.push({ + code: "RUNTIME_AGENTCORE_HOST_CREDENTIAL", + key, + place: context.placeOf(key), + reason: + `${label} sends ${secret} to ${host}. On AgentCore Runtime, runtime ` + + `'${context.runtime.name}' has its default Memory, so box sends every call to that host ` + + "directly, signed with the execution role, and not through the Box gateway. Box cannot " + + "route one host both ways, so the key would not be sent. Remove the secret from " + + `${label} if the service takes the execution role's signature, or remove the default ` + + `Memory of runtime '${context.runtime.name}' from agentcore.json.`, + }); + } +} + +/** + * The routes and HTTP MCP servers of `profile` to `host`, as the header names them: `[egress.agentcore]`, + * or the user's routes when one replaces it. With none, as before the rule runs, the host itself. + */ +function routesToHost(profile: Readonly, host: string): string { + const labels = (["egress", "mcp"] as const).flatMap((kind) => + Object.entries(tableOf(profile[kind])) + .filter(([, entry]) => isTable(entry) && hasDestination(entry.destinations, host)) + .map(([name]) => `[${kind}.${name}]`), + ); + return labels.length > 0 ? `${labels.join(", ")}, to ${host}` : `each route to ${host}`; +} + +/** + * Whether `destinations` has one that box matches to `host` on port 443: the host itself, in any + * case, with or without `:443`, or a `*.` wildcard of its parent domains. + */ +function hasDestination(destinations: unknown, host: string): boolean { + if (!Array.isArray(destinations)) return false; + return destinations.some((text) => { + const destination = typeof text === "string" ? parseDestination(text) : undefined; + if (destination === undefined || destination.port !== 443) return false; + const name = destination.host.toLowerCase(); + return destination.wildcard + ? name.startsWith("*.") && host.endsWith(name.slice(1)) + : name === host; + }); } /** The user's packs in their order, then each Runtime pack that they do not import. */ diff --git a/src/core/project/runtimeProfile/rules/gateway.test.ts b/src/core/project/runtimeProfile/rules/gateway.test.ts index 9db14461a..c5fa41220 100644 --- a/src/core/project/runtimeProfile/rules/gateway.test.ts +++ b/src/core/project/runtimeProfile/rules/gateway.test.ts @@ -1,10 +1,7 @@ import { describe, expect, test } from "bun:test"; import { parse } from "smol-toml"; import { InputValidationError } from "../../../../errors/errors"; -import { - getBoxGatewayAgentCoreTargetSpec, - getBoxGatewayBedrockTargetSpec, -} from "../../../../handlers/project/shortcuts"; +import { getBoxGatewayBedrockTargetSpec } from "../../../../handlers/project/shortcuts"; import type { AgentCoreGatewayTarget } from "../../../../projectSchemas/gateway"; import { boxGatewaySpec, type ProjectSpec } from "../../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../../projectSchemas/runtime"; @@ -301,7 +298,7 @@ describe("the gateway rule", () => { const targets = [ passthrough("orders", "https://orders.example.com/v2"), getBoxGatewayBedrockTargetSpec(), - getBoxGatewayAgentCoreTargetSpec(), + passthrough("tickets", "https://tickets.example.com"), // An earlier build wrote this target, and no host of the profile takes it now. passthrough("egress-old", "https://old.example.com"), { name: "lambda", targetType: "lambda" } as unknown as AgentCoreGatewayTarget, @@ -324,8 +321,8 @@ describe("the gateway rule", () => { backendText("egress.bedrock", "bedrock") + '[egress.orders]\ndestinations = ["orders.example.com"]\n' + backendText("egress.orders", "orders") + - '[egress.agentcore]\ndestinations = ["bedrock-agentcore.us-west-2.amazonaws.com"]\n' + - backendText("egress.agentcore", "agentcore") + + '[egress.tickets]\ndestinations = ["tickets.example.com"]\n' + + backendText("egress.tickets", "tickets") + '[egress.egress-httpbin-org]\ndestinations = ["httpbin.org"]\n' + backendText("egress.egress-httpbin-org", "egress-httpbin-org"), ).egress, @@ -501,6 +498,21 @@ const withEntryKeys = (egress: unknown, bedrockPack = true) => ]), ); +/** + * `withEntryKeys(egress)`, with the Memory route that the old renderer sent through the gateway's + * `agentcore` target as the additions rule now writes it: to Memory directly, with no backend. + */ +const withDirectMemory = (egress: unknown) => { + const result = withEntryKeys(egress); + if (Object.hasOwn(result, "agentcore")) { + result.agentcore = { + destinations: ["bedrock-agentcore.us-west-2.amazonaws.com"], + secret: { ref: "aws://" }, + }; + } + return result; +}; + describe("the gateway rule and the Runtime renderer it replaced", () => { const TEXT = [ 'packs = ["@box/base", "@box/bedrock"]', @@ -651,10 +663,10 @@ describe("the gateway rule and the Runtime renderer it replaced", () => { "orders", ]); expect(Object.keys(http(old.mcp))).toEqual(["docs"]); - expect(derived.profile.egress).toEqual(withEntryKeys(old.egress)); + expect(derived.profile.egress).toEqual(withDirectMemory(old.egress)); expect(http(derived.profile.mcp)).toEqual(http(old.mcp)); // The model that build keeps holds the same derived profile. - expect(network.runtimeProfile?.egress).toEqual(withEntryKeys(old.egress)); + expect(network.runtimeProfile?.egress).toEqual(withDirectMemory(old.egress)); expect(http(network.runtimeProfile?.mcp)).toEqual(http(old.mcp)); }); @@ -665,7 +677,7 @@ describe("the gateway rule and the Runtime renderer it replaced", () => { expect(network.failures).toEqual([]); expect(first.agentCoreGateways[0]!.targets.map(({ name }) => name)).toContain("egress-github"); - expect(derived.profile.egress).toEqual(withEntryKeys(old.egress)); + expect(derived.profile.egress).toEqual(withDirectMemory(old.egress)); expect(http(derived.profile.mcp)).toEqual(http(old.mcp)); }); diff --git a/src/core/project/runtimeProfile/rules/gateway.ts b/src/core/project/runtimeProfile/rules/gateway.ts index 487d636ea..ccc06cc82 100644 --- a/src/core/project/runtimeProfile/rules/gateway.ts +++ b/src/core/project/runtimeProfile/rules/gateway.ts @@ -3,7 +3,8 @@ * Box gateway. Each passthrough target of that gateway, as build writes the gateway, gets one * route: the box sends the calls to the target's host to `${{ inputs.gateway.url }}/`, and * signs them for the gateway in the Runtime's own region, `${{ inputs.aws.region }}`, with a bare - * `aws://`, the execution role. The gateway then calls the host with the target's own auth. + * `aws://`, the execution role. The gateway then calls the host with the target's own auth. The + * agent's Memory calls are the one exception: the additions rule sends them to Memory directly. * * | Local profile | Runtime profile | * | --- | --- | diff --git a/src/core/project/runtimeProfile/rules/paths.test.ts b/src/core/project/runtimeProfile/rules/paths.test.ts index 59428d37a..3f1d8e87f 100644 --- a/src/core/project/runtimeProfile/rules/paths.test.ts +++ b/src/core/project/runtimeProfile/rules/paths.test.ts @@ -25,7 +25,7 @@ const PROFILE = ".box/agent/local/profile.toml"; */ const contextOf = (text: string, runtime: ProjectRuntime = CODEZIP) => runtimeProfileContext({ - spec: { name: "demo", runtimes: [runtime] } as unknown as ProjectSpec, + spec: { name: "demo", runtimes: [runtime], memories: [] } as unknown as ProjectSpec, runtime, profileFile: PROFILE, region: "us-west-2", diff --git a/src/core/project/runtimeProfile/rules/refusals.test.ts b/src/core/project/runtimeProfile/rules/refusals.test.ts index ed1720f94..91b7e3865 100644 --- a/src/core/project/runtimeProfile/rules/refusals.test.ts +++ b/src/core/project/runtimeProfile/rules/refusals.test.ts @@ -26,7 +26,7 @@ const PROFILE = ".box/agent/local/profile.toml"; */ const contextOf = (text: string, runtime: ProjectRuntime = CODEZIP) => runtimeProfileContext({ - spec: { name: "demo", runtimes: [runtime] } as unknown as ProjectSpec, + spec: { name: "demo", runtimes: [runtime], memories: [] } as unknown as ProjectSpec, runtime, profileFile: PROFILE, region: "us-west-2", diff --git a/src/core/project/runtimeProfile/types.ts b/src/core/project/runtimeProfile/types.ts index 8c24da20e..a54dcd89a 100644 --- a/src/core/project/runtimeProfile/types.ts +++ b/src/core/project/runtimeProfile/types.ts @@ -70,7 +70,7 @@ export interface RuntimeProfileContext { readonly runtime: ProjectRuntime; /** The local profile's path from the project root: `.box//local/profile.toml`. */ readonly profileFile: string; - /** The region build builds for: of the Box gateway and its `bedrock` and `agentcore` targets. */ + /** The region build builds for: of the Box gateway, its `bedrock` target, and the Memory route. */ readonly region: string; /** The runtime's Box gateway: its name, and its targets with the ones build adds. */ readonly gateway: { readonly name: string; readonly targets: readonly AgentCoreGatewayTarget[] }; @@ -104,6 +104,10 @@ export const RUNTIME_PROFILE_PROBLEM_CODES = [ "RUNTIME_TELEMETRY_NOT_CLOUDWATCH", /** A CloudWatch telemetry target that box refuses when a run starts. */ "RUNTIME_TELEMETRY_REFUSED", + /** A route of the user under the name of a route that only the Runtime profile has. */ + "RUNTIME_ROUTE_NAME_TAKEN", + /** A route to the AgentCore host with a credential of its own, which the direct route cannot send. */ + "RUNTIME_AGENTCORE_HOST_CREDENTIAL", /** An `[mcp]` server with the name of a gateway of the project, which build adds on the Runtime. */ "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", ] as const; diff --git a/src/handlers/project/add/gateway-target/index.test.ts b/src/handlers/project/add/gateway-target/index.test.ts index a41aee1d8..bf1338c23 100644 --- a/src/handlers/project/add/gateway-target/index.test.ts +++ b/src/handlers/project/add/gateway-target/index.test.ts @@ -118,8 +118,8 @@ describe("project add gateway-target", () => { ...["--outbound-auth", "none"], ]), `the gateway target name '${name}' is reserved on Box gateway '${box.name}': build ` + - `writes the targets 'bedrock', 'agentcore', 'egress-*' for the agent's model, Memory, ` + - `and egress calls. Choose another name.`, + `owns the names 'bedrock', 'agentcore', 'egress-*' for the agent's model calls, Memory ` + + `route, and egress targets. Choose another name.`, InputValidationError, ); // The same name is the user's on a gateway that is not a Box gateway. diff --git a/src/handlers/project/shortcuts.test.ts b/src/handlers/project/shortcuts.test.ts index f22c389bb..3337bea63 100644 --- a/src/handlers/project/shortcuts.test.ts +++ b/src/handlers/project/shortcuts.test.ts @@ -2,8 +2,8 @@ import { describe, expect, test } from "bun:test"; import { EMPTY_TEMPLATE_NAME, formatTemplateParameterHelp, - getBoxGatewayAgentCoreTargetSpec, getBoxGatewayBedrockTargetSpec, + agentCoreDataPlaneHost, getDefaultMemorySpec, PROJECT_TEMPLATE_NAMES, RUNTIME_TEMPLATE_SHORTCUT_NAMES, @@ -87,12 +87,12 @@ test("default memory names fit the service limit for long runtime names", () => expect(memory.name).toHaveLength(48); }); -describe("Box gateway targets", () => { +describe("the Box gateway target and the Memory host", () => { test("take the DNS suffix of the partition of the region", () => { - const endpoints = (region: string) => - [getBoxGatewayBedrockTargetSpec(region), getBoxGatewayAgentCoreTargetSpec(region)].map( - ({ passthrough }) => passthrough?.endpoint, - ); + const endpoints = (region: string) => [ + getBoxGatewayBedrockTargetSpec(region).passthrough?.endpoint, + `https://${agentCoreDataPlaneHost(region)}`, + ]; expect(endpoints("cn-north-1")).toEqual([ "https://bedrock-runtime.cn-north-1.amazonaws.com.cn", diff --git a/src/handlers/project/shortcuts.ts b/src/handlers/project/shortcuts.ts index ff123b337..820fa934a 100644 --- a/src/handlers/project/shortcuts.ts +++ b/src/handlers/project/shortcuts.ts @@ -31,8 +31,8 @@ export function getDefaultMemorySpec(runtimeName: string): Memory { /** * The Bedrock region of the box profile `agentcore create` writes when the caller passes no * region. Both create paths pass the region they resolved. Build and deploy write the Box - * gateway's `bedrock` and `agentcore` targets, and the AgentCore Runtime profile, for the region - * they build for instead (`--region`, else `resolveRegion`). + * gateway's `bedrock` target, and the AgentCore Runtime profile, for the region they build for + * instead (`--region`, else `resolveRegion`). */ export const DEFAULT_EGRESS_BEDROCK_REGION = "us-west-2"; @@ -57,31 +57,13 @@ export function getBoxGatewayBedrockTargetSpec( } /** - * The name of the Box gateway's AgentCore target, which build and deploy add - * for a boxed agent's default Memory; also the name of the box route to it. + * The AgentCore data-plane host of `region`. A boxed agent's Memory calls go to it directly, signed + * with the execution role, and not through the Box gateway. */ -export const BOX_GATEWAY_AGENTCORE_TARGET_NAME = "agentcore"; - -/** The AgentCore data-plane host of `region`, which the Box gateway's AgentCore target fronts. */ -export function boxGatewayAgentCoreHost(region: string = DEFAULT_EGRESS_BEDROCK_REGION): string { +export function agentCoreDataPlaneHost(region: string = DEFAULT_EGRESS_BEDROCK_REGION): string { return `bedrock-agentcore.${region}.${partition(region).dnsSuffix}`; } -/** - * The Box gateway's passthrough target for the AgentCore data plane (Memory), - * signed with the gateway's role. - */ -export function getBoxGatewayAgentCoreTargetSpec( - region: string = DEFAULT_EGRESS_BEDROCK_REGION, -): AgentCoreGatewayTarget { - return { - name: BOX_GATEWAY_AGENTCORE_TARGET_NAME, - targetType: "passthrough", - passthrough: { endpoint: `https://${boxGatewayAgentCoreHost(region)}`, protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region }, - }; -} - /** * Whether the scaffolded agent calls Bedrock for its model: the Bedrock * provider, or LiteLLM with a `bedrock/` model id (its default). diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index 8a21ccf07..b2e67dba4 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it, test } from "bun:test"; -import { - getBoxGatewayAgentCoreTargetSpec, - getBoxGatewayBedrockTargetSpec, -} from "../handlers/project/shortcuts"; +import { getBoxGatewayBedrockTargetSpec } from "../handlers/project/shortcuts"; import { boxGatewaySpec, ProjectSpecSchema, ProjectNameSchema } from "./project"; const minimalProject = { name: "project", version: 2 }; @@ -764,7 +761,7 @@ describe("Box project gateways", () => { }; const box = { ...boxGatewaySpec("agent"), - targets: [getBoxGatewayBedrockTargetSpec(), getBoxGatewayAgentCoreTargetSpec(), egress], + targets: [getBoxGatewayBedrockTargetSpec(), egress], }; expect(messages(parse(["agent"], [box]))).toEqual([]); });