From bee906761dfca7ee2d45da5c8cb0556681ad587e Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sat, 28 Nov 2026 00:27:30 -0800 Subject: [PATCH 01/11] test(e2e): Deploy the LangChain Box template in CI too, and ignore OpenTelemetry's context noise in the runtime log check --- e2eTest/project/templates.test.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/e2eTest/project/templates.test.ts b/e2eTest/project/templates.test.ts index bd25a39b2..63d5e3a33 100644 --- a/e2eTest/project/templates.test.ts +++ b/e2eTest/project/templates.test.ts @@ -363,13 +363,9 @@ describe( }, ); -// In CI, the AgentCore Runtime logs of the LangChain box agent hold OpenTelemetry's "Failed to -// detach context" at ERROR level, which the log check of the deploy refuses, so the deploy tests -// leave it out in CI until the template or the check handles that message. Its dev test below -// still runs there. -const DEPLOY_TEMPLATES = BOX_TEMPLATES.filter( - (t) => !(process.env.CI === "true" && t.name === "agent_python_langchain_box"), -); +// Every Box template deploys, the LangChain one too: the log check ignores the OpenTelemetry noise +// its agent logs at ERROR level (RUNTIME_LOG_NOISE). +const DEPLOY_TEMPLATES = BOX_TEMPLATES; // The templates that run the whole flow, dev before and after build and deploy in one project: one // CodeZip and the container one. Each other template runs build and deploy here, and dev in its own // test below, so its deploy does not wait for a dev step on the shared box ingress port. @@ -1360,9 +1356,20 @@ async function assertRunsInBox( ); const errors = await logs('?ERROR ?"blocked by egress control" ?AccessDenied'); expect(errors.exitCode).toBe(0); - expect(errors.stdout).not.toMatch(/ERROR|blocked by egress control|AccessDenied/); + const failures = errors.stdout + .split("\n") + .filter((line) => /ERROR|blocked by egress control|AccessDenied/.test(line)) + .filter((line) => !RUNTIME_LOG_NOISE.some((noise) => line.includes(noise))); + expect(failures).toEqual([]); } +/** + * Runtime log lines at ERROR level that say nothing about the agent: OpenTelemetry's context + * warning, which the LangChain agent logs when a span ends in another async context than it + * started in, while the request itself succeeds. + */ +const RUNTIME_LOG_NOISE = ["Failed to detach context"]; + /** Deploys `projectDir`, runs `scenario`, and tears the stack down even when a step fails. */ async function deployed( cli: CliRunner, From 25392e4e1f488922f3096886dfb2d6b7a8b9e5dd Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sat, 28 Nov 2026 00:48:05 -0800 Subject: [PATCH 02/11] test(e2e): Split the template e2e tests into one file per suite group, so Vitest runs them in parallel --- .github/workflows/e2e-test.yml | 2 +- e2eTest/project/boxEgress.test.ts | 224 ++++++ e2eTest/project/boxScenarios.test.ts | 214 +++++ e2eTest/project/boxTemplates.test.ts | 129 +++ e2eTest/project/runtimeTemplates.test.ts | 105 +++ ...ates.test.ts => templates-test-support.ts} | 744 ++---------------- vitest.e2e.config.ts | 3 + 7 files changed, 757 insertions(+), 664 deletions(-) create mode 100644 e2eTest/project/boxEgress.test.ts create mode 100644 e2eTest/project/boxScenarios.test.ts create mode 100644 e2eTest/project/boxTemplates.test.ts create mode 100644 e2eTest/project/runtimeTemplates.test.ts rename e2eTest/project/{templates.test.ts => templates-test-support.ts} (58%) diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 0187e6cfa..3711d8a37 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -223,7 +223,7 @@ jobs: # Leave no token in .l3-cdk/.git for later steps. persist-credentials: false # Packed onto the runner only: nothing is published. The Box tests install it into each Box - # project's agentcore/cdk (AGENTCORE_E2E_BOX_CDK in e2eTest/project/templates.test.ts). + # project's agentcore/cdk (AGENTCORE_E2E_BOX_CDK in e2eTest/project/templates-test-support.ts). - name: Pack the L3 constructs for the Box tests if: matrix.name == 'macOS' || matrix.name == 'Linux-arm64' working-directory: .l3-cdk diff --git a/e2eTest/project/boxEgress.test.ts b/e2eTest/project/boxEgress.test.ts new file mode 100644 index 000000000..a1b92c9ca --- /dev/null +++ b/e2eTest/project/boxEgress.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, test } from "vitest"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { retry } from "../helpers/retry"; +import { TIMEOUT_MS } from "../timeouts"; +import { + BOX_ON_PATH, + BOX_DEPLOYS, + BOX_TEMPLATES, + OperationSchema, + RuntimeInvokeResponseSchema, + DeployResponseSchema, + CREATED_RUNTIME_NAME, + BOX_DEV_PORTS, + ECHO_URL, + ECHO_AGENT, + MCP_SERVER_URL, + GATEWAY_AGENT, + useEgressAgent, + assertEgressReply, + assertRunsInBox, + deployed, + ask, + askAgent, + DEPLOY_TEST_TIMEOUT, + tearDown, + createTemplateProject, + invokeLocally, + getSessionId, + withDevPort, +} from "./templates-test-support"; + +describe.skipIf(!BOX_ON_PATH)( + "egress under dev for a Strands Box template", + { tags: [TAGS.BOX_EGRESS] }, + () => { + const cli = new CliRunner(); + const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); + if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case"); + + test( + "allows the profile's host and blocks any other", + { + retry: 2, + timeout: TIMEOUT_MS.PROJECT_CREATE + TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE, + }, + async () => { + const template = runtime; + const projectDir = await createTemplateProject(cli, template, { deploys: false }); + await useEgressAgent(projectDir); + + const port = BOX_DEV_PORTS[template.protocol]; + const { response } = await withDevPort(port, () => + invokeLocally(cli, template, projectDir, port), + ); + assertEgressReply(response.body); + }, + ); + }, +); + +// The same egress check on AgentCore Runtime, where box sends the allowed host's calls through the +// runtime's Box gateway, and the scenarios that need a public host. Each deploys its own project, so +// they run concurrently. They need the AGENTCORE_E2E_BOX_CDK opt-in as well. +describe.skipIf(!BOX_DEPLOYS)( + "egress on AgentCore Runtime for a Strands Box template", + { tags: [TAGS.BOX_EGRESS] }, + () => { + const cli = new CliRunner(); + const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); + if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case"); + + // The public hosts can fail a call, so only the invoke retries: a retry of the whole test would + // deploy and remove the stack again. + test.concurrent( + "allows the profile's host through the Box gateway and blocks any other", + { + timeout: + TIMEOUT_MS.PROJECT_CREATE + + 3 * TIMEOUT_MS.PROJECT_INVOKE + + 2 * TIMEOUT_MS.PROJECT_DEPLOY + + TIMEOUT_MS.PROJECT_REMOVE, + }, + async () => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + await useEgressAgent(projectDir); + let scenarioCompleted = false; + try { + const deployment = parseResult( + DeployResponseSchema, + await cli.run(["deploy", "--yes", "--json"], projectDir), + ); + expect(deployment.message).toContain("deployed project"); + + await retry( + async () => { + const response = parseResult( + RuntimeInvokeResponseSchema, + await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--session-id", + getSessionId(`${runtime.name}-egress`), + "--payload", + JSON.stringify(runtime.payload), + "--json", + ], + projectDir, + ), + ); + expect(response.statusCode).toBeGreaterThanOrEqual(200); + expect(response.statusCode).toBeLessThan(300); + assertEgressReply(response.body); + }, + 3 * TIMEOUT_MS.PROJECT_INVOKE, + 15 * 1000, + ); + scenarioCompleted = true; + } finally { + // Tear the stack down even when a step above failed. + await tearDown(cli, projectDir, scenarioCompleted); + } + }, + ); + + // The profile's egress entry names an env:// key: build stops until deploy has stored it, + // deploy stores it as an API key credential, and the Box gateway sends it to the host. The + // agent never holds the key, so the echoed header can only come from the gateway. + test.concurrent( + "an egress route with an env:// key reaches its host with the key the Box gateway adds", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + const key = `e2e${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`; + const env = { E2E_ECHO_KEY: key }; + await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), ECHO_AGENT); + const profile = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local", "profile.toml"); + await writeFile( + profile, + `${await readFile(profile, "utf8")}\n[egress.echo]\ndestinations = ["${new URL(ECHO_URL).host}"]\nsecret.ref = "env://E2E_ECHO_KEY"\n`, + ); + const build = await cli.run(["build", "--json"], projectDir, env); + expect(build.exitCode).not.toBe(0); + expect(`${build.stdout}${build.stderr}`).toContain("before its first deployment"); + await deployed( + cli, + projectDir, + async () => { + await retry( + async () => { + const body = await ask( + cli, + projectDir, + CREATED_RUNTIME_NAME, + getSessionId("box-echo"), + "echo", + ); + const reply = JSON.parse(body) as { + status?: number; + authorization?: string; + error?: string; + }; + expect(reply.error).toBeUndefined(); + expect(reply.status).toBe(200); + expect(reply.authorization).toBe(`Bearer ${key}`); + }, + 3 * TIMEOUT_MS.PROJECT_INVOKE, + 15 * 1000, + ); + }, + env, + ); + }, + ); + + // A gateway added with `add gateway` reaches a boxed runtime through its Box gateway: build + // gives the Box gateway a target for it, and the runtime its URL. The gateway's target is a + // public MCP server, so the agent lists that server's tools through both gateways. That server + // is a public host, and deploy syncs the target's tools from it, so the test has the box-egress + // tag. + test.concurrent( + "a gateway added with add gateway and add gateway-target lists its target's tools to the boxed agent", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + for (const args of [ + ["add", "gateway", "--name", "tools", "--authorizer-type", "AWS_IAM", "--json"], + [ + "add", + "gateway-target", + "--gateway", + "tools", + "--name", + "docs", + "--endpoint", + MCP_SERVER_URL, + "--outbound-auth", + "none", + "--json", + ], + ]) { + expect(parseResult(OperationSchema, await cli.run(args, projectDir)).operation).toBe( + "add", + ); + } + await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), GATEWAY_AGENT); + await deployed(cli, projectDir, async () => { + await askAgent<{ tools?: string[]; error?: string }>( + cli, + projectDir, + getSessionId("box-gateway"), + "run", + (reply) => expect(reply.tools?.some((name) => name.startsWith("docs___"))).toBe(true), + ); + await assertRunsInBox(cli, projectDir); + }); + }, + ); + }, +); diff --git a/e2eTest/project/boxScenarios.test.ts b/e2eTest/project/boxScenarios.test.ts new file mode 100644 index 000000000..1bdc44129 --- /dev/null +++ b/e2eTest/project/boxScenarios.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, test } from "vitest"; +import { existsSync } from "node:fs"; +import { cp, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { retry } from "../helpers/retry"; +import { + BOX_DEPLOYS, + BOX_TEMPLATES, + OperationSchema, + CREATED_RUNTIME_NAME, + MEMORY_AGENT, + addConnection, + allowBrowserWebSocket, + CODE_INTERPRETER_AGENT, + BROWSER_AGENT, + assertRunsInBox, + deployed, + ask, + askAgent, + DEPLOY_TEST_TIMEOUT, + createTemplateProject, + getSessionId, +} from "./templates-test-support"; + +// Box project scenarios on AgentCore Runtime that a user hits beyond one template's happy path: a +// second runtime beside the first's Memory, a Memory added with `add memory`, a Code Interpreter +// and a Browser connection, and Memory that recalls within a session and across sessions. Each +// deploys its own project; they run concurrently. They reach only AWS hosts; the scenarios that +// need a public host are in the box-egress suite above. They need the AGENTCORE_E2E_BOX_CDK +// opt-in, as the flow tests do. +describe.skipIf(!BOX_DEPLOYS)( + "Box project scenarios on AgentCore Runtime", + { tags: [TAGS.BOX] }, + () => { + const cli = new CliRunner(); + const strands = BOX_TEMPLATES.find((t) => t.template === "agent-python-strands-box"); + const minimal = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); + if (!strands || !minimal) + throw new Error("BOX_TEMPLATES lacks the strands or minimal box case"); + + // A Box project's runtimes each run in a box, and the box pack of each reads the ID of every + // project Memory, so a runtime added beside the first, whose Memory it gets, must start. + test.concurrent( + "a runtime added to a Box project with a Memory deploys and answers beside the first", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, strands, { deploys: true }); + const added = parseResult( + OperationSchema, + await cli.run( + ["add", "runtime", "--name", "second", "--language", "python", "--json"], + projectDir, + ), + ); + expect(added.operation).toBe("add"); + // add runtime writes start.py and the docs; the agent code is the user's, here the first's. + const from = join(projectDir, "app", CREATED_RUNTIME_NAME); + const to = join(projectDir, "app", "second"); + for (const entry of [ + "main.py", + "pyproject.toml", + "uv.lock", + "model", + "memory", + "parse.py", + ]) { + // The first's code must reach the second; the other files only when the template has + // them. + if (entry === "main.py" || existsSync(join(from, entry))) { + await cp(join(from, entry), join(to, entry), { recursive: true }); + } + } + await deployed(cli, projectDir, async () => { + await ask( + cli, + projectDir, + CREATED_RUNTIME_NAME, + getSessionId("box-two-a"), + "Reply with a short greeting.", + ); + await ask( + cli, + projectDir, + "second", + getSessionId("box-two-b"), + "Reply with a short greeting.", + ); + await assertRunsInBox(cli, projectDir, "second"); + }); + }, + ); + + // A Memory added with `add memory` is a project Memory like the default one: the runtime gets + // its ID, and box sends the agent's calls to it to Memory directly, signed with the execution + // role. The minimal template has no Memory of its own, so this Memory is the project's only + // one. + test.concurrent( + "a Memory added with add memory takes and returns an event of the boxed agent", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, minimal, { deploys: true }); + const added = parseResult( + OperationSchema, + await cli.run(["add", "memory", "--name", "notes", "--json"], projectDir), + ); + expect(added.operation).toBe("add"); + await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), MEMORY_AGENT); + const note = `note-${Date.now().toString(36)}`; + await deployed(cli, projectDir, async () => { + await askAgent<{ stored?: string[]; error?: string }>( + cli, + projectDir, + getSessionId("box-notes"), + note, + (reply) => expect(reply.stored).toContain(note), + ); + await assertRunsInBox(cli, projectDir); + }); + }, + ); + + // A runtime reaches the AWS-managed Code Interpreter through a `codeInterpreter` connection in + // agentcore.json, which grants its role the tool. Its calls go to the AgentCore host, which box + // sends directly, signed with the execution role, because the project has a Memory. + test.concurrent( + "a Code Interpreter connection runs code for the boxed agent", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, strands, { deploys: true }); + await addConnection(projectDir, "codeInterpreter"); + await writeFile( + join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), + CODE_INTERPRETER_AGENT, + ); + await deployed(cli, projectDir, async () => { + await askAgent<{ output?: string; error?: string }>( + cli, + projectDir, + getSessionId("box-code"), + "run", + (reply) => expect(reply.output).toContain("42"), + ); + await assertRunsInBox(cli, projectDir); + }); + }, + ); + + // A runtime reaches the AWS-managed Browser through a `browser` connection. The agent starts a + // session over the AgentCore host, then drives the browser over the session's automation + // WebSocket on the same host. A route permits no WebSocket, and build adds no permit for one, + // so the user writes it in a policy of the local profile, as this test does. + test.concurrent( + "a Browser connection opens a browser that the boxed agent drives", + { timeout: DEPLOY_TEST_TIMEOUT }, + async () => { + const projectDir = await createTemplateProject(cli, strands, { deploys: true }); + await addConnection(projectDir, "browser"); + await allowBrowserWebSocket(projectDir); + await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), BROWSER_AGENT); + await deployed(cli, projectDir, async () => { + await askAgent<{ product?: string; error?: string }>( + cli, + projectDir, + getSessionId("box-browser"), + "run", + (reply) => expect(reply.product).toMatch(/Chrom/i), + ); + await assertRunsInBox(cli, projectDir); + }); + }, + ); + + // The template's agent keeps the conversation in Memory: short-term events within a session, + // and facts that long-term extraction makes available to a new session of the same actor. + test.concurrent( + "Memory recalls a fact within a session and from a new session", + { timeout: DEPLOY_TEST_TIMEOUT + 10 * 60 * 1000 }, + async () => { + const projectDir = await createTemplateProject(cli, strands, { deploys: true }); + const color = `teal${Date.now().toString(36).slice(-4)}`; + await deployed(cli, projectDir, async () => { + const first = getSessionId("box-mem-a"); + await ask( + cli, + projectDir, + CREATED_RUNTIME_NAME, + first, + `My favorite color is ${color}. Remember it.`, + ); + expect( + await ask(cli, projectDir, CREATED_RUNTIME_NAME, first, "What is my favorite color?"), + ).toMatch(new RegExp(color, "i")); + // Extraction into long-term memory takes a few minutes. + await retry( + async () => { + const reply = await ask( + cli, + projectDir, + CREATED_RUNTIME_NAME, + getSessionId("box-mem-b"), + "What is my favorite color?", + ); + expect(reply).toMatch(new RegExp(color, "i")); + }, + 10 * 60 * 1000, + 60 * 1000, + ); + }); + }, + ); + }, +); diff --git a/e2eTest/project/boxTemplates.test.ts b/e2eTest/project/boxTemplates.test.ts new file mode 100644 index 000000000..736e4a1d9 --- /dev/null +++ b/e2eTest/project/boxTemplates.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, test } from "vitest"; +import { TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { TIMEOUT_MS } from "../timeouts"; +import { + BOX_ON_PATH, + BOX_DEPLOYS, + BOX_TEMPLATES, + RuntimeInvokeResponseSchema, + DeployResponseSchema, + JsonObjectSchema, + CREATED_RUNTIME_NAME, + DEPLOY_TEMPLATES, + fullFlow, + DEV_ONLY_TEMPLATES, + assertStrandsBoxAssets, + assertRunsInBox, + tearDown, + createTemplateProject, + devInBox, + assertProtocolResponse, + getSessionId, +} from "./templates-test-support"; + +// The Strands Box templates run their agent in a box, locally and on AgentCore Runtime. Each test +// takes one project through build, deploy, invoke, and checks that the Runtime started the agent +// in a box. The FULL_FLOW_TEMPLATES also run dev and invoke --local before build and again after +// deploy, in the same project, as a user does: dev leaves state that build and deploy then read +// (box binds each profile name to the file that ran it), and build and deploy leave state that dev +// must still run beside. Their dev steps wait for the other tests on their box ingress port +// (withDevPort); every deploy runs concurrently. The container template skips dev without a +// container tool. They need `box` on PATH and the AGENTCORE_E2E_BOX_CDK opt-in, a Box-capable +// @aws/agentcore-cdk build. Run them with `bun run test:e2e -- --tagsFilter='box'`. +describe.skipIf(!BOX_DEPLOYS)( + "build, deploy, invoke for Strands Box templates, with dev before and after for some", + { tags: [TAGS.RUNTIME, TAGS.BOX] }, + () => { + const cli = new CliRunner(); + const cases = DEPLOY_TEMPLATES.map((runtime) => ({ + ...runtime, + flow: fullFlow(runtime) ? "dev, build, deploy, dev" : "build, deploy", + })); + + test.concurrent.each(cases)( + "$name: $flow", + { + // A dev step may wait for every other dev step on its port. + timeout: + TIMEOUT_MS.PROJECT_CREATE + + 2 * BOX_TEMPLATES.length * (TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE) + + 2 * TIMEOUT_MS.PROJECT_INVOKE + + 3 * TIMEOUT_MS.PROJECT_DEPLOY + + TIMEOUT_MS.PROJECT_REMOVE, + }, + async (runtime) => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + const withDev = fullFlow(runtime); + let scenarioCompleted = false; + try { + if (withDev) await devInBox(cli, runtime, projectDir); + + // Build after dev, as a user does: build runs box on the local profile that dev ran. + parseResult(JsonObjectSchema, await cli.run(["build", "--json"], projectDir)); + await assertStrandsBoxAssets(projectDir); + + const deployment = parseResult( + DeployResponseSchema, + await cli.run(["deploy", "--yes", "--json"], projectDir), + ); + expect(deployment.message).toContain("deployed project"); + + const response = parseResult( + RuntimeInvokeResponseSchema, + await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--session-id", + getSessionId(runtime.name), + "--payload", + JSON.stringify(runtime.payload), + "--json", + ...(runtime.invokeFlags ?? []), + ], + projectDir, + ), + ); + expect(response.complete).toBe(true); + // An agent that box started but that failed answers with an error status or nothing. + expect(response.statusCode).toBeGreaterThanOrEqual(200); + expect(response.statusCode).toBeLessThan(300); + expect(response.body.trim()).not.toBe(""); + if (runtime.protocol === "MCP" || runtime.protocol === "A2A") { + assertProtocolResponse(runtime, response.body); + } + + await assertRunsInBox(cli, projectDir); + + // Dev again after build and deploy: they leave state (box's profile bindings, the + // Runtime profile, .box-dist) that dev must still run beside. + if (withDev) await devInBox(cli, runtime, projectDir); + scenarioCompleted = true; + } finally { + // Tear the stack down even when a step above failed. + await tearDown(cli, projectDir, scenarioCompleted); + } + }, + ); + }, +); + +describe.skipIf(!BOX_ON_PATH || DEV_ONLY_TEMPLATES.length === 0)( + "create and dev for Strands Box templates", + { tags: [TAGS.BOX], sequential: true }, + () => { + const cli = new CliRunner(); + const templates = DEV_ONLY_TEMPLATES; + + test.each(templates)( + "$name", + { timeout: TIMEOUT_MS.PROJECT_CREATE + TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE }, + async (runtime) => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: false }); + await devInBox(cli, runtime, projectDir); + }, + ); + }, +); diff --git a/e2eTest/project/runtimeTemplates.test.ts b/e2eTest/project/runtimeTemplates.test.ts new file mode 100644 index 000000000..a9511b675 --- /dev/null +++ b/e2eTest/project/runtimeTemplates.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, test } from "vitest"; +import { TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { TIMEOUT_MS } from "../timeouts"; +import { + RUNTIME_TEMPLATES, + OperationSchema, + RuntimeInvokeResponseSchema, + DeployResponseSchema, + JsonObjectSchema, + CREATED_RUNTIME_NAME, + LOCAL_DEV_PORT_BASE, + assertRunsInBox, + createTemplateProject, + invokeLocally, + assertProtocolResponse, + getSessionId, +} from "./templates-test-support"; + +// Each template gets its own project from `agentcore create --template`, the +// command that scaffolds template code (`add runtime` only writes docs). The +// projects are independent, so the templates run concurrently; each one's +// steps run in order inside its test. +describe( + "create, dev, deploy, invoke for runtime templates", + { tags: [TAGS.RUNTIME, TAGS.CANARY] }, + () => { + const cli = new CliRunner(); + + test.concurrent.each(RUNTIME_TEMPLATES)( + "$name", + { + timeout: + TIMEOUT_MS.PROJECT_CREATE + + TIMEOUT_MS.PROJECT_DEV + + 2 * TIMEOUT_MS.PROJECT_INVOKE + + 2 * TIMEOUT_MS.PROJECT_DEPLOY + + TIMEOUT_MS.PROJECT_REMOVE, + }, + async (runtime) => { + const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); + let scenarioCompleted = false; + try { + if (!runtime.skipDev) { + await invokeLocally( + cli, + runtime, + projectDir, + LOCAL_DEV_PORT_BASE + RUNTIME_TEMPLATES.indexOf(runtime), + ); + } + + const deployment = parseResult( + DeployResponseSchema, + await cli.run(["deploy", "--yes", "--json"], projectDir), + ); + expect(deployment.message).toContain("deployed project"); + + const response = parseResult( + RuntimeInvokeResponseSchema, + await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--session-id", + getSessionId(runtime.name), + "--payload", + JSON.stringify(runtime.payload), + "--json", + ...(runtime.invokeFlags ?? []), + ], + projectDir, + ), + ); + expect(response.complete).toBe(true); + // As locally: an agent that failed to start answers with an error status or nothing. + expect(response.statusCode).toBeGreaterThanOrEqual(200); + expect(response.statusCode).toBeLessThan(300); + expect(response.body.trim()).not.toBe(""); + if (runtime.protocol === "MCP" || runtime.protocol === "A2A") { + assertProtocolResponse(runtime, response.body); + } + if (runtime.box) await assertRunsInBox(cli, projectDir); + + const removed = parseResult( + OperationSchema, + await cli.run( + ["remove", "runtime", "--name", CREATED_RUNTIME_NAME, "--json"], + projectDir, + ), + ); + expect(removed.operation).toBe("remove"); + scenarioCompleted = true; + } finally { + // Tear the stack down even when a step above failed. + await cli.run(["remove", "all", "--yes", "--json"], projectDir); + const cleanup = await cli.run(["deploy", "--yes", "--json"], projectDir); + // A cleanup error must not replace the scenario's primary diagnostic. + if (scenarioCompleted) parseResult(JsonObjectSchema, cleanup); + } + }, + ); + }, +); diff --git a/e2eTest/project/templates.test.ts b/e2eTest/project/templates-test-support.ts similarity index 58% rename from e2eTest/project/templates.test.ts rename to e2eTest/project/templates-test-support.ts index 63d5e3a33..b89231292 100644 --- a/e2eTest/project/templates.test.ts +++ b/e2eTest/project/templates-test-support.ts @@ -1,18 +1,17 @@ -import { describe, expect, test } from "vitest"; +import { expect } from "vitest"; import spawn from "cross-spawn"; import { spawnSync } from "node:child_process"; -import { existsSync } from "node:fs"; -import { cp, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { randomBytes } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import z from "zod"; -import { E2E_PREFIX, TAGS } from "../constants"; +import { E2E_PREFIX } from "../constants"; import { CliRunner, parseResult, type RunResult } from "../helpers/run"; import { retry } from "../helpers/retry"; import { TIMEOUT_MS } from "../timeouts"; -type RuntimeTemplateTestCase = { +export type RuntimeTemplateTestCase = { name: string; template: string; protocol: "HTTP" | "MCP" | "A2A" | "AGUI"; @@ -32,7 +31,7 @@ type RuntimeTemplateTestCase = { box?: boolean; }; -const MCP_INITIALIZE_PAYLOAD = { +export const MCP_INITIALIZE_PAYLOAD = { jsonrpc: "2.0", id: 1, method: "initialize", @@ -42,7 +41,7 @@ const MCP_INITIALIZE_PAYLOAD = { clientInfo: { name: "agentcore-e2e", version: "1" }, }, }; -const MCP_INITIALIZE_FLAGS = [ +export const MCP_INITIALIZE_FLAGS = [ "--accept", "application/json, text/event-stream", "--mcp-protocol-version", @@ -50,7 +49,7 @@ const MCP_INITIALIZE_FLAGS = [ "--mcp-method", "initialize", ]; -const A2A_MESSAGE_PAYLOAD = { +export const A2A_MESSAGE_PAYLOAD = { jsonrpc: "2.0", id: "agentcore-e2e", method: "message/send", @@ -62,7 +61,7 @@ const A2A_MESSAGE_PAYLOAD = { }, }, }; -const AGUI_RUN_PAYLOAD = { +export const AGUI_RUN_PAYLOAD = { threadId: "agentcore-e2e", runId: "agentcore-e2e", state: {}, @@ -76,10 +75,10 @@ const AGUI_RUN_PAYLOAD = { * Whether a `box` runs from PATH. Create checks for it for a CodeZip box template, and build and * deploy of every Box template run `box profile show`, so the Box tests skip without one. */ -const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; +export const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; /** Whether a container tool that `agentcore dev` uses (docker, podman or finch) runs from PATH. */ -const CONTAINER_TOOL_ON_PATH = ["docker", "podman", "finch"].some( +export const CONTAINER_TOOL_ON_PATH = ["docker", "podman", "finch"].some( (tool) => spawnSync(tool, ["--version"], { stdio: "ignore" }).status === 0, ); /** @@ -87,11 +86,11 @@ const CONTAINER_TOOL_ON_PATH = ["docker", "podman", "finch"].some( * that deploys Box projects, which the pinned release does not yet. It replaces the pin in each * Box project's agentcore/cdk/package.json, so with it unset (as in CI) those tests skip. */ -const BOX_CDK = process.env.AGENTCORE_E2E_BOX_CDK?.trim() || undefined; +export const BOX_CDK = process.env.AGENTCORE_E2E_BOX_CDK?.trim() || undefined; /** Whether the Box tests that deploy run. */ -const BOX_DEPLOYS = BOX_CDK !== undefined && BOX_ON_PATH; +export const BOX_DEPLOYS = BOX_CDK !== undefined && BOX_ON_PATH; -const RUNTIME_TEMPLATES: RuntimeTemplateTestCase[] = [ +export const RUNTIME_TEMPLATES: RuntimeTemplateTestCase[] = [ { name: "agent_python_minimal", template: "agent-python-minimal", @@ -172,7 +171,7 @@ const RUNTIME_TEMPLATES: RuntimeTemplateTestCase[] = [ * The Strands Box templates, which run their agent in a box on AgentCore Runtime. The describe's * `skipIf` is their only skip: a `skip` on an entry here has no effect. */ -const BOX_TEMPLATES: RuntimeTemplateTestCase[] = [ +export const BOX_TEMPLATES: RuntimeTemplateTestCase[] = [ { name: "agent_python_minimal_box", template: "agent-python-minimal-box", @@ -211,31 +210,31 @@ const BOX_TEMPLATES: RuntimeTemplateTestCase[] = [ }, ].map((template) => ({ ...template, box: true })); -const ProjectCreatedSchema = z.object({ +export const ProjectCreatedSchema = z.object({ project: z.object({ path: z.string() }), }); -const OperationSchema = z.object({ operation: z.string() }); -const RuntimeInvokeResponseSchema = z.object({ +export const OperationSchema = z.object({ operation: z.string() }); +export const RuntimeInvokeResponseSchema = z.object({ statusCode: z.number().int(), body: z.string(), bodyEncoding: z.string(), complete: z.boolean(), }); -const LocalRuntimeInvokeResponseSchema = RuntimeInvokeResponseSchema.extend({ +export const LocalRuntimeInvokeResponseSchema = RuntimeInvokeResponseSchema.extend({ statusCode: z.number().int().min(200).max(299), body: z.string().refine((value) => value.trim().length > 0, "response body must not be empty"), bodyEncoding: z.literal("utf8"), complete: z.literal(true), }); -const DeployResponseSchema = z.object({ message: z.string() }); -const JsonObjectSchema = z.record(z.string(), z.unknown()); -const McpResponseSchema = z.object({ +export const DeployResponseSchema = z.object({ message: z.string() }); +export const JsonObjectSchema = z.record(z.string(), z.unknown()); +export const McpResponseSchema = z.object({ jsonrpc: z.literal("2.0"), id: z.unknown(), result: z.object({ protocolVersion: z.string() }), error: z.undefined().optional(), }); -const A2aResponseSchema = z.object({ +export const A2aResponseSchema = z.object({ jsonrpc: z.literal("2.0"), id: z.unknown(), result: z.object({ kind: z.literal("task") }), @@ -243,225 +242,58 @@ const A2aResponseSchema = z.object({ }); /** The runtime `agentcore create --template` scaffolds (DEFAULT_CREATE_RUNTIME_NAME). */ -const CREATED_RUNTIME_NAME = "agent"; +export const CREATED_RUNTIME_NAME = "agent"; /** Keep concurrent local-dev processes off protocol defaults and one another. */ -const LOCAL_DEV_PORT_BASE = 18080; +export const LOCAL_DEV_PORT_BASE = 18080; /** * The port a box profile's ingress listens on, by protocol. Box `dev` must use it, so the box dev * tests run one at a time. */ -const BOX_DEV_PORTS = { HTTP: 8080, AGUI: 8080, MCP: 8000, A2A: 9000 } as const; +export const BOX_DEV_PORTS = { HTTP: 8080, AGUI: 8080, MCP: 8000, A2A: 9000 } as const; -/** The `agentcore dev` step that holds each box ingress port, so the tests that share it take turns. */ -const devPortQueues = new Map>(); +/** How long a dev-port lock may stand before a test takes it as left by a test process that died. */ +const DEV_PORT_LOCK_STALE_MS = 20 * 60 * 1000; /** * Runs `step` once no other test runs `agentcore dev` on `port`. Box listens on the protocol's fixed * ingress port, so two dev runs on one port cannot overlap; the rest of each test (build, deploy, - * invoke) runs concurrently with the others. + * invoke) runs concurrently with the others. The test files run in separate processes, so the lock + * is a directory in the temporary folder, which `mkdir` creates for one process only. */ -async function withDevPort(port: number, step: () => Promise): Promise { - const previous = devPortQueues.get(port) ?? Promise.resolve(); - let release!: () => void; - const mine = new Promise((resolve) => (release = resolve)); - devPortQueues.set( - port, - previous.then(() => mine), - ); - await previous; +export async function withDevPort(port: number, step: () => Promise): Promise { + const lock = join(tmpdir(), `agentcore-e2e-dev-port-${port}.lock`); + for (;;) { + try { + await mkdir(lock); + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + const since = await stat(lock).then( + ({ mtimeMs }) => Date.now() - mtimeMs, + () => 0, + ); + if (since > DEV_PORT_LOCK_STALE_MS) await rm(lock, { recursive: true, force: true }); + else await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } try { return await step(); } finally { - release(); + await rm(lock, { recursive: true, force: true }); } } -// Each template gets its own project from `agentcore create --template`, the -// command that scaffolds template code (`add runtime` only writes docs). The -// projects are independent, so the templates run concurrently; each one's -// steps run in order inside its test. -describe( - "create, dev, deploy, invoke for runtime templates", - { tags: [TAGS.RUNTIME, TAGS.CANARY] }, - () => { - const cli = new CliRunner(); - - test.concurrent.each(RUNTIME_TEMPLATES)( - "$name", - { - timeout: - TIMEOUT_MS.PROJECT_CREATE + - TIMEOUT_MS.PROJECT_DEV + - 2 * TIMEOUT_MS.PROJECT_INVOKE + - 2 * TIMEOUT_MS.PROJECT_DEPLOY + - TIMEOUT_MS.PROJECT_REMOVE, - }, - async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); - let scenarioCompleted = false; - try { - if (!runtime.skipDev) { - await invokeLocally( - cli, - runtime, - projectDir, - LOCAL_DEV_PORT_BASE + RUNTIME_TEMPLATES.indexOf(runtime), - ); - } - - const deployment = parseResult( - DeployResponseSchema, - await cli.run(["deploy", "--yes", "--json"], projectDir), - ); - expect(deployment.message).toContain("deployed project"); - - const response = parseResult( - RuntimeInvokeResponseSchema, - await cli.run( - [ - "invoke", - "--runtime", - CREATED_RUNTIME_NAME, - "--session-id", - getSessionId(runtime.name), - "--payload", - JSON.stringify(runtime.payload), - "--json", - ...(runtime.invokeFlags ?? []), - ], - projectDir, - ), - ); - expect(response.complete).toBe(true); - // As locally: an agent that failed to start answers with an error status or nothing. - expect(response.statusCode).toBeGreaterThanOrEqual(200); - expect(response.statusCode).toBeLessThan(300); - expect(response.body.trim()).not.toBe(""); - if (runtime.protocol === "MCP" || runtime.protocol === "A2A") { - assertProtocolResponse(runtime, response.body); - } - if (runtime.box) await assertRunsInBox(cli, projectDir); - - const removed = parseResult( - OperationSchema, - await cli.run( - ["remove", "runtime", "--name", CREATED_RUNTIME_NAME, "--json"], - projectDir, - ), - ); - expect(removed.operation).toBe("remove"); - scenarioCompleted = true; - } finally { - // Tear the stack down even when a step above failed. - await cli.run(["remove", "all", "--yes", "--json"], projectDir); - const cleanup = await cli.run(["deploy", "--yes", "--json"], projectDir); - // A cleanup error must not replace the scenario's primary diagnostic. - if (scenarioCompleted) parseResult(JsonObjectSchema, cleanup); - } - }, - ); - }, -); - // Every Box template deploys, the LangChain one too: the log check ignores the OpenTelemetry noise // its agent logs at ERROR level (RUNTIME_LOG_NOISE). -const DEPLOY_TEMPLATES = BOX_TEMPLATES; +export const DEPLOY_TEMPLATES = BOX_TEMPLATES; // The templates that run the whole flow, dev before and after build and deploy in one project: one // CodeZip and the container one. Each other template runs build and deploy here, and dev in its own // test below, so its deploy does not wait for a dev step on the shared box ingress port. -const FULL_FLOW_TEMPLATES = new Set([ +export const FULL_FLOW_TEMPLATES = new Set([ "agent-python-minimal-box", "agent-python-strands-box-container", ]); -const fullFlow = (t: RuntimeTemplateTestCase) => FULL_FLOW_TEMPLATES.has(t.template); - -// The Strands Box templates run their agent in a box, locally and on AgentCore Runtime. Each test -// takes one project through build, deploy, invoke, and checks that the Runtime started the agent -// in a box. The FULL_FLOW_TEMPLATES also run dev and invoke --local before build and again after -// deploy, in the same project, as a user does: dev leaves state that build and deploy then read -// (box binds each profile name to the file that ran it), and build and deploy leave state that dev -// must still run beside. Their dev steps wait for the other tests on their box ingress port -// (withDevPort); every deploy runs concurrently. The container template skips dev without a -// container tool. They need `box` on PATH and the AGENTCORE_E2E_BOX_CDK opt-in, a Box-capable -// @aws/agentcore-cdk build. Run them with `bun run test:e2e -- --tagsFilter='box'`. -describe.skipIf(!BOX_DEPLOYS)( - "build, deploy, invoke for Strands Box templates, with dev before and after for some", - { tags: [TAGS.RUNTIME, TAGS.BOX] }, - () => { - const cli = new CliRunner(); - const cases = DEPLOY_TEMPLATES.map((runtime) => ({ - ...runtime, - flow: fullFlow(runtime) ? "dev, build, deploy, dev" : "build, deploy", - })); - - test.concurrent.each(cases)( - "$name: $flow", - { - // A dev step may wait for every other dev step on its port. - timeout: - TIMEOUT_MS.PROJECT_CREATE + - 2 * BOX_TEMPLATES.length * (TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE) + - 2 * TIMEOUT_MS.PROJECT_INVOKE + - 3 * TIMEOUT_MS.PROJECT_DEPLOY + - TIMEOUT_MS.PROJECT_REMOVE, - }, - async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); - const withDev = fullFlow(runtime); - let scenarioCompleted = false; - try { - if (withDev) await devInBox(cli, runtime, projectDir); - - // Build after dev, as a user does: build runs box on the local profile that dev ran. - parseResult(JsonObjectSchema, await cli.run(["build", "--json"], projectDir)); - await assertStrandsBoxAssets(projectDir); - - const deployment = parseResult( - DeployResponseSchema, - await cli.run(["deploy", "--yes", "--json"], projectDir), - ); - expect(deployment.message).toContain("deployed project"); - - const response = parseResult( - RuntimeInvokeResponseSchema, - await cli.run( - [ - "invoke", - "--runtime", - CREATED_RUNTIME_NAME, - "--session-id", - getSessionId(runtime.name), - "--payload", - JSON.stringify(runtime.payload), - "--json", - ...(runtime.invokeFlags ?? []), - ], - projectDir, - ), - ); - expect(response.complete).toBe(true); - // An agent that box started but that failed answers with an error status or nothing. - expect(response.statusCode).toBeGreaterThanOrEqual(200); - expect(response.statusCode).toBeLessThan(300); - expect(response.body.trim()).not.toBe(""); - if (runtime.protocol === "MCP" || runtime.protocol === "A2A") { - assertProtocolResponse(runtime, response.body); - } - - await assertRunsInBox(cli, projectDir); - - // Dev again after build and deploy: they leave state (box's profile bindings, the - // Runtime profile, .box-dist) that dev must still run beside. - if (withDev) await devInBox(cli, runtime, projectDir); - scenarioCompleted = true; - } finally { - // Tear the stack down even when a step above failed. - await tearDown(cli, projectDir, scenarioCompleted); - } - }, - ); - }, -); +export const fullFlow = (t: RuntimeTemplateTestCase) => FULL_FLOW_TEMPLATES.has(t.template); // `agentcore dev` for each Strands Box template that the tests above do not run dev for: every // template on a machine that cannot deploy Box projects (no AGENTCORE_E2E_BOX_CDK), and on one @@ -471,43 +303,25 @@ describe.skipIf(!BOX_DEPLOYS)( // template's dev builds and runs its image, so it needs a container tool, which the CI macOS // runner does not have (no nested virtualization). They need `box` on PATH and a machine where // `box run` can start its sandbox. -const DEV_ONLY_TEMPLATES = BOX_TEMPLATES.filter( +export const DEV_ONLY_TEMPLATES = BOX_TEMPLATES.filter( (t) => (CONTAINER_TOOL_ON_PATH || t.template !== "agent-python-strands-box-container") && !(BOX_DEPLOYS && DEPLOY_TEMPLATES.includes(t) && fullFlow(t)), ); -describe.skipIf(!BOX_ON_PATH || DEV_ONLY_TEMPLATES.length === 0)( - "create and dev for Strands Box templates", - { tags: [TAGS.BOX], sequential: true }, - () => { - const cli = new CliRunner(); - const templates = DEV_ONLY_TEMPLATES; - - test.each(templates)( - "$name", - { timeout: TIMEOUT_MS.PROJECT_CREATE + TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE }, - async (runtime) => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: false }); - await devInBox(cli, runtime, projectDir); - }, - ); - }, -); // Egress from a boxed agent under `agentcore dev`: the box profile allows one host with no // credential, and box blocks every other host. The agent is the minimal template with its code // replaced, so no model call decides the result. The hosts are public, so the network can make // this fail; it has its own tag, keeping it out of `--tagsFilter='box'`. Run it with // `bun run test:e2e -- --tagsFilter='box-egress'`. -const EGRESS_ALLOWED_URL = "https://checkip.amazonaws.com"; -const EGRESS_BLOCKED_URL = "https://example.com"; -const EGRESS_AGENT = `import urllib.request +export const EGRESS_ALLOWED_URL = "https://checkip.amazonaws.com"; +export const EGRESS_BLOCKED_URL = "https://example.com"; +export const EGRESS_AGENT = `import urllib.request from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() - def fetch(url): try: with urllib.request.urlopen(url, timeout=20) as response: @@ -515,408 +329,24 @@ def fetch(url): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - @app.entrypoint def invoke(payload, context): return {"allowed": fetch("${EGRESS_ALLOWED_URL}"), "blocked": fetch("${EGRESS_BLOCKED_URL}")} - if __name__ == "__main__": app.run() `; -const EgressReplySchema = z.object({ +export const EgressReplySchema = z.object({ allowed: z.object({ status: z.number().optional(), error: z.string().optional() }), blocked: z.object({ status: z.number().optional(), error: z.string().optional() }), }); -describe.skipIf(!BOX_ON_PATH)( - "egress under dev for a Strands Box template", - { tags: [TAGS.BOX_EGRESS] }, - () => { - const cli = new CliRunner(); - const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); - if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case"); - - test( - "allows the profile's host and blocks any other", - { - retry: 2, - timeout: TIMEOUT_MS.PROJECT_CREATE + TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE, - }, - async () => { - const template = runtime; - const projectDir = await createTemplateProject(cli, template, { deploys: false }); - await useEgressAgent(projectDir); - - const { response } = await invokeLocally( - cli, - template, - projectDir, - BOX_DEV_PORTS[template.protocol], - ); - assertEgressReply(response.body); - }, - ); - }, -); - -// The same egress check on AgentCore Runtime, where box sends the allowed host's calls through the -// runtime's Box gateway, and the scenarios that need a public host. Each deploys its own project, so -// they run concurrently. They need the AGENTCORE_E2E_BOX_CDK opt-in as well. -describe.skipIf(!BOX_DEPLOYS)( - "egress on AgentCore Runtime for a Strands Box template", - { tags: [TAGS.BOX_EGRESS] }, - () => { - const cli = new CliRunner(); - const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); - if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case"); - - // The public hosts can fail a call, so only the invoke retries: a retry of the whole test would - // deploy and remove the stack again. - test.concurrent( - "allows the profile's host through the Box gateway and blocks any other", - { - timeout: - TIMEOUT_MS.PROJECT_CREATE + - 3 * TIMEOUT_MS.PROJECT_INVOKE + - 2 * TIMEOUT_MS.PROJECT_DEPLOY + - TIMEOUT_MS.PROJECT_REMOVE, - }, - async () => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); - await useEgressAgent(projectDir); - let scenarioCompleted = false; - try { - const deployment = parseResult( - DeployResponseSchema, - await cli.run(["deploy", "--yes", "--json"], projectDir), - ); - expect(deployment.message).toContain("deployed project"); - - await retry( - async () => { - const response = parseResult( - RuntimeInvokeResponseSchema, - await cli.run( - [ - "invoke", - "--runtime", - CREATED_RUNTIME_NAME, - "--session-id", - getSessionId(`${runtime.name}-egress`), - "--payload", - JSON.stringify(runtime.payload), - "--json", - ], - projectDir, - ), - ); - expect(response.statusCode).toBeGreaterThanOrEqual(200); - expect(response.statusCode).toBeLessThan(300); - assertEgressReply(response.body); - }, - 3 * TIMEOUT_MS.PROJECT_INVOKE, - 15 * 1000, - ); - scenarioCompleted = true; - } finally { - // Tear the stack down even when a step above failed. - await tearDown(cli, projectDir, scenarioCompleted); - } - }, - ); - - // The profile's egress entry names an env:// key: build stops until deploy has stored it, - // deploy stores it as an API key credential, and the Box gateway sends it to the host. The - // agent never holds the key, so the echoed header can only come from the gateway. - test.concurrent( - "an egress route with an env:// key reaches its host with the key the Box gateway adds", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); - const key = `e2e${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`; - const env = { E2E_ECHO_KEY: key }; - await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), ECHO_AGENT); - const profile = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local", "profile.toml"); - await writeFile( - profile, - `${await readFile(profile, "utf8")}\n[egress.echo]\ndestinations = ["${new URL(ECHO_URL).host}"]\nsecret.ref = "env://E2E_ECHO_KEY"\n`, - ); - const build = await cli.run(["build", "--json"], projectDir, env); - expect(build.exitCode).not.toBe(0); - expect(`${build.stdout}${build.stderr}`).toContain("before its first deployment"); - await deployed( - cli, - projectDir, - async () => { - await retry( - async () => { - const body = await ask( - cli, - projectDir, - CREATED_RUNTIME_NAME, - getSessionId("box-echo"), - "echo", - ); - const reply = JSON.parse(body) as { - status?: number; - authorization?: string; - error?: string; - }; - expect(reply.error).toBeUndefined(); - expect(reply.status).toBe(200); - expect(reply.authorization).toBe(`Bearer ${key}`); - }, - 3 * TIMEOUT_MS.PROJECT_INVOKE, - 15 * 1000, - ); - }, - env, - ); - }, - ); - - // A gateway added with `add gateway` reaches a boxed runtime through its Box gateway: build - // gives the Box gateway a target for it, and the runtime its URL. The gateway's target is a - // public MCP server, so the agent lists that server's tools through both gateways. That server - // is a public host, and deploy syncs the target's tools from it, so the test has the box-egress - // tag. - test.concurrent( - "a gateway added with add gateway and add gateway-target lists its target's tools to the boxed agent", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, runtime, { deploys: true }); - for (const args of [ - ["add", "gateway", "--name", "tools", "--authorizer-type", "AWS_IAM", "--json"], - [ - "add", - "gateway-target", - "--gateway", - "tools", - "--name", - "docs", - "--endpoint", - MCP_SERVER_URL, - "--outbound-auth", - "none", - "--json", - ], - ]) { - expect(parseResult(OperationSchema, await cli.run(args, projectDir)).operation).toBe( - "add", - ); - } - await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), GATEWAY_AGENT); - await deployed(cli, projectDir, async () => { - await askAgent<{ tools?: string[]; error?: string }>( - cli, - projectDir, - getSessionId("box-gateway"), - "run", - (reply) => expect(reply.tools?.some((name) => name.startsWith("docs___"))).toBe(true), - ); - await assertRunsInBox(cli, projectDir); - }); - }, - ); - }, -); - -// Box project scenarios on AgentCore Runtime that a user hits beyond one template's happy path: a -// second runtime beside the first's Memory, a Memory added with `add memory`, a Code Interpreter -// and a Browser connection, and Memory that recalls within a session and across sessions. Each -// deploys its own project; they run concurrently. They reach only AWS hosts; the scenarios that -// need a public host are in the box-egress suite above. They need the AGENTCORE_E2E_BOX_CDK -// opt-in, as the flow tests do. -describe.skipIf(!BOX_DEPLOYS)( - "Box project scenarios on AgentCore Runtime", - { tags: [TAGS.BOX] }, - () => { - const cli = new CliRunner(); - const strands = BOX_TEMPLATES.find((t) => t.template === "agent-python-strands-box"); - const minimal = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box"); - if (!strands || !minimal) - throw new Error("BOX_TEMPLATES lacks the strands or minimal box case"); - - // A Box project's runtimes each run in a box, and the box pack of each reads the ID of every - // project Memory, so a runtime added beside the first, whose Memory it gets, must start. - test.concurrent( - "a runtime added to a Box project with a Memory deploys and answers beside the first", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, strands, { deploys: true }); - const added = parseResult( - OperationSchema, - await cli.run( - ["add", "runtime", "--name", "second", "--language", "python", "--json"], - projectDir, - ), - ); - expect(added.operation).toBe("add"); - // add runtime writes start.py and the docs; the agent code is the user's, here the first's. - const from = join(projectDir, "app", CREATED_RUNTIME_NAME); - const to = join(projectDir, "app", "second"); - for (const entry of [ - "main.py", - "pyproject.toml", - "uv.lock", - "model", - "memory", - "parse.py", - ]) { - // The first's code must reach the second; the other files only when the template has - // them. - if (entry === "main.py" || existsSync(join(from, entry))) { - await cp(join(from, entry), join(to, entry), { recursive: true }); - } - } - await deployed(cli, projectDir, async () => { - await ask( - cli, - projectDir, - CREATED_RUNTIME_NAME, - getSessionId("box-two-a"), - "Reply with a short greeting.", - ); - await ask( - cli, - projectDir, - "second", - getSessionId("box-two-b"), - "Reply with a short greeting.", - ); - await assertRunsInBox(cli, projectDir, "second"); - }); - }, - ); - - // A Memory added with `add memory` is a project Memory like the default one: the runtime gets - // its ID, and box sends the agent's calls to it to Memory directly, signed with the execution - // role. The minimal template has no Memory of its own, so this Memory is the project's only - // one. - test.concurrent( - "a Memory added with add memory takes and returns an event of the boxed agent", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, minimal, { deploys: true }); - const added = parseResult( - OperationSchema, - await cli.run(["add", "memory", "--name", "notes", "--json"], projectDir), - ); - expect(added.operation).toBe("add"); - await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), MEMORY_AGENT); - const note = `note-${Date.now().toString(36)}`; - await deployed(cli, projectDir, async () => { - await askAgent<{ stored?: string[]; error?: string }>( - cli, - projectDir, - getSessionId("box-notes"), - note, - (reply) => expect(reply.stored).toContain(note), - ); - await assertRunsInBox(cli, projectDir); - }); - }, - ); - - // A runtime reaches the AWS-managed Code Interpreter through a `codeInterpreter` connection in - // agentcore.json, which grants its role the tool. Its calls go to the AgentCore host, which box - // sends directly, signed with the execution role, because the project has a Memory. - test.concurrent( - "a Code Interpreter connection runs code for the boxed agent", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, strands, { deploys: true }); - await addConnection(projectDir, "codeInterpreter"); - await writeFile( - join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), - CODE_INTERPRETER_AGENT, - ); - await deployed(cli, projectDir, async () => { - await askAgent<{ output?: string; error?: string }>( - cli, - projectDir, - getSessionId("box-code"), - "run", - (reply) => expect(reply.output).toContain("42"), - ); - await assertRunsInBox(cli, projectDir); - }); - }, - ); - - // A runtime reaches the AWS-managed Browser through a `browser` connection. The agent starts a - // session over the AgentCore host, then drives the browser over the session's automation - // WebSocket on the same host. A route permits no WebSocket, and build adds no permit for one, - // so the user writes it in a policy of the local profile, as this test does. - test.concurrent( - "a Browser connection opens a browser that the boxed agent drives", - { timeout: DEPLOY_TEST_TIMEOUT }, - async () => { - const projectDir = await createTemplateProject(cli, strands, { deploys: true }); - await addConnection(projectDir, "browser"); - await allowBrowserWebSocket(projectDir); - await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), BROWSER_AGENT); - await deployed(cli, projectDir, async () => { - await askAgent<{ product?: string; error?: string }>( - cli, - projectDir, - getSessionId("box-browser"), - "run", - (reply) => expect(reply.product).toMatch(/Chrom/i), - ); - await assertRunsInBox(cli, projectDir); - }); - }, - ); - - // The template's agent keeps the conversation in Memory: short-term events within a session, - // and facts that long-term extraction makes available to a new session of the same actor. - test.concurrent( - "Memory recalls a fact within a session and from a new session", - { timeout: DEPLOY_TEST_TIMEOUT + 10 * 60 * 1000 }, - async () => { - const projectDir = await createTemplateProject(cli, strands, { deploys: true }); - const color = `teal${Date.now().toString(36).slice(-4)}`; - await deployed(cli, projectDir, async () => { - const first = getSessionId("box-mem-a"); - await ask( - cli, - projectDir, - CREATED_RUNTIME_NAME, - first, - `My favorite color is ${color}. Remember it.`, - ); - expect( - await ask(cli, projectDir, CREATED_RUNTIME_NAME, first, "What is my favorite color?"), - ).toMatch(new RegExp(color, "i")); - // Extraction into long-term memory takes a few minutes. - await retry( - async () => { - const reply = await ask( - cli, - projectDir, - CREATED_RUNTIME_NAME, - getSessionId("box-mem-b"), - "What is my favorite color?", - ); - expect(reply).toMatch(new RegExp(color, "i")); - }, - 10 * 60 * 1000, - 60 * 1000, - ); - }); - }, - ); - }, -); - /** * The text of an invoke reply. A streamed reply is server-sent events, whose text arrives split * across `contentBlockDelta` events, so a word can span two of them; the text is their join. Any * other body is returned as it is. */ -function replyText(body: string): string { +export function replyText(body: string): string { const deltas = body .split("\n") .filter((line) => line.startsWith("data: ")) @@ -936,16 +366,15 @@ function replyText(body: string): string { } /** The public host that answers with the request's headers, for the API key egress scenario. */ -const ECHO_URL = "https://httpbin.org/headers"; +export const ECHO_URL = "https://httpbin.org/headers"; /** An agent that calls ECHO_URL with no credential of its own and returns the Authorization it saw. */ -const ECHO_AGENT = `import json +export const ECHO_AGENT = `import json import urllib.request from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() - @app.entrypoint def invoke(payload, context): try: @@ -955,7 +384,6 @@ def invoke(payload, context): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - if __name__ == "__main__": app.run() `; @@ -964,7 +392,7 @@ if __name__ == "__main__": * An agent that writes the prompt as an event to the `notes` Memory, which `add memory` adds, and * returns the texts of the session's events that Memory gives back. */ -const MEMORY_AGENT = `import os +export const MEMORY_AGENT = `import os from datetime import datetime, timezone import boto3 @@ -972,7 +400,6 @@ from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() - @app.entrypoint def invoke(payload, context): try: @@ -999,13 +426,12 @@ def invoke(payload, context): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - if __name__ == "__main__": app.run() `; /** Adds a connection to the AWS-managed tool `type` to the created runtime in agentcore.json. */ -async function addConnection(projectDir: string, type: "codeInterpreter" | "browser") { +export async function addConnection(projectDir: string, type: "codeInterpreter" | "browser") { const specPath = join(projectDir, "agentcore", "agentcore.json"); const spec = JSON.parse(await readFile(specPath, "utf8")) as { runtimes: { name: string; connections?: { to: { type: string } }[] }[]; @@ -1021,7 +447,7 @@ async function addConnection(projectDir: string, type: "codeInterpreter" | "brow * `policy.dw` beside the local profile permits `websocket:connect` to the AgentCore host of the * profile's region, on the browser stream paths only, and the profile lists it under `policies`. */ -async function allowBrowserWebSocket(projectDir: string): Promise { +export async function allowBrowserWebSocket(projectDir: string): Promise { const local = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local"); const profilePath = join(local, "profile.toml"); const profile = await readFile(profilePath, "utf8"); @@ -1042,13 +468,12 @@ async function allowBrowserWebSocket(projectDir: string): Promise { } /** An agent that runs `print(6 * 7)` in the AWS-managed Code Interpreter and returns its output. */ -const CODE_INTERPRETER_AGENT = `import boto3 +export const CODE_INTERPRETER_AGENT = `import boto3 from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() TOOL = "aws.codeinterpreter.v1" - @app.entrypoint def invoke(payload, context): try: @@ -1074,7 +499,6 @@ def invoke(payload, context): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - if __name__ == "__main__": app.run() `; @@ -1085,7 +509,7 @@ if __name__ == "__main__": * WebSocket client is the standard library's, through the proxy that box gives the agent, so the * agent needs no package beyond the template's. */ -const BROWSER_AGENT = `import base64 +export const BROWSER_AGENT = `import base64 import http.client import json import os @@ -1099,7 +523,6 @@ from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() TOOL = "aws.browser.v1" - def devtools(url, message): target = urllib.parse.urlsplit(url) proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") @@ -1158,7 +581,6 @@ def devtools(url, message): if reply.get("id") == message["id"]: return reply - @app.entrypoint def invoke(payload, context): try: @@ -1174,13 +596,12 @@ def invoke(payload, context): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - if __name__ == "__main__": app.run() `; /** A public MCP server with no authentication, for the gateway target of the gateway scenario. */ -const MCP_SERVER_URL = "https://knowledge-mcp.global.api.aws"; +export const MCP_SERVER_URL = "https://knowledge-mcp.global.api.aws"; /** * An agent that lists the tools of the project gateway \`tools\` at the URL the runtime gets, with @@ -1189,7 +610,7 @@ const MCP_SERVER_URL = "https://knowledge-mcp.global.api.aws"; * which the URL variable leaves out, and returns the gateway's raw answer when a step has no * result, so a failure says what the gateway said. */ -const GATEWAY_AGENT = `import json +export const GATEWAY_AGENT = `import json import os import urllib.parse import urllib.request @@ -1198,7 +619,6 @@ from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() - def rpc(url, body, session=None): headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} if session: @@ -1218,7 +638,6 @@ def rpc(url, body, session=None): reply = next((m for m in messages if m.get("id") == body["id"]), None) return reply, session, text - @app.entrypoint def invoke(payload, context): url = os.environ.get("AGENTCORE_GATEWAY_TOOLS_URL") @@ -1251,7 +670,6 @@ def invoke(payload, context): except Exception as error: return {"error": f"{type(error).__name__}: {error}"} - if __name__ == "__main__": app.run() `; @@ -1260,7 +678,7 @@ if __name__ == "__main__": * Gives the project in `projectDir` the egress agent, and allows its one host, with no credential, * in the runtime's local box profile, which build derives the AgentCore Runtime profile from. */ -async function useEgressAgent(projectDir: string): Promise { +export async function useEgressAgent(projectDir: string): Promise { await writeFile(join(projectDir, "app", CREATED_RUNTIME_NAME, "main.py"), EGRESS_AGENT); const profile = join(projectDir, ".box", CREATED_RUNTIME_NAME, "local", "profile.toml"); const host = new URL(EGRESS_ALLOWED_URL).host; @@ -1271,7 +689,7 @@ async function useEgressAgent(projectDir: string): Promise { } /** Checks the egress agent's reply: the allowed host answers, and box refuses the other one. */ -function assertEgressReply(body: string): void { +export function assertEgressReply(body: string): void { const reply = EgressReplySchema.parse(JSON.parse(body)); expect(reply.allowed).toEqual({ status: 200 }); expect(reply.blocked.error).toMatch(/403/); @@ -1287,7 +705,7 @@ function assertEgressReply(body: string): void { * (the L3's image tag prefix), so the runtime's code or image URI shows that it belongs to a Strands * Box project. Reads `agentcore build`'s output in agentcore/cdk/cdk.out. */ -async function assertStrandsBoxAssets(projectDir: string): Promise { +export async function assertStrandsBoxAssets(projectDir: string): Promise { const cdkOut = join(projectDir, "agentcore", "cdk", "cdk.out"); const manifestFiles = (await readdir(cdkOut)).filter((file) => file.endsWith(".assets.json")); expect(manifestFiles.length).toBeGreaterThan(0); @@ -1313,7 +731,7 @@ async function assertStrandsBoxAssets(projectDir: string): Promise { expect(templateText).toMatch(/:strands-box-[0-9a-f]{64}"/); } -async function assertRunsInBox( +export async function assertRunsInBox( cli: CliRunner, projectDir: string, runtimeName: string = CREATED_RUNTIME_NAME, @@ -1368,10 +786,10 @@ async function assertRunsInBox( * warning, which the LangChain agent logs when a span ends in another async context than it * started in, while the request itself succeeds. */ -const RUNTIME_LOG_NOISE = ["Failed to detach context"]; +export const RUNTIME_LOG_NOISE = ["Failed to detach context"]; /** Deploys `projectDir`, runs `scenario`, and tears the stack down even when a step fails. */ -async function deployed( +export async function deployed( cli: CliRunner, projectDir: string, scenario: () => Promise, @@ -1392,7 +810,7 @@ async function deployed( } /** Invokes runtime `name` of `projectDir` with `prompt` in `session`, and returns the reply. */ -async function ask( +export async function ask( cli: CliRunner, projectDir: string, name: string, @@ -1426,7 +844,7 @@ async function ask( * component and answers in JSON, and checks the reply with `check`. Retried, since a component * the deploy just made can take a moment to answer. */ -async function askAgent( +export async function askAgent( cli: CliRunner, projectDir: string, session: string, @@ -1447,7 +865,7 @@ async function askAgent( } /** The timeout of a Box scenario that deploys a project once and removes it. */ -const DEPLOY_TEST_TIMEOUT = +export const DEPLOY_TEST_TIMEOUT = TIMEOUT_MS.PROJECT_CREATE + 6 * TIMEOUT_MS.PROJECT_INVOKE + 3 * TIMEOUT_MS.PROJECT_DEPLOY + @@ -1458,7 +876,7 @@ const DEPLOY_TEST_TIMEOUT = * `remove all` emptied the spec and the deploy removed the project. After a failed scenario, a * cleanup failure is logged beside the scenario's error, which stays the test's failure. */ -async function tearDown( +export async function tearDown( cli: CliRunner, projectDir: string, scenarioCompleted: boolean, @@ -1478,7 +896,7 @@ async function tearDown( } /** Six random lowercase letters and digits, for a project name. */ -function randomSuffix(): string { +export function randomSuffix(): string { const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; return Array.from(randomBytes(6), (byte) => alphabet[byte % alphabet.length]).join(""); } @@ -1488,7 +906,7 @@ function randomSuffix(): string { * project that `deploys` gets the AGENTCORE_E2E_BOX_CDK build; one that only runs `agentcore dev` * has no use for it. */ -async function createTemplateProject( +export async function createTemplateProject( cli: CliRunner, runtime: RuntimeTemplateTestCase, { deploys }: { deploys: boolean }, @@ -1530,7 +948,7 @@ async function createTemplateProject( } /** Given a command, its arguments and a working directory, runs it and captures its result. */ -function runCommand(executable: string, args: string[], cwd: string): Promise { +export function runCommand(executable: string, args: string[], cwd: string): Promise { return new Promise((resolve, reject) => { const child = spawn(executable, args, { cwd, stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; @@ -1546,7 +964,7 @@ function runCommand(executable: string, args: string[], cwd: string): Promise line.startsWith("data: ")) @@ -1669,7 +1087,7 @@ function assertProtocolResponse(runtime: RuntimeTemplateTestCase, body: string): } /** Given a prefix, returns a sanitized AgentCore-compatible session identifier. */ -function getSessionId(prefix: string): string { +export function getSessionId(prefix: string): string { return `${prefix}${Date.now().toString(36)}` .replace(/[^a-z0-9]/gi, "") .padEnd(40, "x") diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 272f1c015..9c3b06116 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -7,5 +7,8 @@ export default defineConfig({ setupFiles: ["./e2eTest/setup.ts"], tags: Object.values(TAGS).map((name) => ({ name })), reporters: ["verbose"], + // The tests wait on AWS, not the CPU: run every test file at once, also on a runner with few + // CPUs, where Vitest would otherwise run one or two files at a time. + maxWorkers: 8, }, }); From 10126c17dbbd5c4f2b403f52e97f9cc4e8cf8ea5 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sat, 28 Nov 2026 13:56:37 -0800 Subject: [PATCH 03/11] test(e2e): Deploy the CodeZip Box template on Python 3.10 only beside 3.14, and run three e2e files at a time on macOS --- e2eTest/project/templates-test-support.ts | 27 +++++++++++------------ vitest.e2e.config.ts | 6 ++--- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/e2eTest/project/templates-test-support.ts b/e2eTest/project/templates-test-support.ts index b89231292..6ebb26d41 100644 --- a/e2eTest/project/templates-test-support.ts +++ b/e2eTest/project/templates-test-support.ts @@ -114,20 +114,19 @@ export const RUNTIME_TEMPLATES: RuntimeTemplateTestCase[] = [ }, // The box templates run their agent in Strands Box on AgentCore Runtime; the cases test create, // deploy and invoke, not `agentcore dev`. They run only with the AGENTCORE_E2E_BOX_CDK opt-in. - // The CodeZip box template on each other Python the CodeZip Runtime supports; it defaults to 3.14, - // which the Box describe below covers, as it does the box container template. - ...(["PYTHON_3_10", "PYTHON_3_11", "PYTHON_3_12", "PYTHON_3_13"] as const).map( - (runtimeVersion) => ({ - name: `py_strands_box_${runtimeVersion.slice("PYTHON_".length)}`, - template: "agent-python-strands-box", - protocol: "HTTP" as const, - payload: { prompt: "Reply with a short greeting." }, - skipDev: true, - runtimeVersion, - box: true, - skip: !BOX_DEPLOYS, - }), - ), + // The CodeZip box template on the oldest Python the CodeZip Runtime supports. It defaults to 3.14, + // the newest, which the Box tests cover, as they do the box container template; the versions + // between them are not deployed. + ...(["PYTHON_3_10"] as const).map((runtimeVersion) => ({ + name: `py_strands_box_${runtimeVersion.slice("PYTHON_".length)}`, + template: "agent-python-strands-box", + protocol: "HTTP" as const, + payload: { prompt: "Reply with a short greeting." }, + skipDev: true, + runtimeVersion, + box: true, + skip: !BOX_DEPLOYS, + })), { name: "agent_python_langchain", template: "agent-python-langchain", diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 9c3b06116..1df63e67b 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -7,8 +7,8 @@ export default defineConfig({ setupFiles: ["./e2eTest/setup.ts"], tags: Object.values(TAGS).map((name) => ({ name })), reporters: ["verbose"], - // The tests wait on AWS, not the CPU: run every test file at once, also on a runner with few - // CPUs, where Vitest would otherwise run one or two files at a time. - maxWorkers: 8, + // The tests mostly wait on AWS, so every test file runs at once. The macOS runner has three + // CPUs, and its box sandboxes, installs and dev servers need them: there, three files at a time. + maxWorkers: process.platform === "darwin" ? 3 : 8, }, }); From 66f094615a98a5a93154bb86e184ed4a365c35b7 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sat, 28 Nov 2026 14:23:36 -0800 Subject: [PATCH 04/11] test(e2e): Run at most three concurrent e2e tests per file, so the deploys of a run stay under CloudFormation's rate limit --- vitest.e2e.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 1df63e67b..f2148d638 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -10,5 +10,8 @@ export default defineConfig({ // The tests mostly wait on AWS, so every test file runs at once. The macOS runner has three // CPUs, and its box sandboxes, installs and dev servers need them: there, three files at a time. maxWorkers: process.platform === "darwin" ? 3 : 8, + // At most three concurrent tests per file. Every job deploys in one region at the same time, + // and more stacks at once get CloudFormation's "Rate exceeded" past the CDK's retries. + maxConcurrency: 3, }, }); From 2d6e116cce9600936ba8e6fb421c323d79195f97 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sat, 28 Nov 2026 20:48:16 -0800 Subject: [PATCH 05/11] test(e2e): Run four e2e files at a time on macOS, and five concurrent tests in the runtime templates file --- vitest.e2e.config.ts | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index f2148d638..696907b54 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -1,17 +1,34 @@ -import { defineConfig } from "vitest/config"; +import { configDefaults, defineConfig } from "vitest/config"; import { TAGS } from "./e2eTest/constants.ts"; +/** The suite of non-Box runtime templates, which only deploys: it takes more concurrent tests. */ +const RUNTIME_TEMPLATES = "e2eTest/project/runtimeTemplates.test.ts"; + export default defineConfig({ test: { - include: ["e2eTest/**/**.test.ts"], setupFiles: ["./e2eTest/setup.ts"], tags: Object.values(TAGS).map((name) => ({ name })), reporters: ["verbose"], // The tests mostly wait on AWS, so every test file runs at once. The macOS runner has three - // CPUs, and its box sandboxes, installs and dev servers need them: there, three files at a time. - maxWorkers: process.platform === "darwin" ? 3 : 8, - // At most three concurrent tests per file. Every job deploys in one region at the same time, - // and more stacks at once get CloudFormation's "Rate exceeded" past the CDK's retries. - maxConcurrency: 3, + // CPUs, and its box sandboxes, installs and dev servers need them: there, four files at a time. + maxWorkers: process.platform === "darwin" ? 4 : 8, + // Every job deploys in one region at the same time, and more stacks at once get + // CloudFormation's "Rate exceeded" past the CDK's retries. So each file runs at most three + // concurrent tests, except the runtime templates, which run nothing locally but dev and take five. + projects: [ + { + extends: true, + test: { name: "runtime-templates", include: [RUNTIME_TEMPLATES], maxConcurrency: 5 }, + }, + { + extends: true, + test: { + name: "e2e", + include: ["e2eTest/**/**.test.ts"], + exclude: [...configDefaults.exclude, RUNTIME_TEMPLATES], + maxConcurrency: 3, + }, + }, + ], }, }); From 0be8d5e78d3209eeab4644ba328fbee512443498 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Sun, 29 Nov 2026 20:59:20 -0800 Subject: [PATCH 06/11] Revert "test(e2e): Run four e2e files at a time on macOS, and five concurrent tests in the runtime templates file" This reverts commit 2d6e116cce9600936ba8e6fb421c323d79195f97. --- vitest.e2e.config.ts | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 696907b54..f2148d638 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -1,34 +1,17 @@ -import { configDefaults, defineConfig } from "vitest/config"; +import { defineConfig } from "vitest/config"; import { TAGS } from "./e2eTest/constants.ts"; -/** The suite of non-Box runtime templates, which only deploys: it takes more concurrent tests. */ -const RUNTIME_TEMPLATES = "e2eTest/project/runtimeTemplates.test.ts"; - export default defineConfig({ test: { + include: ["e2eTest/**/**.test.ts"], setupFiles: ["./e2eTest/setup.ts"], tags: Object.values(TAGS).map((name) => ({ name })), reporters: ["verbose"], // The tests mostly wait on AWS, so every test file runs at once. The macOS runner has three - // CPUs, and its box sandboxes, installs and dev servers need them: there, four files at a time. - maxWorkers: process.platform === "darwin" ? 4 : 8, - // Every job deploys in one region at the same time, and more stacks at once get - // CloudFormation's "Rate exceeded" past the CDK's retries. So each file runs at most three - // concurrent tests, except the runtime templates, which run nothing locally but dev and take five. - projects: [ - { - extends: true, - test: { name: "runtime-templates", include: [RUNTIME_TEMPLATES], maxConcurrency: 5 }, - }, - { - extends: true, - test: { - name: "e2e", - include: ["e2eTest/**/**.test.ts"], - exclude: [...configDefaults.exclude, RUNTIME_TEMPLATES], - maxConcurrency: 3, - }, - }, - ], + // CPUs, and its box sandboxes, installs and dev servers need them: there, three files at a time. + maxWorkers: process.platform === "darwin" ? 3 : 8, + // At most three concurrent tests per file. Every job deploys in one region at the same time, + // and more stacks at once get CloudFormation's "Rate exceeded" past the CDK's retries. + maxConcurrency: 3, }, }); From 558f49e102654f4ddde37f8cd54ec8b83b115d0f Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 30 Nov 2026 11:14:47 -0800 Subject: [PATCH 07/11] test(e2e): Take the create wizard's model choices as create flags, and test them under a tui tag --- e2eTest/constants.ts | 2 + e2eTest/project/tui.test.ts | 112 +++++++++++++++++++++++++++ src/handlers/project/create/index.ts | 47 ++++++++++- src/handlers/project/project.test.ts | 45 ++++++++++- 4 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 e2eTest/project/tui.test.ts diff --git a/e2eTest/constants.ts b/e2eTest/constants.ts index 2df8881a3..b70e69b4c 100644 --- a/e2eTest/constants.ts +++ b/e2eTest/constants.ts @@ -6,4 +6,6 @@ export const TAGS = { CANARY: "canary", HARNESS: "harness", RUNTIME: "runtime", + // The flag forms of the choices the interactive create wizard (TUI) offers. + TUI: "tui", } as const; diff --git a/e2eTest/project/tui.test.ts b/e2eTest/project/tui.test.ts new file mode 100644 index 000000000..460bdfd7e --- /dev/null +++ b/e2eTest/project/tui.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import z from "zod"; +import { E2E_PREFIX, TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { TIMEOUT_MS } from "../timeouts"; + +// The model choices of the interactive create wizard, through the flags that `agentcore create` +// takes for them: for each template the wizard asks a model provider of, each provider, with a +// model ID, an API key (a test value) and, for OpenAICompatible, a base URL. Each test creates the +// project and checks what the wizard's answer must leave in it: the runtime's model provider in +// agentcore.json, the key as a project credential and never in agentcore.json, and the model ID in +// the agent's code. Nothing deploys. Run them with `bun run test:e2e -- --tagsFilter='tui'`. + +/** The templates whose create wizard asks for a model provider. */ +const MODEL_TEMPLATES = [ + { template: "agent-python-strands" }, + { template: "agent-python-strands-container" }, + { template: "agent-typescript-strands" }, + { template: "a2a-python-strands" }, + { template: "agui-python-strands" }, + { template: "agent-python-strands-box", box: true }, + { template: "agent-python-strands-box-container", box: true }, + { template: "a2a-python-strands-box", box: true }, + { template: "agui-python-strands-box", box: true }, +] as const; + +/** The providers the wizard offers, and the flags their answer takes. */ +const PROVIDERS = [ + { provider: "Bedrock", key: false }, + { provider: "Anthropic", key: true }, + { provider: "OpenAI", key: true }, + { provider: "OpenAICompatible", key: true, apiBase: "https://models.example.com/v1" }, + { provider: "Gemini", key: true }, + { provider: "LiteLLM", key: true }, +] as const; + +/** Whether a `box` runs from PATH; create checks for it for a CodeZip box template. */ +const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; + +const CreatedSchema = z.object({ project: z.object({ path: z.string() }) }); + +/** Every file under `dir`, for the model ID check, without `.venv` and `node_modules`. */ +async function filesUnder(dir: string): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + const nested = await Promise.all( + entries + .filter((entry) => entry.name !== ".venv" && entry.name !== "node_modules") + .map((entry) => + entry.isDirectory() ? filesUnder(join(dir, entry.name)) : [join(dir, entry.name)], + ), + ); + return nested.flat(); +} + +describe("create with the model choices of the create wizard", { tags: [TAGS.TUI] }, () => { + const cli = new CliRunner(); + // The wizard offers LiteLLM only for Python templates, as create's flags allow. + const cases = MODEL_TEMPLATES.flatMap((t) => + PROVIDERS.filter((p) => !(p.provider === "LiteLLM" && t.template.includes("typescript"))).map( + (p) => ({ ...t, ...p, name: `${t.template} with ${p.provider}` }), + ), + ); + + test.concurrent.each(cases)("$name", { timeout: TIMEOUT_MS.PROJECT_CREATE }, async (c) => { + if ("box" in c && c.box && !BOX_ON_PATH) return; + const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); + const projectName = `${E2E_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + const modelId = `e2e-model-${c.provider.toLowerCase()}`; + const secret = `e2e-test-key-${Math.random().toString(36).slice(2, 10)}`; + const keyFile = join(parent, "key.txt"); + await writeFile(keyFile, secret); + const created = parseResult( + CreatedSchema, + await cli.run( + [ + "create", + "--name", + projectName, + "--template", + c.template, + "--model-provider", + c.provider, + "--model-id", + modelId, + ...(c.key ? ["--api-key", `file://${keyFile}`] : []), + ...("apiBase" in c ? ["--api-base", c.apiBase] : []), + "--skip-install", + "--skip-git", + "--json", + ], + parent, + ), + ); + const root = created.project.path; + const specText = await readFile(join(root, "agentcore", "agentcore.json"), "utf8"); + const spec = JSON.parse(specText) as { + runtimes: { modelProvider?: string }[]; + credentials?: unknown[]; + }; + expect(spec.runtimes[0]?.modelProvider).toBe(c.provider); + expect(specText).not.toContain(secret); + expect((spec.credentials ?? []).length).toBe(c.key ? 1 : 0); + const code = await Promise.all( + (await filesUnder(join(root, "app"))).map((file) => readFile(file, "utf8").catch(() => "")), + ); + expect(code.some((text) => text.includes(modelId))).toBe(true); + }); +}); diff --git a/src/handlers/project/create/index.ts b/src/handlers/project/create/index.ts index 756dcd016..2971c036a 100644 --- a/src/handlers/project/create/index.ts +++ b/src/handlers/project/create/index.ts @@ -2,11 +2,12 @@ import { createHash } from "node:crypto"; import z from "zod"; import { createHandler, flag, PlatformKey, type Middleware } from "../../../router"; import { assertProjectPathFits } from "./pathLimit"; -import { type AppIO } from "../../../io"; +import { SourceResolver, type AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; import { EMPTY_TEMPLATE_NAME, PROJECT_TEMPLATE_NAMES, + RUNTIME_TEMPLATE_SHORTCUTS, RUNTIME_TEMPLATE_SHORTCUT_NAMES, formatTemplateParameterHelp, isBoxTemplate, @@ -14,6 +15,7 @@ import { } from "../shortcuts"; import { CONTAINMENT_LEVELS, + ModelProviderSchema, PRIVATE_VPC_NOTE, type CreateProjectInput, type ModelProvider, @@ -128,6 +130,24 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = z.boolean().default(false), ), flag("skip-git", "skip initializing a git repository", z.boolean().default(false)), + // The model choices of the create wizard, as flags: a template that takes a model provider + // gets the provider, model ID, API key and base URL the wizard would give it. + flag( + "model-provider", + "the model provider of a template that takes one: Bedrock (default), Anthropic, OpenAI, OpenAICompatible, Gemini or LiteLLM", + ModelProviderSchema.optional(), + ), + flag( + "model-id", + "the model ID, in place of the provider's default", + z.string().min(1).optional(), + ), + flag( + "api-key", + "the model provider's API key (file://path or - for stdin; inline values are rejected)", + z.string().min(1).optional(), + ), + flag("api-base", "the base URL of an OpenAICompatible model", z.string().min(1).optional()), ], handle: async (ctx, flags) => { const name = flags["name"]; @@ -147,6 +167,25 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = region, }; + const modelFlags = (["model-provider", "model-id", "api-key", "api-base"] as const).filter( + (key) => flags[key] !== undefined, + ); + if ( + modelFlags.length > 0 && + (template === EMPTY_TEMPLATE_NAME || + !RUNTIME_TEMPLATE_SHORTCUTS[template].supportsModelProviderOverride) + ) { + throw new InputValidationError( + `--template ${template} takes no model flags: ${modelFlags.map((key) => `--${key}`).join(", ")}.`, + ); + } + const apiKey = + flags["api-key"] === undefined + ? undefined + : await new SourceResolver({ stdin: config.io.stdin }).resolveSecret( + "api-key", + flags["api-key"], + ); const createInput: CreateProjectInput = template === EMPTY_TEMPLATE_NAME ? base @@ -154,6 +193,12 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = ...base, scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: DEFAULT_CREATE_RUNTIME_NAME, + ...(flags["model-provider"] !== undefined && { + modelProvider: flags["model-provider"], + }), + ...(flags["model-id"] !== undefined && { modelId: flags["model-id"] }), + ...(apiKey !== undefined && { apiKey }), + ...(flags["api-base"] !== undefined && { apiBase: flags["api-base"] }), }), }; diff --git a/src/handlers/project/project.test.ts b/src/handlers/project/project.test.ts index 5d7d1a335..bf8643a16 100644 --- a/src/handlers/project/project.test.ts +++ b/src/handlers/project/project.test.ts @@ -613,15 +613,52 @@ describe("project create", () => { await expect(run(["create", "--name", "test"])).rejects.toThrow(/conflicts with/); }); - test("rejects the model flags it no longer takes", async () => { + test("rejects the model flags for a template that takes no model provider", async () => { cleanups.push((await inTempDirectory()).cleanup); - for (const removed of ["--model-provider", "--model-id", "--api-key", "--api-base"]) { - await expect(run(["create", "--name", "MyAgent", removed, "x"])).rejects.toThrow( - `unknown option '${removed}'`, + for (const [flag, value] of [ + ["--model-provider", "anthropic"], + ["--model-id", "x"], + ["--api-key", "file://key.txt"], + ["--api-base", "https://models.example.com"], + ]) { + await expect(run(["create", "--name", "MyAgent", flag!, value!])).rejects.toThrow( + `--template empty takes no model flags: ${flag}.`, ); } }); + test("gives a template the model provider and model ID the wizard would", async () => { + const { path, cleanup } = await inTempDirectory(); + cleanups.push(cleanup); + await writeFile(join(path, "key.txt"), "sk-test-key"); + await run([ + "create", + "--name", + "MyAgent", + "--template", + "agent-python-strands", + "--model-provider", + "anthropic", + "--model-id", + "claude-sonnet-5-5", + "--api-key", + `file://${join(path, "key.txt")}`, + "--skip-install", + "--skip-git", + ]); + const spec = JSON.parse( + await readFile(join(path, "MyAgent", "agentcore", "agentcore.json"), "utf8"), + ); + expect(spec.runtimes[0]).toMatchObject({ modelProvider: "Anthropic" }); + // The model ID goes into the agent's model code, as the wizard writes it. + expect( + await readFile(join(path, "MyAgent", "app", "agent", "model", "load.py"), "utf8"), + ).toContain("claude-sonnet-5-5"); + // The key is stored as a project credential, never in agentcore.json. + expect(spec.credentials).toHaveLength(1); + expect(JSON.stringify(spec)).not.toContain("sk-test-key"); + }); + test("rejects an unknown --template value", async () => { cleanups.push((await inTempDirectory()).cleanup); await expect(run(["create", "--name", "MyAgent", "--template", "nonsense"])).rejects.toThrow(); From b131c173662f0f07105c4ba00d83b61c30c62a6b Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 30 Nov 2026 11:26:23 -0800 Subject: [PATCH 08/11] Revert "test(e2e): Take the create wizard's model choices as create flags, and test them under a tui tag" This reverts commit 558f49e102654f4ddde37f8cd54ec8b83b115d0f. --- e2eTest/constants.ts | 2 - e2eTest/project/tui.test.ts | 112 --------------------------- src/handlers/project/create/index.ts | 47 +---------- src/handlers/project/project.test.ts | 45 +---------- 4 files changed, 5 insertions(+), 201 deletions(-) delete mode 100644 e2eTest/project/tui.test.ts diff --git a/e2eTest/constants.ts b/e2eTest/constants.ts index b70e69b4c..2df8881a3 100644 --- a/e2eTest/constants.ts +++ b/e2eTest/constants.ts @@ -6,6 +6,4 @@ export const TAGS = { CANARY: "canary", HARNESS: "harness", RUNTIME: "runtime", - // The flag forms of the choices the interactive create wizard (TUI) offers. - TUI: "tui", } as const; diff --git a/e2eTest/project/tui.test.ts b/e2eTest/project/tui.test.ts deleted file mode 100644 index 460bdfd7e..000000000 --- a/e2eTest/project/tui.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, expect, test } from "vitest"; -import { spawnSync } from "node:child_process"; -import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import z from "zod"; -import { E2E_PREFIX, TAGS } from "../constants"; -import { CliRunner, parseResult } from "../helpers/run"; -import { TIMEOUT_MS } from "../timeouts"; - -// The model choices of the interactive create wizard, through the flags that `agentcore create` -// takes for them: for each template the wizard asks a model provider of, each provider, with a -// model ID, an API key (a test value) and, for OpenAICompatible, a base URL. Each test creates the -// project and checks what the wizard's answer must leave in it: the runtime's model provider in -// agentcore.json, the key as a project credential and never in agentcore.json, and the model ID in -// the agent's code. Nothing deploys. Run them with `bun run test:e2e -- --tagsFilter='tui'`. - -/** The templates whose create wizard asks for a model provider. */ -const MODEL_TEMPLATES = [ - { template: "agent-python-strands" }, - { template: "agent-python-strands-container" }, - { template: "agent-typescript-strands" }, - { template: "a2a-python-strands" }, - { template: "agui-python-strands" }, - { template: "agent-python-strands-box", box: true }, - { template: "agent-python-strands-box-container", box: true }, - { template: "a2a-python-strands-box", box: true }, - { template: "agui-python-strands-box", box: true }, -] as const; - -/** The providers the wizard offers, and the flags their answer takes. */ -const PROVIDERS = [ - { provider: "Bedrock", key: false }, - { provider: "Anthropic", key: true }, - { provider: "OpenAI", key: true }, - { provider: "OpenAICompatible", key: true, apiBase: "https://models.example.com/v1" }, - { provider: "Gemini", key: true }, - { provider: "LiteLLM", key: true }, -] as const; - -/** Whether a `box` runs from PATH; create checks for it for a CodeZip box template. */ -const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; - -const CreatedSchema = z.object({ project: z.object({ path: z.string() }) }); - -/** Every file under `dir`, for the model ID check, without `.venv` and `node_modules`. */ -async function filesUnder(dir: string): Promise { - const entries = await readdir(dir, { withFileTypes: true }); - const nested = await Promise.all( - entries - .filter((entry) => entry.name !== ".venv" && entry.name !== "node_modules") - .map((entry) => - entry.isDirectory() ? filesUnder(join(dir, entry.name)) : [join(dir, entry.name)], - ), - ); - return nested.flat(); -} - -describe("create with the model choices of the create wizard", { tags: [TAGS.TUI] }, () => { - const cli = new CliRunner(); - // The wizard offers LiteLLM only for Python templates, as create's flags allow. - const cases = MODEL_TEMPLATES.flatMap((t) => - PROVIDERS.filter((p) => !(p.provider === "LiteLLM" && t.template.includes("typescript"))).map( - (p) => ({ ...t, ...p, name: `${t.template} with ${p.provider}` }), - ), - ); - - test.concurrent.each(cases)("$name", { timeout: TIMEOUT_MS.PROJECT_CREATE }, async (c) => { - if ("box" in c && c.box && !BOX_ON_PATH) return; - const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); - const projectName = `${E2E_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; - const modelId = `e2e-model-${c.provider.toLowerCase()}`; - const secret = `e2e-test-key-${Math.random().toString(36).slice(2, 10)}`; - const keyFile = join(parent, "key.txt"); - await writeFile(keyFile, secret); - const created = parseResult( - CreatedSchema, - await cli.run( - [ - "create", - "--name", - projectName, - "--template", - c.template, - "--model-provider", - c.provider, - "--model-id", - modelId, - ...(c.key ? ["--api-key", `file://${keyFile}`] : []), - ...("apiBase" in c ? ["--api-base", c.apiBase] : []), - "--skip-install", - "--skip-git", - "--json", - ], - parent, - ), - ); - const root = created.project.path; - const specText = await readFile(join(root, "agentcore", "agentcore.json"), "utf8"); - const spec = JSON.parse(specText) as { - runtimes: { modelProvider?: string }[]; - credentials?: unknown[]; - }; - expect(spec.runtimes[0]?.modelProvider).toBe(c.provider); - expect(specText).not.toContain(secret); - expect((spec.credentials ?? []).length).toBe(c.key ? 1 : 0); - const code = await Promise.all( - (await filesUnder(join(root, "app"))).map((file) => readFile(file, "utf8").catch(() => "")), - ); - expect(code.some((text) => text.includes(modelId))).toBe(true); - }); -}); diff --git a/src/handlers/project/create/index.ts b/src/handlers/project/create/index.ts index 2971c036a..756dcd016 100644 --- a/src/handlers/project/create/index.ts +++ b/src/handlers/project/create/index.ts @@ -2,12 +2,11 @@ import { createHash } from "node:crypto"; import z from "zod"; import { createHandler, flag, PlatformKey, type Middleware } from "../../../router"; import { assertProjectPathFits } from "./pathLimit"; -import { SourceResolver, type AppIO } from "../../../io"; +import { type AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; import { EMPTY_TEMPLATE_NAME, PROJECT_TEMPLATE_NAMES, - RUNTIME_TEMPLATE_SHORTCUTS, RUNTIME_TEMPLATE_SHORTCUT_NAMES, formatTemplateParameterHelp, isBoxTemplate, @@ -15,7 +14,6 @@ import { } from "../shortcuts"; import { CONTAINMENT_LEVELS, - ModelProviderSchema, PRIVATE_VPC_NOTE, type CreateProjectInput, type ModelProvider, @@ -130,24 +128,6 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = z.boolean().default(false), ), flag("skip-git", "skip initializing a git repository", z.boolean().default(false)), - // The model choices of the create wizard, as flags: a template that takes a model provider - // gets the provider, model ID, API key and base URL the wizard would give it. - flag( - "model-provider", - "the model provider of a template that takes one: Bedrock (default), Anthropic, OpenAI, OpenAICompatible, Gemini or LiteLLM", - ModelProviderSchema.optional(), - ), - flag( - "model-id", - "the model ID, in place of the provider's default", - z.string().min(1).optional(), - ), - flag( - "api-key", - "the model provider's API key (file://path or - for stdin; inline values are rejected)", - z.string().min(1).optional(), - ), - flag("api-base", "the base URL of an OpenAICompatible model", z.string().min(1).optional()), ], handle: async (ctx, flags) => { const name = flags["name"]; @@ -167,25 +147,6 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = region, }; - const modelFlags = (["model-provider", "model-id", "api-key", "api-base"] as const).filter( - (key) => flags[key] !== undefined, - ); - if ( - modelFlags.length > 0 && - (template === EMPTY_TEMPLATE_NAME || - !RUNTIME_TEMPLATE_SHORTCUTS[template].supportsModelProviderOverride) - ) { - throw new InputValidationError( - `--template ${template} takes no model flags: ${modelFlags.map((key) => `--${key}`).join(", ")}.`, - ); - } - const apiKey = - flags["api-key"] === undefined - ? undefined - : await new SourceResolver({ stdin: config.io.stdin }).resolveSecret( - "api-key", - flags["api-key"], - ); const createInput: CreateProjectInput = template === EMPTY_TEMPLATE_NAME ? base @@ -193,12 +154,6 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = ...base, scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: DEFAULT_CREATE_RUNTIME_NAME, - ...(flags["model-provider"] !== undefined && { - modelProvider: flags["model-provider"], - }), - ...(flags["model-id"] !== undefined && { modelId: flags["model-id"] }), - ...(apiKey !== undefined && { apiKey }), - ...(flags["api-base"] !== undefined && { apiBase: flags["api-base"] }), }), }; diff --git a/src/handlers/project/project.test.ts b/src/handlers/project/project.test.ts index bf8643a16..5d7d1a335 100644 --- a/src/handlers/project/project.test.ts +++ b/src/handlers/project/project.test.ts @@ -613,52 +613,15 @@ describe("project create", () => { await expect(run(["create", "--name", "test"])).rejects.toThrow(/conflicts with/); }); - test("rejects the model flags for a template that takes no model provider", async () => { + test("rejects the model flags it no longer takes", async () => { cleanups.push((await inTempDirectory()).cleanup); - for (const [flag, value] of [ - ["--model-provider", "anthropic"], - ["--model-id", "x"], - ["--api-key", "file://key.txt"], - ["--api-base", "https://models.example.com"], - ]) { - await expect(run(["create", "--name", "MyAgent", flag!, value!])).rejects.toThrow( - `--template empty takes no model flags: ${flag}.`, + for (const removed of ["--model-provider", "--model-id", "--api-key", "--api-base"]) { + await expect(run(["create", "--name", "MyAgent", removed, "x"])).rejects.toThrow( + `unknown option '${removed}'`, ); } }); - test("gives a template the model provider and model ID the wizard would", async () => { - const { path, cleanup } = await inTempDirectory(); - cleanups.push(cleanup); - await writeFile(join(path, "key.txt"), "sk-test-key"); - await run([ - "create", - "--name", - "MyAgent", - "--template", - "agent-python-strands", - "--model-provider", - "anthropic", - "--model-id", - "claude-sonnet-5-5", - "--api-key", - `file://${join(path, "key.txt")}`, - "--skip-install", - "--skip-git", - ]); - const spec = JSON.parse( - await readFile(join(path, "MyAgent", "agentcore", "agentcore.json"), "utf8"), - ); - expect(spec.runtimes[0]).toMatchObject({ modelProvider: "Anthropic" }); - // The model ID goes into the agent's model code, as the wizard writes it. - expect( - await readFile(join(path, "MyAgent", "app", "agent", "model", "load.py"), "utf8"), - ).toContain("claude-sonnet-5-5"); - // The key is stored as a project credential, never in agentcore.json. - expect(spec.credentials).toHaveLength(1); - expect(JSON.stringify(spec)).not.toContain("sk-test-key"); - }); - test("rejects an unknown --template value", async () => { cleanups.push((await inTempDirectory()).cleanup); await expect(run(["create", "--name", "MyAgent", "--template", "nonsense"])).rejects.toThrow(); From 9145f56ba87cf49578672adb0ad604a507bb21de Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 30 Nov 2026 11:57:39 -0800 Subject: [PATCH 09/11] Reapply "test(e2e): Take the create wizard's model choices as create flags, and test them under a tui tag" This reverts commit b131c173662f0f07105c4ba00d83b61c30c62a6b. --- e2eTest/constants.ts | 2 + e2eTest/project/tui.test.ts | 112 +++++++++++++++++++++++++++ src/handlers/project/create/index.ts | 47 ++++++++++- src/handlers/project/project.test.ts | 45 ++++++++++- 4 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 e2eTest/project/tui.test.ts diff --git a/e2eTest/constants.ts b/e2eTest/constants.ts index 2df8881a3..b70e69b4c 100644 --- a/e2eTest/constants.ts +++ b/e2eTest/constants.ts @@ -6,4 +6,6 @@ export const TAGS = { CANARY: "canary", HARNESS: "harness", RUNTIME: "runtime", + // The flag forms of the choices the interactive create wizard (TUI) offers. + TUI: "tui", } as const; diff --git a/e2eTest/project/tui.test.ts b/e2eTest/project/tui.test.ts new file mode 100644 index 000000000..460bdfd7e --- /dev/null +++ b/e2eTest/project/tui.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import z from "zod"; +import { E2E_PREFIX, TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { TIMEOUT_MS } from "../timeouts"; + +// The model choices of the interactive create wizard, through the flags that `agentcore create` +// takes for them: for each template the wizard asks a model provider of, each provider, with a +// model ID, an API key (a test value) and, for OpenAICompatible, a base URL. Each test creates the +// project and checks what the wizard's answer must leave in it: the runtime's model provider in +// agentcore.json, the key as a project credential and never in agentcore.json, and the model ID in +// the agent's code. Nothing deploys. Run them with `bun run test:e2e -- --tagsFilter='tui'`. + +/** The templates whose create wizard asks for a model provider. */ +const MODEL_TEMPLATES = [ + { template: "agent-python-strands" }, + { template: "agent-python-strands-container" }, + { template: "agent-typescript-strands" }, + { template: "a2a-python-strands" }, + { template: "agui-python-strands" }, + { template: "agent-python-strands-box", box: true }, + { template: "agent-python-strands-box-container", box: true }, + { template: "a2a-python-strands-box", box: true }, + { template: "agui-python-strands-box", box: true }, +] as const; + +/** The providers the wizard offers, and the flags their answer takes. */ +const PROVIDERS = [ + { provider: "Bedrock", key: false }, + { provider: "Anthropic", key: true }, + { provider: "OpenAI", key: true }, + { provider: "OpenAICompatible", key: true, apiBase: "https://models.example.com/v1" }, + { provider: "Gemini", key: true }, + { provider: "LiteLLM", key: true }, +] as const; + +/** Whether a `box` runs from PATH; create checks for it for a CodeZip box template. */ +const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; + +const CreatedSchema = z.object({ project: z.object({ path: z.string() }) }); + +/** Every file under `dir`, for the model ID check, without `.venv` and `node_modules`. */ +async function filesUnder(dir: string): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + const nested = await Promise.all( + entries + .filter((entry) => entry.name !== ".venv" && entry.name !== "node_modules") + .map((entry) => + entry.isDirectory() ? filesUnder(join(dir, entry.name)) : [join(dir, entry.name)], + ), + ); + return nested.flat(); +} + +describe("create with the model choices of the create wizard", { tags: [TAGS.TUI] }, () => { + const cli = new CliRunner(); + // The wizard offers LiteLLM only for Python templates, as create's flags allow. + const cases = MODEL_TEMPLATES.flatMap((t) => + PROVIDERS.filter((p) => !(p.provider === "LiteLLM" && t.template.includes("typescript"))).map( + (p) => ({ ...t, ...p, name: `${t.template} with ${p.provider}` }), + ), + ); + + test.concurrent.each(cases)("$name", { timeout: TIMEOUT_MS.PROJECT_CREATE }, async (c) => { + if ("box" in c && c.box && !BOX_ON_PATH) return; + const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); + const projectName = `${E2E_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + const modelId = `e2e-model-${c.provider.toLowerCase()}`; + const secret = `e2e-test-key-${Math.random().toString(36).slice(2, 10)}`; + const keyFile = join(parent, "key.txt"); + await writeFile(keyFile, secret); + const created = parseResult( + CreatedSchema, + await cli.run( + [ + "create", + "--name", + projectName, + "--template", + c.template, + "--model-provider", + c.provider, + "--model-id", + modelId, + ...(c.key ? ["--api-key", `file://${keyFile}`] : []), + ...("apiBase" in c ? ["--api-base", c.apiBase] : []), + "--skip-install", + "--skip-git", + "--json", + ], + parent, + ), + ); + const root = created.project.path; + const specText = await readFile(join(root, "agentcore", "agentcore.json"), "utf8"); + const spec = JSON.parse(specText) as { + runtimes: { modelProvider?: string }[]; + credentials?: unknown[]; + }; + expect(spec.runtimes[0]?.modelProvider).toBe(c.provider); + expect(specText).not.toContain(secret); + expect((spec.credentials ?? []).length).toBe(c.key ? 1 : 0); + const code = await Promise.all( + (await filesUnder(join(root, "app"))).map((file) => readFile(file, "utf8").catch(() => "")), + ); + expect(code.some((text) => text.includes(modelId))).toBe(true); + }); +}); diff --git a/src/handlers/project/create/index.ts b/src/handlers/project/create/index.ts index 756dcd016..2971c036a 100644 --- a/src/handlers/project/create/index.ts +++ b/src/handlers/project/create/index.ts @@ -2,11 +2,12 @@ import { createHash } from "node:crypto"; import z from "zod"; import { createHandler, flag, PlatformKey, type Middleware } from "../../../router"; import { assertProjectPathFits } from "./pathLimit"; -import { type AppIO } from "../../../io"; +import { SourceResolver, type AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; import { EMPTY_TEMPLATE_NAME, PROJECT_TEMPLATE_NAMES, + RUNTIME_TEMPLATE_SHORTCUTS, RUNTIME_TEMPLATE_SHORTCUT_NAMES, formatTemplateParameterHelp, isBoxTemplate, @@ -14,6 +15,7 @@ import { } from "../shortcuts"; import { CONTAINMENT_LEVELS, + ModelProviderSchema, PRIVATE_VPC_NOTE, type CreateProjectInput, type ModelProvider, @@ -128,6 +130,24 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = z.boolean().default(false), ), flag("skip-git", "skip initializing a git repository", z.boolean().default(false)), + // The model choices of the create wizard, as flags: a template that takes a model provider + // gets the provider, model ID, API key and base URL the wizard would give it. + flag( + "model-provider", + "the model provider of a template that takes one: Bedrock (default), Anthropic, OpenAI, OpenAICompatible, Gemini or LiteLLM", + ModelProviderSchema.optional(), + ), + flag( + "model-id", + "the model ID, in place of the provider's default", + z.string().min(1).optional(), + ), + flag( + "api-key", + "the model provider's API key (file://path or - for stdin; inline values are rejected)", + z.string().min(1).optional(), + ), + flag("api-base", "the base URL of an OpenAICompatible model", z.string().min(1).optional()), ], handle: async (ctx, flags) => { const name = flags["name"]; @@ -147,6 +167,25 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = region, }; + const modelFlags = (["model-provider", "model-id", "api-key", "api-base"] as const).filter( + (key) => flags[key] !== undefined, + ); + if ( + modelFlags.length > 0 && + (template === EMPTY_TEMPLATE_NAME || + !RUNTIME_TEMPLATE_SHORTCUTS[template].supportsModelProviderOverride) + ) { + throw new InputValidationError( + `--template ${template} takes no model flags: ${modelFlags.map((key) => `--${key}`).join(", ")}.`, + ); + } + const apiKey = + flags["api-key"] === undefined + ? undefined + : await new SourceResolver({ stdin: config.io.stdin }).resolveSecret( + "api-key", + flags["api-key"], + ); const createInput: CreateProjectInput = template === EMPTY_TEMPLATE_NAME ? base @@ -154,6 +193,12 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = ...base, scaffoldRuntimeInput: resolveRuntimeTemplateShortcut(template, { runtimeName: DEFAULT_CREATE_RUNTIME_NAME, + ...(flags["model-provider"] !== undefined && { + modelProvider: flags["model-provider"], + }), + ...(flags["model-id"] !== undefined && { modelId: flags["model-id"] }), + ...(apiKey !== undefined && { apiKey }), + ...(flags["api-base"] !== undefined && { apiBase: flags["api-base"] }), }), }; diff --git a/src/handlers/project/project.test.ts b/src/handlers/project/project.test.ts index 5d7d1a335..bf8643a16 100644 --- a/src/handlers/project/project.test.ts +++ b/src/handlers/project/project.test.ts @@ -613,15 +613,52 @@ describe("project create", () => { await expect(run(["create", "--name", "test"])).rejects.toThrow(/conflicts with/); }); - test("rejects the model flags it no longer takes", async () => { + test("rejects the model flags for a template that takes no model provider", async () => { cleanups.push((await inTempDirectory()).cleanup); - for (const removed of ["--model-provider", "--model-id", "--api-key", "--api-base"]) { - await expect(run(["create", "--name", "MyAgent", removed, "x"])).rejects.toThrow( - `unknown option '${removed}'`, + for (const [flag, value] of [ + ["--model-provider", "anthropic"], + ["--model-id", "x"], + ["--api-key", "file://key.txt"], + ["--api-base", "https://models.example.com"], + ]) { + await expect(run(["create", "--name", "MyAgent", flag!, value!])).rejects.toThrow( + `--template empty takes no model flags: ${flag}.`, ); } }); + test("gives a template the model provider and model ID the wizard would", async () => { + const { path, cleanup } = await inTempDirectory(); + cleanups.push(cleanup); + await writeFile(join(path, "key.txt"), "sk-test-key"); + await run([ + "create", + "--name", + "MyAgent", + "--template", + "agent-python-strands", + "--model-provider", + "anthropic", + "--model-id", + "claude-sonnet-5-5", + "--api-key", + `file://${join(path, "key.txt")}`, + "--skip-install", + "--skip-git", + ]); + const spec = JSON.parse( + await readFile(join(path, "MyAgent", "agentcore", "agentcore.json"), "utf8"), + ); + expect(spec.runtimes[0]).toMatchObject({ modelProvider: "Anthropic" }); + // The model ID goes into the agent's model code, as the wizard writes it. + expect( + await readFile(join(path, "MyAgent", "app", "agent", "model", "load.py"), "utf8"), + ).toContain("claude-sonnet-5-5"); + // The key is stored as a project credential, never in agentcore.json. + expect(spec.credentials).toHaveLength(1); + expect(JSON.stringify(spec)).not.toContain("sk-test-key"); + }); + test("rejects an unknown --template value", async () => { cleanups.push((await inTempDirectory()).cleanup); await expect(run(["create", "--name", "MyAgent", "--template", "nonsense"])).rejects.toThrow(); From 5c3000f32481bd467e299bfb1f46a19797149116 Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 30 Nov 2026 11:48:34 -0800 Subject: [PATCH 10/11] test(e2e): Dev, build, deploy and invoke the Box template on each model provider with a test key, and expect the provider to refuse it --- e2eTest/project/tui.test.ts | 180 ++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) diff --git a/e2eTest/project/tui.test.ts b/e2eTest/project/tui.test.ts index 460bdfd7e..6c98496a9 100644 --- a/e2eTest/project/tui.test.ts +++ b/e2eTest/project/tui.test.ts @@ -6,6 +6,19 @@ import { join } from "node:path"; import z from "zod"; import { E2E_PREFIX, TAGS } from "../constants"; import { CliRunner, parseResult } from "../helpers/run"; +import { retry } from "../helpers/retry"; +import { + BOX_CDK, + BOX_DEPLOYS, + BOX_DEV_PORTS, + CREATED_RUNTIME_NAME, + DeployResponseSchema, + JsonObjectSchema, + getSessionId, + runCommand, + tearDown, + withDevPort, +} from "./templates-test-support"; import { TIMEOUT_MS } from "../timeouts"; // The model choices of the interactive create wizard, through the flags that `agentcore create` @@ -110,3 +123,170 @@ describe("create with the model choices of the create wizard", { tags: [TAGS.TUI expect(code.some((text) => text.includes(modelId))).toBe(true); }); }); + +// The Box template on each model provider the create wizard offers but Bedrock, which the other +// suites cover, through dev, build, deploy and invoke. CI has no keys for these providers, so each +// project takes a test key, and the test expects the provider's own refusal of it: that shows the +// agent's model call left the box through its egress route, with the key, and reached the provider. +// "blocked by egress control" or no refusal at all fails the test. OpenAICompatible points at the +// OpenAI API, so its refusal is OpenAI's. They need box on PATH and the AGENTCORE_E2E_BOX_CDK opt-in. + +/** What a provider answers to a key it does not know, in the words each one uses. */ +const INVALID_KEY = + /invalid[^\n]{0,40}api[ _-]?key|incorrect api key|api key not valid|authentication_?error|invalid_api_key|unauthori[sz]ed|\b401\b/i; + +const DEPLOY_PROVIDERS = [ + { provider: "Anthropic" }, + { provider: "OpenAI" }, + { provider: "OpenAICompatible", apiBase: "https://api.openai.com/v1" }, + { provider: "Gemini" }, + { provider: "LiteLLM" }, +] as const; + +/** Runs `agentcore dev` on the box port, invokes it once, and returns all that both printed. */ +async function devInvokeOutput(cli: CliRunner, projectDir: string): Promise { + const port = BOX_DEV_PORTS.HTTP; + return withDevPort(port, async () => { + let output = ""; + let agentPort: number | undefined; + const dev = cli.start(["dev", "--mode", "headless", "--port", String(port)], projectDir); + const capture = (chunk: Buffer) => { + const text = chunk.toString(); + output += text; + const match = /Agent '([^']+)' is running on port (\d+)\./.exec(output); + if (match?.[1] === CREATED_RUNTIME_NAME) agentPort = Number(match[2]); + }; + dev.stdout?.on("data", capture); + dev.stderr?.on("data", capture); + try { + const deadline = Date.now() + TIMEOUT_MS.PROJECT_DEV; + while (agentPort === undefined) { + if (dev.exitCode !== null) throw new Error(`agentcore dev exited.\n${output}`); + if (Date.now() > deadline) throw new Error(`agentcore dev did not start.\n${output}`); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + const invoked = await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--local", + "--port", + String(agentPort), + "--session-id", + getSessionId("tui-dev"), + "--payload", + JSON.stringify({ prompt: "Reply with a short greeting." }), + "--json", + ], + projectDir, + ); + // The agent logs the model's refusal through dev's output a moment after it answers. + await new Promise((resolve) => setTimeout(resolve, 3000)); + return `${invoked.stdout}\n${invoked.stderr}\n${output}`; + } finally { + if (dev.exitCode === null) { + dev.kill("SIGTERM"); + await new Promise((resolve) => dev.once("close", resolve)); + } + } + }); +} + +describe.skipIf(!BOX_DEPLOYS)( + "dev, build, deploy, invoke the Box template with each model provider and a test key", + { tags: [TAGS.TUI] }, + () => { + const cli = new CliRunner(); + + test.concurrent.each(DEPLOY_PROVIDERS)( + "$provider", + { + timeout: + TIMEOUT_MS.PROJECT_CREATE + + 5 * (TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE) + + 3 * TIMEOUT_MS.PROJECT_INVOKE + + 2 * TIMEOUT_MS.PROJECT_DEPLOY + + TIMEOUT_MS.PROJECT_REMOVE, + }, + async (c) => { + const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); + const keyFile = join(parent, "key.txt"); + await writeFile(keyFile, `e2e-invalid-key-${Math.random().toString(36).slice(2, 10)}`); + const projectName = `${E2E_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + const created = parseResult( + CreatedSchema, + await cli.run( + [ + "create", + "--name", + projectName, + "--template", + "agent-python-strands-box", + "--model-provider", + c.provider, + "--api-key", + `file://${keyFile}`, + ...("apiBase" in c ? ["--api-base", c.apiBase] : []), + "--skip-git", + "--json", + ], + parent, + ), + ); + const projectDir = created.project.path; + const installed = await runCommand( + "npm", + ["install", "--no-audit", "--no-fund", `@aws/agentcore-cdk@${BOX_CDK}`], + join(projectDir, "agentcore", "cdk"), + ); + expect(installed.exitCode).toBe(0); + + const dev = await devInvokeOutput(cli, projectDir); + expect(dev).not.toMatch(/blocked by egress control/); + expect(dev).toMatch(INVALID_KEY); + + let scenarioCompleted = false; + try { + // The key is stored as a credential by the first deploy, so build runs after it. + const deployment = parseResult( + DeployResponseSchema, + await cli.run(["deploy", "--yes", "--json"], projectDir), + ); + expect(deployment.message).toContain("deployed project"); + parseResult(JsonObjectSchema, await cli.run(["build", "--json"], projectDir)); + + await retry( + async () => { + const invoked = await cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--session-id", + getSessionId(`tui-${c.provider.toLowerCase()}`), + "--payload", + JSON.stringify({ prompt: "Reply with a short greeting." }), + "--json", + ], + projectDir, + ); + const logs = await cli.run( + ["logs", "runtime", "--name", CREATED_RUNTIME_NAME, "--since", "30m"], + projectDir, + ); + const text = `${invoked.stdout}\n${invoked.stderr}\n${logs.stdout}`; + expect(text).not.toMatch(/blocked by egress control/); + expect(text).toMatch(INVALID_KEY); + }, + 3 * TIMEOUT_MS.PROJECT_INVOKE, + 30 * 1000, + ); + scenarioCompleted = true; + } finally { + await tearDown(cli, projectDir, scenarioCompleted); + } + }, + ); + }, +); From 65f288be65e47f4780505f5295fd9669d301a3bd Mon Sep 17 00:00:00 2001 From: Quang Nguyen Date: Mon, 30 Nov 2026 12:10:56 -0800 Subject: [PATCH 11/11] test(e2e): Retry the local invoke until the agent's server answers, and give OpenAICompatible a model ID --- e2eTest/project/tui.test.ts | 47 +++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/e2eTest/project/tui.test.ts b/e2eTest/project/tui.test.ts index 6c98496a9..e6e410162 100644 --- a/e2eTest/project/tui.test.ts +++ b/e2eTest/project/tui.test.ts @@ -138,7 +138,7 @@ const INVALID_KEY = const DEPLOY_PROVIDERS = [ { provider: "Anthropic" }, { provider: "OpenAI" }, - { provider: "OpenAICompatible", apiBase: "https://api.openai.com/v1" }, + { provider: "OpenAICompatible", apiBase: "https://api.openai.com/v1", modelId: "gpt-4o-mini" }, { provider: "Gemini" }, { provider: "LiteLLM" }, ] as const; @@ -165,22 +165,34 @@ async function devInvokeOutput(cli: CliRunner, projectDir: string): Promise deadline) throw new Error(`agentcore dev did not start.\n${output}`); await new Promise((resolve) => setTimeout(resolve, 1000)); } - const invoked = await cli.run( - [ - "invoke", - "--runtime", - CREATED_RUNTIME_NAME, - "--local", - "--port", - String(agentPort), - "--session-id", - getSessionId("tui-dev"), - "--payload", - JSON.stringify({ prompt: "Reply with a short greeting." }), - "--json", - ], - projectDir, - ); + // Dev reports the agent once box's ingress listens, which can be before the agent's own + // server answers behind it, so the invoke retries while the server cannot be reached. + const invokeLocal = () => + cli.run( + [ + "invoke", + "--runtime", + CREATED_RUNTIME_NAME, + "--local", + "--port", + String(agentPort), + "--session-id", + getSessionId("tui-dev"), + "--payload", + JSON.stringify({ prompt: "Reply with a short greeting." }), + "--json", + ], + projectDir, + ); + let invoked = await invokeLocal(); + for ( + let attempt = 1; + attempt < 20 && /Could not reach local dev server/.test(invoked.stderr); + attempt++ + ) { + await new Promise((resolve) => setTimeout(resolve, 3000)); + invoked = await invokeLocal(); + } // The agent logs the model's refusal through dev's output a moment after it answers. await new Promise((resolve) => setTimeout(resolve, 3000)); return `${invoked.stdout}\n${invoked.stderr}\n${output}`; @@ -228,6 +240,7 @@ describe.skipIf(!BOX_DEPLOYS)( "--api-key", `file://${keyFile}`, ...("apiBase" in c ? ["--api-base", c.apiBase] : []), + ...("modelId" in c ? ["--model-id", c.modelId] : []), "--skip-git", "--json", ],