Skip to content
35 changes: 35 additions & 0 deletions src/core/project/boxMemory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ 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,
Expand All @@ -12,6 +13,7 @@ import type { AgentCoreGateway, AgentCoreGatewayTarget } from "../../projectSche
import { isBoundGateway, type ProjectSpec } from "../../projectSchemas/project";
import { defaultMemoryName } from "../../projectSchemas/memory";
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. */
Expand Down Expand Up @@ -179,6 +181,39 @@ function refuseTargetNameOutsideBoxGateways(spec: ProjectSpec, name: string, cal
}
}

/** 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,
];

/**
* 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.
*/
export function reservedBoxTargetNameProblem(
spec: ProjectSpec,
gateway: AgentCoreGateway,
name: string,
): string | undefined {
const boxed = boxedRuntimes(spec).some((runtime) => runtime.name === gateway.boundRuntime);
if (!isBoundGateway(gateway) || !boxed) return undefined;
if (!BOX_DEFAULT_TARGET_NAMES.includes(name) && !name.startsWith(BOX_EGRESS_TARGET_PREFIX)) {
Comment thread
vvargu marked this conversation as resolved.
Resolved
return undefined;
}
const reserved = [
...BOX_DEFAULT_TARGET_NAMES.map((n) => `'${n}'`),
`'${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.`
);
}

/**
* Lists `policyFile` in `gateway`'s `additionalPolicies`, unless the gateway imports its role
* (`executionRoleArn`), which is the user's to grant; the L3 warns about it at synth.
Expand Down
8 changes: 8 additions & 0 deletions src/core/project/manager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
validateHarnessTemplateSource,
} from "./templates/harness";
import { boxGatewayIamWarnings, type BoxNetwork } from "./boxNetwork";
import { reservedBoxTargetNameProblem } from "./boxMemory";
import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource";
import { DEFAULT_REGION, regionFromConfigFile } from "../region";
import { BoxCliProfileResolver, type BoxProfileResolver } from "./boxProfileResolver";
Expand Down Expand Up @@ -671,6 +672,13 @@ export class FsProjectManager implements ProjectManager {
`a gateway target with name '${input.resourceConfig.name}' already exists in gateway '${gateway.name}'`,
);
}
// Build owns some target names on the Box gateway of a boxed runtime.
const parent = projectSpec.agentCoreGateways.find(
(candidate) => candidate.name === input.gatewayName,
);
const reserved =
Comment thread
vvargu marked this conversation as resolved.
Resolved
parent && reservedBoxTargetNameProblem(projectSpec, parent, input.resourceConfig.name);
if (reserved) throw new InputValidationError(reserved);
} else if (input.resourceType === "policy") {
// Policy names are account-unique on the service, so the check spans engines.
const engine = projectSpec.policyEngines.find((candidate) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { AppIO } from "../../../../io";
import { createGatewayProjectTestHarness } from "../gateway-test-support";
import { authChoices, toGatewayTargetInput } from "./screen";
import { boxGatewaySpec } from "../../../../projectSchemas/project";
import { BOX_RELEASE } from "../../../../core/project/backends/boxRelease";

const ENDPOINT = "https://mcp.example.com";
const OAUTH_CREDENTIAL = {
Expand Down Expand Up @@ -461,6 +462,30 @@ describe("project add gateway-target wizard", () => {
screen.unmount();
}, 15000);

test("refuses a target name build owns on the Box gateway", async () => {
const projectRoot = await inProject();
const spec = await projectSpec(projectRoot);
const box = boxGatewaySpec(spec.runtimes[0].name);
await writeProjectSpec(projectRoot, {
...spec,
projectType: "box",
runtimes: [{ ...spec.runtimes[0], box: { version: BOX_RELEASE.version } }],
agentCoreGateways: [box],
});
const screen = renderScreen("/agentcore/add/gateway-target");
await reachAuthStep(screen, "bedrock");
await screen.press("return");
await waitForText(screen.lastFrame, "this Target will be added to agentcore.json");
await screen.press("return");

await waitForFlatText(
screen.lastFrame,
`the gateway target name 'bedrock' is reserved on Box gateway '${box.name}'`,
);
expect(await targetsOf(projectRoot, box.name)).toEqual([]);
screen.unmount();
}, 15000);

test("esc on the first step returns to the add menu", async () => {
await inProject();
await addGateway();
Expand Down
72 changes: 72 additions & 0 deletions src/handlers/project/add/gateway-target/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from "node:path";
import { InputValidationError, ProjectStateError, ResourceNotFoundError } from "../../../../errors";
import { expectError } from "../../../../testing";
import { createGatewayProjectTestHarness } from "../gateway-test-support";
import { BOX_RELEASE } from "../../../../core/project/backends/boxRelease";
import { boxGatewaySpec } from "../../../../projectSchemas/project";

const DISCOVERY_URL = "https://idp.example.com/.well-known/openid-configuration";
Expand Down Expand Up @@ -75,6 +76,77 @@ describe("project add gateway-target", () => {
expect(JSON.parse(asJson.stdout()).notes).toEqual([note]);
});

/** A Box project with its Box gateway and the `tools` gateway; `boxed` gives the runtime a box. */
async function boxProject(boxed: boolean) {
const projectRoot = await inProject();
const spec = await projectSpec(projectRoot);
const runtime = spec.runtimes[0];
const box = boxGatewaySpec(runtime.name);
await writeProjectSpec(projectRoot, {
...spec,
projectType: "box",
runtimes: [boxed ? { ...runtime, box: { version: BOX_RELEASE.version } } : runtime],
agentCoreGateways: [box],
});
await addGateway();
return { projectRoot, box };
}

async function targetNames(projectRoot: string, gateway: string): Promise<string[]> {
return (await projectSpec(projectRoot)).agentCoreGateways
.find((candidate: { name: string }) => candidate.name === gateway)
.targets.map((target: { name: string }) => target.name);
}

const BUILD_OWNED_NAMES = ["bedrock", "agentcore", "egress-api-example-com"];

test.each(BUILD_OWNED_NAMES)(
"refuses the build-owned name %s on a Box gateway, and only there",
async (name) => {
const { projectRoot, box } = await boxProject(true);

await expectError(
run([
"add",
"gateway-target",
...["--gateway", box.name, "--name", name, "--endpoint", ENDPOINT],
...["--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.`,
InputValidationError,
);
// The same name is the user's on a gateway that is not a Box gateway.
Comment thread
vvargu marked this conversation as resolved.
Resolved
Comment thread
vvargu marked this conversation as resolved.
Resolved
await run([
"add",
"gateway-target",
...["--gateway", "tools", "--name", name, "--endpoint", ENDPOINT],
...["--outbound-auth", "none"],
]);

expect(await targetNames(projectRoot, box.name)).toEqual([]);
expect(await targetNames(projectRoot, "tools")).toEqual([name]);
},
);

test.each(BUILD_OWNED_NAMES)(
"accepts the name %s on a bound gateway whose runtime does not run in a box",
async (name) => {
// A Box project runtime with no box.version: build writes no targets on its gateway.
const { projectRoot, box } = await boxProject(false);

await run([
"add",
"gateway-target",
...["--gateway", box.name, "--name", name, "--endpoint", ENDPOINT],
...["--outbound-auth", "none"],
]);

expect(await targetNames(projectRoot, box.name)).toEqual([name]);
},
);

test("adds endpoint and project Runtime shortcuts", async () => {
const projectRoot = await inProject();
await addGateway();
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/project/add/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function defaultGatewayChoice(

/** " · bound to runtime 'x'" for a gateway bound to one runtime, for a wizard's choice text. */
export function boundRuntimeNote(gateway: { boundRuntime?: string }): string {
return gateway.boundRuntime === undefined ? "" : ` · bound to runtime '${gateway.boundRuntime}'`;
return isBoundGateway(gateway) ? ` · bound to runtime '${gateway.boundRuntime}'` : "";
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/project/remove/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { JsonKey } from "../../keys";
import { renderResult } from "../../utils";
import type { ProjectManager, RemoveResourceInput } from "../types";
import { projectMutationResource, projectReference, type ProjectMutationResult } from "../output";
import { APP_CODE_RETAINED_NOTICE, removedGatewayLines, shouldShowAppCodeNotice } from "./notice";
import { APP_CODE_RETAINED_NOTICE, boundGatewayLines, shouldShowAppCodeNotice } from "./notice";

type RemoveProjectResourceConfig = {
projectManager: ProjectManager;
Expand Down Expand Up @@ -169,7 +169,7 @@ export const createRemoveProjectHandler = (config: RemoveProjectResourceConfig)
},
() => {
config.io.stderr.write(`removed ${resource} with name '${name}' from project\n`);
for (const line of removedGatewayLines(name, result.removedGateways)) {
for (const line of boundGatewayLines(name, result.removedGateways)) {
config.io.stderr.write(`${line}\n`);
}
if (showAppCodeNotice) {
Expand Down
35 changes: 35 additions & 0 deletions src/handlers/project/remove/notice.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, test } from "bun:test";
import { boundGatewayLines } from "./notice";

describe("boundGatewayLines", () => {
test("names each gateway bound to the runtime and its targets before the removal", () => {
const target = (name: string) => ({ name });
const gateways = [
{ name: "none", boundRuntime: "agent", targets: [] },
{ name: "one", boundRuntime: "agent", targets: [target("search")] },
{ name: "two", boundRuntime: "agent", targets: [target("search"), target("docs")] },
{ name: "other", boundRuntime: "checkout", targets: [target("search")] },
{ name: "tools", targets: [target("search")] },
];

expect(boundGatewayLines("agent", gateways)).toEqual([
"gateway 'none'",
"gateway 'one' and its target 'search'",
"gateway 'two' and its targets 'search', 'docs'",
]);
});

test("names each removed gateway and its target count after the removal", () => {
const removed = [
{ name: "none", targetCount: 0 },
{ name: "one", targetCount: 1 },
{ name: "three", targetCount: 3 },
];

expect(boundGatewayLines("agent", removed)).toEqual([
"removed gateway 'none': it is bound to runtime 'agent'",
"removed gateway 'one' and its 1 target: it is bound to runtime 'agent'",
"removed gateway 'three' and its 3 targets: it is bound to runtime 'agent'",
]);
});
});
60 changes: 31 additions & 29 deletions src/handlers/project/remove/notice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,40 @@ export function shouldShowAppCodeNotice(resourceType: ProjectMutationResourceTyp
return resourceType === "runtime" || resourceType === "harness" || resourceType === "evaluator";
}

/** One line for each gateway removed with runtime `runtimeName`, with its target count. */
export function removedGatewayLines(runtimeName: string, gateways: RemovedGateway[]): string[] {
return gateways.map(({ name, targetCount }) => {
const targets =
targetCount === 0
? ""
: ` and its ${targetCount === 1 ? "1 target" : `${targetCount} targets`}`;
return `removed gateway '${name}'${targets}: it is bound to runtime '${runtimeName}'`;
});
}
/** A gateway of the project, as `remove runtime` reads it before the removal. */
type ProjectGateway = {
name: string;
boundRuntime?: string;
targets: readonly { name: string }[];
};

/**
* One line for each gateway that `remove runtime` would remove with runtime `runtimeName`, with
* the names of its targets. The TUI shows it before the removal: a Box gateway can hold targets
* the user added, such as MCP servers, and they go with the runtime.
* One line for each gateway that `remove runtime` removes with runtime `runtimeName`. Give the
* project's gateways before the removal: the lines name each gateway bound to the runtime and the
* names of its targets, because a Box gateway can hold targets the user added, such as MCP
* servers, and the TUI shows them before they go. Give the removed gateways after the removal:
* the lines name each gateway and its target count.
*/
export function boundGatewayWarningLines(
export function boundGatewayLines(
runtimeName: string,
gateways: readonly {
name: string;
boundRuntime?: string;
targets: readonly { name: string }[];
}[],
gateways: readonly (ProjectGateway | RemovedGateway)[],
): string[] {
return gateways
.filter((gateway) => gateway.boundRuntime === runtimeName)
.map(({ name, targets }) => {
const names = targets.map((target) => `'${target.name}'`).join(", ");
const what =
targets.length === 0
? ""
: ` and its ${targets.length === 1 ? "target" : "targets"} ${names}`;
return `gateway '${name}'${what}`;
});
return gateways.flatMap((gateway) => {
if ("targetCount" in gateway) {
const targets = targetsPhrase(gateway.targetCount);
return [
`removed gateway '${gateway.name}'${targets}: it is bound to runtime '${runtimeName}'`,
];
}
if (gateway.boundRuntime !== runtimeName) return [];
const names = gateway.targets.map((target) => `'${target.name}'`);
return [`gateway '${gateway.name}'${targetsPhrase(names.length, names)}`];
});
}

/** " and its 2 targets", or with `names` " and its targets 'a', 'b'"; empty for no target. */
function targetsPhrase(count: number, names?: readonly string[]): string {
if (count === 0) return "";
const noun = count === 1 ? "target" : "targets";
return names ? ` and its ${noun} ${names.join(", ")}` : ` and its ${count} ${noun}`;
}
11 changes: 3 additions & 8 deletions src/handlers/project/remove/screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@ import { isBoundGateway, type ProjectSpec } from "../../../projectSchemas/projec
import type { Project, RemoveResourceInput } from "../types";
import type { ScreenProps } from "../../types";
import { ProjectGate, projectQueryKey } from "../ProjectGate";
import {
APP_CODE_RETAINED_NOTICE,
boundGatewayWarningLines,
removedGatewayLines,
shouldShowAppCodeNotice,
} from "./notice";
import { APP_CODE_RETAINED_NOTICE, boundGatewayLines, shouldShowAppCodeNotice } from "./notice";

type RootResourceType =
| "runtime"
Expand Down Expand Up @@ -337,7 +332,7 @@ function RemoveConfirm({
// A runtime takes its bound gateways (each Box gateway is) and their targets with it.
const alsoRemoves =
resource.resourceType === "runtime"
? boundGatewayWarningLines(resource.name, project.spec.agentCoreGateways)
? boundGatewayLines(resource.name, project.spec.agentCoreGateways)
: [];
const rows: SummaryRows = {
type: config.resourceType,
Expand All @@ -360,7 +355,7 @@ function RemoveConfirm({
action={async () => {
const result = await core.projectManager.removeResource(project, resource);
removedProject.current = result.project;
const gatewayLines = removedGatewayLines(resource.name, result.removedGateways);
const gatewayLines = boundGatewayLines(resource.name, result.removedGateways);
return {
rows: {
removed: `${config.resourceType} '${resource.name}'`,
Expand Down
17 changes: 17 additions & 0 deletions src/projectSchemas/project.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { describe, expect, it, test } from "bun:test";
import {
getBoxGatewayAgentCoreTargetSpec,
getBoxGatewayBedrockTargetSpec,
} from "../handlers/project/shortcuts";
import { boxGatewaySpec, ProjectSpecSchema, ProjectNameSchema } from "./project";

const minimalProject = { name: "project", version: 2 };
Expand Down Expand Up @@ -588,6 +592,19 @@ describe("Box project gateways", () => {
expect(parse(["agent"], [{ ...boxGatewaySpec("agent"), name: "renamed" }]).success).toBe(true);
});

test("accepts the targets build writes on a Box gateway", () => {
const egress = {
name: "egress-api-example-com",
targetType: "passthrough",
passthrough: { endpoint: "https://api.example.com", protocolType: "CUSTOM" },
};
const box = {
...boxGatewaySpec("agent"),
targets: [getBoxGatewayBedrockTargetSpec(), getBoxGatewayAgentCoreTargetSpec(), egress],
};
expect(messages(parse(["agent"], [box]))).toEqual([]);
});

test("does not ask for Box gateways in a project without projectType", () => {
const result = ProjectSpecSchema.safeParse({ ...minimalProject, runtimes: [runtime] });
expect(result.success).toBe(true);
Expand Down
Loading