|
| 1 | +import { describe, expect, test } from "vitest"; |
| 2 | +import { spawnSync } from "node:child_process"; |
| 3 | +import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; |
| 4 | +import { tmpdir } from "node:os"; |
| 5 | +import { join } from "node:path"; |
| 6 | +import z from "zod"; |
| 7 | +import { fileURLToPath } from "node:url"; |
| 8 | +import { E2E_PREFIX, TAGS } from "../constants"; |
| 9 | +import { CliRunner, parseResult } from "../helpers/run"; |
| 10 | +import { retry } from "../helpers/retry"; |
| 11 | +import { |
| 12 | + BOX_CDK, |
| 13 | + BOX_DEPLOYS, |
| 14 | + BOX_DEV_PORTS, |
| 15 | + CREATED_RUNTIME_NAME, |
| 16 | + DeployResponseSchema, |
| 17 | + JsonObjectSchema, |
| 18 | + getSessionId, |
| 19 | + runCommand, |
| 20 | + tearDown, |
| 21 | + withDevPort, |
| 22 | +} from "./templates-test-support"; |
| 23 | +import { TIMEOUT_MS } from "../timeouts"; |
| 24 | + |
| 25 | +// The model choices of the interactive create wizard, made through the wizard's own code |
| 26 | +// (e2eTest/helpers/create-with-model-provider.ts), since `agentcore create` takes no model flags: for each template the wizard asks a model provider of, each provider, with a |
| 27 | +// model ID, an API key (a test value) and, for OpenAICompatible, a base URL. Each test creates the |
| 28 | +// project and checks what the wizard's answer must leave in it: the runtime's model provider in |
| 29 | +// agentcore.json, the key as a project credential and never in agentcore.json, and the model ID in |
| 30 | +// the agent's code. Nothing deploys. Run them with `bun run test:e2e -- --tagsFilter='tui'`. |
| 31 | + |
| 32 | +/** The templates whose create wizard asks for a model provider. */ |
| 33 | +const MODEL_TEMPLATES = [ |
| 34 | + { template: "agent-python-strands" }, |
| 35 | + { template: "agent-python-strands-container" }, |
| 36 | + { template: "agent-typescript-strands" }, |
| 37 | + { template: "a2a-python-strands" }, |
| 38 | + { template: "agui-python-strands" }, |
| 39 | + { template: "agent-python-strands-box", box: true }, |
| 40 | + { template: "agent-python-strands-box-container", box: true }, |
| 41 | + { template: "a2a-python-strands-box", box: true }, |
| 42 | + { template: "agui-python-strands-box", box: true }, |
| 43 | +] as const; |
| 44 | + |
| 45 | +/** The providers the wizard offers, and the flags their answer takes. */ |
| 46 | +const PROVIDERS = [ |
| 47 | + { provider: "Bedrock", key: false }, |
| 48 | + { provider: "Anthropic", key: true }, |
| 49 | + { provider: "OpenAI", key: true }, |
| 50 | + { provider: "OpenAICompatible", key: true, apiBase: "https://models.example.com/v1" }, |
| 51 | + { provider: "Gemini", key: true }, |
| 52 | + { provider: "LiteLLM", key: true }, |
| 53 | +] as const; |
| 54 | + |
| 55 | +/** Whether a `box` runs from PATH; create checks for it for a CodeZip box template. */ |
| 56 | +const BOX_ON_PATH = spawnSync("box", ["--version"], { stdio: "ignore" }).status === 0; |
| 57 | + |
| 58 | +const CreatedSchema = z.object({ project: z.object({ path: z.string() }) }); |
| 59 | + |
| 60 | +/** The script that creates a project through the wizard's code; see its header. */ |
| 61 | +const CREATE_WITH_MODEL_PROVIDER = fileURLToPath( |
| 62 | + new URL("../helpers/create-with-model-provider.ts", import.meta.url), |
| 63 | +); |
| 64 | + |
| 65 | +/** |
| 66 | + * Creates a project in `parent` as the create wizard does when the user picks `modelProvider`, and |
| 67 | + * returns its path. `agentcore create` takes no model flags, so this runs the wizard's own code. |
| 68 | + */ |
| 69 | +async function createWithModelProvider( |
| 70 | + parent: string, |
| 71 | + request: { |
| 72 | + template: string; |
| 73 | + modelProvider: string; |
| 74 | + modelId?: string; |
| 75 | + apiKeyFile?: string; |
| 76 | + apiBase?: string; |
| 77 | + skipInstall?: boolean; |
| 78 | + }, |
| 79 | +): Promise<string> { |
| 80 | + const name = `${E2E_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; |
| 81 | + const created = await runCommand( |
| 82 | + "bun", |
| 83 | + [CREATE_WITH_MODEL_PROVIDER, JSON.stringify({ name, region: REGION, ...request })], |
| 84 | + parent, |
| 85 | + ); |
| 86 | + if (created.exitCode !== 0) { |
| 87 | + throw new Error(`create failed.\nstdout: ${created.stdout}\nstderr: ${created.stderr}`); |
| 88 | + } |
| 89 | + return CreatedSchema.parse(JSON.parse(created.stdout.trim().split("\n").pop() ?? "{}")).project |
| 90 | + .path; |
| 91 | +} |
| 92 | + |
| 93 | +/** The region the projects are created for, as the CLI resolves it. */ |
| 94 | +const REGION = process.env.AWS_REGION ?? "us-east-1"; |
| 95 | + |
| 96 | +/** Every file under `dir`, for the model ID check, without `.venv` and `node_modules`. */ |
| 97 | +async function filesUnder(dir: string): Promise<string[]> { |
| 98 | + const entries = await readdir(dir, { withFileTypes: true }); |
| 99 | + const nested = await Promise.all( |
| 100 | + entries |
| 101 | + .filter((entry) => entry.name !== ".venv" && entry.name !== "node_modules") |
| 102 | + .map((entry) => |
| 103 | + entry.isDirectory() ? filesUnder(join(dir, entry.name)) : [join(dir, entry.name)], |
| 104 | + ), |
| 105 | + ); |
| 106 | + return nested.flat(); |
| 107 | +} |
| 108 | + |
| 109 | +describe("create with the model choices of the create wizard", { tags: [TAGS.TUI] }, () => { |
| 110 | + // The wizard offers LiteLLM only for Python templates. |
| 111 | + const cases = MODEL_TEMPLATES.flatMap((t) => |
| 112 | + PROVIDERS.filter((p) => !(p.provider === "LiteLLM" && t.template.includes("typescript"))).map( |
| 113 | + (p) => ({ ...t, ...p, name: `${t.template} with ${p.provider}` }), |
| 114 | + ), |
| 115 | + ); |
| 116 | + |
| 117 | + test.concurrent.each(cases)("$name", { timeout: TIMEOUT_MS.PROJECT_CREATE }, async (c) => { |
| 118 | + if ("box" in c && c.box && !BOX_ON_PATH) return; |
| 119 | + const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); |
| 120 | + const modelId = `e2e-model-${c.provider.toLowerCase()}`; |
| 121 | + const secret = `e2e-test-key-${Math.random().toString(36).slice(2, 10)}`; |
| 122 | + const keyFile = join(parent, "key.txt"); |
| 123 | + await writeFile(keyFile, secret); |
| 124 | + const root = await createWithModelProvider(parent, { |
| 125 | + template: c.template, |
| 126 | + modelProvider: c.provider, |
| 127 | + modelId, |
| 128 | + ...(c.key && { apiKeyFile: keyFile }), |
| 129 | + ...("apiBase" in c && { apiBase: c.apiBase }), |
| 130 | + skipInstall: true, |
| 131 | + }); |
| 132 | + const specText = await readFile(join(root, "agentcore", "agentcore.json"), "utf8"); |
| 133 | + const spec = JSON.parse(specText) as { |
| 134 | + runtimes: { modelProvider?: string }[]; |
| 135 | + credentials?: unknown[]; |
| 136 | + }; |
| 137 | + expect(spec.runtimes[0]?.modelProvider).toBe(c.provider); |
| 138 | + expect(specText).not.toContain(secret); |
| 139 | + expect((spec.credentials ?? []).length).toBe(c.key ? 1 : 0); |
| 140 | + const code = await Promise.all( |
| 141 | + (await filesUnder(join(root, "app"))).map((file) => readFile(file, "utf8").catch(() => "")), |
| 142 | + ); |
| 143 | + expect(code.some((text) => text.includes(modelId))).toBe(true); |
| 144 | + }); |
| 145 | +}); |
| 146 | + |
| 147 | +// The Box template on each model provider the create wizard offers but Bedrock, which the other |
| 148 | +// suites cover, through dev, build, deploy and invoke. CI has no keys for these providers, so each |
| 149 | +// project takes a test key, and the test expects the provider's own refusal of it: that shows the |
| 150 | +// agent's model call left the box through its egress route, with the key, and reached the provider. |
| 151 | +// "blocked by egress control" or no refusal at all fails the test. OpenAICompatible points at the |
| 152 | +// OpenAI API, so its refusal is OpenAI's. They need box on PATH and the AGENTCORE_E2E_BOX_CDK opt-in. |
| 153 | + |
| 154 | +/** What a provider answers to a key it does not know, in the words each one uses. */ |
| 155 | +const INVALID_KEY = |
| 156 | + /invalid[^\n]{0,40}api[ _-]?key|incorrect api key|api key not valid|authentication_?error|invalid_api_key|unauthori[sz]ed|\b401\b/i; |
| 157 | + |
| 158 | +const DEPLOY_PROVIDERS = [ |
| 159 | + { provider: "Anthropic" }, |
| 160 | + { provider: "OpenAI" }, |
| 161 | + { provider: "OpenAICompatible", apiBase: "https://api.openai.com/v1", modelId: "gpt-4o-mini" }, |
| 162 | + { provider: "Gemini" }, |
| 163 | + { provider: "LiteLLM" }, |
| 164 | +] as const; |
| 165 | + |
| 166 | +/** Runs `agentcore dev` on the box port, invokes it once, and returns all that both printed. */ |
| 167 | +async function devInvokeOutput(cli: CliRunner, projectDir: string): Promise<string> { |
| 168 | + const port = BOX_DEV_PORTS.HTTP; |
| 169 | + return withDevPort(port, async () => { |
| 170 | + let output = ""; |
| 171 | + let agentPort: number | undefined; |
| 172 | + const dev = cli.start(["dev", "--mode", "headless", "--port", String(port)], projectDir); |
| 173 | + const capture = (chunk: Buffer) => { |
| 174 | + const text = chunk.toString(); |
| 175 | + output += text; |
| 176 | + const match = /Agent '([^']+)' is running on port (\d+)\./.exec(output); |
| 177 | + if (match?.[1] === CREATED_RUNTIME_NAME) agentPort = Number(match[2]); |
| 178 | + }; |
| 179 | + dev.stdout?.on("data", capture); |
| 180 | + dev.stderr?.on("data", capture); |
| 181 | + try { |
| 182 | + const deadline = Date.now() + TIMEOUT_MS.PROJECT_DEV; |
| 183 | + while (agentPort === undefined) { |
| 184 | + if (dev.exitCode !== null) throw new Error(`agentcore dev exited.\n${output}`); |
| 185 | + if (Date.now() > deadline) throw new Error(`agentcore dev did not start.\n${output}`); |
| 186 | + await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 187 | + } |
| 188 | + // Dev reports the agent once box's ingress listens, which can be before the agent's own |
| 189 | + // server answers behind it, so the invoke retries while the server cannot be reached. |
| 190 | + const invokeLocal = () => |
| 191 | + cli.run( |
| 192 | + [ |
| 193 | + "invoke", |
| 194 | + "--runtime", |
| 195 | + CREATED_RUNTIME_NAME, |
| 196 | + "--local", |
| 197 | + "--port", |
| 198 | + String(agentPort), |
| 199 | + "--session-id", |
| 200 | + getSessionId("tui-dev"), |
| 201 | + "--payload", |
| 202 | + JSON.stringify({ prompt: "Reply with a short greeting." }), |
| 203 | + "--json", |
| 204 | + ], |
| 205 | + projectDir, |
| 206 | + ); |
| 207 | + let invoked = await invokeLocal(); |
| 208 | + for ( |
| 209 | + let attempt = 1; |
| 210 | + attempt < 20 && /Could not reach local dev server/.test(invoked.stderr); |
| 211 | + attempt++ |
| 212 | + ) { |
| 213 | + await new Promise((resolve) => setTimeout(resolve, 3000)); |
| 214 | + invoked = await invokeLocal(); |
| 215 | + } |
| 216 | + // The agent logs the model's refusal through dev's output a moment after it answers. |
| 217 | + await new Promise((resolve) => setTimeout(resolve, 3000)); |
| 218 | + return `${invoked.stdout}\n${invoked.stderr}\n${output}`; |
| 219 | + } finally { |
| 220 | + if (dev.exitCode === null) { |
| 221 | + dev.kill("SIGTERM"); |
| 222 | + await new Promise<void>((resolve) => dev.once("close", resolve)); |
| 223 | + } |
| 224 | + } |
| 225 | + }); |
| 226 | +} |
| 227 | + |
| 228 | +describe.skipIf(!BOX_DEPLOYS)( |
| 229 | + "dev, build, deploy, invoke the Box template with each model provider and a test key", |
| 230 | + { tags: [TAGS.TUI] }, |
| 231 | + () => { |
| 232 | + const cli = new CliRunner(); |
| 233 | + |
| 234 | + test.concurrent.each(DEPLOY_PROVIDERS)( |
| 235 | + "$provider", |
| 236 | + { |
| 237 | + timeout: |
| 238 | + TIMEOUT_MS.PROJECT_CREATE + |
| 239 | + 5 * (TIMEOUT_MS.PROJECT_DEV + TIMEOUT_MS.PROJECT_INVOKE) + |
| 240 | + 3 * TIMEOUT_MS.PROJECT_INVOKE + |
| 241 | + 2 * TIMEOUT_MS.PROJECT_DEPLOY + |
| 242 | + TIMEOUT_MS.PROJECT_REMOVE, |
| 243 | + }, |
| 244 | + async (c) => { |
| 245 | + const parent = await mkdtemp(join(tmpdir(), "agentcore-e2e-tui-")); |
| 246 | + const keyFile = join(parent, "key.txt"); |
| 247 | + await writeFile(keyFile, `e2e-invalid-key-${Math.random().toString(36).slice(2, 10)}`); |
| 248 | + const projectDir = await createWithModelProvider(parent, { |
| 249 | + template: "agent-python-strands-box", |
| 250 | + modelProvider: c.provider, |
| 251 | + apiKeyFile: keyFile, |
| 252 | + ...("apiBase" in c && { apiBase: c.apiBase }), |
| 253 | + ...("modelId" in c && { modelId: c.modelId }), |
| 254 | + }); |
| 255 | + const installed = await runCommand( |
| 256 | + "npm", |
| 257 | + ["install", "--no-audit", "--no-fund", `@aws/agentcore-cdk@${BOX_CDK}`], |
| 258 | + join(projectDir, "agentcore", "cdk"), |
| 259 | + ); |
| 260 | + expect(installed.exitCode).toBe(0); |
| 261 | + |
| 262 | + const dev = await devInvokeOutput(cli, projectDir); |
| 263 | + expect(dev).not.toMatch(/blocked by egress control/); |
| 264 | + expect(dev).toMatch(INVALID_KEY); |
| 265 | + |
| 266 | + let scenarioCompleted = false; |
| 267 | + try { |
| 268 | + // The key is stored as a credential by the first deploy, so build runs after it. |
| 269 | + const deployment = parseResult( |
| 270 | + DeployResponseSchema, |
| 271 | + await cli.run(["deploy", "--yes", "--json"], projectDir), |
| 272 | + ); |
| 273 | + expect(deployment.message).toContain("deployed project"); |
| 274 | + parseResult(JsonObjectSchema, await cli.run(["build", "--json"], projectDir)); |
| 275 | + |
| 276 | + await retry( |
| 277 | + async () => { |
| 278 | + const invoked = await cli.run( |
| 279 | + [ |
| 280 | + "invoke", |
| 281 | + "--runtime", |
| 282 | + CREATED_RUNTIME_NAME, |
| 283 | + "--session-id", |
| 284 | + getSessionId(`tui-${c.provider.toLowerCase()}`), |
| 285 | + "--payload", |
| 286 | + JSON.stringify({ prompt: "Reply with a short greeting." }), |
| 287 | + "--json", |
| 288 | + ], |
| 289 | + projectDir, |
| 290 | + ); |
| 291 | + const logs = await cli.run( |
| 292 | + ["logs", "runtime", "--name", CREATED_RUNTIME_NAME, "--since", "30m"], |
| 293 | + projectDir, |
| 294 | + ); |
| 295 | + const text = `${invoked.stdout}\n${invoked.stderr}\n${logs.stdout}`; |
| 296 | + expect(text).not.toMatch(/blocked by egress control/); |
| 297 | + expect(text).toMatch(INVALID_KEY); |
| 298 | + }, |
| 299 | + 3 * TIMEOUT_MS.PROJECT_INVOKE, |
| 300 | + 30 * 1000, |
| 301 | + ); |
| 302 | + scenarioCompleted = true; |
| 303 | + } finally { |
| 304 | + await tearDown(cli, projectDir, scenarioCompleted); |
| 305 | + } |
| 306 | + }, |
| 307 | + ); |
| 308 | + }, |
| 309 | +); |
0 commit comments