diff --git a/src/core/dev/box.test.ts b/src/core/dev/box.test.ts index 775a581202..d6432a53ff 100644 --- a/src/core/dev/box.test.ts +++ b/src/core/dev/box.test.ts @@ -32,14 +32,15 @@ async function temp(prefix: string): Promise { return directory; } -/** A project named `Demo` that holds its box profile in .box/profile.toml when `profiled`. */ +/** A project named `Demo` that holds the agent's box profile in .box/agent/local when `profiled`. */ async function scene(profiled: boolean, boxOnPath = true) { const projectRoot = await temp("agentcore-box-project-"); await mkdir(join(projectRoot, "agentcore")); await writeFile(join(projectRoot, "agentcore", "agentcore.json"), '{"name":"Demo"}'); if (profiled) { - await mkdir(join(projectRoot, ".box")); - await writeFile(join(projectRoot, ".box", "profile.toml"), PROFILE); + const local = join(projectRoot, ".box", "agent", "local"); + await mkdir(local, { recursive: true }); + await writeFile(join(local, "profile.toml"), PROFILE); await mkdir(join(projectRoot, "app", "agent", ".venv"), { recursive: true }); } @@ -127,13 +128,16 @@ describe("BoxDevRunner", () => { const events = await collect(runner.run(input(projectRoot))); expect(calls.map(({ command }) => command)).toEqual([ - ["box", "run", ".box/profile.toml", "--no-banner"], + ["box", "run", ".box/agent/local/profile.toml", "--no-banner"], ]); expect(calls[0]!.options.cwd).toBe(projectRoot); expect(fallbackRuns).toEqual([]); expect(events).toEqual([ TRACES_NOTICE, - { type: "status", message: "Starting the agent in a box (box run .box/profile.toml)" }, + { + type: "status", + message: "Starting the agent in a box (box run .box/agent/local/profile.toml)", + }, { type: "stdout", line: "Uvicorn running" }, ]); }); @@ -255,7 +259,7 @@ describe("BoxDevRunner", () => { expect(events).not.toContainEqual(TRACES_NOTICE); }); - test("runs another runtime the usual way, since the profile is the first runtime's", async () => { + test("runs a runtime the usual way when it has no box profile of its own", async () => { const { projectRoot, calls, fallbackRuns, runner } = await scene(true); const second = input(projectRoot); // The second runtime was added without a box template, so it has no box.version. @@ -266,13 +270,7 @@ describe("BoxDevRunner", () => { expect(calls).toEqual([]); expect(fallbackRuns).toHaveLength(1); - expect(events).toEqual([ - { - type: "status", - message: 'Running without a box: runtime "second" has no box.version in agentcore.json', - }, - { type: "stdout", line: "fallback" }, - ]); + expect(events).toEqual([{ type: "stdout", line: "fallback" }]); }); test("tells the user to run uv sync when the runtime has no .venv", async () => { diff --git a/src/core/dev/box.ts b/src/core/dev/box.ts index 8c60becc85..1bfbf4effe 100644 --- a/src/core/dev/box.ts +++ b/src/core/dev/box.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from "node:fs"; +import { existsSync } from "node:fs"; import { join } from "node:path"; import { InputValidationError, ProjectStateError, ResourceNotFoundError } from "../../errors"; import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types"; @@ -6,10 +6,9 @@ import { streamProcess, type ProcessStreamer } from "../../io"; import { requireTool } from "../../io/exec"; import { BOX_INSTALL_HINT } from "../project/backends/boxRelease"; import { - BOX_PROFILE_FILE, boxIngressPort, - boxProfileIsFor, - boxProfilePath, + boxLocalProfileFile, + boxLocalProfilePath, runsInBox, } from "../project/templates/boxProfile"; @@ -22,7 +21,7 @@ type BoxDevRunnerConfig = { }; /** - * Runs a CodeZip agent with `box run .box/profile.toml` in the project folder + * Runs a CodeZip agent with `box run .box//local/profile.toml` in the project folder * when the project has that box profile, the one `agentcore create` writes, * and with the fallback runner otherwise. `box` is the one on PATH, which the * user installs from the box release. The box listens on the profile's @@ -40,7 +39,8 @@ export class BoxDevRunner implements DevRunner { } public async *run(input: DevServerInput): AsyncGenerator { - const profile = boxProfilePath(input.projectRoot); + const profileFile = boxLocalProfileFile(input.runtime.name); + const profile = boxLocalProfilePath(input.projectRoot, input.runtime.name); // As build and deploy, dev decides whether a runtime is boxed from runsInBox alone. if (!runsInBox(input.boxProject, input.runtime)) { if (input.runtime.box !== undefined) { @@ -58,13 +58,11 @@ export class BoxDevRunner implements DevRunner { yield* this.fallback.run(input); return; } - const hasProfile = existsSync(profile); - if (!hasProfile || !boxProfileIsFor(readFileSync(profile, "utf8"), input.runtime)) { + if (!existsSync(profile)) { throw new ResourceNotFoundError( `runtime "${input.runtime.name}" runs its agent in a box (it has box.version in ` + - `agentcore.json), but ${profile} ` + - (hasProfile ? "is the box profile of another runtime." : "does not exist.") + - " Restore the profile that `agentcore create` wrote.", + `agentcore.json), but ${profile} does not exist. ` + + "Restore the profile that `agentcore create` or `agentcore add runtime` wrote.", ); } const listen = boxIngressPort(input.runtime.protocol); @@ -86,9 +84,9 @@ export class BoxDevRunner implements DevRunner { } yield { type: "status", - message: `Starting the agent in a box (box run ${BOX_PROFILE_FILE})`, + message: `Starting the agent in a box (box run ${profileFile})`, }; - yield* this.streamProcess(["box", "run", BOX_PROFILE_FILE, "--no-banner"], { + yield* this.streamProcess(["box", "run", profileFile, "--no-banner"], { cwd: input.projectRoot, env: { ...process.env, ...credentialEnvironment(input.env) }, signal: input.signal, diff --git a/src/core/dev/boxEnvLocal.test.ts b/src/core/dev/boxEnvLocal.test.ts index 13c9890d7e..d7edcf5a13 100644 --- a/src/core/dev/boxEnvLocal.test.ts +++ b/src/core/dev/boxEnvLocal.test.ts @@ -9,6 +9,8 @@ import { writeBoxDevEnvLocal } from "./boxEnvLocal"; const GITHUB_ROUTE = '[egress.github]\ndestinations = ["api.github.com"]\nsecret.ref = "env://GITHUB_TOKEN"\n'; +const AGENT = "agent"; + const roots: string[] = []; afterEach(async () => { @@ -20,8 +22,9 @@ async function project(profile?: string): Promise { roots.push(root); await mkdir(join(root, "agentcore")); if (profile !== undefined) { - await mkdir(join(root, ".box")); - await writeFile(join(root, ".box", "profile.toml"), profile); + const local = join(root, ".box", AGENT, "local"); + await mkdir(local, { recursive: true }); + await writeFile(join(local, "profile.toml"), profile); } return root; } @@ -32,7 +35,7 @@ describe("writeBoxDevEnvLocal", () => { test("writes an env:// route's variable under its own name", async () => { const root = await project(GITHUB_ROUTE); - const messages = await writeBoxDevEnvLocal(root, { GITHUB_TOKEN: "ghp_1" }); + const messages = await writeBoxDevEnvLocal(root, AGENT, { GITHUB_TOKEN: "ghp_1" }); expect(await envLocal(root)).toEqual({ GITHUB_TOKEN: "ghp_1" }); expect(messages).toEqual([ @@ -46,15 +49,15 @@ describe("writeBoxDevEnvLocal", () => { { key: "GITHUB_TOKEN", value: "ghp_old", comment: "mine" }, ]); - expect(await writeBoxDevEnvLocal(root, { GITHUB_TOKEN: "ghp_new" })).toEqual([]); + expect(await writeBoxDevEnvLocal(root, AGENT, { GITHUB_TOKEN: "ghp_new" })).toEqual([]); expect(await envLocal(root)).toEqual({ GITHUB_TOKEN: "ghp_old" }); }); test("writes nothing for a variable that is unset or blank", async () => { const root = await project(GITHUB_ROUTE); - expect(await writeBoxDevEnvLocal(root, {})).toEqual([]); - expect(await writeBoxDevEnvLocal(root, { GITHUB_TOKEN: " " })).toEqual([]); + expect(await writeBoxDevEnvLocal(root, AGENT, {})).toEqual([]); + expect(await writeBoxDevEnvLocal(root, AGENT, { GITHUB_TOKEN: " " })).toEqual([]); expect(existsSync(new EnvLocalFile(root).path)).toBe(false); }); @@ -64,7 +67,7 @@ describe("writeBoxDevEnvLocal", () => { { key: "AGENTCORE_CREDENTIAL_GITHUB", value: "ghp_1", comment: "deploy" }, ]); - expect(await writeBoxDevEnvLocal(root, {})).toEqual([]); + expect(await writeBoxDevEnvLocal(root, AGENT, {})).toEqual([]); expect(await envLocal(root)).toEqual({ AGENTCORE_CREDENTIAL_GITHUB: "ghp_1" }); }); @@ -74,7 +77,7 @@ describe("writeBoxDevEnvLocal", () => { ); expect( - await writeBoxDevEnvLocal(root, { AWS_BEARER_TOKEN_BEDROCK: "token", default: "x" }), + await writeBoxDevEnvLocal(root, AGENT, { AWS_BEARER_TOKEN_BEDROCK: "token", default: "x" }), ).toEqual([]); expect(existsSync(new EnvLocalFile(root).path)).toBe(false); }); @@ -82,7 +85,7 @@ describe("writeBoxDevEnvLocal", () => { test("does nothing without a box profile", async () => { const root = await project(); - expect(await writeBoxDevEnvLocal(root, { GITHUB_TOKEN: "ghp_1" })).toEqual([]); + expect(await writeBoxDevEnvLocal(root, AGENT, { GITHUB_TOKEN: "ghp_1" })).toEqual([]); expect(existsSync(new EnvLocalFile(root).path)).toBe(false); }); }); diff --git a/src/core/dev/boxEnvLocal.ts b/src/core/dev/boxEnvLocal.ts index 5264080774..54f0307463 100644 --- a/src/core/dev/boxEnvLocal.ts +++ b/src/core/dev/boxEnvLocal.ts @@ -4,7 +4,7 @@ import { EnvLocalFile, ENV_LOCAL_RELATIVE_PATH } from "../project/envLocal"; /** * Writes into `agentcore/.env.local`, under its own name, each variable that a - * `[egress.] secret.ref = "env://"` route of the project's box profile + * `[egress.] secret.ref = "env://"` route of the agent's box profile * names and `env` holds, so `box run` finds it under `agentcore dev`, on the host * and in a container alike. A variable `.env.local` holds already keeps its value, * and one that is unset or blank in `env` is left out, so box names it. A profile @@ -13,9 +13,10 @@ import { EnvLocalFile, ENV_LOCAL_RELATIVE_PATH } from "../project/envLocal"; */ export async function writeBoxDevEnvLocal( projectRoot: string, + agentName: string, env: NodeJS.ProcessEnv = process.env, ): Promise { - const routes = readBoxEnvRoutes(projectRoot)?.routes ?? []; + const routes = readBoxEnvRoutes(projectRoot, agentName)?.routes ?? []; const entries: (EnvLocalEntry & { route: string })[] = []; for (const { route, variable: key } of routes) { diff --git a/src/core/dev/container.test.ts b/src/core/dev/container.test.ts index dc7a70a9b0..e00e5dd2a9 100644 --- a/src/core/dev/container.test.ts +++ b/src/core/dev/container.test.ts @@ -809,7 +809,7 @@ describe("ContainerDevRunner", () => { async function boxedScene( options: { profile?: boolean; - /** The text of `.box/profile.toml`. */ + /** The text of `.box/Hello_World/local/profile.toml`. */ profileText?: string; dockerfile?: string; /** Whether the runtime has box.version, which create writes only for a box template. */ @@ -823,11 +823,9 @@ describe("ContainerDevRunner", () => { await mkdir(join(root, "agentcore")); await writeFile(join(root, "agentcore", "agentcore.json"), '{"name":"Demo"}'); if (options.profile ?? true) { - await mkdir(join(root, ".box")); - await writeFile( - join(root, ".box", "profile.toml"), - options.profileText ?? "# local profile\n", - ); + const local = join(root, ".box", projectRuntime.name, "local"); + await mkdir(local, { recursive: true }); + await writeFile(join(local, "profile.toml"), options.profileText ?? "# local profile\n"); } return { projectRuntime, root, context }; } @@ -862,21 +860,6 @@ describe("ContainerDevRunner", () => { expect(commandCall(calls, "run").command).not.toContain("--cap-add"); }); - test("refuses a box profile written for a CodeZip runtime", async () => { - const { projectRuntime, root } = await boxedScene(); - await writeFile( - join(root, ".box", "profile.toml"), - 'read = ["${{ workspace }}/app/other"]\n', - ); - const { calls, runner } = harness({ processEnv: credentials }); - - const run = collect(runner.run(input(root, projectRuntime))); - - await expect(run).rejects.toBeInstanceOf(InputValidationError); - await expect(run).rejects.toThrow("is the box profile of another runtime"); - expect(calls.filter(({ command }) => command[1] === "build")).toEqual([]); - }); - test("stages the local profile in .box-dist/, and lets box's sandbox run", async () => { const { projectRuntime, root, context } = await boxedScene(); const { calls, runner } = harness({ processEnv: credentials }); @@ -1023,9 +1006,10 @@ describe("ContainerDevRunner", () => { const { projectRuntime, root, context } = await boxedScene({ profileText: 'policies = ["policy.dw", "rules/extra.dw"]\n', }); - await mkdir(join(root, ".box", "rules")); - await writeFile(join(root, ".box", "policy.dw"), "// rules\n"); - await writeFile(join(root, ".box", "rules", "extra.dw"), "// extra\n"); + const local = join(root, ".box", projectRuntime.name, "local"); + await mkdir(join(local, "rules")); + await writeFile(join(local, "policy.dw"), "// rules\n"); + await writeFile(join(local, "rules", "extra.dw"), "// extra\n"); const { runner } = harness({ processEnv: credentials }); await collect(runner.run(input(root, projectRuntime))); @@ -1040,20 +1024,21 @@ describe("ContainerDevRunner", () => { [ "a TOML error", 'policies = ["policy.dw"]\n[agent\n', - ".box/profile.toml:2:7 This is not valid TOML (illegal character in key). Correct the " + - "syntax.", + ".box/Hello_World/local/profile.toml:2:7 This is not valid TOML (illegal character in " + + "key). Correct the syntax.", ], [ "the `policy` key", '# one file\npolicy = "policy.dw"\n', - ".box/profile.toml:2:1 Box does not take the key `policy`. List your policy files under " + - '`policies` instead, such as policies = ["policy.dw"].', + ".box/Hello_World/local/profile.toml:2:1 Box does not take the key `policy`. List your " + + 'policy files under `policies` instead, such as policies = ["policy.dw"].', ], [ - "a policy file outside .box/", + "a policy file outside .box/Hello_World/local/", 'policies = ["../../elsewhere.dw"]\n', - '.box/profile.toml:1:1 `policies` names "../../elsewhere.dw", which is outside .box/. ' + - "Move the file into .box/, and name it from there.", + '.box/Hello_World/local/profile.toml:1:1 `policies` names "../../elsewhere.dw", which is ' + + "outside .box/Hello_World/local/. Move the file into .box/Hello_World/local/, and name it " + + "from there.", ], ])("stops, and stages nothing, for a profile with %s", async (_, profileText, line) => { const { projectRuntime, root, context } = await boxedScene({ profileText }); diff --git a/src/core/dev/container.ts b/src/core/dev/container.ts index 96d8d86833..0182becf90 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -27,7 +27,7 @@ import { } from "../project/backends/boxContainer"; import { boxReleaseFor, type BoxRelease } from "../project/backends/boxRelease"; import { boxPolicyFileCopies } from "../project/boxNetworkSource"; -import { boxProfileIsFor, boxProfilePath, runsInBox } from "../project/templates/boxProfile"; +import { boxLocalProfilePath, runsInBox } from "../project/templates/boxProfile"; import { BOX_DEV_AWS_REFRESH_MS, resolveDefaultAwsCredentials, @@ -329,7 +329,7 @@ export class ContainerDevRunner implements DevRunner { /** * Stages box into the build context for a runtime that runs in a box (`runsInBox`), with the - * project's box profile and the policy files it names, and returns the folder it staged, or + * runtime's local box profile and the policy files it names, and returns the folder it staged, or * undefined for a runtime outside a box. A Dockerfile that takes the folder as `BOX_DIST` gets `.box-dev/`, so dev * leaves build and deploy's `.box-dist/` alone; an older one gets `.box-dist/`. The image then * runs `box run`, which needs BOX_RUN_FLAGS. @@ -343,29 +343,22 @@ export class ContainerDevRunner implements DevRunner { } return undefined; } - const profile = boxProfilePath(input.projectRoot); + const profile = boxLocalProfilePath(input.projectRoot, input.runtime.name); if (!existsSync(profile)) { throw new ResourceNotFoundError( `runtime "${input.runtime.name}" runs its agent in a box (it has box.version in agentcore.json), ` + `but its box profile ${profile} does not exist. Restore the profile that ` + - "`agentcore create` wrote.", + "`agentcore create` or `agentcore add runtime` wrote.", ); } const profileText = readFileSync(profile, "utf8"); - if (!boxProfileIsFor(profileText, input.runtime)) { - throw new InputValidationError( - `runtime "${input.runtime.name}" runs its agent in a box (it has box.version in agentcore.json), ` + - `but ${profile} is the box profile of another runtime. Write a box profile for this ` + - "runtime there.", - ); - } const folder = imageTakesBoxDistArg(input.projectRoot, input.runtime) ? BOX_DEV_DIST : BOX_IMAGE_DIST; await stageBoxImage( context, profileText, - boxPolicyFileCopies(input.projectRoot), + boxPolicyFileCopies(input.projectRoot, input.runtime.name), await this.releaseFor(input.runtime.box?.version), folder, ); diff --git a/src/core/project/__fixtures__/box-network-build-stopped.golden.txt b/src/core/project/__fixtures__/box-network-build-stopped.golden.txt index 6691ee66e9..0342f6681e 100644 --- a/src/core/project/__fixtures__/box-network-build-stopped.golden.txt +++ b/src/core/project/__fixtures__/box-network-build-stopped.golden.txt @@ -1,11 +1,11 @@ Build stopped: 10 problems in the Box profile and agentcore.json. Build wrote nothing from the Box profile. -.box/policy.dw:2:1 The rule "wild" allows each host that matches "*.example.com", and each gateway target needs one fixed host. Name each host in the rule, for example context.input.host == "api.example.com". -.box/policy.dw:4:1 The rule "dup" has the same @id as the rule at .box/policy.dw:3:1. Give each rule its own @id. -.box/policy.dw:6:1 The rule "route_github_connect" is one Box adds itself for [egress.github]. Remove it from .box/policy.dw. -.box/policy.dw:7:1 This rule allows requests to every host, and each gateway target needs one fixed host. Add a condition that names each host, for example context.input.host == "api.example.com". -.box/profile.toml:4:1 The rule "pack_mirrors", which a pack in `packs` adds, allows each host that matches "*.mirror.example.com", and each gateway target needs one fixed host. Name each host in the rule, for example context.input.host == "api.example.com". -.box/profile.toml:4:1 [egress.legacy], which a pack in `packs` adds, reads its secret from credsd://prod, and the gateway cannot read credsd. Use an env:// secret, which build stores as an API key credential. -.box/profile.toml:47:1 [egress.signed] signs requests to api.example.com with aws://default, and the gateway signs only for Bedrock, AgentCore, and Lambda function URL hosts. Use an env:// secret for this host, or remove the secret. -.box/profile.toml:51:1 [egress.wide] has the wildcard destination "*.wide.example.com", and each gateway target needs one fixed host. Name each host in `destinations`. -.box/profile.toml:55:1 [mcp.docs] has the destination "docs.example.com/mcp", and the gateway route of an MCP server takes a host with no path. Remove /mcp from the destination. The agent's MCP client keeps the path in its URL. -agentcore/agentcore.json The gateway target 'gh' for api.github.com sends the API key credential 'github' in the header Authorization with the prefix Bearer, and [egress.github] sends no credential. Make the two the same, in agentcore.json or in .box/profile.toml. \ No newline at end of file +.box/agent_python_strands/local/policy.dw:2:1 The rule "wild" allows each host that matches "*.example.com", and each gateway target needs one fixed host. Name each host in the rule, for example context.input.host == "api.example.com". +.box/agent_python_strands/local/policy.dw:4:1 The rule "dup" has the same @id as the rule at .box/agent_python_strands/local/policy.dw:3:1. Give each rule its own @id. +.box/agent_python_strands/local/policy.dw:6:1 The rule "route_github_connect" is one Box adds itself for [egress.github]. Remove it from .box/agent_python_strands/local/policy.dw. +.box/agent_python_strands/local/policy.dw:7:1 This rule allows requests to every host, and each gateway target needs one fixed host. Add a condition that names each host, for example context.input.host == "api.example.com". +.box/agent_python_strands/local/profile.toml:4:1 The rule "pack_mirrors", which a pack in `packs` adds, allows each host that matches "*.mirror.example.com", and each gateway target needs one fixed host. Name each host in the rule, for example context.input.host == "api.example.com". +.box/agent_python_strands/local/profile.toml:4:1 [egress.legacy], which a pack in `packs` adds, reads its secret from credsd://prod, and the gateway cannot read credsd. Use an env:// secret, which build stores as an API key credential. +.box/agent_python_strands/local/profile.toml:47:1 [egress.signed] signs requests to api.example.com with aws://default, and the gateway signs only for Bedrock, AgentCore, and Lambda function URL hosts. Use an env:// secret for this host, or remove the secret. +.box/agent_python_strands/local/profile.toml:51:1 [egress.wide] has the wildcard destination "*.wide.example.com", and each gateway target needs one fixed host. Name each host in `destinations`. +.box/agent_python_strands/local/profile.toml:55:1 [mcp.docs] has the destination "docs.example.com/mcp", and the gateway route of an MCP server takes a host with no path. Remove /mcp from the destination. The agent's MCP client keeps the path in its URL. +agentcore/agentcore.json The gateway target 'gh' for api.github.com sends the API key credential 'github' in the header Authorization with the prefix Bearer, and [egress.github] sends no credential. Make the two the same, in agentcore.json or in .box/agent_python_strands/local/profile.toml. diff --git a/src/core/project/backends/boxCodeZip.test.ts b/src/core/project/backends/boxCodeZip.test.ts index 172172d826..b9c795c5a1 100644 --- a/src/core/project/backends/boxCodeZip.test.ts +++ b/src/core/project/backends/boxCodeZip.test.ts @@ -187,10 +187,11 @@ describe("stageBoxCodeZip", () => { test("copies each policy file of the model, byte for byte, beside the profile that names it", async () => { const build = await linuxBuild(); const demo = await project("start.py"); - await mkdir(join(demo.rootPath, ".box", "rules"), { recursive: true }); + const local = join(demo.rootPath, ".box", "agent", "local"); + await mkdir(join(local, "rules"), { recursive: true }); const bytes = Buffer.from([0x2f, 0x2f, 0x20, 0xe2, 0x9c, 0x93, 0x0d, 0x0a]); - await writeFile(join(demo.rootPath, ".box", "policy.dw"), bytes); - await writeFile(join(demo.rootPath, ".box", "rules", "extra.dw"), "// extra\n"); + await writeFile(join(local, "policy.dw"), bytes); + await writeFile(join(local, "rules", "extra.dw"), "// extra\n"); await stageBoxCodeZip(demo, [model(["policy.dw", "rules/extra.dw"])], async () => build); diff --git a/src/core/project/backends/boxCodeZip.ts b/src/core/project/backends/boxCodeZip.ts index a0dbbc80e3..1669280cd1 100644 --- a/src/core/project/backends/boxCodeZip.ts +++ b/src/core/project/backends/boxCodeZip.ts @@ -2,18 +2,24 @@ import { chmodSync, copyFileSync, cpSync, mkdirSync, rmSync } from "node:fs"; import { join, posix } from "node:path"; import type { Project } from "../../../handlers/project/types"; import type { BoxNetwork } from "../boxNetwork"; -import { boxNetworkEdits, runtimeProfileWriter, writeBoxNetworkFiles } from "../boxNetworkWriters"; +import { + boxNetworkEdits, + runtimeProfileWriter, + writeBoxNetworkFiles, + writeRenderedBoxFiles, +} from "../boxNetworkWriters"; import { BOX_CODEZIP_DIST, runtimeRunsInBox } from "../templates/boxProfile"; import { BOX_BINARIES, type BoxLinuxBuild } from "./boxRelease"; /** * Stages box into each CodeZip runtime that runs in a box ({@link runtimeRunsInBox}), - * so the zip carries it: `/.box-dist/` gets box, its - * helpers, its packs, the libffi shim built for the runtime's Python, and what - * the runtime profile writer writes from the runtime's Box network model: the - * Runtime profile and a byte copy of each policy file it names. The folder is - * rewritten on every build and deploy. `box` is asked for only when a runtime - * needs it. Returns the names of the runtimes it staged. + * so the zip carries it: `/.box-dist/` gets box, its helpers, its + * packs, the libffi shim built for the runtime's Python, and what the runtime + * profile writer writes from the runtime's Box network model (the Runtime profile + * and a byte copy of each policy file it names). `.box//aws/` gets only what + * the writer writes, for people to read. Both folders are rewritten on every build + * and deploy. `box` is asked for only when a runtime needs it. Returns the names + * of the runtimes it staged. */ export async function stageBoxCodeZip( project: Project, @@ -59,6 +65,7 @@ export async function stageBoxCodeZip( const ffi = entry.runtimeVersion ? build.ffi[entry.runtimeVersion] : undefined; if (ffi) cpSync(ffi, join(folder, "ffi"), { recursive: true }); writeBoxNetworkFiles(project.rootPath, filesOf(dist)); + writeRenderedBoxFiles(project.rootPath, runtime, dist, filesOf(dist)); } return runtimes.map((runtime) => runtime.name); } diff --git a/src/core/project/backends/boxContainer.test.ts b/src/core/project/backends/boxContainer.test.ts index dd0a306135..cebdc9c345 100644 --- a/src/core/project/backends/boxContainer.test.ts +++ b/src/core/project/backends/boxContainer.test.ts @@ -7,7 +7,7 @@ import { boxGatewaySpec } from "../../../projectSchemas/project"; import type { Project } from "../../../handlers/project/types"; import type { BoxNetwork } from "../boxNetwork"; import { renderAgentCorePack, renderRuntimeBoxProfile } from "../templates/boxProfile"; -import { assertBoxRuntimesHaveBoxVersion, stageBoxContainers } from "./boxContainer"; +import { stageBoxContainers } from "./boxContainer"; import { BOX_RELEASE, type BoxRelease } from "./boxRelease"; /** The staged path of the generated box/agentcore pack, from `.box-dist/`. */ @@ -124,8 +124,8 @@ describe("stageBoxContainers", () => { test("copies each policy file of the model beside the profile, for an image that copies .box-dist/ whole", async () => { const demo = await project(TEMPLATE_DOCKERFILE); - await mkdir(join(demo.rootPath, ".box"), { recursive: true }); - await writeFile(join(demo.rootPath, ".box", "policy.dw"), "// rules\n"); + await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true }); + await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n"); await stageBoxContainers(demo, [model(["policy.dw"])], releaseOf().releaseFor); @@ -136,8 +136,8 @@ describe("stageBoxContainers", () => { test("refuses an image that copies only the profile when policy files go with it", async () => { const demo = await project(BOX_DOCKERFILE); - await mkdir(join(demo.rootPath, ".box"), { recursive: true }); - await writeFile(join(demo.rootPath, ".box", "policy.dw"), "// rules\n"); + await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true }); + await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n"); await expect( stageBoxContainers(demo, [model(["policy.dw"])], releaseOf().releaseFor), @@ -167,35 +167,3 @@ function model(policyFiles: string[]): BoxNetwork { failures: [], }; } - -describe("assertBoxRuntimesHaveBoxVersion", () => { - test.each(["Container", "CodeZip"] as const)( - "refuses a %s runtime of a Box project with no box.version, and names the pinned release", - async (build) => { - const demo = await project(BOX_DOCKERFILE); - const runtime = demo.spec.runtimes[0]!; - runtime.build = build; - delete runtime.box; - - expect(() => assertBoxRuntimesHaveBoxVersion(demo.spec)).toThrow( - 'runtime "agent" has no box.version in agentcore.json, but every runtime of a Box ' + - `project runs in a box. Add "box": { "version": "${BOX_RELEASE.version}" } to the ` + - "runtime in agentcore.json, then retry.", - ); - }, - ); - - test("accepts a Box project whose runtimes have box.version", async () => { - const demo = await project(BOX_DOCKERFILE); - - expect(() => assertBoxRuntimesHaveBoxVersion(demo.spec)).not.toThrow(); - }); - - test("accepts a runtime with no box.version outside a Box project", async () => { - const demo = await project(BOX_DOCKERFILE); - delete demo.spec.runtimes[0]!.box; - delete (demo.spec as { projectType?: string }).projectType; - - expect(() => assertBoxRuntimesHaveBoxVersion(demo.spec)).not.toThrow(); - }); -}); diff --git a/src/core/project/backends/boxContainer.ts b/src/core/project/backends/boxContainer.ts index 29281b76a1..8007693617 100644 --- a/src/core/project/backends/boxContainer.ts +++ b/src/core/project/backends/boxContainer.ts @@ -1,15 +1,18 @@ import { readFileSync } from "node:fs"; import { copyFile, mkdir, rm, writeFile } from "node:fs/promises"; import { dirname, join, posix } from "node:path"; -import { ProjectStateError } from "../../../errors/errors"; import type { Project } from "../../../handlers/project/types"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; import type { BoxNetwork } from "../boxNetwork"; -import { boxNetworkEdits, runtimeProfileWriter, writeBoxNetworkFiles } from "../boxNetworkWriters"; +import { + boxNetworkEdits, + runtimeProfileWriter, + writeBoxNetworkFiles, + writeRenderedBoxFiles, +} from "../boxNetworkWriters"; import { isFile } from "../runtimeBuild"; -import { isBoxProject, type ProjectSpec } from "../../../projectSchemas/project"; import { runtimeRunsInBox } from "../templates/boxProfile"; -import { BOX_RELEASE, type BoxRelease } from "./boxRelease"; +import type { BoxRelease } from "./boxRelease"; import { assertImageCopiesPolicyFiles } from "./boxStaging"; /** The folder a box image's Dockerfile copies its box profile and policy files from. */ @@ -83,7 +86,7 @@ function boxReleaseEnv({ repo, version, linux }: BoxRelease): string { /** * Writes `/` for a box image: `profileText`, the profile the image runs, each - * policy file of `policies` at its path from `.box/`, and the box release the Dockerfile downloads. + * policy file of `policies` at its path from the agent's local box folder, and the box release the Dockerfile downloads. * The folder is rewritten each time. */ export async function stageBoxImage( @@ -107,9 +110,11 @@ export async function stageBoxImage( /** * Stages box for build and deploy into each container runtime that runs in a box - * ({@link runtimeRunsInBox}): the box release its `box.version` names, and - * what the runtime profile writer writes from the runtime's Box network model, - * the Runtime profile and a byte copy of each policy file it names. Returns the names of the runtimes it staged. + * ({@link runtimeRunsInBox}): the build context's `.box-dist/` gets the box release its + * `box.version` names, and what the runtime profile writer writes from the runtime's Box network + * model (the Runtime profile and a byte copy of each policy file it names). `.box//aws/` + * gets only what the writer writes, for people to read. Returns the names of the runtimes it + * staged. */ export async function stageBoxContainers( project: Project, @@ -141,30 +146,14 @@ export async function stageBoxContainers( ); } for (const [index, { dist }] of staged.entries()) { + const runtime = runtimes[index]!; const folder = join(project.rootPath, ...dist.split("/")); await rm(folder, { recursive: true, force: true }); await mkdir(folder, { recursive: true }); - const release = await releaseFor(runtimes[index]!.box?.version); + const release = await releaseFor(runtime.box?.version); await writeFile(join(folder, BOX_RELEASE_ENV), boxReleaseEnv(release)); writeBoxNetworkFiles(project.rootPath, filesOf(dist)); + writeRenderedBoxFiles(project.rootPath, runtime.name, dist, filesOf(dist)); } return runtimes.map((runtime) => runtime.name); } - -/** - * Throws for a runtime of a Box project with no `box.version`. Every runtime of a Box project runs - * in a box, and only `box.version` makes it do so, so without it build would stage no box and the - * agent could not start on AgentCore Runtime. `agentcore create` writes it with the box release - * this CLI pins. - */ -export function assertBoxRuntimesHaveBoxVersion(spec: ProjectSpec): void { - if (!isBoxProject(spec)) return; - for (const runtime of spec.runtimes) { - if (runtime.box !== undefined) continue; - throw new ProjectStateError( - `runtime "${runtime.name}" has no box.version in agentcore.json, but every runtime of a Box ` + - `project runs in a box. Add "box": { "version": "${BOX_RELEASE.version}" } to the ` + - "runtime in agentcore.json, then retry.", - ); - } -} diff --git a/src/core/project/backends/boxStaging.ts b/src/core/project/backends/boxStaging.ts index 1ffbe43b20..250d191eb3 100644 --- a/src/core/project/backends/boxStaging.ts +++ b/src/core/project/backends/boxStaging.ts @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; import { ProjectStateError } from "../../../errors/errors"; -import { BOX_PROFILE_FILE } from "../templates/boxProfile"; +import { boxLocalProfileFile } from "../templates/boxProfile"; /** A `COPY` of the whole staged folder, which takes the policy files in with the profile. */ const COPIES_WHOLE_DIST = /^\s*COPY\s+(?:--\S+\s+)*(?:\.box-dist|\$\{BOX_DIST\})\/?\s/m; @@ -16,7 +16,7 @@ export function assertImageCopiesPolicyFiles( ): void { if (policyFiles.length === 0 || COPIES_WHOLE_DIST.test(readFileSync(dockerfile, "utf8"))) return; throw new ProjectStateError( - `runtime "${runtimeName}" takes the policy files of ${BOX_PROFILE_FILE} to AgentCore Runtime ` + + `runtime "${runtimeName}" takes the policy files of ${boxLocalProfileFile(runtimeName)} to AgentCore Runtime ` + `(${policyFiles.join(", ")}), but ${dockerfile} does not copy .box-dist/ whole into the ` + "image. Box would refuse its profile there. Copy the box steps of the Dockerfile of a new " + "`agentcore create --template agent-python-strands-box-container` project: they copy " + diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index dd9dd2284e..2fd9516ad3 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -47,11 +47,11 @@ interface Options { readonly executionRoleArn?: string; } -/** The box profile of the project. */ -const PROFILE = ".box/profile.toml"; +/** The local box profile of runtime `agent`. */ +const PROFILE = ".box/agent/local/profile.toml"; /** - * The model of runtime `agent` for `policy` in `.box/policy.dw` and the routes `egress`, as Box + * The model of runtime `agent` for `policy` in `.box/agent/local/policy.dw` and the routes `egress`, as Box * resolves them: its policy holds the file, then the rules Box adds for each route. The profile * sets `packs` on line 1, then each entry of `egress` and `mcp` on a line of its own. */ @@ -85,7 +85,7 @@ function model(policy: string, egress: Record = {}, options: Op places: profilePlaces(profile, PROFILE), }, `${options.boxFirst ?? ""}${policy}\n${options.packRules ?? ""}${boxNetworkRules(egress, mcp)}`, - policy ? [{ file: ".box/policy.dw", text: policy }] : [], + policy ? [{ file: ".box/agent/local/policy.dw", text: policy }] : [], ); const network = buildBoxNetwork(parsed, failures, { spec, @@ -231,7 +231,7 @@ describe("the gateway's targets", () => { "agentcore/agentcore.json The gateway target 'gh' for api.github.com sends requests " + "signed with the gateway's role for execute-api, and [egress.github] sends the API key " + "credential 'github' in the header Authorization with the prefix Bearer. Make the two " + - "the same, in agentcore.json or in .box/profile.toml.", + "the same, in agentcore.json or in .box/agent/local/profile.toml.", ]); }); @@ -360,7 +360,7 @@ describe("the gateway's targets", () => { }); expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", "my-api"]]); expect(r.lines()).toEqual([ - ".box/profile.toml:3:1 [egress.my-api] would name the gateway target for b.example.com " + + ".box/agent/local/profile.toml:3:1 [egress.my-api] would name the gateway target for b.example.com " + "'egress-my-api', and [egress.my_api] for a.example.com has that name. Rename the entry.", ]); }); @@ -371,7 +371,7 @@ describe("the gateway's targets", () => { }); expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", "gh_connect"]]); expect(r.lines()).toEqual([ - '.box/policy.dw:1:1 The rule "gh_connect" allows api.github.com, and its gateway target ' + + '.box/agent/local/policy.dw:1:1 The rule "gh_connect" allows api.github.com, and its gateway target ' + "would have the name 'egress-api-github-com', which [egress.api-github-com] for " + "other.example.com has. Add an [egress] entry with another name for api.github.com.", ]); @@ -391,7 +391,7 @@ describe("the gateway's targets", () => { ?.target, ).toBe(`egress-${"x".repeat(93)}`); expect(model("", { ___: { destinations: ["a.example.com"] } }).lines()).toEqual([ - ".box/profile.toml:2:1 [egress.___] has no letter or digit in its name, so build cannot " + + ".box/agent/local/profile.toml:2:1 [egress.___] has no letter or digit in its name, so build cannot " + "name a gateway target after it. Rename the entry.", ]); }); @@ -411,7 +411,7 @@ describe("the gateway's targets", () => { }); expect(r.failures()).toEqual([["TOO_MANY_TARGETS", undefined]]); expect(r.lines()).toEqual([ - ".box/profile.toml The gateway 'agent-box-egress' needs 101 targets, 99 for the hosts of the " + + ".box/agent/local/profile.toml The gateway 'agent-box-egress' needs 101 targets, 99 for the hosts of the " + "Box profile and 2 of your own, and a gateway can have at most 100. Remove hosts from " + "the profile, or targets from the gateway.", ]); @@ -473,7 +473,7 @@ describe("outbound auth", () => { ); expect(shared.failures()).toEqual([["API_KEY_CREDENTIAL_SHARED", "github"]]); expect(shared.lines()).toEqual([ - ".box/profile.toml:3:1 [egress.github] needs the API key credential 'github' for " + + ".box/agent/local/profile.toml:3:1 [egress.github] needs the API key credential 'github' for " + "env://GITHUB_TOKEN, and [egress.mirror] takes that credential for " + "env://AGENTCORE_CREDENTIAL_GITHUB. One credential holds one key. Rename the entry.", ]); @@ -546,13 +546,13 @@ describe("hosts the model cannot carry", () => { ]); const example = 'for example context.input.host == "api.example.com".'; expect(r.lines()).toEqual([ - '.box/profile.toml:2:1 [egress.wide] has the wildcard destination "*.example.com", and ' + + '.box/agent/local/profile.toml:2:1 [egress.wide] has the wildcard destination "*.example.com", and ' + "each gateway target needs one fixed host. Name each host in `destinations`.", - '.box/policy.dw:1:1 The rule "wild" allows each host that matches "*.example.com", and ' + + '.box/agent/local/policy.dw:1:1 The rule "wild" allows each host that matches "*.example.com", and ' + `each gateway target needs one fixed host. Name each host in the rule, ${example}`, - '.box/policy.dw:2:1 The rule "anywhere" allows requests to every host, and each gateway ' + + '.box/agent/local/policy.dw:2:1 The rule "anywhere" allows requests to every host, and each gateway ' + `target needs one fixed host. Add a condition that names each host, ${example}`, - '.box/policy.dw:3:1 The rule "not_one" allows every host except the ones it excludes ' + + '.box/agent/local/policy.dw:3:1 The rule "not_one" allows every host except the ones it excludes ' + '(context.input.host != "evil.example.com"), and each gateway target needs one fixed ' + `host. Name each host it allows, ${example}`, ]); @@ -612,9 +612,9 @@ describe("hosts the model cannot carry", () => { ["EGRESS_ENTRY_FAILED", "x_get"], ]); expect(r.lines()).toEqual([ - ".box/profile.toml:2:1 [egress.x] already has `backends`, and build sends each host " + + ".box/agent/local/profile.toml:2:1 [egress.x] already has `backends`, and build sends each host " + "through the gateway itself. Remove `backends` from the entry.", - '.box/policy.dw:1:1 The rule "x_get" allows a.example.com, and [egress.x] for that host ' + + '.box/agent/local/policy.dw:1:1 The rule "x_get" allows a.example.com, and [egress.x] for that host ' + "has a problem. Fix [egress.x] first.", ]); }); @@ -623,7 +623,7 @@ describe("hosts the model cannot carry", () => { const r = model("", { m: { destinations: ["mcp.example.com"], protocol: "mcp" } }); expect(r.failures()).toEqual([["MCP_OVER_HTTP", "m"]]); expect(r.lines()).toEqual([ - '.box/profile.toml:2:1 [egress.m] sets protocol = "mcp", which Box does not take. ' + + '.box/agent/local/profile.toml:2:1 [egress.m] sets protocol = "mcp", which Box does not take. ' + 'Declare the server as [mcp.m] with type = "http", and remove this entry.', ]); }); @@ -677,14 +677,14 @@ describe("hosts the model cannot carry", () => { ["UNKNOWN_ATTRIBUTE", "query"], ]); expect(r.lines()).toEqual([ - ".box/policy.dw:5:67 Syntax error: unexpected } in a condition. Correct the rule at this " + + ".box/agent/local/policy.dw:5:67 Syntax error: unexpected } in a condition. Correct the rule at this " + "place.", - '.box/policy.dw:2:1 The rule "dup" has the same @id as the rule at .box/policy.dw:1:1. ' + + '.box/agent/local/policy.dw:2:1 The rule "dup" has the same @id as the rule at .box/agent/local/policy.dw:1:1. ' + "Give each rule its own @id.", - '.box/policy.dw:3:1 The rule "verb" names the action Box::Action::"http:get", which Box ' + + '.box/agent/local/policy.dw:3:1 The rule "verb" names the action Box::Action::"http:get", which Box ' + 'does not have. Use a Box action, such as Box::Action::"http:request" or ' + 'Box::Action::"net:connect".', - '.box/policy.dw:4:1 The rule "query" reads context.input.query, which http:request does ' + + '.box/agent/local/policy.dw:4:1 The rule "query" reads context.input.query, which http:request does ' + "not have. Use one of context.input.host, context.input.port, context.input.method, " + "context.input.path, context.input.body_bytes, context.input.intercepted, " + "context.input.upgrade, or context.output.status.", @@ -720,13 +720,13 @@ describe("hosts the model cannot carry", () => { ...metadata.lines(), ...packed.lines(), ]).toEqual([ - '.box/policy.dw:2:1 The rule "route_github_connect" is one Box adds itself for ' + - "[egress.github]. Remove it from .box/policy.dw.", - '.box/policy.dw:1:1 The rule "shared" has the same @id as a rule that a pack in ' + + '.box/agent/local/policy.dw:2:1 The rule "route_github_connect" is one Box adds itself for ' + + "[egress.github]. Remove it from .box/agent/local/policy.dw.", + '.box/agent/local/policy.dw:1:1 The rule "shared" has the same @id as a rule that a pack in ' + "`packs` adds. Give your rule another @id.", - '.box/policy.dw:1:1 The rule "metadata_hosts" is one Box adds itself to every profile. ' + - "Remove it from .box/policy.dw.", - '.box/policy.dw:1:1 The rule "pack_rule" has the same @id as a rule that a pack in ' + + '.box/agent/local/policy.dw:1:1 The rule "metadata_hosts" is one Box adds itself to every profile. ' + + "Remove it from .box/agent/local/policy.dw.", + '.box/agent/local/policy.dw:1:1 The rule "pack_rule" has the same @id as a rule that a pack in ' + "`packs` adds. Give your rule another @id.", ]); }); @@ -747,12 +747,12 @@ describe("hosts the model cannot carry", () => { const rest = "and each gateway target needs one fixed host."; expect(r.lines().map((line) => line.slice(0, line.indexOf(rest) + rest.length))).toEqual([ - '.box/profile.toml:1:1 The rule "pack_wild", which a pack in `packs` adds, allows each ' + + '.box/agent/local/profile.toml:1:1 The rule "pack_wild", which a pack in `packs` adds, allows each ' + `host that matches "*.pack.example.com", ${rest}`, - `.box/profile.toml:1:1 A rule that a pack in \`packs\` adds allows requests to every host, ${rest}`, + `.box/agent/local/profile.toml:1:1 A rule that a pack in \`packs\` adds allows requests to every host, ${rest}`, ]); expect(unnamed.lines()).toEqual([ - `.box/policy.dw:1:1 This rule allows requests to every host, ${rest} Add a condition ` + + `.box/agent/local/policy.dw:1:1 This rule allows requests to every host, ${rest} Add a condition ` + 'that names each host, for example context.input.host == "api.example.com".', ]); }); @@ -817,7 +817,7 @@ describe("HTTP MCP servers", () => { { mcp: { tools: server(["tools.example.com"], { secret: { ref: "aws://default" } }) } }, ); expect(unsigned.lines()).toEqual([ - ".box/profile.toml:2:1 [mcp.tools] signs requests to tools.example.com with " + + ".box/agent/local/profile.toml:2:1 [mcp.tools] signs requests to tools.example.com with " + "aws://default, and the gateway signs only for Bedrock, AgentCore, and Lambda function " + "URL hosts. Use an env:// secret for this host, or remove the secret.", ]); @@ -841,12 +841,12 @@ describe("HTTP MCP servers", () => { ["MCP_DESTINATION_NOT_ONE_HOST", "wild"], ]); expect(r.lines()).toEqual([ - ".box/profile.toml:2:1 [mcp.two] names 2 destinations, and the gateway route of " + + ".box/agent/local/profile.toml:2:1 [mcp.two] names 2 destinations, and the gateway route of " + "an MCP server takes exactly one host. Declare one [mcp] server for each host.", - '.box/profile.toml:3:1 [mcp.pathed] has the destination "c.example.com/mcp", and ' + + '.box/agent/local/profile.toml:3:1 [mcp.pathed] has the destination "c.example.com/mcp", and ' + "the gateway route of an MCP server takes a host with no path. Remove /mcp from the " + "destination. The agent's MCP client keeps the path in its URL.", - '.box/profile.toml:4:1 [mcp.wild] has the wildcard destination "*.example.com", ' + + '.box/agent/local/profile.toml:4:1 [mcp.wild] has the wildcard destination "*.example.com", ' + "and the gateway route of an MCP server takes one exact host. Name the server's host.", ]); expect(r.network.hosts).toEqual([]); @@ -856,7 +856,7 @@ describe("HTTP MCP servers", () => { const r = model("", { github: GITHUB }, { mcp: { github: server(["api.githubcopilot.com"]) } }); expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", "github"]]); expect(r.lines()).toEqual([ - ".box/profile.toml:3:1 [mcp.github] would name the gateway target for " + + ".box/agent/local/profile.toml:3:1 [mcp.github] would name the gateway target for " + "api.githubcopilot.com 'egress-github', and [egress.github] for api.github.com has that " + "name. Rename the entry.", ]); @@ -880,7 +880,7 @@ describe("HTTP MCP servers", () => { ]); expect(r.failures()).toEqual([["API_KEY_CREDENTIAL_SHARED", "tools"]]); expect(r.lines()).toEqual([ - ".box/profile.toml:3:1 [mcp.tools] needs the API key credential 'tools' for " + + ".box/agent/local/profile.toml:3:1 [mcp.tools] needs the API key credential 'tools' for " + "env://TOOLS_MCP_KEY, and [egress.tools] takes that credential for env://TOOLS_KEY. One " + "credential holds one key. Rename the entry.", ]); @@ -960,7 +960,7 @@ describe("WebSocket", () => { expect(r.failures()).toEqual([]); expect(r.network.hosts.filter((h) => h.target !== undefined)).toEqual([]); expect(r.network.warnings).toEqual([ - '.box/policy.dw:2:1: The rule "chat" allows only WebSocket connections, and build adds no ' + + '.box/agent/local/policy.dw:2:1: The rule "chat" allows only WebSocket connections, and build adds no ' + "gateway target for a WebSocket, so it skips this rule.", ]); }); diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index 63504209f3..1f97ebc129 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -110,7 +110,10 @@ export interface BoxNetwork { readonly hosts: readonly BoxNetworkHost[]; /** The `env://` route of each target that sends an API key, for the credentials writer. */ readonly envRoutes: readonly BoxEnvRoute[]; - /** The policy files, relative to `.box/`, to copy beside the AgentCore Runtime profile. */ + /** + * The policy files, relative to the agent's local box folder, to copy beside the AgentCore + * Runtime profile. + */ readonly policyFiles: readonly string[]; /** The CloudWatch targets of the profile's `[telemetry]`; absent means none. */ readonly telemetry?: readonly CloudWatchTelemetry[]; diff --git a/src/core/project/boxNetwork/policyParser.test.ts b/src/core/project/boxNetwork/policyParser.test.ts index 019bfaf3d2..43e13bd184 100644 --- a/src/core/project/boxNetwork/policyParser.test.ts +++ b/src/core/project/boxNetwork/policyParser.test.ts @@ -21,11 +21,11 @@ const RESOLVED = [ "", ].join("\n"); const FILES: PolicyFileText[] = [ - { file: ".box/policy.dw", text: `// No admin paths on GitHub.\n${NO_ADMIN}\n` }, - { file: ".box/sub/more.dw", text: `// more\n\n${MORE}\n` }, + { file: ".box/agent/local/policy.dw", text: `// No admin paths on GitHub.\n${NO_ADMIN}\n` }, + { file: ".box/agent/local/sub/more.dw", text: `// more\n\n${MORE}\n` }, ]; const NO_ROUTES = { - path: ".box/profile.toml", + path: ".box/agent/local/profile.toml", egress: {}, mcp: {}, policyFiles: ["policy.dw", "sub/more.dw"], @@ -46,8 +46,8 @@ describe("parseResolvedPolicy", () => { expect(result.failures).toEqual([]); expect(places(result)).toEqual([ - ["no_admin", ".box/policy.dw:2:1"], - ["more_rule", ".box/sub/more.dw:3:1"], + ["no_admin", ".box/agent/local/policy.dw:2:1"], + ["more_rule", ".box/agent/local/sub/more.dw:3:1"], ["shell_commands", undefined], ["route_github_connect", undefined], ["route_github_request", undefined], @@ -59,31 +59,37 @@ describe("parseResolvedPolicy", () => { `permit (principal, ${HR}, resource) when { context.input.host == "a.example.com" };\n` + `@id("dup") forbid (principal, ${HR}, resource) when { context.input.host == "a.example.com" };\n` + `@id("dup") forbid (principal, ${HR}, resource) when { context.input.host == "b.example.com" };\n`; - const result = parsed(`${own}\n${RESOLVED}`, [{ file: ".box/policy.dw", text: own }]); + const result = parsed(`${own}\n${RESOLVED}`, [ + { file: ".box/agent/local/policy.dw", text: own }, + ]); expect(places(result).slice(0, 3)).toEqual([ - ["policy0", ".box/policy.dw:1:1"], - ["dup", ".box/policy.dw:2:1"], - ["dup", ".box/policy.dw:3:1"], + ["policy0", ".box/agent/local/policy.dw:1:1"], + ["dup", ".box/agent/local/policy.dw:2:1"], + ["dup", ".box/agent/local/policy.dw:3:1"], ]); }); test("takes no route from a rule of the profile's own policy files that Box's naming fits", () => { const own = `@id("route_mine_connect") permit (principal, ${NC}, resource) when { context.input.host == "x.example.com" && context.input.port == 443 };\n`; - expect(parsed(own, [{ file: ".box/policy.dw", text: own }]).parsed.profile.egress).toEqual({}); + expect( + parsed(own, [{ file: ".box/agent/local/policy.dw", text: own }]).parsed.profile.egress, + ).toEqual({}); }); test("fails a syntax error once, at its place in a policy file, or else in Box's policy", () => { const broken = `permit (principal, ${HR}, resource) when { context.input.host == };\n`; - const inFile = parsed(`${broken}\n${RESOLVED}`, [{ file: ".box/policy.dw", text: broken }]); + const inFile = parsed(`${broken}\n${RESOLVED}`, [ + { file: ".box/agent/local/policy.dw", text: broken }, + ]); const inBox = parsed(`${RESOLVED}${broken}`, FILES); expect(inFile.failures).toEqual([ { code: "PARSE_ERROR", reason: "Syntax error: unexpected } in a condition. Correct the rule at this place.", - place: `.box/policy.dw:1:${broken.indexOf("}") + 1}`, + place: `.box/agent/local/policy.dw:1:${broken.indexOf("}") + 1}`, }, ]); expect(inBox.failures).toEqual([ @@ -92,7 +98,7 @@ describe("parseResolvedPolicy", () => { reason: "Build cannot read a rule that Box or a pack adds to this profile (syntax error: " + "unexpected } in a condition). Update the AgentCore CLI, then retry.", - place: ".box/profile.toml", + place: ".box/agent/local/profile.toml", }, ]); }); diff --git a/src/core/project/boxNetwork/profileParser.test.ts b/src/core/project/boxNetwork/profileParser.test.ts index c00dcf8820..7253f65137 100644 --- a/src/core/project/boxNetwork/profileParser.test.ts +++ b/src/core/project/boxNetwork/profileParser.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { parseResolvedProfile, profilePlaces, profilePolicyFiles } from "./profileParser"; -const PROFILE = ".box/profile.toml"; +const PROFILE = ".box/agent/local/profile.toml"; describe("parseResolvedProfile", () => { test("reads [egress] and [mcp] of Box's resolved box.toml, and keeps the profile's policy files", () => { @@ -124,13 +124,13 @@ describe("profilePolicyFiles", () => { test.each([ [ 'policies = ["../escape.dw"]', - '`policies` names "../escape.dw", which is outside .box/. Move the file into ' + - ".box/, and name it from there.", + '`policies` names "../escape.dw", which is outside .box/agent/local/. Move the file into ' + + ".box/agent/local/, and name it from there.", ], [ 'policies = ["/etc/policy.dw"]', - '`policies` names "/etc/policy.dw", which is outside .box/. Move the file into ' + - ".box/, and name it from there.", + '`policies` names "/etc/policy.dw", which is outside .box/agent/local/. Move the file into ' + + ".box/agent/local/, and name it from there.", ], ['policies = ["a.dw", "./a.dw"]', '`policies` names "./a.dw" twice. Remove one of them.'], [ @@ -141,7 +141,7 @@ describe("profilePolicyFiles", () => { expect(refusal(`# policy files\n ${text}\n`)).toEqual({ code: "INVALID_PROFILE", reason, - place: ".box/profile.toml:2:3", + place: ".box/agent/local/profile.toml:2:3", }); }); @@ -151,7 +151,7 @@ describe("profilePolicyFiles", () => { reason: "Box does not take the key `policy`. List your policy files under `policies` instead, " + 'such as policies = ["policy.dw"].', - place: ".box/profile.toml:2:1", + place: ".box/agent/local/profile.toml:2:1", }); }); @@ -159,7 +159,7 @@ describe("profilePolicyFiles", () => { expect(refusal("a = 1\n[egress\n")).toEqual({ code: "INVALID_PROFILE", reason: "This is not valid TOML (illegal character in key). Correct the syntax.", - place: ".box/profile.toml:2:8", + place: ".box/agent/local/profile.toml:2:8", }); }); }); @@ -191,13 +191,13 @@ describe("profilePlaces", () => { ); expect(Object.fromEntries(places.entries)).toEqual({ - "egress.github": ".box/profile.toml:4:1", - "egress.dot.name": ".box/profile.toml:7:1", - "egress.inline": ".box/profile.toml:11:3", - "mcp.tools": ".box/profile.toml:17:1", + "egress.github": ".box/agent/local/profile.toml:4:1", + "egress.dot.name": ".box/agent/local/profile.toml:7:1", + "egress.inline": ".box/agent/local/profile.toml:11:3", + "mcp.tools": ".box/agent/local/profile.toml:17:1", }); - expect(places.packs).toBe(".box/profile.toml:1:1"); - expect(places.policies).toBe(".box/profile.toml:2:1"); + expect(places.packs).toBe(".box/agent/local/profile.toml:1:1"); + expect(places.policies).toBe(".box/agent/local/profile.toml:2:1"); }); test("places no entry, `packs`, or `policies` that the profile does not set", () => { diff --git a/src/core/project/boxNetwork/projectSpec.test.ts b/src/core/project/boxNetwork/projectSpec.test.ts index 54b5ebbea4..f5e170d78f 100644 --- a/src/core/project/boxNetwork/projectSpec.test.ts +++ b/src/core/project/boxNetwork/projectSpec.test.ts @@ -9,7 +9,7 @@ import { gatewayTargetFor, outboundAuthWords, sameOutboundAuth } from "./project /** The hosts of `egress`, with the rules Box adds for it. */ function hostsOf(egress: Record): BoxNetworkHost[] { const { parsed } = parseResolvedPolicy( - { path: ".box/profile.toml", egress, mcp: {}, policyFiles: [] }, + { path: ".box/agent/local/profile.toml", egress, mcp: {}, policyFiles: [] }, boxNetworkRules(egress), [], ); diff --git a/src/core/project/boxNetwork/telemetry.test.ts b/src/core/project/boxNetwork/telemetry.test.ts index c0f9c6e533..11ec2639f5 100644 --- a/src/core/project/boxNetwork/telemetry.test.ts +++ b/src/core/project/boxNetwork/telemetry.test.ts @@ -107,7 +107,7 @@ describe("cloudWatchTelemetry", () => { }); describe("withDeployRegion", () => { - const PROFILE = ".box/profile.toml"; + const PROFILE = ".box/agent/local/profile.toml"; const logs = { name: "logs", kind: "cloudwatch_logs", logGroup: "g", logStream: "s" } as const; const traces = { name: "traces", kind: "cloudwatch_traces" } as const; diff --git a/src/core/project/boxNetworkSource.test.ts b/src/core/project/boxNetworkSource.test.ts index 19711e7d1c..37a0c43997 100644 --- a/src/core/project/boxNetworkSource.test.ts +++ b/src/core/project/boxNetworkSource.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { InvalidEnvironmentError } from "../../errors/errors"; import { boxGatewaySpec, type ProjectSpec } from "../../projectSchemas/project"; import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; +import type { BoxProfileResolver } from "./boxProfileResolver"; import { boxShowOf, FakeBoxProfileResolver } from "./boxProfileResolver-test-support"; const directories: string[] = []; @@ -32,17 +33,25 @@ const SPEC = { /** What box resolves the profile of {@link project} to: its route `api`, which has no secret. */ const API_ROUTE = { api: { destinations: ["api.example.com"] } }; -/** A project root whose profile names `policies`, with `.box/policy.dw` in it. */ +/** The local box folder of the runtime `agent`, from the project root. */ +const LOCAL = [".box", "agent", "local"]; + +/** A project root whose profile names `policies`, with `.box/agent/local/policy.dw` in it. */ async function project(policies: string[]): Promise { const root = await mkdtemp(join(tmpdir(), "box-network-source-")); directories.push(root); - await mkdir(join(root, ".box"), { recursive: true }); + await writeProfile(root, "agent", policies); + await writeFile(join(root, ...LOCAL, "policy.dw"), "// no rule\n"); + return root; +} + +/** Writes the local box profile of the runtime `agentName`, which names `policies`. */ +async function writeProfile(root: string, agentName: string, policies: string[]): Promise { + await mkdir(join(root, ".box", agentName, "local"), { recursive: true }); await writeFile( - join(root, ".box", "profile.toml"), + join(root, ".box", agentName, "local", "profile.toml"), `policies = ${JSON.stringify(policies)}\n[egress.api]\ndestinations = ["api.example.com"]\n`, ); - await writeFile(join(root, ".box", "policy.dw"), "// no rule\n"); - return root; } const failuresOf = async (root: string) => @@ -51,7 +60,7 @@ const failuresOf = async (root: string) => ); describe("readBoxNetworks", () => { - test("reads box's resolution of .box/profile.toml, in the project folder, into one model per box runtime", async () => { + test("reads box's resolution of .box/agent/local/profile.toml, in the project folder, into one model per box runtime", async () => { const root = await project(["policy.dw"]); const box = new FakeBoxProfileResolver( boxShowOf({ egress: API_ROUTE, policy: "// no rule\n" }), @@ -59,7 +68,9 @@ describe("readBoxNetworks", () => { const [network] = await readBoxNetworks(SPEC, root, box); - expect(box.calls).toEqual([{ projectRoot: root, profilePath: ".box/profile.toml" }]); + expect(box.calls).toEqual([ + { projectRoot: root, profilePath: ".box/agent/local/profile.toml" }, + ]); expect(network?.gateway).toBe("agent-box-egress"); expect(network?.policyFiles).toEqual(["policy.dw"]); // Box writes a route with no secret only as rules, and the target still takes its name. @@ -88,13 +99,13 @@ describe("readBoxNetworks", () => { test("places a rule of a policy file at its line, and an entry at its line in the profile", async () => { const root = await project(["policy.dw"]); await writeFile( - join(root, ".box", "profile.toml"), + join(root, ...LOCAL, "profile.toml"), 'policies = ["policy.dw"]\n\n[egress.wide]\ndestinations = ["*.wide.example.com"]\n' + 'secret.ref = "env://KEY"\n', ); const wild = '@id("wild") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host like "*.example.com" };\n'; - await writeFile(join(root, ".box", "policy.dw"), `// every subdomain\n${wild}`); + await writeFile(join(root, ...LOCAL, "policy.dw"), `// every subdomain\n${wild}`); const box = new FakeBoxProfileResolver( boxShowOf({ egress: { wide: { destinations: ["*.wide.example.com"], secret: { ref: "env://KEY" } } }, @@ -111,8 +122,8 @@ describe("readBoxNetworks", () => { place, ]), ).toEqual([ - ["EGRESS_WILDCARD_DESTINATION", "wide", ".box/profile.toml:3:1"], - ["WILDCARD_HOST", "wild", ".box/policy.dw:2:1"], + ["EGRESS_WILDCARD_DESTINATION", "wide", ".box/agent/local/profile.toml:3:1"], + ["WILDCARD_HOST", "wild", ".box/agent/local/policy.dw:2:1"], ]); }); @@ -121,7 +132,7 @@ describe("readBoxNetworks", () => { const root = await project([]); expect(await readBoxNetworks({ ...SPEC, projectType: undefined }, root, box)).toEqual([]); - await rm(join(root, ".box", "profile.toml")); + await rm(join(root, ...LOCAL, "profile.toml")); expect((await readBoxNetworks(SPEC, root, box))[0]?.hosts).toEqual([]); expect(box.calls).toEqual([]); }); @@ -145,37 +156,99 @@ describe("readBoxNetworks", () => { ]); const elsewhere = join(root, "elsewhere.dw"); await writeFile(elsewhere, "// outside\n"); - await symlink(elsewhere, join(root, ".box", "outside.dw")); - await link(join(root, ".box", "policy.dw"), join(root, ".box", "linked.dw")); - await mkdir(join(root, ".box", "folder.dw")); + await symlink(elsewhere, join(root, ...LOCAL, "outside.dw")); + await link(join(root, ...LOCAL, "policy.dw"), join(root, ...LOCAL, "linked.dw")); + await mkdir(join(root, ...LOCAL, "folder.dw")); const reasons = await failuresOf(root); expect(reasons.map(({ code, place }) => [code, place])).toEqual( - Array(6).fill(["INVALID_POLICY_FILE", ".box/profile.toml:1:1"]), + Array(6).fill(["INVALID_POLICY_FILE", ".box/agent/local/profile.toml:1:1"]), ); expect(reasons.map(({ reason }) => reason)).toEqual([ - "`policies` names missing.dw, but .box/missing.dw does not exist. Create it, or remove " + - "it from `policies`.", - ".box/outside.dw is a symbolic link to a file outside .box/, which Box does not read. Put " + - "the policy file itself in .box/.", - ".box/linked.dw has 2 hard links, and Box reads only a policy file with one. Replace it " + - "with a copy.", - ".box/folder.dw is a folder, not a policy file. Name a file in `policies`.", - '.box/box takes the name "box", which Box keeps for its own files on AgentCore Runtime. ' + - "Rename the file.", - '.box/a b.dw has a character other than a letter, a digit, ".", "_", "-", or "/" in its ' + - "path, and deploy cannot copy it to AgentCore Runtime. Rename the file.", + "`policies` names missing.dw, but .box/agent/local/missing.dw does not exist. Create it, or " + + "remove it from `policies`.", + ".box/agent/local/outside.dw is a symbolic link to a file outside .box/agent/local/, which " + + "Box does not read. Put the policy file itself in .box/agent/local/.", + ".box/agent/local/linked.dw has 2 hard links, and Box reads only a policy file with one. " + + "Replace it with a copy.", + ".box/agent/local/folder.dw is a folder, not a policy file. Name a file in `policies`.", + '.box/agent/local/box takes the name "box", which Box keeps for its own files on AgentCore ' + + "Runtime. Rename the file.", + '.box/agent/local/a b.dw has a character other than a letter, a digit, ".", "_", "-", or "/" ' + + "in its path, and deploy cannot copy it to AgentCore Runtime. Rename the file.", ]); }); - test("reads a symlink that stays inside .box/", async () => { + test("reads a symlink that stays inside the agent's local box folder", async () => { const root = await project(["inner.dw"]); - await symlink(join(root, ".box", "policy.dw"), join(root, ".box", "inner.dw")); + await symlink(join(root, ...LOCAL, "policy.dw"), join(root, ...LOCAL, "inner.dw")); expect(await failuresOf(root)).toEqual([]); }); }); +describe("the telemetry of each box runtime", () => { + test("comes from the runtime's own local box profile", async () => { + const root = await project([]); + await writeProfile(root, "second", []); + await writeProfile(root, "quiet", []); + const spec = { + ...SPEC, + runtimes: [ + ...SPEC.runtimes, + { ...SPEC.runtimes[0]!, name: "second", codeLocation: "app/second" }, + { ...SPEC.runtimes[0]!, name: "quiet", codeLocation: "app/quiet" }, + ], + agentCoreGateways: [ + boxGatewaySpec("agent"), + boxGatewaySpec("second"), + boxGatewaySpec("quiet"), + ], + } as unknown as ProjectSpec; + const logs = (log_group: string) => ({ + kind: "cloudwatch_logs", + region: "us-west-2", + log_group, + log_stream: "s", + secret: { ref: "aws://default" }, + }); + const groups: Record = { + ".box/agent/local/profile.toml": "group-a", + ".box/second/local/profile.toml": "group-b", + }; + const calls: string[] = []; + const resolver: BoxProfileResolver = { + resolve: async (_root, profilePath) => { + calls.push(profilePath); + const shown = boxShowOf({ egress: API_ROUTE }); + const group = groups[profilePath]; + if (group === undefined) return shown; + return { ...shown, boxToml: { ...shown.boxToml, telemetry: { logs: logs(group) } } }; + }, + }; + + const networks = await readBoxNetworks(spec, root, resolver); + + const logsOf = (logGroup: string) => ({ + name: "logs", + kind: "cloudwatch_logs" as const, + region: "us-west-2", + logGroup, + logStream: "s", + }); + expect(calls).toEqual([ + ".box/agent/local/profile.toml", + ".box/second/local/profile.toml", + ".box/quiet/local/profile.toml", + ]); + expect(networks.map(({ runtime, telemetry }) => [runtime, telemetry])).toEqual([ + ["agent", [logsOf("group-a")]], + ["second", [logsOf("group-b")]], + ["quiet", undefined], + ]); + }); +}); + describe("the IAM policy files of the Box gateway", () => { test("counts the actions of each listed file, and warns for one it cannot count", async () => { const root = await project([]); @@ -250,25 +323,22 @@ describe("the IAM policy files of the Box gateway", () => { }); describe("boxNetworkFailureMessage", () => { - test("lists a problem of every box runtime once, with no runtime, and says nothing changed", async () => { + test("lists a problem of the one box runtime with no runtime, and says nothing changed", async () => { + // Each boxed agent reads its own .box//local profile, so a failure names that path. const root = await project(["missing.dw"]); - const spec = { - ...SPEC, - runtimes: [...SPEC.runtimes, { ...SPEC.runtimes[0]!, name: "second" }], - agentCoreGateways: [boxGatewaySpec("agent"), boxGatewaySpec("second")], - } as unknown as ProjectSpec; - const networks = await readBoxNetworks(spec, root, new FakeBoxProfileResolver()); + const networks = await readBoxNetworks(SPEC, root, new FakeBoxProfileResolver()); expect(boxNetworkFailureMessage(networks, "deploy")).toBe( "Deploy stopped: 1 problem in the Box profile. Deploy wrote nothing from the Box profile.\n" + - ".box/profile.toml:1:1 `policies` names missing.dw, but .box/missing.dw does not exist. " + - "Create it, or remove it from `policies`.", + ".box/agent/local/profile.toml:1:1 `policies` names missing.dw, but " + + ".box/agent/local/missing.dw does not exist. Create it, or remove it from `policies`.", ); }); test("names the runtime of a problem that only some box runtimes have", async () => { const root = await project(["missing.dw"]); + await writeProfile(root, "second", ["missing.dw"]); const spec = { ...SPEC, runtimes: [...SPEC.runtimes, { ...SPEC.runtimes[0]!, name: "second" }], @@ -294,10 +364,13 @@ describe("boxNetworkFailureMessage", () => { ); expect(boxNetworkFailureMessage(networks, "build")).toBe( - "Build stopped: 2 problems in the Box profile and agentcore.json. Build wrote nothing from the Box profile.\n" + - ".box/profile.toml:1:1 `policies` names missing.dw, but .box/missing.dw does not exist. " + - "Create it, or remove it from `policies`.\n" + + "Build stopped: 3 problems in the Box profile and agentcore.json. Build wrote nothing from the Box profile.\n" + + "In runtime agent:\n" + + " .box/agent/local/profile.toml:1:1 `policies` names missing.dw, but " + + ".box/agent/local/missing.dw does not exist. Create it, or remove it from `policies`.\n" + "In runtime second:\n" + + " .box/second/local/profile.toml:1:1 `policies` names missing.dw, but " + + ".box/second/local/missing.dw does not exist. Create it, or remove it from `policies`.\n" + " agentcore/agentcore.json The gateway target 'api' for api.example.com has the path " + "/v1 in its endpoint, and the agent's requests do not include it. Remove /v1 from the " + "endpoint, or remove the target.", diff --git a/src/core/project/boxNetworkSource.ts b/src/core/project/boxNetworkSource.ts index 6d1d4d7edb..2abca95437 100644 --- a/src/core/project/boxNetworkSource.ts +++ b/src/core/project/boxNetworkSource.ts @@ -1,7 +1,7 @@ /** - * Reads Box's own resolution of the box profile, and the profile's policy files once, as Box reads - * them, runs the profile and policy parsers on them, and builds the Box network model of each - * runtime that runs its agent in a box. + * Reads Box's own resolution of each boxed agent's local box profile, and the profile's policy + * files, as Box reads them, runs the profile and policy parsers on them, and builds the Box network + * model of each runtime that runs its agent in a box. */ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; @@ -13,7 +13,12 @@ import { InvalidEnvironmentError, ProjectStateError } from "../../errors/errors" import type { PolicyFileCopy } from "./backends/boxContainer"; import { DEFAULT_EGRESS_BEDROCK_REGION } from "../../handlers/project/shortcuts"; import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, BOX_MEMORY_POLICY_FILE } from "./boxMemory"; -import { BOX_PROFILE_FILE, boxProfilePath, runtimeRunsInBox } from "./templates/boxProfile"; +import { + boxLocalDir, + boxLocalProfileFile, + boxLocalProfilePath, + runtimeRunsInBox, +} from "./templates/boxProfile"; import { boxGatewayOf, buildBoxNetwork, @@ -28,19 +33,17 @@ import { } from "./boxNetwork"; import type { BoxProfileResolver, ResolvedBoxProfile } from "./boxProfileResolver"; -/** The folder of the box profile, which holds its policy files. */ -const BOX_PROFILE_DIR = ".box"; - -const NO_POLICY: ParsedPolicy = { - profile: { path: BOX_PROFILE_FILE, egress: {}, mcp: {}, policyFiles: [] }, +/** The policy of an agent that has no local box profile at `profilePath`. */ +const noPolicy = (profilePath: string): ParsedPolicy => ({ + profile: { path: profilePath, egress: {}, mcp: {}, policyFiles: [] }, statements: [], places: new Map(), -}; +}); /** - * The Box network model of each runtime of `spec` that runs its agent in a box, from the box - * profile as `resolver` resolves it for a build in `region`. A project with no box runtime, or no - * box profile, resolves nothing. + * The Box network model of each runtime of `spec` that runs its agent in a box, from the agent's + * own local box profile as `resolver` resolves it for a build in `region`. A project with no box + * runtime resolves nothing, and an agent with no local box profile resolves no profile. */ export async function readBoxNetworks( spec: ProjectSpec, @@ -50,15 +53,22 @@ export async function readBoxNetworks( ): Promise { const runtimes = spec.runtimes.filter((runtime) => runtimeRunsInBox(spec, runtime)); if (runtimes.length === 0) return []; - const { parsed, failures: found } = await readResolvedPolicy(projectRoot, resolver, region); // The model sees the targets build adds for the model and Memory calls, so no host takes a // second target for their endpoints. const withDefaults = structuredClone(spec); addBoxGatewayTargets(withDefaults, region); - return runtimes.flatMap((runtime) => { + const networks: BoxNetwork[] = []; + for (const runtime of runtimes) { // ProjectSpecSchema requires a Box project to keep a gateway bound to each runtime. const entry = boxGatewayOf(withDefaults, runtime.name); - if (!entry) return []; + if (!entry) continue; + // Each boxed agent reads its own .box//local profile and policy files. + const { parsed, failures: found } = await readResolvedPolicy( + projectRoot, + runtime.name, + resolver, + region, + ); const granted = grantedActions(projectRoot, entry.name, entry.additionalPolicies ?? []); const network = buildBoxNetwork(parsed, found, { spec, @@ -68,51 +78,59 @@ export async function readBoxNetworks( targets: entry.targets, grantedActions: granted.actions, }); - return [{ ...network, warnings: [...network.warnings, ...granted.warnings] }]; - }); + networks.push({ ...network, warnings: [...network.warnings, ...granted.warnings] }); + } + return networks; } /** - * Each policy file the box profile names, as an image's `.box-dist/` takes it under `agentcore - * dev`, which stages the profile itself and not the Runtime one, runs no box here, and builds no - * model. Throws, with every failure where it is, for a profile whose policy files cannot be read - * and for a policy file Box would refuse. + * Each policy file the local box profile of `agentName` names, as an image's `.box-dist/` takes it + * under `agentcore dev`, which stages the profile itself and not the Runtime one, runs no box + * here, and builds no model. Throws, with every failure where it is, for a profile whose policy + * files cannot be read and for a policy file Box would refuse. */ -export function boxPolicyFileCopies(projectRoot: string): PolicyFileCopy[] { - const text = profileText(projectRoot); +export function boxPolicyFileCopies(projectRoot: string, agentName: string): PolicyFileCopy[] { + const profileFile = boxLocalProfileFile(agentName); + const text = profileText(projectRoot, agentName); const named = - text === undefined - ? { ok: true as const, files: [] } - : profilePolicyFiles(text, BOX_PROFILE_FILE); - const policies = text === undefined ? undefined : profilePlaces(text, BOX_PROFILE_FILE).policies; - const files = readPolicyFiles(projectRoot, named.ok ? named.files : [], policies); + text === undefined ? { ok: true as const, files: [] } : profilePolicyFiles(text, profileFile); + const policies = text === undefined ? undefined : profilePlaces(text, profileFile).policies; + const files = readPolicyFiles(projectRoot, agentName, named.ok ? named.files : [], policies); const failures = [...(named.ok ? [] : [named.failure]), ...files.failures]; if (failures.length > 0) { - const lines = failureLines(failures); + const lines = failureLines(failures, profileFile); throw new ProjectStateError( [stoppedHeader("dev", lines.length, failures), ...lines].join("\n"), ); } return (named.ok ? named.files : []).map((relative) => ({ - from: join(projectRoot, BOX_PROFILE_DIR, ...relative.split("/")), + from: join(projectRoot, ...boxLocalDir(agentName).split("/"), ...relative.split("/")), relative, })); } /** - * Box's resolution of the box profile for a build in `region`, parsed, with the profile's own - * policy files to place its rules and to stage; nothing when the project has no profile. + * Box's resolution of the local box profile of `agentName` for a build in `region`, parsed, with + * the profile's own policy files to place its rules and to stage; nothing when the agent has no + * local box profile. */ async function readResolvedPolicy( projectRoot: string, + agentName: string, resolver: BoxProfileResolver, region: string, ): Promise<{ parsed: ParsedPolicy; failures: readonly BoxNetworkFailure[] }> { - const text = profileText(projectRoot); - if (text === undefined) return { parsed: NO_POLICY, failures: [] }; - const named = profilePolicyFiles(text, BOX_PROFILE_FILE); - const places = profilePlaces(text, BOX_PROFILE_FILE); - const files = readPolicyFiles(projectRoot, named.ok ? named.files : [], places.policies); + const profileFile = boxLocalProfileFile(agentName); + const text = profileText(projectRoot, agentName); + if (text === undefined) return { parsed: noPolicy(profileFile), failures: [] }; + const named = profilePolicyFiles(text, profileFile); + const places = profilePlaces(text, profileFile); + const files = readPolicyFiles( + projectRoot, + agentName, + named.ok ? named.files : [], + places.policies, + ); // The Runtime profile sets `[options] bedrock.region` to the region build builds for, so Box // resolves box/bedrock's route for that region, not the one `agentcore dev` uses. A profile with // a failure of its own stops build either way, so Box resolves it as it is. @@ -120,9 +138,9 @@ async function readResolvedPolicy( named.ok && files.failures.length === 0 ? profileForRegion(text, region) : undefined; const resolved = forRegion === undefined - ? await resolver.resolve(projectRoot, BOX_PROFILE_FILE) - : await resolveCopy(projectRoot, resolver, forRegion, files.texts); - const profile = parseResolvedProfile(resolved, named.ok ? named.files : [], BOX_PROFILE_FILE); + ? await resolver.resolve(projectRoot, profileFile) + : await resolveCopy(projectRoot, agentName, resolver, forRegion, files.texts); + const profile = parseResolvedProfile(resolved, named.ok ? named.files : [], profileFile); const policy = parseResolvedPolicy({ ...profile.profile, places }, resolved.policy, files.texts); return { parsed: policy.parsed, @@ -135,9 +153,9 @@ async function readResolvedPolicy( }; } -/** The text of the box profile, or `undefined` when the project has none. */ -function profileText(projectRoot: string): string | undefined { - const path = boxProfilePath(projectRoot); +/** The text of the local box profile of `agentName`, or `undefined` when the agent has none. */ +function profileText(projectRoot: string, agentName: string): string | undefined { + const path = boxLocalProfilePath(projectRoot, agentName); return existsSync(path) ? readFileSync(path, "utf8") : undefined; } @@ -183,21 +201,24 @@ function profileForRegion(text: string, region: string): string | undefined { } /** - * Box's resolution of the box profile `text`, from a copy in a temporary folder beside a copy of - * each policy file of `policies`. Box's errors name the profile and its folder, not the copy. + * Box's resolution of the local box profile `text` of `agentName`, from a copy in a temporary + * folder beside a copy of each policy file of `policies`. Box's errors name the profile and its + * folder, not the copy. */ async function resolveCopy( projectRoot: string, + agentName: string, resolver: BoxProfileResolver, text: string, policies: readonly PolicyFileText[], ): Promise { + const localDir = boxLocalDir(agentName); const folder = realpathSync(await mkdtemp(join(tmpdir(), "agentcore-box-profile-"))); const copy = join(folder, "profile.toml"); try { await writeFile(copy, text); for (const policy of policies) { - const to = join(folder, ...policy.file.slice(`${BOX_PROFILE_DIR}/`.length).split("/")); + const to = join(folder, ...policy.file.slice(`${localDir}/`.length).split("/")); await mkdir(dirname(to), { recursive: true }); await writeFile(to, policy.text); } @@ -206,8 +227,8 @@ async function resolveCopy( if (!(error instanceof InvalidEnvironmentError)) throw error; throw new InvalidEnvironmentError( error.message - .replaceAll(copy, BOX_PROFILE_FILE) - .replaceAll(folder, join(projectRoot, BOX_PROFILE_DIR)), + .replaceAll(copy, boxLocalProfileFile(agentName)) + .replaceAll(folder, join(projectRoot, ...localDir.split("/"))), { cause: error }, ); } finally { @@ -216,22 +237,25 @@ async function resolveCopy( } /** - * Each policy file the profile names, read as Box reads it: a regular file with one link, inside - * `.box/`, and a failure for each other one, at `policies`, the place the profile names it. + * Each policy file the local box profile of `agentName` names, read as Box reads it: a regular + * file with one link, inside `.box//local/`, and a failure for each other one, at + * `policies`, the place the profile names it. */ function readPolicyFiles( projectRoot: string, + agentName: string, files: readonly string[], - policies: string = BOX_PROFILE_FILE, + policies: string = boxLocalProfileFile(agentName), ): { texts: PolicyFileText[]; failures: BoxNetworkFailure[] } { - const folder = join(projectRoot, BOX_PROFILE_DIR); + const localDir = boxLocalDir(agentName); + const folder = join(projectRoot, ...localDir.split("/")); const texts: PolicyFileText[] = []; const failures: BoxNetworkFailure[] = []; for (const file of files) { - const shown = `${BOX_PROFILE_DIR}/${file}`; + const shown = `${localDir}/${file}`; const problem = policyPathProblem(file, shown) ?? - policyFileProblem(folder, join(folder, ...file.split("/")), file, shown); + policyFileProblem(folder, join(folder, ...file.split("/")), file, shown, localDir); if (problem !== undefined) { failures.push({ code: "INVALID_POLICY_FILE", reason: problem, place: policies }); continue; @@ -272,19 +296,23 @@ function policyPathProblem(file: string, shown: string): string | undefined { return undefined; } -/** Why Box would refuse the policy file at `path`, or `undefined` when it reads it. */ +/** + * Why Box would refuse the policy file at `path`, inside `folder`, which is `localDir` from the + * project root, or `undefined` when it reads it. + */ function policyFileProblem( folder: string, path: string, file: string, shown: string, + localDir: string, ): string | undefined { if (!existsSync(path)) { return `\`policies\` names ${file}, but ${shown} does not exist. Create it, or remove it from \`policies\`.`; } const inside = relative(realpathSync(folder), realpathSync(path)); if (inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) { - return `${shown} is a symbolic link to a file outside ${BOX_PROFILE_DIR}/, which Box does not read. Put the policy file itself in ${BOX_PROFILE_DIR}/.`; + return `${shown} is a symbolic link to a file outside ${localDir}/, which Box does not read. Put the policy file itself in ${localDir}/.`; } const stat = statSync(path); if (stat.isDirectory()) @@ -368,18 +396,21 @@ const STOPPED: Readonly> = { dev: "Dev", }; -/** One problem: where it is, then what is wrong and how to fix it. */ -function failureLine(failure: BoxNetworkFailure): string { - return `${failure.place ?? BOX_PROFILE_FILE} ${failure.reason}`; +/** + * One problem: where it is, or `profileFile` when it has no place, then what is wrong and how to + * fix it. + */ +function failureLine(failure: BoxNetworkFailure, profileFile: string): string { + return `${failure.place ?? profileFile} ${failure.reason}`; } /** * The lines of `failures`, each once, in order of file, line, and column, as a compiler lists * them; failures at one place keep their order. */ -function failureLines(failures: readonly BoxNetworkFailure[]): string[] { +function failureLines(failures: readonly BoxNetworkFailure[], profileFile: string): string[] { const key = (failure: BoxNetworkFailure) => { - const place = failure.place ?? BOX_PROFILE_FILE; + const place = failure.place ?? profileFile; const [, file = place, line = "0", column = "0"] = /^(.*?):(\d+):(\d+)$/.exec(place) ?? []; return { file, line: Number(line), column: Number(column) }; }; @@ -391,7 +422,7 @@ function failureLines(failures: readonly BoxNetworkFailure[]): string[] { a.at.line - b.at.line || a.at.column - b.at.column, ); - return unique(sorted.map(({ failure }) => failureLine(failure))); + return unique(sorted.map(({ failure }) => failureLine(failure, profileFile))); } /** `Build stopped: 2 problems in the Box profile. Build wrote nothing from the Box profile.` */ @@ -424,7 +455,9 @@ export function boxNetworkFailureMessage( networks: readonly BoxNetwork[], command: Exclude, ): string { - const lines = networks.map((network) => failureLines(network.failures)); + const lines = networks.map((network) => + failureLines(network.failures, boxLocalProfileFile(network.runtime)), + ); const shared = lines[0]?.filter((line) => lines.every((own) => own.includes(line))) ?? []; const blocks: string[] = []; let count = shared.length; diff --git a/src/core/project/boxNetworkWriters.test.ts b/src/core/project/boxNetworkWriters.test.ts index 0daa21406a..75fa678b77 100644 --- a/src/core/project/boxNetworkWriters.test.ts +++ b/src/core/project/boxNetworkWriters.test.ts @@ -461,8 +461,8 @@ describe("runtimeProfileWriter", () => { writer.writes(models, contextFor()), ); expect(files.slice(3)).toEqual([ - { path: "app/agent/.box-dist/policy.dw", copyOf: ".box/policy.dw" }, - { path: "app/agent/.box-dist/rules/extra.dw", copyOf: ".box/rules/extra.dw" }, + { path: "app/agent/.box-dist/policy.dw", copyOf: ".box/agent/local/policy.dw" }, + { path: "app/agent/.box-dist/rules/extra.dw", copyOf: ".box/agent/local/rules/extra.dw" }, ]); expect("text" in files[0]! && files[0].text).toContain( 'policies = ["policy.dw", "rules/extra.dw"]', diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 424f96765b..cbd9104a06 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -4,7 +4,7 @@ * agentcore.json: changes to agentcore.json, files, and `.env.local` entries. One output belongs * to one writer, and {@link boxNetworkEdits} refuses two writers that declare it. */ -import { copyFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { isDeepStrictEqual } from "node:util"; import type { EnvLocalEntry } from "../../handlers/project/types"; @@ -36,6 +36,8 @@ import { import { AGENTCORE_CODEZIP_PACK_PATH, AGENTCORE_PACK_PATH, + boxAwsDir, + boxLocalDir, renderAgentCoreCodeZipPack, renderAgentCorePack, renderRuntimeBoxProfile, @@ -308,8 +310,8 @@ export const defaultTargetsWriter: BoxNetworkWriter = { /** * For each box runtime, the policy that lets its execution role send the CloudWatch telemetry of - * its box profile, and the entry in that runtime's `additionalPolicies`. Every other runtime, and - * a runtime with no CloudWatch target, gets neither, and loses the file and the entry it had. + * its own box profile, and the entry in that runtime's `additionalPolicies`. Every other runtime, + * and a runtime with no CloudWatch target, gets neither, and loses the file and the entry it had. */ export const telemetryPolicyWriter: BoxNetworkWriter = { name: "telemetry policy", @@ -321,6 +323,8 @@ export const telemetryPolicyWriter: BoxNetworkWriter = { })), ], edits: (networks, { spec, projectRoot }) => { + // Each box runtime reads its own .box//local profile, so each one gets the policy of its + // own telemetry only. const files: BoxNetworkFile[] = []; const boxed: string[] = []; for (const { name } of spec.runtimes) { @@ -338,6 +342,25 @@ export const telemetryPolicyWriter: BoxNetworkWriter = { }, }; +/** + * Writes a copy of `files`, what the runtime profile writer wrote into the staged folder `dist` of + * `runtime`, into the runtime's `.box//aws/` folder, so people can read the AgentCore + * Runtime profile that deploys. The folder gets nothing else: the box release is only in `dist`. + */ +export function writeRenderedBoxFiles( + projectRoot: string, + runtime: string, + dist: string, + files: readonly BoxNetworkFile[], +): void { + const aws = boxAwsDir(runtime); + rmSync(join(projectRoot, ...aws.split("/")), { recursive: true, force: true }); + writeBoxNetworkFiles( + projectRoot, + files.map((file) => ({ ...file, path: `${aws}/${file.path.slice(dist.length + 1)}` })), + ); +} + /** One runtime's staged folder, from the project root, which holds its AgentCore Runtime profile. */ export interface StagedRuntime { readonly runtime: string; @@ -389,7 +412,7 @@ export function runtimeProfileWriter(staged: readonly StagedRuntime[]): BoxNetwo : []), ...(network?.policyFiles ?? []).map((file) => ({ path: `${dist}/${file}`, - copyOf: `.box/${file}`, + copyOf: `${boxLocalDir(runtime)}/${file}`, })), ]; }), diff --git a/src/core/project/boxProfileEgress.test.ts b/src/core/project/boxProfileEgress.test.ts index 37a9e8ac1f..a0d7cf8ab3 100644 --- a/src/core/project/boxProfileEgress.test.ts +++ b/src/core/project/boxProfileEgress.test.ts @@ -52,20 +52,22 @@ describe("readBoxEnvRoutes", () => { await Promise.all(directories.splice(0).map((d) => rm(d, { recursive: true, force: true }))); }); - test("reads the project's .box/profile.toml, or is undefined with no profile", async () => { + test("reads the agent's .box//local/profile.toml, or is undefined with none", async () => { const root = await mkdtemp(join(tmpdir(), "box-profile-egress-")); directories.push(root); - expect(readBoxEnvRoutes(root)).toBeUndefined(); + expect(readBoxEnvRoutes(root, "agent")).toBeUndefined(); - await mkdir(join(root, ".box")); + await mkdir(join(root, ".box", "agent", "local"), { recursive: true }); await writeFile( - join(root, ".box", "profile.toml"), + join(root, ".box", "agent", "local", "profile.toml"), '[egress.github]\nsecret.ref = "env://GITHUB_TOKEN"\n', ); - expect(readBoxEnvRoutes(root)).toEqual({ + expect(readBoxEnvRoutes(root, "agent")).toEqual({ routes: [{ route: "github", variable: "GITHUB_TOKEN" }], }); + // The profile of one agent is not the profile of another agent. + expect(readBoxEnvRoutes(root, "second")).toBeUndefined(); }); }); diff --git a/src/core/project/boxProfileEgress.ts b/src/core/project/boxProfileEgress.ts index 0dcf867a85..d655f01005 100644 --- a/src/core/project/boxProfileEgress.ts +++ b/src/core/project/boxProfileEgress.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from "node:fs"; import { parse as parseToml } from "smol-toml"; -import { boxProfilePath } from "./templates/boxProfile"; +import { boxLocalProfilePath } from "./templates/boxProfile"; const ENV_SCHEME = "env://"; @@ -42,11 +42,11 @@ export function parseBoxEnvRoutes(text: string): BoxEnvRoutes { } /** - * The `env://` routes of the box profile of the project at `projectRoot`, or `undefined` when the - * project has no box profile. + * The `env://` routes of the local box profile of agent `agentName` in the project at + * `projectRoot`, or `undefined` when the agent has no local box profile. */ -export function readBoxEnvRoutes(projectRoot: string): BoxEnvRoutes | undefined { - const path = boxProfilePath(projectRoot); +export function readBoxEnvRoutes(projectRoot: string, agentName: string): BoxEnvRoutes | undefined { + const path = boxLocalProfilePath(projectRoot, agentName); if (!existsSync(path)) return undefined; return parseBoxEnvRoutes(readFileSync(path, "utf8")); } diff --git a/src/core/project/boxValidation.test.ts b/src/core/project/boxValidation.test.ts new file mode 100644 index 0000000000..06336b4c51 --- /dev/null +++ b/src/core/project/boxValidation.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, test } from "bun:test"; +import type { ProjectSpec } from "../../projectSchemas/project"; +import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { BOX_RELEASE } from "./backends/boxRelease"; +import { + assertBoxCodeZipRuntimesStartBox, + assertBoxRuntimesHaveBoxVersion, + assertNoBoxContainerSwitch, + syncKeepsBoxEntrypoint, + validateBoxRuntimes, +} from "./boxValidation"; + +/** A box runtime `agent`, as create writes it for a CodeZip box template, with `overrides`. */ +function boxRuntime(overrides: Partial = {}): ProjectRuntime { + return { + name: "agent", + build: "CodeZip", + entrypoint: "start.py", + codeLocation: "app/agent", + runtimeVersion: "PYTHON_3_14", + protocol: "HTTP", + box: { version: BOX_RELEASE.version }, + ...overrides, + } as ProjectRuntime; +} + +/** A project with `runtime`: a Box project unless `boxProject` is false. */ +function spec(runtime: ProjectRuntime, boxProject = true): ProjectSpec { + return { + name: "demo", + ...(boxProject && { projectType: "box" }), + runtimes: [runtime], + } as unknown as ProjectSpec; +} + +describe("assertBoxRuntimesHaveBoxVersion", () => { + test.each(["Container", "CodeZip"] as const)( + "refuses a %s runtime of a Box project with no box.version, and names the pinned release", + (build) => { + const { box: _box, ...runtime } = boxRuntime({ build }); + + expect(() => assertBoxRuntimesHaveBoxVersion(spec(runtime as ProjectRuntime))).toThrow( + 'runtime "agent" has no box.version in agentcore.json, but every runtime of a Box ' + + `project runs in a box. Add "box": { "version": "${BOX_RELEASE.version}" } to the ` + + "runtime in agentcore.json, then retry.", + ); + }, + ); + + test.each([ + ["a Box project whose runtimes have box.version", spec(boxRuntime())], + [ + "a runtime with no box.version outside a Box project", + spec(boxRuntime({ box: undefined }), false), + ], + ])("accepts %s", (_, project) => { + expect(() => assertBoxRuntimesHaveBoxVersion(project)).not.toThrow(); + }); +}); + +describe("assertBoxCodeZipRuntimesStartBox", () => { + test("refuses a CodeZip box runtime whose entrypoint is not start.py", () => { + expect(() => + assertBoxCodeZipRuntimesStartBox(spec(boxRuntime({ entrypoint: "main.py" }))), + ).toThrow( + 'runtime "agent" runs its agent in a box (it has box.version in agentcore.json), but its ' + + "entrypoint is main.py, so AgentCore Runtime would run the agent with no box. Set " + + '"entrypoint": "start.py" for the runtime in agentcore.json, and keep start.py in ' + + "app/agent, then retry.", + ); + }); + + test.each([ + ["start.py", spec(boxRuntime())], + ["start.py with a handler", spec(boxRuntime({ entrypoint: "start.py:main" }))], + // A container image starts box itself, whatever its entrypoint. + ["a container runtime", spec(boxRuntime({ build: "Container", entrypoint: "main.py" }))], + ["a runtime with no box", spec(boxRuntime({ box: undefined, entrypoint: "main.py" }))], + ["a runtime outside a Box project", spec(boxRuntime({ entrypoint: "main.py" }), false)], + ])("accepts %s", (_, project) => { + expect(() => assertBoxCodeZipRuntimesStartBox(project)).not.toThrow(); + }); +}); + +describe("validateBoxRuntimes", () => { + test("runs both checks", () => { + expect(() => validateBoxRuntimes(spec(boxRuntime({ box: undefined })))).toThrow( + "has no box.version", + ); + expect(() => validateBoxRuntimes(spec(boxRuntime({ entrypoint: "main.py" })))).toThrow( + "but its entrypoint is main.py", + ); + expect(() => validateBoxRuntimes(spec(boxRuntime()))).not.toThrow(); + }); +}); + +describe("assertNoBoxContainerSwitch", () => { + test("refuses to make a CodeZip box runtime a container build, and names the box template", () => { + expect(() => assertNoBoxContainerSwitch(true, boxRuntime(), "app/agent/")).toThrow( + 'runtime "agent" runs its agent in a box as a CodeZip agent, but app/agent/ has a ' + + "Dockerfile, which would make it a container build that runs the agent with no box. " + + "Remove the Dockerfile, or create the agent from the agent-python-strands-box-container " + + "template, whose image starts box.", + ); + }); + + test.each([ + ["outside a Box project", false, boxRuntime()], + ["for a runtime with no box", true, boxRuntime({ box: undefined })], + ["for a container runtime", true, boxRuntime({ build: "Container" })], + ])("accepts the switch %s", (_, boxProject, runtime) => { + expect(() => assertNoBoxContainerSwitch(boxProject, runtime, "app/agent/")).not.toThrow(); + }); +}); + +describe("syncKeepsBoxEntrypoint", () => { + test.each([ + ["a CodeZip box runtime with start.py", true, boxRuntime(), true], + ["a runtime outside a Box project", false, boxRuntime(), false], + ["a runtime with no box", true, boxRuntime({ box: undefined }), false], + [ + "a box runtime whose entrypoint is not start.py", + true, + boxRuntime({ entrypoint: "main.py" }), + false, + ], + ["a container box runtime", true, boxRuntime({ build: "Container" }), false], + ])("is right for %s", (_, boxProject, runtime, expected) => { + expect(syncKeepsBoxEntrypoint(boxProject, runtime)).toBe(expected); + }); +}); diff --git a/src/core/project/boxValidation.ts b/src/core/project/boxValidation.ts new file mode 100644 index 0000000000..6339514039 --- /dev/null +++ b/src/core/project/boxValidation.ts @@ -0,0 +1,102 @@ +/** + * The rules a runtime that runs in a box ({@link runsInBox}) must keep, so that it does not run its + * agent with no box. The runtime sync asks the sync rules before it writes agentcore.json, and + * build and deploy call {@link validateBoxRuntimes} before they read the box profiles. + */ +import { ProjectStateError } from "../../errors/errors"; +import { isBoxProject, type ProjectSpec } from "../../projectSchemas/project"; +import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { BOX_RELEASE } from "./backends/boxRelease"; +import { BOX_CODEZIP_ENTRYPOINT, runsInBox } from "./templates/boxProfile"; + +/** The box template whose image starts box itself, for a runtime that needs a container build. */ +const BOX_CONTAINER_TEMPLATE = "agent-python-strands-box-container"; + +/** + * Whether the runtime sync keeps the entrypoint of `runtime`: a CodeZip runtime that runs in a box + * starts box with start.py, and its box profile runs the agent. So `[tool.agentcore] entrypoint` + * names the agent, not the entry point AgentCore Runtime runs. + */ +export function syncKeepsBoxEntrypoint(boxProject: boolean, runtime: ProjectRuntime): boolean { + return ( + runsInBox(boxProject, runtime) && + runtime.build === "CodeZip" && + runtime.entrypoint === BOX_CODEZIP_ENTRYPOINT + ); +} + +/** The warning the runtime sync gives when it keeps start.py over the manifest's `entrypoint`. */ +export function keptBoxEntrypointWarning(runtimeName: string, reason: string, value: string) { + return ( + `runtime "${runtimeName}" runs its agent in a box, so its entrypoint stays ` + + `${BOX_CODEZIP_ENTRYPOINT}, which starts box, and its box profile runs the agent. ` + + `${reason} names ${value}, which is not used.` + ); +} + +/** + * Throws when the runtime sync would switch `runtime`, a CodeZip runtime that runs in a box, to a + * container build because of the Dockerfile in `contextLabel`. The runtime keeps its box profile + * and Box gateway, but the user's Dockerfile does not start box, and the CodeZip box profile does + * not run an agent in an image. So the agent would run with no box. + */ +export function assertNoBoxContainerSwitch( + boxProject: boolean, + runtime: ProjectRuntime, + contextLabel: string, +): void { + if (!runsInBox(boxProject, runtime) || runtime.build !== "CodeZip") return; + throw new ProjectStateError( + `runtime "${runtime.name}" runs its agent in a box as a CodeZip agent, but ${contextLabel} ` + + "has a Dockerfile, which would make it a container build that runs the agent with no box. " + + `Remove the Dockerfile, or create the agent from the ${BOX_CONTAINER_TEMPLATE} template, ` + + "whose image starts box.", + ); +} + +/** + * Throws for a runtime of a Box project with no `box.version`. Every runtime of a Box project runs + * in a box, and only `box.version` makes it do so, so without it build would stage no box and the + * agent could not start on AgentCore Runtime. `agentcore create` writes it with the box release + * this CLI pins. + */ +export function assertBoxRuntimesHaveBoxVersion(spec: ProjectSpec): void { + if (!isBoxProject(spec)) return; + for (const runtime of spec.runtimes) { + if (runtime.box !== undefined) continue; + throw new ProjectStateError( + `runtime "${runtime.name}" has no box.version in agentcore.json, but every runtime of a Box ` + + `project runs in a box. Add "box": { "version": "${BOX_RELEASE.version}" } to the ` + + "runtime in agentcore.json, then retry.", + ); + } +} + +/** + * Throws for a CodeZip runtime that runs in a box but whose entrypoint is not start.py. Only + * start.py starts box on AgentCore Runtime, so another entrypoint would run the agent with no + * box, while build still writes its box profile and Box gateway. + */ +export function assertBoxCodeZipRuntimesStartBox(spec: ProjectSpec): void { + for (const runtime of spec.runtimes) { + if (runtime.build !== "CodeZip" || !runsInBox(isBoxProject(spec), runtime)) continue; + const [file = ""] = runtime.entrypoint.split(":"); + if (file === BOX_CODEZIP_ENTRYPOINT) continue; + throw new ProjectStateError( + `runtime "${runtime.name}" runs its agent in a box (it has box.version in agentcore.json), ` + + `but its entrypoint is ${runtime.entrypoint}, so AgentCore Runtime would run the agent ` + + `with no box. Set "entrypoint": "${BOX_CODEZIP_ENTRYPOINT}" for the runtime in ` + + `agentcore.json, and keep ${BOX_CODEZIP_ENTRYPOINT} in ${runtime.codeLocation}, then retry.`, + ); + } +} + +/** + * The checks build and deploy run on the synced `spec`, before they read the box profiles or + * write anything: every runtime of a Box project has `box.version`, and each CodeZip one starts + * box. + */ +export function validateBoxRuntimes(spec: ProjectSpec): void { + assertBoxRuntimesHaveBoxVersion(spec); + assertBoxCodeZipRuntimesStartBox(spec); +} diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 2f57937fc1..663a0400e1 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -1,20 +1,16 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { existsSync } from "node:fs"; -import { - InputValidationError, - ProjectStateError, - ResourceNotFoundError, -} from "../../errors/errors"; +import { InputValidationError, ResourceNotFoundError } from "../../errors/errors"; import type { AddResourceInput, Project } from "../../handlers/project/types"; import { resolveRuntimeTemplateShortcut } from "../../handlers/project/shortcuts"; import { createSilentLogger, TestIdentityClient } from "../../testing"; import { BOX_RELEASE } from "./backends/boxRelease"; import { FsProjectManager } from "./manager"; import { newProjectSpec } from "./templates/project"; -import { boxGatewaySpec } from "../../projectSchemas/project"; +import { boxGatewaySpec, ProjectSpecSchema } from "../../projectSchemas/project"; /** * `"projectType": "box"` is written by `agentcore create` from a Box template only. A Box project @@ -54,8 +50,8 @@ async function drain(generator: AsyncGenerator): Promise { /** * A Box project with the given box runtimes, as `newProjectSpec` writes one for a Box template: * `projectType: "box"`, `box.version` on each runtime, and the gateway `-box-egress` for - * each. `add runtime` refuses a Box project, so the runtimes are written here. Two runtimes are a - * project edited by hand; they check that each gateway stays bound to its own runtime. + * each. The runtimes are written here, so a test can make a project with two. They check that + * each gateway stays bound to its own runtime. */ async function createdProject( manager: FsProjectManager, @@ -145,6 +141,9 @@ async function existingProject(manager: FsProjectManager): Promise { const specText = (project: Project) => readFile(join(project.rootPath, "agentcore", "agentcore.json"), "utf8"); +/** The spec on disk, parsed, for a test that reads runtimes or gateway bindings. */ +const parsedSpec = async (project: Project) => + ProjectSpecSchema.parse(JSON.parse(await specText(project))); const specOnDisk = async (project: Project) => JSON.parse(await specText(project)) as Record & { agentCoreGateways: { name: string; targets: { name: string }[] }[]; @@ -323,7 +322,39 @@ describe("gateway targets in a Box project", () => { expect(await specText(project)).toBe(before); }); - test("add runtime is refused, and changes nothing: a Box project holds one runtime", async () => { + test("add runtime gives the new runtime a box, its Box gateway, and its own box profile", async () => { + const manager = subject(); + const project = await createdProject(manager); + + const events: unknown[] = []; + const generator = manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never); + for (let next = await generator.next(); !next.done; next = await generator.next()) { + events.push(next.value); + } + + const spec = await parsedSpec(project); + const search = spec.runtimes.find(({ name }) => name === "search")!; + expect(search.box).toEqual({ version: BOX_RELEASE.version }); + expect(search.entrypoint).toBe("start.py"); + expect(spec.agentCoreGateways.find(({ boundRuntime }) => boundRuntime === "search")).toEqual( + expect.objectContaining(boxGatewaySpec("search")), + ); + const profile = join(project.rootPath, ".box", "search", "local", "profile.toml"); + expect(await readFile(profile, "utf8")).toContain("${{ workspace }}/app/search"); + expect(events).toContainEqual({ type: "step", message: `writing box profile ${profile}` }); + expect(existsSync(join(project.rootPath, "app", "search", "start.py"))).toBe(true); + expect(existsSync(join(project.rootPath, "app", "search", ".venv"))).toBe(true); + // The first runtime keeps its own profile folder and gateway. + expect(spec.agentCoreGateways.map(({ boundRuntime }) => boundRuntime)).toEqual([ + "agent", + "search", + ]); + }); + + test("add runtime refuses a Bedrock Agent import in a Box project, and changes nothing", async () => { const manager = subject(); const project = await createdProject(manager); const before = await specText(project); @@ -331,17 +362,263 @@ describe("gateway targets in a Box project", () => { const add = drain( manager.addResource(project, { resourceType: "runtime", - resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + resourceConfig: { + name: "search", + scaffoldRuntimeInput: { + runtimeName: "search", + build: "CodeZip", + language: "Python", + framework: "none", + modelProvider: "Bedrock", + runtimeVersion: "PYTHON_3_14", + }, + importBedrockAgent: {}, + }, } as never), ); - await expect(add).rejects.toBeInstanceOf(ProjectStateError); await expect(add).rejects.toThrow( - "cannot add runtime 'search': a Box project holds one runtime, which `agentcore create` " + - "makes from a box template", + "cannot add runtime 'search' to a Box project from a Bedrock Agent import", ); expect(await specText(project)).toBe(before); expect(existsSync(join(project.rootPath, "app", "search"))).toBe(false); + expect(existsSync(join(project.rootPath, ".box", "search"))).toBe(false); + }); + + // A read-only agentcore folder makes the spec write fail after the box files are written. + // Windows has no mode bits, and root writes through them. + test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "a failed add runtime removes the box files it made, and keeps what was there", + async () => { + const manager = subject(); + const project = await createdProject(manager); + // A code folder the user already has, with a file of their own. + const app = join(project.rootPath, "app", "search"); + await mkdir(app, { recursive: true }); + await writeFile(join(app, "notes.txt"), "mine\n"); + const agentcore = join(project.rootPath, "agentcore"); + const spec = join(agentcore, "agentcore.json"); + await chmod(spec, 0o444); + await chmod(agentcore, 0o555); + + try { + await expect( + drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never), + ), + ).rejects.toThrow(); + } finally { + await chmod(agentcore, 0o755); + await chmod(spec, 0o644); + } + + expect(existsSync(join(project.rootPath, ".box", "search"))).toBe(false); + expect(existsSync(join(app, "start.py"))).toBe(false); + expect(existsSync(join(app, ".venv"))).toBe(false); + expect(await readFile(join(app, "notes.txt"), "utf8")).toBe("mine\n"); + }, + ); + + test("add runtime again after remove runtime keeps the local profile the user had", async () => { + const manager = subject(); + let project = await createdProject(manager, ["agent", "search"]); + const local = join(project.rootPath, ".box", "search", "local", "profile.toml"); + await mkdir(dirname(local), { recursive: true }); + await writeFile(local, "# the user's profile\n"); + project = (await manager.removeResource(project, { resourceType: "runtime", name: "search" })) + .project; + + const events: unknown[] = []; + const generator = manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never); + for (let next = await generator.next(); !next.done; next = await generator.next()) { + events.push(next.value); + } + + expect(await readFile(local, "utf8")).toBe("# the user's profile\n"); + expect(events).toContainEqual({ + type: "warning", + message: `box profile ${local} already exists; left unchanged`, + }); + const spec = await parsedSpec(project); + expect(spec.agentCoreGateways.map(({ boundRuntime }) => boundRuntime)).toEqual([ + "agent", + "search", + ]); + }); + + test("add runtime refuses a start.py of the user's own, and changes nothing", async () => { + const manager = subject(); + const project = await createdProject(manager); + const app = join(project.rootPath, "app", "mine"); + await mkdir(app, { recursive: true }); + await writeFile(join(app, "start.py"), "print('mine')\n"); + const before = await specText(project); + + const add = drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "mine", language: "Python", protocol: "HTTP" }, + } as never), + ); + + await expect(add).rejects.toThrow( + new InputValidationError( + "cannot add runtime 'mine' to a Box project: app/mine/start.py exists, and it is not the " + + "start.py that starts box. A box runtime runs start.py as its entry point, so AgentCore " + + "Runtime would run your file with no box. Rename app/mine/start.py, then retry.", + ), + ); + expect(await specText(project)).toBe(before); + expect(await readFile(join(app, "start.py"), "utf8")).toBe("print('mine')\n"); + expect(existsSync(join(project.rootPath, ".box", "mine"))).toBe(false); + }); + + test("add runtime keeps a start.py that is the one that starts box", async () => { + const manager = subject(); + const project = await createdProject(manager); + const app = join(project.rootPath, "app", "mine"); + await mkdir(app, { recursive: true }); + const boxStart = await readFile( + join(import.meta.dir, "..", "..", "assets", "templates", "box-codezip", "start.py"), + "utf8", + ); + await writeFile(join(app, "start.py"), boxStart); + + await drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "mine", language: "Python", protocol: "HTTP" }, + } as never), + ); + + const spec = await parsedSpec(project); + expect(spec.runtimes.find(({ name }) => name === "mine")?.entrypoint).toBe("start.py"); + }); + + test("add runtime writes the Bedrock region of the command into the box profile", async () => { + const manager = subject(); + const project = await createdProject(manager); + + await drain( + manager.addResource( + project, + { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never, + { region: "eu-west-1" }, + ), + ); + + const profile = join(project.rootPath, ".box", "search", "local", "profile.toml"); + expect(await readFile(profile, "utf8")).toContain('bedrock.region = "eu-west-1"'); + }); + + test("a failed box profile write removes what add runtime made", async () => { + const manager = subject(); + const project = await createdProject(manager); + // A file where the box folder of "search" goes makes the profile write fail. + const blocked = join(project.rootPath, ".box", "search"); + await mkdir(dirname(blocked), { recursive: true }); + await writeFile(blocked, "not a folder\n"); + const before = await specText(project); + + await expect( + drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never), + ), + ).rejects.toThrow(); + + expect(await specText(project)).toBe(before); + expect(existsSync(join(project.rootPath, "app", "search"))).toBe(false); + // The file was there before the add, so it stays. + expect(await readFile(blocked, "utf8")).toBe("not a folder\n"); + }); + + test("add runtime warns when the kept box profile is for another protocol", async () => { + const manager = subject(); + let project = await createdProject(manager, ["agent", "search"]); + const local = join(project.rootPath, ".box", "search", "local", "profile.toml"); + await mkdir(dirname(local), { recursive: true }); + await writeFile(local, '[[agent.ingress]]\nlisten = "127.0.0.1:8080"\n'); + project = (await manager.removeResource(project, { resourceType: "runtime", name: "search" })) + .project; + + const events: unknown[] = []; + const generator = manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "MCP" }, + } as never); + for (let next = await generator.next(); !next.done; next = await generator.next()) { + events.push(next.value); + } + + expect(events).toContainEqual({ + type: "warning", + message: + `box profile ${local} is for another protocol: it listens on port 8080, and a MCP ` + + `runtime listens on port 8000. Remove ${dirname(local)}, then add the runtime again, or ` + + "edit the profile.", + }); + }); + + test("add runtime refuses a TypeScript runtime in a Box project, and changes nothing", async () => { + const manager = subject(); + const project = await createdProject(manager); + const before = await specText(project); + + const add = drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "TypeScript", protocol: "HTTP" }, + } as never), + ); + + await expect(add).rejects.toThrow( + new InputValidationError( + "cannot add runtime 'search' to a Box project: every runtime of a Box project runs in a " + + "box, and add runtime adds a box runtime only as a Python CodeZip agent. Add it with " + + "--language python.", + ), + ); + expect(await specText(project)).toBe(before); + expect(existsSync(join(project.rootPath, "app", "search"))).toBe(false); + expect(existsSync(join(project.rootPath, ".box", "search"))).toBe(false); + }); + + test("add runtime refuses a name whose Box gateway name is taken, and changes nothing", async () => { + const manager = subject(); + const project = await createdProject(manager); + // A gateway of the user's own that has the name the Box gateway of "search" needs. + const path = join(project.rootPath, "agentcore", "agentcore.json"); + const onDisk = await specOnDisk(project); + onDisk.agentCoreGateways.push({ + name: "search-box-egress", + authorizerType: "AWS_IAM", + targets: [], + } as never); + await writeFile(path, JSON.stringify(onDisk, null, 2)); + const before = await specText(project); + + const add = drain( + manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never), + ); + + await expect(add).rejects.toThrow("its Box gateway needs the name 'search-box-egress'"); + expect(await specText(project)).toBe(before); + expect(existsSync(join(project.rootPath, "app", "search"))).toBe(false); }); test("add gateway --name other-box-egress works: only the prefix must be unique", async () => { @@ -416,6 +693,24 @@ describe("gateway targets in a Box project", () => { expect(result.removedGateways).toEqual([{ name: "agent-box-egress", targetCount: 1 }]); }); + test("remove runtime removes its generated .box//aws/, and keeps its local profile", async () => { + const manager = subject(); + const project = await createdProject(manager, ["agent", "my_agent"]); + const box = join(project.rootPath, ".box"); + await mkdir(join(box, "agent", "aws"), { recursive: true }); + await writeFile(join(box, "agent", "aws", "profile.toml"), "# generated\n"); + await mkdir(join(box, "agent", "local"), { recursive: true }); + await writeFile(join(box, "agent", "local", "profile.toml"), "# the user's\n"); + await mkdir(join(box, "my_agent", "aws"), { recursive: true }); + + await manager.removeResource(project, { resourceType: "runtime", name: "agent" }); + + expect(existsSync(join(box, "agent", "aws"))).toBe(false); + expect(existsSync(join(box, "agent", "local", "profile.toml"))).toBe(true); + // The folder of another runtime stays. + expect(existsSync(join(box, "my_agent", "aws"))).toBe(true); + }); + test("remove runtime finds the gateways to remove by boundRuntime", async () => { const manager = subject(); let project = await createdProject(manager, ["agent", "search"]); @@ -457,20 +752,23 @@ describe("gateway targets in a Box project", () => { expect(spec.agentCoreGateways).toEqual([]); }); - test("remove all, then add runtime, is refused, as the project is still a Box project", async () => { + test("remove all, then add runtime, adds a box runtime, as the project is still a Box project", async () => { const manager = subject(); let project = await createdProject(manager); project = (await manager.removeAllResources(project)).project; - const add = drain( + await drain( manager.addResource(project, { resourceType: "runtime", resourceConfig: { name: "agent", language: "Python", protocol: "HTTP" }, } as never), ); - await expect(add).rejects.toBeInstanceOf(ProjectStateError); - expect((await specOnDisk(project)).agentCoreGateways).toEqual([]); + const spec = await parsedSpec(project); + expect(spec.runtimes.map(({ name, box }) => [name, box])).toEqual([ + ["agent", { version: BOX_RELEASE.version }], + ]); + expect(spec.agentCoreGateways.map(({ boundRuntime }) => boundRuntime)).toEqual(["agent"]); }); }); diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 715cf773fe..48dbe4586d 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -6,7 +6,7 @@ import { FsProjectManager } from "./manager"; import type { Project, ProjectEvent } from "../../handlers/project/types"; import type { ProjectBackend } from "./backends/types"; import { ENV_LOCAL_RELATIVE_PATH, EnvLocalFile } from "./envLocal"; -import { BOX_PROFILE_FILE } from "./templates/boxProfile"; +import { boxLocalDir, boxLocalProfileFile } from "./templates/boxProfile"; import { boxShowOf, FakeBoxProfileResolver } from "./boxProfileResolver-test-support"; import { resolveRuntimeTemplateShortcut } from "../../handlers/project/shortcuts"; import { credentialEnvVarName } from "../../projectSchemas/credential"; @@ -14,6 +14,8 @@ import { createSilentLogger, TestIdentityClient } from "../../testing"; // A box template: only it writes the box profile whose env:// secrets build provisions. const AGENT_PYTHON = resolveRuntimeTemplateShortcut("agent-python-strands-box"); +/** The local box profile of the template's runtime, from the project root. */ +const BOX_PROFILE_FILE = boxLocalProfileFile(AGENT_PYTHON.runtimeName); const GITHUB_PROFILE = '[egress.github]\ndestinations = ["api.github.com"]\nsecret.ref = "env://GITHUB_TOKEN"\n'; /** What box resolves {@link GITHUB_PROFILE} to. */ @@ -75,7 +77,7 @@ async function project(subject: FsProjectManager, profile: string): Promise join(root, ...relative.split("/")); const text = (root: string, relative: string) => readFile(path(root, relative), "utf8"); -/** Adds `tables` to the end of the profile, `top` to its start, and writes `.box/policy.dw`. */ +/** Adds `tables` to the end of the profile, `top` to its start, and writes `.box/agent_python_strands/local/policy.dw`. */ async function editProfile(root: string, edit: { top?: string; tables?: string; policy?: string }) { const profile = await text(root, PROFILE); await writeFile(path(root, PROFILE), `${edit.top ?? ""}${profile}${edit.tables ?? ""}`); - if (edit.policy !== undefined) await writeFile(path(root, ".box/policy.dw"), edit.policy); + if (edit.policy !== undefined) + await writeFile(path(root, ".box/agent_python_strands/local/policy.dw"), edit.policy); } /** Changes the Box gateway entry of agentcore.json, as a user does by hand. */ @@ -218,11 +219,16 @@ async function runtimeProfile(root: string): Promise> { return parse(await text(root, RUNTIME_PROFILE)) as Record; } -/** The text of every file under `.box/`, by path. */ +/** The text of every file under `.box/agent_python_strands/local/`, by path. */ async function boxFiles(root: string): Promise> { - const names = (await readdir(path(root, ".box"))).sort(); + const names = (await readdir(path(root, ".box/agent_python_strands/local"))).sort(); return Object.fromEntries( - await Promise.all(names.map(async (name) => [name, await text(root, `.box/${name}`)])), + await Promise.all( + names.map(async (name) => [ + name, + await text(root, `.box/agent_python_strands/local/${name}`), + ]), + ), ); } @@ -549,7 +555,7 @@ describe("build writes the Box network of the box profile", () => { "agentcore/agentcore.json The gateway target 'gh' for api.github.com sends no " + "credential, and [egress.github] sends the API key credential 'github' in the header " + "Authorization with the prefix Bearer. Make the two the same, in agentcore.json or in " + - ".box/profile.toml.", + ".box/agent_python_strands/local/profile.toml.", ); expect(await text(root, SPEC)).toBe(spec); }); @@ -720,7 +726,7 @@ describe("build writes the telemetry policy of the box profile", () => { TRACES_STATEMENT, ]); expect(warnings).toContain( - ".box/profile.toml: [telemetry.logs] has no region, so the AgentCore Runtime profile and " + + ".box/agent_python_strands/local/profile.toml: [telemetry.logs] has no region, so the AgentCore Runtime profile and " + "the telemetry policy get eu-central-1. Deploy sets the region of its deploy target. " + "Box refuses a CloudWatch target with no region, so `agentcore dev` cannot run this " + "profile until you add region to it.", @@ -809,7 +815,7 @@ describe("build reads the box profile as box resolves it", () => { test("stops with box's error when box refuses the profile, and writes nothing", async () => { const { manager, root, counter, box } = await strandsProject(); box.answer = new InvalidEnvironmentError( - "`box profile show .box/profile.toml --format json --full` failed in the project (exit code 1)", + "`box profile show .box/agent_python_strands/local/profile.toml --format json --full` failed in the project (exit code 1)", ); const spec = await text(root, SPEC); diff --git a/src/core/project/manager.export.test.ts b/src/core/project/manager.export.test.ts index 0221a15e59..ebb11e4434 100644 --- a/src/core/project/manager.export.test.ts +++ b/src/core/project/manager.export.test.ts @@ -488,7 +488,7 @@ describe("FsProjectManager.exportHarness rendered tree", () => { ); }); - test("refuses to export a harness into a Box project, which holds one runtime", async () => { + test("refuses to export a harness into a Box project, whose runtimes run in a box", async () => { const { manager: subject } = manager(); // A box template makes a Box project. const project = await projectWithHarness(subject, {}, "agent-python-strands-box"); @@ -496,7 +496,8 @@ describe("FsProjectManager.exportHarness rendered tree", () => { const before = await Bun.file(join(project.rootPath, "agentcore", "agentcore.json")).text(); await expect(drain(subject.exportHarness(project, exportInput()))).rejects.toThrow( - "cannot add the exported harness as a runtime: a Box project holds one runtime", + "cannot add the exported harness as a runtime: every runtime of a Box project runs in a " + + "box, and the exported harness does not.", ); expect(await Bun.file(join(project.rootPath, "agentcore", "agentcore.json")).text()).toBe( before, diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index f6681887b3..0e8817c4d2 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -46,7 +46,7 @@ import { type AddResourceOptions, } from "../../handlers/project/types"; import { createSilentLogger, TestIdentityClient } from "../../testing"; -import { BOX_PROFILE_FILE, boxProfileWarnings, renderBoxProfile } from "./templates/boxProfile"; +import { boxLocalProfileFile, boxProfileWarnings, renderBoxProfile } from "./templates/boxProfile"; import type { DeployBackendInput, ProjectBackend } from "./backends/types"; import { BOX_INSTALL_HINT, BOX_RELEASE } from "./backends/boxRelease"; import { MissingToolError } from "../../io/exec"; @@ -63,6 +63,7 @@ const AGENT_PYTHON_STRANDS_BOX = resolveRuntimeTemplateShortcut("agent-python-st const AGENT_PYTHON_STRANDS_BOX_CONTAINER = resolveRuntimeTemplateShortcut( "agent-python-strands-box-container", ); +const BOX_PROFILE_FILE = boxLocalProfileFile(AGENT_PYTHON_STRANDS_BOX.runtimeName); const AGENT_TYPESCRIPT_STRANDS = resolveRuntimeTemplateShortcut("agent-typescript-strands"); const A2A_PYTHON_STRANDS = resolveRuntimeTemplateShortcut("a2a-python-strands"); const AGUI_PYTHON_STRANDS = resolveRuntimeTemplateShortcut("agui-python-strands"); @@ -815,25 +816,46 @@ describe("FsProjectManager.create", () => { describe("FsProjectManager.create box profile", () => { test.each([ - ["after installing", false], - ["with --skip-install", true], - ])("writes the box profile into the project's .box folder %s", async (_label, skipInstall) => { + ["a Box project gets the Box lines", AGENT_PYTHON_STRANDS_BOX, true], + ["a project with no box matches v1.x", AGENT_PYTHON, false], + ])("writes .gitignore: %s", async (_label, scaffoldRuntimeInput, boxed) => { const directory = await inTempDirectory(); - const { events } = await runCreate(manager().manager, { + await runCreate(manager().manager, { name: "example", - scaffoldRuntimeInput: AGENT_PYTHON_STRANDS_BOX, - skipInstall, + scaffoldRuntimeInput, + skipInstall: true, skipGit: true, - region: "eu-west-1", }); - const path = join(directory, "example", BOX_PROFILE_FILE); - expect(await readFile(path, "utf8")).toBe( - renderBoxProfile("example", AGENT_PYTHON_STRANDS_BOX, "eu-west-1")!, - ); - expect(events).toContainEqual({ type: "step", message: `writing box profile ${path}` }); + const gitignore = await readFile(join(directory, "example", ".gitignore"), "utf8"); + for (const line of [".box/*/aws/", ".box-dist/", ".box-dev/"]) { + expect(gitignore.split("\n").includes(line)).toBe(boxed); + } }); + test.each([ + ["after installing", false], + ["with --skip-install", true], + ])( + "writes the box profile into the agent's .box//local folder %s", + async (_label, skipInstall) => { + const directory = await inTempDirectory(); + const { events } = await runCreate(manager().manager, { + name: "example", + scaffoldRuntimeInput: AGENT_PYTHON_STRANDS_BOX, + skipInstall, + skipGit: true, + region: "eu-west-1", + }); + + const path = join(directory, "example", BOX_PROFILE_FILE); + expect(await readFile(path, "utf8")).toBe( + renderBoxProfile("example", AGENT_PYTHON_STRANDS_BOX, "eu-west-1")!, + ); + expect(events).toContainEqual({ type: "step", message: `writing box profile ${path}` }); + }, + ); + test("warns when a LiteLLM agent's box profile reads a key that nothing set", async () => { await inTempDirectory(); const runtime = resolveRuntimeTemplateShortcut("agent-python-strands-box", { @@ -873,7 +895,7 @@ describe("FsProjectManager.create box profile", () => { test("leaves an existing box profile unchanged", async () => { const directory = await inTempDirectory(); const path = join(directory, "example", BOX_PROFILE_FILE); - await mkdir(join(directory, "example", ".box"), { recursive: true }); + await mkdir(join(path, ".."), { recursive: true }); await writeFile(path, "# mine\n"); const { events } = await runCreate(manager().manager, { @@ -2105,10 +2127,16 @@ describe("FsProjectManager.build", () => { { type: "step", message: "writing agentcore/box-memory-policy.json" }, { type: "step", message: "synthesizing CloudFormation templates" }, ]); - // The zip carries box and the Runtime profile, staged before synth packages the code. + // The zip carries box and the Runtime profile in the code folder's .box-dist. const dist = join(directory, "example", "app", "agent_python_strands_box", ".box-dist"); expect(existsSync(join(dist, "box"))).toBe(true); - expect(existsSync(join(dist, "profile.toml"))).toBe(true); + // .box//aws has only the rendered Runtime profile, for people to read: box is staged once. + const aws = join(directory, "example", ".box", "agent_python_strands_box", "aws"); + expect(await readFile(join(aws, "profile.toml"), "utf8")).toBe( + await readFile(join(dist, "profile.toml"), "utf8"), + ); + expect(existsSync(join(aws, "box"))).toBe(false); + expect(existsSync(join(aws, "resources", "shared"))).toBe(false); }); test("downloads box from the public box release when it is not cached", async () => { diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index c2817e9d5a..2fcadc8812 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -61,15 +61,18 @@ import { BoxCliProfileResolver, type BoxProfileResolver } from "./boxProfileReso import { BOX_NETWORK_WRITERS, boxNetworkEdits, writeBoxNetworkFiles } from "./boxNetworkWriters"; import { createProjectTree } from "./templates/project"; import { - boxProfilePath, + BOX_CODEZIP_ENTRYPOINT, + boxAgentDir, + boxAwsDir, + boxLocalProfilePath, boxProfileWarnings, boxUvSyncEnv, hasBoxProfile, renderBoxProfile, startsInBoxOnCodeZip, } from "./templates/boxProfile"; -import { assertBoxRuntimesHaveBoxVersion } from "./backends/boxContainer"; -import { BOX_INSTALL_HINT } from "./backends/boxRelease"; +import { validateBoxRuntimes } from "./boxValidation"; +import { BOX_INSTALL_HINT, BOX_RELEASE } from "./backends/boxRelease"; import { getRuntimeTemplateResolver } from "./templates/runtime"; import { EXPORT_NOTES_FILENAME, @@ -80,12 +83,14 @@ import { HarnessSpecSchema, HarnessYamlSchema } from "../../projectSchemas/harne import { FsTreeNode } from "./templates/fsTree"; import { getEvaluatorTemplateResolver } from "./templates/evaluator"; import { + boxGatewaySpec, isBoundGateway, isBoxProject, ProjectSpecSchema, type ManagedBy, } from "../../projectSchemas/project"; import { ConfigBundleSchema } from "../../projectSchemas/config-bundle"; +import { AgentCoreGatewaySchema } from "../../projectSchemas/gateway"; import { CredentialSchema, credentialEnvVarName, @@ -124,6 +129,7 @@ import { import { V0AwsDeploymentTargetsSchema } from "../../projectSchemas/v0"; import { isRuntimeDocsConfig, + type RuntimeDocsConfig, type RuntimeResourceConfig, } from "../../handlers/project/add/runtime/types"; import { buildDocsRuntimeSpec, runtimeDocsTree } from "./templates/runtimeDocs"; @@ -137,7 +143,7 @@ import { projectFormat, type ProjectFormat } from "./legacy/detect"; import { loadLegacyProject } from "./legacy/load"; import { assertV1Project } from "./legacy/writeGate"; import { assertNoPendingMigration } from "./migrate/journal"; -import { prepareRuntimes } from "./runtimeBuild"; +import { LATEST_PYTHON, prepareRuntimes } from "./runtimeBuild"; const TARGETS_EXAMPLE = '[{ "name": "default", "account": "111122223333", "region": "us-east-1" }]'; @@ -831,7 +837,11 @@ export class FsProjectManager implements ProjectManager { break; } case "runtime": { - assertNoSecondBoxRuntime(projectSpec, `runtime '${input.resourceConfig.name}'`); + // Every runtime of a Box project runs in a box, so a runtime added to one gets what + // create gives a box runtime, with its own box profile in .box//local/. + const boxInput = isBoxProject(projectSpec) + ? boxRuntimeInput(projectSpec, input.resourceConfig) + : undefined; const outputPath = join(project.rootPath, "app", input.resourceConfig.name); // The folder may hold the user's own code, but never another resource's. const owner = appFolderOwner(projectSpec, project.rootPath, outputPath); @@ -841,6 +851,7 @@ export class FsProjectManager implements ProjectManager { `overlaps the files of ${owner}. Choose a different --name.`, ); } + if (boxInput) await this.assertNoOtherStartScript(outputPath, input.resourceConfig.name); // Rollback removes only what this add created, never a folder the user already had. const folderExisted = existsSync(outputPath); if (isRuntimeDocsConfig(input.resourceConfig)) { @@ -870,6 +881,22 @@ export class FsProjectManager implements ProjectManager { } } projectSpec.runtimes.push(buildDocsRuntimeSpec(input.resourceConfig)); + if (boxInput) { + // A failure here comes before the spec write, whose catch removes what this add + // created, so the box scaffold removes it itself. + try { + yield* this.addBoxRuntime( + project.rootPath, + projectSpec, + boxInput, + scaffoldedPaths, + options.region ?? (await this.boxBuildRegion()), + ); + } catch (err) { + await this.discardStaged(scaffoldedPaths); + throw err; + } + } break; } @@ -1070,8 +1097,17 @@ export class FsProjectManager implements ProjectManager { /** Best-effort removal of paths an add created; failures are logged, not thrown. */ private async discardStaged(paths: string[]): Promise { + // A path inside another one goes with it. Removing both at the same time races: the + // recursive remove of the folder can stop on a child the other remove took first. + const inside = (child: string, parent: string) => { + const path = relative(parent, child); + return path !== "" && !path.startsWith("..") && !isAbsolute(path); + }; + const outermost = [...new Set(paths)].filter( + (path) => !paths.some((other) => inside(path, other)), + ); await Promise.all( - paths.map((p) => + outermost.map((p) => rm(p, { recursive: true, force: true }).catch((e) => { const error = AgentCoreCLIError.fromError(e); this.logger @@ -1236,6 +1272,14 @@ export class FsProjectManager implements ProjectManager { } const newProjectSpec = await this.commitSpec(agentCoreSpecPath, newSpec, envFile); + // Build and deploy generate the runtime's .box//aws/ folder, so it goes with the runtime. + // Its .box//local/ profile is the user's, as its code folder is, so it stays. + if (input.resourceType === "runtime") { + await rm(join(project.rootPath, ...boxAwsDir(input.name).split("/")), { + recursive: true, + force: true, + }); + } return { project: { ...project, spec: newProjectSpec }, @@ -1322,7 +1366,7 @@ export class FsProjectManager implements ProjectManager { ): AsyncGenerator { if (project) assertV1Project(project, "export harness"); // Export adds a runtime, which a Box project cannot take. - if (project) assertNoSecondBoxRuntime(project.spec, "the exported harness as a runtime"); + if (project) assertNotBoxProject(project.spec, "the exported harness as a runtime"); if (!project) { if (!input.prefetched) { throw new ProjectStateError( @@ -1573,6 +1617,8 @@ export class FsProjectManager implements ProjectManager { await assertNoPendingMigration(project.rootPath); const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); for (const message of synced.messages) yield { type: "step", message }; + // Every runtime of a Box project runs in a box, so stop before anything is written. + validateBoxRuntimes(synced.project.spec); const boxed = await this.applyBoxNetwork(synced.project, "build", await this.boxBuildRegion()); yield* boxed.events; yield* this.backendFor(project).build(boxed.project, { boxNetworks: boxed.networks }); @@ -1606,8 +1652,6 @@ export class FsProjectManager implements ProjectManager { command: "build" | "deploy", region: string, ): Promise<{ project: Project; networks: BoxNetwork[]; events: ProjectEvent[] }> { - // Every runtime of a Box project runs in a box, so stop before anything is written. - assertBoxRuntimesHaveBoxVersion(project.spec); const networks = await readBoxNetworks( project.spec, project.rootPath, @@ -1679,7 +1723,9 @@ export class FsProjectManager implements ProjectManager { const runtimes = input.runtimeNames ? project.spec.runtimes.filter((runtime) => input.runtimeNames!.includes(runtime.name)) : project.spec.runtimes; - const prepared = prepareRuntimes(project.rootPath, runtimes, input.purpose); + const prepared = prepareRuntimes(project.rootPath, runtimes, input.purpose, { + boxProject: isBoxProject(project.spec), + }); if (prepared.changed.length === 0) { return { project, messages: prepared.messages, written: false }; } @@ -1768,6 +1814,8 @@ export class FsProjectManager implements ProjectManager { // first; only once the target is known, so a bad --target rewrites nothing. const synced = await this.syncRuntimeBuilds(project, { purpose: "deploy" }); for (const message of synced.messages) yield { type: "step", message }; + // Every runtime of a Box project runs in a box, so stop before anything is written. + validateBoxRuntimes(synced.project.spec); const boxed = await this.applyBoxNetwork(synced.project, "deploy", target.region); yield* boxed.events; project = boxed.project; @@ -2055,9 +2103,72 @@ export class FsProjectManager implements ProjectManager { } /** - * Writes the box profile that runs the scaffolded agent into the project's - * `.box` folder, named after the project, calling Bedrock in `region`. An - * existing profile is the user's, so it is never overwritten. + * Gives the runtime `boxInput` names, just added to the Box project `projectSpec`, what create + * gives a CodeZip box runtime: `box.version`, start.py as its entry point, its own Box gateway, + * and its own box profile in `.box//local/`. Each path it creates goes into + * `scaffoldedPaths`, so a failed add removes it; a file or folder the user already had stays. + */ + private async *addBoxRuntime( + projectRoot: string, + projectSpec: z.infer, + boxInput: ScaffoldRuntimeInput, + scaffoldedPaths: string[], + region: string, + ): AsyncGenerator { + const name = boxInput.runtimeName; + const runtime = projectSpec.runtimes.find((candidate) => candidate.name === name)!; + // The box release build and deploy ship, as create pins it. + runtime.box = { version: BOX_RELEASE.version }; + // start.py starts `box run` on AgentCore Runtime, and the profile runs the agent. + runtime.entrypoint = BOX_CODEZIP_ENTRYPOINT; + projectSpec.agentCoreGateways.push(AgentCoreGatewaySchema.parse(boxGatewaySpec(name))); + + const appDir = join(projectRoot, ...runtime.codeLocation.split("/")); + const startScript = join(appDir, BOX_CODEZIP_ENTRYPOINT); + if (!existsSync(startScript)) { + scaffoldedPaths.push(startScript); + await writeFile( + startScript, + await this.assetSource.read(`templates/box-codezip/${BOX_CODEZIP_ENTRYPOINT}`), + { flag: "wx" }, + ); + } + // The profile keeps the venv out of the write grant with an optional deny_write, which box + // drops while `.venv` is missing, and then refuses the profile. An empty `.venv` keeps the + // profile valid until `uv sync` fills it. + const venv = join(appDir, ".venv"); + if (!existsSync(venv)) { + scaffoldedPaths.push(venv); + await mkdir(venv, { recursive: true }); + } + const boxFolder = join(projectRoot, ...boxAgentDir(name).split("/")); + if (!existsSync(boxFolder)) scaffoldedPaths.push(boxFolder); + yield* this.writeBoxProfile(projectRoot, projectSpec.name, boxInput, region); + } + + /** + * Throws when `appDir` already holds a start.py that is not the one that starts box. A box + * runtime runs start.py as its entry point, so AgentCore Runtime would run the user's file with + * no box, while build still writes the runtime's box profile and Box gateway. + */ + private async assertNoOtherStartScript(appDir: string, runtimeName: string): Promise { + const startScript = join(appDir, BOX_CODEZIP_ENTRYPOINT); + if (!existsSync(startScript)) return; + const boxStart = await this.assetSource.read(`templates/box-codezip/${BOX_CODEZIP_ENTRYPOINT}`); + if ((await readFile(startScript, "utf8")) === boxStart) return; + const shown = `app/${runtimeName}/${BOX_CODEZIP_ENTRYPOINT}`; + throw new InputValidationError( + `cannot add runtime '${runtimeName}' to a Box project: ${shown} exists, and it is not the ` + + `${BOX_CODEZIP_ENTRYPOINT} that starts box. A box runtime runs ${BOX_CODEZIP_ENTRYPOINT} as ` + + `its entry point, so AgentCore Runtime would run your file with no box. Rename ${shown}, ` + + "then retry.", + ); + } + + /** + * Writes the box profile that runs the scaffolded agent into the agent's + * `.box//local/` folder, named after the project, calling Bedrock in + * `region`. An existing profile is the user's, so it is never overwritten. */ private async *writeBoxProfile( projectRoot: string, @@ -2067,9 +2178,20 @@ export class FsProjectManager implements ProjectManager { ): AsyncGenerator { const text = renderBoxProfile(projectName, runtime, region); if (text === undefined) return; - const path = boxProfilePath(projectRoot); + const path = boxLocalProfilePath(projectRoot, runtime.runtimeName); if (existsSync(path)) { yield { type: "warning", message: `box profile ${path} already exists; left unchanged` }; + const kept = ingressPort(await readFile(path, "utf8")); + const wanted = ingressPort(text); + if (kept !== undefined && wanted !== undefined && kept !== wanted) { + yield { + type: "warning", + message: + `box profile ${path} is for another protocol: it listens on port ${kept}, and a ` + + `${runtime.protocol ?? "HTTP"} runtime listens on port ${wanted}. Remove ` + + `${dirname(path)}, then add the runtime again, or edit the profile.`, + }; + } return; } yield { type: "step", message: `writing box profile ${path}` }; @@ -2251,22 +2373,69 @@ async function readStrandsVersion(agentDir: string): Promise { } } +/** The port of the first `[[agent.ingress]] listen` in the box profile `text`, if it names one. */ +function ingressPort(text: string): string | undefined { + return /^\s*listen\s*=\s*"[^"]*:(\d+)"/m.exec(text)?.[1]; +} + /** - * Refuses to add a runtime to a Box project. A Box project holds one runtime, the one `agentcore - * create` made from a box template, and runs it in a box with its box profile. The project has - * one box profile, so a second runtime could not run in a box, and a Box project has no runtime - * outside one. + * Refuses to export a harness as a runtime into a Box project. Every runtime of a Box project runs + * in a box, and the exported harness runs its agent the usual way. */ -function assertNoSecondBoxRuntime(spec: z.infer, what: string): void { +function assertNotBoxProject(spec: z.infer, what: string): void { if (!isBoxProject(spec)) return; throw new ProjectStateError( - `cannot add ${what}: a Box project holds one runtime, which \`agentcore ` + - "create` makes from a box template (agent-python-strands-box or " + - "agent-python-strands-box-container), and every runtime of a Box project runs in a box. " + - "Create a separate project for this runtime.", + `cannot add ${what}: every runtime of a Box project runs in a box, and the exported ` + + "harness does not. Export it into a project that is not a Box project.", ); } +/** + * The input that the box profile of `config`, a docs-only runtime added to the Box project `spec`, + * renders from: a Python CodeZip agent with the framework `none` and Bedrock, as + * agent-python-minimal-box has. Throws for a Bedrock Agent import, for a TypeScript runtime, and + * for a runtime whose Box gateway name is taken. + */ +function boxRuntimeInput( + spec: z.infer, + config: RuntimeResourceConfig | RuntimeDocsConfig, +): ScaffoldRuntimeInput { + // The imported agent can call Bedrock Agent and action group hosts that the box profile of a + // new runtime does not allow, so a Box project does not take an import yet. + if (!isRuntimeDocsConfig(config)) { + throw new InputValidationError( + `cannot add runtime '${config.name}' to a Box project from a Bedrock Agent import: every ` + + "runtime of a Box project runs in a box, and the box profile of an added runtime does not " + + "allow the hosts an imported agent calls. Import it into a project that is not a Box " + + "project, or add a runtime with --language python.", + ); + } + if (config.language !== "Python") { + throw new InputValidationError( + `cannot add runtime '${config.name}' to a Box project: every runtime of a Box project ` + + "runs in a box, and add runtime adds a box runtime only as a Python CodeZip agent. Add " + + "it with --language python.", + ); + } + const gateway = boxGatewaySpec(config.name).name; + if (spec.agentCoreGateways.some(({ name }) => name === gateway)) { + throw new InputValidationError( + `cannot add runtime '${config.name}': its Box gateway needs the name '${gateway}', and a ` + + "gateway with that name already exists. Choose a different --name.", + ); + } + return { + runtimeName: config.name, + build: "CodeZip", + language: "Python", + framework: "none", + protocol: config.protocol ?? "HTTP", + modelProvider: "Bedrock", + runtimeVersion: LATEST_PYTHON, + boxTemplate: true, + }; +} + /** * The raw agentcore.json array `raw` with the edits that turned the parsed entries `before` into * `after`, matched by name: an entry `after` changed gets only its changed fields, so its other diff --git a/src/core/project/runtimeBuild.test.ts b/src/core/project/runtimeBuild.test.ts index 47ab9452d2..ccedfbb739 100644 --- a/src/core/project/runtimeBuild.test.ts +++ b/src/core/project/runtimeBuild.test.ts @@ -613,3 +613,53 @@ describe("prepareRuntimes", () => { expect(() => prepareRuntimes(root, [nodeRuntime()], "deploy")).toThrow("no node_modules"); }); }); + +describe("entrypoint of a CodeZip runtime that runs in a box", () => { + const boxed = (overrides: Partial = {}) => + runtime({ entrypoint: "start.py", box: { version: "1.0.0" }, ...overrides }); + + test("stays start.py when pyproject.toml names the agent's main.py, with a warning", async () => { + const root = await project({ + "app/search/pyproject.toml": pyproject( + ">=3.12", + '[tool.agentcore]\nentrypoint = "main.py"\n', + ), + }); + + const sync = syncRuntimeBuild(boxed(), root, { boxProject: true }); + + expect(sync.runtime.entrypoint).toBe("start.py"); + expect(sync.changes.map(({ field }) => field)).not.toContain("entrypoint"); + expect(sync.warnings).toEqual([ + 'runtime "search" runs its agent in a box, so its entrypoint stays start.py, which starts ' + + "box, and its box profile runs the agent. [tool.agentcore] entrypoint in " + + "app/search/pyproject.toml names main.py, which is not used.", + ]); + }); + + test.each([ + ["a runtime with no box", runtime(), true], + ["a box runtime outside a Box project", boxed(), false], + ])("still takes the pyproject.toml entrypoint for %s", async (_, synced, boxProject) => { + const root = await project({ + "app/search/pyproject.toml": pyproject(">=3.12", '[tool.agentcore]\nentrypoint = "app.py"\n'), + }); + + expect(syncRuntimeBuild(synced, root, { boxProject }).runtime.entrypoint).toBe("app.py"); + }); + + test("refuses the switch to a container build when a Dockerfile appears", async () => { + const root = await project({ + "app/search/pyproject.toml": pyproject(">=3.12"), + "app/search/start.py": "", + "app/search/Dockerfile": "FROM python:3.12\n", + }); + + expect(() => prepareRuntimes(root, [boxed()], "deploy", { boxProject: true })).toThrow( + 'runtime "search" runs its agent in a box as a CodeZip agent, but app/search has a ' + + "Dockerfile", + ); + // Outside a Box project the Dockerfile still makes it a container build. + expect(syncRuntimeBuild(boxed(), root).runtime.build).toBe("Container"); + }); +}); diff --git a/src/core/project/runtimeBuild.ts b/src/core/project/runtimeBuild.ts index be74f38f3b..df456b0297 100644 --- a/src/core/project/runtimeBuild.ts +++ b/src/core/project/runtimeBuild.ts @@ -9,6 +9,11 @@ import { type RuntimeVersion, } from "../../projectSchemas/constants"; import { EntrypointSchema, type ProjectRuntime } from "../../projectSchemas/runtime"; +import { + assertNoBoxContainerSwitch, + keptBoxEntrypointWarning, + syncKeepsBoxEntrypoint, +} from "./boxValidation"; /** * Re-derives a runtime's build settings (`build`, `dockerfile`, `runtimeVersion`, @@ -74,8 +79,19 @@ function codeZipRevertEdits(runtime: ProjectRuntime): string { : `${edits.slice(0, -1).join(", ")}, and ${edits[edits.length - 1]}`; } +/** How the project of the runtimes being synced runs them. */ +export interface SyncOptions { + /** Whether the project is a Box project, so the box rules of boxValidation.ts apply. */ + boxProject?: boolean; +} + /** Re-derives a runtime's build settings. Throws a {@link ProjectStateError} when they cannot be. */ -export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): RuntimeSync { +export function syncRuntimeBuild( + runtime: ProjectRuntime, + projectRoot: string, + options: SyncOptions = {}, +): RuntimeSync { + const boxProject = options.boxProject ?? false; const next: ProjectRuntime = { ...runtime }; const reasons: Partial> = {}; const warnings: string[] = []; @@ -87,6 +103,7 @@ export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): // Dockerfile is a precheck error, so deleting one by accident cannot silently // change how the runtime deploys. if (runtime.build === "CodeZip" && hasDockerfile(context)) { + assertNoBoxContainerSwitch(boxProject, runtime, contextLabel); next.build = "Container"; next.dockerfile = DOCKERFILE_NAME; reasons.build = reasons.dockerfile = `${DOCKERFILE_NAME} in ${contextLabel}`; @@ -105,7 +122,11 @@ export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): : next.build === "CodeZip" ? nodeEntrypoint(runtime, projectRoot, warnings) : undefined; - if (entrypoint !== undefined) { + if (entrypoint !== undefined && syncKeepsBoxEntrypoint(boxProject, runtime)) { + if (entrypoint.value !== runtime.entrypoint) { + warnings.push(keptBoxEntrypointWarning(runtime.name, entrypoint.reason, entrypoint.value)); + } + } else if (entrypoint !== undefined) { next.entrypoint = entrypoint.value; reasons.entrypoint = entrypoint.reason; } @@ -516,6 +537,7 @@ export function prepareRuntimes( projectRoot: string, runtimes: ProjectRuntime[], purpose: "dev" | "deploy", + options: SyncOptions = {}, ): PreparedRuntimes { const prepared: ProjectRuntime[] = []; const changed: RuntimeSync[] = []; @@ -534,7 +556,7 @@ export function prepareRuntimes( } let sync: RuntimeSync; try { - sync = syncRuntimeBuild(runtime, projectRoot); + sync = syncRuntimeBuild(runtime, projectRoot, options); } catch (error) { if (!(error instanceof ProjectStateError)) throw error; pointAtReadme([error.message]); diff --git a/src/core/project/templates/boxProfile.test.ts b/src/core/project/templates/boxProfile.test.ts index 3b8670ad80..906a110afd 100644 --- a/src/core/project/templates/boxProfile.test.ts +++ b/src/core/project/templates/boxProfile.test.ts @@ -86,9 +86,11 @@ describe("renderBoxProfile", () => { }); }); - test("names itself after the project, so `box run .box/profile.toml` can load it by its path", () => { + test("names itself after the project, so `box run .box/agent/local/profile.toml` can load it by its path", () => { expect(profile("agent-python-minimal").profile).toEqual({ name: "V3Demo" }); - expect(renderBoxProfile("V3Demo", STRANDS)).toContain("Run `box run .box/profile.toml`"); + expect(renderBoxProfile("V3Demo", STRANDS)).toContain( + "Run `box run .box/agent/local/profile.toml`", + ); }); test("names no host path, so the profile works on any machine and after a move", () => { @@ -242,7 +244,7 @@ describe("renderBoxProfile", () => { expect(profile("agent-python-strands", groq).egress).toBeUndefined(); expect(boxProfileWarnings(template("agent-python-strands", groq))).toEqual([ "the box profile has no route for the LiteLLM model 'groq/llama3': add an [egress.groq] " + - "section with its provider's host to .box/profile.toml, or the box blocks the agent's " + + "section with its provider's host to .box/agent/local/profile.toml, or the box blocks the agent's " + "model calls", ]); }); @@ -288,7 +290,7 @@ describe("renderBoxProfile", () => { }); expect(boxProfileWarnings(runtime)).toEqual([ "the box profile has no route for the LiteLLM model 'gpt-4o': add an [egress.] " + - "section with its provider's host to .box/profile.toml (or use an openai/, anthropic/ or " + + "section with its provider's host to .box/agent/local/profile.toml (or use an openai/, anthropic/ or " + "gemini/ model ID), or the box blocks the agent's model calls", ]); }); @@ -785,7 +787,8 @@ describe("renderRuntimeBoxProfile", () => { }, }); expect(text).toContain( - "\n# The [telemetry.logs] target of .box/profile.toml, signed with the execution role.\n" + + "\n# The [telemetry.logs] target of .box/agent/local/profile.toml, signed with the " + + "execution role.\n" + '[telemetry.logs]\nkind = "cloudwatch_logs"\nregion = "us-west-2"\n' + 'log_group = "/aws/box"\nlog_stream = "agent"\ninclude = ["logs", "trace"]\n' + 'secret.ref = "aws://"\n', diff --git a/src/core/project/templates/boxProfile.ts b/src/core/project/templates/boxProfile.ts index cd49d5a866..d72610bb4c 100644 --- a/src/core/project/templates/boxProfile.ts +++ b/src/core/project/templates/boxProfile.ts @@ -1,4 +1,4 @@ -import { join } from "node:path"; +import { join, posix } from "node:path"; import { InputValidationError } from "../../../errors/errors"; import { DEFAULT_EGRESS_BEDROCK_REGION, @@ -123,38 +123,52 @@ export function boxWorkloadPort(protocol: Protocol | undefined): number { return boxIngressPort(protocol) + 1; } +/** The box folder at the project root that holds every agent's profiles. */ +export const BOX_ROOT = ".box"; + +/** An agent's box folder, relative to the project root: `.box/`. */ +export function boxAgentDir(agentName: string): string { + return posix.join(BOX_ROOT, agentName); +} + /** - * The project's box profile, relative to the project root: `box run - * .box/profile.toml` there runs it. box keeps the agent out of the project's - * `.box` folder, so the agent cannot change its own profile. + * An agent's local profile folder, relative to the project root: + * `.box//local`. It holds the profile `agentcore dev` runs and the + * policy files it names. box keeps the agent out of this folder, so the agent + * cannot change its own profile. */ -export const BOX_PROFILE_FILE = ".box/profile.toml"; +export function boxLocalDir(agentName: string): string { + return posix.join(boxAgentDir(agentName), "local"); +} -/** The box profile of the project at `projectRoot`. */ -export function boxProfilePath(projectRoot: string): string { - return join(projectRoot, BOX_PROFILE_FILE); +/** + * An agent's AWS folder, relative to the project root: `.box//aws`. + * Build and deploy generate the AgentCore Runtime profile and its resources + * here, then copy the folder into the deploy artifact's `.box-dist/` staging. + */ +export function boxAwsDir(agentName: string): string { + return posix.join(boxAgentDir(agentName), "aws"); } /** - * Whether create writes a box profile for this runtime: a box template, CodeZip or container, - * which runs its agent in Strands Box. Every other template runs its agent the usual way. + * An agent's local box profile, relative to the project root: `box run + * .box//local/profile.toml` there runs it. */ -export function hasBoxProfile(runtime: ScaffoldRuntimeInput): boolean { - return startsInBoxOnCodeZip(runtime) || isBoxedContainer(runtime); +export function boxLocalProfileFile(agentName: string): string { + return posix.join(boxLocalDir(agentName), "profile.toml"); +} + +/** An agent's local box profile at `projectRoot`. */ +export function boxLocalProfilePath(projectRoot: string, agentName: string): string { + return join(projectRoot, boxLocalProfileFile(agentName)); } /** - * Whether the project's box profile, `profileText`, was written for `runtime`. Create writes one - * profile, for the first runtime, and `add` writes none, so a runtime added later has no profile. - * A CodeZip profile names its runtime's folder; the container profile runs /app and names none. + * Whether create writes a box profile for this runtime: a box template, CodeZip or container, + * which runs its agent in Strands Box. Every other template runs its agent the usual way. */ -export function boxProfileIsFor( - profileText: string, - runtime: { build: string; codeLocation: string }, -): boolean { - const codeZip = profileText.includes("${{ workspace }}/app/"); - if (runtime.build === "Container") return !codeZip; - return profileText.includes(`/${runtime.codeLocation}"`); +export function hasBoxProfile(runtime: ScaffoldRuntimeInput): boolean { + return startsInBoxOnCodeZip(runtime) || isBoxedContainer(runtime); } /** The Strands box container template, whose image starts `box run` in /app. */ @@ -483,7 +497,7 @@ export function renderBoxProfile( ? "# Rendered by agentcore build and deploy from agentcore.json, for AgentCore Runtime. The box/agentcore pack carries the deployed resources' variables." : container ? "# Written by `agentcore create` for the agent's image, to run with `box run` in /app." - : `# Written by \`agentcore create\`. Run \`box run ${BOX_PROFILE_FILE}\` in the project folder.`; + : `# Written by \`agentcore create\` or \`agentcore add runtime\`. Run \`box run ${boxLocalProfileFile(runtime.runtimeName)}\` in the project folder.`; const regionComment = onRuntime ? "" : "# The AWS region `agentcore create` resolved. Change it to call Bedrock in another region\n" + @@ -506,7 +520,7 @@ export function renderBoxProfile( const routes = onRuntime ? runtimeRoutes : ""; const policies = onRuntime && runtimePolicies.length > 0 - ? `# The policy files of ${BOX_PROFILE_FILE}, copied unchanged beside this profile.\npolicies = ${list([...runtimePolicies])}\n` + ? `# The policy files of ${boxLocalProfileFile(runtime.runtimeName)}, copied unchanged beside this profile.\npolicies = ${list([...runtimePolicies])}\n` : ""; const bedrockRoute = !bedrock ? "" @@ -683,11 +697,11 @@ function runtimeMcpServers(hosts: BoxNetwork["hosts"]): Map]` - * table with the same keys, signed with the execution role, whatever the box - * profile signs it with. Starts with a blank line. + * A CloudWatch target of the box profile `profileFile` on the Runtime: its + * `[telemetry.]` table with the same keys, signed with the execution + * role, whatever the box profile signs it with. Starts with a blank line. */ -function runtimeTelemetrySection(target: CloudWatchTelemetry): string { +function runtimeTelemetrySection(target: CloudWatchTelemetry, profileFile: string): string { const logs = target.kind === "cloudwatch_logs" ? `log_group = ${str(target.logGroup)}\nlog_stream = ${str(target.logStream)}\n` @@ -695,7 +709,7 @@ function runtimeTelemetrySection(target: CloudWatchTelemetry): string { const include = target.include ? `include = ${list([...target.include])}\n` : ""; const key = tomlKey(target.name); return ` -# The [telemetry.${key}] target of ${BOX_PROFILE_FILE}, signed with the execution role. +# The [telemetry.${key}] target of ${profileFile}, signed with the execution role. [telemetry.${key}] kind = ${str(target.kind)} region = ${str(target.region)} @@ -740,7 +754,13 @@ export function renderRuntimeBoxProfile( runtimeGatewayRoutes(spec, runtime, runtimeMcpServers(network?.hosts ?? [])), network?.policyFiles, )!; - return profile + (network?.telemetry ?? []).map(runtimeTelemetrySection).join(""); + const profileFile = boxLocalProfileFile(runtime.name); + return ( + profile + + (network?.telemetry ?? []) + .map((target) => runtimeTelemetrySection(target, profileFile)) + .join("") + ); } /** @@ -778,7 +798,8 @@ export function boxProfileWarnings(runtime: ScaffoldRuntimeInput): string[] { model === undefined ? " (or use an openai/, anthropic/ or gemini/ model ID)" : ""; return [ `the box profile has no route for the LiteLLM model '${modelId}': add an ` + - `${section} section with its provider's host to ${BOX_PROFILE_FILE}${prefixHint}, or the ` + + `${section} section with its provider's host to ` + + `${boxLocalProfileFile(runtime.runtimeName)}${prefixHint}, or the ` + "box blocks the agent's model calls", ]; } diff --git a/src/core/project/templates/project.ts b/src/core/project/templates/project.ts index 68db3b9f0f..548f63f576 100644 --- a/src/core/project/templates/project.ts +++ b/src/core/project/templates/project.ts @@ -54,11 +54,13 @@ export async function createProjectTree( } const envEntries = templates.flatMap((template) => template.envEntries ?? []); + const boxProject = options?.runtime !== undefined && hasBoxProfile(options.runtime); const tree = FsTreeNode.createDirectory(".", [ - FsTreeNode.createFile(".gitignore", () => - config.assetSource.read("templates/shared/gitignore.template"), - ), + FsTreeNode.createFile(".gitignore", async () => { + const shared = await config.assetSource.read("templates/shared/gitignore.template"); + return boxProject ? `${shared}${BOX_GITIGNORE}` : shared; + }), FsTreeNode.createDirectory("agentcore", [ await FsTreeNode.fromAssetSource({ assetSource: config.assetSource }, { assetDir: "cdk" }), FsTreeNode.createFile("agentcore.json", async () => @@ -116,6 +118,17 @@ function withBoxContainerBoxVersion(template: Template): void { const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`; +/** + * The lines a Box project adds to its .gitignore, for every runtime it has or gets later: the + * Runtime profile build renders into `.box//aws/`, and the box release build and dev stage + * into `.box-dist/` and `.box-dev/`. `.box//local/` is the user's, and is committed. + */ +const BOX_GITIGNORE = + "\n# Box (written by agentcore build, deploy and dev; .box//local is committed)\n" + + ".box/*/aws/\n" + + ".box-dist/\n" + + ".box-dev/\n"; + /** * The agentcore.json of a new project, from the spec entries of its templates. Only a Box template * (one with `projectType: "box"`) makes a Box project: it gets `projectType` and one Box gateway diff --git a/src/handlers/project/add/runtime/screen.test.ts b/src/handlers/project/add/runtime/screen.test.ts new file mode 100644 index 0000000000..939d1618aa --- /dev/null +++ b/src/handlers/project/add/runtime/screen.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, test } from "bun:test"; +import { summaryOf } from "./screen"; + +describe("summaryOf", () => { + const values = { name: "search", language: "python", protocol: "HTTP" } as const; + + test("shows the docs-only runtime outside a Box project", () => { + expect(summaryOf(values)).toEqual({ + runtime: "search", + language: "Python", + protocol: "HTTP", + folder: "app/search/ (README.md, AGENTS.md)", + entrypoint: "main.py", + }); + }); + + test("shows start.py and the box profile in a Box project, as add runtime writes them", () => { + expect(summaryOf(values, true)).toEqual({ + runtime: "search", + language: "Python", + protocol: "HTTP", + folder: "app/search/ (README.md, AGENTS.md, start.py)", + entrypoint: "start.py", + "box profile": ".box/search/local/profile.toml", + }); + }); +}); diff --git a/src/handlers/project/add/runtime/screen.tsx b/src/handlers/project/add/runtime/screen.tsx index d6fd8e129e..a8a31ed4df 100644 --- a/src/handlers/project/add/runtime/screen.tsx +++ b/src/handlers/project/add/runtime/screen.tsx @@ -17,6 +17,11 @@ import { type Choice, } from "../../../../components/wizard"; import { docsRuntimeEntrypoint } from "../../../../core/project/templates/runtimeDocs"; +import { + BOX_CODEZIP_ENTRYPOINT, + boxLocalProfileFile, +} from "../../../../core/project/templates/boxProfile"; +import { isBoxProject } from "../../../../projectSchemas/project"; import { RUNTIME_LANGUAGES, runtimeDocsAddedMessage, @@ -38,6 +43,15 @@ const LANGUAGE_CHOICES: Choice[] = [ }, ]; +/** A Box project runs every runtime in a box, and add runtime adds a box runtime only in Python. */ +const BOX_LANGUAGE_CHOICES: Choice[] = [ + { + value: "python", + label: "python", + description: "main.py in a box: start.py starts box, and its box profile runs main.py", + }, +]; + const PROTOCOL_CHOICES: Choice[] = [ { value: "HTTP", @@ -66,15 +80,23 @@ export function toRuntimeInput(values: RuntimeFormValues): RuntimeInput { }; } -function summaryOf(values: RuntimeFormValues): Record { +export function summaryOf(values: RuntimeFormValues, boxProject = false): Record { const language = RUNTIME_LANGUAGES[values.language]; - return { + const summary: Record = { runtime: values.name, language, protocol: values.protocol, folder: `app/${values.name}/ (README.md, AGENTS.md)`, entrypoint: docsRuntimeEntrypoint(language), }; + if (!boxProject) return summary; + // add runtime gives a runtime of a Box project the start.py that starts box. + return { + ...summary, + folder: `app/${values.name}/ (README.md, AGENTS.md, ${BOX_CODEZIP_ENTRYPOINT})`, + entrypoint: BOX_CODEZIP_ENTRYPOINT, + "box profile": boxLocalProfileFile(values.name), + }; } export function AddRuntimeScreen({ ctx, core }: ScreenProps) { @@ -112,6 +134,7 @@ function AddRuntimeWizard({ }); const set = (update: Partial) => setValues((current) => ({ ...current, ...update })); + const boxProject = isBoxProject(project.spec); return ( help="app// gets a README.md and AGENTS.md describing what your code needs" - choices={LANGUAGE_CHOICES} + choices={boxProject ? BOX_LANGUAGE_CHOICES : LANGUAGE_CHOICES} value={values.language} onChange={(language) => set({ language })} /> @@ -168,7 +191,7 @@ function AddRuntimeWizard({ - + ); diff --git a/src/handlers/project/dev/index.test.ts b/src/handlers/project/dev/index.test.ts index c6280029a2..c83e9cf23d 100644 --- a/src/handlers/project/dev/index.test.ts +++ b/src/handlers/project/dev/index.test.ts @@ -642,9 +642,12 @@ describe("project dev Inspector UI mode", () => { test("leaves the box's agent port to the box when a CodeZip runtime runs in one", async () => { const root = await mkdtemp(join(tmpdir(), "agentcore-dev-box-ui-")); try { - await mkdir(join(root, ".box")); - await writeFile(join(root, ".box", "profile.toml"), ""); - const subject = harness({ project: { ...project(runtime("search")), rootPath: root } }); + const local = join(root, ".box", "search", "local"); + await mkdir(local, { recursive: true }); + await writeFile(join(local, "profile.toml"), ""); + const base = project({ ...runtime("search"), box: { version: "1.0.0" } } as never); + const boxed = { ...base, rootPath: root, spec: { ...base.spec, projectType: "box" } }; + const subject = harness({ project: boxed as never }); const { pending } = await runUi(subject); @@ -657,6 +660,26 @@ describe("project dev Inspector UI mode", () => { } }); + test("takes the box's agent port for the UI when a profile file is left outside a Box project", async () => { + const root = await mkdtemp(join(tmpdir(), "agentcore-dev-box-ui-")); + try { + // A leftover profile does not make the runtime boxed: BoxDevRunner runs it the usual way. + const local = join(root, ".box", "search", "local"); + await mkdir(local, { recursive: true }); + await writeFile(join(local, "profile.toml"), ""); + const subject = harness({ project: { ...project(runtime("search")), rootPath: root } }); + + const { pending } = await runUi(subject); + + expect(subject.ui.starts).toEqual([{ port: 8081 }]); + + process.emit("SIGINT", "SIGINT"); + await pending.catch(() => undefined); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + test("starts the Inspector, prints the URL, and opens the browser on a TTY", async () => { const subject = harness({ tty: true }); const { pending } = await runUi(subject); diff --git a/src/handlers/project/dev/index.ts b/src/handlers/project/dev/index.ts index a8fd04d3bc..dd7749def0 100644 --- a/src/handlers/project/dev/index.ts +++ b/src/handlers/project/dev/index.ts @@ -1,4 +1,3 @@ -import { existsSync } from "node:fs"; import { join } from "node:path"; import z from "zod"; import { createInspectorHandler } from "../../../core/dev/inspector/server"; @@ -6,7 +5,7 @@ import type { InspectorDeps } from "../../../core/dev/inspector/types"; import { rewriteOtelEndpointForContainer } from "../../../core/dev/otel/collector"; import { findFreePort, resolveDevPort, resolveDevPorts } from "../../../core/dev/port"; import { writeBoxDevEnvLocal } from "../../../core/dev/boxEnvLocal"; -import { boxProfilePath, boxWorkloadPort } from "../../../core/project/templates/boxProfile"; +import { boxWorkloadPort, runsInBox } from "../../../core/project/templates/boxProfile"; import { projectSpecPath } from "../../../core/project/fsUtils"; import type { V0DeployRunner } from "../../../core/project/legacy/deploy"; import { DevSupervisor, type SupervisorConfig } from "../../../core/dev/supervisor"; @@ -394,12 +393,17 @@ async function runRuntimeDev({ runtimeNames, }); for (const message of synced.messages) renderStatus({ io: config.io, message, json }); - for (const message of await writeBoxDevEnvLocal(project.rootPath)) { - renderStatus({ io: config.io, message, json }); - } const runtimes = synced.project.spec.runtimes.filter(({ name }) => runtimeNames.includes(name), ); + // Each boxed agent reads its own .box//local profile for the env vars its routes name. + // A runtime is boxed by the rule BoxDevRunner uses, not by a profile file on disk. + for (const runtime of runtimes) { + if (!runsInBox(isBoxProject(synced.project.spec), runtime)) continue; + for (const message of await writeBoxDevEnvLocal(project.rootPath, runtime.name)) { + renderStatus({ io: config.io, message, json }); + } + } collector = input.traces ? await startRuntimeTraceCollector({ config, project, runtimes, json }) @@ -475,13 +479,14 @@ async function runRuntimeDev({ } // On macOS the box refuses to start when another process listens on its agent's port. - const boxPorts = existsSync(boxProfilePath(project.rootPath)) - ? new Set( - runtimes - .filter(({ build }) => build === "CodeZip") - .map(({ protocol }) => boxWorkloadPort(protocol)), + const boxPorts = new Set( + runtimes + .filter( + (runtime) => + runtime.build === "CodeZip" && runsInBox(isBoxProject(project.spec), runtime), ) - : new Set(); + .map(({ protocol }) => boxWorkloadPort(protocol)), + ); const uiPort = ( await findFreePort( UI_DEFAULT_PORT,