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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions src/core/dev/box.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ async function temp(prefix: string): Promise<string> {
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 });
}

Expand Down Expand Up @@ -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" },
]);
});
Expand Down Expand Up @@ -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.
Expand All @@ -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 () => {
Expand Down
24 changes: 11 additions & 13 deletions src/core/dev/box.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
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";
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";

Expand All @@ -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/<agentName>/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
Expand All @@ -40,7 +39,8 @@ export class BoxDevRunner implements DevRunner {
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
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) {
Expand All @@ -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);
Expand All @@ -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,
Expand Down
21 changes: 12 additions & 9 deletions src/core/dev/boxEnvLocal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -20,8 +22,9 @@ async function project(profile?: string): Promise<string> {
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;
}
Expand All @@ -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([
Expand All @@ -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);
});

Expand All @@ -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" });
});

Expand All @@ -74,15 +77,15 @@ 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);
});

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);
});
});
5 changes: 3 additions & 2 deletions src/core/dev/boxEnvLocal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.<name>] secret.ref = "env://<VAR>"` route of the project's box profile
* `[egress.<name>] secret.ref = "env://<VAR>"` 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
Expand All @@ -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<string[]> {
const routes = readBoxEnvRoutes(projectRoot)?.routes ?? [];
const routes = readBoxEnvRoutes(projectRoot, agentName)?.routes ?? [];

const entries: (EnvLocalEntry & { route: string })[] = [];
for (const { route, variable: key } of routes) {
Expand Down
47 changes: 16 additions & 31 deletions src/core/dev/container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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 };
}
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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)));
Expand All @@ -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 });
Expand Down
17 changes: 5 additions & 12 deletions src/core/dev/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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,
);
Expand Down
Loading
Loading