From 157c01797d810cc550cb3cec2e8eb22b2f956666 Mon Sep 17 00:00:00 2001 From: Vignesh Somasundaram Date: Fri, 20 Nov 2026 22:11:01 +0000 Subject: [PATCH 01/19] feat(runtime): add --platform-version to add runtime Accept an optional platformVersion (V1 | V2) on runtimes in agentcore.json and write it from `agentcore add runtime --platform-version`, which rejects any other value. Both spec builders carry it through, and `agentcore runtime get` shows the deployed platform version. The runtime docs that add runtime writes now describe V2 for Python and TypeScript: startup versus per-request work, snapshot-safe randomness, shared hostname and PID, slower create and update, keeping the field set, and the service error when the Region or account doesn't offer V2. They link to the AWS region list rather than copying it. Reaching a deployed runtime needs a @aws/agentcore-cdk release with platformVersion support and a bump of the pin in src/assets/cdk/package.json, which maintainers handle separately. Closes #2674 --- .../templates/runtime-docs/python/AGENTS.md | 4 +++ .../templates/runtime-docs/python/README.md | 28 +++++++++++++++++++ .../runtime-docs/typescript/AGENTS.md | 4 +++ .../runtime-docs/typescript/README.md | 28 +++++++++++++++++++ src/core/project/templates/runtime.test.ts | 2 ++ src/core/project/templates/runtime.ts | 1 + src/core/project/templates/runtimeDocs.ts | 1 + .../project/add/runtime/index.test.ts | 4 +++ src/handlers/project/add/runtime/index.ts | 8 ++++++ src/handlers/project/add/runtime/types.ts | 1 + src/handlers/runtime/get/screen.tsx | 1 + src/handlers/runtime/runtime.screen.test.tsx | 2 ++ src/projectSchemas/constants.ts | 2 ++ src/projectSchemas/runtime.test.ts | 12 ++++++++ src/projectSchemas/runtime.ts | 3 ++ 15 files changed, 101 insertions(+) diff --git a/src/assets/templates/runtime-docs/python/AGENTS.md b/src/assets/templates/runtime-docs/python/AGENTS.md index dcae043ebf..404354495b 100644 --- a/src/assets/templates/runtime-docs/python/AGENTS.md +++ b/src/assets/templates/runtime-docs/python/AGENTS.md @@ -68,6 +68,10 @@ in more detail. `context.session_id`) to tell conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup + code to work that is the same for every request, and create random values + (`secrets` or `os.urandom()`), timestamps, and credentials inside the + request handler. ## Must not diff --git a/src/assets/templates/runtime-docs/python/README.md b/src/assets/templates/runtime-docs/python/README.md index eee3e23840..af4854c6e9 100644 --- a/src/assets/templates/runtime-docs/python/README.md +++ b/src/assets/templates/runtime-docs/python/README.md @@ -196,6 +196,34 @@ Every protocol also shares these: to the current time on every ping. Change it only when the status changes, or idle sessions never time out and can use up your session quota. +### Platform version V2 + +`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each +instance from a snapshot of your initialized code, so cold starts stay fast +as images and traffic grow. V1 is the default, and V2 is offered in +[some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +On V2: + +- Startup work (imports, loading models, building clients) is captured once + in the snapshot and shared by every instance. Finish it within 120 seconds, + or creating the runtime fails its health check. +- Produce anything that must differ per request, or can expire, in your + request handler: random values and IDs, the current time, the reference + point for elapsed time, and credentials. +- Get random values from the operating system on each request + (`secrets`, `os.urandom()`, `uuid.uuid4()`). The `random` module is seeded + at startup, so restored instances repeat its sequence. +- Every instance reports the same hostname and PID, so don't use either as + an instance or worker ID. +- Creating or updating a V2 runtime takes several minutes. Keep + `platformVersion` set: removing it doesn't move the runtime back, and a + later replacement of the runtime would start on V1. Set `V1` to move back. +- If deploy fails with "platformVersion V2 is not available for this + account", the target's Region, or your account, doesn't offer V2: deploy to + a supported Region or set `V1`. + +More: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-v2-optimize.html + ## Dependencies: `pyproject.toml` Declare dependencies in `[project].dependencies`. That's the only place the diff --git a/src/assets/templates/runtime-docs/typescript/AGENTS.md b/src/assets/templates/runtime-docs/typescript/AGENTS.md index 8de7f8283d..381f72fb64 100644 --- a/src/assets/templates/runtime-docs/typescript/AGENTS.md +++ b/src/assets/templates/runtime-docs/typescript/AGENTS.md @@ -56,6 +56,10 @@ in more detail. conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup + code to work that is the same for every request, and create random values + (`/dev/urandom`, not the `crypto` module), timestamps, and credentials + inside the request handler. ## Must not diff --git a/src/assets/templates/runtime-docs/typescript/README.md b/src/assets/templates/runtime-docs/typescript/README.md index e8abc3b3c6..96bcdb7842 100644 --- a/src/assets/templates/runtime-docs/typescript/README.md +++ b/src/assets/templates/runtime-docs/typescript/README.md @@ -136,6 +136,34 @@ Every protocol also shares these: to the current time on every ping. Change it only when the status changes, or idle sessions never time out and can use up your session quota. +### Platform version V2 + +`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each +instance from a snapshot of your initialized code, so cold starts stay fast +as images and traffic grow. V1 is the default, and V2 is offered in +[some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +On V2: + +- Startup work (imports, loading models, building clients) is captured once + in the snapshot and shared by every instance. Finish it within 120 seconds, + or creating the runtime fails its health check. +- Produce anything that must differ per request, or can expire, in your + request handler: random values and IDs, the current time, the reference + point for elapsed time, and credentials. +- Read random bytes from `/dev/urandom` on each request. Node's `crypto` + module (`randomBytes`, `randomUUID`, `getRandomValues`, and packages such + as `uuid`) can repeat values across instances, even inside the handler. +- Every instance reports the same hostname and PID, so don't use either as + an instance or worker ID. +- Creating or updating a V2 runtime takes several minutes. Keep + `platformVersion` set: removing it doesn't move the runtime back, and a + later replacement of the runtime would start on V1. Set `V1` to move back. +- If deploy fails with "platformVersion V2 is not available for this + account", the target's Region, or your account, doesn't offer V2: deploy to + a supported Region or set `V1`. + +More: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-v2-optimize.html + ## Dependencies: `package.json` ```json diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index cd5ca140a4..cd39f5da91 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -100,6 +100,7 @@ describe("runtime templates", () => { const { runtime, appDir, core } = await addTemplate("my_bma", "environment-python-bma", { infra: { lifecycleConfiguration: { idleRuntimeSessionTimeout: 300, maxLifetime: 3600 }, + platformVersion: "V2", additionalPolicies: ["custom-policy.json"], tags: { team: "agents" }, }, @@ -111,6 +112,7 @@ describe("runtime templates", () => { dockerfile: "Dockerfile", protocol: "HTTP", lifecycleConfiguration: { idleRuntimeSessionTimeout: 300, maxLifetime: 3600 }, + platformVersion: "V2", additionalPolicies: ["bma-acr-policy.json", "custom-policy.json"], tags: { "agentcore:template": "BedrockManagedAgents", team: "agents" }, }); diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 2a5cc7fb9f..e69740ba12 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -120,6 +120,7 @@ function buildRuntimeSpec(input: RuntimeResourceConfig): ProjectRuntime { ...(infra.envVars && { envVars: infra.envVars }), ...(infra.networkMode && { networkMode: infra.networkMode }), ...(infra.networkConfig && { networkConfig: infra.networkConfig }), + ...(infra.platformVersion && { platformVersion: infra.platformVersion }), ...(infra.authorizerType && { authorizerType: infra.authorizerType }), ...(infra.authorizerConfiguration && { authorizerConfiguration: infra.authorizerConfiguration, diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index f5ed443e11..3922ec5dc5 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -156,6 +156,7 @@ export function buildDocsRuntimeSpec(input: RuntimeDocsConfig): ProjectRuntime { ...(infra.envVars?.length && { envVars: infra.envVars }), ...(infra.networkMode && { networkMode: infra.networkMode }), ...(infra.networkConfig && { networkConfig: infra.networkConfig }), + ...(infra.platformVersion && { platformVersion: infra.platformVersion }), ...(infra.authorizerType && { authorizerType: infra.authorizerType }), ...(infra.authorizerConfiguration && { authorizerConfiguration: infra.authorizerConfiguration, diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index b9bc61335a..98cc398453 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -327,6 +327,8 @@ describe("project add runtime", () => { "VPC", "--network-config", '{"subnets":["subnet-0123456789abcdef0"],"securityGroups":["sg-0123456789abcdef0"]}', + "--platform-version", + "V2", "--authorizer-type", "CUSTOM_JWT", "--authorizer-configuration", @@ -458,6 +460,7 @@ describe("project add runtime", () => { subnets: ["subnet-0123456789abcdef0"], securityGroups: ["sg-0123456789abcdef0"], }, + platformVersion: "V2", authorizerType: "CUSTOM_JWT", authorizerConfiguration: { customJwtAuthorizer: { @@ -566,6 +569,7 @@ describe("project add runtime", () => { ["--model-provider", "anthropic"], ["--language", "rust"], ["--protocol", "GRPC"], + ["--platform-version", "v2"], ["--type", "create"], ["--type", "import"], ])("rejects %s %s and writes nothing", async (flagName, value) => { diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index eecaebc547..98d5a43924 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -8,6 +8,7 @@ import { AgentNameSchema, type EnvVar } from "../../../../projectSchemas/runtime import { RuntimeAuthorizerTypeSchema } from "../../../../projectSchemas/auth"; import { NetworkModeSchema, + PlatformVersionSchema, ProtocolModeSchema, type ProtocolMode, } from "../../../../projectSchemas/constants"; @@ -124,6 +125,12 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => flag("network-config", "VPC network configuration (JSON)", z.string().optional(), { group: ENVIRONMENT, }), + flag( + "platform-version", + "Runtime platform version: V1 (service default) or V2", + PlatformVersionSchema.optional(), + { group: ENVIRONMENT }, + ), flag( "lifecycle-configuration", "session idle timeout and instance lifetime configuration (JSON)", @@ -270,6 +277,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => envVars: toEnvironmentVariables(inputEnvironmentVariables), networkMode: flags["network-mode"], networkConfig: parseJsonFlag("network-config", flags["network-config"]), + platformVersion: flags["platform-version"], authorizerType: flags["authorizer-type"], authorizerConfiguration: parseJsonFlag( "authorizer-configuration", diff --git a/src/handlers/project/add/runtime/types.ts b/src/handlers/project/add/runtime/types.ts index 618aebb731..f2c2dc8032 100644 --- a/src/handlers/project/add/runtime/types.ts +++ b/src/handlers/project/add/runtime/types.ts @@ -13,6 +13,7 @@ const RuntimeInfraConfigSchema = z.object({ additionalPolicies: ProjectRuntimeSchema.shape.additionalPolicies, envVars: ProjectRuntimeSchema.shape.envVars, networkMode: ProjectRuntimeSchema.shape.networkMode, + platformVersion: ProjectRuntimeSchema.shape.platformVersion, networkConfig: ProjectRuntimeSchema.shape.networkConfig, authorizerType: ProjectRuntimeSchema.shape.authorizerType, authorizerConfiguration: ProjectRuntimeSchema.shape.authorizerConfiguration, diff --git a/src/handlers/runtime/get/screen.tsx b/src/handlers/runtime/get/screen.tsx index 6940cb7061..9206c5ea75 100644 --- a/src/handlers/runtime/get/screen.tsx +++ b/src/handlers/runtime/get/screen.tsx @@ -67,6 +67,7 @@ export function RuntimeGetScreen(props: ScreenProps) { version: detail.data?.agentRuntimeVersion ?? "", protocol: detail.data?.protocolConfiguration?.serverProtocol ?? "-", network: detail.data?.networkConfiguration?.networkMode ?? "-", + platform: detail.data?.platformVersion ?? "-", arn: detail.data?.agentRuntimeArn ?? "", }} actions={ diff --git a/src/handlers/runtime/runtime.screen.test.tsx b/src/handlers/runtime/runtime.screen.test.tsx index 7bac21fb59..49d5d4bfa6 100644 --- a/src/handlers/runtime/runtime.screen.test.tsx +++ b/src/handlers/runtime/runtime.screen.test.tsx @@ -42,6 +42,7 @@ function getRuntimeResponse( lastUpdatedAt: new Date("2026-07-20T12:34:56.000Z"), roleArn: "arn:aws:iam::123456789012:role/runtime-role", networkConfiguration: { networkMode: "PUBLIC" }, + platformVersion: "V2", status: "READY", protocolConfiguration: { serverProtocol: "HTTP" }, lifecycleConfiguration: { @@ -176,6 +177,7 @@ describe("runtime hub", () => { expect(r.lastFrame()).toMatch(/version\s+7/); expect(r.lastFrame()).toMatch(/protocol\s+HTTP/); expect(r.lastFrame()).toMatch(/network\s+PUBLIC/); + expect(r.lastFrame()).toMatch(/platform\s+V2/); expect(r.lastFrame()).not.toContain("failureReason"); await waitFor(() => core.runtime.calls.some((call) => call.method === "getRuntime")); expect(core.runtime.calls.find((call) => call.method === "getRuntime")).toEqual({ diff --git a/src/projectSchemas/constants.ts b/src/projectSchemas/constants.ts index a7a8c6e31f..514fad4641 100644 --- a/src/projectSchemas/constants.ts +++ b/src/projectSchemas/constants.ts @@ -70,6 +70,8 @@ export const RuntimeVersionSchema = z.union([PythonRuntimeSchema, NodeRuntimeSch export type RuntimeVersion = z.infer; export const NetworkModeSchema = z.enum(["PUBLIC", "VPC"]); export type NetworkMode = z.infer; +export const PlatformVersionSchema = z.enum(["V1", "V2"]); +export type PlatformVersion = z.infer; export const VPC_ID_PATTERN = /^vpc-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SUBNET_ID_PATTERN = /^subnet-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SECURITY_GROUP_ID_PATTERN = /^sg-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index 967991cb15..f5a4c3dfff 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -51,6 +51,18 @@ describe("runtime custom validation", () => { }).success, ).toBe(false); }); + it("accepts only the V1 and V2 platform versions", () => { + for (const platformVersion of ["V1", "V2"]) { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( + true, + ); + } + for (const platformVersion of ["v2", "V3", ""]) { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( + false, + ); + } + }); it("couples VPC mode and network configuration", () => { expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, networkMode: "VPC" }).success).toBe( false, diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index bd7bbc1926..49f3da0f11 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -1,6 +1,7 @@ import { MAX_CONTAINER_BUILD_SECURITY_GROUPS, NetworkModeSchema, + PlatformVersionSchema, ProtocolModeSchema, RuntimeVersionSchema as RuntimeVersionSchemaFromConstants, SECURITY_GROUP_ID_PATTERN, @@ -311,6 +312,8 @@ export const ProjectRuntimeSchema = z buildContextPath: DirectoryPathSchema.optional(), customDockerBuildArgs: z.record(EnvVarNameSchema, BuildArgValueSchema).optional(), runtimeVersion: RuntimeVersionSchemaFromConstants.optional(), + /** Removing this keeps a deployed runtime on its current version; set V1 to move back. */ + platformVersion: PlatformVersionSchema.optional(), envVars: z.array(EnvVarSchema).optional(), networkMode: NetworkModeSchema.optional(), networkConfig: NetworkConfigSchema.optional(), From 6d2b890d3b132a57b11187739eefba3a33458482 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 23 Nov 2026 19:54:18 -0500 Subject: [PATCH 02/19] ci: pin workflow-metrics to the devtools commit that runs on ubuntu-latest (#2904) The pinned devtools workflow-metrics.yml hardcoded the codebuild-agentcore-e2e label, so Workflow Metrics stayed queued. aws/agentcore-devx-devtools#27 moved it to ubuntu-latest. Co-authored-by: jariy17 --- .github/workflows/workflow-metrics.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/workflow-metrics.yml b/.github/workflows/workflow-metrics.yml index f34293f1b4..75883186af 100644 --- a/.github/workflows/workflow-metrics.yml +++ b/.github/workflows/workflow-metrics.yml @@ -9,7 +9,7 @@ permissions: jobs: metrics: - uses: aws/agentcore-devx-devtools/.github/workflows/workflow-metrics.yml@c2106996dd94e56f6c5fad625c83573e9724fb63 + uses: aws/agentcore-devx-devtools/.github/workflows/workflow-metrics.yml@28f401925cbdd8900e468d10ed950b48fd2cde1a with: namespace: AgentCoreCLI/Workflows os: Linux From 722f8428d73127114a8b707e62c1bdce763f2e31 Mon Sep 17 00:00:00 2001 From: Tejas Kashinath <42380254+tejaskash@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:25:35 -0500 Subject: [PATCH 03/19] feat(telemetry): record the template a project is created with (#2907) agentcore create now sets project_template on cli.command_run, from the --template flag and from the create wizard. Config-based (harness) creates leave it unset. --- .../project/create/create.screen.test.tsx | 36 ++++++++++- src/handlers/project/create/index.ts | 11 +++- src/handlers/project/create/screen.tsx | 5 +- src/handlers/project/project.test.ts | 59 ++++++++++++++++++- src/telemetry/shapes.tsx | 2 + 5 files changed, 105 insertions(+), 8 deletions(-) diff --git a/src/handlers/project/create/create.screen.test.tsx b/src/handlers/project/create/create.screen.test.tsx index 8aadbedc9f..3c5713bd93 100644 --- a/src/handlers/project/create/create.screen.test.tsx +++ b/src/handlers/project/create/create.screen.test.tsx @@ -1,9 +1,11 @@ import { test, expect, describe, afterEach } from "bun:test"; import { existsSync } from "node:fs"; -import { mkdir, readdir, writeFile } from "node:fs/promises"; +import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { parse } from "yaml"; import { + assertMetricEmitted, + getTestTelemetryClient, renderScreen, waitForText, flatFrame, @@ -23,6 +25,7 @@ import { resolveRuntimeTemplateShortcut } from "../shortcuts"; import type { CreateProjectInput } from "../types"; import { ProjectSpecSchema } from "../../../projectSchemas/project"; import { RegionKey } from "../../keys"; +import { CommandRunMetricEventKey, type Context } from "../../../router"; import { readEnvFile } from "../../../io/envFile"; import { credentialEnvVarName } from "../../../projectSchemas/credential"; import { DEFAULT_MODEL_IDS } from "../../../projectSchemas/runtime"; @@ -50,6 +53,24 @@ function spyOnCreate(core: TestCoreClient): CreateProjectInput[] { return inputs; } +async function trackCommandRun() { + const { client, filePath, cleanup } = await getTestTelemetryClient(); + cleanups.push(cleanup); + const event = client.createMetricEvent("cli.command_run", { + exit_reason: "success", + command_path: "/agentcore/create", + is_tui: true, + }); + return { + filePath, + withContext: (ctx: Context) => ctx.withValue(CommandRunMetricEventKey, event), + emit: async () => { + await event.emit(100); + await client.shutdown(); + }, + }; +} + const DEFAULT_MODEL_ID = "global.anthropic.claude-sonnet-5-5"; const STRANDS_BEDROCK_MODEL_ID = DEFAULT_MODEL_IDS.Bedrock; const API_KEY_HELP = "file:// to the key file"; @@ -60,7 +81,8 @@ describe("project create wizard", () => { cleanups.push(cleanup); const core = new TestCoreClient(); const inputs = spyOnCreate(core); - const r = renderScreen("/agentcore/create", { core }); + const commandRun = await trackCommandRun(); + const r = renderScreen("/agentcore/create", { core, withContext: commandRun.withContext }); await waitForText(r.lastFrame, "name your project"); await r.write("DemoApp"); @@ -122,6 +144,9 @@ describe("project create wizard", () => { const spec = await Bun.file(join(directory, "DemoApp", "agentcore", "agentcore.json")).json(); expect(spec.harnesses).toEqual([{ name: "DemoApp", path: "app/DemoApp" }]); expect(spec.runtimes).toEqual([]); + await commandRun.emit(); + const [entry] = (await readFile(commandRun.filePath, "utf8")).trim().split("\n"); + expect(JSON.parse(entry!).attrs).not.toHaveProperty("project_template"); r.unmount(); }, 10000); @@ -493,7 +518,8 @@ describe("project create wizard", () => { cleanups.push(cleanup); const core = new TestCoreClient(); const inputs = spyOnCreate(core); - const r = renderScreen("/agentcore/create", { core }); + const commandRun = await trackCommandRun(); + const r = renderScreen("/agentcore/create", { core, withContext: commandRun.withContext }); await waitForText(r.lastFrame, "name your project"); await r.write("StrandsApp"); @@ -565,6 +591,10 @@ describe("project create wizard", () => { expect(spec.runtimes.map((runtime: { name: string }) => runtime.name)).toEqual(["agent"]); // The strands template ships with longAndShortTerm memory pre-configured. expect(spec.memories).toHaveLength(1); + await commandRun.emit(); + await assertMetricEmitted(commandRun.filePath, "cli.command_run", { + project_template: "agent-python-strands", + }); r.unmount(); }, 10000); diff --git a/src/handlers/project/create/index.ts b/src/handlers/project/create/index.ts index c8622a034f..9752194b65 100644 --- a/src/handlers/project/create/index.ts +++ b/src/handlers/project/create/index.ts @@ -1,6 +1,12 @@ import { createHash } from "node:crypto"; import z from "zod"; -import { createHandler, flag, PlatformKey, type Middleware } from "../../../router"; +import { + CommandRunMetricEventKey, + createHandler, + flag, + PlatformKey, + type Middleware, +} from "../../../router"; import { assertProjectPathFits } from "./pathLimit"; import { type AppIO } from "../../../io"; import { runWithProgress } from "../../../tui/progress"; @@ -118,13 +124,14 @@ export const createCreateProjectHandler = (config: CreateProjectHandlerConfig) = ], handle: async (ctx, flags) => { const name = flags["name"]; + const template = flags["template"]; + ctx.value(CommandRunMetricEventKey)?.setAttributes({ project_template: template }); if (!flags["skip-install"]) { assertProjectPathFits(name, ctx.require(PlatformKey), { alternative: "pass --skip-install and install the CDK dependencies yourself", }); } - const template = flags["template"]; const base = { name, skipInstall: flags["skip-install"], diff --git a/src/handlers/project/create/screen.tsx b/src/handlers/project/create/screen.tsx index 4e61d95c82..37264894a2 100644 --- a/src/handlers/project/create/screen.tsx +++ b/src/handlers/project/create/screen.tsx @@ -3,7 +3,7 @@ import { Box, Text, useApp } from "ink"; import { useNavigate } from "react-router"; import { ProjectNameSchema } from "../../../projectSchemas/project"; import type { ScreenProps } from "../../types"; -import { PlatformKey } from "../../../router"; +import { CommandRunMetricEventKey, PlatformKey } from "../../../router"; import { RegionKey } from "../../keys"; import { assertProjectPathFits } from "./pathLimit"; import type { CreateProjectInput } from "../types"; @@ -210,6 +210,9 @@ export function ProjectCreateScreen({ ctx, core }: ScreenProps) { // same place RouterScreen's esc goes. onCancel={() => navigate("/agentcore")} onSubmit={async function* () { + ctx.value(CommandRunMetricEventKey)?.setAttributes({ + project_template: values.kind === "agent" ? values.template : undefined, + }); // All of these throw before anything is written, so the wizard reports // them the way it reports a failed create — with the retry still on // offer, because nothing has to be cleaned up first. The API key is diff --git a/src/handlers/project/project.test.ts b/src/handlers/project/project.test.ts index 5e27a67cf5..12a299b9cb 100644 --- a/src/handlers/project/project.test.ts +++ b/src/handlers/project/project.test.ts @@ -4,14 +4,18 @@ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createRootHandler } from "../index"; import { + assertMetricEmitted, createSilentLogger, expectError, + getTestTelemetryClient, initProject, inTempDirectory, TestCoreClient, TestGlobalConfigAccessor, testIO, + withTelemetry, } from "../../testing"; +import { ValueContext, type Context } from "../../router"; import { InputValidationError, SourceResolutionError } from "../../errors"; import { DEFAULT_MODEL_IDS } from "../../projectSchemas/runtime"; import { resolveScaffoldHarnessInput } from "./create/index"; @@ -19,7 +23,7 @@ import { readEnvFile } from "../../io/envFile"; async function run( args: string[], - opts?: { core?: TestCoreClient; stdin?: string; platform?: NodeJS.Platform }, + opts?: { core?: TestCoreClient; stdin?: string; platform?: NodeJS.Platform; ctx?: Context }, ) { const io = testIO({ stdin: opts?.stdin }); const core = opts?.core ?? new TestCoreClient(); @@ -29,10 +33,22 @@ async function run( logger: createSilentLogger(), platform: opts?.platform, }); - await root.route(["node", "agentcore", ...args]); + await root.route(["node", "agentcore", ...args], opts?.ctx); return { io, core }; } +async function runWithTelemetry(args: string[], opts?: { platform?: NodeJS.Platform }) { + const { client, filePath, cleanup } = await getTestTelemetryClient(); + cleanups.push(cleanup); + const error = await withTelemetry(ValueContext.EmptyContext(), client, (ctx) => + run(args, { ...opts, ctx }), + ).then( + () => undefined, + (caught: unknown) => caught, + ); + return { filePath, error }; +} + const cleanups: Array<() => Promise> = []; afterEach(() => Promise.all(cleanups.splice(0).map((cleanup) => cleanup()))); @@ -502,6 +518,45 @@ describe("project create", () => { expect(await Bun.file(join(projectRoot, "app", "agent", "main.ts")).exists()).toBe(true); }); + test.each([ + [[], "empty"], + [["--template", "agent-python-minimal"], "agent-python-minimal"], + ] as const)("create %j records project_template %s", async (templateArgs, template) => { + cleanups.push((await inTempDirectory()).cleanup); + const { filePath, error } = await runWithTelemetry([ + "create", + "--name", + "MyAgent", + "--skip-install", + "--skip-git", + ...templateArgs, + ]); + expect(error).toBeUndefined(); + await assertMetricEmitted(filePath, "cli.command_run", { + command_path: "/agentcore/create", + exit_reason: "success", + project_template: template, + }); + }); + + test("a create that fails still records the chosen project_template", async () => { + const { path, cleanup } = await inTempDirectory(); + cleanups.push(cleanup); + const deep = join(path, "n".repeat(120)); + await mkdir(deep); + process.chdir(deep); + + const { filePath, error } = await runWithTelemetry( + ["create", "--name", "Deep", "--template", "agent-python-strands"], + { platform: "win32" }, + ); + expect(error).toBeInstanceOf(InputValidationError); + await assertMetricEmitted(filePath, "cli.command_run", { + exit_reason: "failure", + project_template: "agent-python-strands", + }); + }); + test("rejects an invalid --name", async () => { cleanups.push((await inTempDirectory()).cleanup); await expect(run(["create", "--name", "1-bad"])).rejects.toThrow(); diff --git a/src/telemetry/shapes.tsx b/src/telemetry/shapes.tsx index 1b67371050..329b1987aa 100644 --- a/src/telemetry/shapes.tsx +++ b/src/telemetry/shapes.tsx @@ -1,5 +1,6 @@ import z from "zod"; import { ERROR_SOURCE } from "../errors"; +import { PROJECT_TEMPLATE_NAMES } from "../handlers/project/shortcuts"; const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const SEMVER_PATTERN = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/; @@ -64,6 +65,7 @@ export const commandRunSchema = safeSchema({ error_source: z.enum(Object.values(ERROR_SOURCE)).optional(), is_tui: z.boolean().default(false), project_format: z.enum(["v0", "v1", "unknown"]).optional(), + project_template: z.enum(PROJECT_TEMPLATE_NAMES).optional(), legacy_deploy_exit_code: z.number().int().min(0).max(255).optional(), project_runtime_count: z.number().int().nonnegative().optional(), project_memory_count: z.number().int().nonnegative().optional(), From 48273c42365242959ca63b84f66d416e34284f78 Mon Sep 17 00:00:00 2001 From: Sasha Mittal Date: Wed, 18 Nov 2026 22:54:33 +0000 Subject: [PATCH 04/19] feat(runtime): support s3BucketMount filesystem configurations --- .../templates/a2a-python-strands/main.py | 2 + .../templates/mcp-python-fastmcp/main.py | 1 + src/core/project/templates/runtime.test.ts | 18 ++++ src/core/project/templates/runtime.ts | 12 +++ .../runtime/__snapshots__/index.test.ts.snap | 24 ++++++ .../project/add/runtime/index.test.ts | 29 +++++++ src/handlers/project/add/runtime/index.ts | 2 +- src/projectSchemas/runtime.test.ts | 82 +++++++++++++++++++ src/projectSchemas/runtime.ts | 48 ++++++++++- 9 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 src/handlers/project/add/runtime/__snapshots__/index.test.ts.snap diff --git a/src/assets/templates/a2a-python-strands/main.py b/src/assets/templates/a2a-python-strands/main.py index c3182b7a8d..122bba38f2 100644 --- a/src/assets/templates/a2a-python-strands/main.py +++ b/src/assets/templates/a2a-python-strands/main.py @@ -21,6 +21,7 @@ def add_numbers(a: int, b: int) -> int: {{#if sessionStorageMountPath}}"{{sessionStorageMountPath}}",{{/if}} {{#each efsMounts}}"{{mountPath}}",{{/each}} {{#each s3Mounts}}"{{mountPath}}",{{/each}} + {{#each s3BucketMounts}}"{{mountPath}}",{{/each}} ] def _safe_resolve(path: str) -> str: @@ -79,6 +80,7 @@ def list_files(path: str) -> str: {{#if sessionStorageMountPath}}- {{sessionStorageMountPath}}: ephemeral session storage (lost when session ends) {{/if}}{{#each efsMounts}}- {{mountPath}}: EFS persistent storage (persists across sessions and agent restarts) {{/each}}{{#each s3Mounts}}- {{mountPath}}: S3 Files persistent storage (durable, backed by S3) +{{/each}}{{#each s3BucketMounts}}- {{mountPath}}: S3 bucket mount (durable, backed by S3; write whole files, no appending or in-place edits) {{/each}}{{/if}} """ diff --git a/src/assets/templates/mcp-python-fastmcp/main.py b/src/assets/templates/mcp-python-fastmcp/main.py index fd5cef416f..331d4e31b6 100644 --- a/src/assets/templates/mcp-python-fastmcp/main.py +++ b/src/assets/templates/mcp-python-fastmcp/main.py @@ -13,6 +13,7 @@ {{#if sessionStorageMountPath}}"{{sessionStorageMountPath}}",{{/if}} {{#each efsMounts}}"{{mountPath}}",{{/each}} {{#each s3Mounts}}"{{mountPath}}",{{/each}} + {{#each s3BucketMounts}}"{{mountPath}}",{{/each}} ] def _safe_resolve(path: str) -> str: diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index cd39f5da91..ec2460aefa 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -76,6 +76,24 @@ const mounts = { } as const; describe("runtime templates", () => { + test.each(["mcp-python-fastmcp", "a2a-python-strands"] as const)( + "%s gives its file tools access to an S3 bucket mount", + async (template) => { + const { appDir } = await addTemplate("my_agent", template, { + infra: { + platformVersion: "V2", + filesystemConfigurations: [ + { s3BucketMount: { bucket: "amzn-s3-demo-bucket", mountPath: "/mnt/bucket" } }, + ], + } as Partial, + }); + const main = await Bun.file(join(appDir, "main.py")).text(); + expect(main).toMatch(/_MOUNT_PATHS = \[\s*"\/mnt\/bucket",\s*\]/); + if (template === "a2a-python-strands") + expect(main).toContain("- /mnt/bucket: S3 bucket mount"); + }, + ); + test.each<[RuntimeTemplateShortcutName, Record, Partial]>([ ["agent-python-minimal", { build: "CodeZip", runtimeVersion: "PYTHON_3_14" }, {}], ["agent-python-strands", { build: "CodeZip", protocol: "HTTP" }, {}], diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index e69740ba12..1ec462e51c 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -396,11 +396,17 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa ? [{ mountPath: configuration.s3FilesAccessPoint.mountPath }] : [], ); + const s3BucketMounts = filesystemConfigurations.flatMap((configuration) => + "s3BucketMount" in configuration + ? [{ mountPath: configuration.s3BucketMount.mountPath }] + : [], + ); const context = { name: toPythonPackageName(input.name), sessionStorageMountPath, efsMounts, s3Mounts, + s3BucketMounts, needsOs: filesystemConfigurations.length > 0, // The AgentCore Runtime requires OTEL dependencies to be present; the // container launches main.py as the `main` module under @@ -436,6 +442,11 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa ? [{ mountPath: configuration.s3FilesAccessPoint.mountPath }] : [], ); + const s3BucketMounts = filesystemConfigurations.flatMap((configuration) => + "s3BucketMount" in configuration + ? [{ mountPath: configuration.s3BucketMount.mountPath }] + : [], + ); const memory = input.scaffoldRuntimeInput.memory; const modelScaffold = resolveModelProviderScaffold(input); const modelProvider = input.scaffoldRuntimeInput.modelProvider ?? "Bedrock"; @@ -452,6 +463,7 @@ const getTemplateResolvers = (assetSource: AssetSource, templateRenderer: Templa sessionStorageMountPath, efsMounts, s3Mounts, + s3BucketMounts, needsOs: filesystemConfigurations.length > 0, // The AgentCore Runtime requires OTEL dependencies to be present; the // container launches main.py as the `main` module under diff --git a/src/handlers/project/add/runtime/__snapshots__/index.test.ts.snap b/src/handlers/project/add/runtime/__snapshots__/index.test.ts.snap new file mode 100644 index 0000000000..e0a34821ed --- /dev/null +++ b/src/handlers/project/add/runtime/__snapshots__/index.test.ts.snap @@ -0,0 +1,24 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`project add runtime an S3 bucket mount is written to the spec entry 1`] = ` +{ + "build": "CodeZip", + "codeLocation": "app/s3_agent", + "entrypoint": "main.py", + "filesystemConfigurations": [ + { + "s3BucketMount": { + "bucket": "amzn-s3-demo-bucket", + "mountPath": "/mnt/data", + "prefix": "sessions/{runtimeSessionId}/", + "s3BucketOwner": "123456789012", + "s3BucketRegion": "us-west-2", + }, + }, + ], + "name": "s3_agent", + "platformVersion": "V2", + "protocol": "HTTP", + "runtimeVersion": "PYTHON_3_14", +} +`; diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index 98cc398453..19dfc42088 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -479,6 +479,35 @@ describe("project add runtime", () => { }); }); + test("an S3 bucket mount is written to the spec entry", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + await run([ + "add", + "runtime", + "--name", + "s3_agent", + "--language", + "python", + "--platform-version", + "V2", + "--filesystem-configurations", + JSON.stringify([ + { + s3BucketMount: { + bucket: "amzn-s3-demo-bucket", + mountPath: "/mnt/data", + prefix: "sessions/{runtimeSessionId}/", + s3BucketOwner: "123456789012", + s3BucketRegion: "us-west-2", + }, + }, + ]), + ]); + + expect(await runtimeOf(projectRoot, "s3_agent")).toMatchSnapshot(); + }); + test("an existing folder keeps the user's files; only missing docs are added", async () => { const { projectRoot, cleanup } = await initProject(); cleanups.push(cleanup); diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index 98d5a43924..a2b1601bec 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -139,7 +139,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => ), flag( "filesystem-configurations", - "filesystem mount configurations (JSON)", + "filesystem mount configurations (JSON); an s3BucketMount needs --platform-version V2", z.string().optional(), { group: ENVIRONMENT }, ), diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index f5a4c3dfff..4f816260ed 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -181,3 +181,85 @@ describe("runtime custom validation", () => { expect(ProjectRuntimeSchema.safeParse(containerAgent).success).toBe(true); }); }); + +describe("s3BucketMount validation", () => { + const v2Agent = { ...codeZipAgent, platformVersion: "V2" as const }; + const withMount = (s3BucketMount: Record, agent: object = v2Agent) => + ProjectRuntimeSchema.safeParse({ + ...agent, + filesystemConfigurations: [ + { + s3BucketMount: { + bucket: "amzn-s3-demo-bucket", + mountPath: "/mnt/bucket", + ...s3BucketMount, + }, + }, + ], + }); + const messages = (result: ReturnType) => + result.error?.issues.map((issue) => issue.message) ?? []; + + it("accepts a whole-bucket mount in PUBLIC and VPC network mode on V2", () => { + expect(withMount({}, { ...v2Agent, networkMode: "PUBLIC" }).success).toBe(true); + expect(withMount({}, { ...v2Agent, networkMode: "VPC", networkConfig }).success).toBe(true); + }); + it("rejects a misspelled field instead of dropping it", () => { + const result = withMount({ s3BucketOwnr: "123456789012" }); + expect(result.success).toBe(false); + }); + it("accepts every optional field", () => { + expect( + withMount({ + prefix: "data/{runtimeSessionId}/", + s3BucketOwner: "123456789012", + s3BucketRegion: "us-east-1", + }).success, + ).toBe(true); + }); + it("requires platformVersion V2, including when it is left unset", () => { + for (const agent of [codeZipAgent, { ...codeZipAgent, platformVersion: "V1" }]) { + const result = withMount({}, agent); + expect(result.success).toBe(false); + expect(messages(result)).toContain( + "s3BucketMount filesystem mounts require platformVersion: V2 (--platform-version V2)", + ); + } + }); + it("counts toward the five-mount limit with no cap of its own", () => { + const mounts = (count: number) => + Array.from({ length: count }, (_, index) => ({ + s3BucketMount: { bucket: "amzn-s3-demo-bucket", mountPath: `/mnt/bucket${index}` }, + })); + expect( + ProjectRuntimeSchema.safeParse({ ...v2Agent, filesystemConfigurations: mounts(5) }).success, + ).toBe(true); + expect( + ProjectRuntimeSchema.safeParse({ ...v2Agent, filesystemConfigurations: mounts(6) }).success, + ).toBe(false); + }); + it("rejects a mount path another mount type already uses", () => { + const result = ProjectRuntimeSchema.safeParse({ + ...v2Agent, + filesystemConfigurations: [ + { sessionStorage: { mountPath: "/mnt/data" } }, + { s3BucketMount: { bucket: "amzn-s3-demo-bucket", mountPath: "/mnt/data/" } }, + ], + }); + expect(messages(result)).toContain("Filesystem mount paths must be unique"); + }); + it("checks only the bucket and prefix length, leaving their rules to the CDK app", () => { + for (const bucket of ["my.bucket-1", "my-bucket--usw2-az1--x-s3", "my-mrap.mrap"]) { + expect(withMount({ bucket }).success).toBe(true); + } + expect(withMount({ bucket: "ab" }).success).toBe(false); + expect(withMount({ bucket: "a".repeat(64) }).success).toBe(false); + expect(withMount({ prefix: "data/{runtimeSessionId}/" }).success).toBe(true); + expect(withMount({ prefix: "" }).success).toBe(false); + expect(withMount({ prefix: "a".repeat(1025) }).success).toBe(false); + }); + it("checks the bucket owner and Region formats", () => { + expect(withMount({ s3BucketOwner: "12345678901" }).success).toBe(false); + expect(withMount({ s3BucketRegion: "uswest2" }).success).toBe(false); + }); +}); diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index 49f3da0f11..d09b43a0f6 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -191,12 +191,45 @@ export const S3FilesAccessPointConfigSchema = z.object({ ), }); export type S3FilesAccessPointConfig = z.infer; +// Only the shape is checked here; the CDK app and the service check the bucket and prefix rules. +// Strict so a misspelled optional key, such as s3BucketOwner, fails instead of being dropped. +export const S3BucketMountConfigSchema = z.strictObject({ + /** General purpose or directory bucket name. */ + bucket: z.string().min(3).max(63), + mountPath: z + .string() + .min(6) + .max(200) + .regex( + /^\/mnt\/[a-zA-Z0-9._-]+\/?$/, + "Must be a path under /mnt with exactly one subdirectory (e.g. /mnt/bucket)", + ), + /** + * Key prefix to mount; the whole bucket when omitted. {runtimeSessionId} gives each session + * its own prefix (e.g. "data/{runtimeSessionId}/"). + */ + prefix: z.string().min(1).max(1024).optional(), + /** Account that must own the bucket; defaults to the runtime's account. */ + s3BucketOwner: z + .string() + .regex(/^[0-9]{12}$/, "Must be a 12-digit AWS account ID") + .optional(), + /** Region of the bucket; defaults to the runtime's Region. */ + s3BucketRegion: z + .string() + .min(1) + .max(32) + .regex(/^([a-z]+-){2,3}\d+$/, "Must be an AWS Region code (e.g. us-west-2)") + .optional(), +}); +export type S3BucketMountConfig = z.infer; export const MAX_EFS_MOUNTS = 2; export const MAX_S3_MOUNTS = 2; export const FilesystemConfigurationSchema = z.union([ z.strictObject({ sessionStorage: SessionStorageSchema }), z.strictObject({ efsAccessPoint: EfsAccessPointConfigSchema }), z.strictObject({ s3FilesAccessPoint: S3FilesAccessPointConfigSchema }), + z.strictObject({ s3BucketMount: S3BucketMountConfigSchema }), ]); export type FilesystemConfiguration = z.infer; export const LIFECYCLE_TIMEOUT_MIN = 60; @@ -460,12 +493,25 @@ export const ProjectRuntimeSchema = z path: ["filesystemConfigurations"], }); } + // The service mounts only on V2. Its default when the field is unset depends on partition and + // account rollout, and an update without the field keeps the current version; the CLI sees + // neither, so it requires V2 explicitly. + if (fcs.some((fc) => "s3BucketMount" in fc) && data.platformVersion !== "V2") { + ctx.addIssue({ + code: "custom", + message: + "s3BucketMount filesystem mounts require platformVersion: V2 (--platform-version V2)", + path: ["platformVersion"], + }); + } const mountPaths = fcs.map((fc) => ("sessionStorage" in fc ? fc.sessionStorage.mountPath : "efsAccessPoint" in fc ? fc.efsAccessPoint.mountPath - : fc.s3FilesAccessPoint.mountPath + : "s3FilesAccessPoint" in fc + ? fc.s3FilesAccessPoint.mountPath + : fc.s3BucketMount.mountPath ).replace(/\/$/, ""), ); if (new Set(mountPaths).size !== mountPaths.length) { From 8ac35313c6f8a49a49c0f2c8df71a6fc52ef995e Mon Sep 17 00:00:00 2001 From: Vignesh Somasundaram Date: Fri, 20 Nov 2026 22:11:01 +0000 Subject: [PATCH 05/19] feat(runtime): add --platform-version to add runtime Accept an optional platformVersion (V1 | V2) on runtimes in agentcore.json and write it from `agentcore add runtime --platform-version`, which rejects any other value. Both spec builders carry it through, and `agentcore runtime get` shows the deployed platform version. The runtime docs that add runtime writes now describe V2 for Python and TypeScript: startup versus per-request work, snapshot-safe randomness, shared hostname and PID, slower create and update, keeping the field set, and the service error when the Region or account doesn't offer V2. They link to the AWS region list rather than copying it. Reaching a deployed runtime needs a @aws/agentcore-cdk release with platformVersion support and a bump of the pin in src/assets/cdk/package.json, which maintainers handle separately. Closes #2674 (cherry picked from commit 157c01797d810cc550cb3cec2e8eb22b2f956666) --- .../templates/runtime-docs/python/AGENTS.md | 4 +++ .../templates/runtime-docs/python/README.md | 28 +++++++++++++++++++ .../runtime-docs/typescript/AGENTS.md | 4 +++ .../runtime-docs/typescript/README.md | 28 +++++++++++++++++++ src/core/project/templates/runtime.test.ts | 2 ++ src/core/project/templates/runtime.ts | 1 + src/core/project/templates/runtimeDocs.ts | 1 + .../project/add/runtime/index.test.ts | 4 +++ src/handlers/project/add/runtime/index.ts | 8 ++++++ src/handlers/project/add/runtime/types.ts | 1 + src/handlers/runtime/get/screen.tsx | 1 + src/handlers/runtime/runtime.screen.test.tsx | 2 ++ src/projectSchemas/constants.ts | 2 ++ src/projectSchemas/runtime.test.ts | 12 ++++++++ src/projectSchemas/runtime.ts | 3 ++ 15 files changed, 101 insertions(+) diff --git a/src/assets/templates/runtime-docs/python/AGENTS.md b/src/assets/templates/runtime-docs/python/AGENTS.md index dcae043ebf..404354495b 100644 --- a/src/assets/templates/runtime-docs/python/AGENTS.md +++ b/src/assets/templates/runtime-docs/python/AGENTS.md @@ -68,6 +68,10 @@ in more detail. `context.session_id`) to tell conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup + code to work that is the same for every request, and create random values + (`secrets` or `os.urandom()`), timestamps, and credentials inside the + request handler. ## Must not diff --git a/src/assets/templates/runtime-docs/python/README.md b/src/assets/templates/runtime-docs/python/README.md index eee3e23840..af4854c6e9 100644 --- a/src/assets/templates/runtime-docs/python/README.md +++ b/src/assets/templates/runtime-docs/python/README.md @@ -196,6 +196,34 @@ Every protocol also shares these: to the current time on every ping. Change it only when the status changes, or idle sessions never time out and can use up your session quota. +### Platform version V2 + +`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each +instance from a snapshot of your initialized code, so cold starts stay fast +as images and traffic grow. V1 is the default, and V2 is offered in +[some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +On V2: + +- Startup work (imports, loading models, building clients) is captured once + in the snapshot and shared by every instance. Finish it within 120 seconds, + or creating the runtime fails its health check. +- Produce anything that must differ per request, or can expire, in your + request handler: random values and IDs, the current time, the reference + point for elapsed time, and credentials. +- Get random values from the operating system on each request + (`secrets`, `os.urandom()`, `uuid.uuid4()`). The `random` module is seeded + at startup, so restored instances repeat its sequence. +- Every instance reports the same hostname and PID, so don't use either as + an instance or worker ID. +- Creating or updating a V2 runtime takes several minutes. Keep + `platformVersion` set: removing it doesn't move the runtime back, and a + later replacement of the runtime would start on V1. Set `V1` to move back. +- If deploy fails with "platformVersion V2 is not available for this + account", the target's Region, or your account, doesn't offer V2: deploy to + a supported Region or set `V1`. + +More: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-v2-optimize.html + ## Dependencies: `pyproject.toml` Declare dependencies in `[project].dependencies`. That's the only place the diff --git a/src/assets/templates/runtime-docs/typescript/AGENTS.md b/src/assets/templates/runtime-docs/typescript/AGENTS.md index 8de7f8283d..381f72fb64 100644 --- a/src/assets/templates/runtime-docs/typescript/AGENTS.md +++ b/src/assets/templates/runtime-docs/typescript/AGENTS.md @@ -56,6 +56,10 @@ in more detail. conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup + code to work that is the same for every request, and create random values + (`/dev/urandom`, not the `crypto` module), timestamps, and credentials + inside the request handler. ## Must not diff --git a/src/assets/templates/runtime-docs/typescript/README.md b/src/assets/templates/runtime-docs/typescript/README.md index e8abc3b3c6..96bcdb7842 100644 --- a/src/assets/templates/runtime-docs/typescript/README.md +++ b/src/assets/templates/runtime-docs/typescript/README.md @@ -136,6 +136,34 @@ Every protocol also shares these: to the current time on every ping. Change it only when the status changes, or idle sessions never time out and can use up your session quota. +### Platform version V2 + +`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each +instance from a snapshot of your initialized code, so cold starts stay fast +as images and traffic grow. V1 is the default, and V2 is offered in +[some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +On V2: + +- Startup work (imports, loading models, building clients) is captured once + in the snapshot and shared by every instance. Finish it within 120 seconds, + or creating the runtime fails its health check. +- Produce anything that must differ per request, or can expire, in your + request handler: random values and IDs, the current time, the reference + point for elapsed time, and credentials. +- Read random bytes from `/dev/urandom` on each request. Node's `crypto` + module (`randomBytes`, `randomUUID`, `getRandomValues`, and packages such + as `uuid`) can repeat values across instances, even inside the handler. +- Every instance reports the same hostname and PID, so don't use either as + an instance or worker ID. +- Creating or updating a V2 runtime takes several minutes. Keep + `platformVersion` set: removing it doesn't move the runtime back, and a + later replacement of the runtime would start on V1. Set `V1` to move back. +- If deploy fails with "platformVersion V2 is not available for this + account", the target's Region, or your account, doesn't offer V2: deploy to + a supported Region or set `V1`. + +More: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-v2-optimize.html + ## Dependencies: `package.json` ```json diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index cd5ca140a4..cd39f5da91 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -100,6 +100,7 @@ describe("runtime templates", () => { const { runtime, appDir, core } = await addTemplate("my_bma", "environment-python-bma", { infra: { lifecycleConfiguration: { idleRuntimeSessionTimeout: 300, maxLifetime: 3600 }, + platformVersion: "V2", additionalPolicies: ["custom-policy.json"], tags: { team: "agents" }, }, @@ -111,6 +112,7 @@ describe("runtime templates", () => { dockerfile: "Dockerfile", protocol: "HTTP", lifecycleConfiguration: { idleRuntimeSessionTimeout: 300, maxLifetime: 3600 }, + platformVersion: "V2", additionalPolicies: ["bma-acr-policy.json", "custom-policy.json"], tags: { "agentcore:template": "BedrockManagedAgents", team: "agents" }, }); diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index 2a5cc7fb9f..e69740ba12 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -120,6 +120,7 @@ function buildRuntimeSpec(input: RuntimeResourceConfig): ProjectRuntime { ...(infra.envVars && { envVars: infra.envVars }), ...(infra.networkMode && { networkMode: infra.networkMode }), ...(infra.networkConfig && { networkConfig: infra.networkConfig }), + ...(infra.platformVersion && { platformVersion: infra.platformVersion }), ...(infra.authorizerType && { authorizerType: infra.authorizerType }), ...(infra.authorizerConfiguration && { authorizerConfiguration: infra.authorizerConfiguration, diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index f5ed443e11..3922ec5dc5 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -156,6 +156,7 @@ export function buildDocsRuntimeSpec(input: RuntimeDocsConfig): ProjectRuntime { ...(infra.envVars?.length && { envVars: infra.envVars }), ...(infra.networkMode && { networkMode: infra.networkMode }), ...(infra.networkConfig && { networkConfig: infra.networkConfig }), + ...(infra.platformVersion && { platformVersion: infra.platformVersion }), ...(infra.authorizerType && { authorizerType: infra.authorizerType }), ...(infra.authorizerConfiguration && { authorizerConfiguration: infra.authorizerConfiguration, diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index b9bc61335a..98cc398453 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -327,6 +327,8 @@ describe("project add runtime", () => { "VPC", "--network-config", '{"subnets":["subnet-0123456789abcdef0"],"securityGroups":["sg-0123456789abcdef0"]}', + "--platform-version", + "V2", "--authorizer-type", "CUSTOM_JWT", "--authorizer-configuration", @@ -458,6 +460,7 @@ describe("project add runtime", () => { subnets: ["subnet-0123456789abcdef0"], securityGroups: ["sg-0123456789abcdef0"], }, + platformVersion: "V2", authorizerType: "CUSTOM_JWT", authorizerConfiguration: { customJwtAuthorizer: { @@ -566,6 +569,7 @@ describe("project add runtime", () => { ["--model-provider", "anthropic"], ["--language", "rust"], ["--protocol", "GRPC"], + ["--platform-version", "v2"], ["--type", "create"], ["--type", "import"], ])("rejects %s %s and writes nothing", async (flagName, value) => { diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index eecaebc547..98d5a43924 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -8,6 +8,7 @@ import { AgentNameSchema, type EnvVar } from "../../../../projectSchemas/runtime import { RuntimeAuthorizerTypeSchema } from "../../../../projectSchemas/auth"; import { NetworkModeSchema, + PlatformVersionSchema, ProtocolModeSchema, type ProtocolMode, } from "../../../../projectSchemas/constants"; @@ -124,6 +125,12 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => flag("network-config", "VPC network configuration (JSON)", z.string().optional(), { group: ENVIRONMENT, }), + flag( + "platform-version", + "Runtime platform version: V1 (service default) or V2", + PlatformVersionSchema.optional(), + { group: ENVIRONMENT }, + ), flag( "lifecycle-configuration", "session idle timeout and instance lifetime configuration (JSON)", @@ -270,6 +277,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => envVars: toEnvironmentVariables(inputEnvironmentVariables), networkMode: flags["network-mode"], networkConfig: parseJsonFlag("network-config", flags["network-config"]), + platformVersion: flags["platform-version"], authorizerType: flags["authorizer-type"], authorizerConfiguration: parseJsonFlag( "authorizer-configuration", diff --git a/src/handlers/project/add/runtime/types.ts b/src/handlers/project/add/runtime/types.ts index 618aebb731..f2c2dc8032 100644 --- a/src/handlers/project/add/runtime/types.ts +++ b/src/handlers/project/add/runtime/types.ts @@ -13,6 +13,7 @@ const RuntimeInfraConfigSchema = z.object({ additionalPolicies: ProjectRuntimeSchema.shape.additionalPolicies, envVars: ProjectRuntimeSchema.shape.envVars, networkMode: ProjectRuntimeSchema.shape.networkMode, + platformVersion: ProjectRuntimeSchema.shape.platformVersion, networkConfig: ProjectRuntimeSchema.shape.networkConfig, authorizerType: ProjectRuntimeSchema.shape.authorizerType, authorizerConfiguration: ProjectRuntimeSchema.shape.authorizerConfiguration, diff --git a/src/handlers/runtime/get/screen.tsx b/src/handlers/runtime/get/screen.tsx index 6940cb7061..9206c5ea75 100644 --- a/src/handlers/runtime/get/screen.tsx +++ b/src/handlers/runtime/get/screen.tsx @@ -67,6 +67,7 @@ export function RuntimeGetScreen(props: ScreenProps) { version: detail.data?.agentRuntimeVersion ?? "", protocol: detail.data?.protocolConfiguration?.serverProtocol ?? "-", network: detail.data?.networkConfiguration?.networkMode ?? "-", + platform: detail.data?.platformVersion ?? "-", arn: detail.data?.agentRuntimeArn ?? "", }} actions={ diff --git a/src/handlers/runtime/runtime.screen.test.tsx b/src/handlers/runtime/runtime.screen.test.tsx index 7bac21fb59..49d5d4bfa6 100644 --- a/src/handlers/runtime/runtime.screen.test.tsx +++ b/src/handlers/runtime/runtime.screen.test.tsx @@ -42,6 +42,7 @@ function getRuntimeResponse( lastUpdatedAt: new Date("2026-07-20T12:34:56.000Z"), roleArn: "arn:aws:iam::123456789012:role/runtime-role", networkConfiguration: { networkMode: "PUBLIC" }, + platformVersion: "V2", status: "READY", protocolConfiguration: { serverProtocol: "HTTP" }, lifecycleConfiguration: { @@ -176,6 +177,7 @@ describe("runtime hub", () => { expect(r.lastFrame()).toMatch(/version\s+7/); expect(r.lastFrame()).toMatch(/protocol\s+HTTP/); expect(r.lastFrame()).toMatch(/network\s+PUBLIC/); + expect(r.lastFrame()).toMatch(/platform\s+V2/); expect(r.lastFrame()).not.toContain("failureReason"); await waitFor(() => core.runtime.calls.some((call) => call.method === "getRuntime")); expect(core.runtime.calls.find((call) => call.method === "getRuntime")).toEqual({ diff --git a/src/projectSchemas/constants.ts b/src/projectSchemas/constants.ts index a7a8c6e31f..514fad4641 100644 --- a/src/projectSchemas/constants.ts +++ b/src/projectSchemas/constants.ts @@ -70,6 +70,8 @@ export const RuntimeVersionSchema = z.union([PythonRuntimeSchema, NodeRuntimeSch export type RuntimeVersion = z.infer; export const NetworkModeSchema = z.enum(["PUBLIC", "VPC"]); export type NetworkMode = z.infer; +export const PlatformVersionSchema = z.enum(["V1", "V2"]); +export type PlatformVersion = z.infer; export const VPC_ID_PATTERN = /^vpc-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SUBNET_ID_PATTERN = /^subnet-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SECURITY_GROUP_ID_PATTERN = /^sg-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index 967991cb15..f5a4c3dfff 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -51,6 +51,18 @@ describe("runtime custom validation", () => { }).success, ).toBe(false); }); + it("accepts only the V1 and V2 platform versions", () => { + for (const platformVersion of ["V1", "V2"]) { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( + true, + ); + } + for (const platformVersion of ["v2", "V3", ""]) { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( + false, + ); + } + }); it("couples VPC mode and network configuration", () => { expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, networkMode: "VPC" }).success).toBe( false, diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index bd7bbc1926..49f3da0f11 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -1,6 +1,7 @@ import { MAX_CONTAINER_BUILD_SECURITY_GROUPS, NetworkModeSchema, + PlatformVersionSchema, ProtocolModeSchema, RuntimeVersionSchema as RuntimeVersionSchemaFromConstants, SECURITY_GROUP_ID_PATTERN, @@ -311,6 +312,8 @@ export const ProjectRuntimeSchema = z buildContextPath: DirectoryPathSchema.optional(), customDockerBuildArgs: z.record(EnvVarNameSchema, BuildArgValueSchema).optional(), runtimeVersion: RuntimeVersionSchemaFromConstants.optional(), + /** Removing this keeps a deployed runtime on its current version; set V1 to move back. */ + platformVersion: PlatformVersionSchema.optional(), envVars: z.array(EnvVarSchema).optional(), networkMode: NetworkModeSchema.optional(), networkConfig: NetworkConfigSchema.optional(), From acedeb822a334746a4ececaf2f8dbf8e9e18bbd6 Mon Sep 17 00:00:00 2001 From: Vignesh Somasundaram <76790050+vigneshsundar1997@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:50:04 -0800 Subject: [PATCH 06/19] feat(runtime): add V2 runtime settings, dev warmup hooks, and V2 template fixes (#2905) - resourceConfigurations and hooksConfiguration in agentcore.json, with `agentcore add runtime --resource-configurations/--hooks-configuration` (JSON, V2 only) and memory and hooks rows in `agentcore runtime get`. - `agentcore dev` runs a runtime's build warmup hook the way V2 does: waits for a healthy GET /ping, sends the memory and disk calls in one 120 s budget, and fails the start if either fails. Covers the supervisor and `dev --agent`; a container hook on its own port is published with an extra port mapping. - Templates: AG-UI builds the agent on the first request for API-key model providers, so the key isn't frozen into a V2 snapshot; the Strands container moves to Amazon Linux 2023 with snapshot-safe OpenSSL and Python 3.12; BMA uses AL2023's Python 3.14, which links the base image's snapshot-safe OpenSSL, instead of a uv-installed Python with its own. - Runtime docs follow the current "Optimize for V2" guidance. Co-authored-by: Vignesh Somasundaram (cherry picked from commit a6ec000362eda1a2f5efd4bcaac2dcdb95c2fdff) --- README.md | 3 + .../agent-python-strands/Dockerfile.template | 14 +- .../templates/agui-python-strands/main.py | 53 +++- .../bedrock-managed-agents/Dockerfile | 9 +- .../templates/runtime-docs/python/AGENTS.md | 10 +- .../templates/runtime-docs/python/README.md | 50 ++-- .../runtime-docs/typescript/AGENTS.md | 11 +- .../runtime-docs/typescript/README.md | 39 ++- src/core/dev/container.test.ts | 31 ++ src/core/dev/container.ts | 9 + src/core/dev/readiness.test.ts | 196 ++++++++++++ src/core/dev/readiness.ts | 280 ++++++++++++++++++ src/core/dev/supervisor.test.ts | 91 ++++++ src/core/dev/supervisor.ts | 38 ++- .../templates/bedrockManagedAgents.test.ts | 9 +- .../project/templates/pythonSecurity.test.ts | 6 +- src/core/project/templates/runtime.test.ts | 15 + src/core/project/templates/runtime.ts | 2 + src/core/project/templates/runtimeDocs.ts | 2 + .../project/add/runtime/index.test.ts | 20 ++ src/handlers/project/add/runtime/index.ts | 19 ++ src/handlers/project/add/runtime/types.ts | 2 + src/handlers/project/dev/index.test.ts | 72 +++++ src/handlers/project/dev/index.ts | 82 ++++- src/handlers/project/dev/types.ts | 2 + src/handlers/runtime/get/screen.tsx | 19 ++ src/handlers/runtime/runtime.screen.test.tsx | 11 +- src/projectSchemas/runtime.test.ts | 23 ++ src/projectSchemas/runtime.ts | 26 ++ 29 files changed, 1066 insertions(+), 78 deletions(-) create mode 100644 src/core/dev/readiness.test.ts create mode 100644 src/core/dev/readiness.ts diff --git a/README.md b/README.md index 6a3dba7b7e..59aaa8eb45 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,9 @@ up from the current directory. `agentcore dev` runs runtimes locally or deploys harnesses and prints invoke guidance. Use `--mode browser` for Agent Inspector, `--skip-deploy` to reuse deployed harnesses, and `--agent ` to choose an agent in mixed projects. +For a runtime with a build warmup hook (`hooksConfiguration.build.warmup`), dev waits for a healthy +`GET /ping`, then sends the hook's `memory` and `disk` calls as platform version V2 does, and fails +the start if either fails. New payment credentials receive provider names that payment connectors can reference. An existing payment credential keeps the provider ARN recorded for its deployment diff --git a/src/assets/templates/agent-python-strands/Dockerfile.template b/src/assets/templates/agent-python-strands/Dockerfile.template index 319ad9ba28..91965046ca 100644 --- a/src/assets/templates/agent-python-strands/Dockerfile.template +++ b/src/assets/templates/agent-python-strands/Dockerfile.template @@ -1,8 +1,13 @@ -FROM public.ecr.aws/docker/library/python:3.12-slim-trixie +FROM public.ecr.aws/amazonlinux/amazonlinux:2023 -RUN apt-get update && apt-get upgrade -y && rm -rf /var/lib/apt/lists/* +# Snapshot-safe OpenSSL reseeds its random number generator after a platform version V2 +# snapshot restore, so sessions don't repeat random values. Python's ssl module uses it. +RUN dnf upgrade -y \ + && dnf swap -y openssl-libs openssl-snapsafe-libs \ + && dnf install -y python3.12 python3.12-pip shadow-utils \ + && dnf clean all -RUN pip install --no-cache-dir uv +RUN python3.12 -m pip install --no-cache-dir uv ARG UV_DEFAULT_INDEX ARG UV_INDEX @@ -17,6 +22,7 @@ ENV UV_SYSTEM_PYTHON=1 \ DOCKER_CONTAINER=1 \ UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX} \ UV_INDEX=${UV_INDEX} \ + UV_PYTHON=python3.12 \ PATH="/app/.venv/bin:$PATH" RUN useradd -m -u 1000 bedrock_agentcore @@ -25,7 +31,7 @@ COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project COPY --chown=bedrock_agentcore:bedrock_agentcore . . -RUN uv sync --frozen --no-dev && /usr/local/bin/python -m pip uninstall -y uv +RUN uv sync --frozen --no-dev && /usr/bin/python3.12 -m pip uninstall -y uv USER bedrock_agentcore diff --git a/src/assets/templates/agui-python-strands/main.py b/src/assets/templates/agui-python-strands/main.py index e230027fe2..5f685b8e07 100644 --- a/src/assets/templates/agui-python-strands/main.py +++ b/src/assets/templates/agui-python-strands/main.py @@ -1,4 +1,7 @@ import os +{{#unless (eq modelProvider "Bedrock")}} +import asyncio +{{/unless}} import uvicorn from fastapi import FastAPI @@ -15,12 +18,6 @@ def add_numbers(a: int, b: int) -> int: return a + b -agent = Agent( - model=load_model(), - system_prompt="You are a helpful assistant. Use tools when appropriate.", - tools=[add_numbers], -) - # The AG-UI protocol carries a per-conversation thread_id; each thread gets its # own session manager so history is scoped to the conversation. Returns None # (in-process history only) until the deployed MEMORY_ID env var is set. @@ -30,9 +27,47 @@ def session_manager_provider(input_data): config = StrandsAgentConfig(session_manager_provider=session_manager_provider) -agui_agent = StrandsAgent( - agent=agent, name="{{ name }}", description="A helpful assistant", config=config -) + +def _build_agui_agent() -> StrandsAgent: + agent = Agent( + model=load_model(), + system_prompt="You are a helpful assistant. Use tools when appropriate.", + tools=[add_numbers], + ) + return StrandsAgent( + agent=agent, name="{{ name }}", description="A helpful assistant", config=config + ) + + +{{#if (eq modelProvider "Bedrock")}} +# Built at import, before a V2 snapshot: the Bedrock client resolves and refreshes +# its own AWS credentials, so every session can reuse it. +agui_agent = _build_agui_agent() +{{else}} +class _LazyAguiAgent: + """Builds the agent on the first request instead of at import. + + load_model() fetches the model API key from AgentCore Identity. Fetched at + import, the key would be frozen into a V2 snapshot and shared by every session. + Each session runs in its own process, so this builds once per session. The build + runs in a worker thread so /ping and other requests keep being served meanwhile. + """ + + def __init__(self): + self._agent = None + self._lock = asyncio.Lock() # concurrent first requests wait for one build + + async def run(self, *args, **kwargs): + if self._agent is None: + async with self._lock: + if self._agent is None: + self._agent = await asyncio.to_thread(_build_agui_agent) + async for event in self._agent.run(*args, **kwargs): + yield event + + +agui_agent = _LazyAguiAgent() +{{/if}} # The app is assembled here instead of with ag_ui_strands.create_strands_app so # FastAPI's environment-driven OTLP export (FastAPI >= 0.142) can be turned off: the diff --git a/src/assets/templates/bedrock-managed-agents/Dockerfile b/src/assets/templates/bedrock-managed-agents/Dockerfile index 249fd02775..366c733965 100644 --- a/src/assets/templates/bedrock-managed-agents/Dockerfile +++ b/src/assets/templates/bedrock-managed-agents/Dockerfile @@ -1,7 +1,9 @@ FROM public.ecr.aws/lambda/microvms:al2023-minimal -# OS setup -RUN dnf install -y tar gzip findutils shadow-utils ca-certificates \ +# OS setup. The base image ships snapshot-safe OpenSSL (openssl-snapsafe-libs), which reseeds its +# random number generator after a platform version V2 snapshot restore. AL2023's Python links it, +# unlike a standalone Python that bundles its own OpenSSL. +RUN dnf install -y tar gzip findutils shadow-utils ca-certificates python3.14 \ && dnf clean all \ && useradd -m -u 1000 app @@ -23,8 +25,7 @@ RUN arch=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') \ COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/ ARG UV_DEFAULT_INDEX ARG UV_INDEX -ENV UV_PYTHON_INSTALL_DIR=/opt/python UV_PYTHON_BIN_DIR=/usr/local/bin -RUN uv python install --default +ENV UV_PYTHON=python3.14 UV_PYTHON_PREFERENCE=only-system UV_PYTHON_DOWNLOADS=never # Application. The layout of /opt/bma is the same as the layout of this directory. WORKDIR /opt/bma diff --git a/src/assets/templates/runtime-docs/python/AGENTS.md b/src/assets/templates/runtime-docs/python/AGENTS.md index 404354495b..86aa554fcf 100644 --- a/src/assets/templates/runtime-docs/python/AGENTS.md +++ b/src/assets/templates/runtime-docs/python/AGENTS.md @@ -68,10 +68,12 @@ in more detail. `context.session_id`) to tell conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. -- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup - code to work that is the same for every request, and create random values - (`secrets` or `os.urandom()`), timestamps, and credentials inside the - request handler. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, load models and + build reusable clients at module scope, before the snapshot, and create + random values (`secrets` or `os.urandom()`), IDs and timestamps inside the + request handler. Refresh credentials when they expire. Anything that fetches + credentials, such as a model whose API key comes from AgentCore Identity, + stays per session: build it on the first request, not at import. ## Must not diff --git a/src/assets/templates/runtime-docs/python/README.md b/src/assets/templates/runtime-docs/python/README.md index af4854c6e9..bf6896f912 100644 --- a/src/assets/templates/runtime-docs/python/README.md +++ b/src/assets/templates/runtime-docs/python/README.md @@ -198,23 +198,32 @@ Every protocol also shares these: ### Platform version V2 -`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each -instance from a snapshot of your initialized code, so cold starts stay fast -as images and traffic grow. V1 is the default, and V2 is offered in +`--platform-version V2` (`platformVersion` in `agentcore.json`) prepares your +agent once and starts each session from a snapshot of it, so cold starts stay +fast as images and traffic grow. V1 is the default, and V2 is offered in [some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). On V2: -- Startup work (imports, loading models, building clients) is captured once - in the snapshot and shared by every instance. Finish it within 120 seconds, - or creating the runtime fails its health check. -- Produce anything that must differ per request, or can expire, in your - request handler: random values and IDs, the current time, the reference - point for elapsed time, and credentials. -- Get random values from the operating system on each request - (`secrets`, `os.urandom()`, `uuid.uuid4()`). The `random` module is seeded - at startup, so restored instances repeat its sequence. -- Every instance reports the same hostname and PID, so don't use either as - an instance or worker ID. +- The snapshot is taken when your health check (`GET /ping`) first passes, + so report healthy only after your agent has loaded what sessions need. + `BedrockAgentCoreApp` does this for you: code at module scope (imports, + models, clients) runs before `app.run()` starts the server. + If the health check doesn't pass in time, the create or update fails. +- Build reusable clients before the snapshot. Refresh credentials when they + expire, and create a new boto3 `Session` in the handler only for + clients that need the session's context keys. +- Create random values, IDs, tokens and timestamps in the request handler, + from the operating system (`secrets`, `os.urandom()`, `uuid.uuid4()`). The + `random` module repeats the same sequence in every session. +- In a container, use a snapshot-safe OpenSSL. On Amazon Linux 2023: + `RUN dnf swap -y openssl-libs openssl-snapsafe-libs`. Direct code deploys + already use it; OpenSSL builds that libraries bundle can repeat values. +- Every session reports the same hostname and PID, so don't use either as an + ID. +- `--hooks-configuration` adds a build warmup hook that loads memory and warms + files before sessions start; its two calls share 120 seconds. + `--resource-configurations` sets a committed memory baseline per session. + Each update replaces both, so keep them set in `agentcore.json`. - Creating or updating a V2 runtime takes several minutes. Keep `platformVersion` set: removing it doesn't move the runtime back, and a later replacement of the runtime would start on V1. Set `V1` to move back. @@ -379,14 +388,19 @@ Requirements for the image: A starting point: ```dockerfile -FROM public.ecr.aws/docker/library/python:3.12-slim-trixie - -RUN pip install --no-cache-dir uv +FROM public.ecr.aws/amazonlinux/amazonlinux:2023 + +# Snapshot-safe OpenSSL, so platform version V2 sessions don't repeat random values. +RUN dnf upgrade -y \ + && dnf swap -y openssl-libs openssl-snapsafe-libs \ + && dnf install -y python3.12 python3.12-pip shadow-utils \ + && dnf clean all +RUN python3.12 -m pip install --no-cache-dir uv ARG UV_DEFAULT_INDEX ARG UV_INDEX ENV UV_SYSTEM_PYTHON=1 UV_COMPILE_BYTECODE=1 PYTHONUNBUFFERED=1 \ UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX} UV_INDEX=${UV_INDEX} \ - PATH="/app/.venv/bin:$PATH" + UV_PYTHON=python3.12 PATH="/app/.venv/bin:$PATH" WORKDIR /app RUN useradd -m -u 1000 bedrock_agentcore diff --git a/src/assets/templates/runtime-docs/typescript/AGENTS.md b/src/assets/templates/runtime-docs/typescript/AGENTS.md index 381f72fb64..be193915a1 100644 --- a/src/assets/templates/runtime-docs/typescript/AGENTS.md +++ b/src/assets/templates/runtime-docs/typescript/AGENTS.md @@ -56,10 +56,13 @@ in more detail. conversations apart. Custom headers only arrive if they are named `X-Amzn-Bedrock-AgentCore-Runtime-Custom-*` and listed in `requestHeaderAllowlist`. -- If `platformVersion` is `V2` in `agentcore/agentcore.json`, keep startup - code to work that is the same for every request, and create random values - (`/dev/urandom`, not the `crypto` module), timestamps, and credentials - inside the request handler. +- If `platformVersion` is `V2` in `agentcore/agentcore.json`, load models and + build reusable clients at top level, before the snapshot, and create random + values, IDs and timestamps inside the request handler, with + `crypto.randomUUID({ disableEntropyCache: true })` or `/dev/urandom`, never + `Math.random()`. Refresh credentials when they expire. Anything that fetches + credentials, such as a model whose API key comes from AgentCore Identity, + stays per session: build it on the first request, not at import. ## Must not diff --git a/src/assets/templates/runtime-docs/typescript/README.md b/src/assets/templates/runtime-docs/typescript/README.md index 96bcdb7842..6f2e6433cc 100644 --- a/src/assets/templates/runtime-docs/typescript/README.md +++ b/src/assets/templates/runtime-docs/typescript/README.md @@ -138,23 +138,34 @@ Every protocol also shares these: ### Platform version V2 -`--platform-version V2` (`platformVersion` in `agentcore.json`) starts each -instance from a snapshot of your initialized code, so cold starts stay fast -as images and traffic grow. V1 is the default, and V2 is offered in +`--platform-version V2` (`platformVersion` in `agentcore.json`) prepares your +agent once and starts each session from a snapshot of it, so cold starts stay +fast as images and traffic grow. V1 is the default, and V2 is offered in [some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). On V2: -- Startup work (imports, loading models, building clients) is captured once - in the snapshot and shared by every instance. Finish it within 120 seconds, - or creating the runtime fails its health check. -- Produce anything that must differ per request, or can expire, in your - request handler: random values and IDs, the current time, the reference - point for elapsed time, and credentials. -- Read random bytes from `/dev/urandom` on each request. Node's `crypto` - module (`randomBytes`, `randomUUID`, `getRandomValues`, and packages such - as `uuid`) can repeat values across instances, even inside the handler. -- Every instance reports the same hostname and PID, so don't use either as - an instance or worker ID. +- The snapshot is taken when your health check (`GET /ping`) first passes, + so report healthy only after your agent has loaded what sessions need. + `BedrockAgentCoreApp` does this for you: top-level code (imports, models, + clients) runs before `app.run()` starts the server. + If the health check doesn't pass in time, the create or update fails. +- Build reusable clients before the snapshot. Refresh credentials when they + expire. +- Create random values, IDs, tokens and timestamps in the request handler. + `Math.random()` repeats the same sequence in every session. Call + `crypto.randomUUID({ disableEntropyCache: true })`; if + `node -p process.config.variables.node_shared_openssl` prints `false`, your + Node.js bundles its own OpenSSL and every `crypto` random function can + repeat, so read `/dev/urandom` instead. +- In a container, use a snapshot-safe OpenSSL. On Amazon Linux 2023: + `RUN dnf swap -y openssl-libs openssl-snapsafe-libs`. Direct code deploys + already use it. +- Every session reports the same hostname and PID, so don't use either as an + ID. +- `--hooks-configuration` adds a build warmup hook that loads memory and warms + files before sessions start; its two calls share 120 seconds. + `--resource-configurations` sets a committed memory baseline per session. + Each update replaces both, so keep them set in `agentcore.json`. - Creating or updating a V2 runtime takes several minutes. Keep `platformVersion` set: removing it doesn't move the runtime back, and a later replacement of the runtime would start on V1. Set `V1` to move back. diff --git a/src/core/dev/container.test.ts b/src/core/dev/container.test.ts index 5fc7295c39..ca8a2e9b2c 100644 --- a/src/core/dev/container.test.ts +++ b/src/core/dev/container.test.ts @@ -242,6 +242,37 @@ describe("ContainerDevRunner", () => { expect(run.command.join(" ")).not.toContain("test-secret-key"); }); + test.each([ + ["a hook on its own port", 9300, 9301, ["-p", "127.0.0.1:9301:9300"]], + ["a hook on the serving port", 8080, 9301, []], + ["no host port for the hook", 9300, undefined, []], + ] as const)( + "publishes a warmup hook port only for %s", + async (_label, hookPort, hostPort, extra) => { + const projectRuntime = runtime({ + hooksConfiguration: { + build: { warmup: { action: { httpPost: { path: "/warmup", port: hookPort } } } }, + }, + } as RuntimeOverrides); + const root = await projectRoot(projectRuntime); + const { calls, runner } = harness(); + + await collect( + runner.run({ + ...input(root, projectRuntime), + ...(hostPort !== undefined && { hookPort: hostPort }), + }), + ); + + const run = commandCall(calls, "run"); + expect(run.command.slice(5, 7 + extra.length)).toEqual([ + "-p", + "127.0.0.1:3000:8080", + ...extra, + ]); + }, + ); + test("uses a shared AWS config and rejects missing credentials", async () => { const projectRuntime = runtime(); const root = await projectRoot(projectRuntime); diff --git a/src/core/dev/container.ts b/src/core/dev/container.ts index 89cb9de544..1a1ab69e20 100644 --- a/src/core/dev/container.ts +++ b/src/core/dev/container.ts @@ -14,6 +14,7 @@ import { import { resolveContainerTool, type ContainerTool, type ToolAvailable } from "./containerTool"; import { isDirectory, isFile, resolvePathWithinProject } from "./path"; import { DEV_PORTS } from "./port"; +import { containerHookPort } from "./readiness"; const AWS_ENV_KEYS = [ "AWS_ACCESS_KEY_ID", @@ -177,6 +178,7 @@ export class ContainerDevRunner implements DevRunner { containerName, "-p", `127.0.0.1:${input.port}:${containerPort}`, + ...hookPortMapping(input), // Docker Engine on Linux does not define host.docker.internal (Desktop, // Podman, and Finch do); the mapping makes the OTLP endpoint rewrite // resolve everywhere and is harmless where the name already exists. @@ -252,3 +254,10 @@ function hashString(value: string): string { function sanitizeImageNameComponent(value: string): string { return value.replace(/_{3,}/g, "__"); } + +/** The extra `-p` for a warmup hook on its own port, so dev can call it from the host. */ +function hookPortMapping(input: DevServerInput): string[] { + const hookPort = containerHookPort(input.runtime); + if (hookPort === undefined || input.hookPort === undefined) return []; + return ["-p", `127.0.0.1:${input.hookPort}:${hookPort}`]; +} diff --git a/src/core/dev/readiness.test.ts b/src/core/dev/readiness.test.ts new file mode 100644 index 0000000000..b50c309bbb --- /dev/null +++ b/src/core/dev/readiness.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, test } from "bun:test"; +import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { + HookPortReserver, + type HttpFetch, + runWarmupHook, + WARMUP_TYPE_HEADER, + waitForHealthyPing, + warmupTarget, +} from "./readiness"; + +function runtime(build: ProjectRuntime["build"], httpPost?: { path: string; port?: number }) { + return { + name: "agent", + build, + protocol: "HTTP", + entrypoint: "main.py", + codeLocation: "app/agent", + ...(httpPost && { hooksConfiguration: { build: { warmup: { action: { httpPost } } } } }), + } as ProjectRuntime; +} + +type Call = { url: string; init: RequestInit }; + +/** A fetch that records each call and answers with the next scripted response (or throws it). */ +function scriptedFetch(responses: Array) { + const calls: Call[] = []; + const fetchImpl: HttpFetch = async (url, init) => { + calls.push({ url, init }); + const next = responses.length > 1 ? responses.shift()! : responses[0]!; + if (next instanceof Error) throw next; + return next.clone() as Response; + }; + return { fetchImpl, calls }; +} + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + +describe("warmupTarget", () => { + test("is undefined without a warmup hook", () => { + expect(warmupTarget(runtime("CodeZip"), 9100)).toBeUndefined(); + }); + + test.each(["CodeZip", "Container"] as const)( + "%s: a hook without a port is served on the agent's dev port", + (build) => { + expect(warmupTarget(runtime(build, { path: "/warmup" }), 9100)).toEqual({ + path: "/warmup", + port: 9100, + }); + }, + ); + + test.each(["CodeZip", "Container"] as const)( + "%s: a hook on the serving port follows the dev port, wherever dev runs the agent", + (build) => { + expect(warmupTarget(runtime(build, { path: "/warmup", port: 8080 }), 9100)).toEqual({ + path: "/warmup", + port: 9100, + }); + }, + ); + + test("CodeZip: a hook on its own port is reached on that local port", () => { + expect(warmupTarget(runtime("CodeZip", { path: "/warmup", port: 9300 }), 9100)).toEqual({ + path: "/warmup", + port: 9300, + }); + }); + + test("Container: a hook on the serving port goes through the dev port mapping", () => { + expect(warmupTarget(runtime("Container", { path: "/warmup", port: 8080 }), 9100)).toEqual({ + path: "/warmup", + port: 9100, + }); + }); + + test("Container: a hook on its own port goes through its mapped host port", () => { + expect(warmupTarget(runtime("Container", { path: "/warmup", port: 9300 }), 9100, 9301)).toEqual( + { + path: "/warmup", + port: 9301, + viaContainerMapping: true, + }, + ); + }); + + test("Container: a hook on its own port without a mapped host port is refused with the fix", () => { + expect(() => warmupTarget(runtime("Container", { path: "/warmup", port: 9300 }), 9100)).toThrow( + /port 9300, which agentcore dev can't reach inside a container[\s\S]*serving port \(8080\)/, + ); + }); +}); + +describe("waitForHealthyPing", () => { + test("retries until /ping reports Healthy", async () => { + const { fetchImpl, calls } = scriptedFetch([ + new Error("ECONNREFUSED"), + json({ status: "Starting" }), + new Response("unavailable", { status: 503 }), + json({ status: "Healthy" }), + ]); + await waitForHealthyPing(9100, new AbortController().signal, fetchImpl, 1); + expect(calls.map((call) => [call.url, call.init.method])).toEqual( + Array(4).fill(["http://127.0.0.1:9100/ping", "GET"]), + ); + }); + + test.each(["HealthyBusy", "healthy"])("accepts %s, in any case", async (status) => { + const { fetchImpl } = scriptedFetch([json({ status })]); + await waitForHealthyPing(9100, new AbortController().signal, fetchImpl, 1); + }); + + test("gives up at a fixed deadline, however much the agent logs meanwhile", async () => { + const { fetchImpl } = scriptedFetch([new Response("not found", { status: 404 })]); + await expect( + waitForHealthyPing(9100, new AbortController().signal, fetchImpl, 1, 20), + ).rejects.toThrow("GET /ping on port 9100 did not report Healthy within 0.02s."); + }); +}); + +describe("HookPortReserver", () => { + const free = async () => true; + + test("prefers the hook's own number and skips ports dev already uses", async () => { + const reserver = new HookPortReserver(free, new AbortController().signal, [9300]); + expect(await reserver.reserve(9300)).toBe(9301); + expect(await reserver.reserve(9400)).toBe(9400); + }); + + test("never hands out one port twice, even to agents starting together", async () => { + const reserver = new HookPortReserver(free, new AbortController().signal); + const ports = await Promise.all([reserver.reserve(9300), reserver.reserve(9300)]); + expect(ports.sort()).toEqual([9300, 9301]); + }); +}); + +describe("runWarmupHook", () => { + const target = { path: "/warmup", port: 9100 }; + + test("sends memory then disk as the service does: POST, the type header, no body", async () => { + const { fetchImpl, calls } = scriptedFetch([json({ status: "ok" })]); + const announced: string[] = []; + await runWarmupHook(target, new AbortController().signal, fetchImpl, (type) => + announced.push(type), + ); + expect(announced).toEqual(["memory", "disk"]); + expect(calls.map((call) => call.url)).toEqual([ + "http://127.0.0.1:9100/warmup", + "http://127.0.0.1:9100/warmup", + ]); + for (const [index, type] of ["memory", "disk"].entries()) { + const { init } = calls[index]!; + expect(init.method).toBe("POST"); + expect(init.headers).toEqual({ [WARMUP_TYPE_HEADER]: type }); + expect(init.body).toBeUndefined(); + } + }); + + test("fails on a non-2xx response with the call, status and body", async () => { + const { fetchImpl, calls } = scriptedFetch([ + json({ status: "ok" }), + new Response('{"error": "disk warmup failed"}', { status: 500 }), + ]); + await expect(runWarmupHook(target, new AbortController().signal, fetchImpl)).rejects.toThrow( + 'The warmup disk call (POST /warmup on port 9100) returned 500: {"error": "disk warmup failed"}.', + ); + expect(calls).toHaveLength(2); + }); + + test("hints at the container loopback when a mapped hook refuses the connection", async () => { + const { fetchImpl } = scriptedFetch([new Error("Unable to connect")]); + await expect( + runWarmupHook( + { ...target, viaContainerMapping: true }, + new AbortController().signal, + fetchImpl, + ), + ).rejects.toThrow( + /failed: Unable to connect\. If the hook listens only on the container's loopback/, + ); + }); + + test("fails when the calls outlast the shared budget", async () => { + const hanging: HttpFetch = (_url, init) => + new Promise((_resolve, reject) => + init.signal!.addEventListener("abort", () => reject(init.signal!.reason), { once: true }), + ); + await expect( + runWarmupHook(target, new AbortController().signal, hanging, () => {}, 20), + ).rejects.toThrow( + "The warmup memory call (POST /warmup on port 9100) did not finish within the 0.02s warmup budget.", + ); + }); +}); diff --git a/src/core/dev/readiness.ts b/src/core/dev/readiness.ts new file mode 100644 index 0000000000..b4a40665cd --- /dev/null +++ b/src/core/dev/readiness.ts @@ -0,0 +1,280 @@ +import type { ProjectRuntime } from "../../projectSchemas/runtime"; +import { isContainerBuild } from "../../projectSchemas/constants"; +import type { PortChecker } from "../../io"; +import { DEV_PORTS, findFreePort } from "./port"; + +/** The header AgentCore Runtime sets on build warmup calls; its value is the warmup type. */ +export const WARMUP_TYPE_HEADER = "x-amzn-bedrock-agentcore-runtime-warmup-type"; +/** The `memory` and `disk` calls share this budget on AgentCore Runtime. */ +export const WARMUP_BUDGET_MS = 120_000; +/** The service calls `memory` (before the snapshot), then `disk` (on a restored microVM). */ +export const WARMUP_TYPES = ["memory", "disk"] as const; + +const PING_INTERVAL_MS = 250; +const PING_REQUEST_TIMEOUT_MS = 2_000; +const PING_TIMEOUT_MS = 120_000; +/** Compared case-insensitively: ag_ui_strands' `add_ping` reports `"healthy"`. */ +const HEALTHY_STATUSES = new Set(["healthy", "healthybusy"]); + +export type HttpFetch = (url: string, init: RequestInit) => Promise; + +/** Where dev sends a runtime's build warmup hook. */ +export type WarmupTarget = { + path: string; + port: number; + /** The hook is a container's own port, reached through an extra port mapping. */ + viaContainerMapping?: boolean; +}; + +/** + * The in-container port of a container runtime's build warmup hook when it isn't the serving + * port, so dev has to publish it with its own port mapping. Undefined in every other case. + */ +export function containerHookPort(runtime: ProjectRuntime): number | undefined { + const port = runtime.hooksConfiguration?.build?.warmup?.action.httpPost.port; + if (port === undefined || !isContainerBuild(runtime)) return undefined; + return port === DEV_PORTS[runtime.protocol ?? "HTTP"] ? undefined : port; +} + +/** + * The local address of a runtime's build warmup hook, or undefined when it has none. + * + * A hook on the serving port, which is the default, is reached on the agent's dev port in both + * builds. A CodeZip hook on its own port is a local listener. A container's own-port hook is + * reached through the extra mapping dev publishes for it, on `hookHostPort`. + */ +export function warmupTarget( + runtime: ProjectRuntime, + devPort: number, + hookHostPort?: number, +): WarmupTarget | undefined { + const httpPost = runtime.hooksConfiguration?.build?.warmup?.action.httpPost; + if (!httpPost) return undefined; + const { path, port } = httpPost; + const servingPort = DEV_PORTS[runtime.protocol ?? "HTTP"]; + // The serving port is wherever dev runs the agent, which may not be its configured number. + if (port === undefined || port === servingPort) return { path, port: devPort }; + if (!isContainerBuild(runtime)) return { path, port }; + if (hookHostPort !== undefined) return { path, port: hookHostPort, viaContainerMapping: true }; + throw new Error( + `Runtime '${runtime.name}' serves its warmup hook on port ${port}, which agentcore dev can't ` + + `reach inside a container. Remove "port" from hooksConfiguration.build.warmup.action.httpPost, ` + + `or set it to the serving port (${servingPort}), to run the hook locally.`, + ); +} + +/** + * Poll `GET /ping` until it reports Healthy or HealthyBusy, the signal aborts, or `timeoutMs` + * passes. AgentCore Runtime calls the warmup hook only after this check passes. The deadline is + * fixed: each poll makes the agent log a line, so a deadline based on its output would never pass. + */ +export async function waitForHealthyPing( + port: number, + signal: AbortSignal, + fetchImpl: HttpFetch, + intervalMs = PING_INTERVAL_MS, + timeoutMs = PING_TIMEOUT_MS, +): Promise { + const url = `http://127.0.0.1:${port}/ping`; + const deadline = Date.now() + timeoutMs; + for (;;) { + if (signal.aborted) throw new Error("Aborted while waiting for /ping to report healthy."); + if (Date.now() > deadline) { + throw new Error( + `GET /ping on port ${port} did not report Healthy within ${timeoutMs / 1000}s.`, + ); + } + try { + const response = await fetchImpl(url, { + method: "GET", + signal: AbortSignal.any([signal, AbortSignal.timeout(PING_REQUEST_TIMEOUT_MS)]), + }); + if (response.ok) { + const body = (await response.json().catch(() => undefined)) as + { status?: unknown } | undefined; + if (typeof body?.status === "string" && HEALTHY_STATUSES.has(body.status.toLowerCase())) { + return; + } + } + } catch { + // Not listening yet, or a slow or malformed response: retry until the deadline. + } + await sleep(intervalMs, signal); + } +} + +/** + * Send the build warmup calls the way AgentCore Runtime does: `POST ` with the warmup type + * header, no body and no Content-Type, `memory` then `disk`, within one shared budget. + * Any non-2xx response or a timeout fails, as it fails a V2 create or update. + */ +export async function runWarmupHook( + target: WarmupTarget, + signal: AbortSignal, + fetchImpl: HttpFetch, + onCall: (type: (typeof WARMUP_TYPES)[number]) => void = () => {}, + budgetMs = WARMUP_BUDGET_MS, +): Promise { + const deadline = Date.now() + budgetMs; + const url = `http://127.0.0.1:${target.port}${target.path}`; + for (const type of WARMUP_TYPES) { + const remaining = deadline - Date.now(); + const describe = `warmup ${type} call (POST ${target.path} on port ${target.port})`; + if (remaining <= 0) + throw new Error( + `The ${describe} did not start within the ${budgetMs / 1000}s warmup budget.`, + ); + onCall(type); + const budget = AbortSignal.timeout(remaining); + let response: Response; + try { + response = await fetchImpl(url, { + method: "POST", + headers: { [WARMUP_TYPE_HEADER]: type }, + signal: AbortSignal.any([signal, budget]), + }); + } catch (error) { + if (budget.aborted) { + throw new Error( + `The ${describe} did not finish within the ${budgetMs / 1000}s warmup budget.`, + ); + } + const hint = target.viaContainerMapping + ? " If the hook listens only on the container's loopback (for example the SDK's HookConfig.port)," + + " dev can't reach it: leave the port unset so it's served on the serving port." + : ""; + throw new Error(`The ${describe} failed: ${fetchErrorMessage(error)}${hint}`, { + cause: error, + }); + } + if (!response.ok) { + const detail = (await response.text().catch(() => "")).trim().slice(0, 300); + throw new Error(`The ${describe} returned ${response.status}${detail ? `: ${detail}` : ""}.`); + } + } +} + +/** A runtime's warmup hook as dev runs it: the host port to publish for it, and where to call it. */ +export type WarmupPlan = { hookPort?: number; target?: WarmupTarget }; + +/** + * Resolves where dev calls a runtime's build warmup hook, reserving a host port first when a + * container's hook has its own port. `reserveHookPort` picks a free host port, preferring the + * hook's own number. Throws before the agent starts when the hook can't be reached. + */ +export async function planWarmup( + runtime: ProjectRuntime, + devPort: number, + reserveHookPort: (preferred: number) => Promise, +): Promise { + const ownPort = containerHookPort(runtime); + const hookPort = ownPort === undefined ? undefined : await reserveHookPort(ownPort); + return { hookPort, target: warmupTarget(runtime, devPort, hookPort) }; +} + +/** + * What AgentCore Runtime V2 does before an agent with a build warmup hook is ready: a healthy + * `GET /ping`, then the `memory` and `disk` warmup calls. Call it once the agent's port is open. + */ +export async function runWarmupSequence(options: { + name: string; + devPort: number; + target: WarmupTarget; + signal: AbortSignal; + fetchImpl: HttpFetch; + onStatus: (message: string) => void; +}): Promise { + const { name, devPort, target, signal, fetchImpl, onStatus } = options; + onStatus(`Waiting for '${name}' to report healthy on GET /ping.`); + await waitForHealthyPing(devPort, signal, fetchImpl); + await runWarmupHook(target, signal, fetchImpl, (type) => + onStatus( + `Running the warmup hook for '${name}' (${type}): POST ${target.path} on port ${target.port}.`, + ), + ); + onStatus( + `Warmup hook for '${name}' succeeded. Locally both calls run in one process, so state that ` + + "doesn't survive a V2 snapshot isn't caught here, and a code reload doesn't rerun the hook.", + ); +} + +/** + * Resolves once a started agent is ready the way AgentCore Runtime V2 sees it: its port accepts + * connections and, when it has a build warmup hook, `/ping` is healthy and both warmup calls passed. + * The supervisor and `dev --agent` both start agents through this. + */ +export async function waitUntilReady(options: { + name: string; + devPort: number; + warmup?: WarmupTarget; + waitForPort: () => Promise; + signal: AbortSignal; + fetchImpl: HttpFetch; + onStatus: (message: string) => void; +}): Promise { + const { warmup, waitForPort, ...sequence } = options; + await waitForPort(); + if (warmup) await runWarmupSequence({ ...sequence, target: warmup }); +} + +/** + * Reserves host ports for container warmup hooks among ports already taken by dev, one at a time + * so agents starting together can't claim the same port. Seed it with the dev ports in use. + */ +export class HookPortReserver { + private readonly reserved: Set; + private queue: Promise = Promise.resolve(); + + constructor( + private readonly checkPort: PortChecker, + private readonly signal: AbortSignal, + reserved: Iterable = [], + ) { + this.reserved = new Set(reserved); + } + + /** Marks a port dev already uses, such as an agent's dev port picked later. */ + public add(port: number): void { + this.reserved.add(port); + } + + public isReserved(port: number): boolean { + return this.reserved.has(port); + } + + public reserve(preferred: number): Promise { + const next = this.queue.then(async () => { + const { port } = await findFreePort( + preferred, + undefined, + async (candidate, checkSignal) => + !this.reserved.has(candidate) && this.checkPort(candidate, checkSignal), + this.signal, + ); + this.reserved.add(port); + return port; + }); + this.queue = next.catch(() => {}); + return next; + } +} + +/** A fetch failure's message, without the runtime's "pass verbose: true" advice, ending in a period. */ +function fetchErrorMessage(error: unknown): string { + const message = (error instanceof Error ? error.message : String(error)) + .replace(/\s*For more information, pass `verbose: true`[^.]*\./, "") + .trim(); + return message.endsWith(".") ? message : `${message}.`; +} + +function sleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + const timer = setTimeout(done, ms); + function done() { + clearTimeout(timer); + signal.removeEventListener("abort", done); + resolve(); + } + signal.addEventListener("abort", done, { once: true }); + }); +} diff --git a/src/core/dev/supervisor.test.ts b/src/core/dev/supervisor.test.ts index 4c81d83b1c..86403813d7 100644 --- a/src/core/dev/supervisor.test.ts +++ b/src/core/dev/supervisor.test.ts @@ -84,6 +84,7 @@ type HarnessOptions = { codeZip?: { runner: DevRunner }; container?: { runner: DevRunner }; ready?: (port: number, signal: AbortSignal) => Promise; + fetch?: (url: string, init: RequestInit) => Promise; }; function harness(options: HarnessOptions = {}) { @@ -98,6 +99,11 @@ function harness(options: HarnessOptions = {}) { getDevEnvVarsForRuntime: async (agentRuntime) => ({ AGENT: agentRuntime.name }), resolvePort: async () => nextPort++, waitReady: options.ready ?? (async () => {}), + fetch: + options.fetch ?? + (async (url) => { + throw new Error(`unexpected HTTP call to ${url}`); + }), signal: controller.signal, }); return { supervisor, controller, codeZip, container }; @@ -114,6 +120,91 @@ async function drain( } describe("DevSupervisor", () => { + describe("build warmup hook", () => { + const withHook = (build: ProjectRuntime["build"] = "CodeZip") => + ({ + ...runtime("orders", build), + hooksConfiguration: { build: { warmup: { action: { httpPost: { path: "/warmup" } } } } }, + }) as ProjectRuntime; + const healthy = () => + new Response(JSON.stringify({ status: "Healthy" }), { + headers: { "content-type": "application/json" }, + }); + + test("reports running only after a healthy /ping and both warmup calls", async () => { + const calls: string[] = []; + const { supervisor, controller } = harness({ + runtimes: [withHook()], + fetch: async (url, init) => { + const headers = (init.headers ?? {}) as Record; + calls.push( + `${init.method} ${url} ${headers["x-amzn-bedrock-agentcore-runtime-warmup-type"] ?? ""}`.trim(), + ); + return url.endsWith("/ping") ? healthy() : new Response("{}"); + }, + }); + expect(await supervisor.start("orders")).toEqual({ name: "orders", port: 9100 }); + expect(calls).toEqual([ + "GET http://127.0.0.1:9100/ping", + "POST http://127.0.0.1:9100/warmup memory", + "POST http://127.0.0.1:9100/warmup disk", + ]); + expect(supervisor.snapshot()[0]).toMatchObject({ phase: "running" }); + const statuses = (await drain(supervisor, controller)) + .filter((e) => e.event.type === "status") + .map((e) => (e.event as { message: string }).message); + expect(statuses).toContainEqual( + expect.stringContaining("Warmup hook for 'orders' succeeded"), + ); + }); + + test("a failing warmup hook fails the start like a V2 deploy would", async () => { + const { supervisor, controller } = harness({ + runtimes: [withHook()], + fetch: async (url) => + url.endsWith("/ping") ? healthy() : new Response("boom", { status: 500 }), + }); + await expect(supervisor.start("orders")).rejects.toThrow( + "The warmup memory call (POST /warmup on port 9100) returned 500: boom.", + ); + expect(supervisor.snapshot()[0]).toMatchObject({ phase: "failed" }); + controller.abort(); + }); + + test("a container hook on its own port is called through its mapped host port", async () => { + const container = serverRunner(); + const calls: string[] = []; + const runtimeWithPort = { + ...withHook("Container"), + hooksConfiguration: { + build: { warmup: { action: { httpPost: { path: "/warmup", port: 9300 } } } }, + }, + } as ProjectRuntime; + const { supervisor, controller } = harness({ + runtimes: [runtimeWithPort], + container, + fetch: async (url, init) => { + calls.push(`${init.method} ${url}`); + return url.endsWith("/ping") ? healthy() : new Response("{}"); + }, + }); + await supervisor.start("orders"); + expect(container.inputs[0]).toMatchObject({ port: 9100, hookPort: 9300 }); + expect(calls).toEqual([ + "GET http://127.0.0.1:9100/ping", + "POST http://127.0.0.1:9300/warmup", + "POST http://127.0.0.1:9300/warmup", + ]); + controller.abort(); + }); + + test("an agent without a warmup hook makes no HTTP calls", async () => { + const { supervisor, controller } = harness({ runtimes: [runtime("orders")] }); + expect(await supervisor.start("orders")).toEqual({ name: "orders", port: 9100 }); + controller.abort(); + }); + }); + test("agents are idle until started, then report running with their port", async () => { const { supervisor, controller } = harness(); expect(supervisor.snapshot()).toMatchObject([ diff --git a/src/core/dev/supervisor.ts b/src/core/dev/supervisor.ts index eddb58fc85..8578458a67 100644 --- a/src/core/dev/supervisor.ts +++ b/src/core/dev/supervisor.ts @@ -3,6 +3,7 @@ import { waitForPort } from "../../io"; import type { DevEvent, DevRunner } from "../../handlers/project/dev/types"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; import { isContainerBuild } from "../../projectSchemas/constants"; +import { type HttpFetch, planWarmup, waitUntilReady } from "./readiness"; export type AgentPhase = "idle" | "starting" | "running" | "failed"; @@ -29,12 +30,19 @@ export type SupervisorConfig = { getDevEnvVarsForRuntime: (runtime: ProjectRuntime) => Promise>; /** Resolves the port a runtime should serve on. */ resolvePort: (runtime: ProjectRuntime) => Promise; + /** + * Reserves a free host port for a container warmup hook on its own port, preferring the hook's + * own number, so it can't collide with a dev port or another agent's hook. Defaults to that number. + */ + reserveHookPort?: (runtime: ProjectRuntime, hookPort: number) => Promise; /** * Resolves once a started agent accepts connections on its port. `lastActivityAt` * returns the time of the agent's most recent output, so a build that keeps * logging is not timed out mid-flight. */ waitReady?: (port: number, signal: AbortSignal, lastActivityAt: () => number) => Promise; + /** HTTP client for the `/ping` check and warmup hook calls; defaults to the global fetch. */ + fetch?: HttpFetch; signal: AbortSignal; }; @@ -195,17 +203,36 @@ export class DevSupervisor { try { const port = await this.config.resolvePort(entry.runtime); + // Resolved before the agent starts, so an unreachable hook fails without launching it. + const reserveHookPort = + this.config.reserveHookPort ?? (async (_runtime, preferred) => preferred); + const { hookPort, target: warmup } = await planWarmup(entry.runtime, port, (preferred) => + reserveHookPort(entry.runtime, preferred), + ); const env = await this.config.getDevEnvVarsForRuntime(entry.runtime); const runner = this.config.runners[isContainerBuild(entry.runtime) ? "Container" : "CodeZip"]; let ready = false; const activity = { at: Date.now() }; - const readiness = this.waitReady(port, controller.signal, () => activity.at).then(() => { + const readiness = waitUntilReady({ + name, + devPort: port, + warmup, + waitForPort: () => this.waitReady(port, controller.signal, () => activity.at), + signal: controller.signal, + fetchImpl: this.config.fetch ?? fetch, + onStatus: (message) => this.push(name, { type: "status", message }), + }).then(() => { ready = true; }); - const pump = this.pump(entry, runner, { port, env, signal: controller.signal }, () => { - activity.at = Date.now(); - }); + const pump = this.pump( + entry, + runner, + { port, hookPort, env, signal: controller.signal }, + () => { + activity.at = Date.now(); + }, + ); entry.running = pump; const earlyExit = pump.finally(unchain).then(() => { if (!ready) @@ -238,7 +265,7 @@ export class DevSupervisor { private async pump( entry: AgentEntry, runner: DevRunner, - input: { port: number; env: Record; signal: AbortSignal }, + input: { port: number; hookPort?: number; env: Record; signal: AbortSignal }, onActivity: () => void, ): Promise { const name = entry.runtime.name; @@ -247,6 +274,7 @@ export class DevSupervisor { runtime: entry.runtime, projectRoot: this.config.projectRoot, port: input.port, + ...(input.hookPort !== undefined && { hookPort: input.hookPort }), env: input.env, signal: input.signal, })) { diff --git a/src/core/project/templates/bedrockManagedAgents.test.ts b/src/core/project/templates/bedrockManagedAgents.test.ts index 2f23d42c0f..050c35c8d3 100644 --- a/src/core/project/templates/bedrockManagedAgents.test.ts +++ b/src/core/project/templates/bedrockManagedAgents.test.ts @@ -49,8 +49,13 @@ test("Bedrock Managed Agents assets preserve the environment and lifecycle contr expect(dockerfile).toContain("https://chatgpt.com/codex/install.sh"); expect(dockerfile).toContain("amazon-cloudwatch-agent.rpm"); expect(dockerfile).toContain("COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/"); - // Python is installed before pyproject.toml is copied, so requires-python sets a minimum and does not pin the image. - expect(dockerfile).toMatch(/RUN uv python install --default\n[\s\S]*COPY pyproject\.toml/); + // AL2023's Python links the base image's snapshot-safe OpenSSL, and uv must use it rather than + // download a standalone Python that bundles its own OpenSSL. + expect(dockerfile).toMatch(/RUN dnf install -y [^\n]*python3\.14/); + expect(dockerfile).toContain( + "ENV UV_PYTHON=python3.14 UV_PYTHON_PREFERENCE=only-system UV_PYTHON_DOWNLOADS=never", + ); + expect(dockerfile).not.toContain("uv python install"); expect(dockerfile).toContain("RUN uv sync --no-dev"); expect(dockerfile).toContain("COPY lifecycle/ lifecycle/"); expect(dockerfile).toContain("COPY otel/ otel/"); diff --git a/src/core/project/templates/pythonSecurity.test.ts b/src/core/project/templates/pythonSecurity.test.ts index 5309a371be..aa9a3867d3 100644 --- a/src/core/project/templates/pythonSecurity.test.ts +++ b/src/core/project/templates/pythonSecurity.test.ts @@ -35,19 +35,19 @@ test.each([ }); }); -test("the Strands container updates OS packages and removes uv after installing dependencies", async () => { +test("the Strands container updates OS packages, uses snapshot-safe OpenSSL and removes uv after installing dependencies", async () => { const dockerfile = renderer.render( await source.read("templates/agent-python-strands/Dockerfile.template"), { entrypoint: "main" }, ); expect(dockerfile).toMatch( - /RUN apt-get update && apt-get upgrade -y[\s\S]*USER bedrock_agentcore/, + /RUN dnf upgrade -y[\s\S]*dnf swap -y openssl-libs openssl-snapsafe-libs[\s\S]*USER bedrock_agentcore/, ); expect(dockerfile).toMatch( /UV_NO_CACHE=1[\s\S]*RUN uv sync --frozen --no-dev --no-install-project/, ); expect(dockerfile).toMatch( - /RUN uv sync --frozen --no-dev && \/usr\/local\/bin\/python -m pip uninstall -y uv[\s\S]*USER bedrock_agentcore/, + /RUN uv sync --frozen --no-dev && \/usr\/bin\/python3\.12 -m pip uninstall -y uv[\s\S]*USER bedrock_agentcore/, ); }); diff --git a/src/core/project/templates/runtime.test.ts b/src/core/project/templates/runtime.test.ts index cd39f5da91..e40367c48d 100644 --- a/src/core/project/templates/runtime.test.ts +++ b/src/core/project/templates/runtime.test.ts @@ -213,6 +213,21 @@ describe("runtime templates", () => { expect(loadModel).toContain('"base_url": "https://api.deepseek.com/v1"'); }); + test.each<[ModelProvider, string, string]>([ + ["Bedrock", "agui_agent = _build_agui_agent()", "_LazyAguiAgent"], + ["Anthropic", "agui_agent = _LazyAguiAgent()", "agui_agent = _build_agui_agent()"], + ])( + "agui-python-strands with %s builds the agent at the right time for a V2 snapshot", + async (modelProvider, expected, unexpected) => { + const { appDir } = await addTemplate("my_agent", "agui-python-strands", { + model: { modelProvider, ...(modelProvider !== "Bedrock" && { apiKey: "test-api-key" }) }, + }); + const main = await Bun.file(join(appDir, "main.py")).text(); + expect(main).toContain(expected); + expect(main).not.toContain(unexpected); + }, + ); + test("an API base is refused with a provider other than OpenAICompatible", () => { expect(() => resolveRuntimeTemplateShortcut("agent-python-strands", { diff --git a/src/core/project/templates/runtime.ts b/src/core/project/templates/runtime.ts index e69740ba12..ee77d785de 100644 --- a/src/core/project/templates/runtime.ts +++ b/src/core/project/templates/runtime.ts @@ -128,6 +128,8 @@ function buildRuntimeSpec(input: RuntimeResourceConfig): ProjectRuntime { ...(infra.protocol && { protocol: infra.protocol }), ...(infra.requestHeaderAllowlist && { requestHeaderAllowlist: infra.requestHeaderAllowlist }), ...(lifecycleConfiguration && { lifecycleConfiguration }), + ...(infra.resourceConfigurations && { resourceConfigurations: infra.resourceConfigurations }), + ...(infra.hooksConfiguration && { hooksConfiguration: infra.hooksConfiguration }), ...(infra.filesystemConfigurations && { filesystemConfigurations: infra.filesystemConfigurations, }), diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index 3922ec5dc5..e0b07d8edc 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -163,6 +163,8 @@ export function buildDocsRuntimeSpec(input: RuntimeDocsConfig): ProjectRuntime { }), ...(infra.requestHeaderAllowlist && { requestHeaderAllowlist: infra.requestHeaderAllowlist }), ...(infra.lifecycleConfiguration && { lifecycleConfiguration: infra.lifecycleConfiguration }), + ...(infra.resourceConfigurations && { resourceConfigurations: infra.resourceConfigurations }), + ...(infra.hooksConfiguration && { hooksConfiguration: infra.hooksConfiguration }), ...(infra.filesystemConfigurations && { filesystemConfigurations: infra.filesystemConfigurations, }), diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index 98cc398453..d16994e601 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -337,6 +337,10 @@ describe("project add runtime", () => { "X-Custom-Header", "--lifecycle-configuration", '{"idleRuntimeSessionTimeout":300,"maxLifetime":3600}', + "--resource-configurations", + '[{"minimumMemoryInMiB":4096}]', + "--hooks-configuration", + '{"build":{"warmup":{"action":{"httpPost":{"path":"/warmup","port":8080}}}}}', "--environment-variables", '{"LOG_LEVEL":"debug","APP_ENV":"staging"}', "--filesystem-configurations", @@ -470,6 +474,10 @@ describe("project add runtime", () => { }, requestHeaderAllowlist: ["X-Custom-Header"], lifecycleConfiguration: { idleRuntimeSessionTimeout: 300, maxLifetime: 3600 }, + resourceConfigurations: [{ minimumMemoryInMiB: 4096 }], + hooksConfiguration: { + build: { warmup: { action: { httpPost: { path: "/warmup", port: 8080 } } } }, + }, envVars: [ { name: "LOG_LEVEL", value: "debug" }, { name: "APP_ENV", value: "staging" }, @@ -557,6 +565,18 @@ describe("project add runtime", () => { "invalid JSON in --network-config", ["--name", "my_agent", "--language", "python", "--network-config", "{bad}"], ], + [ + "an empty hook path in --hooks-configuration", + [ + "--name", + "my_agent", + "--language", + "python", + "--hooks-configuration", + '{"build":{"warmup":{"action":{"httpPost":{"path":""}}}}}', + ], + "path", + ], ])("%s", async (...[_label, flags, requiredMessage]) => { const { cleanup } = await initProject(); cleanups.push(cleanup); diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index 98d5a43924..06a9504403 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -39,6 +39,8 @@ type JsonRuntimeField = | "networkConfig" | "authorizerConfiguration" | "lifecycleConfiguration" + | "resourceConfigurations" + | "hooksConfiguration" | "filesystemConfigurations"; type WithJsonFields = Omit & Partial>; @@ -137,6 +139,18 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => z.string().optional(), { group: ENVIRONMENT }, ), + flag( + "resource-configurations", + 'committed per-session memory baseline, e.g. [{"minimumMemoryInMiB":4096}] (JSON, V2 only)', + z.string().optional(), + { group: ENVIRONMENT }, + ), + flag( + "hooks-configuration", + "lifecycle hooks, e.g. a build warmup hook (JSON, V2 only)", + z.string().optional(), + { group: ENVIRONMENT }, + ), flag( "filesystem-configurations", "filesystem mount configurations (JSON)", @@ -288,6 +302,11 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => "lifecycle-configuration", flags["lifecycle-configuration"], ), + resourceConfigurations: parseJsonFlag( + "resource-configurations", + flags["resource-configurations"], + ), + hooksConfiguration: parseJsonFlag("hooks-configuration", flags["hooks-configuration"]), filesystemConfigurations: parseJsonFlag( "filesystem-configurations", flags["filesystem-configurations"], diff --git a/src/handlers/project/add/runtime/types.ts b/src/handlers/project/add/runtime/types.ts index f2c2dc8032..f187a6dae7 100644 --- a/src/handlers/project/add/runtime/types.ts +++ b/src/handlers/project/add/runtime/types.ts @@ -20,6 +20,8 @@ const RuntimeInfraConfigSchema = z.object({ protocol: ProjectRuntimeSchema.shape.protocol, requestHeaderAllowlist: ProjectRuntimeSchema.shape.requestHeaderAllowlist, lifecycleConfiguration: ProjectRuntimeSchema.shape.lifecycleConfiguration, + resourceConfigurations: ProjectRuntimeSchema.shape.resourceConfigurations, + hooksConfiguration: ProjectRuntimeSchema.shape.hooksConfiguration, filesystemConfigurations: ProjectRuntimeSchema.shape.filesystemConfigurations, tags: ProjectRuntimeSchema.shape.tags, build: ProjectRuntimeSchema.shape.build.optional(), diff --git a/src/handlers/project/dev/index.test.ts b/src/handlers/project/dev/index.test.ts index ba6242e84b..fe8e30bef1 100644 --- a/src/handlers/project/dev/index.test.ts +++ b/src/handlers/project/dev/index.test.ts @@ -132,6 +132,7 @@ type HarnessOptions = { * since most projects here are in-memory; `"real"` uses the project manager's. */ syncRuntimeBuilds?: "real" | ProjectManager["syncRuntimeBuilds"]; + fetch?: DevProjectHandlerConfig["fetch"]; }; function harness(options: HarnessOptions = {}) { @@ -216,6 +217,11 @@ function harness(options: HarnessOptions = {}) { waitReady: async () => { await Bun.sleep(5); }, + fetch: + options.fetch ?? + (async (url) => { + throw new Error(`unexpected HTTP call to ${url}`); + }), }); const ctx = ValueContext.EmptyContext() .withValue(GlobalConfigAccessorKey, new TestGlobalConfigAccessor()) @@ -458,6 +464,72 @@ describe("project dev selection and dispatch", () => { }); }); +describe("project dev build warmup hook", () => { + const withHook = (): ProjectRuntime => ({ + ...runtime("orders"), + hooksConfiguration: { build: { warmup: { action: { httpPost: { path: "/warmup" } } } } }, + }); + const healthy = () => + new Response(JSON.stringify({ status: "Healthy" }), { + headers: { "content-type": "application/json" }, + }); + /** A runner that serves briefly and then exits, so a successful run of `dev --agent` returns. */ + const briefRunner = () => { + const inputs: DevServerInput[] = []; + const runner: DevRunner = { + run: async function* (input) { + inputs.push(input); + yield { type: "stdout", line: "serving" }; + await Bun.sleep(100); + }, + }; + return { runner, inputs }; + }; + + test("dev --agent waits for /ping, then sends memory and disk warmup calls", async () => { + const calls: string[] = []; + const subject = harness({ + project: project(withHook()), + codeZip: briefRunner(), + fetch: async (url, init) => { + const type = (init.headers as Record | undefined)?.[ + "x-amzn-bedrock-agentcore-runtime-warmup-type" + ]; + calls.push(`${init.method} ${url}${type ? ` ${type}` : ""}`); + return url.endsWith("/ping") ? healthy() : new Response("{}"); + }, + }); + await subject.run({ agent: "orders" }); + + expect(calls).toEqual([ + "GET http://127.0.0.1:8080/ping", + "POST http://127.0.0.1:8080/warmup memory", + "POST http://127.0.0.1:8080/warmup disk", + ]); + expect(subject.io.stderr()).toContain("Warmup hook for 'orders' succeeded"); + }); + + test("dev --agent stops the agent and fails when the warmup hook fails", async () => { + const codeZip = stayingRunner([{ type: "stdout", line: "serving" }]); + const subject = harness({ + project: project(withHook()), + codeZip, + fetch: async (url) => + url.endsWith("/ping") ? healthy() : new Response("not ready", { status: 503 }), + }); + await expect(subject.run({ agent: "orders" })).rejects.toThrow( + "Agent 'orders' failed to start: The warmup memory call (POST /warmup on port 8080) returned 503: not ready.", + ); + expect(codeZip.inputs[0]?.signal.aborted).toBe(true); + }); + + test("dev --agent without a warmup hook makes no HTTP calls", async () => { + const subject = harness({ codeZip: briefRunner() }); + await subject.run({ agent: "orders" }); + expect(subject.io.stderr()).not.toContain("GET /ping"); + }); +}); + describe("project dev headless multi-agent", () => { const twoRuntimes = () => project(runtime("orders"), runtime("support", "Container")); diff --git a/src/handlers/project/dev/index.ts b/src/handlers/project/dev/index.ts index a21cfa09e1..beffccd4a5 100644 --- a/src/handlers/project/dev/index.ts +++ b/src/handlers/project/dev/index.ts @@ -7,6 +7,12 @@ import { findFreePort, resolveDevPort, resolveDevPorts } from "../../../core/dev import { projectSpecPath } from "../../../core/project/fsUtils"; import type { V0DeployRunner } from "../../../core/project/legacy/deploy"; import { DevSupervisor, type SupervisorConfig } from "../../../core/dev/supervisor"; +import { + HookPortReserver, + type HttpFetch, + planWarmup, + waitUntilReady, +} from "../../../core/dev/readiness"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; import { AgentCoreCLIError, @@ -19,6 +25,7 @@ import { SilentCLIError, } from "../../../errors"; import type { AppIO, BrowserOpener, FileWatcher, PortChecker, startHttpServer } from "../../../io"; +import { waitForPort } from "../../../io"; import { createHandler, flag, ProjectKey, type Context, type Middleware } from "../../../router"; import { withUserCancellation } from "../../../runnable"; import { JsonRendererKey, type JsonRenderer } from "../../../tui"; @@ -57,6 +64,8 @@ export type DevProjectHandlerConfig = { harness: Pick; /** Overrides how the supervisor decides an agent is ready (defaults to a real TCP poll). */ waitReady?: SupervisorConfig["waitReady"]; + /** HTTP client for the `/ping` check and warmup hook calls; defaults to the global fetch. */ + fetch?: HttpFetch; /** Runs the final v0 deployer when harness dev is opened from a v0 project. */ runV0Deploy?: V0DeployRunner; }; @@ -431,6 +440,9 @@ async function runRuntimeDev({ input.mode === "headless" ? await resolveDevPorts(runtimes, input.port, config.checkPort, signal) : undefined; + // Container warmup hooks on their own port get host ports that can't collide with a dev + // port or each other, including agents the Inspector starts later. + const hookPorts = new HookPortReserver(config.checkPort, signal, assignedPorts?.values()); const supervisor = new DevSupervisor({ runtimes, projectRoot: project.rootPath, @@ -446,10 +458,19 @@ async function runRuntimeDev({ } return assignedPort; } - return (await resolveDevPort(runtime.protocol, input.port, config.checkPort, signal)) - .port; + const { port } = await resolveDevPort( + runtime.protocol, + input.port, + async (candidate, checkSignal) => + !hookPorts.isReserved(candidate) && config.checkPort(candidate, checkSignal), + signal, + ); + hookPorts.add(port); + return port; }, + reserveHookPort: (_runtime, hookPort) => hookPorts.reserve(hookPort), waitReady: config.waitReady, + fetch: config.fetch, signal, }); @@ -622,17 +643,58 @@ async function runWithoutUi({ }); } + // Resolved before the agent starts, so an unreachable hook fails without launching it. + const { hookPort, target: warmup } = await planWarmup(runtime, devPort.port, (preferred) => + new HookPortReserver(config.checkPort, signal, [devPort.port]).reserve(preferred), + ); const env = await options.environment(runtime); signal.throwIfAborted(); + // A failed warmup stops the agent and fails the command, the way it fails a V2 deploy. + const controller = new AbortController(); + const onParentAbort = () => controller.abort(signal.reason); + signal.addEventListener("abort", onParentAbort, { once: true }); + let lastActivityAt = Date.now(); + let warmupError: Error | undefined; + if (warmup) { + void waitUntilReady({ + name: runtime.name, + devPort: devPort.port, + warmup, + waitForPort: () => + (config.waitReady ?? waitForPort)(devPort.port, controller.signal, () => lastActivityAt), + signal: controller.signal, + fetchImpl: config.fetch ?? fetch, + onStatus: (message) => renderStatus({ io: config.io, message, json }), + }).catch((error: unknown) => { + if (controller.signal.aborted) return; + warmupError = error instanceof Error ? error : new Error(String(error)); + controller.abort(warmupError); + }); + } + const runner = config.runners[isContainerBuild(runtime) ? "Container" : "CodeZip"]; - for await (const event of runner.run({ - runtime, - projectRoot: project.rootPath, - port: devPort.port, - env, - signal, - })) { - renderAgentEvent({ io: config.io, event, agent: runtime.name, json }); + try { + for await (const event of runner.run({ + runtime, + projectRoot: project.rootPath, + port: devPort.port, + ...(hookPort !== undefined && { hookPort }), + env, + signal: controller.signal, + })) { + lastActivityAt = Date.now(); + renderAgentEvent({ io: config.io, event, agent: runtime.name, json }); + } + } catch (error) { + if (warmupError) + throw new AgentCoreCLIError( + `Agent '${runtime.name}' failed to start: ${warmupError.message}`, + ); + throw error; + } finally { + signal.removeEventListener("abort", onParentAbort); } + if (warmupError) + throw new AgentCoreCLIError(`Agent '${runtime.name}' failed to start: ${warmupError.message}`); } diff --git a/src/handlers/project/dev/types.ts b/src/handlers/project/dev/types.ts index 98175248d7..319215dcf8 100644 --- a/src/handlers/project/dev/types.ts +++ b/src/handlers/project/dev/types.ts @@ -10,6 +10,8 @@ export type DevServerInput = { runtime: ProjectRuntime; projectRoot: string; port: number; + /** Host port mapped to a container's warmup hook when the hook has its own port. */ + hookPort?: number; env?: Record; signal: AbortSignal; }; diff --git a/src/handlers/runtime/get/screen.tsx b/src/handlers/runtime/get/screen.tsx index 9206c5ea75..b46cb0fa91 100644 --- a/src/handlers/runtime/get/screen.tsx +++ b/src/handlers/runtime/get/screen.tsx @@ -1,3 +1,7 @@ +import type { + ResourceConfiguration, + RuntimeHooksConfiguration, +} from "@aws-sdk/client-bedrock-agentcore-control"; import { useQuery } from "@tanstack/react-query"; import { useNavigate, useParams } from "react-router"; import { JsonDetail } from "../../../components/JsonDetail"; @@ -68,6 +72,8 @@ export function RuntimeGetScreen(props: ScreenProps) { protocol: detail.data?.protocolConfiguration?.serverProtocol ?? "-", network: detail.data?.networkConfiguration?.networkMode ?? "-", platform: detail.data?.platformVersion ?? "-", + memory: memoryBaseline(detail.data?.resourceConfigurations), + hooks: hookSummary(detail.data?.hooksConfiguration), arn: detail.data?.agentRuntimeArn ?? "", }} actions={ @@ -106,3 +112,16 @@ export function RuntimeGetJsonScreen(props: ScreenProps) { /> ); } + +/** The committed per-session memory baseline, or "-" when the runtime has none. */ +function memoryBaseline(configurations: ResourceConfiguration[] | undefined): string { + const memory = configurations?.[0]?.minimumMemoryInMiB; + return memory === undefined ? "-" : `${memory} MiB`; +} + +/** The configured lifecycle hooks, e.g. "build.warmup POST /warmup:8080", or "-". */ +function hookSummary(hooks: RuntimeHooksConfiguration | undefined): string { + const httpPost = hooks?.build?.warmup?.action?.httpPost; + if (!httpPost?.path) return "-"; + return `build.warmup POST ${httpPost.path}${httpPost.port === undefined ? "" : `:${httpPost.port}`}`; +} diff --git a/src/handlers/runtime/runtime.screen.test.tsx b/src/handlers/runtime/runtime.screen.test.tsx index 49d5d4bfa6..de09ea4b1f 100644 --- a/src/handlers/runtime/runtime.screen.test.tsx +++ b/src/handlers/runtime/runtime.screen.test.tsx @@ -165,7 +165,14 @@ describe("runtime picker", () => { describe("runtime hub", () => { test("fetches the route ID with exact Core options and renders its summary", async () => { const core = new TestCoreClient(); - core.runtime.setGetResponse(getRuntimeResponse()); + core.runtime.setGetResponse( + getRuntimeResponse({ + resourceConfigurations: [{ minimumMemoryInMiB: 4096 }], + hooksConfiguration: { + build: { warmup: { action: { httpPost: { path: "/warmup", port: 8080 } } } }, + }, + }), + ); const r = renderScreen("/agentcore/runtime/get/runtime-123", { core, endpointUrl: runtimeEndpointUrl, @@ -178,6 +185,8 @@ describe("runtime hub", () => { expect(r.lastFrame()).toMatch(/protocol\s+HTTP/); expect(r.lastFrame()).toMatch(/network\s+PUBLIC/); expect(r.lastFrame()).toMatch(/platform\s+V2/); + expect(r.lastFrame()).toMatch(/memory\s+4096 MiB/); + expect(r.lastFrame()).toMatch(/hooks\s+build\.warmup POST \/warmup:8080/); expect(r.lastFrame()).not.toContain("failureReason"); await waitFor(() => core.runtime.calls.some((call) => call.method === "getRuntime")); expect(core.runtime.calls.find((call) => call.method === "getRuntime")).toEqual({ diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index f5a4c3dfff..cbff61a135 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -51,6 +51,29 @@ describe("runtime custom validation", () => { }).success, ).toBe(false); }); + it("keeps V2 resource and hook fields it does not model, and rejects invalid ones", () => { + const warmup = { action: { httpPost: { path: "/warmup", port: 8080 } } }; + expect( + ProjectRuntimeSchema.safeParse({ + ...codeZipAgent, + resourceConfigurations: [{ minimumMemoryInMiB: 4096 }], + hooksConfiguration: { build: { warmup } }, + }).success, + ).toBe(true); + const unmodeled = { + build: { warmup: { action: { httpPost: { path: "/w", timeoutSeconds: 30 } } } }, + }; + expect( + ProjectRuntimeSchema.parse({ ...codeZipAgent, hooksConfiguration: unmodeled }) + .hooksConfiguration, + ).toEqual(unmodeled); + for (const fields of [ + { hooksConfiguration: { build: { warmup: { action: { httpPost: { path: "" } } } } } }, + { resourceConfigurations: [{ minimumMemoryInMiB: 0 }] }, + ]) { + expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, ...fields }).success).toBe(false); + } + }); it("accepts only the V1 and V2 platform versions", () => { for (const platformVersion of ["V1", "V2"]) { expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, platformVersion }).success).toBe( diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index 49f3da0f11..a3123b8da1 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -223,6 +223,28 @@ export const LifecycleConfigurationSchema = z } }); export type LifecycleConfiguration = z.infer; + +// Shape only, and loose: the service validates sizes, paths, ports and the V2 requirement, and +// fields it adds later pass through to it without a CLI release. +export const ResourceConfigurationSchema = z.looseObject({ + minimumMemoryInMiB: z.number().int().positive(), +}); +export type ResourceConfiguration = z.infer; + +export const LifecycleHookSchema = z.looseObject({ + action: z.looseObject({ + httpPost: z.looseObject({ + path: z.string().min(1), + port: z.number().int().optional(), + }), + }), +}); +export type LifecycleHook = z.infer; + +export const RuntimeHooksConfigurationSchema = z.looseObject({ + build: z.looseObject({ warmup: LifecycleHookSchema.optional() }).optional(), +}); +export type RuntimeHooksConfiguration = z.infer; export const RuntimeEndpointNameSchema = z .string() .min(1, "Endpoint name is required") @@ -328,6 +350,10 @@ export const ProjectRuntimeSchema = z authorizerConfiguration: AuthorizerConfigSchema.optional(), tags: TagsSchema.optional(), lifecycleConfiguration: LifecycleConfigurationSchema.optional(), + /** Each update replaces this, so removing it returns sessions to consumption-based pricing. */ + resourceConfigurations: z.array(ResourceConfigurationSchema).optional(), + /** Each update replaces this, so removing it removes the hooks. */ + hooksConfiguration: RuntimeHooksConfigurationSchema.optional(), filesystemConfigurations: z.array(FilesystemConfigurationSchema).optional(), endpoints: z.record(RuntimeEndpointNameSchema, RuntimeEndpointSchema).optional(), connections: z.array(ConnectionSchema).optional(), From ae14bb540cfeb05ae93f17ae61affa5016047102 Mon Sep 17 00:00:00 2001 From: sasha177 <32937070+sasha177@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:58:19 -0800 Subject: [PATCH 07/19] fix(runtime): leave s3BucketMount V2 rule to the service (#2915) Co-authored-by: Sasha Mittal --- src/projectSchemas/runtime.test.ts | 78 ++++++++++++++++++++++++++++++ src/projectSchemas/runtime.ts | 11 ----- 2 files changed, 78 insertions(+), 11 deletions(-) diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index cbff61a135..90a0343e3f 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -204,3 +204,81 @@ describe("runtime custom validation", () => { expect(ProjectRuntimeSchema.safeParse(containerAgent).success).toBe(true); }); }); + +describe("s3BucketMount validation", () => { + const v2Agent = { ...codeZipAgent, platformVersion: "V2" as const }; + const withMount = (s3BucketMount: Record, agent: object = v2Agent) => + ProjectRuntimeSchema.safeParse({ + ...agent, + filesystemConfigurations: [ + { + s3BucketMount: { + bucket: "amzn-s3-demo-bucket", + mountPath: "/mnt/bucket", + ...s3BucketMount, + }, + }, + ], + }); + const messages = (result: ReturnType) => + result.error?.issues.map((issue) => issue.message) ?? []; + + it("accepts a whole-bucket mount in PUBLIC and VPC network mode on V2", () => { + expect(withMount({}, { ...v2Agent, networkMode: "PUBLIC" }).success).toBe(true); + expect(withMount({}, { ...v2Agent, networkMode: "VPC", networkConfig }).success).toBe(true); + }); + it("rejects a misspelled field instead of dropping it", () => { + const result = withMount({ s3BucketOwnr: "123456789012" }); + expect(result.success).toBe(false); + }); + it("accepts every optional field", () => { + expect( + withMount({ + prefix: "data/{runtimeSessionId}/", + s3BucketOwner: "123456789012", + s3BucketRegion: "us-east-1", + }).success, + ).toBe(true); + }); + it("leaves the platformVersion V2 rule to the service", () => { + for (const agent of [codeZipAgent, { ...codeZipAgent, platformVersion: "V1" }]) { + expect(withMount({}, agent).success).toBe(true); + } + }); + it("counts toward the five-mount limit with no cap of its own", () => { + const mounts = (count: number) => + Array.from({ length: count }, (_, index) => ({ + s3BucketMount: { bucket: "amzn-s3-demo-bucket", mountPath: `/mnt/bucket${index}` }, + })); + expect( + ProjectRuntimeSchema.safeParse({ ...v2Agent, filesystemConfigurations: mounts(5) }).success, + ).toBe(true); + expect( + ProjectRuntimeSchema.safeParse({ ...v2Agent, filesystemConfigurations: mounts(6) }).success, + ).toBe(false); + }); + it("rejects a mount path another mount type already uses", () => { + const result = ProjectRuntimeSchema.safeParse({ + ...v2Agent, + filesystemConfigurations: [ + { sessionStorage: { mountPath: "/mnt/data" } }, + { s3BucketMount: { bucket: "amzn-s3-demo-bucket", mountPath: "/mnt/data/" } }, + ], + }); + expect(messages(result)).toContain("Filesystem mount paths must be unique"); + }); + it("checks only the bucket and prefix length, leaving their rules to the CDK app", () => { + for (const bucket of ["my.bucket-1", "my-bucket--usw2-az1--x-s3", "my-mrap.mrap"]) { + expect(withMount({ bucket }).success).toBe(true); + } + expect(withMount({ bucket: "ab" }).success).toBe(false); + expect(withMount({ bucket: "a".repeat(64) }).success).toBe(false); + expect(withMount({ prefix: "data/{runtimeSessionId}/" }).success).toBe(true); + expect(withMount({ prefix: "" }).success).toBe(false); + expect(withMount({ prefix: "a".repeat(1025) }).success).toBe(false); + }); + it("checks the bucket owner and Region formats", () => { + expect(withMount({ s3BucketOwner: "12345678901" }).success).toBe(false); + expect(withMount({ s3BucketRegion: "uswest2" }).success).toBe(false); + }); +}); diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index ff042e35ca..dd24811907 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -519,17 +519,6 @@ export const ProjectRuntimeSchema = z path: ["filesystemConfigurations"], }); } - // The service mounts only on V2. Its default when the field is unset depends on partition and - // account rollout, and an update without the field keeps the current version; the CLI sees - // neither, so it requires V2 explicitly. - if (fcs.some((fc) => "s3BucketMount" in fc) && data.platformVersion !== "V2") { - ctx.addIssue({ - code: "custom", - message: - "s3BucketMount filesystem mounts require platformVersion: V2 (--platform-version V2)", - path: ["platformVersion"], - }); - } const mountPaths = fcs.map((fc) => ("sessionStorage" in fc ? fc.sessionStorage.mountPath From 072852923fc03c26649c423a71e236aac0676dc5 Mon Sep 17 00:00:00 2001 From: Vignesh Somasundaram <76790050+vigneshsundar1997@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:14:51 -0800 Subject: [PATCH 08/19] fix(runtime): bug bash fixes for V2 warmup hooks in dev, add runtime, and templates (#2918) - dev: for MCP, any GET /ping response but 502 or 429 counts as ready, as on AgentCore Runtime; a hook path without a leading "/" fails with a clear message; a Python CodeZip hook on its own port warns and names the cause; headless dev refuses CodeZip agents whose hooks share an own port. - add runtime and dev warn when hooksConfiguration has no camelCase build.warmup.action.httpPost.path. The schema stays loose. - --platform-version help and the runtime READMEs no longer name V1 as the service default. - Runtime READMEs and AGENTS.md explain how each protocol serves the warmup hook and that the SDK version must support it. - BMA template: POST /warmup keeps the Codex and CloudWatch agent binaries in memory in the V2 snapshot and warms their start-up files; the README shows how to enable it. BMA's profile is unchanged. Co-authored-by: Vignesh Somasundaram --- .../bedrock-managed-agents/README.md | 18 +++ .../lifecycle/server.py | 48 ++++++- .../templates/runtime-docs/python/AGENTS.md | 5 + .../templates/runtime-docs/python/README.md | 46 +++++-- .../runtime-docs/typescript/AGENTS.md | 5 + .../runtime-docs/typescript/README.md | 46 +++++-- src/core/dev/readiness.test.ts | 123 +++++++++++++++++- src/core/dev/readiness.ts | 116 +++++++++++++++-- .../templates/bedrockManagedAgents.test.ts | 5 + .../project/add/runtime/index.test.ts | 40 ++++++ src/handlers/project/add/runtime/index.ts | 15 ++- src/handlers/project/dev/index.test.ts | 29 +++++ src/handlers/project/dev/index.ts | 14 ++ 13 files changed, 481 insertions(+), 29 deletions(-) diff --git a/src/assets/templates/bedrock-managed-agents/README.md b/src/assets/templates/bedrock-managed-agents/README.md index e1b1ee69a5..061b830b19 100644 --- a/src/assets/templates/bedrock-managed-agents/README.md +++ b/src/assets/templates/bedrock-managed-agents/README.md @@ -67,6 +67,24 @@ If you set `WORKSPACE_DIRECTORY` to a path on session storage, the Runtime must server cannot create the workspace, and the session fails. If `BMA_STATE_DIR` is not on a mounted path, or the server cannot create it, the server keeps `state.json` in `.bma` in `BMA_HOME_DIR`. +## Platform version V2 + +On platform version V2, AgentCore prepares the Runtime once and starts each session from a snapshot of it. Without a +warmup hook, a new session reads the Codex and CloudWatch agent binaries from disk the first time it runs them, which +can take seconds. The lifecycle server has a build warmup hook, `POST /warmup`, that loads both binaries into memory +before the snapshot and warms their start-up files after it. To use it, set these on the Runtime in +`agentcore/agentcore.json`: + +```json +"platformVersion": "V2", +"hooksConfiguration": { "build": { "warmup": { "action": { "httpPost": { "path": "/warmup" } } } } } +``` + +The hook keeps about 520 MiB of binaries in the snapshot, and starts no processes before it, so sessions still start +their own exec-server and collector. In tests in us-east-1 and ap-southeast-2, the first `codex --version` in a new session took 4-5 ms +with the hook and up to 14 s without it, and the CloudWatch agent's 38-47 ms with the hook and up to 37 s without it. +On V1, leave `hooksConfiguration` unset: AgentCore rejects it. + # Environment variables To change a setting of the server, add the variable to `envVars` of the agent in `agentcore/agentcore.json`. Then run diff --git a/src/assets/templates/bedrock-managed-agents/lifecycle/server.py b/src/assets/templates/bedrock-managed-agents/lifecycle/server.py index 1d54e46080..a9c35002a9 100644 --- a/src/assets/templates/bedrock-managed-agents/lifecycle/server.py +++ b/src/assets/templates/bedrock-managed-agents/lifecycle/server.py @@ -2,7 +2,8 @@ AgentCore calls ``GET /ping`` for health and ``POST /invocations`` for the BMA lifecycle calls ``activate``, ``renew_turn_lease``, ``release_turn_lease``, and -``disconnect``. An invocation with no action returns the status. +``disconnect``. An invocation with no action returns the status. On platform version V2 with a +build warmup hook, AgentCore calls ``POST /warmup`` before sessions start (see ``warmup``). The server runs one ``codex exec-server`` for the attachment of the last ``activate`` call and saves the attachment in ``state.json`` in ``BMA_STATE_DIR``. @@ -17,6 +18,7 @@ import contextlib import json +import mmap import os import shlex import signal @@ -75,6 +77,11 @@ } PROTOCOL_VERSION = 1 + +WARMUP_TYPE_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type" +# Kept for the life of the process, so the binaries' pages are in memory in the V2 snapshot. +WARMUP_MAPS: list[mmap.mmap] = [] +WARMUP_LOCK = threading.Lock() RESTART_DELAY_SECONDS = 5 STOP_GRACE_SECONDS = 3 @@ -575,7 +582,46 @@ def do_GET(self) -> None: else: self.send_json(HTTPStatus.NOT_FOUND, {"error": "route not found"}) + def warmup(self) -> None: + """Build warmup hook for platform version V2: POST /warmup on the serving port. + + ``memory`` runs before the snapshot: it maps the Codex and CloudWatch agent binaries and + reads every page, keeping the maps, so each session starts with them in memory instead of + reading them from disk. ``disk`` runs after it: it starts each binary once, so the files a + start reads are fast for new sessions. No process keeps running, so no random state is + shared between sessions. Enable it with ``hooksConfiguration`` in ``agentcore.json``. + """ + kind = (self.headers.get(WARMUP_TYPE_HEADER) or "").lower() + started = time.monotonic() + try: + if kind == "memory": + with WARMUP_LOCK: + if not WARMUP_MAPS: + for binary in (BMA_CODEX_BINARY.resolve(), COLLECTOR_BINARY): + with open(binary, "rb") as handle: + mapped = mmap.mmap(handle.fileno(), 0, prot=mmap.PROT_READ) + for offset in range(0, len(mapped), mmap.PAGESIZE): + mapped[offset] + WARMUP_MAPS.append(mapped) + elif kind == "disk": + for command in ( + [str(BMA_CODEX_BINARY), "--version"], + [str(COLLECTOR_BINARY), "-version"], + ): + subprocess.run(command, capture_output=True, timeout=60, check=True) + except (OSError, ValueError, subprocess.SubprocessError) as error: + log("warmup_failed", type=kind, error=str(error)) + self.send_json( + HTTPStatus.INTERNAL_SERVER_ERROR, {"error": str(error), "type": kind} + ) + return + log("warmup", type=kind, seconds=round(time.monotonic() - started, 2)) + self.send_json(HTTPStatus.OK, {"status": "ok", "type": kind}) + def do_POST(self) -> None: + if self.path == "/warmup": + self.warmup() + return if self.path != "/invocations": self.close_connection = True self.send_json(HTTPStatus.NOT_FOUND, {"error": "route not found"}) diff --git a/src/assets/templates/runtime-docs/python/AGENTS.md b/src/assets/templates/runtime-docs/python/AGENTS.md index 86aa554fcf..546d5b523d 100644 --- a/src/assets/templates/runtime-docs/python/AGENTS.md +++ b/src/assets/templates/runtime-docs/python/AGENTS.md @@ -74,6 +74,11 @@ in more detail. request handler. Refresh credentials when they expire. Anything that fetches credentials, such as a model whose API key comes from AgentCore Identity, stays per session: build it on the first request, not at import. +- If `agentcore/agentcore.json` gives the runtime a + `hooksConfiguration.build.warmup` hook, the agent must serve `POST ` + from it on the serving port: load what sessions need on the `memory` call, + read startup files on the `disk` call, and return 2xx only when done. See + the README's "Platform version V2" section. ## Must not diff --git a/src/assets/templates/runtime-docs/python/README.md b/src/assets/templates/runtime-docs/python/README.md index bf6896f912..4bb709a3f3 100644 --- a/src/assets/templates/runtime-docs/python/README.md +++ b/src/assets/templates/runtime-docs/python/README.md @@ -200,12 +200,15 @@ Every protocol also shares these: `--platform-version V2` (`platformVersion` in `agentcore.json`) prepares your agent once and starts each session from a snapshot of it, so cold starts stay -fast as images and traffic grow. V1 is the default, and V2 is offered in +fast as images and traffic grow. V2 is offered in [some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +If you don't set it, the service picks the version for your account, so set +it when you need a specific one. On V2: -- The snapshot is taken when your health check (`GET /ping`) first passes, - so report healthy only after your agent has loaded what sessions need. +- Without a warmup hook, the snapshot is taken when your health check + (`GET /ping`) first passes, so report healthy only after your agent has + loaded what sessions need. `BedrockAgentCoreApp` does this for you: code at module scope (imports, models, clients) runs before `app.run()` starts the server. If the health check doesn't pass in time, the create or update fails. @@ -220,13 +223,40 @@ On V2: already use it; OpenSSL builds that libraries bundle can repeat values. - Every session reports the same hostname and PID, so don't use either as an ID. -- `--hooks-configuration` adds a build warmup hook that loads memory and warms - files before sessions start; its two calls share 120 seconds. - `--resource-configurations` sets a committed memory baseline per session. - Each update replaces both, so keep them set in `agentcore.json`. +- `--hooks-configuration` adds a build warmup hook, for example + `{"build":{"warmup":{"action":{"httpPost":{"path":"/warmup"}}}}}` (keys are + camelCase). After the health check passes, the service sends `POST /warmup` + to your agent twice, with the `X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type` + header set to `memory` (before the snapshot: load and keep what sessions + need) and then `disk` (after it: read the files a session starts with). + Return 2xx only when the work is done. The two calls share 120 seconds, and + a failed call fails the create or update. Your agent has to serve the route: +{{#if (eq protocol "HTTP")}} + With `bedrock-agentcore`, use `@app.warmup`, or add the route yourself. + Check that your `bedrock-agentcore` version has `@app.warmup`: without it + the route returns 404, `agentcore dev` fails, and so does the deploy. +{{/if}} +{{#if (eq protocol "MCP")}} + With FastMCP, add `@mcp.custom_route("/warmup", methods=["POST"])`; it's + served on the serving port (8000). It can't be `POST /mcp`. +{{/if}} +{{#if (eq protocol "A2A")}} + Add a `POST /warmup` route to the server on the serving port (9000). It + can't be `POST /` or `GET /.well-known/agent-card.json`. +{{/if}} +{{#if (eq protocol "AGUI")}} + Add a `POST /warmup` route to your FastAPI app. It can't be + `POST /invocations`. +{{/if}} + Leave `port` unset unless a separate server in your agent listens on another + port. `agentcore dev` runs the same calls, and can't reach a hook that + listens only on `127.0.0.1` inside a container. +- `--resource-configurations` sets a committed memory baseline per session. + Each update replaces both settings, so keep them set in `agentcore.json`. - Creating or updating a V2 runtime takes several minutes. Keep `platformVersion` set: removing it doesn't move the runtime back, and a - later replacement of the runtime would start on V1. Set `V1` to move back. + later replacement of the runtime would start on the service's default for + your account. Set `V1` to move back. - If deploy fails with "platformVersion V2 is not available for this account", the target's Region, or your account, doesn't offer V2: deploy to a supported Region or set `V1`. diff --git a/src/assets/templates/runtime-docs/typescript/AGENTS.md b/src/assets/templates/runtime-docs/typescript/AGENTS.md index be193915a1..15e8e0139c 100644 --- a/src/assets/templates/runtime-docs/typescript/AGENTS.md +++ b/src/assets/templates/runtime-docs/typescript/AGENTS.md @@ -63,6 +63,11 @@ in more detail. `Math.random()`. Refresh credentials when they expire. Anything that fetches credentials, such as a model whose API key comes from AgentCore Identity, stays per session: build it on the first request, not at import. +- If `agentcore/agentcore.json` gives the runtime a + `hooksConfiguration.build.warmup` hook, the agent must serve `POST ` + from it on the serving port: load what sessions need on the `memory` call, + read startup files on the `disk` call, and return 2xx only when done. See + the README's "Platform version V2" section. ## Must not diff --git a/src/assets/templates/runtime-docs/typescript/README.md b/src/assets/templates/runtime-docs/typescript/README.md index 6f2e6433cc..b559444f57 100644 --- a/src/assets/templates/runtime-docs/typescript/README.md +++ b/src/assets/templates/runtime-docs/typescript/README.md @@ -140,12 +140,15 @@ Every protocol also shares these: `--platform-version V2` (`platformVersion` in `agentcore.json`) prepares your agent once and starts each session from a snapshot of it, so cold starts stay -fast as images and traffic grow. V1 is the default, and V2 is offered in +fast as images and traffic grow. V2 is offered in [some Regions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html#runtime-platform-versions). +If you don't set it, the service picks the version for your account, so set +it when you need a specific one. On V2: -- The snapshot is taken when your health check (`GET /ping`) first passes, - so report healthy only after your agent has loaded what sessions need. +- Without a warmup hook, the snapshot is taken when your health check + (`GET /ping`) first passes, so report healthy only after your agent has + loaded what sessions need. `BedrockAgentCoreApp` does this for you: top-level code (imports, models, clients) runs before `app.run()` starts the server. If the health check doesn't pass in time, the create or update fails. @@ -162,13 +165,40 @@ On V2: already use it. - Every session reports the same hostname and PID, so don't use either as an ID. -- `--hooks-configuration` adds a build warmup hook that loads memory and warms - files before sessions start; its two calls share 120 seconds. - `--resource-configurations` sets a committed memory baseline per session. - Each update replaces both, so keep them set in `agentcore.json`. +- `--hooks-configuration` adds a build warmup hook, for example + `{"build":{"warmup":{"action":{"httpPost":{"path":"/warmup"}}}}}` (keys are + camelCase). After the health check passes, the service sends `POST /warmup` + to your agent twice, with the `X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type` + header set to `memory` (before the snapshot: load and keep what sessions + need) and then `disk` (after it: read the files a session starts with). + Return 2xx only when the work is done. The two calls share 120 seconds, and + a failed call fails the create or update. Your agent has to serve the route: +{{#if (eq protocol "HTTP")}} + With `bedrock-agentcore`, pass `warmupHook` to `BedrockAgentCoreApp`, or add + the route yourself. Check that your `bedrock-agentcore` version has + `warmupHook`: without it the route returns 404, `agentcore dev` fails, and + so does the deploy. +{{/if}} +{{#if (eq protocol "MCP")}} + Add a `POST /warmup` route to the HTTP server that serves your MCP endpoint, + on the serving port (8000). It can't be `POST /mcp`. +{{/if}} +{{#if (eq protocol "A2A")}} + Add a `POST /warmup` route to the server on the serving port (9000). It + can't be `POST /` or `GET /.well-known/agent-card.json`. +{{/if}} +{{#if (eq protocol "AGUI")}} + Add a `POST /warmup` route to your server. It can't be `POST /invocations`. +{{/if}} + Leave `port` unset unless a separate server in your agent listens on another + port. `agentcore dev` runs the same calls, and can't reach a hook that + listens only on `127.0.0.1` inside a container. +- `--resource-configurations` sets a committed memory baseline per session. + Each update replaces both settings, so keep them set in `agentcore.json`. - Creating or updating a V2 runtime takes several minutes. Keep `platformVersion` set: removing it doesn't move the runtime back, and a - later replacement of the runtime would start on V1. Set `V1` to move back. + later replacement of the runtime would start on the service's default for + your account. Set `V1` to move back. - If deploy fails with "platformVersion V2 is not available for this account", the target's Region, or your account, doesn't offer V2: deploy to a supported Region or set `V1`. diff --git a/src/core/dev/readiness.test.ts b/src/core/dev/readiness.test.ts index b50c309bbb..b1b3908cfb 100644 --- a/src/core/dev/readiness.test.ts +++ b/src/core/dev/readiness.test.ts @@ -2,19 +2,27 @@ import { describe, expect, test } from "bun:test"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; import { HookPortReserver, + hooksConfigurationWarning, type HttpFetch, runWarmupHook, + sharedHookPortError, WARMUP_TYPE_HEADER, waitForHealthyPing, + waitUntilReady, warmupTarget, } from "./readiness"; -function runtime(build: ProjectRuntime["build"], httpPost?: { path: string; port?: number }) { +function runtime( + build: ProjectRuntime["build"], + httpPost?: { path: string; port?: number }, + overrides: Partial = {}, +) { return { name: "agent", build, protocol: "HTTP", entrypoint: "main.py", + ...overrides, codeLocation: "app/agent", ...(httpPost && { hooksConfiguration: { build: { warmup: { action: { httpPost } } } } }), } as ProjectRuntime; @@ -63,12 +71,38 @@ describe("warmupTarget", () => { ); test("CodeZip: a hook on its own port is reached on that local port", () => { + const typescript = runtime( + "CodeZip", + { path: "/warmup", port: 9300 }, + { entrypoint: "main.ts" }, + ); + expect(warmupTarget(typescript, 9100)).toEqual({ path: "/warmup", port: 9300 }); + }); + + test("Python CodeZip: a hook on its own port carries the uvicorn hint", () => { expect(warmupTarget(runtime("CodeZip", { path: "/warmup", port: 9300 }), 9100)).toEqual({ path: "/warmup", port: 9300, + hint: expect.stringContaining("HookConfig(port=...) isn't served"), }); }); + test("a path without a leading slash is refused before dev builds a URL from it", () => { + expect(() => warmupTarget(runtime("CodeZip", { path: "warmup" }), 9100)).toThrow( + `Runtime 'agent' has warmup hook path "warmup", which must start with "/" (for example "/warmup").`, + ); + }); + + test("MCP: any /ping response counts, as it does for the service", () => { + const mcp = runtime("CodeZip", { path: "/warmup" }, { protocol: "MCP" }); + expect(warmupTarget(mcp, 8000)).toEqual({ path: "/warmup", port: 8000, anyPingResponse: true }); + }); + + test("A2A still has to report Healthy", () => { + const a2a = runtime("CodeZip", { path: "/warmup" }, { protocol: "A2A" }); + expect(warmupTarget(a2a, 9000)).toEqual({ path: "/warmup", port: 9000 }); + }); + test("Container: a hook on the serving port goes through the dev port mapping", () => { expect(warmupTarget(runtime("Container", { path: "/warmup", port: 8080 }), 9100)).toEqual({ path: "/warmup", @@ -112,6 +146,24 @@ describe("waitForHealthyPing", () => { await waitForHealthyPing(9100, new AbortController().signal, fetchImpl, 1); }); + test("with anyResponse, a 404 from a server without /ping counts as ready", async () => { + const { fetchImpl, calls } = scriptedFetch([ + new Error("ECONNREFUSED"), + new Response("bad gateway", { status: 502 }), + new Response("too many", { status: 429 }), + new Response("not found", { status: 404 }), + ]); + await waitForHealthyPing(8000, new AbortController().signal, fetchImpl, 1, 1_000, true); + expect(calls).toHaveLength(4); + }); + + test("with anyResponse, only 502 and 429 keep it waiting", async () => { + const { fetchImpl } = scriptedFetch([new Response("bad gateway", { status: 502 })]); + await expect( + waitForHealthyPing(8000, new AbortController().signal, fetchImpl, 1, 20, true), + ).rejects.toThrow("GET /ping on port 8000 got no response other than 502 or 429 within 0.02s."); + }); + test("gives up at a fixed deadline, however much the agent logs meanwhile", async () => { const { fetchImpl } = scriptedFetch([new Response("not found", { status: 404 })]); await expect( @@ -194,3 +246,72 @@ describe("runWarmupHook", () => { ); }); }); + +describe("hooksConfigurationWarning", () => { + const named = (hooksConfiguration: unknown) => + ({ name: "agent", hooksConfiguration }) as Pick; + + test.each([ + ["PascalCase keys", { Build: { Warmup: { Action: { HttpPost: { Path: "/warmup" } } } } }], + ["a warmUp typo", { build: { warmUp: { action: { httpPost: { path: "/warmup" } } } } }], + ["a build without a warmup", { build: {} }], + ])("warns about %s, which dev would silently skip", (_case, hooks) => { + expect(hooksConfigurationWarning(named(hooks))).toContain( + "Runtime 'agent' has a hooksConfiguration without build.warmup.action.httpPost.path", + ); + }); + + test.each([ + ["a recognized hook", { build: { warmup: { action: { httpPost: { path: "/warmup" } } } } }], + ["no hooks", undefined], + ["an empty object", {}], + ])("stays quiet for %s", (_case, hooks) => { + expect(hooksConfigurationWarning(named(hooks))).toBeUndefined(); + }); +}); + +describe("sharedHookPortError", () => { + const hooked = (name: string, build: ProjectRuntime["build"], port?: number) => ({ + ...runtime(build, { path: "/warmup", ...(port !== undefined && { port }) }), + name, + }); + + test("names CodeZip agents whose hooks share their own port", () => { + expect( + sharedHookPortError([hooked("ta", "CodeZip", 9000), hooked("tb", "CodeZip", 9000)]), + ).toContain("('ta' and 'tb' on port 9000)"); + }); + + test.each([ + ["different ports", [hooked("ta", "CodeZip", 9000), hooked("tb", "CodeZip", 9001)]], + ["hooks on the serving port", [hooked("ta", "CodeZip", 8080), hooked("tb", "CodeZip")]], + [ + "containers, which get their own host ports", + [hooked("ta", "Container", 9000), hooked("tb", "Container", 9000)], + ], + ])("is undefined for %s", (_case, runtimes) => { + expect(sharedHookPortError(runtimes)).toBeUndefined(); + }); +}); + +describe("waitUntilReady", () => { + test("adds the target's hint to a startup failure, and warns with it first", async () => { + const statuses: string[] = []; + await expect( + waitUntilReady({ + name: "agent", + devPort: 8080, + warmup: { path: "/warmup", port: 9000, hint: "Leave the port unset." }, + waitForPort: async () => { + throw new Error("Agent did not accept connections on port 8080 within 120s."); + }, + signal: new AbortController().signal, + fetchImpl: scriptedFetch([json({})]).fetchImpl, + onStatus: (message) => statuses.push(message), + }), + ).rejects.toThrow( + "Agent did not accept connections on port 8080 within 120s. Leave the port unset.", + ); + expect(statuses).toEqual(["Warning: Leave the port unset."]); + }); +}); diff --git a/src/core/dev/readiness.ts b/src/core/dev/readiness.ts index b4a40665cd..c28bb65240 100644 --- a/src/core/dev/readiness.ts +++ b/src/core/dev/readiness.ts @@ -24,6 +24,13 @@ export type WarmupTarget = { port: number; /** The hook is a container's own port, reached through an extra port mapping. */ viaContainerMapping?: boolean; + /** + * MCP servers don't have to serve `/ping`: the service treats any response other than 502 or 429 + * as ready, including a 404. Every other protocol must report Healthy. + */ + anyPingResponse?: boolean; + /** Added to a startup or warmup failure when dev knows a likely cause. */ + hint?: string; }; /** @@ -51,11 +58,23 @@ export function warmupTarget( const httpPost = runtime.hooksConfiguration?.build?.warmup?.action.httpPost; if (!httpPost) return undefined; const { path, port } = httpPost; - const servingPort = DEV_PORTS[runtime.protocol ?? "HTTP"]; + if (!path.startsWith("/")) { + throw new Error( + `Runtime '${runtime.name}' has warmup hook path "${path}", which must start with "/" ` + + `(for example "/${path}"). AgentCore Runtime rejects it too.`, + ); + } + const protocol = runtime.protocol ?? "HTTP"; + const servingPort = DEV_PORTS[protocol]; + const base = protocol === "MCP" ? { path, anyPingResponse: true } : { path }; // The serving port is wherever dev runs the agent, which may not be its configured number. - if (port === undefined || port === servingPort) return { path, port: devPort }; - if (!isContainerBuild(runtime)) return { path, port }; - if (hookHostPort !== undefined) return { path, port: hookHostPort, viaContainerMapping: true }; + if (port === undefined || port === servingPort) return { ...base, port: devPort }; + if (!isContainerBuild(runtime)) { + return isPythonHttpCodeZip(runtime) + ? { ...base, port, hint: PYTHON_CODEZIP_HOOK_PORT_HINT } + : { ...base, port }; + } + if (hookHostPort !== undefined) return { ...base, port: hookHostPort, viaContainerMapping: true }; throw new Error( `Runtime '${runtime.name}' serves its warmup hook on port ${port}, which agentcore dev can't ` + `reach inside a container. Remove "port" from hooksConfiguration.build.warmup.action.httpPost, ` + @@ -63,10 +82,65 @@ export function warmupTarget( ); } +const PYTHON_CODEZIP_HOOK_PORT_HINT = + "agentcore dev runs Python CodeZip agents under uvicorn, where the SDK's HookConfig(port=...) " + + 'isn\'t served (it needs app.run()). To run the hook locally, remove "port" from ' + + "hooksConfiguration.build.warmup.action.httpPost so it's served on the serving port."; + +/** dev runs these with `uvicorn --reload` instead of the agent's own `app.run()`. */ +function isPythonHttpCodeZip(runtime: ProjectRuntime): boolean { + const file = runtime.entrypoint.split(":")[0] ?? ""; + return (runtime.protocol ?? "HTTP") === "HTTP" && file.endsWith(".py"); +} + +/** + * A warning for a `hooksConfiguration` that dev and the service won't recognize as a warmup hook. + * The schema keeps unknown keys so new service fields pass through, which also lets PascalCase + * keys (`Build`) and typos (`warmUp`) through. Undefined when the hook is recognized or unset. + */ +export function hooksConfigurationWarning( + runtime: Pick, +): string | undefined { + const hooks = runtime.hooksConfiguration; + if (!hooks || Object.keys(hooks).length === 0) return undefined; + // Optional chaining throughout: `add` checks the raw flag value before the schema does. + if (hooks.build?.warmup?.action?.httpPost?.path) return undefined; + return ( + `Runtime '${runtime.name}' has a hooksConfiguration without build.warmup.action.httpPost.path. ` + + "Keys are camelCase (build, warmup, action, httpPost), so agentcore dev skips the warmup, " + + "and AgentCore Runtime may reject the hook at deploy." + ); +} + +/** + * For agents started together: CodeZip agents whose warmup hooks listen on the same own port of + * this machine. Only one of them can bind it, so the other's warmup would reach the wrong agent. + */ +export function sharedHookPortError(runtimes: ProjectRuntime[]): string | undefined { + const byPort = new Map(); + for (const runtime of runtimes) { + if (isContainerBuild(runtime)) continue; + const port = runtime.hooksConfiguration?.build?.warmup?.action.httpPost.port; + if (port === undefined || port === DEV_PORTS[runtime.protocol ?? "HTTP"]) continue; + byPort.set(port, [...(byPort.get(port) ?? []), runtime.name]); + } + const clashes = [...byPort].filter(([, names]) => names.length > 1); + if (clashes.length === 0) return undefined; + const described = clashes + .map(([port, names]) => `${names.map((name) => `'${name}'`).join(" and ")} on port ${port}`) + .join("; "); + return ( + `Agents serve their warmup hooks on the same port of this machine (${described}), so only ` + + "one of them can listen there. Give each hook its own port, or run the agents one at a time " + + "with --agent." + ); +} + /** * Poll `GET /ping` until it reports Healthy or HealthyBusy, the signal aborts, or `timeoutMs` * passes. AgentCore Runtime calls the warmup hook only after this check passes. The deadline is * fixed: each poll makes the agent log a line, so a deadline based on its output would never pass. + * With `anyResponse` (MCP), any response other than 502 or 429 counts, as it does for the service. */ export async function waitForHealthyPing( port: number, @@ -74,6 +148,7 @@ export async function waitForHealthyPing( fetchImpl: HttpFetch, intervalMs = PING_INTERVAL_MS, timeoutMs = PING_TIMEOUT_MS, + anyResponse = false, ): Promise { const url = `http://127.0.0.1:${port}/ping`; const deadline = Date.now() + timeoutMs; @@ -81,7 +156,9 @@ export async function waitForHealthyPing( if (signal.aborted) throw new Error("Aborted while waiting for /ping to report healthy."); if (Date.now() > deadline) { throw new Error( - `GET /ping on port ${port} did not report Healthy within ${timeoutMs / 1000}s.`, + anyResponse + ? `GET /ping on port ${port} got no response other than 502 or 429 within ${timeoutMs / 1000}s.` + : `GET /ping on port ${port} did not report Healthy within ${timeoutMs / 1000}s.`, ); } try { @@ -89,6 +166,10 @@ export async function waitForHealthyPing( method: "GET", signal: AbortSignal.any([signal, AbortSignal.timeout(PING_REQUEST_TIMEOUT_MS)]), }); + if (anyResponse && response.status !== 502 && response.status !== 429) { + await response.body?.cancel().catch(() => {}); + return; + } if (response.ok) { const body = (await response.json().catch(() => undefined)) as { status?: unknown } | undefined; @@ -185,8 +266,19 @@ export async function runWarmupSequence(options: { onStatus: (message: string) => void; }): Promise { const { name, devPort, target, signal, fetchImpl, onStatus } = options; - onStatus(`Waiting for '${name}' to report healthy on GET /ping.`); - await waitForHealthyPing(devPort, signal, fetchImpl); + onStatus( + target.anyPingResponse + ? `Waiting for '${name}' to answer GET /ping (any response but 502 or 429, as for MCP on AgentCore Runtime).` + : `Waiting for '${name}' to report healthy on GET /ping.`, + ); + await waitForHealthyPing( + devPort, + signal, + fetchImpl, + undefined, + undefined, + target.anyPingResponse, + ); await runWarmupHook(target, signal, fetchImpl, (type) => onStatus( `Running the warmup hook for '${name}' (${type}): POST ${target.path} on port ${target.port}.`, @@ -213,8 +305,14 @@ export async function waitUntilReady(options: { onStatus: (message: string) => void; }): Promise { const { warmup, waitForPort, ...sequence } = options; - await waitForPort(); - if (warmup) await runWarmupSequence({ ...sequence, target: warmup }); + if (warmup?.hint) sequence.onStatus(`Warning: ${warmup.hint}`); + try { + await waitForPort(); + if (warmup) await runWarmupSequence({ ...sequence, target: warmup }); + } catch (error) { + if (!warmup?.hint || !(error instanceof Error) || sequence.signal.aborted) throw error; + throw new Error(`${error.message} ${warmup.hint}`, { cause: error }); + } } /** diff --git a/src/core/project/templates/bedrockManagedAgents.test.ts b/src/core/project/templates/bedrockManagedAgents.test.ts index 050c35c8d3..fd76ddbb0b 100644 --- a/src/core/project/templates/bedrockManagedAgents.test.ts +++ b/src/core/project/templates/bedrockManagedAgents.test.ts @@ -64,6 +64,11 @@ test("Bedrock Managed Agents assets preserve the environment and lifecycle contr expect(dockerfile).toContain( 'CMD ["uv", "run", "--no-sync", "opentelemetry-instrument", "python", "-u", "lifecycle/server.py"]', ); + // The V2 build warmup hook keeps both binaries in memory in the snapshot and starts no process. + expect(server).toContain('if self.path == "/warmup":'); + expect(server).toContain('WARMUP_TYPE_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type"'); + expect(server).toContain("mmap.mmap(handle.fileno(), 0, prot=mmap.PROT_READ)"); + expect(server).toContain('[str(BMA_CODEX_BINARY), "--version"]'); expect(dockerignore).toContain(".venv/"); expect(dockerignore).toContain(".env"); expect(dockerignore).toContain(".git/"); diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index 449b820e1c..5e7750f928 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -436,6 +436,46 @@ describe("project add runtime", () => { }, ); + test("warns when --hooks-configuration has no warmup hook in camelCase, and still adds it", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const { io } = await run([ + "add", + "runtime", + "--name", + "pascal_hooks", + "--language", + "python", + "--platform-version", + "V2", + "--hooks-configuration", + '{"Build":{"Warmup":{"Action":{"HttpPost":{"Path":"/warmup"}}}}}', + ]); + + expect(io.stderr()).toContain( + "Warning: Runtime 'pascal_hooks' has a hooksConfiguration without build.warmup.action.httpPost.path", + ); + expect((await runtimeOf(projectRoot, "pascal_hooks"))?.hooksConfiguration).toEqual({ + Build: { Warmup: { Action: { HttpPost: { Path: "/warmup" } } } }, + }); + }); + + test("a recognized warmup hook adds without a warning", async () => { + const { cleanup } = await initProject(); + cleanups.push(cleanup); + const { io } = await run([ + "add", + "runtime", + "--name", + "camel_hooks", + "--language", + "python", + "--hooks-configuration", + '{"build":{"warmup":{"action":{"httpPost":{"path":"/warmup"}}}}}', + ]); + expect(io.stderr()).not.toContain("Warning:"); + }); + test("infrastructure flags are written to the spec entry", async () => { const { projectRoot, cleanup } = await initProject(); cleanups.push(cleanup); diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index 725dbc0d29..ffed2b65ac 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -4,7 +4,12 @@ import { isChinaRegion } from "../../../../core/partition"; import type { AddProjectResourceConfig } from "../types"; import { parseJsonFlag, parseTags, tagsFlag } from "../../../utils"; import { InputValidationError, RegionUnsupportedFeatureError } from "../../../../errors"; -import { AgentNameSchema, type EnvVar } from "../../../../projectSchemas/runtime"; +import { + AgentNameSchema, + type EnvVar, + type ProjectRuntime, +} from "../../../../projectSchemas/runtime"; +import { hooksConfigurationWarning } from "../../../../core/dev/readiness"; import { RuntimeAuthorizerTypeSchema } from "../../../../projectSchemas/auth"; import { NetworkModeSchema, @@ -129,7 +134,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => }), flag( "platform-version", - "Runtime platform version: V1 (service default) or V2", + "Runtime platform version: V1 or V2. If unset, the service picks the version for your account", PlatformVersionSchema.optional(), { group: ENVIRONMENT }, ), @@ -313,6 +318,11 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => ), tags: parseTags(flags["tags"]), }; + const hooksWarning = hooksConfigurationWarning({ + name: flags.name, + hooksConfiguration: infra.hooksConfiguration as ProjectRuntime["hooksConfiguration"], + }); + if (hooksWarning) notes.push(`Warning: ${hooksWarning}`); if (isImport) { await addProjectResource( @@ -341,6 +351,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => project, toAddRuntimeInput({ ...infra, language, protocol }), runtimeDocsAddedMessage(flags.name, language, protocol), + { notes }, ); }, }); diff --git a/src/handlers/project/dev/index.test.ts b/src/handlers/project/dev/index.test.ts index fe8e30bef1..14de2b6c13 100644 --- a/src/handlers/project/dev/index.test.ts +++ b/src/handlers/project/dev/index.test.ts @@ -523,6 +523,21 @@ describe("project dev build warmup hook", () => { expect(codeZip.inputs[0]?.signal.aborted).toBe(true); }); + test("dev --agent warns when hooksConfiguration has no warmup it recognizes", async () => { + const subject = harness({ + project: project({ + ...runtime("orders"), + hooksConfiguration: { Build: { Warmup: {} } } as ProjectRuntime["hooksConfiguration"], + }), + codeZip: briefRunner(), + }); + await subject.run({ agent: "orders" }); + expect(subject.io.stderr()).toContain( + "Warning: Runtime 'orders' has a hooksConfiguration without build.warmup.action.httpPost.path", + ); + expect(subject.io.stderr()).not.toContain("GET /ping"); + }); + test("dev --agent without a warmup hook makes no HTTP calls", async () => { const subject = harness({ codeZip: briefRunner() }); await subject.run({ agent: "orders" }); @@ -602,6 +617,20 @@ describe("project dev headless multi-agent", () => { await pending.catch(() => undefined); }); + test("refuses CodeZip agents whose warmup hooks share their own port, before starting any", async () => { + const ownPort = (name: string): ProjectRuntime => ({ + ...runtime(name), + hooksConfiguration: { + build: { warmup: { action: { httpPost: { path: "/warmup", port: 9000 } } } }, + }, + }); + const codeZip = stayingRunner(); + const subject = harness({ project: project(ownPort("ta"), ownPort("tb")), codeZip }); + + await expect(subject.run()).rejects.toThrow("('ta' and 'tb' on port 9000)"); + expect(codeZip.inputs).toHaveLength(0); + }); + test("exits non-zero when every agent fails to start", async () => { const subject = harness({ project: twoRuntimes() }); diff --git a/src/handlers/project/dev/index.ts b/src/handlers/project/dev/index.ts index beffccd4a5..ce1706c231 100644 --- a/src/handlers/project/dev/index.ts +++ b/src/handlers/project/dev/index.ts @@ -9,8 +9,10 @@ import type { V0DeployRunner } from "../../../core/project/legacy/deploy"; import { DevSupervisor, type SupervisorConfig } from "../../../core/dev/supervisor"; import { HookPortReserver, + hooksConfigurationWarning, type HttpFetch, planWarmup, + sharedHookPortError, waitUntilReady, } from "../../../core/dev/readiness"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; @@ -403,6 +405,18 @@ async function runRuntimeDev({ const runtimes = synced.project.spec.runtimes.filter(({ name }) => runtimeNames.includes(name), ); + for (const runtime of runtimes) { + const warning = hooksConfigurationWarning(runtime); + if (warning) renderStatus({ io: config.io, message: `Warning: ${warning}`, json }); + } + const sharedHookPort = runtimes.length > 1 ? sharedHookPortError(runtimes) : undefined; + // Headless starts every agent at once; the Inspector starts them one by one on request. + if (sharedHookPort && input.mode === "headless" && !input.agent) { + throw new InputValidationError(sharedHookPort); + } + if (sharedHookPort) { + renderStatus({ io: config.io, message: `Warning: ${sharedHookPort}`, json }); + } collector = input.traces ? await startRuntimeTraceCollector({ config, project, runtimes, json }) From a6452a42b76ed5a0ec7bfb48d45efa216f693c82 Mon Sep 17 00:00:00 2001 From: Gitika <53349492+notgitika@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:20:25 -0500 Subject: [PATCH 09/19] feat(runtime): support pre-built ECR container images (#2719) A Runtime can deploy an existing private or public ECR image: set containerUri in agentcore.json, or with agentcore add runtime --build-config '{"containerUri":"..."}'. The image is deployed as is: no local source, Dockerfile, CodeBuild, or managed ECR repository. - containerUri requires build Container and excludes dockerfile, buildContextPath, and customDockerBuildArgs, matching @aws/agentcore-cdk - add runtime --build-config accepts containerUri, defaults build to Container, and needs no --language; with containerUri it skips the Dockerfile requirement for Container builds - a containerUri Runtime resolves to workload build mode ContainerUri, so it triggers no local image build, Dockerfile sync, or ARM64 builder check - dev skips pre-built Runtimes (with a status line) and runs the rest, also on reload; selecting only pre-built Runtimes explains how to deploy and invoke - the switch guard rejects a deployed Runtime changing between CodeZip and ContainerUri in either direction (the service rejects artifact-type changes); Container or ContainerLocal to ContainerUri stays allowed, except Container to an image in the ECR repository the stack created for that build, which the deploy deletes - public.ecr.aws URIs need an alias and a repository; the 2-205 length applies to the repository only - one Node probe checks the CDK package for every feature the project uses (ContainerLocal, Runtime containerUri); a missing feature names the minimum @aws/agentcore-cdk version and, when the CLI manages the dependencies, asks to update the CLI; a package that fails to load is reported with its own error - workload build mode ContainerUri is counted in telemetry Co-authored-by: gitikavj --- docs/runtime-prebuilt-images.md | 67 + e2eTest/README.md | 20 + e2eTest/project/prebuilt-runtime.test.ts | 203 ++ src/core/project/backends/cdk.test.ts | 123 +- src/core/project/backends/cdk.ts | 98 +- .../AgentCore-Fixture.assets.json | 65 + .../AgentCore-Fixture.template.json | 2087 +++++++++++++++++ .../__fixtures__/prebuilt-runtime/README.md | 30 + .../prebuilt-runtime/agentcore.json | 19 + .../prebuilt-runtime/manifest.json | 511 ++++ .../backends/cdk/compatibility.test.ts | 231 +- .../project/backends/cdk/compatibility.ts | 162 +- .../backends/cdk/localContainers.test.ts | 45 + .../project/backends/cdk/localContainers.ts | 78 +- .../backends/cdk/prebuiltRuntime.test.ts | 125 + src/core/project/manager.test.ts | 26 + src/core/project/manager.tsx | 11 +- src/core/project/runtimeBuild.test.ts | 53 + src/core/project/runtimeBuild.ts | 23 +- src/core/project/templates/runtimeDocs.ts | 12 +- src/handlers/project/add/buildConfig.ts | 26 +- .../project/add/runtime/index.test.ts | 138 ++ src/handlers/project/add/runtime/index.ts | 39 +- src/handlers/project/add/runtime/types.ts | 10 +- src/handlers/project/deploy/index.test.ts | 31 + src/handlers/project/deploy/index.ts | 1 + src/handlers/project/dev/index.test.ts | 60 + src/handlers/project/dev/index.ts | 16 +- src/projectSchemas/constants.ts | 54 + src/projectSchemas/harness.ts | 20 +- src/projectSchemas/runtime.test.ts | 108 + src/projectSchemas/runtime.ts | 49 +- src/telemetry/shapes.tsx | 1 + 33 files changed, 4412 insertions(+), 130 deletions(-) create mode 100644 docs/runtime-prebuilt-images.md create mode 100644 e2eTest/project/prebuilt-runtime.test.ts create mode 100644 src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.assets.json create mode 100644 src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.template.json create mode 100644 src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/README.md create mode 100644 src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/agentcore.json create mode 100644 src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/manifest.json create mode 100644 src/core/project/backends/cdk/prebuiltRuntime.test.ts diff --git a/docs/runtime-prebuilt-images.md b/docs/runtime-prebuilt-images.md new file mode 100644 index 0000000000..904dc8ff60 --- /dev/null +++ b/docs/runtime-prebuilt-images.md @@ -0,0 +1,67 @@ +# Deploy an existing Runtime image + +Set `containerUri` in `--build-config` on `agentcore add runtime` to deploy an image you have +already built and pushed to ECR: + +```sh +agentcore add runtime --name agent \ + --build-config '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1"}' +agentcore deploy +agentcore invoke --runtime agent --payload '{"prompt":"Hello"}' +``` + +Private ECR tags and digests, and public ECR image URIs, are supported. The image must satisfy the +AgentCore Runtime contract, including Linux ARM64 and the selected protocol's server requirements. +The toolkit does not build, copy, publish, or check the existence of this image. + +`--build-config` keys match `agentcore.json`. With `containerUri`: + +- `build` must be `"Container"`; when omitted, the CLI writes `"build": "Container"`. `CodeZip` and + `ContainerLocal` are rejected. +- `dockerfile`, `buildContextPath`, and `customDockerBuildArgs` are rejected: the image is not built. +- `--language` is optional. The persisted Runtime keeps schema-required `entrypoint` and + `codeLocation` placeholders, but the CLI creates no source folder, and build and deploy do not + read those placeholders or any local Dockerfile or manifest. + +All other `add runtime` flags (`--protocol`, `--network-mode`, `--environment-variables`, and so +on) work as usual. + +`agentcore build` synthesizes the deployment and builds nothing locally. `agentcore deploy` uses the +configured URI directly and grants the Runtime execution role the applicable ECR pull permissions. +Neither command creates a managed ECR repository, CodeBuild project, source archive, or +image-build custom resource for this Runtime. `agentcore dev` cannot run a pre-built image: it skips +pre-built Runtimes and runs the project's other Runtimes, and `--agent ` for a pre-built +Runtime explains how to deploy and invoke it instead. + +Change `containerUri` in `agentcore/agentcore.json` and deploy to update the image. Use a new tag or +digest to trigger an update; replacing the contents of an unchanged tag does not change the +CloudFormation template. Named endpoints continue to select Runtime versions. + +A deployed Runtime keeps its artifact type. Switching a deployed Runtime between a pre-built +`containerUri` and an image the toolkit builds (`Container` or `ContainerLocal`) is allowed, because +both are container artifacts. One exception: a `containerUri` in the ECR repository the toolkit +created for the Runtime's `Container` build is rejected before deploy, because switching away from +`Container` deletes that repository and its images. Copy the image to an ECR repository you manage +first, then set `containerUri` to the copy. Switching a deployed Runtime between `CodeZip` and `containerUri`, in +either direction, is rejected before deploy: the service does not allow changing a Runtime's +artifact type. Add a Runtime with a new name instead. + +`networkMode: "VPC"` configures the deployed workload. A pre-built image does not require +`networkConfig.vpcId` for CodeBuild and is not subject to CodeBuild's five-security-group check. +Runtime networking must still satisfy VPC and account limits, including the security-groups-per-ENI +quota. This setting does not restrict inbound invocation to private endpoints. +The deployed workload still needs the [documented VPC networking prerequisites](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/agentcore-vpc.html#agentcore-vpc-endpoints), +including ECR and S3 connectivity for container images. + +Cross-account images: the Runtime's execution role pulls the image with `ecr:BatchGetImage`, +`ecr:GetDownloadUrlForLayer`, and `ecr:BatchCheckLayerAvailability` on the repository, and +`ecr:GetAuthorizationToken`. The deploy grants these to the role, but when the repository is in +another account, its repository policy must also allow the Runtime's execution role (or its +account) as a principal for `ecr:BatchGetImage`, `ecr:GetDownloadUrlForLayer`, and +`ecr:BatchCheckLayerAvailability`; otherwise the Runtime cannot pull the image. + +This feature requires `@aws/agentcore-cdk` 1.3.0 or newer. Older packages can +silently strip unknown schema properties, so before building or deploying, the CLI checks that the +project's package supports every feature the project uses (pre-built Runtime images, +`ContainerLocal`) and fails with the missing feature named. A package that is installed but fails +to load is reported with its own load error instead. diff --git a/e2eTest/README.md b/e2eTest/README.md index ea7f54dd9a..31e7fe3531 100644 --- a/e2eTest/README.md +++ b/e2eTest/README.md @@ -21,3 +21,23 @@ run through a shell, so paths containing spaces, quoting, and shell syntax are n ```sh AGENTCORE_CLI_PATH=/path/to/agentcore bun run test:e2e ``` + +The pre-built Runtime tests accept existing Linux ARM64 HTTP images. The test handler must return +`{"version":"v1","echo":}` for the initial image and `"v2"` for the update: + +```sh +export AGENTCORE_PREBUILT_V1_URI='' +export AGENTCORE_PREBUILT_V1_DIGEST_URI='' +export AGENTCORE_PREBUILT_V2_URI='' +# Optional: an existing public ECR image with the v1 handler. +export AGENTCORE_PREBUILT_PUBLIC_URI='' +# Until the CDK release includes them, install a package packed from CDK PRs #463 and #440. +export AGENTCORE_CDK_PACKAGE=/absolute/path/to/aws-agentcore-cdk.tgz +bun run test:e2e e2eTest/project/prebuilt-runtime.test.ts +``` + +These tests skip when their image variables are absent. They add each Runtime with +`agentcore add runtime --build-config '{"containerUri":"..."}'`, then exercise build, deploy, +invoke, digest pinning, a named endpoint, an image update that keeps the Runtime ID, the absence +of build resources, and stack teardown. They never create or publish the image fixtures. Their +projects use the standard e2e prefix, so the setup sweep removes stacks left by an interrupted run. diff --git a/e2eTest/project/prebuilt-runtime.test.ts b/e2eTest/project/prebuilt-runtime.test.ts new file mode 100644 index 0000000000..aaff242137 --- /dev/null +++ b/e2eTest/project/prebuilt-runtime.test.ts @@ -0,0 +1,203 @@ +import { describe, expect, test } from "vitest"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { randomUUID } from "node:crypto"; +import { + CloudFormationClient, + DescribeStacksCommand, + GetTemplateCommand, +} from "@aws-sdk/client-cloudformation"; +import z from "zod"; +import { E2E_PREFIX, TAGS } from "../constants"; +import { CliRunner, parseResult } from "../helpers/run"; +import { retry } from "../helpers/retry"; +import { TIMEOUT_MS } from "../timeouts"; + +// Supply existing ARM64 HTTP fixtures; this suite never creates or publishes images. +const v1 = process.env.AGENTCORE_PREBUILT_V1_URI; +const digest = process.env.AGENTCORE_PREBUILT_V1_DIGEST_URI; +const v2 = process.env.AGENTCORE_PREBUILT_V2_URI; +const publicUri = process.env.AGENTCORE_PREBUILT_PUBLIC_URI; +const resultSchema = z.object({ message: z.string() }).passthrough(); +const operationSchema = z.object({ operation: z.string() }); +const invocationSchema = z.object({ + statusCode: z.literal(200), + body: z.string(), + complete: z.literal(true), +}); + +describe("pre-built Runtime images", { tags: [TAGS.RUNTIME] }, () => { + const cli = new CliRunner(); + const cfn = new CloudFormationClient({ + region: process.env.AWS_REGION ?? "us-west-2", + }); + + async function createProject() { + const parent = await mkdtemp(join(tmpdir(), "agentcore-prebuilt-e2e-")); + // The standard prefix, so setup.ts sweeps the stack if a run dies before cleanup. + const name = `${E2E_PREFIX}pb${randomUUID().replaceAll("-", "").slice(0, 12)}`; + const created = parseResult( + z.object({ project: z.object({ path: z.string() }) }), + await cli.run( + ["create", "--name", name, "--template", "empty", "--skip-git", "--json"], + parent, + ), + ); + const path = created.project.path; + // Before the CDK release, exercise a package packed from #463 and #440. + if (process.env.AGENTCORE_CDK_PACKAGE) { + await promisify(execFile)( + process.platform === "win32" ? "npm.cmd" : "npm", + ["install", process.env.AGENTCORE_CDK_PACKAGE], + { cwd: join(path, "agentcore", "cdk") }, + ); + } + const stack = `AgentCore-${name}-default`; + console.info(`pre-built Runtime test project: ${path}; stack: ${stack}`); + return { path, stack }; + } + + async function addImage(path: string, name: string, containerUri: string) { + parseResult( + operationSchema, + await cli.run( + [ + "add", + "runtime", + "--name", + name, + "--build-config", + JSON.stringify({ containerUri }), + "--json", + ], + path, + ), + ); + await expect(readFile(join(path, "app", name, "main.py"))).rejects.toMatchObject({ + code: "ENOENT", + }); + } + + async function invoke(path: string, name: string, version: string, qualifier?: string) { + await retry( + async () => { + const response = parseResult( + invocationSchema, + await cli.run( + [ + "invoke", + "--runtime", + name, + "--session-id", + randomUUID(), + "--payload", + '{"test":"prebuilt-e2e"}', + "--json", + ...(qualifier ? ["--qualifier", qualifier] : []), + ], + path, + ), + ); + expect(JSON.parse(response.body)).toEqual({ + version, + echo: { test: "prebuilt-e2e" }, + }); + }, + TIMEOUT_MS.PROJECT_INVOKE, + 2_000, + ); + } + + async function runtimeIds(stack: string) { + const response = await cfn.send(new DescribeStacksCommand({ StackName: stack })); + return Object.fromEntries( + (response.Stacks?.[0]?.Outputs ?? []) + .filter((output) => output.ExportName?.endsWith("-RuntimeId")) + .map((output) => [output.ExportName!, output.OutputValue!]), + ); + } + + async function assertNoBuilder(stack: string) { + const response = await cfn.send(new GetTemplateCommand({ StackName: stack })); + const template = JSON.parse(response.TemplateBody!) as { + Resources: Record; + }; + const types = Object.values(template.Resources).map((resource) => resource.Type); + expect(types).not.toContain("AWS::CodeBuild::Project"); + expect(types).not.toContain("AWS::ECR::Repository"); + expect(types.every((type) => !type.startsWith("Custom::"))).toBe(true); + } + + async function cleanup(path: string) { + parseResult(operationSchema, await cli.run(["remove", "all", "--yes", "--json"], path)); + parseResult(resultSchema, await cli.run(["deploy", "--yes", "--json"], path)); + } + + test.skipIf(!v1 || !digest || !v2)( + "tag, digest, named endpoint, image update, and stack teardown", + { timeout: 5 * TIMEOUT_MS.PROJECT_DEPLOY + 5 * TIMEOUT_MS.PROJECT_INVOKE }, + async () => { + const { path, stack } = await createProject(); + try { + await addImage(path, "tagged", v1!); + await addImage(path, "digest", digest!); + parseResult(resultSchema, await cli.run(["build", "--json"], path)); + parseResult(resultSchema, await cli.run(["deploy", "--yes", "--json"], path)); + await assertNoBuilder(stack); + await invoke(path, "tagged", "v1"); + await invoke(path, "digest", "v1"); + const idsBefore = await runtimeIds(stack); + + parseResult( + operationSchema, + await cli.run( + [ + "add", + "runtime-endpoint", + "--runtime", + "tagged", + "--name", + "stable", + "--version", + "1", + "--json", + ], + path, + ), + ); + const specPath = join(path, "agentcore", "agentcore.json"); + const spec = JSON.parse(await readFile(specPath, "utf8")); + spec.runtimes.find((runtime: { name: string }) => runtime.name === "tagged").containerUri = + v2; + await writeFile(specPath, JSON.stringify(spec, null, 2)); + parseResult(resultSchema, await cli.run(["deploy", "--yes", "--json"], path)); + expect(await runtimeIds(stack)).toEqual(idsBefore); + await assertNoBuilder(stack); + await invoke(path, "tagged", "v2"); + await invoke(path, "digest", "v1"); + await invoke(path, "tagged", "v1", "stable"); + } finally { + await cleanup(path); + } + }, + ); + + test.skipIf(!publicUri)( + "an existing public ECR image deploys and invokes without a build", + { timeout: 2 * TIMEOUT_MS.PROJECT_DEPLOY + TIMEOUT_MS.PROJECT_INVOKE }, + async () => { + const { path, stack } = await createProject(); + try { + await addImage(path, "public", publicUri!); + parseResult(resultSchema, await cli.run(["deploy", "--yes", "--json"], path)); + await assertNoBuilder(stack); + await invoke(path, "public", "v1"); + } finally { + await cleanup(path); + } + }, + ); +}); diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 69470a7025..6c2d2633d0 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -3,7 +3,7 @@ import * as fs from "node:fs"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { tmpdir } from "node:os"; -import type { Stack } from "@aws-sdk/client-cloudformation"; +import { ListStackResourcesCommand, type Stack } from "@aws-sdk/client-cloudformation"; import type { DeployResult, Project, ProjectEvent } from "../../../handlers/project/types"; import { FsReadWriteJson, ProcessFailedError } from "../../../io"; import { ProjectSpecSchema } from "../../../projectSchemas/project"; @@ -189,9 +189,12 @@ async function writeLocalImageManifest(p: Project): Promise { } type HarnessOptions = { + assertCdkFeatures?: CdkBackendConfig["assertCdkFeatures"]; deployedTemplate?: object | null; /** Thrown by GetTemplate instead of returning the deployed template. */ getTemplateError?: Error; + /** Resources ListStackResources reports for the deployed stack. */ + stackResources?: { ResourceType: string; PhysicalResourceId: string }[]; checkLocalBuilder?: CdkBackendConfig["checkLocalBuilder"]; resolveContainerExecutable?: CdkBackendConfig["resolveContainerExecutable"]; account?: string; @@ -242,10 +245,13 @@ function harness(options: HarnessOptions = {}) { const backend = new CdkBackend({ logger: createSilentLogger(), - assertLocalCdkSupport: () => {}, + assertCdkFeatures: options.assertCdkFeatures ?? (async () => {}), createCloudFormationClient: () => ({ - send: async () => { + send: async (command: unknown) => { + if (command instanceof ListStackResourcesCommand) { + return { StackResourceSummaries: options.stackResources ?? [] }; + } if (options.getTemplateError) throw options.getTemplateError; return { TemplateBody: @@ -510,6 +516,31 @@ describe("CdkBackend.build", () => { expect(message).toContain("Dockerfile: app/agent/Dockerfile.agent"); expect(message).toContain("COPY requirements.txt: not found"); }); + test("checks CDK support for a pre-built image Runtime and builds nothing locally", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "image", + build: "Container", + codeLocation: "app/image", + entrypoint: "main.py", + containerUri: "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1", + }), + ); + await writeAssembly(p, [TARGET.name]); + const probed: unknown[] = []; + const h = harness({ + assertCdkFeatures: async (_directory, features) => { + probed.push(features); + }, + resolveContainerExecutable: async () => { + throw new Error("must not detect a builder"); + }, + }); + await collect(h.backend.build(p)); + expect(probed).toEqual([["Runtime containerUri"]]); + expect(h.commands.map(({ command }) => command)).toEqual([synthCommand(p)]); + }); test("builds no images when no workload builds locally", async () => { const p = await project(); p.spec.runtimes.push( @@ -891,6 +922,64 @@ describe("CdkBackend.deploy", () => { expect(h.stackReads[0]?.stackName).toBe("CustomOrders"); expect(h.runs).toHaveLength(0); }); + describe("a deployed Container Runtime switching to a containerUri", () => { + const deployedContainerRuntime = { + Metadata: { "agentcore:builds": { "runtime/agent": "Container" } }, + Resources: { + AgentRepository: { + Type: "AWS::ECR::Repository", + Properties: { RepositoryName: { "Fn::Join": ["", ["example/", "agent"]] } }, + }, + }, + }; + const stackResources = [ + { ResourceType: "AWS::ECR::Repository", PhysicalResourceId: "example/default/agent" }, + ]; + async function switchedProject(containerUri: string) { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "agent", + build: "Container", + codeLocation: "app/agent", + entrypoint: "main.py", + containerUri, + }), + ); + await writeAssembly(p, [TARGET.name]); + return p; + } + + test("is rejected before any deploy when the image is in the repository the stack manages", async () => { + const p = await switchedProject( + `${TARGET.account}.dkr.ecr.${TARGET.region}.amazonaws.com/example/default/agent:latest`, + ); + const h = harness({ deployedTemplate: deployedContainerRuntime, stackResources }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "that image is in the ECR repository 'example/default/agent', which the CLI created for " + + "the Container build. This deploy deletes that repository and its images", + ); + expect(h.runs).toHaveLength(0); + }); + + test.each([ + [ + "another repository", + `${TARGET.account}.dkr.ecr.${TARGET.region}.amazonaws.com/mine/agent:v1`, + ], + ["another account", "444455556666.dkr.ecr.us-east-1.amazonaws.com/example/default/agent:v1"], + [ + "another region", + `${TARGET.account}.dkr.ecr.us-west-2.amazonaws.com/example/default/agent:v1`, + ], + ["public ECR", "public.ecr.aws/example/default/agent:v1"], + ])("is allowed for an image in %s", async (_case, containerUri) => { + const p = await switchedProject(containerUri); + const h = harness({ deployedTemplate: deployedContainerRuntime, stackResources }); + await collectDeploy(h.backend.deploy(p, deployInput())); + expect(h.runs.map(({ operation }) => operation.kind)).toContain("deploy"); + }); + }); test("inspects the live stack by name, not a recorded ARN of a deleted stack", async () => { const p = await project(); p.spec.runtimes.push( @@ -916,6 +1005,34 @@ describe("CdkBackend.deploy", () => { expect(h.stackReads[0]?.stackName).toBe("AgentCore-example-default-0"); expect(h.runs).toHaveLength(0); }); + test("checks CDK feature support before provisioning credentials", async () => { + const p = await project(); + p.spec.runtimes.push( + ProjectRuntimeSchema.parse({ + name: "image", + build: "Container", + codeLocation: "app/image", + entrypoint: "main.py", + containerUri: "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1", + }), + ); + let provisioned = false; + const h = harness({ + assertCdkFeatures: async () => { + throw new Error("CDK package lacks Runtime containerUri"); + }, + provisionCredentials: async function* () { + provisioned = true; + yield { type: "step", message: "provisioning credentials" }; + return {}; + }, + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "lacks Runtime containerUri", + ); + expect(provisioned).toBe(false); + expect(h.commands).toHaveLength(0); + }); test("refuses an unavailable local builder before provisioning credentials or invoking Toolkit", async () => { const p = await project(); p.spec.runtimes.push( diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 2b60f67fe9..14b466e89e 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -1,6 +1,10 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; -import { GetTemplateCommand, type Stack } from "@aws-sdk/client-cloudformation"; +import { + GetTemplateCommand, + ListStackResourcesCommand, + type Stack, +} from "@aws-sdk/client-cloudformation"; import { parse as parseYaml } from "yaml"; import { MalformedServiceResponseError, ProjectStateError } from "../../../errors/errors"; import type { @@ -15,13 +19,18 @@ import type { WorkloadBuilds, WorkloadKey, } from "../../../handlers/project/types"; -import { assertCdkLocalContainerSupport, cdkCompatibilityWarning } from "./cdk/compatibility"; +import { + assertCdkFeatureSupport, + cdkCompatibilityWarning, + cdkFeaturesFor, +} from "./cdk/compatibility"; import { assertSupportedBuildTransitions, byoExecutionRoleWarning, hasLocalContainerBuilds, resolveWorkloads, type DeployedTemplate, + type ManagedRepository, } from "./cdk/localContainers"; import { buildxDriverWarning, checkArm64Builder, selectBuildxBuilder } from "./cdk/arm64Builder"; import { localImageBuilds } from "./cdk/localImages"; @@ -172,7 +181,7 @@ export type CdkBackendConfig = { reportPaymentConnectorAuthorizationUrls?: PaymentConnectorAuthorizationUrlReporter; checkLocalBuilder?: typeof checkArm64Builder; resolveContainerExecutable?: () => Promise; - assertLocalCdkSupport?: typeof assertCdkLocalContainerSupport; + assertCdkFeatures?: typeof assertCdkFeatureSupport; }; // Stacks in these states hold no deployed workloads: deleted, rolled back after a @@ -211,7 +220,7 @@ export class CdkBackend implements ProjectBackend { private readonly reportPaymentConnectorAuthorizationUrls: PaymentConnectorAuthorizationUrlReporter; private readonly checkLocalBuilder: typeof checkArm64Builder; private readonly resolveContainerExecutable: () => Promise; - private readonly assertLocalCdkSupport: typeof assertCdkLocalContainerSupport; + private readonly assertCdkFeatures: typeof assertCdkFeatureSupport; private readonly createCloudFormationClient: CreateCloudFormationClient; constructor(config: CdkBackendConfig) { @@ -220,7 +229,7 @@ export class CdkBackend implements ProjectBackend { this.checkLocalBuilder = config.checkLocalBuilder ?? checkArm64Builder; this.resolveContainerExecutable = config.resolveContainerExecutable ?? (() => resolveCdkDockerExecutable()); - this.assertLocalCdkSupport = config.assertLocalCdkSupport ?? assertCdkLocalContainerSupport; + this.assertCdkFeatures = config.assertCdkFeatures ?? assertCdkFeatureSupport; this.createCloudFormationClient = config.createCloudFormationClient ?? createCloudFormationClient; this.checkTool = config.checkTool ?? requireTool; @@ -286,16 +295,12 @@ export class CdkBackend implements ProjectBackend { private async *synthesize( project: Project, explainUndeployedCredentials: boolean, - builds: WorkloadBuilds, ): AsyncGenerator { const compatibilityWarning = await cdkCompatibilityWarning(this.cdkDirectory(project)); if (compatibilityWarning) { yield { type: "warning", message: compatibilityWarning }; } - if (hasLocalContainerBuilds(builds)) { - this.assertLocalCdkSupport(this.cdkDirectory(project)); - } yield { type: "step", message: "synthesizing CloudFormation templates" }; try { yield* withOutputEvents((emit) => { @@ -331,7 +336,11 @@ export class CdkBackend implements ProjectBackend { ): AsyncGenerator { yield* this.ensureCdkDependencies(project, input); const { builds, local } = resolveWorkloads(project); - yield* this.synthesize(project, true, builds); + // An older CDK package would silently drop settings it does not know. + await this.assertCdkFeatures(this.cdkDirectory(project), cdkFeaturesFor(builds), this.runner, { + dependenciesManaged: !input.disableDependencyManagement, + }); + yield* this.synthesize(project, true); yield* this.buildLocalImages(project, builds, local); } @@ -418,8 +427,11 @@ export class CdkBackend implements ProjectBackend { // BUILDX_BUILDER chosen here, so the check runs on that same builder. let containerExecutable: string | undefined; let buildxBuilder: string | undefined; + // Before any AWS mutation: an older CDK package would silently drop settings. + await this.assertCdkFeatures(this.cdkDirectory(project), cdkFeaturesFor(builds), this.runner, { + dependenciesManaged: !input.disableDependencyManagement, + }); if (hasLocalContainerBuilds(builds)) { - this.assertLocalCdkSupport(this.cdkDirectory(project)); containerExecutable = await this.resolveContainerExecutable(); yield { type: "step", @@ -464,7 +476,8 @@ export class CdkBackend implements ProjectBackend { resources: { credentials: provisioned }, }); - yield* this.synthesize(project, false, builds); + // The CDK features were checked before provisioning, above. + yield* this.synthesize(project, false); const assemblyDirectory = this.assemblyDirectory(project); const artifact = await stackArtifactForTarget(this.json, assemblyDirectory, target.name); // Checked against the stack this deploy is about to update, before teardown @@ -898,7 +911,8 @@ export class CdkBackend implements ProjectBackend { /** * Rejects switching a deployed workload into or out of ContainerLocal, or a - * deployed Runtime between CodeZip and Container. + * deployed Runtime between CodeZip and Container, or from Container to a + * containerUri in an ECR repository the stack manages (this deploy deletes it). * Reads the live template of the synthesized stack, looked up by name (never by * a recorded ARN, which can point at a deleted stack), after synthesis and * before the stack is touched. Credential providers are already provisioned. @@ -913,13 +927,15 @@ export class CdkBackend implements ProjectBackend { stackName: string, ): Promise { let template: string | undefined; + let deployedStackName = stackName; try { const stack = await this.describeStack(target.region, credentials, stackName); if (!stack || NOT_DEPLOYED_STACK_STATUSES.has(stack.StackStatus ?? "")) return undefined; + deployedStackName = stack.StackId ?? stackName; const client = this.createCloudFormationClient({ region: target.region, credentials }); const previous = await client.send( new GetTemplateCommand({ - StackName: stack.StackId ?? stackName, + StackName: deployedStackName, TemplateStage: "Original", }), ); @@ -941,15 +957,67 @@ export class CdkBackend implements ProjectBackend { "Cannot verify build modes: the deployed stack template is unavailable.", ); } + const deployed = parseYaml(template) as DeployedTemplate; + const containerUris = Object.fromEntries( + project.spec.runtimes.flatMap(({ name, containerUri }) => + containerUri ? [[`runtime/${name}`, containerUri]] : [], + ), + ); assertSupportedBuildTransitions( - parseYaml(template) as DeployedTemplate, + deployed, builds, project.name, project.spec.migratedFrom ? undefined : target.name, + { + containerUris, + managedRepositories: Object.keys(containerUris).length + ? await this.managedRepositories(deployed, target, credentials, deployedStackName) + : [], + }, ); return undefined; } + /** + * The ECR repositories the deployed stack creates: their physical names from + * ListStackResources, plus any literal RepositoryName in the template, which + * is all there is when the credentials cannot list the stack's resources. + */ + private async managedRepositories( + template: DeployedTemplate, + target: AwsDeploymentTarget, + credentials: CdkCredentialProvider, + stackName: string, + ): Promise { + const repositories = Object.values(template.Resources ?? {}).filter( + (resource) => resource.Type === "AWS::ECR::Repository", + ); + if (!repositories.length) return []; + const names = new Set(); + for (const repository of repositories) { + const name = repository.Properties?.RepositoryName; + if (typeof name === "string") names.add(name); + } + try { + const client = this.createCloudFormationClient({ region: target.region, credentials }); + let token: string | undefined; + do { + const page = await client.send( + new ListStackResourcesCommand({ StackName: stackName, NextToken: token }), + ); + for (const resource of page.StackResourceSummaries ?? []) { + if (resource.ResourceType === "AWS::ECR::Repository" && resource.PhysicalResourceId) { + names.add(resource.PhysicalResourceId); + } + } + token = page.NextToken; + } while (token); + } catch (error) { + if (!isAuthorizationError(error)) throw error; + } + return [...names].map((name) => ({ account: target.account, region: target.region, name })); + } + private async credentialsForTarget(target: AwsDeploymentTarget) { const credentials = await this.resolveCredentials(target.region); const account = await this.resolveAccount(target.region, credentials); diff --git a/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.assets.json b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.assets.json new file mode 100644 index 0000000000..b3a7a1b8db --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.assets.json @@ -0,0 +1,65 @@ +{ + "version": "54.0.0", + "files": { + "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c": { + "displayName": "Application/RuntimeBilling/ContainerSourceAsset/SourceAsset", + "source": { + "path": "asset.cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c", + "packaging": "zip" + }, + "destinations": { + "current_account-current_region-4443d752": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c.zip", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "7b1ec9dcb8e710b31b67727fc1c277eaccfa62270f7df4bba3694d07fa83bca7": { + "displayName": "AgentCore-Fixture Template", + "source": { + "path": "AgentCore-Fixture.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region-758cc26a": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "7b1ec9dcb8e710b31b67727fc1c277eaccfa62270f7df4bba3694d07fa83bca7.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": { + "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e": { + "displayName": "Application/RuntimeOrders/LocalContainerImage/Image", + "source": { + "directory": "asset.b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "dockerFile": "Dockerfile", + "platform": "linux/arm64" + }, + "destinations": { + "current_account-current_region-e3460c4d": { + "repositoryName": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}", + "imageTag": "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-image-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624": { + "displayName": "Application/HarnessAssistant/LocalContainerImage/Image", + "source": { + "directory": "asset.312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624", + "dockerFile": "Dockerfile", + "platform": "linux/arm64" + }, + "destinations": { + "current_account-current_region-56e3b610": { + "repositoryName": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}", + "imageTag": "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-image-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + } +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.template.json b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.template.json new file mode 100644 index 0000000000..67153d8d9c --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/AgentCore-Fixture.template.json @@ -0,0 +1,2087 @@ +{ + "Description": "AgentCore stack for Fixture (no deployment target configured)", + "Metadata": { + "agentcore:builds": { + "runtime/orders": "ContainerLocal", + "runtime/billing": "Container", + "runtime/image": "ContainerUri", + "harness/assistant": "ContainerLocal" + }, + "agentcore:localImages": { + "runtime/orders": "b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e", + "harness/assistant": "312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + }, + "Resources": { + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":runtime/Fixture_orders*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "Execution role for Bedrock Agent Core Runtime", + "MaxSessionDuration": 28800 + } + }, + "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:DescribeLogStreams", + "logs:CreateLogGroup" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "LogGroupAccess" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "DescribeLogGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "LogStreamAccess" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayAccess" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetrics" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT", + "bedrock-agentcore:GetWorkloadAccessTokenForUserId" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/*" + ] + ] + } + ], + "Sid": "GetAgentAccessToken" + }, + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:CountTokens" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*:", + { + "Ref": "AWS::AccountId" + }, + ":inference-profile/*" + ] + ] + } + ] + }, + { + "Action": [ + "logs:GetLogEvents", + "logs:FilterLogEvents", + "logs:PutResourcePolicy" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + } + }, + { + "Action": [ + "bedrock-agentcore:GetConfigurationBundle", + "bedrock-agentcore:GetConfigurationBundleVersion", + "bedrock-agentcore:ListConfigurationBundles", + "bedrock-agentcore:ListConfigurationBundleVersions", + "bedrock-agentcore:CreateConfigurationBundle", + "bedrock-agentcore:UpdateConfigurationBundle", + "bedrock-agentcore:DeleteConfigurationBundle" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:*:*:configuration-bundle/*" + ] + ] + } + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "ecr:BatchGetImage", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ecr:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":repository/", + { + "Fn::Sub": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360", + "Roles": [ + { + "Ref": "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC" + } + ] + } + }, + "ApplicationRuntimeOrdersRuntimeACF3F5A3": { + "Type": "AWS::BedrockAgentCore::Runtime", + "Properties": { + "AgentRuntimeArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:b418ebb81dba09fd5bd243309dc187c231c9f8ae8396e578aec20d56b26dc08e" + } + } + }, + "AgentRuntimeName": "Fixture_orders", + "Description": "AgentCore Runtime: Fixture_orders", + "LifecycleConfiguration": {}, + "NetworkConfiguration": { + "NetworkMode": "PUBLIC" + }, + "ProtocolConfiguration": "HTTP", + "RoleArn": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC", + "Arn" + ] + } + }, + "DependsOn": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleDefaultPolicy76731360", + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC" + ] + }, + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400": { + "Type": "AWS::KMS::Key", + "Properties": { + "Description": "ECR encryption key for fixture/billing", + "EnableKeyRotation": true, + "KeyPolicy": { + "Statement": [ + { + "Action": "kms:*", + "Effect": "Allow", + "Principal": { + "AWS": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::", + { + "Ref": "AWS::AccountId" + }, + ":root" + ] + ] + } + }, + "Resource": "*" + } + ], + "Version": "2012-10-17" + } + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingContainerRepositoryD276BA4F": { + "Type": "AWS::ECR::Repository", + "Properties": { + "EmptyOnDelete": true, + "EncryptionConfiguration": { + "EncryptionType": "KMS", + "KmsKey": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400", + "Arn" + ] + } + }, + "ImageScanningConfiguration": { + "ScanOnPush": true + }, + "LifecyclePolicy": { + "LifecyclePolicyText": "{\"rules\":[{\"rulePriority\":1,\"description\":\"Keep last 10 images\",\"selection\":{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":10},\"action\":{\"type\":\"expire\"}}]}" + }, + "RepositoryName": "fixture/billing" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ] + ] + } + ] + } + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "codebuild:StartBuild", + "codebuild:BatchGetBuilds" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ContainerBuildProject5A4F8922", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "Roles": [ + { + "Ref": "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48" + } + ] + } + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "ZipFile": "\nconst { CodeBuildClient, StartBuildCommand, BatchGetBuildsCommand } = require('@aws-sdk/client-codebuild');\nconst codebuild = new CodeBuildClient();\n\nexports.handler = async function(event, context) {\n const props = event.ResourceProperties;\n const requestType = event.RequestType;\n\n // Build the response object\n const response = {\n Status: 'SUCCESS',\n PhysicalResourceId: props.ImageUri || 'container-build',\n StackId: event.StackId,\n RequestId: event.RequestId,\n LogicalResourceId: event.LogicalResourceId,\n Data: {},\n };\n\n try {\n if (requestType === 'Delete') {\n response.Data = {};\n await sendResponse(event, response);\n return;\n }\n\n // Docker build args: forward each as its own build environment variable and reference it with\n // '--build-arg NAME' (no value), so docker inherits the value from the environment. This keeps\n // arbitrary values off the shell command line (no quoting/word-splitting hazards). BUILD_ARG_FLAGS\n // is the space-separated flag list the buildspec interpolates; it is empty when there are no args.\n const buildArgs = props.BuildArgs ? JSON.parse(props.BuildArgs) : {};\n const buildArgNames = Object.keys(buildArgs);\n const buildArgEnv = buildArgNames.map(name => ({ name, value: String(buildArgs[name]), type: 'PLAINTEXT' }));\n const buildArgFlags = buildArgNames.map(name => '--build-arg ' + name).join(' ');\n\n // Start CodeBuild\n const startResult = await codebuild.send(new StartBuildCommand({\n projectName: props.ProjectName,\n sourceTypeOverride: 'S3',\n sourceLocationOverride: props.SourceBucket + '/' + props.SourceKey,\n environmentVariablesOverride: [\n { name: 'ECR_REGISTRY', value: props.EcrRegistry, type: 'PLAINTEXT' },\n { name: 'IMAGE_URI', value: props.ImageUri, type: 'PLAINTEXT' },\n { name: 'DOCKERFILE_PATH', value: props.DockerfilePath, type: 'PLAINTEXT' },\n { name: 'BUILD_ARG_FLAGS', value: buildArgFlags, type: 'PLAINTEXT' },\n ...buildArgEnv,\n ],\n }));\n\n const buildId = startResult.build.id;\n console.log('Started build:', buildId);\n\n // Poll until complete (14 minutes max to stay within Lambda's 15-minute timeout)\n const maxWaitMs = 14 * 60 * 1000;\n const start = Date.now();\n while (Date.now() - start < maxWaitMs) {\n const result = await codebuild.send(new BatchGetBuildsCommand({ ids: [buildId] }));\n const build = result.builds[0];\n if (build.buildStatus !== 'IN_PROGRESS') {\n if (build.buildStatus === 'SUCCEEDED') {\n response.Data = { ContainerUri: props.ImageUri };\n await sendResponse(event, response);\n return;\n } else {\n const logsUrl = build.logs && build.logs.deepLink ? build.logs.deepLink : 'Check CloudWatch Logs';\n response.Status = 'FAILED';\n response.Reason = 'CodeBuild build failed. Status: ' + build.buildStatus + '. Logs: ' + logsUrl;\n await sendResponse(event, response);\n return;\n }\n }\n await new Promise(r => setTimeout(r, 10000));\n }\n\n response.Status = 'FAILED';\n response.Reason = 'Build timed out after 14 minutes';\n await sendResponse(event, response);\n } catch (err) {\n response.Status = 'FAILED';\n response.Reason = err.message || 'Unknown error';\n await sendResponse(event, response);\n }\n};\n\nasync function sendResponse(event, response) {\n const https = require('https');\n const responseBody = JSON.stringify(response);\n const parsedUrl = new URL(event.ResponseURL);\n const options = {\n hostname: parsedUrl.hostname,\n port: 443,\n path: parsedUrl.pathname + parsedUrl.search,\n method: 'PUT',\n headers: { 'content-type': '', 'content-length': responseBody.length },\n };\n return new Promise((resolve, reject) => {\n const req = https.request(options, resolve);\n req.on('error', reject);\n req.write(responseBody);\n req.end();\n });\n}\n" + }, + "Handler": "index.handler", + "MemorySize": 256, + "Role": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "Arn" + ] + }, + "Runtime": "nodejs22.x", + "Timeout": 900 + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48" + ] + }, + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F": { + "Type": "AWS::CloudFormation::CustomResource", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "Arn" + ] + }, + "ProjectName": { + "Ref": "ContainerBuildProject5A4F8922" + }, + "SourceBucket": { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "SourceKey": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c.zip", + "ImageUri": { + "Fn::Join": [ + "", + [ + { + "Fn::Select": [ + 4, + { + "Fn::Split": [ + ":", + { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + ] + } + ] + }, + ".dkr.ecr.", + { + "Fn::Select": [ + 3, + { + "Fn::Split": [ + ":", + { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + ] + } + ] + }, + ".", + { + "Ref": "AWS::URLSuffix" + }, + "/", + { + "Ref": "ApplicationRuntimeBillingContainerRepositoryD276BA4F" + }, + ":cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c" + ] + ] + }, + "DockerfilePath": "Dockerfile", + "EcrRegistry": { + "Fn::Join": [ + "", + [ + { + "Ref": "AWS::AccountId" + }, + ".dkr.ecr.", + { + "Ref": "AWS::Region" + }, + ".", + { + "Ref": "AWS::URLSuffix" + } + ] + ] + }, + "SourceHash": "cc27b6ff04dc894279081033893efad16fb5f9031cb6c33727543f56ec2edf6c" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":runtime/Fixture_billing*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "Execution role for Bedrock Agent Core Runtime", + "MaxSessionDuration": 28800 + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F" + ] + }, + "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:DescribeLogStreams", + "logs:CreateLogGroup" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "LogGroupAccess" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "DescribeLogGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "LogStreamAccess" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayAccess" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetrics" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT", + "bedrock-agentcore:GetWorkloadAccessTokenForUserId" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/*" + ] + ] + } + ], + "Sid": "GetAgentAccessToken" + }, + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:CountTokens" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*:", + { + "Ref": "AWS::AccountId" + }, + ":inference-profile/*" + ] + ] + } + ] + }, + { + "Action": [ + "logs:GetLogEvents", + "logs:FilterLogEvents", + "logs:PutResourcePolicy" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + } + }, + { + "Action": [ + "bedrock-agentcore:GetConfigurationBundle", + "bedrock-agentcore:GetConfigurationBundleVersion", + "bedrock-agentcore:ListConfigurationBundles", + "bedrock-agentcore:ListConfigurationBundleVersions", + "bedrock-agentcore:CreateConfigurationBundle", + "bedrock-agentcore:UpdateConfigurationBundle", + "bedrock-agentcore:DeleteConfigurationBundle" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:*:*:configuration-bundle/*" + ] + ] + } + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "ecr:BatchGetImage", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + }, + { + "Action": "kms:Decrypt", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryEncryptionKey6FF9F400", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC", + "Roles": [ + { + "Ref": "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19" + } + ] + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F" + ] + }, + "ApplicationRuntimeBillingRuntime3CC6043B": { + "Type": "AWS::BedrockAgentCore::Runtime", + "Properties": { + "AgentRuntimeArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F", + "ContainerUri" + ] + } + } + }, + "AgentRuntimeName": "Fixture_billing", + "Description": "AgentCore Runtime: Fixture_billing", + "LifecycleConfiguration": {}, + "NetworkConfiguration": { + "NetworkMode": "PUBLIC" + }, + "ProtocolConfiguration": "HTTP", + "RoleArn": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19", + "Arn" + ] + } + }, + "DependsOn": [ + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandler61CCAB6F", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRoleDefaultPolicyC42F517C", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildHandlerServiceRole13C12C48", + "ApplicationRuntimeBillingContainerImageBuilderContainerBuildTrigger9F6BC73F", + "ApplicationRuntimeBillingRuntimeExecutionRoleDefaultPolicyA3FC57FC", + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19" + ] + }, + "ApplicationRuntimeImageRuntimeExecutionRoleBEE688F0": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":runtime/Fixture_image*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "Execution role for Bedrock Agent Core Runtime", + "MaxSessionDuration": 28800 + } + }, + "ApplicationRuntimeImageRuntimeExecutionRoleDefaultPolicyA40B963F": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:DescribeLogStreams", + "logs:CreateLogGroup" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "LogGroupAccess" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "DescribeLogGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "LogStreamAccess" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayAccess" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetrics" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT", + "bedrock-agentcore:GetWorkloadAccessTokenForUserId" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/*" + ] + ] + } + ], + "Sid": "GetAgentAccessToken" + }, + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + "bedrock:CountTokens" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*:", + { + "Ref": "AWS::AccountId" + }, + ":inference-profile/*" + ] + ] + } + ] + }, + { + "Action": [ + "logs:GetLogEvents", + "logs:FilterLogEvents", + "logs:PutResourcePolicy" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + } + }, + { + "Action": [ + "bedrock-agentcore:GetConfigurationBundle", + "bedrock-agentcore:GetConfigurationBundleVersion", + "bedrock-agentcore:ListConfigurationBundles", + "bedrock-agentcore:ListConfigurationBundleVersions", + "bedrock-agentcore:CreateConfigurationBundle", + "bedrock-agentcore:UpdateConfigurationBundle", + "bedrock-agentcore:DeleteConfigurationBundle" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:*:*:configuration-bundle/*" + ] + ] + } + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "ecr:BatchGetImage", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ecr:us-west-2:123456789012:repository/agent" + ] + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationRuntimeImageRuntimeExecutionRoleDefaultPolicyA40B963F", + "Roles": [ + { + "Ref": "ApplicationRuntimeImageRuntimeExecutionRoleBEE688F0" + } + ] + } + }, + "ApplicationRuntimeImageRuntime4FFD55D6": { + "Type": "AWS::BedrockAgentCore::Runtime", + "Properties": { + "AgentRuntimeArtifact": { + "ContainerConfiguration": { + "ContainerUri": "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1" + } + }, + "AgentRuntimeName": "Fixture_image", + "Description": "AgentCore Runtime: Fixture_image", + "LifecycleConfiguration": {}, + "NetworkConfiguration": { + "NetworkMode": "PUBLIC" + }, + "ProtocolConfiguration": "HTTP", + "RoleArn": { + "Fn::GetAtt": [ + "ApplicationRuntimeImageRuntimeExecutionRoleBEE688F0", + "Arn" + ] + } + }, + "DependsOn": [ + "ApplicationRuntimeImageRuntimeExecutionRoleDefaultPolicyA40B963F", + "ApplicationRuntimeImageRuntimeExecutionRoleBEE688F0" + ] + }, + "ApplicationHarnessAssistantRoleExecutionRole1A384D55": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "aws:SourceAccount": { + "Ref": "AWS::AccountId" + } + }, + "ArnLike": { + "aws:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":*" + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "bedrock-agentcore.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Description": "AgentCore Harness assistant execution role" + } + }, + "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:*::foundation-model/*" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":*" + ] + ] + } + ], + "Sid": "BedrockModelInvocation" + }, + { + "Action": "ecr-public:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "EcrPublicTokenAccess" + }, + { + "Action": "sts:GetServiceBearerToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "StsForEcrPublicPull" + }, + { + "Action": [ + "xray:PutTraceSegments", + "xray:PutTelemetryRecords", + "xray:GetSamplingRules", + "xray:GetSamplingTargets" + ], + "Effect": "Allow", + "Resource": "*", + "Sid": "XRayTracingAccess" + }, + { + "Action": [ + "logs:CreateLogGroup", + "logs:DescribeLogStreams" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*" + ] + ] + }, + "Sid": "CloudWatchLogsGroup" + }, + { + "Action": "logs:DescribeLogGroups", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:*" + ] + ] + }, + "Sid": "CloudWatchLogsDescribeGroups" + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*" + ] + ] + }, + "Sid": "CloudWatchLogsStream" + }, + { + "Action": "cloudwatch:PutMetricData", + "Condition": { + "StringEquals": { + "cloudwatch:namespace": "bedrock-agentcore" + } + }, + "Effect": "Allow", + "Resource": "*", + "Sid": "CloudWatchMetricsPublish" + }, + { + "Action": [ + "bedrock-agentcore:GetWorkloadAccessToken", + "bedrock-agentcore:GetWorkloadAccessTokenForJWT" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock-agentcore:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":workload-identity-directory/default/workload-identity/harness_Fixture_assistant-*" + ] + ] + } + ], + "Sid": "AgentCoreWorkloadIdentity" + }, + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*", + "Sid": "ECRTokenAccess" + }, + { + "Action": [ + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:BatchCheckLayerAvailability" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ecr:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":repository/", + { + "Fn::Sub": "cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + }, + "Sid": "ECRImageAccess" + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13", + "Roles": [ + { + "Ref": "ApplicationHarnessAssistantRoleExecutionRole1A384D55" + } + ] + } + }, + "ApplicationHarnessAssistantHarness1F2A9185": { + "Type": "AWS::BedrockAgentCore::Harness", + "Properties": { + "EnvironmentArtifact": { + "ContainerConfiguration": { + "ContainerUri": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + } + }, + "ExecutionRoleArn": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantRoleExecutionRole1A384D55", + "Arn" + ] + }, + "HarnessName": "Fixture_assistant", + "Memory": { + "Disabled": {} + }, + "Model": { + "BedrockModelConfig": { + "ModelId": "global.anthropic.claude-sonnet-4-6" + } + } + }, + "DependsOn": [ + "ApplicationHarnessAssistantRoleExecutionRoleDefaultPolicy21682F13", + "ApplicationHarnessAssistantRoleExecutionRole1A384D55" + ] + }, + "ContainerBuildProjectContainerBuildExecutionRole69AD3217": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "codebuild.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + } + } + }, + "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": "ecr:GetAuthorizationToken", + "Effect": "Allow", + "Resource": "*" + }, + { + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":log-group:/aws/codebuild/*" + ] + ] + } + }, + { + "Action": [ + "ecr:BatchCheckLayerAvailability", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:CompleteLayerUpload", + "ecr:UploadLayerPart", + "ecr:InitiateLayerUpload", + "ecr:PutImage" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingContainerRepositoryD276BA4F", + "Arn" + ] + } + }, + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::", + { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + } + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::", + { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "/*" + ] + ] + } + ] + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239", + "Roles": [ + { + "Ref": "ContainerBuildProjectContainerBuildExecutionRole69AD3217" + } + ] + } + }, + "ContainerBuildProject5A4F8922": { + "Type": "AWS::CodeBuild::Project", + "Properties": { + "Artifacts": { + "Type": "NO_ARTIFACTS" + }, + "Cache": { + "Modes": [ + "LOCAL_DOCKER_LAYER_CACHE" + ], + "Type": "LOCAL" + }, + "EncryptionKey": "alias/aws/s3", + "Environment": { + "ComputeType": "BUILD_GENERAL1_SMALL", + "Image": "aws/codebuild/amazonlinux-aarch64-standard:3.0", + "ImagePullCredentialsType": "CODEBUILD", + "PrivilegedMode": true, + "Type": "ARM_CONTAINER" + }, + "Name": "AgentCore-Fixture-container-builder", + "ServiceRole": { + "Fn::GetAtt": [ + "ContainerBuildProjectContainerBuildExecutionRole69AD3217", + "Arn" + ] + }, + "Source": { + "BuildSpec": "{\n \"version\": \"0.2\",\n \"phases\": {\n \"pre_build\": {\n \"commands\": [\n \"echo \\\"Logging in to Amazon ECR...\\\"\",\n \"aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $ECR_REGISTRY\"\n ]\n },\n \"build\": {\n \"commands\": [\n \"echo \\\"Building container image...\\\"\",\n \"docker build -t $IMAGE_URI -f $DOCKERFILE_PATH $BUILD_ARG_FLAGS .\"\n ]\n },\n \"post_build\": {\n \"commands\": [\n \"echo \\\"Pushing image to ECR...\\\"\",\n \"docker push $IMAGE_URI\",\n \"echo \\\"Image pushed: $IMAGE_URI\\\"\"\n ]\n }\n }\n}", + "Type": "NO_SOURCE" + }, + "TimeoutInMinutes": 30 + }, + "DependsOn": [ + "ContainerBuildProjectContainerBuildExecutionRoleDefaultPolicyE43AE239", + "ContainerBuildProjectContainerBuildExecutionRole69AD3217" + ] + } + }, + "Outputs": { + "ApplicationRuntimeOrdersRuntimeIdOutput16125101": { + "Description": "Runtime ID for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeACF3F5A3", + "AgentRuntimeId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RuntimeId" + } + }, + "ApplicationRuntimeOrdersRuntimeArnOutputFC642947": { + "Description": "Runtime ARN for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeACF3F5A3", + "AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RuntimeArn" + } + }, + "ApplicationRuntimeOrdersRoleArnOutputC7A8CEC9": { + "Description": "Execution Role ARN for: orders", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeOrdersRuntimeExecutionRoleA14806EC", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-orders-RoleArn" + } + }, + "ApplicationRuntimeBillingRuntimeIdOutputBCE2E749": { + "Description": "Runtime ID for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntime3CC6043B", + "AgentRuntimeId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RuntimeId" + } + }, + "ApplicationRuntimeBillingRuntimeArnOutputB69FF2F2": { + "Description": "Runtime ARN for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntime3CC6043B", + "AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RuntimeArn" + } + }, + "ApplicationRuntimeBillingRoleArnOutputC3A2D95A": { + "Description": "Execution Role ARN for: billing", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeBillingRuntimeExecutionRole70B57E19", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-billing-RoleArn" + } + }, + "ApplicationRuntimeImageRuntimeIdOutput1D86D040": { + "Description": "Runtime ID for: image", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeImageRuntime4FFD55D6", + "AgentRuntimeId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-image-RuntimeId" + } + }, + "ApplicationRuntimeImageRuntimeArnOutput5EF567F2": { + "Description": "Runtime ARN for: image", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeImageRuntime4FFD55D6", + "AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-image-RuntimeArn" + } + }, + "ApplicationRuntimeImageRoleArnOutput1C80DAEF": { + "Description": "Execution Role ARN for: image", + "Value": { + "Fn::GetAtt": [ + "ApplicationRuntimeImageRuntimeExecutionRoleBEE688F0", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-image-RoleArn" + } + }, + "ApplicationHarnessAssistantImageUriOutput444CA041": { + "Description": "Container image URI for harness \"assistant\"", + "Value": { + "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/cdk-hnb659fds-container-assets-${AWS::AccountId}-${AWS::Region}:312890e9c6b30db7140a9db65b441447cec73a6a420ad53b95972974e99aa624" + } + }, + "ApplicationHarnessAssistantRoleRoleArnOutput0DE2C07F": { + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantRoleExecutionRole1A384D55", + "Arn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-RoleArn" + } + }, + "ApplicationHarnessAssistantIdOutputBA102026": { + "Description": "Harness ID for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "HarnessId" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Id" + } + }, + "ApplicationHarnessAssistantArnOutput31DCA32F": { + "Description": "Harness ARN for: assistant", + "Value": { + "Ref": "ApplicationHarnessAssistantHarness1F2A9185" + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Arn" + } + }, + "ApplicationHarnessAssistantStatusOutput0CFD8979": { + "Description": "Harness status for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Status" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Status" + } + }, + "ApplicationHarnessAssistantVersionOutputBBE292E0": { + "Description": "Harness config version for: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Version" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-Version" + } + }, + "ApplicationHarnessAssistantAgentRuntimeArnOutput6F4D9700": { + "Description": "Underlying AgentCore Runtime ARN for harness: assistant", + "Value": { + "Fn::GetAtt": [ + "ApplicationHarnessAssistantHarness1F2A9185", + "Environment.AgentCoreRuntimeEnvironment.AgentRuntimeArn" + ] + }, + "Export": { + "Name": "AgentCore-Fixture-Harness-assistant-AgentRuntimeArn" + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/README.md b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/README.md new file mode 100644 index 0000000000..69257ea140 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/README.md @@ -0,0 +1,30 @@ +# Pre-built Runtime assembly fixture + +A real cloud assembly synthesized by `@aws/agentcore-cdk` with ContainerLocal +(aws/agentcore-l3-cdk-constructs#463) and Runtime `containerUri` (#440) support, from the +`agentcore.json` in this directory. Tests read it to pin how the CDK package records a pre-built +image Runtime: `"runtime/image": "ContainerUri"` in `agentcore:builds`, with no +`agentcore:localImages` entry, and the image URI used as is. + +The project has no deployment targets, so it synthesized one stack, `AgentCore-Fixture`: + +- Runtime `orders`: `build: ContainerLocal` +- Runtime `billing`: `build: Container` (CodeBuild) +- Runtime `image`: `build: Container` with `containerUri` +- Harness `assistant`: `build: ContainerLocal` + +Only `agentcore.json`, `manifest.json`, the stack template, and the asset manifest are kept; +`manifest.json` still references `tree.json` and the stack's `*.metadata.json`, which the CLI +does not read. + +## Regenerating + +1. In a checkout of aws/agentcore-l3-cdk-constructs with both features, run + `npm run build && npm pack`. +2. Create an AgentCore project with this directory's `agentcore.json` (and empty + `aws-targets.json`), with a Dockerfile in `app/orders`, `app/billing`, and `app/assistant`, and + the harness `app/assistant/harness.yaml` (`build: ContainerLocal`, `dockerfile: Dockerfile`). +3. In its `agentcore/cdk/` directory, install the packed tarball with the `aws-cdk-lib` and + `constructs` versions it requires, and synthesize the vended app. +4. Copy `manifest.json`, `AgentCore-Fixture.template.json`, and `AgentCore-Fixture.assets.json` + from the output directory here. diff --git a/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/agentcore.json b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/agentcore.json new file mode 100644 index 0000000000..a20f63e8f3 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/agentcore.json @@ -0,0 +1,19 @@ +{ + "name": "Fixture", + "version": 2, + "managedBy": "CDK", + "runtimes": [ + { "name": "orders", "build": "ContainerLocal", "codeLocation": "app/orders", "entrypoint": "main.py" }, + { "name": "billing", "build": "Container", "codeLocation": "app/billing", "entrypoint": "main.py" }, + { "name": "image", "build": "Container", "codeLocation": "app/image", "entrypoint": "main.py", "containerUri": "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1" } + ], + "memories": [], + "knowledgeBases": [], + "credentials": [], + "evaluators": [], + "onlineEvalConfigs": [], + "agentCoreGateways": [], + "policyEngines": [], + "configBundles": [], + "harnesses": [{ "name": "assistant", "path": "app/assistant" }] +} diff --git a/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/manifest.json b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/manifest.json new file mode 100644 index 0000000000..4c3adbc366 --- /dev/null +++ b/src/core/project/backends/cdk/__fixtures__/prebuilt-runtime/manifest.json @@ -0,0 +1,511 @@ +{ + "version": "54.0.0", + "artifacts": { + "AgentCore-Fixture.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "AgentCore-Fixture.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "AgentCore-Fixture": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "AgentCore-Fixture.template.json", + "terminationProtection": false, + "tags": { + "agentcore:project-name": "Fixture" + }, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/7b1ec9dcb8e710b31b67727fc1c277eaccfa62270f7df4bba3694d07fa83bca7.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "AgentCore-Fixture.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "AgentCore-Fixture.assets" + ], + "additionalMetadataFile": "AgentCore-Fixture.metadata.json", + "displayName": "AgentCore-Fixture" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + }, + "aws-cdk-lib/feature-flag-report": { + "type": "cdk:feature-flag-report", + "properties": { + "module": "aws-cdk-lib", + "flags": { + "@aws-cdk/aws-signer:signingProfileNamePassedToCfn": { + "recommendedValue": true, + "explanation": "Pass signingProfileName to CfnSigningProfile" + }, + "@aws-cdk/core:newStyleStackSynthesis": { + "recommendedValue": true, + "explanation": "Switch to new stack synthesis method which enables CI/CD", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:stackRelativeExports": { + "recommendedValue": true, + "explanation": "Name exports based on the construct paths relative to the stack, rather than the global construct path", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:secGroupsDisablesImplicitOpenListener": { + "recommendedValue": true, + "explanation": "Disable implicit openListener when custom security groups are provided" + }, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": { + "recommendedValue": true, + "explanation": "Force lowercasing of RDS Cluster names in CDK", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": { + "recommendedValue": true, + "explanation": "Allow adding/removing multiple UsagePlanKeys independently", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeVersionProps": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeLayerVersion": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`." + }, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have cloudfront distributions use the security policy TLSv1.2_2021 by default.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:checkSecretUsage": { + "recommendedValue": true, + "explanation": "Enable this flag to make it impossible to accidentally use SecretValues in unsafe locations" + }, + "@aws-cdk/core:target-partitions": { + "recommendedValue": [ + "aws", + "aws-cn" + ], + "explanation": "What regions to include in lookup tables of environment agnostic stacks" + }, + "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": { + "recommendedValue": true, + "explanation": "ECS extensions will automatically add an `awslogs` driver if no logging is specified" + }, + "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have Launch Templates generated by the `InstanceRequireImdsv2Aspect` use unique names." + }, + "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": { + "recommendedValue": true, + "explanation": "ARN format used by ECS. In the new ARN format, the cluster name is part of the resource ID." + }, + "@aws-cdk/aws-iam:minimizePolicies": { + "recommendedValue": true, + "explanation": "Minimize IAM policies by combining Statements" + }, + "@aws-cdk/core:validateSnapshotRemovalPolicy": { + "recommendedValue": true, + "explanation": "Error on snapshot removal policies on resources that do not support it." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": { + "recommendedValue": true, + "explanation": "Generate key aliases that include the stack name" + }, + "@aws-cdk/aws-s3:createDefaultLoggingPolicy": { + "recommendedValue": true, + "explanation": "Enable this feature flag to create an S3 bucket policy by default in cases where an AWS service would automatically create the Policy if one does not exist." + }, + "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": { + "recommendedValue": true, + "explanation": "Restrict KMS key policy for encrypted Queues a bit more" + }, + "@aws-cdk/aws-apigateway:disableCloudWatchRole": { + "recommendedValue": true, + "explanation": "Make default CloudWatch Role behavior safe for multiple API Gateways in one environment" + }, + "@aws-cdk/core:enablePartitionLiterals": { + "recommendedValue": true, + "explanation": "Make ARNs concrete if AWS partition is known" + }, + "@aws-cdk/aws-events:eventsTargetQueueSameAccount": { + "recommendedValue": true, + "explanation": "Event Rules may only push to encrypted SQS queues in the same account" + }, + "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": { + "recommendedValue": true, + "explanation": "Avoid setting the \"ECS\" deployment controller when adding a circuit breaker" + }, + "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": { + "recommendedValue": true, + "explanation": "Enable this feature to create default policy names for imported roles that depend on the stack the role is in." + }, + "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": { + "recommendedValue": true, + "explanation": "Use S3 Bucket Policy instead of ACLs for Server Access Logging" + }, + "@aws-cdk/aws-route53-patters:useCertificate": { + "recommendedValue": true, + "explanation": "Use the official `Certificate` resource instead of `DnsValidatedCertificate`" + }, + "@aws-cdk/customresources:installLatestAwsSdkDefault": { + "recommendedValue": false, + "explanation": "Whether to install the latest SDK by default in AwsCustomResource" + }, + "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": { + "recommendedValue": true, + "explanation": "Use unique resource name for Database Proxy" + }, + "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": { + "recommendedValue": true, + "explanation": "Remove CloudWatch alarms from deployment group" + }, + "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": { + "recommendedValue": true, + "explanation": "Include authorizer configuration in the calculation of the API deployment logical ID." + }, + "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": { + "recommendedValue": true, + "explanation": "Define user data for a launch template by default when a machine image is provided." + }, + "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": { + "recommendedValue": true, + "explanation": "SecretTargetAttachments uses the ResourcePolicy of the attached Secret." + }, + "@aws-cdk/aws-redshift:columnId": { + "recommendedValue": true, + "explanation": "Whether to use an ID to track Redshift column changes" + }, + "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": { + "recommendedValue": true, + "explanation": "Enable AmazonEMRServicePolicy_v2 managed policies" + }, + "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": { + "recommendedValue": true, + "explanation": "Restrict access to the VPC default security group" + }, + "@aws-cdk/aws-apigateway:requestValidatorUniqueId": { + "recommendedValue": true, + "explanation": "Generate a unique id for each RequestValidator added to a method" + }, + "@aws-cdk/aws-kms:aliasNameRef": { + "recommendedValue": true, + "explanation": "KMS Alias name and keyArn will have implicit reference to KMS Key" + }, + "@aws-cdk/aws-kms:applyImportedAliasPermissionsToPrincipal": { + "recommendedValue": true, + "explanation": "Enable grant methods on Aliases imported by name to use kms:ResourceAliases condition" + }, + "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": { + "recommendedValue": true, + "explanation": "Generate a launch template when creating an AutoScalingGroup" + }, + "@aws-cdk/core:includePrefixInUniqueNameGeneration": { + "recommendedValue": true, + "explanation": "Include the stack prefix in the stack name generation process" + }, + "@aws-cdk/aws-efs:denyAnonymousAccess": { + "recommendedValue": true, + "explanation": "EFS denies anonymous clients accesses" + }, + "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": { + "recommendedValue": true, + "explanation": "Enables support for Multi-AZ with Standby deployment for opensearch domains" + }, + "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": { + "recommendedValue": true, + "explanation": "Enables aws-lambda-nodejs.Function to use the latest available NodeJs runtime as the default" + }, + "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": { + "recommendedValue": true, + "explanation": "When enabled, mount targets will have a stable logicalId that is linked to the associated subnet." + }, + "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": { + "recommendedValue": true, + "explanation": "When enabled, a scope of InstanceParameterGroup for AuroraClusterInstance with each parameters will change." + }, + "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": { + "recommendedValue": true, + "explanation": "When enabled, will always use the arn for identifiers for CfnSourceApiAssociation in the GraphqlApi construct rather than id." + }, + "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": { + "recommendedValue": true, + "explanation": "When enabled, creating an RDS database cluster from a snapshot will only render credentials for snapshot credentials." + }, + "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": { + "recommendedValue": true, + "explanation": "When enabled, the CodeCommit source action is using the default branch name 'main'." + }, + "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": { + "recommendedValue": true, + "explanation": "When enabled, the logical ID of a Lambda permission for a Lambda action includes an alarm ID." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default value for crossAccountKeys to false." + }, + "@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default pipeline type to V2." + }, + "@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": { + "recommendedValue": true, + "explanation": "When enabled, IAM Policy created from KMS key grant will reduce the resource scope to this key only." + }, + "@aws-cdk/pipelines:reduceAssetRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from PipelineAssetsFileRole trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-eks:nodegroupNameAttribute": { + "recommendedValue": true, + "explanation": "When enabled, nodegroupName attribute of the provisioned EKS NodeGroup will not have the cluster name prefix." + }, + "@aws-cdk/aws-eks:useNativeOidcProvider": { + "recommendedValue": true, + "explanation": "When enabled, EKS V2 clusters will use the native OIDC provider resource AWS::IAM::OIDCProvider instead of creating the OIDCProvider with a custom resource (iam.OpenIDConnectProvider)." + }, + "@aws-cdk/aws-ec2:ebsDefaultGp3Volume": { + "recommendedValue": true, + "explanation": "When enabled, the default volume type of the EBS volume will be GP3" + }, + "@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": { + "recommendedValue": true, + "explanation": "When enabled, remove default deployment alarm settings" + }, + "@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": { + "recommendedValue": false, + "explanation": "When enabled, the custom resource used for `AwsCustomResource` will configure the `logApiResponseData` property as true by default" + }, + "@aws-cdk/aws-s3:keepNotificationInImportedBucket": { + "recommendedValue": false, + "explanation": "When enabled, Adding notifications to a bucket in the current stack will not remove notification from imported stack." + }, + "@aws-cdk/aws-stepfunctions-tasks:useNewS3UriParametersForBedrockInvokeModelTask": { + "recommendedValue": true, + "explanation": "When enabled, use new props for S3 URI field in task definition of state machine for bedrock invoke model.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:explicitStackTags": { + "recommendedValue": true, + "explanation": "When enabled, stack tags need to be assigned explicitly on a Stack." + }, + "@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": { + "recommendedValue": true, + "explanation": "When enabled, we will only grant the necessary permissions when users specify cloudwatch log group through logConfiguration" + }, + "@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": { + "recommendedValue": true, + "explanation": "When enabled will allow you to specify a resource policy per replica, and not copy the source table policy to all replicas" + }, + "@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": { + "recommendedValue": true, + "explanation": "When enabled, initOptions.timeout and resourceSignalTimeout values will be summed together." + }, + "@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": { + "recommendedValue": true, + "explanation": "When enabled, a Lambda authorizer Permission created when using GraphqlApi will be properly scoped with a SourceArn." + }, + "@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": { + "recommendedValue": true, + "explanation": "When enabled, the value of property `instanceResourceId` in construct `DatabaseInstanceReadReplica` will be set to the correct value which is `DbiResourceId` instead of currently `DbInstanceArn`" + }, + "@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": { + "recommendedValue": true, + "explanation": "When enabled, CFN templates added with `cfn-include` will error if the template contains Resource Update or Create policies with CFN Intrinsics that include non-primitive values." + }, + "@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": { + "recommendedValue": true, + "explanation": "When enabled, both `@aws-sdk` and `@smithy` packages will be excluded from the Lambda Node.js 18.x runtime to prevent version mismatches in bundled applications." + }, + "@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": { + "recommendedValue": true, + "explanation": "When enabled, the resource of IAM Run Ecs policy generated by SFN EcsRunTask will reference the definition, instead of constructing ARN." + }, + "@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": { + "recommendedValue": true, + "explanation": "When enabled, the BastionHost construct will use the latest Amazon Linux 2023 AMI, instead of Amazon Linux 2." + }, + "@aws-cdk/core:aspectStabilization": { + "recommendedValue": true, + "explanation": "When enabled, a stabilization loop will be run when invoking Aspects during synthesis.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": { + "recommendedValue": true, + "explanation": "When enabled, use a new method for DNS Name of user pool domain target without creating a custom resource." + }, + "@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": { + "recommendedValue": true, + "explanation": "When enabled, the default security group ingress rules will allow IPv6 ingress from anywhere" + }, + "@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": { + "recommendedValue": true, + "explanation": "When enabled, the default behaviour of OIDC provider will reject unauthorized connections" + }, + "@aws-cdk/core:enableAdditionalMetadataCollection": { + "recommendedValue": true, + "explanation": "When enabled, CDK will expand the scope of usage data collected to better inform CDK development and improve communication for security concerns and emerging issues." + }, + "@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": { + "recommendedValue": false, + "explanation": "[Deprecated] When enabled, Lambda will create new inline policies with AddToRolePolicy instead of adding to the Default Policy Statement" + }, + "@aws-cdk/aws-s3:setUniqueReplicationRoleName": { + "recommendedValue": true, + "explanation": "When enabled, CDK will automatically generate a unique role name that is used for s3 object replication." + }, + "@aws-cdk/pipelines:reduceStageRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from Stage addActions trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-events:requireEventBusPolicySid": { + "recommendedValue": true, + "explanation": "When enabled, grantPutEventsTo() will use resource policies with Statement IDs for service principals." + }, + "@aws-cdk/core:aspectPrioritiesMutating": { + "recommendedValue": true, + "explanation": "When set to true, Aspects added by the construct library on your behalf will be given a priority of MUTATING." + }, + "@aws-cdk/aws-dynamodb:retainTableReplica": { + "recommendedValue": true, + "explanation": "When enabled, table replica will be default to the removal policy of source table unless specified otherwise." + }, + "@aws-cdk/cognito:logUserPoolClientSecretValue": { + "recommendedValue": false, + "explanation": "When disabled, the value of the user pool client secret will not be logged in the custom resource lambda function logs." + }, + "@aws-cdk/pipelines:reduceCrossAccountActionRoleTrustScope": { + "recommendedValue": true, + "explanation": "When enabled, scopes down the trust policy for the cross-account action role", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2": { + "recommendedValue": true, + "explanation": "When enabled, the resultWriterV2 property of DistributedMap will be used insted of resultWriter" + }, + "@aws-cdk/s3-notifications:addS3TrustKeyPolicyForSnsSubscriptions": { + "recommendedValue": true, + "explanation": "Add an S3 trust policy to a KMS key resource policy for SNS subscriptions." + }, + "@aws-cdk/aws-ec2:requirePrivateSubnetsForEgressOnlyInternetGateway": { + "recommendedValue": true, + "explanation": "When enabled, the EgressOnlyGateway resource is only created if private subnets are defined in the dual-stack VPC." + }, + "@aws-cdk/aws-ec2-alpha:useResourceIdForVpcV2Migration": { + "recommendedValue": false, + "explanation": "When enabled, use resource IDs for VPC V2 migration" + }, + "@aws-cdk/aws-s3:publicAccessBlockedByDefault": { + "recommendedValue": true, + "explanation": "When enabled, setting any combination of options for BlockPublicAccess will automatically set true for any options not defined." + }, + "@aws-cdk/aws-lambda:useCdkManagedLogGroup": { + "recommendedValue": true, + "explanation": "When enabled, CDK creates and manages loggroup for the lambda function" + }, + "@aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault": { + "recommendedValue": true, + "explanation": "When enabled, Network Load Balancer will be created with a security group by default." + }, + "@aws-cdk/aws-stepfunctions-tasks:httpInvokeDynamicJsonPathEndpoint": { + "recommendedValue": true, + "explanation": "When enabled, allows using a dynamic apiEndpoint with JSONPath format in HttpInvoke tasks.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:uniqueTargetGroupId": { + "recommendedValue": true, + "explanation": "When enabled, ECS patterns will generate unique target group IDs to prevent conflicts during load balancer replacement" + }, + "@aws-cdk/aws-route53-patterns:useDistribution": { + "recommendedValue": true, + "explanation": "Use the `Distribution` resource instead of `CloudFrontWebDistribution`" + }, + "@aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0": { + "recommendedValue": true, + "explanation": "Use cloudfront-js-2.0 as the default runtime for CloudFront Functions" + }, + "@aws-cdk/aws-elasticloadbalancingv2:usePostQuantumTlsPolicy": { + "recommendedValue": true, + "explanation": "When enabled, HTTPS/TLS listeners use post-quantum TLS policy by default" + }, + "@aws-cdk/core:automaticL1Traits": { + "recommendedValue": true, + "explanation": "Automatically use the default L1 traits for L1 constructs`", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-batch:defaultToAL2023": { + "recommendedValue": true, + "explanation": "Use AL2023 as the default imageType for EC2 Batch compute environments instead of the deprecated AL2" + }, + "@aws-cdk/aws-eks:defaultToAL2023": { + "recommendedValue": true, + "explanation": "Use AL2023 as the default AMI type for EKS managed node groups using non-GPU instance types instead of the deprecated AL2" + }, + "@aws-cdk/core:annotationsInValidationReport": { + "recommendedValue": true, + "explanation": "Include construct annotations (warnings and errors) in the policy validation report" + }, + "@aws-cdk/core:defaultCrossStackReferences": { + "recommendedValue": "weak", + "explanation": "Controls whether cross-stack references are strong, weak, or both", + "unconfiguredBehavesLike": { + "v2": "strong" + } + }, + "@aws-cdk/core:validateAgainstDefaultRules": { + "recommendedValue": true, + "explanation": "Treat CloudFormation Validate findings as errors" + }, + "@aws-cdk/aws-ecs:removeEmptyLoadBalancers": { + "recommendedValue": true, + "explanation": "Render an empty `LoadBalancers` array on an ECS service that has no target groups" + } + } + } + } + }, + "minimumCliVersion": "2.1144.0" +} \ No newline at end of file diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 8aa60252a3..92117dd7ae 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -2,9 +2,12 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; +import { ProcessFailedError, runProcess, type ProcessRunner } from "../../../../io"; import { - assertCdkLocalContainerSupport, + assertCdkFeatureSupport, cdkCompatibilityWarning, + cdkFeaturesFor, + CDK_FEATURE_RELEASES, MINIMUM_COMPATIBLE_CDK_VERSION, } from "./compatibility"; @@ -26,46 +29,6 @@ async function cdkDirectoryWith(version: unknown): Promise { } describe("cdkCompatibilityWarning", () => { - test("rejects an older package that would ignore a local harness build selection", async () => { - const directory = await cdkDirectoryWith("1.0.1"); - const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); - await writeFile( - join(packageDirectory, "index.js"), - "exports.BuildTypeSchema = { safeParse: () => ({ success: false }) };", - ); - expect(() => assertCdkLocalContainerSupport(directory)).toThrow('supports "ContainerLocal"'); - }); - - test("asks to update the dependency when the package is not installed", async () => { - const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-compatibility-")); - tempDirectories.push(directory); - expect(() => assertCdkLocalContainerSupport(directory)).toThrow('supports "ContainerLocal"'); - }); - - test("reports a package that fails to load with its own error", async () => { - const directory = await cdkDirectoryWith("1.0.2"); - const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); - await writeFile(join(packageDirectory, "index.js"), 'throw new Error("corrupt install");'); - let message = ""; - try { - assertCdkLocalContainerSupport(directory); - } catch (error) { - message = (error as Error).message; - } - expect(message).toContain("Cannot load @aws/agentcore-cdk"); - expect(message).toContain("corrupt install"); - expect(message).not.toContain('supports "ContainerLocal"'); - }); - - test("accepts a supporting local or prerelease CDK package by capability", async () => { - const directory = await cdkDirectoryWith("1.0.2-rc.1"); - const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); - await writeFile( - join(packageDirectory, "index.js"), - 'exports.BuildTypeSchema = { safeParse: value => ({ success: value === "ContainerLocal" }) }; exports.LocalContainerImageAsset = class {};', - ); - expect(() => assertCdkLocalContainerSupport(directory)).not.toThrow(); - }); test.each(["0.0.0-0", "1.0.0-rc.1", "1.0.0-rc.2"])( "warns for incompatible version %s", async (version) => { @@ -101,3 +64,189 @@ describe("cdkCompatibilityWarning", () => { expect(await cdkCompatibilityWarning(directory)).toBeUndefined(); }); }); + +// These run the real Node probe against fake @aws/agentcore-cdk packages. +describe("assertCdkFeatureSupport", () => { + const CONTAINER_LOCAL = + 'exports.BuildTypeSchema = { safeParse: value => ({ success: value === "ContainerLocal" }) };' + + "exports.LocalContainerImageAsset = class {};"; + const CONTAINER_URI = + "exports.AgentEnvSpecSchema = { safeParse: input => ({ success: true, data: input }) };"; + const STRIPS_CONTAINER_URI = + "exports.AgentEnvSpecSchema = { safeParse: () => ({ success: true, data: {} }) };"; + + async function cdkPackage(code: string): Promise { + const directory = await cdkDirectoryWith("1.0.2-rc.1"); + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await writeFile( + join(packageDirectory, "package.json"), + JSON.stringify({ version: "1.0.2-rc.1", main: "index.cjs" }), + ); + await writeFile(join(packageDirectory, "index.cjs"), code); + return directory; + } + + test("accepts a package that supports every feature the project uses", async () => { + const directory = await cdkPackage(CONTAINER_LOCAL + CONTAINER_URI); + await expect( + assertCdkFeatureSupport(directory, ["ContainerLocal", "Runtime containerUri"]), + ).resolves.toBeUndefined(); + }); + + test("names only the missing feature and its minimum CDK version, and asks a managed project to update the CLI", async () => { + const directory = await cdkPackage(CONTAINER_LOCAL + STRIPS_CONTAINER_URI); + const error = await assertCdkFeatureSupport(directory, [ + "ContainerLocal", + "Runtime containerUri", + ]).then( + () => undefined, + (caught: unknown) => caught as Error, + ); + expect(error?.message).toBe( + "This project uses Runtime containerUri, which its @aws/agentcore-cdk package does not " + + `support; it needs @aws/agentcore-cdk ${CDK_FEATURE_RELEASES["Runtime containerUri"]} or newer. ` + + "The CLI installs the @aws/agentcore-cdk version it ships with, so update the CLI " + + "(agentcore update), then rebuild or redeploy.", + ); + expect(error?.message).not.toContain("#"); + expect(error?.message).not.toContain("npm install"); + }); + + test("asks a project that manages its own dependencies to install the minimum CDK version", async () => { + const directory = await cdkPackage(CONTAINER_LOCAL + STRIPS_CONTAINER_URI); + const error = await assertCdkFeatureSupport(directory, ["Runtime containerUri"], runProcess, { + dependenciesManaged: false, + }).then( + () => undefined, + (caught: unknown) => caught as Error, + ); + expect(error?.message).toBe( + "This project uses Runtime containerUri, which its @aws/agentcore-cdk package does not " + + `support; it needs @aws/agentcore-cdk ${CDK_FEATURE_RELEASES["Runtime containerUri"]} or newer. ` + + `Install @aws/agentcore-cdk ${CDK_FEATURE_RELEASES["Runtime containerUri"]} or newer in ` + + `${directory} (npm install), then rebuild or redeploy.`, + ); + expect(error?.message).not.toContain("agentcore update"); + }); + + test("names the newest minimum version when several features are missing", async () => { + const directory = await cdkDirectoryWith("1.0.0"); + await expect( + assertCdkFeatureSupport(directory, ["ContainerLocal", "Runtime containerUri"]), + ).rejects.toThrow( + `they need @aws/agentcore-cdk ${CDK_FEATURE_RELEASES["Runtime containerUri"]} or newer`, + ); + }); + + test("records each feature's minimum @aws/agentcore-cdk release", () => { + expect(CDK_FEATURE_RELEASES).toEqual({ + ContainerLocal: "1.2.0", + "Runtime containerUri": "1.3.0", + }); + }); + + test("reports every feature when the package cannot be loaded", async () => { + const directory = await cdkDirectoryWith("1.0.0"); + await expect( + assertCdkFeatureSupport(directory, ["ContainerLocal", "Runtime containerUri"]), + ).rejects.toThrow("ContainerLocal and Runtime containerUri"); + }); + + test("asks to update the dependency when the package is not installed", async () => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-compatibility-")); + tempDirectories.push(directory); + await expect(assertCdkFeatureSupport(directory, ["ContainerLocal"])).rejects.toThrow( + "This project uses ContainerLocal,", + ); + }); + + test("reports a package that fails to load with its own error", async () => { + const directory = await cdkPackage('throw new Error("corrupt install");'); + const error = await assertCdkFeatureSupport(directory, ["ContainerLocal"]).then( + () => undefined, + (caught: unknown) => caught as Error, + ); + expect(error?.message).toContain("Cannot load @aws/agentcore-cdk"); + expect(error?.message).toContain("corrupt install"); + expect(error?.message).not.toContain("This project uses"); + }); + + test("reports a package whose own dependency is missing as a load error", async () => { + const directory = await cdkPackage('require("constructs");'); + const error = await assertCdkFeatureSupport(directory, ["Runtime containerUri"]).then( + () => undefined, + (caught: unknown) => caught as Error, + ); + expect(error?.message).toContain(`Cannot load @aws/agentcore-cdk from ${directory}:`); + expect(error?.message).toContain("Cannot find module 'constructs'"); + expect(error?.message).not.toContain("This project uses"); + }); + + test("ignores Node stderr output after the probe result", async () => { + const directory = await cdkPackage(CONTAINER_URI); + const preload = join(directory, "noise.cjs"); + await writeFile( + preload, + 'process.emitWarning("corp shim"); process.on("exit", () => console.error("corp shim bye"));', + ); + const runner: ProcessRunner = (command, options) => + runProcess(command, { + ...options, + env: { ...process.env, NODE_OPTIONS: `--require ${preload}` }, + }); + await expect( + assertCdkFeatureSupport(directory, ["Runtime containerUri"], runner), + ).resolves.toBeUndefined(); + }); + + test("reports a missing node concisely, without the probe source", async () => { + const error = await assertCdkFeatureSupport( + "/project/cdk", + ["Runtime containerUri"], + (command) => + Promise.reject( + new ProcessFailedError(command, "/project/cdk", null, "Error: spawn node ENOENT"), + ), + ).then( + () => undefined, + (caught: unknown) => caught as Error, + ); + expect(error?.message).toBe( + "Node.js was not found on your PATH; it is required to check the @aws/agentcore-cdk " + + "package installed in /project/cdk. Install Node.js, then rebuild or redeploy.", + ); + }); + + test("runs no probe when the project uses neither feature", async () => { + await expect( + assertCdkFeatureSupport("/missing/project", [], async () => { + throw new Error("must not probe"); + }), + ).resolves.toBeUndefined(); + }); + + test("passes only feature names to the Node probe", async () => { + const commands: string[][] = []; + await assertCdkFeatureSupport( + "/project/cdk", + ["Runtime containerUri"], + async (command, options) => { + expect(options.cwd).toBe("/project/cdk"); + commands.push(command); + options.onOutput?.('noise\nagentcore-cdk-probe-result:{"missing":[]}\nmore noise'); + }, + ); + expect(commands[0]?.slice(0, 3)).toEqual(["node", "--input-type=commonjs", "-e"]); + expect(commands[0]?.at(-1)).toBe('["Runtime containerUri"]'); + }); +}); + +describe("cdkFeaturesFor", () => { + test("derives features from the workload build modes", () => { + expect(cdkFeaturesFor({ "runtime/a": "CodeZip", "harness/h": "ContainerUri" })).toEqual([]); + expect(cdkFeaturesFor({ "runtime/a": "ContainerUri", "harness/h": "ContainerLocal" })).toEqual([ + "ContainerLocal", + "Runtime containerUri", + ]); + }); +}); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 5dbfcd3f9e..b0e2ad4e3c 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -1,37 +1,159 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import semver from "semver"; -import { createRequire } from "node:module"; import { ProjectStateError } from "../../../../errors"; +import { ProcessFailedError, runProcess, type ProcessRunner } from "../../../../io"; +import type { WorkloadBuilds } from "../../../../handlers/project/types"; export const MINIMUM_COMPATIBLE_CDK_VERSION = "1.0.0"; -/** Detect support directly so prereleases and local CDK packages also work. */ -export function assertCdkLocalContainerSupport(cdkDirectory: string): void { +/** CDK package features a project can depend on beyond the minimum version. */ +export type CdkFeature = "ContainerLocal" | "Runtime containerUri"; + +/** The first @aws/agentcore-cdk release with each feature. */ +export const CDK_FEATURE_RELEASES: Record = { + ContainerLocal: "1.2.0", + "Runtime containerUri": "1.3.0", +}; + +// Runs in Node, like the CDK app: a standalone CLI binary cannot reliably resolve +// the project's external modules through its compiled-in Bun resolver. Prints the +// features the installed @aws/agentcore-cdk lacks on its own stdout line after +// PROBE_RESULT_PREFIX, so Node warnings or preload output around it are ignored. +const PROBE_RESULT_PREFIX = "agentcore-cdk-probe-result:"; +const FEATURE_PROBE = ` +const { createRequire } = require("node:module"); +const { join } = require("node:path"); +const wanted = JSON.parse(process.argv[1]); +const loadError = (error) => ({ loadError: error instanceof Error ? error.message : String(error) }); +function probe() { + const projectRequire = createRequire(join(process.cwd(), "package.json")); + let cdk = {}; + // Only a package that cannot be resolved at all falls through to "update the + // dependency". A resolved package that fails to load (a dependency of it missing, + // or it throws) is a broken install, which that advice would hide. + let resolved = true; try { - const require = createRequire(join(cdkDirectory, "package.json")); - const cdk = require("@aws/agentcore-cdk") as { - BuildTypeSchema?: { safeParse(value: string): { success: boolean } }; - LocalContainerImageAsset?: unknown; - }; - if (cdk.BuildTypeSchema?.safeParse("ContainerLocal").success && cdk.LocalContainerImageAsset) - return; + projectRequire.resolve("@aws/agentcore-cdk"); } catch (error) { - // A missing package falls through to "update the dependency". Anything else is a - // broken install, which that advice would hide. - const code = (error as { code?: unknown }).code; - if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND") { + const code = error && error.code; + if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND") return loadError(error); + resolved = false; + } + if (resolved) { + try { + cdk = projectRequire("@aws/agentcore-cdk"); + } catch (error) { + return loadError(error); + } + } + const supported = { + ContainerLocal: () => + Boolean(cdk.BuildTypeSchema?.safeParse("ContainerLocal").success && cdk.LocalContainerImageAsset), + // Older Runtime schemas strip containerUri, which would silently build with CodeBuild. + "Runtime containerUri": () => { + const containerUri = "123456789012.dkr.ecr.us-west-2.amazonaws.com/compatibility:probe"; + const parsed = cdk.AgentEnvSpecSchema?.safeParse({ + name: "compatibility_probe", + build: "Container", + entrypoint: "main.py", + codeLocation: "app/compatibility_probe", + containerUri, + }); + return Boolean(parsed?.success && parsed.data.containerUri === containerUri); + }, + }; + return { + missing: wanted.filter((feature) => { + try { + return !supported[feature](); + } catch { + return true; + } + }), + }; +} +process.stdout.write("\\n${PROBE_RESULT_PREFIX}" + JSON.stringify(probe()) + "\\n"); +`; + +/** The CDK features a project's workloads use. A Harness containerUri predates both. */ +export function cdkFeaturesFor(builds: WorkloadBuilds): CdkFeature[] { + const entries = Object.entries(builds); + return [ + ...(entries.some(([, build]) => build === "ContainerLocal") + ? (["ContainerLocal"] as const) + : []), + ...(entries.some(([key, build]) => key.startsWith("runtime/") && build === "ContainerUri") + ? (["Runtime containerUri"] as const) + : []), + ]; +} + +/** + * Verifies in one Node probe that the project's @aws/agentcore-cdk supports every + * feature in `features`, so an older or missing package never silently drops a + * setting. Detects support directly, so prereleases and local packages also work. + * A package that is installed but fails to load is reported with its own error. + * When the CLI manages the CDK dependencies it installs the version it vends and + * rejects a newer pin, so the fix is a newer CLI; otherwise it is a newer package. + */ +export async function assertCdkFeatureSupport( + cdkDirectory: string, + features: readonly CdkFeature[], + runner: ProcessRunner = runProcess, + { dependenciesManaged = true }: { dependenciesManaged?: boolean } = {}, +): Promise { + if (features.length === 0) return; + let output = ""; + let result: { missing?: CdkFeature[]; loadError?: string }; + try { + await runner(["node", "--input-type=commonjs", "-e", FEATURE_PROBE, JSON.stringify(features)], { + cwd: cdkDirectory, + onOutput: (chunk) => { + output += chunk; + }, + }); + } catch (error) { + // Report the failure itself, never the command line (it holds the whole probe). + const exitCode = error instanceof ProcessFailedError ? error.meta.exitCode : undefined; + if (exitCode === null && (error as Error).message.includes("ENOENT")) { throw new ProjectStateError( - `Cannot load @aws/agentcore-cdk from ${cdkDirectory}: ` + - (error instanceof Error ? error.message : String(error)), - { cause: error }, + "Node.js was not found on your PATH; it is required to check the @aws/agentcore-cdk " + + `package installed in ${cdkDirectory}. Install Node.js, then rebuild or redeploy.`, ); } + throw new ProjectStateError( + `Cannot load @aws/agentcore-cdk from ${cdkDirectory}: the Node.js check failed` + + `${typeof exitCode === "number" ? ` (exit code ${exitCode})` : ""}.` + + (output.trim() ? `\n\n${output.trim()}` : ""), + ); + } + const resultLine = output.split(/\r?\n/).findLast((line) => line.startsWith(PROBE_RESULT_PREFIX)); + try { + result = JSON.parse(resultLine?.slice(PROBE_RESULT_PREFIX.length) ?? "") as typeof result; + } catch { + throw new ProjectStateError( + `Cannot load @aws/agentcore-cdk from ${cdkDirectory}: the Node.js check printed no result.` + + (output.trim() ? `\n\n${output.trim()}` : ""), + ); + } + if (result.loadError !== undefined) { + throw new ProjectStateError( + `Cannot load @aws/agentcore-cdk from ${cdkDirectory}: ${result.loadError}`, + ); } - // An old or unavailable package must never silently strip a harness build selection. + const missing = result.missing ?? []; + if (missing.length === 0) return; + const minimum = semver.sort(missing.map((feature) => CDK_FEATURE_RELEASES[feature])).at(-1)!; + const unsupported = + `This project uses ${missing.join(" and ")}, which its @aws/agentcore-cdk package does not ` + + `support; ${missing.length === 1 ? "it needs" : "they need"} @aws/agentcore-cdk ${minimum} or newer.`; throw new ProjectStateError( - 'This project requires an @aws/agentcore-cdk package that supports "ContainerLocal". ' + - `Update the dependency in ${cdkDirectory} and run npm install.`, + dependenciesManaged + ? `${unsupported} The CLI installs the @aws/agentcore-cdk version it ships with, so update ` + + "the CLI (agentcore update), then rebuild or redeploy." + : `${unsupported} Install @aws/agentcore-cdk ${minimum} or newer in ${cdkDirectory} ` + + "(npm install), then rebuild or redeploy.", ); } diff --git a/src/core/project/backends/cdk/localContainers.test.ts b/src/core/project/backends/cdk/localContainers.test.ts index ad19ef4db5..20dd64ae99 100644 --- a/src/core/project/backends/cdk/localContainers.test.ts +++ b/src/core/project/backends/cdk/localContainers.test.ts @@ -153,6 +153,16 @@ describe("assertSupportedBuildTransitions", () => { test.each([ ["CodeZip", "Container", 'delete the Dockerfile and set "build": "CodeZip" in agentcore.json'], ["Container", "CodeZip", 'set "build": "Container" and its "dockerfile" in agentcore.json'], + [ + "CodeZip", + "ContainerUri", + 'remove "containerUri" and set "build": "CodeZip" in agentcore.json', + ], + [ + "ContainerUri", + "CodeZip", + 'set "build": "Container" and its "containerUri" in agentcore.json', + ], ] as const)("rejects a deployed runtime %s to %s transition", (before, after, keep) => { expect(() => assertSupportedBuildTransitions( @@ -188,6 +198,40 @@ describe("assertSupportedBuildTransitions", () => { ), ).toThrow("Cannot change runtime/agent from CodeZip to Container"); }); + test("rejects a pre-feature CodeZip runtime becoming a pre-built image", () => { + const previous: DeployedTemplate = { + Resources: { + Runtime: { + Type: "AWS::BedrockAgentCore::Runtime", + Properties: { + AgentRuntimeName: "example_default_agent", + AgentRuntimeArtifact: { CodeConfiguration: { Code: {} } }, + }, + }, + }, + }; + expect(() => + assertSupportedBuildTransitions( + previous, + { "runtime/agent": "ContainerUri" }, + "example", + "default", + ), + ).toThrow("Cannot change runtime/agent from CodeZip to ContainerUri"); + }); + test.each([ + ["Container", "ContainerUri"], + ["ContainerUri", "Container"], + ] as const)("allows a deployed runtime %s to %s transition", (before, after) => { + expect(() => + assertSupportedBuildTransitions( + { Metadata: { "agentcore:builds": { "runtime/agent": before } } }, + { "runtime/agent": after }, + "example", + "default", + ), + ).not.toThrow(); + }); test.each([ ["Managed", "Container"], ["Container", "Managed"], @@ -205,6 +249,7 @@ describe("assertSupportedBuildTransitions", () => { ["ContainerUri", "ContainerLocal"], ["ContainerLocal", "ContainerUri"], ["Managed", "ContainerUri"], + ["Container", "ContainerUri"], ] as const satisfies [string, WorkloadBuildMode][])( "allows a deployed %s to %s transition", (before, after) => { diff --git a/src/core/project/backends/cdk/localContainers.ts b/src/core/project/backends/cdk/localContainers.ts index 6e4c7cf436..b9d36af3fe 100644 --- a/src/core/project/backends/cdk/localContainers.ts +++ b/src/core/project/backends/cdk/localContainers.ts @@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parse } from "yaml"; import { z } from "zod"; +import { CONTAINER_URI_PATTERN } from "../../../../projectSchemas/constants"; import { HarnessYamlSchema } from "../../../../projectSchemas/harness"; import type { LocalWorkloadSources, @@ -16,8 +17,9 @@ import { InputValidationError, ProjectStateError } from "../../../../errors"; * Resolves every workload's build mode from agentcore.json and each harness.yaml, * and, for each ContainerLocal workload, where it is built from and its execution * role. It reads the harness files, so resolve once per command and pass the - * result on. A Harness is Managed without a Dockerfile or image, ContainerUri with - * an image. + * result on. A Runtime or Harness with a pre-built image (containerUri) is + * ContainerUri and is never built locally; a Harness with neither image nor + * Dockerfile is Managed. */ export function resolveWorkloads(project: Project): { builds: WorkloadBuilds; @@ -26,8 +28,8 @@ export function resolveWorkloads(project: Project): { const builds: WorkloadBuilds = {}; const local: LocalWorkloadSources = new Map(); for (const runtime of project.spec.runtimes) { - builds[`runtime/${runtime.name}`] = runtime.build; - if (runtime.build !== "ContainerLocal") continue; + builds[`runtime/${runtime.name}`] = runtime.containerUri ? "ContainerUri" : runtime.build; + if (runtime.containerUri || runtime.build !== "ContainerLocal") continue; local.set(`runtime/${runtime.name}`, { context: runtime.buildContextPath ?? runtime.codeLocation, dockerfile: runtime.dockerfile ?? "Dockerfile", @@ -153,13 +155,44 @@ function deployedBuild( return undefined; } +/** An ECR repository the deployed stack creates for a Container build. */ +export type ManagedRepository = { account: string; region: string; name: string }; + +/** + * What the guard needs to protect a Runtime moving from Container to a pre-built + * image: each Runtime's containerUri by workload key, and the deployed stack's + * ECR repositories. + */ +export type PrebuiltImageContext = { + containerUris: Readonly>; + managedRepositories: readonly ManagedRepository[]; +}; + +/** The deployed stack's repository that `containerUri` names, if any. */ +function managedRepositoryFor( + containerUri: string | undefined, + repositories: readonly ManagedRepository[], +): ManagedRepository | undefined { + const match = containerUri === undefined ? null : CONTAINER_URI_PATTERN.exec(containerUri); + if (!match) return undefined; + const [, account, region, , repository] = match; + return repositories.find( + (managed) => + managed.account === account && managed.region === region && managed.name === repository, + ); +} + /** * Rejects switching a deployed workload into or out of ContainerLocal, and a - * deployed Runtime between CodeZip and Container. AgentCore rejects an + * deployed Runtime between CodeZip and a container artifact (Container or a + * pre-built image, ContainerUri). AgentCore rejects an * artifact-type change in place ("Agent artifact type cannot be updated"), and * Container to ContainerLocal replaces how the image is built and published, so - * only a new workload may use ContainerLocal. ContainerUri is left - * to CloudFormation. The deployed template is authoritative: editing + * only a new workload may use ContainerLocal. A Runtime moving from Container to + * a containerUri in the ECR repository the stack created for its Container build + * is rejected too: that repository is created with RemovalPolicy.DESTROY and + * emptyOnDelete, so the deploy would delete the image the Runtime then points + * at. Other ContainerUri changes are left to CloudFormation. The deployed template is authoritative: editing * agentcore.json or deleting deployed-state.json must not permit a build-mode * migration. */ @@ -168,6 +201,7 @@ export function assertSupportedBuildTransitions( builds: WorkloadBuilds, projectName: string, targetName: string | undefined, + prebuilt?: PrebuiltImageContext, ): void { const recorded = template.Metadata?.["agentcore:builds"]; if ( @@ -187,6 +221,19 @@ export function assertSupportedBuildTransitions( targetName, ); if (deployed === undefined || deployed === desired) continue; + if (key.startsWith("runtime/") && deployed === "Container" && desired === "ContainerUri") { + const containerUri = prebuilt?.containerUris[key]; + const repository = managedRepositoryFor(containerUri, prebuilt?.managedRepositories ?? []); + if (repository) { + throw new ProjectStateError( + `Cannot change ${key} from Container to ContainerUri with containerUri '${containerUri}': ` + + `that image is in the ECR repository '${repository.name}', which the CLI created for ` + + "the Container build. This deploy deletes that repository and its images, so the " + + "Runtime would point at a deleted image. Copy the image to an ECR repository you " + + "manage first, then set containerUri to the copy.", + ); + } + } const pair = new Set([deployed, desired]); if (pair.has("ContainerLocal") && !pair.has("ContainerUri")) { throw new ProjectStateError( @@ -199,11 +246,20 @@ export function assertSupportedBuildTransitions( } // The CLI flips a CodeZip Runtime to Container itself when a Dockerfile appears // (runtimeBuild.ts); on a deployed Runtime the service then fails the update. - if (key.startsWith("runtime/") && pair.has("CodeZip") && pair.has("Container")) { + // A pre-built image (ContainerUri) is a container artifact too. + if ( + key.startsWith("runtime/") && + pair.has("CodeZip") && + (pair.has("Container") || pair.has("ContainerUri")) + ) { const keep = - deployed === "CodeZip" - ? 'delete the Dockerfile and set "build": "CodeZip" in agentcore.json' - : 'set "build": "Container" and its "dockerfile" in agentcore.json again'; + deployed === "Container" + ? 'set "build": "Container" and its "dockerfile" in agentcore.json again' + : deployed === "ContainerUri" + ? 'set "build": "Container" and its "containerUri" in agentcore.json again' + : desired === "Container" + ? 'delete the Dockerfile and set "build": "CodeZip" in agentcore.json' + : 'remove "containerUri" and set "build": "CodeZip" in agentcore.json'; throw new ProjectStateError( `Cannot change ${key} from ${deployed} to ${desired}. The service does not allow ` + "changing a Runtime's artifact type, so the deploy would fail and roll back. Add a " + diff --git a/src/core/project/backends/cdk/prebuiltRuntime.test.ts b/src/core/project/backends/cdk/prebuiltRuntime.test.ts new file mode 100644 index 0000000000..6f5f77b863 --- /dev/null +++ b/src/core/project/backends/cdk/prebuiltRuntime.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { FsReadWriteJson } from "../../../../io"; +import { ProjectRuntimeSchema } from "../../../../projectSchemas/runtime"; +import { createSilentLogger } from "../../../../testing"; +import type { WorkloadBuilds } from "../../../../handlers/project/types"; +import { assertSupportedBuildTransitions, type DeployedTemplate } from "./localContainers"; +import { localImageBuilds } from "./localImages"; + +// A real assembly synthesized by @aws/agentcore-cdk with Runtime containerUri +// support; see __fixtures__/prebuilt-runtime/README.md. +const FIXTURE = join(import.meta.dir, "__fixtures__", "prebuilt-runtime"); +const json = new FsReadWriteJson({ logger: createSilentLogger() }); +const template = JSON.parse( + readFileSync(join(FIXTURE, "AgentCore-Fixture.template.json"), "utf8"), +) as DeployedTemplate & { Resources: Record }; +const spec = JSON.parse(readFileSync(join(FIXTURE, "agentcore.json"), "utf8")) as { + runtimes: unknown[]; +}; +const BUILDS: WorkloadBuilds = { + "runtime/orders": "ContainerLocal", + "runtime/billing": "Container", + "runtime/image": "ContainerUri", + "harness/assistant": "ContainerLocal", +}; + +describe("a Runtime with containerUri, as the CDK package synthesizes it", () => { + test("the CLI schema accepts the agentcore.json the fixture was synthesized from", () => { + for (const runtime of spec.runtimes) { + expect(ProjectRuntimeSchema.safeParse(runtime).success).toBe(true); + } + }); + + test("records ContainerUri, the CLI's build mode for it, and no local image", () => { + const metadata = template.Metadata as Record>; + for (const [key, build] of Object.entries(BUILDS)) { + expect(metadata["agentcore:builds"]![key]).toBe(build); + } + expect(metadata["agentcore:localImages"]).not.toHaveProperty("runtime/image"); + }); + + test("deploys the image URI as is, with no build resources of its own", () => { + const runtime = Object.values(template.Resources).find( + (resource) => resource.Properties?.AgentRuntimeName === "Fixture_image", + ); + expect(runtime?.Properties.AgentRuntimeArtifact).toEqual({ + ContainerConfiguration: { + ContainerUri: "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1", + }, + }); + const ids = Object.keys(template.Resources).filter((id) => id.includes("RuntimeImage")); + expect(ids.map((id) => template.Resources[id]!.Type)).not.toContain("AWS::CodeBuild::Project"); + }); + + test("agentcore build builds only the ContainerLocal images", async () => { + const images = await localImageBuilds(json, FIXTURE, "Fixture", BUILDS); + expect(images.map((image) => image.resource).sort()).toEqual([ + "harness/assistant", + "runtime/orders", + ]); + }); + + test("the switch guard allows ContainerUri transitions and still rejects Container to ContainerLocal and ContainerUri to CodeZip", () => { + expect(() => + assertSupportedBuildTransitions( + template, + { ...BUILDS, "runtime/image": "ContainerLocal" }, + "Fixture", + undefined, + ), + ).not.toThrow(); + expect(() => + assertSupportedBuildTransitions( + template, + { ...BUILDS, "runtime/billing": "ContainerUri" }, + "Fixture", + undefined, + ), + ).not.toThrow(); + expect(() => + assertSupportedBuildTransitions( + template, + { ...BUILDS, "runtime/billing": "ContainerLocal" }, + "Fixture", + undefined, + ), + ).toThrow("cannot be switched into or out of ContainerLocal"); + expect(() => + assertSupportedBuildTransitions( + template, + { ...BUILDS, "runtime/image": "CodeZip" }, + "Fixture", + undefined, + ), + ).toThrow("Cannot change runtime/image from ContainerUri to CodeZip"); + }); + + test("the switch guard rejects moving billing to an image in its own CLI-managed repository", () => { + const managedRepositories = [ + { account: "123456789012", region: "us-west-2", name: "fixture/billing" }, + ]; + const switchTo = (containerUri: string) => () => + assertSupportedBuildTransitions( + template, + { ...BUILDS, "runtime/billing": "ContainerUri" }, + "Fixture", + undefined, + { containerUris: { "runtime/billing": containerUri }, managedRepositories }, + ); + expect(switchTo("123456789012.dkr.ecr.us-west-2.amazonaws.com/fixture/billing:latest")).toThrow( + "Copy the image to an ECR repository you manage first, then set containerUri to the copy.", + ); + expect(switchTo("123456789012.dkr.ecr.us-west-2.amazonaws.com/team/billing:v1")).not.toThrow(); + // A Runtime already on a pre-built image keeps whatever URI it has. + expect(() => + assertSupportedBuildTransitions(template, BUILDS, "Fixture", undefined, { + containerUris: { + "runtime/image": "123456789012.dkr.ecr.us-west-2.amazonaws.com/fixture/billing:v1", + }, + managedRepositories, + }), + ).not.toThrow(); + }); +}); diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 08f9c2bfb7..a4121077c9 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -2918,6 +2918,32 @@ describe("docs-only runtimes", () => { await expect(runAdd(subject, project, docsRuntime())).resolves.toBeDefined(); }); + test("refuses a pre-built runtime whose folder overlaps a harness", async () => { + const { manager: subject } = manager(); + const created = await emptyProject(subject); + const specPath = join(created.rootPath, "agentcore", "agentcore.json"); + const spec = JSON.parse(await readFile(specPath, "utf-8")); + spec.harnesses = [{ name: "search", path: "app/search" }]; + await writeFile(specPath, JSON.stringify(spec)); + const project = (await subject.resolve({ filePath: created.rootPath }))!; + + await expect( + runAdd( + subject, + project, + docsRuntime({ + build: "Container", + containerUri: "123456789012.dkr.ecr.us-west-2.amazonaws.com/search:v1", + }), + ), + ).rejects.toThrow( + new InputValidationError( + "cannot add runtime 'search': 'app/search' overlaps the files of harness 'search'. " + + "Choose a different --name.", + ), + ); + }); + test("an import into an existing folder that fails partway removes only what it wrote", async () => { const { manager: subject } = manager(); const project = await emptyProject(subject); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 1f84022969..2526cb29f3 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -793,7 +793,8 @@ export class FsProjectManager implements ProjectManager { } case "runtime": { const outputPath = join(project.rootPath, "app", input.resourceConfig.name); - // The folder may hold the user's own code, but never another resource's. + // The folder may hold the user's own code, but never another resource's. A + // pre-built runtime writes no files but still records app/ as its codeLocation. const owner = appFolderOwner(projectSpec, project.rootPath, outputPath); if (owner !== undefined) { throw new InputValidationError( @@ -801,6 +802,14 @@ export class FsProjectManager implements ProjectManager { `overlaps the files of ${owner}. Choose a different --name.`, ); } + if ( + isRuntimeDocsConfig(input.resourceConfig) && + input.resourceConfig.containerUri !== undefined + ) { + projectSpec.runtimes.push(buildDocsRuntimeSpec(input.resourceConfig)); + yield { type: "step", message: "configuring runtime from the existing ECR image" }; + break; + } // Rollback removes only what this add created, never a folder the user already had. const folderExisted = existsSync(outputPath); if (isRuntimeDocsConfig(input.resourceConfig)) { diff --git a/src/core/project/runtimeBuild.test.ts b/src/core/project/runtimeBuild.test.ts index 0e731d548b..8fb1cd0742 100644 --- a/src/core/project/runtimeBuild.test.ts +++ b/src/core/project/runtimeBuild.test.ts @@ -300,6 +300,59 @@ describe("build", () => { expect(syncRuntimeBuild(first.runtime, root).changes).toEqual([]); }); + test("a pre-built image ignores local Dockerfiles and manifests", async () => { + const root = await project({ + "app/search/Dockerfile": "FROM scratch\n", + "app/search/pyproject.toml": "[invalid", + "app/search/package.json": "{invalid", + }); + const prebuilt = runtime({ + build: "Container", + containerUri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/search:release", + runtimeVersion: undefined, + }); + + expect(syncRuntimeBuild(prebuilt, root)).toEqual({ + runtime: prebuilt, + changes: [], + warnings: [], + }); + expect(prepareRuntimes(root, [prebuilt], "deploy")).toEqual({ + runtimes: [prebuilt], + changed: [], + messages: [], + }); + }); + + test("a pre-built image does not require its local code folder", async () => { + const root = await project({}); + const prebuilt = runtime({ + build: "Container", + codeLocation: "app/missing" as ProjectRuntime["codeLocation"], + containerUri: "public.ecr.aws/example/search:release", + runtimeVersion: undefined, + }); + + expect(prepareRuntimes(root, [prebuilt], "deploy").runtimes).toEqual([prebuilt]); + }); + + test("a pre-built image removes a stale runtimeVersion without reading local files", async () => { + const root = await project({}); + const prebuilt = runtime({ + build: "Container", + codeLocation: "app/missing" as ProjectRuntime["codeLocation"], + containerUri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/search:release", + }); + + expect(syncRuntimeBuild(prebuilt, root).changes).toEqual([ + { + field: "runtimeVersion", + from: "PYTHON_3_14", + reason: "pre-built container image", + }, + ]); + }); + test("a Container runtime whose Dockerfile is missing fails instead of switching", async () => { const root = await project({ "app/search/main.py": "", diff --git a/src/core/project/runtimeBuild.ts b/src/core/project/runtimeBuild.ts index e40337cd6e..6d864356ac 100644 --- a/src/core/project/runtimeBuild.ts +++ b/src/core/project/runtimeBuild.ts @@ -82,6 +82,26 @@ export function syncRuntimeBuild(runtime: ProjectRuntime, projectRoot: string): const next: ProjectRuntime = { ...runtime }; const reasons: Partial> = {}; const warnings: string[] = []; + + // A pre-built image is the complete container artifact: local manifests, + // Dockerfiles, and build contexts take no part in deploying it, so nothing is + // inferred from them. runtimeVersion does not apply to a container image. + if (runtime.containerUri !== undefined) { + if (next.runtimeVersion === undefined) return { runtime: next, changes: [], warnings }; + delete next.runtimeVersion; + return { + runtime: next, + changes: [ + { + field: "runtimeVersion", + from: runtime.runtimeVersion, + to: undefined, + reason: "pre-built container image", + }, + ], + warnings, + }; + } const context = contextDir(runtime, projectRoot); const contextLabel = displayPath(projectRoot, context); @@ -529,7 +549,7 @@ export function prepareRuntimes( const pointAtReadme = (found: string[]) => problems.push(...found.map((problem) => `${problem.replace(/\.?$/, ".")} See ${readme}.`)); const folder = resolve(projectRoot, runtime.codeLocation); - if (!isDirectory(folder)) { + if (runtime.containerUri === undefined && !isDirectory(folder)) { pointAtReadme([ `runtime "${runtime.name}": ${displayPath(projectRoot, folder)}/ does not exist.`, ]); @@ -567,6 +587,7 @@ function runtimeProblems( const folder = resolve(projectRoot, runtime.codeLocation); const folderLabel = `${displayPath(projectRoot, folder)}/`; const problems: string[] = []; + if (runtime.containerUri !== undefined) return problems; if (isContainerBuild(runtime)) { const context = contextDir(runtime, projectRoot); const dockerfile = runtime.dockerfile ?? DOCKERFILE_NAME; diff --git a/src/core/project/templates/runtimeDocs.ts b/src/core/project/templates/runtimeDocs.ts index f5ed443e11..f2a7d70950 100644 --- a/src/core/project/templates/runtimeDocs.ts +++ b/src/core/project/templates/runtimeDocs.ts @@ -131,16 +131,20 @@ export async function runtimeDocsTree( * The agentcore.json entry for a docs-only runtime, with starting values: a * CodeZip build on the latest runtime for the language. dev, build, and deploy * update build, runtimeVersion, and entrypoint from the code once it exists. + * With containerUri, a Container build of that image; codeLocation and + * entrypoint are schema-required placeholders that nothing reads. */ export function buildDocsRuntimeSpec(input: RuntimeDocsConfig): ProjectRuntime { const { name, language, ...infra } = input; return { name, codeLocation: `app/${name}` as ProjectRuntime["codeLocation"], - build: input.build ?? "CodeZip", - ...((input.build === undefined || input.build === "CodeZip") && { - runtimeVersion: language === "TypeScript" ? LATEST_NODE : LATEST_PYTHON, - }), + build: input.build ?? (input.containerUri ? "Container" : "CodeZip"), + ...(input.containerUri && { containerUri: input.containerUri }), + ...(input.containerUri === undefined && + (input.build === undefined || input.build === "CodeZip") && { + runtimeVersion: language === "TypeScript" ? LATEST_NODE : LATEST_PYTHON, + }), ...(input.dockerfile && { dockerfile: input.buildContextPath ? input.dockerfile : "Dockerfile", }), diff --git a/src/handlers/project/add/buildConfig.ts b/src/handlers/project/add/buildConfig.ts index b87e781303..c728231ad5 100644 --- a/src/handlers/project/add/buildConfig.ts +++ b/src/handlers/project/add/buildConfig.ts @@ -3,6 +3,7 @@ import { flag } from "../../../router"; import { parseJsonFlagWithSchema } from "../../utils"; import { isAbsolute } from "node:path"; import { + containerUriIssues, DockerfilePathSchema, isReservedBuildArgKey, ProjectRuntimeSchema, @@ -64,8 +65,17 @@ function checkBuildFields(data: BuildConfigFields, ctx: z.RefinementCtx, default } export const RuntimeBuildConfigSchema = z - .strictObject({ build: ProjectRuntimeSchema.shape.build.optional(), ...buildFields }) + .strictObject({ + build: ProjectRuntimeSchema.shape.build.optional(), + // A pre-built ECR image; deployed as is, with build "Container" (the default). + containerUri: ProjectRuntimeSchema.shape.containerUri, + ...buildFields, + }) .superRefine((data, ctx) => { + if (data.containerUri !== undefined) { + for (const issue of containerUriIssues(data)) ctx.addIssue({ code: "custom", ...issue }); + return; + } const container = data.build === "Container" || data.build === "ContainerLocal"; if (container && data.dockerfile === undefined) { ctx.addIssue({ @@ -89,15 +99,15 @@ export const HarnessBuildConfigSchema = z .strictObject({ build: HarnessSpecSchema.shape.build, ...buildFields }) .superRefine((data, ctx) => checkBuildFields(data, ctx, "Container")); -export function buildConfigFlag(builds: string) { +export function buildConfigFlag(builds: string, extraKeys = "") { return flag( "build-config", - `advanced build settings (JSON object): build (${builds}), dockerfile, buildContextPath, ` + - "customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the " + - "current directory, copied once to app//Dockerfile (app// is the build " + - "context). With buildContextPath (relative to the project root), dockerfile is relative " + - "to that build context and used in place. Build args are not secret: they appear in " + - "logs and image metadata", + `advanced build settings (JSON object): build (${builds}), ${extraKeys}dockerfile, ` + + "buildContextPath, customDockerBuildArgs. Without buildContextPath, dockerfile is a path " + + "relative to the current directory, copied once to app//Dockerfile (app// is " + + "the build context). With buildContextPath (relative to the project root), dockerfile is " + + "relative to that build context and used in place. Build args are not secret: they " + + "appear in logs and image metadata", z.string().optional(), { group: ADVANCED }, ); diff --git a/src/handlers/project/add/runtime/index.test.ts b/src/handlers/project/add/runtime/index.test.ts index b9bc61335a..21feb9aa05 100644 --- a/src/handlers/project/add/runtime/index.test.ts +++ b/src/handlers/project/add/runtime/index.test.ts @@ -65,6 +65,144 @@ async function runtimeOf(projectRoot: string, name: string) { return spec.runtimes.find((candidate: { name: string }) => candidate.name === name); } +describe("runtime pre-built image (--build-config containerUri)", () => { + const privateUri = "123456789012.dkr.ecr.us-west-2.amazonaws.com/team/agent:v1"; + + test.each([ + privateUri, + "public.ecr.aws/example/agent:v1", + `${privateUri.split(":")[0]}@sha256:${"a".repeat(64)}`, + ])("adds a pre-built image without language or local scaffolding: %s", async (containerUri) => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const { io, core } = await run([ + "add", + "runtime", + "--name", + "image", + "--build-config", + JSON.stringify({ containerUri }), + ]); + expect(await runtimeOf(projectRoot, "image")).toEqual({ + name: "image", + codeLocation: "app/image", + entrypoint: "main.py", + build: "Container", + protocol: "HTTP", + containerUri, + }); + expect(await Bun.file(join(projectRoot, "app", "image", "README.md")).exists()).toBe(false); + expect(core.projectCommands).toEqual([]); + expect(io.stderr()).toContain("from a pre-built ECR image"); + expect(io.stderr()).not.toContain("write your agent"); + }); + + test("keeps the other add runtime flags, including CodeBuild-free VPC settings", async () => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const networkConfig = { + subnets: ["subnet-0123456789abcdef0"], + securityGroups: Array.from({ length: 6 }, (_, i) => `sg-${String(i).padStart(17, "0")}`), + }; + await run([ + "add", + "runtime", + "--name", + "image", + "--language", + "typescript", + "--protocol", + "MCP", + "--network-mode", + "VPC", + "--network-config", + JSON.stringify(networkConfig), + "--build-config", + JSON.stringify({ build: "Container", containerUri: privateUri }), + ]); + expect(await runtimeOf(projectRoot, "image")).toMatchObject({ + build: "Container", + containerUri: privateUri, + entrypoint: "main.js", + protocol: "MCP", + networkMode: "VPC", + networkConfig, + }); + }); + + test.each<[string, Record, string]>([ + ["build CodeZip", { build: "CodeZip" }, "containerUri requires build 'Container'"], + [ + "build ContainerLocal", + { build: "ContainerLocal" }, + "containerUri requires build 'Container'", + ], + ["a Dockerfile", { dockerfile: "Dockerfile" }, "dockerfile cannot be used with containerUri"], + [ + "a build context", + { buildContextPath: "app" }, + "buildContextPath cannot be used with containerUri", + ], + [ + "build args", + { customDockerBuildArgs: { VERSION: "1" } }, + "customDockerBuildArgs cannot be used with containerUri", + ], + ])("rejects containerUri with %s before writing anything", async (_label, extra, message) => { + const { projectRoot, cleanup } = await initProject(); + cleanups.push(cleanup); + const before = await specOf(projectRoot); + await expectError( + run([ + "add", + "runtime", + "--name", + "image", + "--build-config", + JSON.stringify({ containerUri: privateUri, ...extra }), + ]), + message, + InputValidationError, + ); + expect(await specOf(projectRoot)).toEqual(before); + }); + + test.each([ + '{"containerUri":"https://example.com/image:v1"}', + '{"containerUri":"docker.io/library/python:3.12"}', + '{"container_uri":"typo"}', + '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1 "}', + '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1!"}', + '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/agent@sha256:XYZ"}', + '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/a:v1"}', + ])("rejects an invalid image setting: %s", async (value) => { + const { cleanup } = await initProject(); + cleanups.push(cleanup); + await expectError( + run(["add", "runtime", "--name", "image", "--build-config", value]), + "--build-config", + InputValidationError, + ); + }); + + test("rejects pre-built images with a Bedrock Agent import", async () => { + const { cleanup } = await initProject(); + cleanups.push(cleanup); + await expect( + run([ + "add", + "runtime", + "--name", + "image", + "--agent-id", + "A1B2C3D4E5", + "--build-config", + JSON.stringify({ containerUri: privateUri }), + ]), + ).rejects.toThrow(/--build-config cannot be combined/); + }); +}); + describe("project add runtime", () => { test.each(["Container", "ContainerLocal"])( "--build-config with build %s persists it and copies the Dockerfile", diff --git a/src/handlers/project/add/runtime/index.ts b/src/handlers/project/add/runtime/index.ts index eecaebc547..4895d8d8c1 100644 --- a/src/handlers/project/add/runtime/index.ts +++ b/src/handlers/project/add/runtime/index.ts @@ -4,7 +4,12 @@ import { isChinaRegion } from "../../../../core/partition"; import type { AddProjectResourceConfig } from "../types"; import { parseJsonFlag, parseTags, tagsFlag } from "../../../utils"; import { InputValidationError, RegionUnsupportedFeatureError } from "../../../../errors"; -import { AgentNameSchema, type EnvVar } from "../../../../projectSchemas/runtime"; +import { + AgentNameSchema, + ProjectRuntimeSchema, + type EnvVar, +} from "../../../../projectSchemas/runtime"; +import { buildDocsRuntimeSpec } from "../../../../core/project/templates/runtimeDocs"; import { RuntimeAuthorizerTypeSchema } from "../../../../projectSchemas/auth"; import { NetworkModeSchema, @@ -61,6 +66,13 @@ export function toAddRuntimeInput(input: RuntimeInput): AddResourceInput { : RuntimeDocsConfigSchema.safeParse(input); if (!result.success) throw new InputValidationError(z.prettifyError(result.error), { cause: result.error }); + // A pre-built image adds the agentcore.json entry directly, so check that + // entry against the agentcore.json schema here rather than at the next load. + if (!("scaffoldRuntimeInput" in result.data) && result.data.containerUri !== undefined) { + const runtime = ProjectRuntimeSchema.safeParse(buildDocsRuntimeSpec(result.data)); + if (!runtime.success) + throw new InputValidationError(z.prettifyError(runtime.error), { cause: runtime.error }); + } return { resourceType: "runtime", resourceConfig: result.data }; } @@ -73,7 +85,15 @@ export function runtimeDocsAddedMessage( name: string, language: "Python" | "TypeScript", protocol: ProtocolMode, + containerUri?: string, ): string { + if (containerUri !== undefined) + return [ + `added runtime "${name}" (${protocol}) from a pre-built ECR image`, + "", + "next steps:", + " 1. deploy it with agentcore deploy", + ].join("\n"); const folder = `app/${name}`; return [ `added runtime "${name}" (${language}, ${protocol})`, @@ -95,7 +115,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => flag("name", "the name of the Runtime", AgentNameSchema, { group: CONFIGURATION }), flag( "language", - "language you will write the Runtime in: python or typescript (required unless --agent-id imports a Bedrock Agent)", + "language you will write the Runtime in: python or typescript (required unless --agent-id imports a Bedrock Agent or --build-config sets containerUri)", z.enum(["python", "typescript"]).optional(), { group: CONFIGURATION }, ), @@ -186,13 +206,14 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => z.enum(["strands", "langgraph"]).optional(), { group: BEDROCK_AGENT_IMPORT }, ), - buildConfigFlag("CodeZip, Container, or ContainerLocal"), + buildConfigFlag("CodeZip, Container, or ContainerLocal", "containerUri, "), ], handle: async (ctx, flags) => { const project = ctx.require(ProjectKey); const deploymentTargets = await config.projectManager.listTargets(project); requireDeployedNameFits("Runtime", project.name, flags.name, "_", 48, deploymentTargets); + const buildConfig = parseBuildConfig(flags["build-config"], RuntimeBuildConfigSchema); // Passing --agent-id is what selects a Bedrock Agent import. const isImport = flags["agent-id"] !== undefined; @@ -214,7 +235,7 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => `--${offending} cannot be combined with it`, ); } - } else if (flags.language === undefined) { + } else if (flags.language === undefined && buildConfig?.containerUri === undefined) { throw new InputValidationError( "required option '--language ' not specified: pass python or typescript", ); @@ -263,7 +284,10 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => const infra = { name: flags.name, - ...parseBuildConfig(flags["build-config"], RuntimeBuildConfigSchema), + ...buildConfig, + // A pre-built image deploys as a Container Runtime. + ...(buildConfig?.containerUri !== undefined && + buildConfig.build === undefined && { build: "Container" as const }), description: flags.description, executionRoleArn: flags["role-arn"], additionalPolicies: flags["additional-policies"], @@ -306,14 +330,15 @@ export const createAddRuntimeHandler = (config: AddProjectResourceConfig) => return; } - const language = RUNTIME_LANGUAGES[flags.language!]; + // The language only names the docs; a pre-built image writes none. + const language = RUNTIME_LANGUAGES[flags.language ?? "python"]; const protocol = flags.protocol ?? "HTTP"; await addProjectResource( ctx, config, project, toAddRuntimeInput({ ...infra, language, protocol }), - runtimeDocsAddedMessage(flags.name, language, protocol), + runtimeDocsAddedMessage(flags.name, language, protocol, buildConfig?.containerUri), ); }, }); diff --git a/src/handlers/project/add/runtime/types.ts b/src/handlers/project/add/runtime/types.ts index 618aebb731..16ed07f1a9 100644 --- a/src/handlers/project/add/runtime/types.ts +++ b/src/handlers/project/add/runtime/types.ts @@ -1,5 +1,5 @@ import z from "zod"; -import { ProjectRuntimeSchema } from "../../../../projectSchemas/runtime"; +import { containerUriIssues, ProjectRuntimeSchema } from "../../../../projectSchemas/runtime"; import { ScaffoldRuntimeInputSchema } from "../../types"; import { BedrockAgentImportPlanSchema } from "../../../../core/project/bedrockAgentImport"; @@ -22,6 +22,7 @@ const RuntimeInfraConfigSchema = z.object({ filesystemConfigurations: ProjectRuntimeSchema.shape.filesystemConfigurations, tags: ProjectRuntimeSchema.shape.tags, build: ProjectRuntimeSchema.shape.build.optional(), + containerUri: ProjectRuntimeSchema.shape.containerUri, dockerfile: z.string().min(1).optional(), buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs, @@ -38,11 +39,16 @@ export type RuntimeResourceConfig = z.infer; * A runtime added without code: the CLI writes README.md and AGENTS.md for the * language and protocol into app//, and the user (or their coding agent) * writes the code. The spec entry starts with default build settings, which - * dev, build, and deploy update from the code. + * dev, build, and deploy update from the code. With containerUri it deploys an + * existing image instead, and no files are written. */ export const RuntimeDocsConfigSchema = RuntimeInfraConfigSchema.extend({ language: z.enum(["Python", "TypeScript"]), }).superRefine((data, ctx) => { + if (data.containerUri !== undefined) { + for (const issue of containerUriIssues(data)) ctx.addIssue({ code: "custom", ...issue }); + return; + } const container = data.build === "Container" || data.build === "ContainerLocal"; if (container && data.dockerfile === undefined) { ctx.addIssue({ diff --git a/src/handlers/project/deploy/index.test.ts b/src/handlers/project/deploy/index.test.ts index 99827861fb..b0639b3720 100644 --- a/src/handlers/project/deploy/index.test.ts +++ b/src/handlers/project/deploy/index.test.ts @@ -518,6 +518,37 @@ describe("project deploy handler", () => { }); }); + test("counts pre-built image Runtimes as ContainerUri", async () => { + const subject = await testDeployCommand({ outputs: {} }); + await inProjectWithTargets(); + const add = createRootHandler(new TestCoreClient(), { + io: testIO().io, + globalConfigAccessor: new TestGlobalConfigAccessor(), + logger: createSilentLogger(), + }); + await add.route([ + "node", + "agentcore", + "add", + "runtime", + "--name", + "image", + "--build-config", + '{"containerUri":"123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1"}', + ]); + + await subject.run(); + + expect(subject.calls[0]?.input.workloadBuilds).toMatchObject({ + "runtime/image": "ContainerUri", + }); + await assertMetricEmitted(subject.telemetryFilePath, "cli.command_run", { + command_path: "/agentcore/deploy", + project_runtime_container_uri_count: 1, + project_runtime_container_count: 0, + }); + }); + test("passes the global config's transactionSearch flag into the deploy", async () => { const enabled = await testDeployCommand({ outputs: {} }); await inProjectWithTargets(); diff --git a/src/handlers/project/deploy/index.ts b/src/handlers/project/deploy/index.ts index 5a46d87904..37d77c7a31 100644 --- a/src/handlers/project/deploy/index.ts +++ b/src/handlers/project/deploy/index.ts @@ -177,6 +177,7 @@ export function recordBuildTypeCounts(ctx: Context, builds: WorkloadBuilds): voi project_runtime_codezip_count: count("runtime", "CodeZip"), project_runtime_container_count: count("runtime", "Container"), project_runtime_container_local_count: count("runtime", "ContainerLocal"), + project_runtime_container_uri_count: count("runtime", "ContainerUri"), project_harness_container_count: count("harness", "Container"), project_harness_container_local_count: count("harness", "ContainerLocal"), }); diff --git a/src/handlers/project/dev/index.test.ts b/src/handlers/project/dev/index.test.ts index ba6242e84b..90053e8362 100644 --- a/src/handlers/project/dev/index.test.ts +++ b/src/handlers/project/dev/index.test.ts @@ -271,7 +271,24 @@ async function inspectorStatus(subject: ReturnType): Promise<{ n return status.agents; } +const prebuiltRuntime = (name = "image"): ProjectRuntime => ({ + ...runtime(name, "Container"), + containerUri: "123456789012.dkr.ecr.us-west-2.amazonaws.com/agent:v1", +}); + describe("project dev build settings sync", () => { + test("pre-built images fail before any local builder, environment, or listener starts", async () => { + const subject = harness({ project: project(runtime("orders"), prebuiltRuntime()) }); + await expect(subject.run({ agent: "image" })).rejects.toThrow( + "Runtime 'image' uses a pre-built containerUri. Deploy it with agentcore deploy, then use agentcore invoke.", + ); + expect(subject.container.inputs).toEqual([]); + expect(subject.codeZip.inputs).toEqual([]); + expect(subject.environmentInputs).toEqual([]); + expect(subject.collector.starts).toEqual([]); + expect(subject.ui.starts).toEqual([]); + }); + async function codeProject(files: Record) { const root = await mkdtemp(join(tmpdir(), "dev-sync-")); for (const [path, content] of Object.entries(files)) { @@ -503,6 +520,34 @@ describe("project dev headless multi-agent", () => { expect(subject.collector.state.closed).toBe(1); }); + test("a mixed project without --agent skips pre-built runtimes and runs the rest", async () => { + const codeZip = stayingRunner(); + const container = stayingRunner(); + const subject = harness({ + project: project(runtime("orders"), prebuiltRuntime(), runtime("support", "Container")), + codeZip, + container, + }); + const { pending } = await supervised(subject); + + expect(subject.io.stderr()).toContain( + "Skipping runtime 'image': it deploys a pre-built image. Deploy it with agentcore deploy, then use agentcore invoke.", + ); + expect(codeZip.inputs.map(({ runtime }) => runtime.name)).toEqual(["orders"]); + expect(container.inputs.map(({ runtime }) => runtime.name)).toEqual(["support"]); + + process.emit("SIGINT", "SIGINT"); + await expect(pending).rejects.toMatchObject({ exitCode: 130 }); + }); + + test("a project of only pre-built runtimes gives the deploy-and-invoke guidance", async () => { + const subject = harness({ project: project(prebuiltRuntime("a"), prebuiltRuntime("b")) }); + await expect(subject.run()).rejects.toThrow( + "Runtime 'a' uses a pre-built containerUri. Deploy it with agentcore deploy", + ); + expect(subject.container.inputs).toEqual([]); + }); + test("assigns distinct ports to runtimes launched together", async () => { const codeZip = stayingRunner(); const container = stayingRunner(); @@ -668,6 +713,21 @@ describe("project dev Inspector UI mode", () => { await pending.catch(() => undefined); }); + test("a reload never passes a newly added pre-built runtime to the local runner", async () => { + const subject = harness({ + reloadedRuntimes: [runtime("orders"), prebuiltRuntime()], + }); + const { pending } = await runUi(subject); + + subject.watchers[0]!.onChange(); + await Bun.sleep(5); + + expect((await inspectorStatus(subject)).map((agent) => agent.name)).toEqual(["orders"]); + + process.emit("SIGINT", "SIGINT"); + await pending.catch(() => undefined); + }); + test("agentcore.json edits reload the supervised agents", async () => { const subject = harness({ reloadedRuntimes: [bmaRuntime({ tags: undefined }), runtime("orders"), runtime("payments")], diff --git a/src/handlers/project/dev/index.ts b/src/handlers/project/dev/index.ts index a21cfa09e1..d49106b712 100644 --- a/src/handlers/project/dev/index.ts +++ b/src/handlers/project/dev/index.ts @@ -71,9 +71,11 @@ function otelEnvForRuntime( } function supportsLocalDev(runtime: ProjectRuntime): boolean { - return !isBmaRuntime(runtime); + return !isBmaRuntime(runtime) && runtime.containerUri === undefined; } +const PREBUILT_DEV_GUIDANCE = "Deploy it with agentcore deploy, then use agentcore invoke."; + /** An agent's own output, always tagged with the agent that produced it. */ function renderAgentEvent({ io, @@ -231,6 +233,13 @@ function resolveAgentSelection(project: Project, agent?: string): AgentSelection ); } const supportedRuntimes = selectedRuntimes.filter(supportsLocalDev); + const prebuilt = selectedRuntimes.find((runtime) => runtime.containerUri !== undefined); + if (!supportedRuntimes.length && prebuilt) { + throw new InputValidationError( + `Runtime '${prebuilt.name}' uses a pre-built containerUri. ${PREBUILT_DEV_GUIDANCE} ` + + "For local dev, select a runtime with local source using --agent .", + ); + } if (!supportedRuntimes.length) { throw new NotImplementedError( `Local dev is not supported for runtime '${selectedRuntimes[0]!.name}' (${BMA_TEMPLATE_NAME}). ` + @@ -376,7 +385,10 @@ async function runRuntimeDev({ )) { renderStatus({ io: config.io, - message: `Skipping runtime '${runtime.name}': local dev is not supported for ${BMA_TEMPLATE_NAME}.`, + message: + runtime.containerUri !== undefined + ? `Skipping runtime '${runtime.name}': it deploys a pre-built image. ${PREBUILT_DEV_GUIDANCE}` + : `Skipping runtime '${runtime.name}': local dev is not supported for ${BMA_TEMPLATE_NAME}.`, json, }); } diff --git a/src/projectSchemas/constants.ts b/src/projectSchemas/constants.ts index a7a8c6e31f..2455eb1c25 100644 --- a/src/projectSchemas/constants.ts +++ b/src/projectSchemas/constants.ts @@ -74,6 +74,60 @@ export const VPC_ID_PATTERN = /^vpc-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SUBNET_ID_PATTERN = /^subnet-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const SECURITY_GROUP_ID_PATTERN = /^sg-(?:[0-9a-f]{8}|[0-9a-f]{17})$/; export const MAX_CONTAINER_BUILD_SECURITY_GROUPS = 5; +/** + * A private ECR image URI (`<12-digit account>.dkr.ecr..amazonaws.com[.cn]/`) + * or a public one (`public.ecr.aws//`), with an optional tag and digest. + * Groups: 1 account, 2 region, 3 `.cn`, 4 private repository, 5 public alias, + * 6 public repository, 7 tag, 8 digest. + */ +export const CONTAINER_URI_PATTERN = + /^(?:([0-9]{12})\.dkr\.ecr\.([a-z0-9-]+)\.amazonaws\.com(\.cn)?\/((?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*)|public\.ecr\.aws\/([a-z0-9]+(?:[._-][a-z0-9]+)*)\/((?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*))(?::([^:@]{1,300}))?(?:@(.+))?$/; +export const MAX_CONTAINER_URI_LENGTH = 1024; +// The service's image tag and digest grammar, and its repository name lengths. +const CONTAINER_IMAGE_TAG_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$/; +const CONTAINER_IMAGE_DIGEST_PATTERN = /^(?:sha256:[a-f0-9]{64}|sha512:[a-f0-9]{128})$/; +const MIN_REPOSITORY_NAME_LENGTH = 2; +const MAX_PRIVATE_REPOSITORY_NAME_LENGTH = 256; +const MAX_PUBLIC_REPOSITORY_NAME_LENGTH = 205; +export const ContainerUriSchema = z + .string() + .min(1) + .max(MAX_CONTAINER_URI_LENGTH) + .superRefine((uri, ctx) => { + const fail = (message: string) => ctx.addIssue({ code: "custom", message }); + if (/\s/.test(uri)) return fail("containerUri must not contain whitespace"); + const match = CONTAINER_URI_PATTERN.exec(uri); + if (!match) { + if (/^public\.ecr\.aws\/[^/:@]*(?:[:@]|$)/.test(uri)) { + return fail( + "containerUri for public.ecr.aws must name a registry alias and a repository: " + + "public.ecr.aws//[:tag][@digest]", + ); + } + return fail("containerUri must be an ECR image URI (12-digit private ECR or public.ecr.aws)"); + } + const [, , , , privateRepository, , publicRepository, tag, digest] = match; + // The public registry alias is not part of the repository name. + const repository = privateRepository ?? publicRepository ?? ""; + const maxRepositoryLength = + publicRepository !== undefined + ? MAX_PUBLIC_REPOSITORY_NAME_LENGTH + : MAX_PRIVATE_REPOSITORY_NAME_LENGTH; + if (repository.length < MIN_REPOSITORY_NAME_LENGTH || repository.length > maxRepositoryLength) { + fail( + `containerUri repository name must be ${MIN_REPOSITORY_NAME_LENGTH}-${maxRepositoryLength} characters`, + ); + } + if (tag !== undefined && !CONTAINER_IMAGE_TAG_PATTERN.test(tag)) { + fail( + "containerUri tag must start with a letter, digit or '_' and have at most 128 letters, " + + "digits, '.', '_' or '-'", + ); + } + if (digest !== undefined && !CONTAINER_IMAGE_DIGEST_PATTERN.test(digest)) { + fail("containerUri digest must be sha256:<64 hex digits> or sha512:<128 hex digits>"); + } + }); export function isContainerBuild(spec: { build?: string; containerUri?: string; diff --git a/src/projectSchemas/harness.ts b/src/projectSchemas/harness.ts index b6208b1e59..86d108de10 100644 --- a/src/projectSchemas/harness.ts +++ b/src/projectSchemas/harness.ts @@ -1,5 +1,9 @@ import { ProjectRuntimeSchema, BuildTypeSchema, isReservedBuildArgKey } from "./runtime"; -import { MAX_CONTAINER_BUILD_SECURITY_GROUPS, NetworkModeSchema } from "./constants"; +import { + ContainerUriSchema, + MAX_CONTAINER_BUILD_SECURITY_GROUPS, + NetworkModeSchema, +} from "./constants"; import { EfsAccessPointConfigSchema, LifecycleConfigurationSchema, @@ -13,9 +17,7 @@ import { uniqueBy } from "./zod-util"; import { TagsSchema } from "./tags"; import { z } from "zod"; import { modelIdHelp } from "./modelDocs"; -export const CONTAINER_URI_PATTERN = - /^(([0-9]{12})\.dkr\.ecr\.([a-z0-9-]+)\.amazonaws\.com(\.cn)?|public\.ecr\.aws)\/((?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*)(?::([^:@]{1,300}))?(?:@(.+))?$/; -export const MAX_CONTAINER_URI_LENGTH = 1024; +export { CONTAINER_URI_PATTERN, MAX_CONTAINER_URI_LENGTH } from "./constants"; export const MAX_ENV_VAR_VALUE_LENGTH = 5000; export const MAX_ENV_VARS = 50; export const MAX_ENV_VAR_KEY_LENGTH = 100; @@ -512,15 +514,7 @@ export const HarnessSpecSchema = z maxTokens: z.number().int().min(1).optional(), timeoutSeconds: z.number().int().min(1).optional(), truncation: HarnessTruncationConfigSchema.optional(), - containerUri: z - .string() - .min(1) - .max(MAX_CONTAINER_URI_LENGTH) - .regex( - CONTAINER_URI_PATTERN, - "containerUri must be an ECR image URI (12-digit private ECR or public.ecr.aws)", - ) - .optional(), + containerUri: ContainerUriSchema.optional(), build: BuildTypeSchema.exclude(["CodeZip"]).optional(), buildContextPath: ProjectRuntimeSchema.shape.buildContextPath, customDockerBuildArgs: ProjectRuntimeSchema.shape.customDockerBuildArgs, diff --git a/src/projectSchemas/runtime.test.ts b/src/projectSchemas/runtime.test.ts index 967991cb15..8044473441 100644 --- a/src/projectSchemas/runtime.test.ts +++ b/src/projectSchemas/runtime.test.ts @@ -19,6 +19,12 @@ const containerAgent = { entrypoint: "main.py", codeLocation: "./agent", }; +const privateContainerUri = "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/agent:latest"; +const publicContainerUri = `public.ecr.aws/example/agent@sha256:${"a".repeat(64)}`; +const prebuiltAgent = { + ...containerAgent, + containerUri: privateContainerUri, +}; const networkConfig = { subnets: ["subnet-0123456789abcdef0"], securityGroups: ["sg-0123456789abcdef0"], @@ -84,6 +90,7 @@ describe("runtime custom validation", () => { }); it("restricts container-only fields to container builds", () => { for (const field of [ + { containerUri: privateContainerUri }, { dockerfile: "Dockerfile" }, { buildContextPath: "." }, { customDockerBuildArgs: { KEY: "value" } }, @@ -92,6 +99,105 @@ describe("runtime custom validation", () => { expect(ProjectRuntimeSchema.safeParse({ ...containerAgent, ...field }).success).toBe(true); } }); + it.each([privateContainerUri, publicContainerUri])( + "accepts a supported pre-built ECR image URI: %s", + (containerUri) => { + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, containerUri }).success).toBe(true); + }, + ); + it.each([ + "docker.io/example/agent:latest", + "12345678901.dkr.ecr.us-east-1.amazonaws.com/agent:latest", + "123456789012.dkr.ecr.us-east-1.amazonaws.com/UPPERCASE:latest", + `${privateContainerUri}${"x".repeat(1025)}`, + ])("rejects an invalid pre-built image URI: %s", (containerUri) => { + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, containerUri }).success).toBe(false); + }); + const ecr = "123456789012.dkr.ecr.us-west-2.amazonaws.com"; + it.each([ + `${ecr}/ab:v1`, + `${ecr}/${"a".repeat(256)}:v1`, + `public.ecr.aws/myalias/${"a".repeat(205)}:v1`, + `public.ecr.aws/myalias/ns/${"a".repeat(202)}:v1`, + "public.ecr.aws/myalias/ab:v1", + `${ecr}/agent:_v1.0-rc`, + `${ecr}/agent:${"a".repeat(128)}`, + `${ecr}/agent@sha256:${"0".repeat(64)}`, + `${ecr}/agent:v1@sha512:${"f".repeat(128)}`, + ])("accepts a URI within the service image grammar: %s", (containerUri) => { + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, containerUri }).success).toBe(true); + }); + it.each([ + [`${ecr}/agent:v1 `, "containerUri must not contain whitespace"], + [`${ecr}/agent:v1 v2\n`, "containerUri must not contain whitespace"], + [` ${ecr}/agent:v1`, "containerUri must not contain whitespace"], + [`${ecr}/agent:v1!`, "containerUri tag must start with a letter, digit or '_'"], + [`${ecr}/agent:.v1`, "containerUri tag must start with a letter, digit or '_'"], + [`${ecr}/agent:${"a".repeat(129)}`, "containerUri tag must start with a letter, digit or '_'"], + [`${ecr}/agent@sha256:XYZ`, "containerUri digest must be sha256:<64 hex digits>"], + [`${ecr}/agent@md5:abc`, "containerUri digest must be sha256:<64 hex digits>"], + [`${ecr}/agent@sha256:${"A".repeat(64)}`, "containerUri digest must be sha256:<64 hex digits>"], + [`${ecr}/a:v1`, "containerUri repository name must be 2-256 characters"], + [`${ecr}/${"a".repeat(257)}:v1`, "containerUri repository name must be 2-256 characters"], + [ + `public.ecr.aws/myalias/${"a".repeat(206)}:v1`, + "containerUri repository name must be 2-205 characters", + ], + ["public.ecr.aws/myalias/a:v1", "containerUri repository name must be 2-205 characters"], + [ + "public.ecr.aws/abcdefgh:v1", + "containerUri for public.ecr.aws must name a registry alias and a repository", + ], + [ + "public.ecr.aws/abcdefgh", + "containerUri for public.ecr.aws must name a registry alias and a repository", + ], + [ + `public.ecr.aws/myalias/agent@sha256:${"A".repeat(64)}`, + "containerUri digest must be sha256:<64 hex digits>", + ], + ])("rejects a URI outside the service image grammar: %s", (containerUri, message) => { + const result = ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, containerUri }); + expect(result.success).toBe(false); + expect(result.error?.issues.map((issue) => issue.message).join("; ")).toContain(message); + }); + it.each([ + { dockerfile: "Dockerfile" }, + { buildContextPath: "." }, + { customDockerBuildArgs: { STAGE: "prod" } }, + ])("rejects local build configuration with containerUri: %j", (field) => { + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, ...field }).success).toBe(false); + }); + it.each(["CodeZip", "ContainerLocal"])( + "requires build Container with containerUri, not %s", + (build) => { + const result = ProjectRuntimeSchema.safeParse({ + ...prebuiltAgent, + build, + runtimeVersion: "PYTHON_3_12", + }); + expect(result.success).toBe(false); + expect(result.error?.issues).toContainEqual( + expect.objectContaining({ + path: ["containerUri"], + message: + "containerUri requires build 'Container' (it cannot be used with CodeZip or ContainerLocal)", + }), + ); + }, + ); + it("exempts a pre-built image from the CodeBuild VPC limits", () => { + expect( + ProjectRuntimeSchema.safeParse({ + ...prebuiltAgent, + networkMode: "VPC", + networkConfig: { + subnets: ["subnet-0123456789abcdef0"], + securityGroups: Array.from({ length: 6 }, (_, i) => `sg-${String(i).padStart(17, "0")}`), + }, + }).success, + ).toBe(true); + }); it("rejects reserved build args and control characters", () => { expect( ProjectRuntimeSchema.safeParse({ @@ -150,6 +256,7 @@ describe("runtime custom validation", () => { expect(capped.success).toBe(false); expect(capped.error?.issues[0]?.path).toEqual(["networkConfig", "securityGroups"]); expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, ...vpc }).success).toBe(true); + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, ...vpc }).success).toBe(true); }); it("requires a VPC ID for container builds in VPC mode only", () => { const vpc = { networkMode: "VPC" as const, networkConfig }; @@ -166,6 +273,7 @@ describe("runtime custom validation", () => { // CodeZip never reaches CodeBuild, so it needs no VPC ID. expect(ProjectRuntimeSchema.safeParse({ ...codeZipAgent, ...vpc }).success).toBe(true); + expect(ProjectRuntimeSchema.safeParse({ ...prebuiltAgent, ...vpc }).success).toBe(true); expect(ProjectRuntimeSchema.safeParse(containerAgent).success).toBe(true); }); }); diff --git a/src/projectSchemas/runtime.ts b/src/projectSchemas/runtime.ts index bd7bbc1926..a1009d1325 100644 --- a/src/projectSchemas/runtime.ts +++ b/src/projectSchemas/runtime.ts @@ -1,4 +1,5 @@ import { + ContainerUriSchema, MAX_CONTAINER_BUILD_SECURITY_GROUPS, NetworkModeSchema, ProtocolModeSchema, @@ -283,6 +284,41 @@ export const ModelProviderSchema = z.preprocess( z.enum(MODEL_PROVIDERS), ); +/** + * The rules for a pre-built image (`containerUri`): it is the whole container + * artifact, so it needs `build: "Container"` and excludes every local build + * setting. Shared by agentcore.json and `add runtime --build-config`. The CDK + * package's Runtime schema applies the same cross-field rules, and its + * ContainerUriSchema enforces the same image URI grammar as ContainerUriSchema + * in constants.ts (tag, digest, repository length, whitespace, total length); + * keep the two in sync. + */ +export function containerUriIssues(data: { + containerUri?: string; + build?: string; + dockerfile?: unknown; + buildContextPath?: unknown; + customDockerBuildArgs?: unknown; +}): { message: string; path: string[] }[] { + if (data.containerUri === undefined) return []; + const issues: { message: string; path: string[] }[] = []; + // Messages and paths match @aws/agentcore-cdk's AgentEnvSpecSchema. An omitted + // build (add runtime --build-config) defaults to Container. + if (data.build !== undefined && data.build !== "Container") { + issues.push({ + message: + "containerUri requires build 'Container' (it cannot be used with CodeZip or ContainerLocal)", + path: ["containerUri"], + }); + } + for (const field of ["dockerfile", "buildContextPath", "customDockerBuildArgs"] as const) { + if (data[field] !== undefined) { + issues.push({ message: `${field} cannot be used with containerUri`, path: [field] }); + } + } + return issues; +} + export const ProjectRuntimeSchema = z .object({ name: AgentNameSchema, @@ -307,6 +343,12 @@ export const ProjectRuntimeSchema = z build: BuildTypeSchema, entrypoint: EntrypointSchema, codeLocation: DirectoryPathSchema, + /** + * An existing private or public ECR image to deploy, with `build: "Container"`. + * Deployment then skips local source, the Dockerfile, CodeBuild, and the + * CDK-managed ECR repository. + */ + containerUri: ContainerUriSchema.optional(), dockerfile: DockerfilePathSchema.optional(), buildContextPath: DirectoryPathSchema.optional(), customDockerBuildArgs: z.record(EnvVarNameSchema, BuildArgValueSchema).optional(), @@ -344,9 +386,11 @@ export const ProjectRuntimeSchema = z path: ["networkConfig"], }); } + // Only a Runtime CodeBuild builds has the CodeBuild VPC limits; a pre-built image does not. + const codeBuildContainer = data.build === "Container" && data.containerUri === undefined; if ( data.networkMode === "VPC" && - data.build === "Container" && + codeBuildContainer && data.networkConfig && data.networkConfig.securityGroups.length > MAX_CONTAINER_BUILD_SECURITY_GROUPS ) { @@ -358,7 +402,7 @@ export const ProjectRuntimeSchema = z } // Mirrors the CDK, which feeds networkConfig.vpcId to the CodeBuild project's // VpcConfig. Only `build: "Container"` reaches that path, so CodeZip is exempt. - if (data.networkMode === "VPC" && data.build === "Container" && !data.networkConfig?.vpcId) { + if (data.networkMode === "VPC" && codeBuildContainer && !data.networkConfig?.vpcId) { ctx.addIssue({ code: "custom", message: @@ -404,6 +448,7 @@ export const ProjectRuntimeSchema = z }); } } + for (const issue of containerUriIssues(data)) ctx.addIssue({ code: "custom", ...issue }); // Reserved by the CodeBuild build environment; ContainerLocal builds locally. // Keep in step with the @aws/agentcore-cdk schema. for (const key of Object.keys(data.customDockerBuildArgs ?? {})) { diff --git a/src/telemetry/shapes.tsx b/src/telemetry/shapes.tsx index 329b1987aa..c9b43ac756 100644 --- a/src/telemetry/shapes.tsx +++ b/src/telemetry/shapes.tsx @@ -81,6 +81,7 @@ export const commandRunSchema = safeSchema({ project_runtime_codezip_count: z.number().int().nonnegative().optional(), project_runtime_container_count: z.number().int().nonnegative().optional(), project_runtime_container_local_count: z.number().int().nonnegative().optional(), + project_runtime_container_uri_count: z.number().int().nonnegative().optional(), project_harness_container_count: z.number().int().nonnegative().optional(), project_harness_container_local_count: z.number().int().nonnegative().optional(), project_payment_manager_count: z.number().int().nonnegative().optional(), From 173134a6a1539923a1af168df8c3ab5546f97901 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 25 Nov 2026 18:00:39 +0000 Subject: [PATCH 10/19] chore(release): v1.3.0 --- command.md | 11 +++++++---- package.json | 2 +- src/assets/cdk/package.json | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/command.md b/command.md index 2f776407ba..5a68c93a68 100644 --- a/command.md +++ b/command.md @@ -2,7 +2,7 @@ # AgentCore CLI command reference -This reference was generated from `agentcore --help` for version `1.2.0`. +This reference was generated from `agentcore --help` for version `1.3.0`. ## Table of contents @@ -316,15 +316,18 @@ add a Runtime to the current project **Options** - `--name `: the name of the Runtime (required) -- `--language `: language you will write the Runtime in: python or typescript (required unless --agent-id imports a Bedrock Agent) +- `--language `: language you will write the Runtime in: python or typescript (required unless --agent-id imports a Bedrock Agent or --build-config sets containerUri) - `--protocol `: protocol the Runtime serves: HTTP (default), MCP, A2A, or AGUI - `--description `: an optional description of the Runtime - `--tags `: tags as repeated key=value entries or one JSON object - `--environment-variables `: environment variables (JSON object of key/value strings) - `--network-mode `: network mode for the Runtime environment (PUBLIC or VPC) - `--network-config `: VPC network configuration (JSON) +- `--platform-version `: Runtime platform version: V1 or V2. If unset, the service picks the version for your account - `--lifecycle-configuration `: session idle timeout and instance lifetime configuration (JSON) -- `--filesystem-configurations `: filesystem mount configurations (JSON) +- `--resource-configurations `: committed per-session memory baseline, e.g. [{"minimumMemoryInMiB":4096}] (JSON, V2 only) +- `--hooks-configuration `: lifecycle hooks, e.g. a build warmup hook (JSON, V2 only) +- `--filesystem-configurations `: filesystem mount configurations (JSON); an s3BucketMount needs --platform-version V2 - `--role-arn `: IAM role ARN that provides permissions for the Runtime - `--additional-policies `: additional IAM policy ARNs or policy document paths for the execution role - `--authorizer-type `: inbound authorizer type (AWS\_IAM or CUSTOM\_JWT) @@ -333,7 +336,7 @@ add a Runtime to the current project - `--agent-id `: Bedrock Agent ID to import; translates that agent version into runtime code instead of writing docs - `--agent-alias-id `: Bedrock Agent Alias ID selecting the version to import; must point at a prepared version, not DRAFT (requires --agent-id) - `--framework `: agent framework for an imported Bedrock Agent: strands or langgraph (requires --agent-id) -- `--build-config `: advanced build settings (JSON object): build (CodeZip, Container, or ContainerLocal), dockerfile, buildContextPath, customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the current directory, copied once to app/<name>/Dockerfile (app/<name>/ is the build context). With buildContextPath (relative to the project root), dockerfile is relative to that build context and used in place. Build args are not secret: they appear in logs and image metadata +- `--build-config `: advanced build settings (JSON object): build (CodeZip, Container, or ContainerLocal), containerUri, dockerfile, buildContextPath, customDockerBuildArgs. Without buildContextPath, dockerfile is a path relative to the current directory, copied once to app/<name>/Dockerfile (app/<name>/ is the build context). With buildContextPath (relative to the project root), dockerfile is relative to that build context and used in place. Build args are not secret: they appear in logs and image metadata #### `agentcore add runtime-endpoint` diff --git a/package.json b/package.json index 14a1f11f90..de131fab0a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@aws/agentcore", - "version": "1.2.0", + "version": "1.3.0", "repository": { "type": "git", "url": "https://github.com/aws/agentcore-cli.git" diff --git a/src/assets/cdk/package.json b/src/assets/cdk/package.json index 091e71a2e0..244b5d9c75 100644 --- a/src/assets/cdk/package.json +++ b/src/assets/cdk/package.json @@ -16,7 +16,7 @@ "typescript": "~5.9.3" }, "dependencies": { - "@aws/agentcore-cdk": "1.2.0", + "@aws/agentcore-cdk": "1.3.0", "aws-cdk-lib": "~2.269.0", "constructs": "~10.7.0" } From b564424f32aed6c18771014bc2d7f793841914e2 Mon Sep 17 00:00:00 2001 From: Nicolas Date: Fri, 27 Nov 2026 09:58:07 -0500 Subject: [PATCH 11/19] fix(region): strip inline comments from AWS config (#2941) * fix(region): strip inline comments from AWS config * fix(region): handle CRLF in AWS config parsing --- src/core/region.ts | 8 ++--- src/middleware/withRegion.test.tsx | 49 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/core/region.ts b/src/core/region.ts index f7c2ba415d..c09421032b 100644 --- a/src/core/region.ts +++ b/src/core/region.ts @@ -26,14 +26,14 @@ export async function regionFromConfigFile(): Promise { const wanted = profile === "default" ? "default" : `profile ${profile}`; let inSection = false; - for (const raw of text.split("\n")) { - const line = raw.trim(); + for (const raw of text.split(/\r?\n/)) { + const line = raw.replace(/(^|\s)[#;].*$/, "").trim(); if (line.startsWith("[") && line.endsWith("]")) { inSection = line.slice(1, -1).trim() === wanted; continue; } - if (inSection && line.startsWith("region")) { - const value = line.split("=")[1]?.trim(); + if (inSection) { + const value = /^region\s*=\s*(.*)$/.exec(line)?.[1]?.trim(); if (value) return value; } } diff --git a/src/middleware/withRegion.test.tsx b/src/middleware/withRegion.test.tsx index 1404f93ac8..c8c13cd02a 100644 --- a/src/middleware/withRegion.test.tsx +++ b/src/middleware/withRegion.test.tsx @@ -94,6 +94,55 @@ describe("region resolution precedence", () => { expect(await resolvedRegion([])).toBe("eu-central-1"); }); + test.each([" # main region", " ; main region", "\t# main region"])( + "strips an inline comment from the default profile's region: %s", + async (comment) => { + clearAwsEnv(); + process.env.AWS_CONFIG_FILE = writeConfigFile(`[default]\nregion = us-west-2${comment}\n`); + expect(await resolvedRegion([])).toBe("us-west-2"); + }, + ); + + test.each(["\n", "\r\n"])( + "strips inline comments from named profile headers and region values with %j line endings", + async (lineEnding) => { + clearAwsEnv(); + process.env.AWS_CONFIG_FILE = writeConfigFile( + "[default]\nregion = ca-central-1\n\n[profile work] # work profile\nregion = eu-central-1 ; main region\n".replaceAll( + "\n", + lineEnding, + ), + ); + process.env.AWS_PROFILE = "work"; + expect(await resolvedRegion([])).toBe("eu-central-1"); + }, + ); + + test("ignores keys that only start with region", async () => { + clearAwsEnv(); + process.env.AWS_CONFIG_FILE = writeConfigFile( + "[default]\nregion_name = eu-west-1\nregional_endpoint = eu-central-1\nregion = us-west-2\n", + ); + expect(await resolvedRegion([])).toBe("us-west-2"); + }); + + test("falls back when the region value is only a comment", async () => { + clearAwsEnv(); + process.env.AWS_CONFIG_FILE = writeConfigFile("[default]\nregion = # no region configured\n"); + expect(await resolvedRegion([])).toBe("us-east-1"); + }); + + test.each(["#", ";"])( + "preserves %s inside a value without preceding whitespace", + async (marker) => { + clearAwsEnv(); + process.env.AWS_CONFIG_FILE = writeConfigFile( + `[default]\nregion = us-west-2${marker}literal\n`, + ); + expect(await resolvedRegion([])).toBe(`us-west-2${marker}literal`); + }, + ); + test("env AWS_REGION wins over the shared config file", async () => { clearAwsEnv(); process.env.AWS_CONFIG_FILE = writeConfigFile("[default]\nregion = ca-central-1\n"); From f54e68c5b364e3bba885f68250e76bdb1ef2c149 Mon Sep 17 00:00:00 2001 From: Andre Devay <43342188+andretorresdg@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:14:55 -0300 Subject: [PATCH 12/19] fix(tui): keep unmatched markdown markers as literal text (#2945) The Markdown renderer used for settled harness replies dropped any `*`, `` ` ``, `[` or `~` that did not open a closed span, so "2 * 3" rendered as "2 3" and "items[0]" as "items0]". Emit such a marker as text instead. --- src/components/ui/markdown/Markdown.test.tsx | 26 ++++++++++++++++++++ src/components/ui/markdown/Markdown.tsx | 6 +++-- 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 src/components/ui/markdown/Markdown.test.tsx diff --git a/src/components/ui/markdown/Markdown.test.tsx b/src/components/ui/markdown/Markdown.test.tsx new file mode 100644 index 0000000000..f6a1fe6bb0 --- /dev/null +++ b/src/components/ui/markdown/Markdown.test.tsx @@ -0,0 +1,26 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import React from "react"; +import { cleanup, render } from "ink-testing-library"; +import { Markdown } from "./Markdown"; + +afterEach(cleanup); + +function renderMarkdown(content: string): string { + return render().lastFrame() ?? ""; +} + +describe("Markdown", () => { + test("keeps a marker that opens no span as literal text", () => { + expect(renderMarkdown("2 * 3 = 6")).toBe("2 * 3 = 6"); + expect(renderMarkdown("items[0] is the first")).toBe("items[0] is the first"); + expect(renderMarkdown("a stray ` backtick")).toBe("a stray ` backtick"); + expect(renderMarkdown("approx ~~10")).toBe("approx ~~10"); + expect(renderMarkdown("an **unclosed bold")).toBe("an **unclosed bold"); + }); + + test("still renders closed spans without their markers", () => { + expect(renderMarkdown("**bold**, *italic*, `code` and [docs](https://example.com)")).toBe( + "bold, italic, code and docs (https://example.com)", + ); + }); +}); diff --git a/src/components/ui/markdown/Markdown.tsx b/src/components/ui/markdown/Markdown.tsx index 773733ecfb..bf0cb98819 100644 --- a/src/components/ui/markdown/Markdown.tsx +++ b/src/components/ui/markdown/Markdown.tsx @@ -85,8 +85,10 @@ function parseInline(line: string): InlineToken[] { ) { i++; } - if (i > start) tokens.push({ type: "text", text: line.slice(start, i) }); - else i++; // safety + // Nothing was consumed only when line[i] is a marker that opens no span + // (an unclosed `*`, a `[` that is not a link): keep it as literal text. + if (i === start) i++; + tokens.push({ type: "text", text: line.slice(start, i) }); } return tokens; From f006ebb50701835f46fa8ecd2aad17733fb12126 Mon Sep 17 00:00:00 2001 From: jariy17 Date: Mon, 30 Nov 2026 18:25:20 +0000 Subject: [PATCH 13/19] test: raise timeouts on Windows-slow remove and memory wizard tests On the Windows runner the two credential remove tests can pass bun's 5s default, and the memory wizard's save can take over the 1s waitForText default. A timed-out remove test keeps running after bun moves on, so its leftover remove lands in the next test's project and fails that one too. --- src/handlers/project/add/memory/memory.screen.test.tsx | 3 ++- src/handlers/project/remove/index.test.ts | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/handlers/project/add/memory/memory.screen.test.tsx b/src/handlers/project/add/memory/memory.screen.test.tsx index f3c751b524..cb9401e6ba 100644 --- a/src/handlers/project/add/memory/memory.screen.test.tsx +++ b/src/handlers/project/add/memory/memory.screen.test.tsx @@ -75,7 +75,8 @@ describe("project add memory wizard", () => { expect(review).toContain("event retention 30 days"); await r.press("return"); - await waitForText(r.lastFrame, "added memory 'orders_memory' to 'TestProject'"); + // Writing agentcore.json can take over a second on the Windows runner. + await waitForText(r.lastFrame, "added memory 'orders_memory' to 'TestProject'", 5000); expect(r.lastFrame()).toContain("[enter] go back"); // The strategies carry the same namespaces `--strategies SEMANTIC,EPISODIC` diff --git a/src/handlers/project/remove/index.test.ts b/src/handlers/project/remove/index.test.ts index d4b755f1cb..4dfa0ef481 100644 --- a/src/handlers/project/remove/index.test.ts +++ b/src/handlers/project/remove/index.test.ts @@ -191,7 +191,7 @@ describe("project remove", () => { expect(await Bun.file(envPath).text()).not.toContain(envKey); expect(io.stderr()).toContain(`removed '${envKey}' from ${ENV_LOCAL_RELATIVE_PATH}`); expect(io.stderr()).toContain("removed credential with name 'svc-key' from project"); - }); + }, 15000); test("--json reports a removal and its cleaned environment keys", async () => { const { projectRoot, cleanup } = await initProject({ @@ -213,7 +213,7 @@ describe("project remove", () => { }); expect(io.stdout()).not.toContain("removed credential with name"); expect(io.stderr()).toContain(`removed '${envKey}' from ${ENV_LOCAL_RELATIVE_PATH}`); - }); + }, 15000); test("removing a secret-reference credential leaves .env.local alone", async () => { const { projectRoot, cleanup } = await initProject({ From eb7520292adc7c30b6d4fb441281c83a7f6b86a4 Mon Sep 17 00:00:00 2001 From: Trirmadura J Ariyawansa Date: Mon, 30 Nov 2026 14:10:16 -0500 Subject: [PATCH 14/19] feat(payments): add merchant payment providers, payment intent commands and AWS Billing connectors (#2961) * feat(payments): add Stripe, PayPal and Amazon Pay providers and payment intent commands Add typed provider subcommands under `add credentials payment` for Stripe, PayPal and Amazon Pay with shared secret value/reference handling and deploy reconciliation, the seven payment intent operations under `payment intent`, payment-context flags for runtime and project invocation, and AWS Billing connector configuration. * chore(deps): bump @aws-sdk/client-bedrock-agentcore* to 3.1181.0 3.1181.0 is the first release carrying the payment intent operations and the Stripe, PayPal and Amazon Pay credential provider types. * fix(payments): address review feedback - check @aws/agentcore-cdk supports merchant payment credentials and AwsBilling connectors before deploy writes any Identity provider - restore the v1.x credential suffix lists so existing variables such as AGENTCORE_CREDENTIAL_PROD_ENVIRONMENT stay encrypted - validate --client-token locally (33-256 letters, digits or hyphens) - remove contract tests that exercised only the AWS SDK - correct the rollback description in docs/payments.md --------- Co-authored-by: jariy17 --- README.md | 4 + bun.lock | 88 ++-- docs/aws-billing.md | 25 ++ docs/payments.md | 208 +++++++++ e2eTest/README.md | 8 + e2eTest/constants.ts | 1 + e2eTest/payment/intent.test.ts | 60 +++ package.json | 4 +- src/components/CommandFallbackScreen.test.tsx | 25 ++ src/core/payment.tsx | 162 ++++++- src/core/project/backends/cdk.test.ts | 38 ++ src/core/project/backends/cdk.ts | 22 +- .../backends/cdk/compatibility.test.ts | 33 ++ .../project/backends/cdk/compatibility.ts | 37 +- .../project/backends/cdk/credentials.test.ts | 411 +++++++++++++++++- src/core/project/backends/cdk/credentials.ts | 166 ++++++- src/handlers/payment/index.tsx | 4 +- .../payment/intent/authorize/index.tsx | 42 ++ src/handlers/payment/intent/cancel/index.tsx | 22 + src/handlers/payment/intent/capture/index.tsx | 52 +++ .../create-buyer-approval-url/index.tsx | 43 ++ src/handlers/payment/intent/create/index.tsx | 46 ++ src/handlers/payment/intent/get/index.tsx | 38 ++ src/handlers/payment/intent/index.tsx | 23 + .../payment/intent/initiate/index.tsx | 22 + src/handlers/payment/intent/input.ts | 108 +++++ .../payment/intent/lifecycle.test.tsx | 397 +++++++++++++++++ src/handlers/payment/payment.read.test.tsx | 80 ++++ src/handlers/payment/types.tsx | 55 +++ .../project/add/credentials/payment/index.ts | 81 +++- .../project/add/credentials/payment/input.ts | 27 +- .../add/credentials/payment/merchant.test.ts | 316 ++++++++++++++ .../add/credentials/payment/merchant.ts | 144 ++++++ .../payment/payment.screen.test.tsx | 4 +- .../add/credentials/payment/providers.test.ts | 145 ++++++ .../add/credentials/payment/providers.ts | 145 ++++++ .../add/credentials/payment/screen.tsx | 6 +- .../project/add/credentials/shared.test.ts | 84 ++++ .../project/add/credentials/shared.ts | 12 +- .../add/payment-connector/index.test.ts | 40 ++ .../project/add/payment-connector/index.ts | 41 +- src/handlers/project/invoke/index.test.tsx | 108 +++++ src/handlers/project/invoke/index.tsx | 9 + src/handlers/project/invoke/runtime.tsx | 6 +- src/handlers/runtime/invoke/index.tsx | 18 +- src/handlers/runtime/invoke/invoke.test.tsx | 81 ++++ .../runtime/invoke/paymentContext.test.ts | 105 +++++ src/handlers/runtime/invoke/paymentContext.ts | 129 ++++++ src/handlers/runtime/invoke/request.ts | 18 +- src/projectSchemas/credential.test.ts | 3 + src/projectSchemas/credential.ts | 61 ++- src/projectSchemas/payment.test.ts | 23 + src/projectSchemas/payment.ts | 23 +- src/projectSchemas/project.test.ts | 31 ++ src/projectSchemas/project.ts | 3 +- src/router/router.test.ts | 99 +++++ src/router/router.tsx | 81 +++- src/secrets/sensitiveKeys.test.ts | 7 + src/testing/TestCoreClient.tsx | 28 ++ vitest.e2e.config.ts | 1 + vitest.payment-e2e.config.ts | 10 + 61 files changed, 3985 insertions(+), 128 deletions(-) create mode 100644 docs/aws-billing.md create mode 100644 docs/payments.md create mode 100644 e2eTest/payment/intent.test.ts create mode 100644 src/handlers/payment/intent/authorize/index.tsx create mode 100644 src/handlers/payment/intent/cancel/index.tsx create mode 100644 src/handlers/payment/intent/capture/index.tsx create mode 100644 src/handlers/payment/intent/create-buyer-approval-url/index.tsx create mode 100644 src/handlers/payment/intent/create/index.tsx create mode 100644 src/handlers/payment/intent/get/index.tsx create mode 100644 src/handlers/payment/intent/index.tsx create mode 100644 src/handlers/payment/intent/initiate/index.tsx create mode 100644 src/handlers/payment/intent/input.ts create mode 100644 src/handlers/payment/intent/lifecycle.test.tsx create mode 100644 src/handlers/project/add/credentials/payment/merchant.test.ts create mode 100644 src/handlers/project/add/credentials/payment/merchant.ts create mode 100644 src/handlers/project/add/credentials/payment/providers.test.ts create mode 100644 src/handlers/project/add/credentials/payment/providers.ts create mode 100644 src/handlers/project/add/credentials/shared.test.ts create mode 100644 src/handlers/runtime/invoke/paymentContext.test.ts create mode 100644 src/handlers/runtime/invoke/paymentContext.ts create mode 100644 vitest.payment-e2e.config.ts diff --git a/README.md b/README.md index 59aaa8eb45..911806ba48 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,8 @@ For a runtime with a build warmup hook (`hooksConfiguration.build.warmup`), dev `GET /ping`, then sends the hook's `memory` and `disk` calls as platform version V2 does, and fails the start if either fails. +See [payment checkout configuration](docs/payments.md) for merchant providers, billing connectors, and intent inspection. + New payment credentials receive provider names that payment connectors can reference. An existing payment credential keeps the provider ARN recorded for its deployment target. If that ARN is incompatible with a manual connector, deploy stops before @@ -206,6 +208,8 @@ declares, not the ones you add in the stack. ## Documentation +- [AWS Billing connectors](docs/aws-billing.md): headless configuration and deployment prerequisites. + - [Command reference](command.md): every command and flag. - [Harness project configuration](docs/harness-project-configuration.md): Harness YAML, prompts, tools, skills, and environment settings. - [China regions](docs/china-regions.md): what is available there and how the restrictions are enforced. diff --git a/bun.lock b/bun.lock index 2d20a21173..9baf246f08 100644 --- a/bun.lock +++ b/bun.lock @@ -9,8 +9,8 @@ "@aws-cdk/toolkit-lib": "1.38.2", "@aws-sdk/client-application-signals": "^3.1092.0", "@aws-sdk/client-bedrock-agent": "^3.1092.0", - "@aws-sdk/client-bedrock-agentcore": "^3.1171.0", - "@aws-sdk/client-bedrock-agentcore-control": "^3.1171.0", + "@aws-sdk/client-bedrock-agentcore": "^3.1181.0", + "@aws-sdk/client-bedrock-agentcore-control": "^3.1181.0", "@aws-sdk/client-cloudformation": "^3.1092.0", "@aws-sdk/client-cloudwatch-logs": "^3.1092.0", "@aws-sdk/client-iam": "^3.1080.0", @@ -117,9 +117,9 @@ "@aws-sdk/client-bedrock-agent": ["@aws-sdk/client-bedrock-agent@3.1121.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-node": "^3.972.81", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-RAjn1g6X+u4WwnuwxYU8sKna5q1waTBCM+kzXWAvxSaNbgRsXFL6ZylPjOl0qCDZ7x6aVTj7Jb7Q0z6DZifP3w=="], - "@aws-sdk/client-bedrock-agentcore": ["@aws-sdk/client-bedrock-agentcore@3.1171.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-NC7bE1uEHKcw61ws6Nte7Bv1o/ogY+szSPNyj0QFN5upVCypjXmnql7Prb5v+njJRQgNTov96mIKhLt1fc4LZg=="], + "@aws-sdk/client-bedrock-agentcore": ["@aws-sdk/client-bedrock-agentcore@3.1181.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/credential-provider-node": "^3.972.99", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-aXqjaTKAVx+ONY0wNjnvui8OylIZHc7ytRl2t3gAWdktqp/klEd12f6NUJSg33hYpGJrjrSNNHJleqMS2C/1dQ=="], - "@aws-sdk/client-bedrock-agentcore-control": ["@aws-sdk/client-bedrock-agentcore-control@3.1171.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-fH4ZNjchQAbc57jOijFNklstf8UQNKHrLrpOZTN+IlihZXnvhAeniHOx8fm71fyxQ8co9r8fQPPgW9aCvR0pDQ=="], + "@aws-sdk/client-bedrock-agentcore-control": ["@aws-sdk/client-bedrock-agentcore-control@3.1181.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/credential-provider-node": "^3.972.99", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ZqY8FZj7YBWiRenO+QF4zZvRFJf7yBqCYixlXCNz/fyb3KpLav4PXdC6by6Zf7p+ekXAnmkKk1IIGK9+bKUZag=="], "@aws-sdk/client-cloudcontrol": ["@aws-sdk/client-cloudcontrol@3.1121.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-node": "^3.972.81", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-kpR+c528XFWFT04APYPKrhSCyzdEJPgxryR0wWs2dfIj7Ovqwak+1zLwFOS8zpNqDPEx8xn7j3dqA/HTCo+qLw=="], @@ -1261,13 +1261,13 @@ "@aws-sdk/client-bedrock-agent/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.81", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-ini": "^3.973.15", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Rml+WitoFvXmv6JZ18U/xGdGDGGvB/mOin0ya0lTnTrdC0Z1lrVxTYh7iNklZBcvcRMrs4DoEf6xy1KWyrLQQw=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/core": ["@aws-sdk/core@3.981.0", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/core": ["@aws-sdk/core@3.981.2", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.41.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-N3XKZdfa+Dcm7Kl8NJnaaHLx860Ts3QYHOraj/wuKOYHqqCApQBIKwzSxrpwZdwrqfbPt7BvJdYVhVMPpsRoGA=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.97", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-ini": "^3.973.30", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.99", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.86", "@aws-sdk/credential-provider-http": "^3.972.88", "@aws-sdk/credential-provider-ini": "^3.973.32", "@aws-sdk/credential-provider-process": "^3.972.86", "@aws-sdk/credential-provider-sso": "^3.973.30", "@aws-sdk/credential-provider-web-identity": "^3.972.92", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-AgS2qV8P9XmT4M44LfGcFtKbbt/yLgBydETKxPvqN9y7gMnKYv8GY+QfH7JsNvu6eQgDl600uAjvzC6K7ilkJQ=="], "@aws-sdk/client-bedrock-agentcore/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], - "@aws-sdk/client-bedrock-agentcore/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + "@aws-sdk/client-bedrock-agentcore/@smithy/core": ["@smithy/core@3.41.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-24LyiHSY0R/MLcbTylurWXU6Uy4lzI6KJgsdzxkNnjT9/OLWc2zGPb/3k5AM1f0vcgCGrExanUG339t+TBiIrA=="], "@aws-sdk/client-bedrock-agentcore/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], @@ -1275,13 +1275,13 @@ "@aws-sdk/client-bedrock-agentcore/@smithy/types": ["@smithy/types@4.20.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/core": ["@aws-sdk/core@3.981.0", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/core": ["@aws-sdk/core@3.981.2", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.41.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-N3XKZdfa+Dcm7Kl8NJnaaHLx860Ts3QYHOraj/wuKOYHqqCApQBIKwzSxrpwZdwrqfbPt7BvJdYVhVMPpsRoGA=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.97", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-ini": "^3.973.30", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.99", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.86", "@aws-sdk/credential-provider-http": "^3.972.88", "@aws-sdk/credential-provider-ini": "^3.973.32", "@aws-sdk/credential-provider-process": "^3.972.86", "@aws-sdk/credential-provider-sso": "^3.973.30", "@aws-sdk/credential-provider-web-identity": "^3.972.92", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-AgS2qV8P9XmT4M44LfGcFtKbbt/yLgBydETKxPvqN9y7gMnKYv8GY+QfH7JsNvu6eQgDl600uAjvzC6K7ilkJQ=="], "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], - "@aws-sdk/client-bedrock-agentcore-control/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + "@aws-sdk/client-bedrock-agentcore-control/@smithy/core": ["@smithy/core@3.41.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-24LyiHSY0R/MLcbTylurWXU6Uy4lzI6KJgsdzxkNnjT9/OLWc2zGPb/3k5AM1f0vcgCGrExanUG339t+TBiIrA=="], "@aws-sdk/client-bedrock-agentcore-control/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], @@ -1505,33 +1505,41 @@ "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ZFIkIzLAiOLOakfrzUuOz938+AF+q4nc/MYINYwFlgBbl8CsI8ofJ8Ueh0/Pp7hXMJfpq10eJdnQ7aaE6kfikQ=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.88", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-92dpM3lwCyDjcDI3R+olUI2IG8R+qfUdnMQgxWZB4XM37P+N+oBaRd5xGc7uOH7FqMQY03XsrVKQeuWbPfIrKg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-login": "^3.972.92", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.32", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/credential-provider-env": "^3.972.86", "@aws-sdk/credential-provider-http": "^3.972.88", "@aws-sdk/credential-provider-login": "^3.972.94", "@aws-sdk/credential-provider-process": "^3.972.86", "@aws-sdk/credential-provider-sso": "^3.973.30", "@aws-sdk/credential-provider-web-identity": "^3.972.92", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-MdIAf70d701Hj04Yo7AKqI1RfjTW5dFf+tEvUirYFMbs3NRHWiwqQj/C9wGFptZtmX+z/c57H3gQfzTt5Bsn8A=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9x/+gtSDNxMQrRXgwIdwdNCVGxzUZtTZArjEeLfsn9xDvyXdsgs4my1g7JN5wKxT61ZLx4bKPREaDXnO8j7gkg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.28", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/token-providers": "3.1166.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/token-providers": "3.1177.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-sMvwUIaKQEeprbMT5LXrI6nhM1IUEBDRpJAydEkAMrI7brrsRl7pxnOAJ6nweg/Hn5pJOVS7JgieJIv6CvJ7Sw=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.90", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-AKaUwpy1wPN3B/byFWuvL6v+Qk8Gm840InZJw/bA1A+ciCL3zkzBUyEgxdeghJPEe79VKLs6BvbME74MQa3YKg=="], + + "@aws-sdk/client-bedrock-agentcore-control/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore-control/@smithy/node-http-handler/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], "@aws-sdk/client-bedrock-agentcore/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.43", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og=="], "@aws-sdk/client-bedrock-agentcore/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ZFIkIzLAiOLOakfrzUuOz938+AF+q4nc/MYINYwFlgBbl8CsI8ofJ8Ueh0/Pp7hXMJfpq10eJdnQ7aaE6kfikQ=="], + + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.88", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-92dpM3lwCyDjcDI3R+olUI2IG8R+qfUdnMQgxWZB4XM37P+N+oBaRd5xGc7uOH7FqMQY03XsrVKQeuWbPfIrKg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.32", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/credential-provider-env": "^3.972.86", "@aws-sdk/credential-provider-http": "^3.972.88", "@aws-sdk/credential-provider-login": "^3.972.94", "@aws-sdk/credential-provider-process": "^3.972.86", "@aws-sdk/credential-provider-sso": "^3.973.30", "@aws-sdk/credential-provider-web-identity": "^3.972.92", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-MdIAf70d701Hj04Yo7AKqI1RfjTW5dFf+tEvUirYFMbs3NRHWiwqQj/C9wGFptZtmX+z/c57H3gQfzTt5Bsn8A=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-login": "^3.972.92", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9x/+gtSDNxMQrRXgwIdwdNCVGxzUZtTZArjEeLfsn9xDvyXdsgs4my1g7JN5wKxT61ZLx4bKPREaDXnO8j7gkg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/token-providers": "3.1177.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-sMvwUIaKQEeprbMT5LXrI6nhM1IUEBDRpJAydEkAMrI7brrsRl7pxnOAJ6nweg/Hn5pJOVS7JgieJIv6CvJ7Sw=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.28", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/token-providers": "3.1166.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-AKaUwpy1wPN3B/byFWuvL6v+Qk8Gm840InZJw/bA1A+ciCL3zkzBUyEgxdeghJPEe79VKLs6BvbME74MQa3YKg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.90", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ=="], + "@aws-sdk/client-bedrock-agentcore/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore/@smithy/node-http-handler/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], "@aws-sdk/client-cloudcontrol/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-7ImGm+FkHRLcBaRttIAMZ6bzJZWb2cJGoYjq46F2UjycujWzrL9GEN9h4w7eQyXJYnltrUhxbbieBAIRrdqpow=="], @@ -1627,25 +1635,29 @@ "@aws-cdk/cloudformation-diff/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/core/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.94", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-sSq1PxdXT1kqR11/dRvE5AC2dEWMbYJCXzRU03Ulu4stu6vv08zju8uUNhVdqiIX+OrMIcEHHT1maLrUZDBGDA=="], + + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1177.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-KFQ/2YqE7OIGNu05hys6y9ZUyoNxxLJVHM7NCvjfyjV0Mki0u0Euwjduj5M/HMurdbZJfBV0NjMNQQkGlJEQqg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1166.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g=="], + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], - "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/core/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.94", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-sSq1PxdXT1kqR11/dRvE5AC2dEWMbYJCXzRU03Ulu4stu6vv08zju8uUNhVdqiIX+OrMIcEHHT1maLrUZDBGDA=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1166.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1177.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/nested-clients": "^3.998.5", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-KFQ/2YqE7OIGNu05hys6y9ZUyoNxxLJVHM7NCvjfyjV0Mki0u0Euwjduj5M/HMurdbZJfBV0NjMNQQkGlJEQqg=="], - "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.5", "", { "dependencies": { "@aws-sdk/core": "^3.981.2", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.41.1", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-9w5mkwVLOuGqlJkPR1uhod6ZP+TOtaxrKtvK2pY9G/+FEx0e8wYRLIDeg30dYQjFDx27jHGSzEA+OaMqxeyTPg=="], "@aws-sdk/signature-v4/@smithy/signature-v4/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@1.1.0", "", { "dependencies": { "@smithy/is-array-buffer": "^1.1.0", "tslib": "^2.5.0" } }, "sha512-9m6NXE0ww+ra5HKHCHig20T+FAwxBAm7DIdwc/767uGWbRcY720ybgPacQNB96JMOI7xVr/CDa3oMzKmW4a+kw=="], @@ -1672,5 +1684,17 @@ "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore-control/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-bedrock-agentcore/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], } } diff --git a/docs/aws-billing.md b/docs/aws-billing.md new file mode 100644 index 0000000000..762e66515c --- /dev/null +++ b/docs/aws-billing.md @@ -0,0 +1,25 @@ +# AWS Billing connectors + +Add an AWS Marketplace billing connector to an existing project payment manager: + +```sh +agentcore add payment-connector --manager payments --name billing --aws-billing +``` + +Choose exactly one of `--aws-billing`, `--credential`, or `--quick-create`. Billing has no payment credential, provider secret, or connector role-ARN input. Existing CoinbaseCDP/StripePrivy credential and Coinbase Quick Create commands retain their syntax. Existing interactive forms are unchanged; use the headless flag for billing. + +The command persists this connector under the named manager in `agentcore.json`: + +```json +{ "name": "billing", "provider": "AwsBilling" } +``` + +`provisionMode: "MANUAL"` is optional. Credential references, Quick Create and role fields are rejected for billing. Other connectors in the same project still require their normal credentials. + +## Deployment prerequisites + +This command adds local configuration support. Deploying a billing connector requires a vended `@aws/agentcore-cdk` that accepts `AwsBilling` connectors without a credential. The CloudFormation PaymentConnector resource and handler must also support `AwsBilling` in the target AWS region. No custom-resource fallback is used. + +The customer must provision the required AWS Marketplace service-linked role before deployment. The service returns its role ARN; it is not a connector input and this command does not create the role or grant `iam:PassRole`. + +Payment runtime seller-header and offer-selection integration is separate from connector configuration. This command neither purchases an offer nor provides runtime billing settlement. diff --git a/docs/payments.md b/docs/payments.md new file mode 100644 index 0000000000..fd1e01c052 --- /dev/null +++ b/docs/payments.md @@ -0,0 +1,208 @@ +# Merchant payments + +Merchant checkout supports Stripe, PayPal and Amazon Pay configuration alongside the existing +CoinbaseCDP and StripePrivy projects. New provider screens are deferred; the existing interactive +flows remain unchanged. + +## Configuration and secrets + +Use a provider subcommand; each requires `--name`. New provider leaves are headless: + +```sh +agentcore add credentials payment stripe --name stripe-checkout --restricted-key file://restricted-key.txt +agentcore add credentials payment paypal --name paypal-checkout --client-id CLIENT_ID --environment SANDBOX --client-secret - +agentcore add credentials payment amazon-pay --name amazon-checkout --merchant-id MERCHANT_ID --store-id STORE_ID --environment LIVE --amazon-pay-region EU --authorization-token-secret-reference '{"secretId":"merchant-authorization","jsonKey":"token"}' +agentcore add credentials payment coinbase-cdp --name wallet +agentcore add credentials payment stripe-privy --name privy +``` + +| Subcommand | Provider-owned flags | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `stripe` | `--restricted-key`, `--restricted-key-secret-reference`, `--publishable-key` | +| `paypal` | `--client-id`, `--client-secret`, `--client-secret-reference`, `--environment` | +| `amazon-pay` | `--merchant-id`, `--store-id`, `--authorization-token`, `--authorization-token-secret-reference`, `--environment`, `--amazon-pay-region` | +| `coinbase-cdp` | `--api-key-id`, `--api-key-secret`, `--wallet-secret` | +| `stripe-privy` | `--app-id`, `--app-secret`, `--authorization-private-key`, `--authorization-id` | + +Secret value flags accept `file://` or `-` for stdin; raw secret literals are rejected. +Only one secret may claim stdin. Secret-reference flags take strict JSON with `secretId` and +`jsonKey` and cannot accompany the corresponding value flag. Stripe requires a restricted key +(`rk_test_` or `rk_live_`); an optional publishable key must use the same test/live mode. + +All fields except the name may be omitted during setup. Missing deployment-required fields create +`.env.local` placeholders with instructions to fill them before deployment. PayPal requires client +ID, client secret and environment at deployment; Amazon Pay requires merchant ID, store ID, +authorization token, environment and merchant region. Environment is `SANDBOX` or `LIVE`; +Amazon Pay merchant region is `NA` or `EU`. `JP` is deferred and rejected during credential setup +and deploy validation. Neither setting has an implicit default. +A supplied value must still be valid even if other fields are deferred. + +Existing flat `payment --name NAME --provider CoinbaseCDP|StripePrivy ...` commands and the bare +interactive wizard remain supported. Do not mix a subcommand with `--provider` or put provider +flags before its subcommand. A bare noninteractive command shows usage and exits with code 2. +Provider-specific reference flags map to the shared persisted `secretRef` field below. + +Vendor values, including environment and merchant region, are saved in `agentcore/.env.local` +under `AGENTCORE_CREDENTIAL__`. External secret references stay in `agentcore.json`: + +```json +{ + "authorizerType": "PaymentCredentialProvider", + "name": "merchant", + "provider": "AmazonPay", + "secretRef": { "secretId": "merchant-authorization", "jsonKey": "token" } +} +``` + +An external reference replaces only that provider's secret value requirement. Merchant identifiers, +environment and merchant region remain required. Amazon Pay merchant region, payment currency +(`USD` or `EUR`) and AWS deployment region are separate settings. + +Deployment validates local provider inputs before writing providers, creates absent providers, +updates supplied configuration, and reuses existing providers when required local values are absent. +An external reference requires all other vendor fields even for an existing provider, so a reference +change cannot be silently ignored. A vendor mismatch is rejected. + +A merchant provider's secret source cannot change between `MANAGED` and `EXTERNAL`. When Identity +returns the source, deployment rejects a mode change before writing any provider. To use another +source, create a credential with a different name, point the connector to it, then deploy. Same-source +secret rotation and external reference updates remain supported. Missing source metadata is not +assumed to mean `MANAGED`; Identity validates those updates. Inline secret values use the service's +managed default without requiring the external-secrets feature; external references still require it. + +When a deployment fails, rollback deletes every provider that deployment tried to create, newest +first. That includes a provider whose create call failed, because a failed or interrupted call can +still have created it; a provider that is not found is skipped. A provider that cannot be deleted is reported, and the next deploy of the target adopts it. +Existing providers are never deleted by rollback, and their successful updates are not restored. +The CLI never creates or deletes customer-owned external secrets. + +## Connectors + +```sh +agentcore add payment-connector --manager payments --name merchant --credential merchant +agentcore add payment-connector --manager payments --name marketplace --aws-billing +``` + +Exactly one of `--credential`, `--quick-create` or `--aws-billing` is required. AWS Billing +connectors have no credential. The customer must create the Marketplace service-linked role before +deployment; no role ARN is accepted as connector input. Runtime AWS Billing payment-header and +offer selection integration is separate work. + +## Headless intent lifecycle + +All seven intent commands require `--manager-id` and a nonblank `--user-id`. The CLI resolves +the manager ID to its ARN and supports IAM managers. `--agent-name` is optional telemetry. +JSON output retains the complete nested response, intent version, decimal money strings, +structured partner data and separate capture status. `CAPTURE_PENDING` is not settlement. + +Create a checkout with trusted application values, using a JSON file or stdin for the checkout: + +```sh +agentcore payment intent create --manager-id MANAGER_ID --user-id BUYER_ID \ + --connector-id CONNECTOR_ID --capture-strategy FUTURE \ + --checkout-details file://checkout.json --json +agentcore payment intent get --manager-id MANAGER_ID --user-id BUYER_ID --intent-id INTENT_ID --json +agentcore payment intent create-buyer-approval-url --manager-id MANAGER_ID --user-id BUYER_ID \ + --intent-id INTENT_ID --parent-origin https://shop.example --json +``` + +`checkout.json` follows the service checkout structure. Monetary values must remain strings: + +```json +{ + "totalAmount": { "value": "12.0100", "currency": "EUR" }, + "merchant": { "name": "Example shop", "website": "https://shop.example" }, + "lineItems": [{ "sku": "item", "quantity": 2, "amount": { "value": "5.00", "currency": "EUR" } }], + "amountBreakdown": { "shipping": { "value": "2.0100", "currency": "EUR" } }, + "referenceId": "order-123" +} +``` + +Capture strategies are `INSTANT`, `FUTURE` and `SETUP`; `amountMode` may be `EXACT` or `UPTO`. +The service enforces provider, arithmetic and lifecycle constraints. Deliver the opaque approval URL +to the buyer UI. These commands never open or redeem it. Only after approval, a separate backend +principal may initiate, authorize and capture: + +```sh +agentcore payment intent initiate --manager-id MANAGER_ID --user-id BUYER_ID --intent-id INTENT_ID --json +agentcore payment intent authorize --manager-id MANAGER_ID --user-id BUYER_ID --intent-id INTENT_ID \ + --partner-callback-result file://partner-callback.txt --json +agentcore payment intent capture --manager-id MANAGER_ID --user-id BUYER_ID --intent-id INTENT_ID \ + --capture-amount '{"value":"5.0100","currency":"EUR"}' \ + --client-token 9467ced1-60fd-4e48-8494-40bfa473d648 --json +agentcore payment intent cancel --manager-id MANAGER_ID --user-id BUYER_ID --intent-id INTENT_ID --json +``` + +The partner callback is optional and accepted only from a file or `-` for stdin. Checkout and +capture-amount objects accept inline JSON, `file://...` or `-`. Errors and debug flag logs omit +sensitive input contents. Successful JSON output can contain approval URLs and partner secrets; +deliver it only to the intended application/UI. + +Capture requires a caller-owned `--client-token`: 33 to 256 letters, digits or hyphens, such as a +UUID. The CLI rejects any other token before calling AWS and sends a valid one unchanged. Store and +reuse that token for retries of the same capture; a new token requests another capture. Omitting +`--capture-amount` requests the remaining authorization. Other mutations accept an optional +`--client-token`. There is no `complete` or intent `list` command. + +These mutation commands run with the developer's explicit AWS credentials. Agent tools should be +limited to Create/Get/Cancel and approval-link delivery. Buyer approval and backend settlement are +separate responsibilities; do not grant the agent backend settlement permissions. + +## Invoking an application with payment context + +Headless HTTP Runtime invocation accepts four application-context flags, also available through +`agentcore invoke --runtime ...`, including `--local`: + +| Flag | JSON payload field | +| ------------------------- | ----------------------- | +| `--payment-user-id` | `user_id` | +| `--payment-intent-id` | `payment_intent_id` | +| `--payment-instrument-id` | `payment_instrument_id` | +| `--payment-session-id` | `payment_session_id` | + +```sh +agentcore runtime invoke --id RUNTIME_ID --payload '{"prompt":"Review my checkout"}' \ + --payment-user-id BUYER_ID --payment-intent-id INTENT_ID --json +agentcore invoke --runtime checkout --local --payload file://request.json \ + --payment-user-id BUYER_ID --payment-instrument-id INSTRUMENT_ID \ + --payment-session-id PAYMENT_SESSION_ID +``` + +Any payment flag requires explicit `--payment-user-id` and a headless `--payload` containing an +`application/json` object. Merchant intent context cannot coexist with legacy instrument/session +context, including values already in the payload. Identical existing values are accepted; different +values, blank/non-string context fields and incompatible combinations fail. Unrelated JSON is +preserved, including numeric representations. With no payment flags, the exact input bytes are +unchanged. Gateway, harness, MCP and other non-HTTP protocols do not support this context. + +Runtime `--user-id` and `--session-id` still identify the Runtime invocation; they neither supply nor +replace payment buyer/session identity. No new service headers are invented. Body context is not +authentication or authorization: the application must compare the buyer with trusted authenticated +identity before creating payment adapters, and an intent ID does not authorize settlement. + +For v0.x migration, the explicit payment instrument/session flag names remain the same. Use +`--payload` instead of the v0 `--prompt` flow and always pass `--payment-user-id`; the v0 fallback +to Runtime `--user-id` or a default buyer is removed. There is no CLI `--auto-session`: create a legacy payment session through the existing SDK +`PaymentManager.create_payment_session` method, then pass `--payment-session-id`. Existing +interactive behavior is unchanged; these payment-context flags are headless-only. + +## Dependency and acceptance gates + +Payment intent commands and the Stripe, PayPal and Amazon Pay provider fields require +`@aws-sdk/client-bedrock-agentcore` and `@aws-sdk/client-bedrock-agentcore-control` 3.1181.0 or +later. Connector deployment also requires the CloudFormation properties for the provider and a +vended `@aws/agentcore-cdk` that supports them; SDK model availability alone does not provide +those. + +Run `bun test src/handlers/payment` to verify the request each command sends and the response it +renders. For deployed read/ownership acceptance, create a sandbox intent through the SDK and set: + +- `PAYMENT_TEST_MANAGER_ID`, `PAYMENT_TEST_INTENT_ID`, `PAYMENT_TEST_USER_ID` +- `PAYMENT_TEST_OTHER_USER_ID` (a distinct buyer) +- `PAYMENT_TEST_REGION`, `PAYMENT_TEST_CURRENCY` (`USD` or `EUR`) +- AWS credentials and `AGENTCORE_CLI_PATH="node $PWD/dist/index.js"` + +Then run `bunx vitest run --config vitest.payment-e2e.config.ts`. This read-only configuration +does not run the general deployment suite’s stale-stack cleanup. Repeat per provider/currency/merchant-region +combination in each supported AWS Region. Browser approval, PSP sandbox checkout and +CloudFormation create/update/delete remain separate deployed acceptance checks. diff --git a/e2eTest/README.md b/e2eTest/README.md index 31e7fe3531..3b0810a392 100644 --- a/e2eTest/README.md +++ b/e2eTest/README.md @@ -41,3 +41,11 @@ These tests skip when their image variables are absent. They add each Runtime wi invoke, digest pinning, a named endpoint, an image update that keeps the Runtime ID, the absence of build resources, and stack teardown. They never create or publish the image fixtures. Their projects use the standard e2e prefix, so the setup sweep removes stacks left by an interrupted run. + +## Read-only payment acceptance + +See [payment inputs](../docs/payments.md#dependency-and-acceptance-gates) for required sandbox +intent IDs and buyer identities. Run `bunx vitest run --config vitest.payment-e2e.config.ts`. +This dedicated configuration does not load the deployment suite's stale-stack cleanup hook. +The top-level e2e configuration excludes these payment tests because it does not provide their +required fixture inputs. diff --git a/e2eTest/constants.ts b/e2eTest/constants.ts index c10c7dd989..476cf475a4 100644 --- a/e2eTest/constants.ts +++ b/e2eTest/constants.ts @@ -4,4 +4,5 @@ export const TAGS = { CANARY: "canary", HARNESS: "harness", RUNTIME: "runtime", + PAYMENT: "payment", } as const; diff --git a/e2eTest/payment/intent.test.ts b/e2eTest/payment/intent.test.ts new file mode 100644 index 0000000000..fe68ffbcf2 --- /dev/null +++ b/e2eTest/payment/intent.test.ts @@ -0,0 +1,60 @@ +import { beforeAll, describe, expect, test } from "vitest"; +import { CliRunner } from "../helpers/run"; +import { TAGS } from "../constants"; + +const required = [ + "PAYMENT_TEST_MANAGER_ID", + "PAYMENT_TEST_INTENT_ID", + "PAYMENT_TEST_USER_ID", + "PAYMENT_TEST_OTHER_USER_ID", + "PAYMENT_TEST_REGION", + "PAYMENT_TEST_CURRENCY", +] as const; + +describe("read a sandbox payment intent", { tags: [TAGS.PAYMENT] }, () => { + beforeAll(() => { + const missing = required.filter((key) => !process.env[key]?.trim()); + if (missing.length) + throw new Error(`Payment acceptance needs sandbox inputs: ${missing.join(", ")}`); + }); + + function args(userId: string): string[] { + return [ + "payment", + "intent", + "get", + "--manager-id", + process.env.PAYMENT_TEST_MANAGER_ID!, + "--intent-id", + process.env.PAYMENT_TEST_INTENT_ID!, + "--user-id", + userId, + "--region", + process.env.PAYMENT_TEST_REGION!, + "--json", + ]; + } + + test("reads the buyer's intent with its original currency and decimal amount", async () => { + const result = await new CliRunner().run( + args(process.env.PAYMENT_TEST_USER_ID!), + process.cwd(), + ); + expect(result.exitCode).toBe(0); + const { paymentIntent } = JSON.parse(result.stdout); + expect(paymentIntent.paymentIntentId).toBe(process.env.PAYMENT_TEST_INTENT_ID); + expect(paymentIntent.checkoutDetails.totalAmount.currency).toBe( + process.env.PAYMENT_TEST_CURRENCY, + ); + expect(typeof paymentIntent.checkoutDetails.totalAmount.value).toBe("string"); + }); + + test("does not return the intent to another buyer", async () => { + const result = await new CliRunner().run( + args(process.env.PAYMENT_TEST_OTHER_USER_ID!), + process.cwd(), + ); + expect(result.exitCode).not.toBe(0); + expect(result.stdout).not.toContain('"paymentIntent"'); + }); +}); diff --git a/package.json b/package.json index de131fab0a..cf56fdf8f3 100644 --- a/package.json +++ b/package.json @@ -70,8 +70,8 @@ "@aws-cdk/toolkit-lib": "1.38.2", "@aws-sdk/client-application-signals": "^3.1092.0", "@aws-sdk/client-bedrock-agent": "^3.1092.0", - "@aws-sdk/client-bedrock-agentcore": "^3.1171.0", - "@aws-sdk/client-bedrock-agentcore-control": "^3.1171.0", + "@aws-sdk/client-bedrock-agentcore": "^3.1181.0", + "@aws-sdk/client-bedrock-agentcore-control": "^3.1181.0", "@aws-sdk/client-cloudformation": "^3.1092.0", "@aws-sdk/client-cloudwatch-logs": "^3.1092.0", "@aws-sdk/client-iam": "^3.1080.0", diff --git a/src/components/CommandFallbackScreen.test.tsx b/src/components/CommandFallbackScreen.test.tsx index d2b54c7ba5..2b783c4a2f 100644 --- a/src/components/CommandFallbackScreen.test.tsx +++ b/src/components/CommandFallbackScreen.test.tsx @@ -5,12 +5,17 @@ import { cleanupScreens, compiledRootCommand, inProjectContext, + initProject, menuEntries, renderScreen, waitForText, } from "../testing"; afterEach(cleanupScreens); +const projectCleanups: Array<() => Promise> = []; +afterEach(async () => { + await Promise.all(projectCleanups.splice(0).map((cleanup) => cleanup())); +}); function menusWithCliOnlyChildren(command: Command, path: string[] = []): [string[], string[]][] { const here = [...path, command.name()]; @@ -30,7 +35,27 @@ test.each( ([path, hidden]) => [path.join(" "), path, hidden] as const, ), )("%s hides CLI-only children", async (_label, path, hidden) => { + if (path.join("/") === "agentcore/add/credentials/payment") { + const project = await initProject({ + name: "WizardProject", + flags: ["--template", "agent-python-minimal"], + }); + projectCleanups.push(project.cleanup); + } const screen = renderScreen("/" + path.join("/"), { withContext: inProjectContext }); + if (path.join("/") === "agentcore/add/credentials/payment") { + // The compatibility group keeps its original wizard rather than adding a menu. + await waitForText(screen.lastFrame, "what should this credential provider be called?"); + await screen.write("menu-check"); + await screen.press("return"); + await waitForText(screen.lastFrame, "which payment provider?"); + const picker = screen.lastFrame()!.split("which payment provider?")[1]!; + const choices = [...picker.matchAll(/[●○]\s+(\S+)/g)].map((match) => match[1]); + expect(choices).toEqual(["CoinbaseCDP", "StripePrivy"]); + for (const name of hidden) expect(screen.lastFrame()).not.toContain(name); + screen.unmount(); + return; + } await waitForText(screen.lastFrame, "type to choose a command"); const entries = menuEntries(screen.lastFrame()!); const visible = [...entries.screens, ...entries.cliOnly]; diff --git a/src/core/payment.tsx b/src/core/payment.tsx index 045097f100..5cf379199a 100644 --- a/src/core/payment.tsx +++ b/src/core/payment.tsx @@ -1,3 +1,4 @@ +import { ServiceException } from "@smithy/core/client"; import { GetPaymentConnectorCommand, GetPaymentManagerCommand, @@ -14,6 +15,20 @@ import { import { GetPaymentInstrumentBalanceCommand, GetPaymentInstrumentCommand, + CreatePaymentIntentCommand, + type CreatePaymentIntentResponse, + CreateBuyerApprovalUrlCommand, + type CreateBuyerApprovalUrlResponse, + InitiatePaymentIntentCommand, + type InitiatePaymentIntentResponse, + AuthorizePaymentIntentCommand, + type AuthorizePaymentIntentResponse, + CapturePaymentIntentCommand, + type CapturePaymentIntentResponse, + CancelPaymentIntentCommand, + type CancelPaymentIntentResponse, + GetPaymentIntentCommand, + type GetPaymentIntentResponse, GetPaymentSessionCommand, ListPaymentInstrumentsCommand, ListPaymentSessionsCommand, @@ -24,9 +39,21 @@ import { type ListPaymentInstrumentsResponse, type ListPaymentSessionsResponse, } from "@aws-sdk/client-bedrock-agentcore"; -import { InputValidationError, MalformedServiceResponseError } from "../errors"; +import { + AgentCoreCLIError, + ERROR_SOURCE, + InputValidationError, + MalformedServiceResponseError, +} from "../errors"; import type { CorePaymentClient, + CreatePaymentIntentInput, + CreateBuyerApprovalUrlInput, + InitiatePaymentIntentInput, + AuthorizePaymentIntentInput, + CapturePaymentIntentInput, + CancelPaymentIntentInput, + GetPaymentIntentInput, GetPaymentSessionInput, ListPaymentSessionsInput, GetPaymentInstrumentInput, @@ -99,6 +126,106 @@ export class PaymentClient implements CorePaymentClient { // ─── payment sessions (data plane) ────────────────────────────────────────── + async createPaymentIntent( + input: CreatePaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("CreatePaymentIntent", () => + data.send(new CreatePaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async createBuyerApprovalUrl( + input: CreateBuyerApprovalUrlInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("CreateBuyerApprovalUrl", () => + data.send(new CreateBuyerApprovalUrlCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async initiatePaymentIntent( + input: InitiatePaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("InitiatePaymentIntent", () => + data.send(new InitiatePaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async authorizePaymentIntent( + input: AuthorizePaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("AuthorizePaymentIntent", () => + data.send(new AuthorizePaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async capturePaymentIntent( + input: CapturePaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + if (!input.clientToken?.trim()) + throw new InputValidationError("Capture requires a nonempty caller-owned client token"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("CapturePaymentIntent", () => + data.send(new CapturePaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async cancelPaymentIntent( + input: CancelPaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("CancelPaymentIntent", () => + data.send(new CancelPaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + + async getPaymentIntent( + input: GetPaymentIntentInput, + options: CoreOptions, + ): Promise { + if (!input.userId?.trim()) + throw new InputValidationError("Payment intent requires a nonempty buyer user ID"); + const { managerId, ...request } = input; + return this.withPaymentManagerArn(managerId, options, (data, paymentManagerArn) => + this.safeIntentCall("GetPaymentIntent", () => + data.send(new GetPaymentIntentCommand({ paymentManagerArn, ...request })), + ), + ); + } + async getPaymentSession( input: GetPaymentSessionInput, options: CoreOptions, @@ -153,6 +280,39 @@ export class PaymentClient implements CorePaymentClient { // ─── helpers ──────────────────────────────────────────────────────────────── + private async safeIntentCall(operation: string, send: () => Promise): Promise { + try { + return await send(); + } catch (error) { + // PSP/API error messages can echo checkout details or callback secrets. + const service = ServiceException.isInstance(error) ? error : undefined; + const code = + service && /^[A-Za-z][A-Za-z0-9]{0,127}$/.test(service.name) + ? service.name + : "PaymentIntentError"; + const requestId = service?.$metadata.requestId; + const safeRequestId = + requestId && /^[A-Za-z0-9-]{1,128}$/.test(requestId) ? requestId : undefined; + const httpStatusCode = service?.$metadata.httpStatusCode; + throw new AgentCoreCLIError( + `${operation} failed (${code})${safeRequestId ? `; request ID ${safeRequestId}` : ""}`, + { + name: code, + source: + httpStatusCode !== undefined && httpStatusCode >= 400 && httpStatusCode < 500 + ? ERROR_SOURCE.USER + : ERROR_SOURCE.SERVICE, + meta: { + operation, + code, + ...(safeRequestId && { requestId: safeRequestId }), + ...(httpStatusCode !== undefined && { httpStatusCode }), + }, + }, + ); + } + } + private async withPaymentManagerArn( managerId: string, options: CoreOptions, diff --git a/src/core/project/backends/cdk.test.ts b/src/core/project/backends/cdk.test.ts index 6c2d2633d0..9148ecfb47 100644 --- a/src/core/project/backends/cdk.test.ts +++ b/src/core/project/backends/cdk.test.ts @@ -1033,6 +1033,44 @@ describe("CdkBackend.deploy", () => { expect(provisioned).toBe(false); expect(h.commands).toHaveLength(0); }); + test("refuses payment vendors an older CDK package lacks before writing any Identity provider", async () => { + const p = await project(); + p.spec = ProjectSpecSchema.parse({ + name: "example", + version: 2, + credentials: [ + { name: "shop", authorizerType: "PaymentCredentialProvider", provider: "Stripe" }, + ], + payments: [ + { + name: "MyPayments", + connectors: [ + { name: "Card", provider: "Stripe", credentialName: "shop" }, + { name: "Billing", provider: "AwsBilling" }, + ], + }, + ], + }); + const probed: unknown[] = []; + // unusedIdentity fails any provider read or write, so reaching provisioning would + // surface as an "unexpected Identity call" rather than this error. + const h = harness({ + assertCdkFeatures: async (_directory, features) => { + probed.push(features); + throw new Error("CDK package lacks payment vendors"); + }, + }); + await expect(collectDeploy(h.backend.deploy(p, deployInput()))).rejects.toThrow( + "lacks payment vendors", + ); + expect(probed).toEqual([ + [ + "merchant payment credentials (Stripe, PayPal, Amazon Pay)", + "AwsBilling payment connectors", + ], + ]); + expect(h.commands).toHaveLength(0); + }); test("refuses an unavailable local builder before provisioning credentials or invoking Toolkit", async () => { const p = await project(); p.spec.runtimes.push( diff --git a/src/core/project/backends/cdk.ts b/src/core/project/backends/cdk.ts index 14b466e89e..5bfe54733f 100644 --- a/src/core/project/backends/cdk.ts +++ b/src/core/project/backends/cdk.ts @@ -337,9 +337,14 @@ export class CdkBackend implements ProjectBackend { yield* this.ensureCdkDependencies(project, input); const { builds, local } = resolveWorkloads(project); // An older CDK package would silently drop settings it does not know. - await this.assertCdkFeatures(this.cdkDirectory(project), cdkFeaturesFor(builds), this.runner, { - dependenciesManaged: !input.disableDependencyManagement, - }); + await this.assertCdkFeatures( + this.cdkDirectory(project), + cdkFeaturesFor(builds, project.spec), + this.runner, + { + dependenciesManaged: !input.disableDependencyManagement, + }, + ); yield* this.synthesize(project, true); yield* this.buildLocalImages(project, builds, local); } @@ -428,9 +433,14 @@ export class CdkBackend implements ProjectBackend { let containerExecutable: string | undefined; let buildxBuilder: string | undefined; // Before any AWS mutation: an older CDK package would silently drop settings. - await this.assertCdkFeatures(this.cdkDirectory(project), cdkFeaturesFor(builds), this.runner, { - dependenciesManaged: !input.disableDependencyManagement, - }); + await this.assertCdkFeatures( + this.cdkDirectory(project), + cdkFeaturesFor(builds, project.spec), + this.runner, + { + dependenciesManaged: !input.disableDependencyManagement, + }, + ); if (hasLocalContainerBuilds(builds)) { containerExecutable = await this.resolveContainerExecutable(); yield { diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 92117dd7ae..5188970518 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -10,6 +10,7 @@ import { CDK_FEATURE_RELEASES, MINIMUM_COMPATIBLE_CDK_VERSION, } from "./compatibility"; +import type { ProjectSpec } from "../../../../projectSchemas/project"; const tempDirectories: string[] = []; @@ -86,6 +87,22 @@ describe("assertCdkFeatureSupport", () => { return directory; } + test("detects payment vendor support from the package's payment schemas", async () => { + const payments = + "exports.PaymentProviderSchema = { safeParse: () => ({ success: true }) };" + + "exports.PaymentConnectorSchema = { safeParse: () => ({ success: true }) };"; + const features = [ + "merchant payment credentials (Stripe, PayPal, Amazon Pay)", + "AwsBilling payment connectors", + ] as const; + await expect( + assertCdkFeatureSupport(await cdkPackage(payments), features), + ).resolves.toBeUndefined(); + await expect(assertCdkFeatureSupport(await cdkPackage(""), features)).rejects.toThrow( + `@aws/agentcore-cdk ${CDK_FEATURE_RELEASES["AwsBilling payment connectors"]} or newer`, + ); + }); + test("accepts a package that supports every feature the project uses", async () => { const directory = await cdkPackage(CONTAINER_LOCAL + CONTAINER_URI); await expect( @@ -142,6 +159,8 @@ describe("assertCdkFeatureSupport", () => { expect(CDK_FEATURE_RELEASES).toEqual({ ContainerLocal: "1.2.0", "Runtime containerUri": "1.3.0", + "merchant payment credentials (Stripe, PayPal, Amazon Pay)": "1.4.0", + "AwsBilling payment connectors": "1.4.0", }); }); @@ -249,4 +268,18 @@ describe("cdkFeaturesFor", () => { "Runtime containerUri", ]); }); + test("derives payment features from merchant credentials and AwsBilling connectors", () => { + const credential = (provider: "CoinbaseCDP" | "Stripe") => + ({ authorizerType: "PaymentCredentialProvider", name: "pay", provider }) as const; + const awsBilling = [ + { name: "billing", connectors: [{ name: "aws", provider: "AwsBilling" }] }, + ] as unknown as ProjectSpec["payments"]; + expect(cdkFeaturesFor({}, { credentials: [credential("CoinbaseCDP")] })).toEqual([]); + expect( + cdkFeaturesFor({}, { credentials: [credential("Stripe")], payments: awsBilling }), + ).toEqual([ + "merchant payment credentials (Stripe, PayPal, Amazon Pay)", + "AwsBilling payment connectors", + ]); + }); }); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index b0e2ad4e3c..49df26f131 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -4,16 +4,23 @@ import semver from "semver"; import { ProjectStateError } from "../../../../errors"; import { ProcessFailedError, runProcess, type ProcessRunner } from "../../../../io"; import type { WorkloadBuilds } from "../../../../handlers/project/types"; +import type { ProjectSpec } from "../../../../projectSchemas/project"; export const MINIMUM_COMPATIBLE_CDK_VERSION = "1.0.0"; /** CDK package features a project can depend on beyond the minimum version. */ -export type CdkFeature = "ContainerLocal" | "Runtime containerUri"; +export type CdkFeature = + | "ContainerLocal" + | "Runtime containerUri" + | "merchant payment credentials (Stripe, PayPal, Amazon Pay)" + | "AwsBilling payment connectors"; /** The first @aws/agentcore-cdk release with each feature. */ export const CDK_FEATURE_RELEASES: Record = { ContainerLocal: "1.2.0", "Runtime containerUri": "1.3.0", + "merchant payment credentials (Stripe, PayPal, Amazon Pay)": "1.4.0", + "AwsBilling payment connectors": "1.4.0", }; // Runs in Node, like the CDK app: a standalone CLI binary cannot reliably resolve @@ -62,6 +69,14 @@ function probe() { }); return Boolean(parsed?.success && parsed.data.containerUri === containerUri); }, + "merchant payment credentials (Stripe, PayPal, Amazon Pay)": () => + ["Stripe", "PayPal", "AmazonPay"].every( + (provider) => cdk.PaymentProviderSchema?.safeParse(provider).success, + ), + "AwsBilling payment connectors": () => + Boolean( + cdk.PaymentConnectorSchema?.safeParse({ name: "probe", provider: "AwsBilling" }).success, + ), }; return { missing: wanted.filter((feature) => { @@ -76,9 +91,13 @@ function probe() { process.stdout.write("\\n${PROBE_RESULT_PREFIX}" + JSON.stringify(probe()) + "\\n"); `; -/** The CDK features a project's workloads use. A Harness containerUri predates both. */ -export function cdkFeaturesFor(builds: WorkloadBuilds): CdkFeature[] { +/** The CDK features a project uses. A Harness containerUri predates all of them. */ +export function cdkFeaturesFor( + builds: WorkloadBuilds, + spec?: Pick, +): CdkFeature[] { const entries = Object.entries(builds); + const merchantProviders = new Set(["Stripe", "PayPal", "AmazonPay"]); return [ ...(entries.some(([, build]) => build === "ContainerLocal") ? (["ContainerLocal"] as const) @@ -86,6 +105,18 @@ export function cdkFeaturesFor(builds: WorkloadBuilds): CdkFeature[] { ...(entries.some(([key, build]) => key.startsWith("runtime/") && build === "ContainerUri") ? (["Runtime containerUri"] as const) : []), + ...(spec?.credentials.some( + (credential) => + credential.authorizerType === "PaymentCredentialProvider" && + merchantProviders.has(credential.provider), + ) + ? (["merchant payment credentials (Stripe, PayPal, Amazon Pay)"] as const) + : []), + ...(spec?.payments?.some((manager) => + manager.connectors.some((connector) => connector.provider === "AwsBilling"), + ) + ? (["AwsBilling payment connectors"] as const) + : []), ]; } diff --git a/src/core/project/backends/cdk/credentials.test.ts b/src/core/project/backends/cdk/credentials.test.ts index 5bf24ac3a5..2e4f39589d 100644 --- a/src/core/project/backends/cdk/credentials.test.ts +++ b/src/core/project/backends/cdk/credentials.test.ts @@ -4,6 +4,7 @@ import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { ResourceNotFoundException, + ValidationException, type GetApiKeyCredentialProviderResponse, type GetOauth2CredentialProviderResponse, type GetPaymentCredentialProviderResponse, @@ -115,6 +116,7 @@ type StoredProvider = { credentialProviderVendor?: string; /** The request body this provider was last written with; absent if never written. */ config?: unknown; + providerConfigurationOutput?: GetPaymentCredentialProviderResponse["providerConfigurationOutput"]; /** How this run last touched it; absent when it was left exactly as found. */ operation?: "created" | "updated"; }; @@ -129,10 +131,15 @@ type Behavior = { deleteFails?: Error; /** Thrown when the named provider would be created. */ createFailsFor?: string; + /** Service rejects source/config fields when the external-secrets feature is disabled. */ + externalSecretsDisabled?: boolean; }; /** A provider already in the fake account, optionally one of a specific vendor. */ -type ExistingProvider = DeployedCredential & { credentialProviderVendor?: string }; +type ExistingProvider = DeployedCredential & { + credentialProviderVendor?: string; + providerConfigurationOutput?: GetPaymentCredentialProviderResponse["providerConfigurationOutput"]; +}; /** * An in-memory Identity account: providers can be looked up, created, updated and @@ -173,6 +180,22 @@ function account( if (operation === "created" && behavior.createFailsFor === name) { throw new Error(`create ${name} failed`); } + if (kind === "payment" && behavior.externalSecretsDisabled) { + const input = config as { + providerConfigurationInput: Record>; + }; + if ( + Object.values(input.providerConfigurationInput).some((fields) => + Object.keys(fields).some((key) => key.endsWith("Source") || key.endsWith("Config")), + ) + ) { + throw new ValidationException({ + $metadata: {}, + message: "External secrets are disabled", + reason: "FieldValidationFailed", + }); + } + } const arns = behavior.writeReturns ?? ({ @@ -215,13 +238,40 @@ function account( }), }) as GetOauth2CredentialProviderResponse; - const asPayment = (provider: StoredProvider) => - ({ + const asPayment = (provider: StoredProvider) => { + const input = provider.config as + | { + providerConfigurationInput?: Record>; + } + | undefined; + // Identity returns source metadata, not plaintext secrets. The feature gate can + // omit it; an initial provider can explicitly supply that older response shape. + const output = + input?.providerConfigurationInput && + Object.fromEntries( + Object.entries(input.providerConfigurationInput).map(([key, fields]) => [ + key, + Object.fromEntries( + Object.entries(fields).flatMap(([field, value]) => { + if (field.endsWith("Source")) return [[field, value]]; + if (["restrictedKey", "clientSecret", "authorizationToken"].includes(field)) { + return [[`${field}Source`, "MANAGED"]]; + } + return []; + }), + ), + ]), + ); + return { credentialProviderArn: provider.credentialProviderArn, ...(provider.credentialProviderVendor && { credentialProviderVendor: provider.credentialProviderVendor, }), - }) as GetPaymentCredentialProviderResponse; + providerConfigurationOutput: + provider.providerConfigurationOutput ?? + (behavior.externalSecretsDisabled ? undefined : output), + } as GetPaymentCredentialProviderResponse; + }; const client: CredentialProviderCalls = { async getApiKeyCredentialProvider(name, options) { @@ -947,18 +997,35 @@ describe("createCredentialProvisioner rollback", () => { expect(subject.contents()).toEqual({}); }); - test("deletes a provider it created whose response then failed validation", async () => { - // The create reaches Identity and the provider exists, but the response carries no - // ARN, so validation throws after the side effect. Rollback still owns it. - const subject = account({}, { writeReturns: {} as DeployedCredential }); - const input = await project([API_KEY], "AGENTCORE_CREDENTIAL_OPENAI_KEY='sk-live'\n"); - - const { error } = await runFailing(subject.provision, input); - - expect(error.message).toMatch(/no credentialProviderArn/); - expect(subject.deleted).toEqual([{ kind: "apikey", name: OPENAI_PROVIDER }]); - expect(subject.contents()).toEqual({}); - }); + for (const scenario of [ + { + label: "API key", + credential: API_KEY, + provider: OPENAI_PROVIDER, + env: "AGENTCORE_CREDENTIAL_OPENAI_KEY=example", + }, + { + label: "OAuth", + credential: OAUTH, + provider: "example_dev_my-oauth", + env: "AGENTCORE_CREDENTIAL_MY_OAUTH_CLIENT_SECRET=example", + }, + { + label: "payment", + credential: { authorizerType: "PaymentCredentialProvider", name: "pay", provider: "Stripe" }, + provider: PAY_PROVIDER, + env: "AGENTCORE_CREDENTIAL_PAY_RESTRICTED_KEY=rk_test_example", + }, + ]) { + test(`${scenario.label} rolls back a fulfilled create even when its response lacks an ARN`, async () => { + const subject = account({}, { writeReturns: {} as DeployedCredential }); + const input = await project([scenario.credential], scenario.env); + const { error } = await runFailing(subject.provision, input); + expect(error.message).toMatch(/no credentialProviderArn/); + expect(subject.deleted.map(({ name }) => name)).toEqual([scenario.provider]); + expect(subject.contents()).toEqual({}); + }); + } test("does not delete a provider it only updated", async () => { const subject = account( @@ -1286,3 +1353,315 @@ describe("v0 projects", () => { ]); }); }); + +describe("merchant payment reconciliation", () => { + const external = { secretId: "merchant-secret", jsonKey: "key" }; + const configurations = [ + { + provider: "Stripe", + fields: { RESTRICTED_KEY: "rk_test_example", PUBLISHABLE_KEY: "pk_test_example" }, + configKey: "stripeConfiguration", + secretKey: "restrictedKey", + }, + { + provider: "PayPal", + fields: { + CLIENT_ID: "merchant-client", + CLIENT_SECRET: "example-secret", + ENVIRONMENT: "SANDBOX", + }, + configKey: "payPalConfiguration", + secretKey: "clientSecret", + }, + { + provider: "AmazonPay", + fields: { + MERCHANT_ID: "merchant", + STORE_ID: "store", + AUTHORIZATION_TOKEN: "example-token", + ENVIRONMENT: "LIVE", + AMAZON_PAY_REGION: "EU", + }, + configKey: "amazonPayConfiguration", + secretKey: "authorizationToken", + }, + ] as const; + for (const configuration of configurations) { + for (const reference of [false, true]) { + test(`${configuration.provider} ${reference ? "external" : "managed"} creates then updates without touching external secrets`, async () => { + const env = Object.entries(configuration.fields) + .map(([key, value]) => `AGENTCORE_CREDENTIAL_PAY_${key}=${value}`) + .join("\n"); + const proj = await project( + [ + { + authorizerType: "PaymentCredentialProvider", + name: "pay", + provider: configuration.provider, + ...(reference && { secretRef: external }), + }, + ], + env, + ); + const subject = account(); + await run(subject.provision, proj); + const created = subject.contents()[PAY_PROVIDER]!; + const input = created.config as { + providerConfigurationInput: Record>; + }; + const config = input.providerConfigurationInput[configuration.configKey]!; + expect( + config[reference ? `${configuration.secretKey}Config` : configuration.secretKey], + ).toEqual( + reference + ? external + : Object.values(configuration.fields).find( + (value) => value.startsWith("rk_") || value.startsWith("example-"), + ), + ); + expect(config[`${configuration.secretKey}Source`]).toBe(reference ? "EXTERNAL" : undefined); + if (configuration.provider === "AmazonPay") expect(config.amazonPayRegion).toBe("EU"); + expect(created.operation).toBe("created"); + await run(subject.provision, proj); + expect(subject.contents()[PAY_PROVIDER]?.operation).toBe("updated"); + expect(subject.deleted).toEqual([]); + }); + } + } + + for (const configuration of configurations) { + for (const existingExternal of [false, true]) { + test(`${configuration.provider} rejects ${existingExternal ? "EXTERNAL to MANAGED" : "MANAGED to EXTERNAL"} before any provider writes`, async () => { + const env = Object.entries(configuration.fields) + .map(([key, value]) => `AGENTCORE_CREDENTIAL_PAY_${key}=${value}`) + .join("\n"); + const credential = { + authorizerType: "PaymentCredentialProvider" as const, + name: "pay", + provider: configuration.provider, + }; + const subject = account(); + await run( + subject.provision, + await project([{ ...credential, ...(existingExternal && { secretRef: external }) }], env), + ); + const before = subject.contents(); + const changed = await project( + [API_KEY, { ...credential, ...(!existingExternal && { secretRef: external }) }], + `${env}\nAGENTCORE_CREDENTIAL_OPENAI_KEY=example`, + ); + + await expect(run(subject.provision, changed)).rejects.toThrow( + /cannot change.*MANAGED.*EXTERNAL|cannot change.*EXTERNAL.*MANAGED/, + ); + expect(subject.contents()).toEqual(before); + expect(subject.deleted).toEqual([]); + }); + } + + for (const source of ["MANAGED", "EXTERNAL"] as const) { + test(`${configuration.provider} rotates ${source} material without changing ownership`, async () => { + const credential = { + authorizerType: "PaymentCredentialProvider" as const, + name: "pay", + provider: configuration.provider, + ...(source === "EXTERNAL" && { secretRef: external }), + }; + const env = Object.entries(configuration.fields) + .map(([key, value]) => `AGENTCORE_CREDENTIAL_PAY_${key}=${value}`) + .join("\n"); + const subject = account(); + await run(subject.provision, await project([credential], env)); + const arn = subject.contents()[PAY_PROVIDER]!.credentialProviderArn; + const rotatedEnv = env + .replace("rk_test_example", "rk_test_rotated") + .replace("example-secret", "rotated-secret") + .replace("example-token", "rotated-token"); + const rotatedRef = { secretId: "replacement", jsonKey: "new-key" }; + await run( + subject.provision, + await project( + [{ ...credential, ...(source === "EXTERNAL" && { secretRef: rotatedRef }) }], + rotatedEnv, + ), + ); + expect(subject.contents()[PAY_PROVIDER]?.credentialProviderArn).toBe(arn); + expect(subject.contents()[PAY_PROVIDER]?.operation).toBe("updated"); + const body = subject.configFor(PAY_PROVIDER) as { + providerConfigurationInput: Record>; + }; + const fields = body.providerConfigurationInput[configuration.configKey]!; + expect( + fields[ + source === "EXTERNAL" ? `${configuration.secretKey}Config` : configuration.secretKey + ], + ).toEqual( + source === "EXTERNAL" + ? rotatedRef + : configuration.provider === "Stripe" + ? "rk_test_rotated" + : configuration.provider === "PayPal" + ? "rotated-secret" + : "rotated-token", + ); + expect(subject.deleted).toEqual([]); + }); + } + + for (const reference of [false, true]) { + test(`${configuration.provider} does not infer an omitted source for ${reference ? "external" : "managed"} updates`, async () => { + const credential = { + authorizerType: "PaymentCredentialProvider" as const, + name: "pay", + provider: configuration.provider, + ...(reference && { secretRef: external }), + }; + const env = Object.entries(configuration.fields) + .map(([key, value]) => `AGENTCORE_CREDENTIAL_PAY_${key}=${value}`) + .join("\n"); + const subject = account({ + [PAY_PROVIDER]: { + credentialProviderArn: paymentArn(PAY_PROVIDER), + credentialProviderVendor: configuration.provider, + // JSON key presence must not be interpreted as a source discriminator. + providerConfigurationOutput: { + [configuration.configKey]: { + [`${configuration.secretKey}JsonKey`]: "key", + }, + } as unknown as GetPaymentCredentialProviderResponse["providerConfigurationOutput"], + }, + }); + await run(subject.provision, await project([credential], env)); + expect(subject.contents()[PAY_PROVIDER]?.operation).toBe("updated"); + expect(subject.deleted).toEqual([]); + }); + } + + test(`${configuration.provider} managed create and update work without external-secrets support`, async () => { + const credential = { + authorizerType: "PaymentCredentialProvider" as const, + name: "pay", + provider: configuration.provider, + }; + const env = Object.entries(configuration.fields) + .map(([key, value]) => `AGENTCORE_CREDENTIAL_PAY_${key}=${value}`) + .join("\n"); + const subject = account({}, { externalSecretsDisabled: true }); + const input = await project([credential], env); + await run(subject.provision, input); + await run(subject.provision, input); + expect(subject.contents()[PAY_PROVIDER]?.operation).toBe("updated"); + expect(subject.deleted).toEqual([]); + }); + } + + test("external PayPal secret still requires client ID and environment", async () => { + const proj = await project([ + { + authorizerType: "PaymentCredentialProvider", + name: "pay", + provider: "PayPal", + secretRef: external, + }, + ]); + const subject = account(); + await expect(run(subject.provision, proj)).rejects.toThrow( + "AGENTCORE_CREDENTIAL_PAY_CLIENT_ID, AGENTCORE_CREDENTIAL_PAY_ENVIRONMENT", + ); + expect(Object.keys(subject.contents()).length).toBe(0); + }); + + test.each(["us-east-1", "JP"])( + "invalid merchant region %s fails before any provider writes", + async (region) => { + const proj = await project( + [ + API_KEY, + { + authorizerType: "PaymentCredentialProvider", + name: "pay", + provider: "AmazonPay", + secretRef: external, + }, + ], + [ + "AGENTCORE_CREDENTIAL_OPENAI_KEY=example", + "AGENTCORE_CREDENTIAL_PAY_MERCHANT_ID=merchant", + "AGENTCORE_CREDENTIAL_PAY_STORE_ID=store", + "AGENTCORE_CREDENTIAL_PAY_ENVIRONMENT=SANDBOX", + `AGENTCORE_CREDENTIAL_PAY_AMAZON_PAY_REGION=${region}`, + ].join("\n"), + ); + const subject = account(); + await expect(run(subject.provision, proj)).rejects.toThrow("merchant region"); + expect(Object.keys(subject.contents()).length).toBe(0); + }, + ); +}); + +test("merchant empty placeholders report missing values", async () => { + const proj = await project( + [{ authorizerType: "PaymentCredentialProvider", name: "pay", provider: "AmazonPay" }], + "AGENTCORE_CREDENTIAL_PAY_ENVIRONMENT=''\nAGENTCORE_CREDENTIAL_PAY_AMAZON_PAY_REGION=''\nAGENTCORE_CREDENTIAL_PAY_AUTHORIZATION_TOKEN=''", + ); + await expect(run(account().provision, proj)).rejects.toThrow("missing the values"); +}); + +test("external Stripe source ignores stale local restricted key", async () => { + const proj = await project( + [ + { + authorizerType: "PaymentCredentialProvider", + name: "pay", + provider: "Stripe", + secretRef: { secretId: "merchant", jsonKey: "key" }, + }, + ], + "AGENTCORE_CREDENTIAL_PAY_RESTRICTED_KEY=stale\nAGENTCORE_CREDENTIAL_PAY_PUBLISHABLE_KEY=pk_test_example", + ); + const subject = account(); + await run(subject.provision, proj); + expect(subject.contents()[PAY_PROVIDER]?.config).toEqual({ + name: PAY_PROVIDER, + credentialProviderVendor: "Stripe", + providerConfigurationInput: { + stripeConfiguration: { + restrictedKeyConfig: { secretId: "merchant", jsonKey: "key" }, + restrictedKeySource: "EXTERNAL", + publishableKey: "pk_test_example", + }, + }, + }); +}); + +test("a changed external source cannot be silently skipped for an existing merchant provider", async () => { + const proj = await project([ + { + authorizerType: "PaymentCredentialProvider", + name: "pay", + provider: "PayPal", + secretRef: { secretId: "replacement", jsonKey: "key" }, + }, + ]); + const subject = account({ + [PAY_PROVIDER]: { + credentialProviderArn: paymentArn(PAY_PROVIDER), + credentialProviderVendor: "PayPal", + }, + }); + await expect(run(subject.provision, proj)).rejects.toThrow("missing the values"); + expect(subject.contents()[PAY_PROVIDER]?.operation).toBeUndefined(); + expect(subject.deleted).toEqual([]); +}); + +test.each(["PayPal", "AmazonPay"] as const)( + "incomplete %s scaffold fails deployment before provider writes", + async (provider) => { + const proj = await project([ + { authorizerType: "PaymentCredentialProvider", name: "pay", provider }, + ]); + const subject = account(); + await expect(run(subject.provision, proj)).rejects.toThrow("missing the values"); + expect(Object.keys(subject.contents())).toEqual([]); + }, +); diff --git a/src/core/project/backends/cdk/credentials.ts b/src/core/project/backends/cdk/credentials.ts index 356e91e2cc..173bd5bac3 100644 --- a/src/core/project/backends/cdk/credentials.ts +++ b/src/core/project/backends/cdk/credentials.ts @@ -4,6 +4,7 @@ import { ResourceNotFoundException, type Oauth2ProviderConfigInput, type PaymentProviderConfigurationInput, + type PaymentProviderConfigurationOutput, } from "@aws-sdk/client-bedrock-agentcore-control"; import { MalformedServiceResponseError, ProjectStateError } from "../../../../errors/errors"; import type { CoreIdentityClient } from "../../../../handlers/identity/types"; @@ -21,6 +22,10 @@ import { credentialEnvVarName, } from "../../../../projectSchemas/credential"; import type { CoreOptions } from "../../../types"; +import { + PaymentEnvironmentSchema, + AmazonPayRegionSchema, +} from "../../../../projectSchemas/payment"; import { ENV_LOCAL_RELATIVE_PATH, EnvLocalFile } from "../../envLocal"; import type { CdkCredentialProvider } from "./toolkit"; @@ -600,16 +605,21 @@ async function resolvePayment( const fields = paymentFields(credential, env); if ("missing" in fields) { - if (existing) return { reuse: paymentProvision(provider, existing) }; + // A configured external source is an update request. Do not silently ignore it + // when other vendor fields needed to send that update are absent. + if (existing && !("secretRef" in credential && credential.secretRef)) { + return { reuse: paymentProvision(provider, existing) }; + } throw missingPaymentSecrets(name, fields.missing, rootPath); } const input = { name: provider, - credentialProviderVendor: credential.provider as never, + credentialProviderVendor: credential.provider, providerConfigurationInput: fields.configuration, }; if (existing) { + requirePaymentSourceMatch(credential, provider, existing.providerConfigurationOutput); return { kind: "update", write: async () => @@ -623,6 +633,37 @@ async function resolvePayment( }; } +function requirePaymentSourceMatch( + credential: PaymentCredential, + provider: string, + configuration: PaymentProviderConfigurationOutput | undefined, +): void { + let source: string | undefined; + switch (credential.provider) { + case "Stripe": + source = configuration?.stripeConfiguration?.restrictedKeySource; + break; + case "PayPal": + source = configuration?.payPalConfiguration?.clientSecretSource; + break; + case "AmazonPay": + source = configuration?.amazonPayConfiguration?.authorizationTokenSource; + break; + default: + return; + } + // Identity may omit this metadata when external-secrets support is disabled. + // Absence is not evidence of MANAGED ownership; let Identity validate the update. + if (source !== "MANAGED" && source !== "EXTERNAL") return; + const desired = credential.secretRef ? "EXTERNAL" : "MANAGED"; + if (source === desired) return; + throw new ProjectStateError( + `Credential '${credential.name}' cannot change provider '${provider}' from ${source} to ` + + `${desired}. Create a credential with a different name and point its connectors to it, ` + + "then deploy. The existing provider is unchanged.", + ); +} + /** * Collects a payment vendor's configuration from the environment, or reports every * variable that is unset so the user can fill them in one pass. @@ -631,31 +672,110 @@ function paymentFields( credential: PaymentCredential, env: Record, ): { configuration: PaymentProviderConfigurationInput } | { missing: string[] } { - const read = (suffix: string) => env[credentialEnvVarName(credential.name, suffix)]; - const missing = credentialEnvironmentVariableNames(credential).filter((key) => !env[key]); + const read = (suffix: string) => { + const value = env[credentialEnvVarName(credential.name, suffix)]; + return value?.trim() ? value : undefined; + }; + const invalid = (field: string): never => { + throw new ProjectStateError(`Credential '${credential.name}' has an invalid ${field}`); + }; + const environment = read("_ENVIRONMENT"); + const region = read("_AMAZON_PAY_REGION"); + if ( + (credential.provider === "PayPal" || credential.provider === "AmazonPay") && + environment !== undefined && + !PaymentEnvironmentSchema.safeParse(environment).success + ) { + invalid("environment (expected SANDBOX or LIVE)"); + } + if ( + credential.provider === "AmazonPay" && + region !== undefined && + !AmazonPayRegionSchema.safeParse(region).success + ) + invalid("Amazon Pay merchant region (expected NA or EU)"); + if (credential.provider === "Stripe") { + const restricted = credential.secretRef ? undefined : read("_RESTRICTED_KEY"); + const publishable = read("_PUBLISHABLE_KEY"); + if (restricted !== undefined && !/^rk_(test|live)_\S+$/.test(restricted)) + invalid("Stripe restricted key"); + if (publishable !== undefined && !/^pk_(test|live)_\S+$/.test(publishable)) + invalid("Stripe publishable key"); + if (restricted && publishable && restricted.split("_")[1] !== publishable.split("_")[1]) { + invalid("Stripe key mode combination"); + } + } + const missing = credentialEnvironmentVariableNames(credential) + .filter((key) => key !== credentialEnvVarName(credential.name, "_PUBLISHABLE_KEY")) + .filter((key) => !env[key]?.trim()); if (missing.length > 0) return { missing }; - if (credential.provider === "CoinbaseCDP") { - return { - configuration: { - coinbaseCdpConfiguration: { - apiKeyId: read("_API_KEY_ID")!, - apiKeySecret: read("_API_KEY_SECRET")!, - walletSecret: read("_WALLET_SECRET")!, + switch (credential.provider) { + case "CoinbaseCDP": + return { + configuration: { + coinbaseCdpConfiguration: { + apiKeyId: read("_API_KEY_ID")!, + apiKeySecret: read("_API_KEY_SECRET")!, + walletSecret: read("_WALLET_SECRET")!, + }, }, - }, - }; + }; + case "StripePrivy": + return { + configuration: { + stripePrivyConfiguration: { + appId: read("_APP_ID")!, + appSecret: read("_APP_SECRET")!, + authorizationPrivateKey: read("_AUTHORIZATION_PRIVATE_KEY")!, + authorizationId: read("_AUTHORIZATION_ID")!, + }, + }, + }; + case "Stripe": + return { + configuration: { + stripeConfiguration: { + // Omitted source selects managed storage without requiring the BYOS flag. + ...(credential.secretRef + ? { restrictedKeyConfig: credential.secretRef, restrictedKeySource: "EXTERNAL" } + : { restrictedKey: read("_RESTRICTED_KEY")! }), + ...(read("_PUBLISHABLE_KEY") && { publishableKey: read("_PUBLISHABLE_KEY") }), + }, + }, + }; + case "PayPal": + return { + configuration: { + payPalConfiguration: { + clientId: read("_CLIENT_ID")!, + environment: PaymentEnvironmentSchema.parse(environment), + ...(credential.secretRef + ? { clientSecretConfig: credential.secretRef, clientSecretSource: "EXTERNAL" } + : { clientSecret: read("_CLIENT_SECRET")! }), + }, + }, + }; + case "AmazonPay": + return { + configuration: { + amazonPayConfiguration: { + merchantId: read("_MERCHANT_ID")!, + storeId: read("_STORE_ID")!, + environment: PaymentEnvironmentSchema.parse(environment), + amazonPayRegion: AmazonPayRegionSchema.parse(region), + ...(credential.secretRef + ? { + authorizationTokenConfig: credential.secretRef, + authorizationTokenSource: "EXTERNAL", + } + : { + authorizationToken: read("_AUTHORIZATION_TOKEN")!, + }), + }, + }, + }; } - return { - configuration: { - stripePrivyConfiguration: { - appId: read("_APP_ID")!, - appSecret: read("_APP_SECRET")!, - authorizationPrivateKey: read("_AUTHORIZATION_PRIVATE_KEY")!, - authorizationId: read("_AUTHORIZATION_ID")!, - }, - }, - }; } /** diff --git a/src/handlers/payment/index.tsx b/src/handlers/payment/index.tsx index 7b37fecbbb..c1330940a3 100644 --- a/src/handlers/payment/index.tsx +++ b/src/handlers/payment/index.tsx @@ -6,11 +6,12 @@ import type { Core } from "../types"; import { createPaymentConnectorHandler } from "./connector"; import { createPaymentInstrumentHandler } from "./instrument"; import { createPaymentManagerHandler } from "./manager"; +import { createPaymentIntentHandler } from "./intent"; import { createPaymentSessionHandler } from "./session"; export function createPaymentHandler(core: Core, io: AppIO): Router { return ( - new Router("payment", "inspect payment managers, sessions, and instruments") + new Router("payment", "inspect payment resources and manage intent lifecycles") .use(withTuiOnEmptyFlagsAndArgs(core, io)) .default(renderTui(core, io)) // No payment screens ship yet: every leaf runs from the command line and the @@ -20,5 +21,6 @@ export function createPaymentHandler(core: Core, io: AppIO): Router { .handler(createPaymentConnectorHandler(core, io)) .handler(createPaymentSessionHandler(core, io)) .handler(createPaymentInstrumentHandler(core, io)) + .handler(createPaymentIntentHandler(core, io)) ); } diff --git a/src/handlers/payment/intent/authorize/index.tsx b/src/handlers/payment/intent/authorize/index.tsx new file mode 100644 index 0000000000..ca4bc7bda1 --- /dev/null +++ b/src/handlers/payment/intent/authorize/index.tsx @@ -0,0 +1,42 @@ +import z from "zod"; +import type { AppIO } from "../../../../io"; +import { createHandler, flag } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { + PaymentIntentScope, + intentIdFlag, + optionalClientTokenFlag, + PaymentIntentSources, +} from "../input"; + +export const createAuthorizePaymentIntentHandler = (core: Core, io: AppIO) => + createHandler({ + name: "authorize", + description: "authorize an initiated intent using developer/backend credentials", + flags: [ + ...PaymentIntentScope.flags, + intentIdFlag, + flag( + "partner-callback-result", + "sensitive partner callback from file:// or stdin '-'", + z.string().optional(), + { sensitive: true }, + ), + optionalClientTokenFlag, + ], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentIntentId: flags["intent-id"], + partnerCallbackResult: await new PaymentIntentSources(io).callback( + flags["partner-callback-result"], + ), + ...(flags["client-token"] !== undefined && { clientToken: flags["client-token"] }), + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.authorizePaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/cancel/index.tsx b/src/handlers/payment/intent/cancel/index.tsx new file mode 100644 index 0000000000..6501b53d5c --- /dev/null +++ b/src/handlers/payment/intent/cancel/index.tsx @@ -0,0 +1,22 @@ +import { createHandler } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { PaymentIntentScope, intentIdFlag, optionalClientTokenFlag } from "../input"; + +export const createCancelPaymentIntentHandler = (core: Core) => + createHandler({ + name: "cancel", + description: "cancel a payment intent", + flags: [...PaymentIntentScope.flags, intentIdFlag, optionalClientTokenFlag], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentIntentId: flags["intent-id"], + ...(flags["client-token"] !== undefined && { clientToken: flags["client-token"] }), + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.cancelPaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/capture/index.tsx b/src/handlers/payment/intent/capture/index.tsx new file mode 100644 index 0000000000..ee7ad23225 --- /dev/null +++ b/src/handlers/payment/intent/capture/index.tsx @@ -0,0 +1,52 @@ +import z from "zod"; +import type { AppIO } from "../../../../io"; +import { createHandler, flag } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { + PaymentIntentScope, + intentIdFlag, + PaymentIntentSources, + PaymentIntentAmountSchema, + ClientTokenSchema, +} from "../input"; + +export const createCapturePaymentIntentHandler = (core: Core, io: AppIO) => + createHandler({ + name: "capture", + description: "capture authorized funds using developer/backend credentials", + flags: [ + ...PaymentIntentScope.flags, + intentIdFlag, + flag( + "capture-amount", + "optional amount JSON object, file://, or stdin '-' (omitted: remainder)", + z.string().optional(), + { sensitive: true }, + ), + flag( + "client-token", + "caller-owned capture token (33-256 letters, digits or hyphens); reuse on retries, new token requests a new capture", + ClientTokenSchema, + { sensitive: true }, + ), + ], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentIntentId: flags["intent-id"], + ...(flags["capture-amount"] !== undefined && { + captureAmount: await new PaymentIntentSources(io).json( + "capture-amount", + flags["capture-amount"], + PaymentIntentAmountSchema, + ), + }), + clientToken: flags["client-token"], + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.capturePaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/create-buyer-approval-url/index.tsx b/src/handlers/payment/intent/create-buyer-approval-url/index.tsx new file mode 100644 index 0000000000..2f0a45ca6c --- /dev/null +++ b/src/handlers/payment/intent/create-buyer-approval-url/index.tsx @@ -0,0 +1,43 @@ +import z from "zod"; +import { createHandler, flag } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { PaymentIntentScope, intentIdFlag, optionalClientTokenFlag } from "../input"; + +export const createCreateBuyerApprovalUrlHandler = (core: Core) => + createHandler({ + name: "create-buyer-approval-url", + description: "create an approval URL for delivery to the buyer UI", + flags: [ + ...PaymentIntentScope.flags, + intentIdFlag, + flag( + "parent-origin", + "the exact origin allowed to embed the buyer approval widget", + z + .string() + .url() + .refine((value) => { + try { + const url = new URL(value); + return ["https:", "http:"].includes(url.protocol) && value === url.origin; + } catch { + return false; + } + }, "must be an exact HTTP(S) origin"), + ), + optionalClientTokenFlag, + ], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentIntentId: flags["intent-id"], + parentOrigin: flags["parent-origin"], + ...(flags["client-token"] !== undefined && { clientToken: flags["client-token"] }), + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.createBuyerApprovalUrl(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/create/index.tsx b/src/handlers/payment/intent/create/index.tsx new file mode 100644 index 0000000000..21d67e7632 --- /dev/null +++ b/src/handlers/payment/intent/create/index.tsx @@ -0,0 +1,46 @@ +import z from "zod"; +import type { AppIO } from "../../../../io"; +import { createHandler, flag } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { + PaymentIntentScope, + optionalClientTokenFlag, + PaymentIntentSources, + CheckoutDetailsSchema, +} from "../input"; + +export const createCreatePaymentIntentHandler = (core: Core, io: AppIO) => + createHandler({ + name: "create", + description: "create a merchant payment intent", + flags: [ + ...PaymentIntentScope.flags, + flag("connector-id", "the payment connector ID", z.string().trim().min(1)), + flag("capture-strategy", "INSTANT, FUTURE or SETUP", z.enum(["INSTANT", "FUTURE", "SETUP"])), + flag( + "checkout-details", + "checkout JSON object, file://, or '-' for stdin", + z.string(), + { sensitive: true }, + ), + optionalClientTokenFlag, + ], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentConnectorId: flags["connector-id"], + captureStrategy: flags["capture-strategy"], + checkoutDetails: await new PaymentIntentSources(io).json( + "checkout-details", + flags["checkout-details"], + CheckoutDetailsSchema, + ), + ...(flags["client-token"] !== undefined && { clientToken: flags["client-token"] }), + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.createPaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/get/index.tsx b/src/handlers/payment/intent/get/index.tsx new file mode 100644 index 0000000000..00a28c836a --- /dev/null +++ b/src/handlers/payment/intent/get/index.tsx @@ -0,0 +1,38 @@ +import z from "zod"; +import { createHandler, flag } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import type { GetPaymentIntentInput } from "../../types"; + +export const createGetPaymentIntentHandler = (core: Core) => + createHandler({ + name: "get", + description: "get a payment intent by id", + flags: [ + flag("manager-id", "the parent payment manager ID", z.string().min(1)), + flag("intent-id", "the payment intent ID", z.string().min(1)), + flag( + "user-id", + "the application user ID associated with the intent", + z.string().trim().min(1), + ), + flag( + "agent-name", + "optional observability label, not an agent selector", + z.string().optional(), + ), + ], + handle: async (ctx, flags) => { + const request: GetPaymentIntentInput = { + managerId: flags["manager-id"], + userId: flags["user-id"], + paymentIntentId: flags["intent-id"], + ...(flags["agent-name"] ? { agentName: flags["agent-name"] } : {}), + }; + + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.getPaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/index.tsx b/src/handlers/payment/intent/index.tsx new file mode 100644 index 0000000000..016749529f --- /dev/null +++ b/src/handlers/payment/intent/index.tsx @@ -0,0 +1,23 @@ +import type { AppIO } from "../../../io"; +import { Router } from "../../../router"; +import type { Core } from "../../types"; +import { createGetPaymentIntentHandler } from "./get"; + +import { createCreatePaymentIntentHandler } from "./create"; +import { createCreateBuyerApprovalUrlHandler } from "./create-buyer-approval-url"; +import { createInitiatePaymentIntentHandler } from "./initiate"; +import { createAuthorizePaymentIntentHandler } from "./authorize"; +import { createCapturePaymentIntentHandler } from "./capture"; +import { createCancelPaymentIntentHandler } from "./cancel"; + +export function createPaymentIntentHandler(core: Core, io: AppIO): Router { + return new Router("intent", "create, inspect and manage payment intents") + .supportedTuiCommands() + .handler(createCreatePaymentIntentHandler(core, io)) + .handler(createGetPaymentIntentHandler(core)) + .handler(createCreateBuyerApprovalUrlHandler(core)) + .handler(createInitiatePaymentIntentHandler(core)) + .handler(createAuthorizePaymentIntentHandler(core, io)) + .handler(createCapturePaymentIntentHandler(core, io)) + .handler(createCancelPaymentIntentHandler(core)); +} diff --git a/src/handlers/payment/intent/initiate/index.tsx b/src/handlers/payment/intent/initiate/index.tsx new file mode 100644 index 0000000000..0808972db8 --- /dev/null +++ b/src/handlers/payment/intent/initiate/index.tsx @@ -0,0 +1,22 @@ +import { createHandler } from "../../../../router"; +import { JsonRendererKey } from "../../../../tui"; +import type { Core } from "../../../types"; +import { coreOptsFromCtx } from "../../../utils"; +import { PaymentIntentScope, intentIdFlag, optionalClientTokenFlag } from "../input"; + +export const createInitiatePaymentIntentHandler = (core: Core) => + createHandler({ + name: "initiate", + description: "initiate an approved intent using developer/backend credentials", + flags: [...PaymentIntentScope.flags, intentIdFlag, optionalClientTokenFlag], + handle: async (ctx, flags) => { + const request = { + ...PaymentIntentScope.fromFlags(flags), + paymentIntentId: flags["intent-id"], + ...(flags["client-token"] !== undefined && { clientToken: flags["client-token"] }), + }; + ctx + .require(JsonRendererKey) + .renderJson(await core.payment.initiatePaymentIntent(request, coreOptsFromCtx(ctx))); + }, + }); diff --git a/src/handlers/payment/intent/input.ts b/src/handlers/payment/intent/input.ts new file mode 100644 index 0000000000..7cac655799 --- /dev/null +++ b/src/handlers/payment/intent/input.ts @@ -0,0 +1,108 @@ +import z from "zod"; +import { InputValidationError } from "../../../errors"; +import { SourceResolver, type AppIO } from "../../../io"; +import { flag, type FlagsOf } from "../../../router"; +import { parseJsonObjectFlag } from "../../utils"; + +const nonempty = z.string().trim().min(1); +export class PaymentIntentScope { + static readonly flags = [ + flag("manager-id", "the parent payment manager ID", nonempty), + flag( + "user-id", + "the application buyer ID (required independently of Runtime identity)", + nonempty, + ), + flag("agent-name", "optional agent observability label", nonempty.optional()), + ] as const; + static fromFlags(flags: FlagsOf) { + return { + managerId: flags["manager-id"], + userId: flags["user-id"], + ...(flags["agent-name"] !== undefined && { agentName: flags["agent-name"] }), + }; + } +} +export const intentIdFlag = flag("intent-id", "the payment intent ID", nonempty); +// The service's clientToken shape; checked locally so a bad token fails before any request. +export const ClientTokenSchema = z + .string() + .regex(/^[A-Za-z0-9-]{33,256}$/, "must be 33-256 letters, digits or hyphens"); +export const optionalClientTokenFlag = flag( + "client-token", + "idempotency token (33-256 letters, digits or hyphens); reuse for the same operation", + ClientTokenSchema.optional(), + { sensitive: true }, +); +export const PaymentIntentAmountSchema = z.strictObject({ + value: z + .string() + .max(40) + .regex(/^-?(0|[1-9][0-9]{0,17})(\.[0-9]{1,18})?$/), + currency: z.enum(["USD", "EUR"]), +}); +export const CheckoutDetailsSchema = z.strictObject({ + totalAmount: PaymentIntentAmountSchema, + merchant: z.strictObject({ + name: z.string().min(1).max(256), + website: z.string().min(1).max(2048).optional(), + }), + lineItems: z + .array( + z.strictObject({ + sku: z.string().min(1).max(256), + quantity: z.number().int().positive(), + amount: PaymentIntentAmountSchema, + }), + ) + .max(100) + .optional(), + amountBreakdown: z + .strictObject({ + shipping: PaymentIntentAmountSchema.optional(), + tax: PaymentIntentAmountSchema.optional(), + discount: PaymentIntentAmountSchema.optional(), + }) + .optional(), + amountMode: z.enum(["EXACT", "UPTO"]).optional(), + returnUrl: z.string().min(1).max(2048).optional(), + referenceId: z.string().min(1).max(127).optional(), +}); + +// SourceResolver owns file/stdin handling; discard parse/source causes which may contain customer data. +export class PaymentIntentSources { + private readonly resolver: SourceResolver; + constructor(io: Pick) { + this.resolver = new SourceResolver({ stdin: io.stdin }); + } + async json(name: string, source: string, schema: z.ZodType): Promise { + try { + const text = await this.resolver.resolveText(name, source); + const parsed = parseJsonObjectFlag(name, text); + const result = schema.safeParse(parsed); + if (result.success) return result.data; + } catch { + /* Sensitive source/JSON details must not enter error causes or logs. */ + } + throw new InputValidationError( + `Invalid --${name}: supply a valid JSON object with the documented fields`, + ); + } + async callback(source: string | undefined): Promise { + if (source === undefined) return undefined; + if (source !== "-" && !source.startsWith("file://")) { + throw new InputValidationError( + "--partner-callback-result must come from file:// or '-' for stdin", + ); + } + try { + const value = await this.resolver.resolveText("partner-callback-result", source); + if (value.trim()) return value; + } catch { + /* Do not include file contents or parsing causes. */ + } + throw new InputValidationError( + "Invalid --partner-callback-result: supply a nonempty UTF-8 file or stdin value", + ); + } +} diff --git a/src/handlers/payment/intent/lifecycle.test.tsx b/src/handlers/payment/intent/lifecycle.test.tsx new file mode 100644 index 0000000000..862ea93581 --- /dev/null +++ b/src/handlers/payment/intent/lifecycle.test.tsx @@ -0,0 +1,397 @@ +import { ServiceException } from "@smithy/core/client"; +import { afterEach, expect, mock, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import { CoreClient } from "../../../core"; +import type { Logger } from "../../../logging"; +import { createRootHandler } from "../../index"; +import { createSilentLogger, TestGlobalConfigAccessor, testIO } from "../../../testing"; +import { CheckoutDetailsSchema, PaymentIntentAmountSchema } from "./input"; + +const managerId = "merchant-manager"; +const managerArn = + "arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/merchant-manager"; +const scope = ["--manager-id", managerId, "--user-id", "buyer-a"]; +const checkout = { + totalAmount: { value: "12.0100", currency: "EUR" }, + merchant: { name: "Shop" }, + lineItems: [{ sku: "item", quantity: 2, amount: { value: "5.00", currency: "EUR" } }], + amountBreakdown: { shipping: { value: "2.0100", currency: "EUR" } }, + referenceId: "order-a", +}; +const directories: string[] = []; +afterEach(async () => { + await Promise.all( + directories.splice(0).map((path) => rm(path, { recursive: true, force: true })), + ); +}); +async function file(value: string | Uint8Array) { + const dir = await mkdtemp(join(tmpdir(), "intent-source-")); + directories.push(dir); + const path = join(dir, "input"); + await writeFile(path, value); + return `file://${path}`; +} +function setup(response: unknown = {}, authorizerType = "AWS_IAM", stdin?: string) { + const logs: unknown[] = []; + const logger: Logger = { + ...createSilentLogger(), + child(bindings) { + logs.push(bindings); + return logger; + }, + }; + const control = mock(async () => ({ paymentManagerArn: managerArn, authorizerType })); + const data = mock(async (_command: { input: unknown }) => response); + const unexpectedClient = () => { + throw new Error("Unexpected nonpayment AWS client"); + }; + const core = new CoreClient({ + createIamClient: unexpectedClient, + createLogsClient: unexpectedClient, + createXrayClient: unexpectedClient, + createApplicationSignalsClient: unexpectedClient, + createControlClient: () => ({ send: control }) as never, + createDataClient: () => ({ send: data }) as never, + logger, + }); + const output = testIO(); + if (stdin !== undefined) (output.io.stdin as unknown as PassThrough).end(stdin); + const root = createRootHandler(core, { + io: output.io, + logger, + globalConfigAccessor: new TestGlobalConfigAccessor(), + }); + return { + core, + logs, + control, + data, + output, + run: (args: string[]) => + root.route([ + "node", + "agentcore", + "payment", + "intent", + ...args, + "--region", + "us-west-2", + "--json", + ]), + }; +} +const leaves = [ + { + leaf: "create", + command: "CreatePaymentIntentCommand", + args: [ + "--connector-id", + "merchant", + "--capture-strategy", + "FUTURE", + "--checkout-details", + JSON.stringify(checkout), + ], + fields: { + paymentConnectorId: "merchant", + captureStrategy: "FUTURE", + checkoutDetails: checkout, + }, + }, + { + leaf: "create-buyer-approval-url", + command: "CreateBuyerApprovalUrlCommand", + args: ["--intent-id", "intent", "--parent-origin", "https://shop.example"], + fields: { paymentIntentId: "intent", parentOrigin: "https://shop.example" }, + }, + { + leaf: "initiate", + command: "InitiatePaymentIntentCommand", + args: ["--intent-id", "intent"], + fields: { paymentIntentId: "intent" }, + }, + { + leaf: "authorize", + command: "AuthorizePaymentIntentCommand", + args: ["--intent-id", "intent"], + fields: { paymentIntentId: "intent", partnerCallbackResult: undefined }, + }, + { + leaf: "capture", + command: "CapturePaymentIntentCommand", + args: ["--intent-id", "intent", "--capture-amount", '{"value":"1.0100","currency":"EUR"}'], + fields: { paymentIntentId: "intent", captureAmount: { value: "1.0100", currency: "EUR" } }, + }, + { + leaf: "cancel", + command: "CancelPaymentIntentCommand", + args: ["--intent-id", "intent"], + fields: { paymentIntentId: "intent" }, + }, +]; +test.each(leaves)( + "%s routes developer credentials/buyer/token and preserves nested output", + async ({ leaf, command, args, fields }) => { + const response = { + paymentIntent: { status: "INITIATED", version: 2, checkoutDetails: checkout }, + capture: { status: "CAPTURE_PENDING", captureAmount: { value: "1.0100", currency: "EUR" } }, + partnerIntentData: { nested: { clientSecret: "sensitive-result" } }, + }; + const app = setup(response); + const token = "9467ced1-60fd-4e48-8494-40bfa473d648"; + await app.run([leaf, ...scope, ...args, "--agent-name", "agent", "--client-token", token]); + expect(app.data.mock.calls[0]![0].constructor.name).toBe(command); + expect(app.data.mock.calls[0]![0].input).toEqual({ + paymentManagerArn: managerArn, + userId: "buyer-a", + agentName: "agent", + clientToken: token, + ...fields, + }); + expect(JSON.parse(app.output.stdout())).toEqual(response); + }, +); +test.each(leaves)("%s requires explicit buyer before AWS", async ({ leaf, args }) => { + for (const user of [[], ["--user-id", " "]]) { + const app = setup(); + await expect( + app.run([ + leaf, + "--manager-id", + managerId, + ...args, + "--client-token", + "9467ced1-60fd-4e48-8494-40bfa473d648", + ...user, + ]), + ).rejects.toThrow(); + expect(app.control).not.toHaveBeenCalled(); + expect(app.data).not.toHaveBeenCalled(); + } +}); +test.each(leaves)("%s rejects a malformed client token before AWS", async ({ leaf, args }) => { + for (const token of ["too-short", `${"a".repeat(32)} `, "a".repeat(257)]) { + const app = setup(); + await expect(app.run([leaf, ...scope, ...args, "--client-token", token])).rejects.toThrow( + "33-256 letters, digits or hyphens", + ); + expect(app.control).not.toHaveBeenCalled(); + } +}); +test.each(leaves)("%s retains IAM-only manager boundary", async ({ leaf, args }) => { + const app = setup({}, "CUSTOM_JWT"); + await expect( + app.run([leaf, ...scope, ...args, "--client-token", "9467ced1-60fd-4e48-8494-40bfa473d648"]), + ).rejects.toThrow("CUSTOM_JWT"); + expect(app.data).not.toHaveBeenCalled(); +}); +test("capture requires caller token before AWS, omits amount for remainder, and replays exact token", async () => { + for (const token of [[], ["--client-token", " "], ["--client-token", "too-short"]]) { + const app = setup(); + await expect( + app.run(["capture", ...scope, "--intent-id", "intent", ...token]), + ).rejects.toThrow(); + expect(app.control).not.toHaveBeenCalled(); + } + const app = setup(); + for (let i = 0; i < 2; i++) + await app.run([ + "capture", + ...scope, + "--intent-id", + "intent", + "--client-token", + "9467ced1-60fd-4e48-8494-40bfa473d648", + ]); + expect(app.data.mock.calls[0]![0].input).toEqual(app.data.mock.calls[1]![0].input); + expect(app.data.mock.calls[0]![0].input).not.toHaveProperty("captureAmount"); + await expect( + app.core.payment.capturePaymentIntent( + { managerId, paymentIntentId: "intent", userId: "buyer-a", clientToken: " " }, + { region: "us-west-2" }, + ), + ).rejects.toThrow("caller-owned"); + expect(app.control).toHaveBeenCalledTimes(2); +}); +test.each(["INSTANT", "FUTURE", "SETUP"])( + "create retains %s and structured checkout from file", + async (strategy) => { + const app = setup(); + await app.run([ + "create", + ...scope, + "--connector-id", + "merchant", + "--capture-strategy", + strategy, + "--checkout-details", + await file(JSON.stringify({ ...checkout, amountMode: "UPTO" })), + ]); + expect(app.data.mock.calls[0]![0].input).toMatchObject({ + captureStrategy: strategy, + checkoutDetails: { amountMode: "UPTO", totalAmount: checkout.totalAmount }, + }); + }, +); +test("checkout and partner callback accept stdin without opening or redeeming URLs", async () => { + const create = setup({}, "AWS_IAM", JSON.stringify(checkout)); + await create.run([ + "create", + ...scope, + "--connector-id", + "merchant", + "--capture-strategy", + "FUTURE", + "--checkout-details", + "-", + ]); + const callback = '{"token":"sensitive-callback"}\n'; + const authorize = setup({}, "AWS_IAM", callback); + await authorize.run([ + "authorize", + ...scope, + "--intent-id", + "intent", + "--partner-callback-result", + "-", + ]); + expect(authorize.data.mock.calls[0]![0].input).toMatchObject({ partnerCallbackResult: callback }); + const approval = setup({ + buyerApprovalUrl: "https://opaque.example/secret", + paymentIntentVersion: 3, + }); + await approval.run([ + "create-buyer-approval-url", + ...scope, + "--intent-id", + "intent", + "--parent-origin", + "https://shop.example", + ]); + expect(JSON.parse(approval.output.stdout()).buyerApprovalUrl).toBe( + "https://opaque.example/secret", + ); + expect(approval.data).toHaveBeenCalledTimes(1); +}); +test("sensitive input errors omit raw material, causes and AWS effects", async () => { + for (const input of [ + '{"secret-value":', + '{"totalAmount":{"value":1.01,"currency":"EUR"},"merchant":{"name":"secret-value"}}', + "[]", + "null", + await file(new Uint8Array([255])), + ]) { + const app = setup(); + const error = await app + .run([ + "create", + ...scope, + "--connector-id", + "merchant", + "--capture-strategy", + "FUTURE", + "--checkout-details", + input, + ]) + .catch((error: Error) => error); + expect(String(error)).not.toContain("secret-value"); + expect(error).toBeInstanceOf(Error); + if (!(error instanceof Error)) throw new Error("Expected rejected command"); + expect(error.cause).toBeUndefined(); + expect(app.control).not.toHaveBeenCalled(); + } + const app = setup(); + const error = await app + .run([ + "authorize", + ...scope, + "--intent-id", + "intent", + "--partner-callback-result", + "secret-value", + ]) + .catch((error: Error) => error); + expect(String(error)).not.toContain("secret-value"); + expect(error).toBeInstanceOf(Error); + if (!(error instanceof Error)) throw new Error("Expected rejected command"); + expect(error.cause).toBeUndefined(); + expect(app.control).not.toHaveBeenCalled(); +}); +test("decimal schema matches generated signed precision while leaving arithmetic to the service", () => { + for (const value of ["0", "-1.00", "123456789012345678.123456789012345678"]) + expect(PaymentIntentAmountSchema.safeParse({ value, currency: "EUR" }).success).toBe(true); + for (const value of [1.1, "1e3", "01", "1234567890123456789", "0.1234567890123456789"]) + expect(PaymentIntentAmountSchema.safeParse({ value, currency: "USD" }).success).toBe(false); + expect( + CheckoutDetailsSchema.safeParse({ + ...checkout, + totalAmount: { value: "-1.00", currency: "EUR" }, + returnUrl: "application-defined-return", + merchant: { name: "Shop", website: "merchant.example" }, + }).success, + ).toBe(true); +}); + +test.each([ + ...leaves, + { leaf: "get", command: "GetPaymentIntentCommand", args: ["--intent-id", "intent"], fields: {} }, +])( + "%s service errors retain code/request ID without partner secrets or original cause", + async ({ leaf, args }) => { + const app = setup(); + app.data.mockRejectedValue( + new ServiceException({ + name: "ValidationException", + $fault: "client", + $metadata: { httpStatusCode: 400, requestId: "request-123" }, + message: "sensitive-callback-secret was rejected at https://secret.example", + }), + ); + const error = await app + .run( + [leaf, ...scope, ...args, "--client-token", "9467ced1-60fd-4e48-8494-40bfa473d648"].filter( + (value, index, values) => leaf !== "get" || index < values.length - 2, + ), + ) + .catch((error: Error) => error); + expect(String(error)).toContain("ValidationException"); + expect(String(error)).toContain("request-123"); + expect(JSON.stringify(error)).not.toContain("sensitive-callback-secret"); + expect(error).toBeInstanceOf(Error); + if (!(error instanceof Error)) throw new Error("Expected rejected command"); + expect(error.cause).toBeUndefined(); + }, +); + +test("debug logging redacts checkout, callback sources and tokens", async () => { + const checkoutApp = setup(); + await checkoutApp.run([ + "create", + ...scope, + "--connector-id", + "merchant", + "--capture-strategy", + "FUTURE", + "--checkout-details", + JSON.stringify({ ...checkout, referenceId: "sensitive-checkout-reference" }), + "--client-token", + "sensitive-token-0000000000000000000000", + ]); + const loggedCheckout = JSON.stringify(checkoutApp.logs); + expect(loggedCheckout).toContain("[REDACTED]"); + expect(loggedCheckout).not.toContain("sensitive-checkout-reference"); + expect(loggedCheckout).not.toContain("sensitive-token"); + const callbackApp = setup({}, "AWS_IAM", "sensitive-callback-body"); + await callbackApp.run([ + "authorize", + ...scope, + "--intent-id", + "intent", + "--partner-callback-result", + "-", + ]); + expect(JSON.stringify(callbackApp.logs)).not.toContain("sensitive-callback-body"); +}); diff --git a/src/handlers/payment/payment.read.test.tsx b/src/handlers/payment/payment.read.test.tsx index 7416681296..72d3c81fcb 100644 --- a/src/handlers/payment/payment.read.test.tsx +++ b/src/handlers/payment/payment.read.test.tsx @@ -63,6 +63,15 @@ test("registers the payment command tree without TUI leaves", () => { connector: ["get", "list", "rotate-credentials"], session: ["get", "list"], instrument: ["get", "list", "balance"], + intent: [ + "create", + "get", + "create-buyer-approval-url", + "initiate", + "authorize", + "capture", + "cancel", + ], }); for (const resource of payment.commands) { for (const command of resource.commands) expect(isTuiCommandSupported(command)).toBe(false); @@ -261,3 +270,74 @@ test.each([ expect(send).toHaveBeenCalledTimes(1); expect(io.stdout()).toBe(""); }); + +test("intent get preserves the complete nested result and buyer identity", async () => { + const response = { + paymentIntent: { + paymentIntentId: "intent-test", + status: "INITIATED", + version: 3, + buyerApprovalStatus: "BUYER_APPROVAL_CONFIRMED", + checkoutDetails: { totalAmount: { value: "10.01", currency: "EUR" } }, + captures: [{ status: "CAPTURE_PENDING", captureAmount: { value: "5.01", currency: "EUR" } }], + }, + }; + const send = mock(async (_command: { input: unknown }) => response); + const { run, io } = setup("intent", { createDataClient: () => ({ send }) as never }); + await run([ + "intent", + "get", + ...scope, + "--intent-id", + "intent-test", + "--agent-name", + "shopping-agent", + "--json", + ]); + expect(send.mock.calls[0]![0].input).toEqual({ + paymentManagerArn: MANAGER_ARN, + paymentIntentId: "intent-test", + userId: "agentcore-cli-e2e", + agentName: "shopping-agent", + }); + expect(JSON.parse(io.stdout())).toEqual(response); +}); + +test("intent get requires buyer identity before reaching AWS", async () => { + const send = mock(async () => ({})); + const { run } = setup("intent", { createControlClient: () => ({ send }) as never }); + await expect( + run(["intent", "get", "--manager-id", MANAGER_ID, "--intent-id", "intent-test", "--json"]), + ).rejects.toThrow("user-id"); + expect(send).not.toHaveBeenCalled(); +}); + +test("intent get rejects blank buyer identity before reaching AWS", async () => { + const send = mock(async () => ({})); + const { run } = setup("intent", { createControlClient: () => ({ send }) as never }); + await expect( + run([ + "intent", + "get", + "--manager-id", + MANAGER_ID, + "--intent-id", + "intent-test", + "--user-id", + " ", + "--json", + ]), + ).rejects.toThrow(); + expect(send).not.toHaveBeenCalled(); +}); + +test("intent get leaves agent telemetry unset when omitted", async () => { + const send = mock(async (_command: { input: unknown }) => ({ paymentIntent: {} })); + const { run } = setup("intent", { createDataClient: () => ({ send }) as never }); + await run(["intent", "get", ...scope, "--intent-id", "intent-test", "--json"]); + expect(send.mock.calls[0]![0].input).toEqual({ + paymentManagerArn: MANAGER_ARN, + paymentIntentId: "intent-test", + userId: "agentcore-cli-e2e", + }); +}); diff --git a/src/handlers/payment/types.tsx b/src/handlers/payment/types.tsx index f15275d28b..ca07587443 100644 --- a/src/handlers/payment/types.tsx +++ b/src/handlers/payment/types.tsx @@ -11,6 +11,20 @@ import type { GetPaymentInstrumentResponse, GetPaymentInstrumentBalanceRequest, GetPaymentInstrumentBalanceResponse, + CreatePaymentIntentRequest, + CreatePaymentIntentResponse, + CreateBuyerApprovalUrlRequest, + CreateBuyerApprovalUrlResponse, + InitiatePaymentIntentRequest, + InitiatePaymentIntentResponse, + AuthorizePaymentIntentRequest, + AuthorizePaymentIntentResponse, + CapturePaymentIntentRequest, + CapturePaymentIntentResponse, + CancelPaymentIntentRequest, + CancelPaymentIntentResponse, + GetPaymentIntentRequest, + GetPaymentIntentResponse, GetPaymentSessionRequest, GetPaymentSessionResponse, ListPaymentInstrumentsRequest, @@ -22,6 +36,17 @@ import type { CoreOptions } from "../../core/types"; type WithPaymentManagerId = Omit & { managerId: string }; +type IntentInput = Omit, "userId"> & { userId: string }; +export type GetPaymentIntentInput = IntentInput; +export type CreatePaymentIntentInput = IntentInput; +export type CreateBuyerApprovalUrlInput = IntentInput; +export type InitiatePaymentIntentInput = IntentInput; +export type AuthorizePaymentIntentInput = IntentInput; +export type CapturePaymentIntentInput = IntentInput & { + clientToken: string; +}; +export type CancelPaymentIntentInput = IntentInput; + export type GetPaymentSessionInput = WithPaymentManagerId; export type ListPaymentSessionsInput = WithPaymentManagerId; export type GetPaymentInstrumentInput = WithPaymentManagerId; @@ -52,6 +77,36 @@ export interface CorePaymentClient { options: CoreOptions, ): Promise; + createPaymentIntent( + request: CreatePaymentIntentInput, + options: CoreOptions, + ): Promise; + createBuyerApprovalUrl( + request: CreateBuyerApprovalUrlInput, + options: CoreOptions, + ): Promise; + initiatePaymentIntent( + request: InitiatePaymentIntentInput, + options: CoreOptions, + ): Promise; + authorizePaymentIntent( + request: AuthorizePaymentIntentInput, + options: CoreOptions, + ): Promise; + capturePaymentIntent( + request: CapturePaymentIntentInput, + options: CoreOptions, + ): Promise; + cancelPaymentIntent( + request: CancelPaymentIntentInput, + options: CoreOptions, + ): Promise; + + getPaymentIntent( + request: GetPaymentIntentInput, + options: CoreOptions, + ): Promise; + // Core resolves the selected manager ID to the ARN required by the data plane. getPaymentSession( request: GetPaymentSessionInput, diff --git a/src/handlers/project/add/credentials/payment/index.ts b/src/handlers/project/add/credentials/payment/index.ts index 7c5fafbc88..f85618f176 100644 --- a/src/handlers/project/add/credentials/payment/index.ts +++ b/src/handlers/project/add/credentials/payment/index.ts @@ -1,7 +1,14 @@ import z from "zod"; import type { AppIO } from "../../../../../io"; -import { PaymentProviderSchema, type PaymentProvider } from "../../../../../projectSchemas/payment"; -import { createHandler, flag } from "../../../../../router"; +import { + LegacyPaymentProviderSchema, + type LegacyPaymentProvider, +} from "../../../../../projectSchemas/payment"; +import { CommandKey, createHandler, flag, Router, type Middleware } from "../../../../../router"; +import { InputValidationError } from "../../../../../errors"; +import { CredentialNameSchema } from "../../../../../projectSchemas/credential"; +import { attributeName } from "../../../../../router/flags"; +import { createMerchantPaymentHandlers } from "./merchant"; import type { AddProjectResourceConfig } from "../../types"; import { addCredentialToProject, type AddCredentialInput } from "../shared"; import { @@ -12,7 +19,7 @@ import { export type PaymentCredentialInput = { name: string; - provider: PaymentProvider; + provider: LegacyPaymentProvider; flags: PaymentCredentialInputFlags; io?: Pick; }; @@ -30,15 +37,43 @@ export async function toAddPaymentCredentialInput( }; } -export const createAddPaymentCredentialHandler = (config: AddProjectResourceConfig) => +const createLegacyPaymentCredentialHandler = (config: AddProjectResourceConfig) => createHandler({ name: "payment", description: "add a payment credential provider to the current project", flags: [ flag("name", "the name of the credential provider", z.string().min(1)), - flag("provider", "the payment provider: CoinbaseCDP or StripePrivy", PaymentProviderSchema), + flag( + "provider", + "the payment provider: CoinbaseCDP or StripePrivy", + LegacyPaymentProviderSchema, + ), ...paymentCredentialInputFlags, ], + middlewares: [ + ((handler) => ({ + name: () => handler.name(), + description: () => handler.description(), + flags: () => handler.flags(), + arguments: () => handler.arguments(), + children: () => handler.children(), + doesSupportTui: () => handler.doesSupportTui(), + handle: async (ctx, flags, args) => { + const command = ctx.require(CommandKey); + if ( + handler + .flags() + .every((item) => command.getOptionValueSource(attributeName(item.name)) !== "cli") + ) { + config.io.stderr.write(command.helpInformation()); + throw new InputValidationError( + "Choose a payment provider subcommand, or supply legacy --name and --provider", + ); + } + await handler.handle(ctx, flags, args); + }, + })) satisfies Middleware, + ], handle: async (ctx, flags) => { await addCredentialToProject( ctx, @@ -52,3 +87,39 @@ export const createAddPaymentCredentialHandler = (config: AddProjectResourceConf ); }, }); + +export function createAddPaymentCredentialHandler(config: AddProjectResourceConfig): Router { + const router = new Router("payment", "add a payment credential provider to the current project") + .defaultLeaf(createLegacyPaymentCredentialHandler(config)) + .supportedTuiCommands(); + for (const handler of createMerchantPaymentHandlers(config)) router.handler(handler); + for (const [name, provider, fields] of [ + ["coinbase-cdp", "CoinbaseCDP", ["api-key-id", "api-key-secret", "wallet-secret"]], + [ + "stripe-privy", + "StripePrivy", + ["app-id", "app-secret", "authorization-private-key", "authorization-id"], + ], + ] as const) { + router.handler( + createHandler({ + name, + description: `add ${provider} credentials to the current project`, + flags: [ + flag("name", "the name of the credential provider", CredentialNameSchema), + ...paymentCredentialInputFlags.filter((item) => + (fields as readonly string[]).includes(item.name), + ), + ], + handle: async (ctx, flags) => { + await addCredentialToProject( + ctx, + config, + await toAddPaymentCredentialInput({ name: flags.name, provider, flags, io: config.io }), + ); + }, + }), + ); + } + return router; +} diff --git a/src/handlers/project/add/credentials/payment/input.ts b/src/handlers/project/add/credentials/payment/input.ts index e40aea48fd..8e498fab62 100644 --- a/src/handlers/project/add/credentials/payment/input.ts +++ b/src/handlers/project/add/credentials/payment/input.ts @@ -1,7 +1,7 @@ import z from "zod"; import { InputValidationError } from "../../../../../errors"; import { type AppIO, SourceResolver } from "../../../../../io"; -import type { PaymentProvider } from "../../../../../projectSchemas/payment"; +import type { LegacyPaymentProvider } from "../../../../../projectSchemas/payment"; import { flag } from "../../../../../router"; import type { EnvLocalEntry } from "../../../types"; import { credentialEnvVarName } from "../shared"; @@ -76,7 +76,7 @@ function normalizedIdentifier(name: string, value: string | undefined): string | export async function resolvePaymentCredentialEnvEntries(input: { name: string; - provider: PaymentProvider; + provider: LegacyPaymentProvider; flags: PaymentCredentialInputFlags; io?: Pick; }): Promise { @@ -92,6 +92,29 @@ export async function resolvePaymentCredentialEnvEntries(input: { ); } + const secretFlags = [ + "api-key-secret", + "wallet-secret", + "app-secret", + "authorization-private-key", + ] as const; + const stdinFlags = secretFlags.filter((flagName) => flags[flagName] === "-"); + if (stdinFlags.length > 1) { + throw new InputValidationError("Only one payment credential secret may read from stdin"); + } + for (const flagName of secretFlags) { + const source = flags[flagName]; + if ( + source !== undefined && + source !== "-" && + !(source.startsWith("file://") && source.length > 7) + ) { + throw new InputValidationError( + `--${flagName} must come from stdin ('-') or a file ('file://'); inline secret values are not accepted`, + ); + } + } + const resolver = new SourceResolver({ stdin: io?.stdin }); if (provider === "StripePrivy") { const appId = normalizedIdentifier("appId", flags["app-id"]); diff --git a/src/handlers/project/add/credentials/payment/merchant.test.ts b/src/handlers/project/add/credentials/payment/merchant.test.ts new file mode 100644 index 0000000000..eff91b3c2c --- /dev/null +++ b/src/handlers/project/add/credentials/payment/merchant.test.ts @@ -0,0 +1,316 @@ +import { afterEach, expect, test } from "bun:test"; +import { join } from "node:path"; +import { compile, ValueContext } from "../../../../../router"; +import { createRootHandler } from "../../../../index"; +import { + createSilentLogger, + TestCoreClient, + TestGlobalConfigAccessor, + testIO, +} from "../../../../../testing"; +import { readEnvFile } from "../../../../../io/envFile"; +import { createPaymentProjectTestHarness } from "../../payment-test-support"; + +const { cleanup, inProject, projectSpec } = createPaymentProjectTestHarness("typed-payment"); +afterEach(cleanup); +function command(args: string[], stdin?: string) { + const io = testIO({ stdin }); + const root = createRootHandler(new TestCoreClient(), { + io: io.io, + logger: createSilentLogger(), + globalConfigAccessor: new TestGlobalConfigAccessor(), + }); + return { + io, + root, + run: () => root.route(["node", "agentcore", "add", "credentials", "payment", ...args]), + }; +} +const providers = [ + { + leaf: "stripe", + provider: "Stripe", + secret: "restricted-key", + reference: "restricted-key-secret-reference", + suffix: "RESTRICTED_KEY", + value: "rk_test_example", + placeholders: ["RESTRICTED_KEY"], + }, + { + leaf: "paypal", + provider: "PayPal", + secret: "client-secret", + reference: "client-secret-reference", + suffix: "CLIENT_SECRET", + value: "paypal-test-secret", + placeholders: ["CLIENT_ID", "ENVIRONMENT", "CLIENT_SECRET"], + }, + { + leaf: "amazon-pay", + provider: "AmazonPay", + secret: "authorization-token", + reference: "authorization-token-secret-reference", + suffix: "AUTHORIZATION_TOKEN", + value: "amazon-test-token", + placeholders: [ + "MERCHANT_ID", + "STORE_ID", + "ENVIRONMENT", + "AMAZON_PAY_REGION", + "AUTHORIZATION_TOKEN", + ], + }, +] as const; +test.each([...providers])( + "$leaf name-only setup writes placeholders without defaults", + async ({ leaf, provider, placeholders }) => { + const project = await inProject(); + const { io, run } = command([leaf, "--name", "merchant"]); + await run(); + expect((await projectSpec(project)).credentials).toEqual([ + { name: "merchant", authorizerType: "PaymentCredentialProvider", provider }, + ]); + const env = await readEnvFile(join(project, "agentcore", ".env.local")); + for (const suffix of placeholders) { + expect(env[`AGENTCORE_CREDENTIAL_MERCHANT_${suffix}`]).toBe(""); + expect(io.stderr()).toContain(`Set AGENTCORE_CREDENTIAL_MERCHANT_${suffix}`); + } + }, +); +test.each([...providers])( + "$leaf maps provider reference to generic persisted secretRef", + async ({ leaf, reference, suffix, placeholders }) => { + const project = await inProject(); + const secretRef = { secretId: "merchant-secret", jsonKey: "key" }; + await command([leaf, "--name", "merchant", `--${reference}`, JSON.stringify(secretRef)]).run(); + expect((await projectSpec(project)).credentials[0].secretRef).toEqual(secretRef); + const env = await readEnvFile(join(project, "agentcore", ".env.local")); + expect(env[`AGENTCORE_CREDENTIAL_MERCHANT_${suffix}`]).toBeUndefined(); + for (const field of placeholders.filter((field) => field !== suffix)) + expect(env[`AGENTCORE_CREDENTIAL_MERCHANT_${field}`]).toBe(""); + }, +); +test.each([...providers])( + "$leaf reads one stdin source without storing secret in project", + async ({ leaf, secret, suffix, value }) => { + const project = await inProject(); + await command([leaf, "--name", "merchant", `--${secret}`, "-"], `${value}\n`).run(); + expect( + (await readEnvFile(join(project, "agentcore", ".env.local")))[ + `AGENTCORE_CREDENTIAL_MERCHANT_${suffix}` + ], + ).toBe(value); + expect(JSON.stringify(await projectSpec(project))).not.toContain(value); + }, +); +test.each(["NA", "EU"])("Amazon Pay accepts %s merchant region", async (region) => { + const project = await inProject(); + await command([ + "amazon-pay", + "--name", + "merchant", + "--merchant-id", + "merchant-id", + "--store-id", + "store-id", + "--environment", + "LIVE", + "--amazon-pay-region", + region, + ]).run(); + expect(await readEnvFile(join(project, "agentcore", ".env.local"))).toMatchObject({ + AGENTCORE_CREDENTIAL_MERCHANT_AMAZON_PAY_REGION: region, + AGENTCORE_CREDENTIAL_MERCHANT_ENVIRONMENT: "LIVE", + }); +}); +test("Amazon Pay rejects JP before reading secrets or writing project files", async () => { + const project = await inProject(); + const before = JSON.stringify(await projectSpec(project)); + const envPath = join(project, "agentcore", ".env.local"); + const beforeEnv = await Bun.file(envPath).text(); + const { io, run } = command( + [ + "amazon-pay", + "--name", + "merchant", + "--merchant-id", + "merchant-id", + "--store-id", + "store-id", + "--environment", + "SANDBOX", + "--amazon-pay-region", + "JP", + "--authorization-token", + "-", + ], + "example-token\n", + ); + await expect(run()).rejects.toThrow("amazon-pay-region"); + expect(io.io.stdin.readableFlowing).toBeNull(); + expect(JSON.stringify(await projectSpec(project))).toBe(before); + expect(await Bun.file(envPath).text()).toBe(beforeEnv); +}, 1000); +test.each([ + ["coinbase-cdp", "CoinbaseCDP"], + ["stripe-privy", "StripePrivy"], +])("%s typed legacy leaf retains scaffold behavior", async (leaf, provider) => { + const project = await inProject(); + await command([leaf!, "--name", "merchant"]).run(); + expect((await projectSpec(project)).credentials[0].provider).toBe(provider); +}); +const invalid = [ + ["stripe", "--name", "merchant", "--provider", "CoinbaseCDP"], + ["--provider", "CoinbaseCDP", "stripe", "--name", "merchant"], + ["--name", "parent", "stripe", "--name", "merchant"], + ["stripe", "--name", "merchant", "--client-secret", "-"], + ["paypal", "--name", "merchant", "--client-secret", "-", "--environment", "invalid"], + ["amazon-pay", "--name", "merchant", "--authorization-token", "-", "--amazon-pay-region", "US"], + [ + "stripe", + "--name", + "merchant", + "--restricted-key", + "-", + "--restricted-key-secret-reference", + '{"secretId":"secret","jsonKey":"key"}', + ], + ["coinbase-cdp", "--name", "merchant", "--api-key-secret", "-", "--wallet-secret", "-"], + [ + "--name", + "merchant", + "--provider", + "CoinbaseCDP", + "--api-key-secret", + "-", + "--wallet-secret", + "-", + ], + ["coinbase-cdp", "--name", "merchant", "--api-key-secret", "-", "--wallet-secret", "literal"], + ["stripe", "--name", "merchant", "--restricted-key", "literal"], + [ + "stripe", + "--name", + "merchant", + "--restricted-key-secret-reference", + '{"secretId":" ","jsonKey":"key"}', + ], + ["--name", "merchant", "--provider", "Stripe"], + ["unknown-child", "--restricted-key", "-"], + ["--", "stripe", "--restricted-key", "-"], +]; +test.each(invalid.map((args) => ({ args })))( + "rejects invalid root arguments before reading stdin or writing project: $args", + async ({ args }) => { + const project = await inProject(); + const before = JSON.stringify(await projectSpec(project)); + // An idle stream would hang if validation consumed it. Inspect its readable state too. + const { io, run } = command(args); + await expect(run()).rejects.toThrow(); + expect(io.io.stdin.readableFlowing).toBeNull(); + expect(JSON.stringify(await projectSpec(project))).toBe(before); + expect(await Bun.file(join(project, "agentcore", ".env.local")).text()).not.toContain( + "AGENTCORE_CREDENTIAL_MERCHANT", + ); + }, + 1000, +); +test.each([...providers])( + "$leaf malformed reference does not leak parser input or cause", + async ({ leaf, reference }) => { + await inProject(); + const { io, run } = command([ + leaf, + "--name", + "merchant", + `--${reference}`, + "SENSITIVE_REFERENCE_SENTINEL", + ]); + const error = await run().catch((error) => error); + expect(error.message).toContain("expected JSON"); + expect(error.cause).toBeUndefined(); + expect(`${error.stack}${io.stderr()}${io.stdout()}`).not.toContain( + "SENSITIVE_REFERENCE_SENTINEL", + ); + }, +); +test.each([...providers])("$leaf help excludes compatibility-only options", async ({ leaf }) => { + const { io, root } = command([]); + const compiled = compile(root, ValueContext.EmptyContext()); + function capture(cmd: typeof compiled) { + cmd.configureOutput({ + writeOut: (text) => io.io.stdout.write(text), + writeErr: (text) => io.io.stderr.write(text), + }); + cmd.commands.forEach(capture); + } + capture(compiled); + await expect( + compiled.parseAsync(["node", "agentcore", "add", "credentials", "payment", leaf, "--help"]), + ).rejects.toMatchObject({ exitCode: 0 }); + expect(io.stdout()).toContain(`payment ${leaf}`); + expect(io.stdout()).not.toContain("--provider"); + expect(io.stdout()).not.toContain("--wallet-secret"); +}); +test("bare noninteractive group explains provider selection without mutation", async () => { + const project = await inProject(); + const { io, run } = command([]); + await expect(run()).rejects.toThrow("Choose a payment provider subcommand"); + expect(io.stderr()).toContain("amazon-pay"); + expect((await projectSpec(project)).credentials ?? []).toEqual([]); +}); + +test.each([...providers])( + "$leaf file source preserves secret and strips one newline", + async ({ leaf, secret, suffix, value }) => { + const project = await inProject(); + const path = join(project, "secret.txt"); + await Bun.write(path, `${value}\r\n`); + await command([leaf, "--name", "merchant", `--${secret}`, `file://${path}`]).run(); + expect( + (await readEnvFile(join(project, "agentcore", ".env.local")))[ + `AGENTCORE_CREDENTIAL_MERCHANT_${suffix}` + ], + ).toBe(value); + }, +); +test("legacy values equal to subcommands are values, not routing instructions", async () => { + const project = await inProject(); + await command(["--name", "stripe", "--provider", "CoinbaseCDP", "--api-key-id", "paypal"]).run(); + expect((await projectSpec(project)).credentials[0]).toMatchObject({ + name: "stripe", + provider: "CoinbaseCDP", + }); +}); + +test.each( + [ + ["stripe", "--name", "merchant", "--client-secret=SENSITIVE_UNKNOWN_SENTINEL"], + ["stripe", "--name", "merchant", "--", "SENSITIVE_UNKNOWN_SENTINEL"], + ["--", "stripe", "--restricted-key", "SENSITIVE_UNKNOWN_SENTINEL"], + ].map((args) => ({ args })), +)("parser errors never echo unknown values: $args", async ({ args }) => { + await inProject(); + const { io, run } = command(args); + const error = await run().catch((error) => error); + expect(error).toBeInstanceOf(Error); + expect(`${error.stack}${io.stderr()}${io.stdout()}`).not.toContain("SENSITIVE_UNKNOWN_SENTINEL"); + expect(error.cause).toBeUndefined(); +}); + +test.each([...providers])( + "$leaf source errors identify the actual secret flag before changing the project", + async ({ leaf, secret }) => { + const project = await inProject(); + const before = JSON.stringify(await projectSpec(project)); + const { run } = command([ + leaf, + "--name", + "merchant", + `--${secret}`, + `file://${join(project, "missing-secret")}`, + ]); + await expect(run()).rejects.toThrow(`'--${secret}'`); + expect(JSON.stringify(await projectSpec(project))).toBe(before); + }, +); diff --git a/src/handlers/project/add/credentials/payment/merchant.ts b/src/handlers/project/add/credentials/payment/merchant.ts new file mode 100644 index 0000000000..ffd3c7f759 --- /dev/null +++ b/src/handlers/project/add/credentials/payment/merchant.ts @@ -0,0 +1,144 @@ +import z from "zod"; +import { CredentialNameSchema } from "../../../../../projectSchemas/credential"; +import { + AmazonPayRegionSchema, + PaymentEnvironmentSchema, +} from "../../../../../projectSchemas/payment"; +import { createHandler, flag } from "../../../../../router"; +import type { AddProjectResourceConfig } from "../../types"; +import { addCredentialToProject, parseExclusiveSecretRef } from "../shared"; +import { toAddMerchantPaymentCredentialInput } from "./providers"; + +const nameFlag = flag("name", "the name of the credential provider", CredentialNameSchema); +const secretFlag = (name: N, description: string) => + flag( + name, + `${description} (file://path or - for stdin; inline values are rejected)`, + z.string().optional(), + { sensitive: true }, + ); +const referenceFlag = (name: N) => + flag( + name, + 'external secret reference JSON: {"secretId":"","jsonKey":""}', + z.string().optional(), + { sensitive: true }, + ); + +export function createMerchantPaymentHandlers(config: AddProjectResourceConfig) { + return [ + createHandler({ + name: "stripe", + description: "add Stripe credentials to the current project", + flags: [ + nameFlag, + secretFlag("restricted-key", "the Stripe restricted key"), + referenceFlag("restricted-key-secret-reference"), + flag("publishable-key", "optional Stripe publishable key", z.string().optional()), + ], + handle: async (ctx, flags) => { + await addCredentialToProject( + ctx, + config, + await toAddMerchantPaymentCredentialInput({ + name: flags.name, + configuration: { + provider: "Stripe", + secret: flags["restricted-key"], + secretRef: parseExclusiveSecretRef( + "restricted-key-secret-reference", + flags["restricted-key-secret-reference"], + "restricted-key", + flags["restricted-key"], + ), + publishableKey: flags["publishable-key"], + }, + io: config.io, + }), + ); + }, + }), + createHandler({ + name: "paypal", + description: "add PayPal credentials to the current project", + flags: [ + nameFlag, + flag("client-id", "the PayPal REST application client ID", z.string().optional()), + secretFlag("client-secret", "the PayPal client secret"), + referenceFlag("client-secret-reference"), + flag( + "environment", + "PayPal environment: SANDBOX or LIVE (no default)", + PaymentEnvironmentSchema.optional(), + ), + ], + handle: async (ctx, flags) => { + await addCredentialToProject( + ctx, + config, + await toAddMerchantPaymentCredentialInput({ + name: flags.name, + configuration: { + provider: "PayPal", + secret: flags["client-secret"], + secretRef: parseExclusiveSecretRef( + "client-secret-reference", + flags["client-secret-reference"], + "client-secret", + flags["client-secret"], + ), + clientId: flags["client-id"], + environment: flags.environment, + }, + io: config.io, + }), + ); + }, + }), + createHandler({ + name: "amazon-pay", + description: "add Amazon Pay credentials to the current project", + flags: [ + nameFlag, + flag("merchant-id", "the Amazon Pay merchant ID", z.string().optional()), + flag("store-id", "the Amazon Pay store ID", z.string().optional()), + secretFlag("authorization-token", "the Amazon Pay authorization token"), + referenceFlag("authorization-token-secret-reference"), + flag( + "environment", + "Amazon Pay environment: SANDBOX or LIVE (no default)", + PaymentEnvironmentSchema.optional(), + ), + flag( + "amazon-pay-region", + "Amazon Pay merchant region: NA or EU (no default)", + AmazonPayRegionSchema.optional(), + ), + ], + handle: async (ctx, flags) => { + await addCredentialToProject( + ctx, + config, + await toAddMerchantPaymentCredentialInput({ + name: flags.name, + configuration: { + provider: "AmazonPay", + secret: flags["authorization-token"], + secretRef: parseExclusiveSecretRef( + "authorization-token-secret-reference", + flags["authorization-token-secret-reference"], + "authorization-token", + flags["authorization-token"], + ), + merchantId: flags["merchant-id"], + storeId: flags["store-id"], + environment: flags.environment, + amazonPayRegion: flags["amazon-pay-region"], + }, + io: config.io, + }), + ); + }, + }), + ]; +} diff --git a/src/handlers/project/add/credentials/payment/payment.screen.test.tsx b/src/handlers/project/add/credentials/payment/payment.screen.test.tsx index 4315bf1aa6..23921e019e 100644 --- a/src/handlers/project/add/credentials/payment/payment.screen.test.tsx +++ b/src/handlers/project/add/credentials/payment/payment.screen.test.tsx @@ -385,7 +385,9 @@ describe("project add credentials payment dispatch", () => { ])("%s stays headless", async (_label, io, args) => { await inProject(); - expectMissingName(await routeError(io(), args)); + const error = await routeError(io(), args); + if (args.includes("--provider")) expectMissingName(error); + else expect((error as Error).message).toContain("Choose a payment provider subcommand"); }); test("flag-driven add still runs headless in a TTY session", async () => { diff --git a/src/handlers/project/add/credentials/payment/providers.test.ts b/src/handlers/project/add/credentials/payment/providers.test.ts new file mode 100644 index 0000000000..351b34c699 --- /dev/null +++ b/src/handlers/project/add/credentials/payment/providers.test.ts @@ -0,0 +1,145 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { toAddMerchantPaymentCredentialInput } from "./providers"; +import { + credentialEnvironmentVariableNames, + CredentialSchema, +} from "../../../../../projectSchemas/credential"; +import { ProjectSpecSchema } from "../../../../../projectSchemas/project"; + +const directories: string[] = []; +afterEach(async () => { + await Promise.all( + directories.splice(0).map((path) => rm(path, { recursive: true, force: true })), + ); +}); +const secretRef = { secretId: "merchant-secret", jsonKey: "key" }; +const configurations = [ + { provider: "Stripe", publishableKey: "pk_test_example" }, + { provider: "PayPal", clientId: "merchant-client", environment: "SANDBOX" }, + { + provider: "AmazonPay", + merchantId: "merchant", + storeId: "store", + environment: "SANDBOX", + amazonPayRegion: "EU", + }, +] as const; + +describe("merchant payment credentials", () => { + test.each([...configurations])( + "persists %j references without suppressing identifiers", + async (configuration) => { + const input = await toAddMerchantPaymentCredentialInput({ + name: "merchant", + configuration: { ...configuration, secretRef }, + }); + expect(input.resourceConfig).toEqual({ + authorizerType: "PaymentCredentialProvider", + name: "merchant", + provider: configuration.provider, + secretRef, + }); + expect(input.envEntries?.every((entry) => entry.value !== undefined)).toBe(true); + const keys = credentialEnvironmentVariableNames(CredentialSchema.parse(input.resourceConfig)); + expect( + keys.some( + (key) => + key.endsWith("_SECRET") || + key.endsWith("_RESTRICTED_KEY") || + key.endsWith("_AUTHORIZATION_TOKEN"), + ), + ).toBe(false); + if (configuration.provider === "AmazonPay") + expect(keys).toContain("AGENTCORE_CREDENTIAL_MERCHANT_AMAZON_PAY_REGION"); + expect(JSON.stringify(CredentialSchema.parse(input.resourceConfig))).toBe( + JSON.stringify(input.resourceConfig), + ); + }, + ); + + test.each([...configurations])( + "keeps %j values outside project config", + async (configuration) => { + const directory = await mkdtemp(join(tmpdir(), "merchant-payment-")); + directories.push(directory); + const path = join(directory, "key"); + const secret = configuration.provider === "Stripe" ? "rk_test_example" : "example-value"; + await writeFile(path, `${secret}\n`); + const input = await toAddMerchantPaymentCredentialInput({ + name: "merchant", + configuration: { ...configuration, secret: `file://${path}` }, + }); + expect(JSON.stringify(input.resourceConfig)).not.toContain(secret); + expect(input.envEntries?.some((entry) => entry.value === secret)).toBe(true); + }, + ); + + test.each(["NA", "EU"])( + "accepts Amazon Pay %s independently of environment", + async (amazonPayRegion) => { + const input = await toAddMerchantPaymentCredentialInput({ + name: "merchant", + configuration: { ...configurations[2], amazonPayRegion, environment: "LIVE", secretRef }, + }); + expect(input.envEntries).toContainEqual( + expect.objectContaining({ + key: "AGENTCORE_CREDENTIAL_MERCHANT_AMAZON_PAY_REGION", + value: amazonPayRegion, + }), + ); + }, + ); + + test.each([ + { ...configurations[0], secret: "file:///does-not-exist", secretRef }, + { ...configurations[1], secret: "file:///does-not-exist", environment: "TEST" }, + { ...configurations[2], secret: "file:///does-not-exist", amazonPayRegion: "us-east-1" }, + { ...configurations[2], secret: "file:///does-not-exist", amazonPayRegion: "JP" }, + { ...configurations[0], secret: "raw-secret" }, + { ...configurations[0], secretRef: { secretId: "missing-key" } }, + { ...configurations[2], publicKeyId: "stale-model-field" }, + { ...configurations[0], clientId: "foreign-field" }, + ])("rejects invalid configuration before reading secrets: %j", async (configuration) => { + await expect( + toAddMerchantPaymentCredentialInput({ name: "merchant", configuration }), + ).rejects.toThrow("Invalid payment configuration"); + }); + + test("allows a missing secret to produce one scaffold placeholder", async () => { + const input = await toAddMerchantPaymentCredentialInput({ + name: "merchant", + configuration: configurations[1], + }); + expect( + input.envEntries?.filter((entry) => entry.value === undefined).map((entry) => entry.key), + ).toEqual(["AGENTCORE_CREDENTIAL_MERCHANT_CLIENT_SECRET"]); + }); + + test("billing needs no credential and rejects credential and role inputs", () => { + const project = { + version: 2, + name: "shop", + payments: [{ name: "payments", connectors: [{ name: "billing", provider: "AwsBilling" }] }], + }; + expect(ProjectSpecSchema.parse(project).payments?.[0]?.connectors[0]).toEqual({ + name: "billing", + provider: "AwsBilling", + }); + for (const invalid of [{ credentialName: "credential" }, { iamRoleArn: "role" }]) { + expect( + ProjectSpecSchema.safeParse({ + ...project, + payments: [ + { + name: "payments", + connectors: [{ ...project.payments[0]!.connectors[0], ...invalid }], + }, + ], + }).success, + ).toBe(false); + } + }); +}); diff --git a/src/handlers/project/add/credentials/payment/providers.ts b/src/handlers/project/add/credentials/payment/providers.ts new file mode 100644 index 0000000000..725f9d54aa --- /dev/null +++ b/src/handlers/project/add/credentials/payment/providers.ts @@ -0,0 +1,145 @@ +import z from "zod"; +import { InputValidationError } from "../../../../../errors"; +import { SourceResolver, type AppIO } from "../../../../../io"; +import { + CredentialNameSchema, + SecretReferenceSchema, + credentialEnvVarName, +} from "../../../../../projectSchemas/credential"; +import { + AmazonPayRegionSchema, + PaymentEnvironmentSchema, +} from "../../../../../projectSchemas/payment"; +import type { AddCredentialInput } from "../shared"; + +const identifier = z.string().trim().min(1); +const secretSource = z + .string() + .refine( + (value) => value === "-" || (value.startsWith("file://") && value.length > 7), + "Secret values must come from file:// or '-' for stdin", + ); +const sources = { secret: secretSource.optional(), secretRef: SecretReferenceSchema.optional() }; + +/** Shared by command adapters; values are saved only in .env.local. */ +export const MerchantPaymentInputSchema = z + .discriminatedUnion("provider", [ + z + .object({ + provider: z.literal("Stripe"), + ...sources, + publishableKey: z + .string() + .regex(/^pk_(test|live)_\S+$/) + .optional(), + }) + .strict(), + z + .object({ + provider: z.literal("PayPal"), + ...sources, + clientId: identifier.optional(), + environment: PaymentEnvironmentSchema.optional(), + }) + .strict(), + z + .object({ + provider: z.literal("AmazonPay"), + ...sources, + merchantId: identifier.optional(), + storeId: identifier.optional(), + environment: PaymentEnvironmentSchema.optional(), + amazonPayRegion: AmazonPayRegionSchema.optional(), + }) + .strict(), + ]) + .superRefine((input, ctx) => { + if (input.secret !== undefined && input.secretRef !== undefined) { + ctx.addIssue({ code: "custom", message: "secret and secretRef are mutually exclusive" }); + } + }); +export type MerchantPaymentInput = z.infer; + +const secretFlags = { + Stripe: "restricted-key", + PayPal: "client-secret", + AmazonPay: "authorization-token", +} satisfies Record; + +/** Resolve sensitive sources only after validating the whole provider configuration. */ +export async function toAddMerchantPaymentCredentialInput(input: { + name: string; + configuration: unknown; + io?: Pick; + resolver?: SourceResolver; +}): Promise { + const nameResult = CredentialNameSchema.safeParse(input.name); + const result = MerchantPaymentInputSchema.safeParse(input.configuration); + if (!nameResult.success) throw new InputValidationError("Invalid payment credential name"); + if (!result.success) { + // Zod's full error includes input values; diagnostics name fields, never material. + throw new InputValidationError( + `Invalid payment configuration: ${result.error.issues + .map((issue) => (issue.path.length ? issue.path.join(".") : issue.message)) + .join(", ")}`, + ); + } + const configuration = result.data; + const resolver = input.resolver ?? new SourceResolver({ stdin: input.io?.stdin }); + const secret = await resolver.resolveSecret( + secretFlags[configuration.provider], + configuration.secret, + ); + if (secret !== undefined && !secret.trim()) { + throw new InputValidationError("Payment credential secret must not be empty"); + } + if (configuration.provider === "Stripe" && secret !== undefined) { + if (!/^rk_(test|live)_\S+$/.test(secret)) { + throw new InputValidationError("Stripe requires a restricted key (rk_test_ or rk_live_)"); + } + if ( + configuration.publishableKey && + configuration.publishableKey.split("_")[1] !== secret.split("_")[1] + ) { + throw new InputValidationError("Stripe restricted and publishable key modes must match"); + } + } + const fields: [string, string | undefined][] = []; + switch (configuration.provider) { + case "Stripe": + if (!configuration.secretRef) fields.push(["_RESTRICTED_KEY", secret]); + if (configuration.publishableKey !== undefined) { + fields.push(["_PUBLISHABLE_KEY", configuration.publishableKey]); + } + break; + case "PayPal": + fields.push( + ["_CLIENT_ID", configuration.clientId], + ["_ENVIRONMENT", configuration.environment], + ); + if (!configuration.secretRef) fields.push(["_CLIENT_SECRET", secret]); + break; + case "AmazonPay": + fields.push( + ["_MERCHANT_ID", configuration.merchantId], + ["_STORE_ID", configuration.storeId], + ["_ENVIRONMENT", configuration.environment], + ["_AMAZON_PAY_REGION", configuration.amazonPayRegion], + ); + if (!configuration.secretRef) fields.push(["_AUTHORIZATION_TOKEN", secret]); + break; + } + return { + resourceConfig: { + authorizerType: "PaymentCredentialProvider", + name: input.name, + provider: configuration.provider, + ...(configuration.secretRef && { secretRef: configuration.secretRef }), + }, + envEntries: fields.map(([suffix, value]) => ({ + key: credentialEnvVarName(input.name, suffix), + value, + comment: `${configuration.provider} ${suffix.slice(1).toLowerCase().replaceAll("_", " ")} for payment credential provider '${input.name}' (set before deploy)`, + })), + }; +} diff --git a/src/handlers/project/add/credentials/payment/screen.tsx b/src/handlers/project/add/credentials/payment/screen.tsx index 27f9a3d2bb..0d08d0ec8c 100644 --- a/src/handlers/project/add/credentials/payment/screen.tsx +++ b/src/handlers/project/add/credentials/payment/screen.tsx @@ -15,7 +15,7 @@ import { type TextInputSpec, } from "../../../../../components/wizard"; import { CredentialNameSchema } from "../../../../../projectSchemas/credential"; -import type { PaymentProvider } from "../../../../../projectSchemas/payment"; +import type { LegacyPaymentProvider } from "../../../../../projectSchemas/payment"; import { ProjectKey } from "../../../../../router"; import type { ScreenProps } from "../../../../types"; import { ProjectGate, projectQueryKey } from "../../../ProjectGate"; @@ -30,7 +30,7 @@ const BREADCRUMB = ["agentcore", "add", "credentials", "payment"]; const DESCRIPTION = "add a payment credential provider to the current project"; const CREDENTIALS_MENU = "/agentcore/add/credentials"; -const PROVIDER_CHOICES: Choice[] = [ +const PROVIDER_CHOICES: Choice[] = [ { value: "CoinbaseCDP", label: "CoinbaseCDP", @@ -56,7 +56,7 @@ const AuthorizationIdSchema = identifierSchema("authorizationId"); type PaymentFormValues = { name: string; - provider: PaymentProvider; + provider: LegacyPaymentProvider; apiKeyId: string; apiKeySecretFile: string; walletSecretFile: string; diff --git a/src/handlers/project/add/credentials/shared.test.ts b/src/handlers/project/add/credentials/shared.test.ts new file mode 100644 index 0000000000..63d810a359 --- /dev/null +++ b/src/handlers/project/add/credentials/shared.test.ts @@ -0,0 +1,84 @@ +import { afterEach, expect, test } from "bun:test"; +import { createRootHandler } from "../../../index"; +import { + createSilentLogger, + TestCoreClient, + TestGlobalConfigAccessor, + testIO, +} from "../../../../testing"; +import { createPaymentProjectTestHarness } from "../payment-test-support"; + +const { cleanup, inProject, projectSpec } = createPaymentProjectTestHarness("shared-secret-ref"); +afterEach(cleanup); +const credentials = [ + { kind: "api-key", reference: "api-key-secret-reference", secret: "api-key" }, + { kind: "oauth", reference: "client-secret-reference", secret: "client-secret" }, +]; +function command(args: string[]) { + const io = testIO(); + const root = createRootHandler(new TestCoreClient(), { + io: io.io, + logger: createSilentLogger(), + globalConfigAccessor: new TestGlobalConfigAccessor(), + }); + return { io, run: () => root.route(["node", "agentcore", "add", "credentials", ...args]) }; +} +const invalidReferences = [ + "", + " ", + "SENSITIVE_REFERENCE_SENTINEL", + '{"secretId":" ","jsonKey":"key"}', + '{"secretId":"secret","jsonKey":"\\t"}', + '{"secretId":"secret","jsonKey":""}', + '{"secretId":"secret"}', + '{"secretId":"secret","jsonKey":"key","extra":"SENSITIVE_REFERENCE_SENTINEL"}', +]; +test.each( + credentials.flatMap((credential) => invalidReferences.map((value) => ({ ...credential, value }))), +)( + "$kind rejects malformed reference $value without writes or sensitive diagnostics", + async ({ kind, reference, value }) => { + const project = await inProject(); + const before = JSON.stringify(await projectSpec(project)); + const { io, run } = command([kind, "--name", "credential", `--${reference}`, value]); + const error = await run().catch((error) => error); + expect(error).toBeInstanceOf(Error); + expect(error.message).toBe( + `Invalid --${reference}: expected JSON with nonempty secretId and jsonKey`, + ); + expect(error.cause).toBeUndefined(); + expect(`${error.stack}${io.stderr()}${io.stdout()}`).not.toContain( + "SENSITIVE_REFERENCE_SENTINEL", + ); + expect(JSON.stringify(await projectSpec(project))).toBe(before); + }, +); +test.each(credentials)( + "$kind rejects an empty reference alongside a secret before reading stdin", + async ({ kind, reference, secret }) => { + await inProject(); + const { io, run } = command([ + kind, + "--name", + "credential", + `--${reference}`, + "", + `--${secret}`, + "-", + ]); + await expect(run()).rejects.toThrow(`--${secret} and --${reference} are mutually exclusive`); + expect(io.io.stdin.readableFlowing).toBeNull(); + }, +); +test("shared parser preserves nonblank JSON keys without trimming", async () => { + const project = await inProject(); + const secretRef = { secretId: "secret", jsonKey: " key with spaces " }; + await command([ + "api-key", + "--name", + "credential", + "--api-key-secret-reference", + JSON.stringify(secretRef), + ]).run(); + expect((await projectSpec(project)).credentials[0].secretRef).toEqual(secretRef); +}); diff --git a/src/handlers/project/add/credentials/shared.ts b/src/handlers/project/add/credentials/shared.ts index 9a89f74fab..e01d4b11e8 100644 --- a/src/handlers/project/add/credentials/shared.ts +++ b/src/handlers/project/add/credentials/shared.ts @@ -24,11 +24,19 @@ export function parseExclusiveSecretRef( secretFlag: string, secretValue: string | undefined, ) { - if (!refValue) return undefined; + if (refValue === undefined) return undefined; if (secretValue !== undefined) { throw new InputValidationError(`--${secretFlag} and --${refFlag} are mutually exclusive`); } - return parseSecretReference(refFlag, refValue); + try { + const reference = parseSecretReference(refFlag, refValue); + if (!reference.secretId.trim() || !reference.jsonKey.trim()) throw new Error(); + return reference; + } catch { + throw new InputValidationError( + `Invalid --${refFlag}: expected JSON with nonempty secretId and jsonKey`, + ); + } } /** Applies credential-specific name and environment-variable collision checks. */ diff --git a/src/handlers/project/add/payment-connector/index.test.ts b/src/handlers/project/add/payment-connector/index.test.ts index a2a4d298e1..07d581a125 100644 --- a/src/handlers/project/add/payment-connector/index.test.ts +++ b/src/handlers/project/add/payment-connector/index.test.ts @@ -206,3 +206,43 @@ describe("project add payment-connector", () => { ); }); }); + +test("adds AWS Billing without a credential", async () => { + const projectRoot = await inProject(); + await addManager(); + await run([ + "add", + "payment-connector", + "--manager", + "payments", + "--name", + "billing", + "--aws-billing", + ]); + const spec = await projectSpec(projectRoot); + expect(spec.credentials).toEqual([]); + expect(spec.payments[0].connectors).toEqual([{ name: "billing", provider: "AwsBilling" }]); +}); + +test.each([{ flags: ["--quick-create"] }, { flags: ["--credential", "existing"] }])( + "rejects billing with another selector: %j", + async ({ flags }) => { + const projectRoot = await inProject(); + await addManager(); + await expectError( + run([ + "add", + "payment-connector", + "--manager", + "payments", + "--name", + "billing", + "--aws-billing", + ...flags, + ]), + "specify exactly one", + InputValidationError, + ); + expect((await projectSpec(projectRoot)).payments[0].connectors).toEqual([]); + }, +); diff --git a/src/handlers/project/add/payment-connector/index.ts b/src/handlers/project/add/payment-connector/index.ts index b23a9ddc1b..c807abf752 100644 --- a/src/handlers/project/add/payment-connector/index.ts +++ b/src/handlers/project/add/payment-connector/index.ts @@ -7,6 +7,7 @@ import { addProjectResource, addDescription } from "../shared"; import { assertMutuallyExclusiveFlags } from "../../../utils"; export type PaymentConnectorInput = + | { managerName: string; name: string; awsBilling: true; quickCreate?: false } | { managerName: string; name: string; @@ -23,6 +24,13 @@ export function toAddPaymentConnectorInput( project: Project, input: PaymentConnectorInput, ): AddResourceInput { + if ("awsBilling" in input) { + return { + resourceType: "payment-connector", + managerName: input.managerName, + resourceConfig: { name: input.name, provider: "AwsBilling" }, + }; + } if (input.quickCreate) { return { resourceType: "payment-connector", @@ -71,25 +79,34 @@ export const createAddPaymentConnectorHandler = (config: AddProjectResourceConfi flag("manager", "the parent payment manager", z.string().min(1)), flag("name", "the payment connector name", z.string().min(1)), flag("credential", "an existing payment credential to reuse", z.string().optional()), + flag( + "aws-billing", + "create an AWS Marketplace billing connector (requires its service-linked role)", + z.boolean(), + ), flag("quick-create", "create a CoinbaseCDP connector through Quick Create", z.boolean()), ], handle: async (ctx, flags) => { - assertMutuallyExclusiveFlags(flags, ["credential", "quick-create"], { exactlyOne: true }); + assertMutuallyExclusiveFlags(flags, ["credential", "quick-create", "aws-billing"], { + exactlyOne: true, + }); const project = ctx.require(ProjectKey); const input = toAddPaymentConnectorInput( project, - flags["quick-create"] - ? { - managerName: flags.manager, - name: flags.name, - quickCreate: true, - } - : { - managerName: flags.manager, - name: flags.name, - credentialName: flags.credential!, - }, + flags["aws-billing"] + ? { managerName: flags.manager, name: flags.name, awsBilling: true } + : flags["quick-create"] + ? { + managerName: flags.manager, + name: flags.name, + quickCreate: true, + } + : { + managerName: flags.manager, + name: flags.name, + credentialName: flags.credential!, + }, ); await addProjectResource( diff --git a/src/handlers/project/invoke/index.test.tsx b/src/handlers/project/invoke/index.test.tsx index 1bfdf65c65..14e49c1c2e 100644 --- a/src/handlers/project/invoke/index.test.tsx +++ b/src/handlers/project/invoke/index.test.tsx @@ -659,3 +659,111 @@ describe("invoke", () => { ); }); }); + +describe("project payment invocation context", () => { + test("deployed Runtime forwards explicit buyer and legacy context independently of Runtime IDs", async () => { + const { core } = await run( + [ + "--runtime", + RUNTIME.name, + "--payload", + '{"prompt":"hi"}', + "--payment-user-id", + "buyer-a", + "--payment-instrument-id", + "instrument-a", + "--payment-session-id", + "payment-session-a", + "--session-id", + "runtime-session-a", + "--user-id", + "runtime-user-a", + ], + { runtimes: [RUNTIME] }, + ); + const request = core.runtime.calls.find((call) => call.method === "invokeRuntime")!.args[0] as { + payload: Uint8Array; + runtimeSessionId: string; + runtimeUserId: string; + }; + expect(JSON.parse(new TextDecoder().decode(request.payload))).toEqual({ + prompt: "hi", + user_id: "buyer-a", + payment_instrument_id: "instrument-a", + payment_session_id: "payment-session-a", + }); + expect(request.runtimeSessionId).toBe("runtime-session-a"); + expect(request.runtimeUserId).toBe("runtime-user-a"); + }); + test("local HTTP Runtime receives the same merchant context without payment headers", async () => { + let receivedBody = ""; + let paymentHeaders: string[] = []; + const server = await startHttpServer((request) => { + receivedBody = request.body.toString(); + paymentHeaders = Object.keys(request.headers).filter((key) => key.includes("payment")); + return { status: 200, headers: { "content-type": "text/plain" }, body: "ok" }; + }); + servers.push(server); + const { core, resolved } = await run( + [ + "--runtime", + RUNTIME.name, + "--local", + "--port", + String(server.port), + "--payload", + '{"prompt":"hi","big":9007199254740993}', + "--payment-user-id", + "buyer-a", + "--payment-intent-id", + "intent-a", + ], + { runtimes: [RUNTIME] }, + { writeTargets: false }, + ); + expect(receivedBody).toContain("9007199254740993"); + expect(JSON.parse(receivedBody)).toMatchObject({ + user_id: "buyer-a", + payment_intent_id: "intent-a", + }); + expect(paymentHeaders).toEqual([]); + expect(resolved.targets).toEqual([]); + expect(core.runtime.calls).toEqual([]); + }); + test.each( + [ + ["--gateway", GATEWAY.name, "--payment-user-id", "buyer-a"], + ["--harness", HARNESS.name, "--payment-user-id", "buyer-a"], + ["--runtime", RUNTIME.name, "--payment-intent-id", "intent-a", "--payload", "{}"], + ["--runtime", RUNTIME.name, "--payment-user-id", "buyer-a"], + [ + "--runtime", + RUNTIME.name, + "--payment-user-id", + "buyer-a", + "--payload", + "{}", + "--content-type", + "text/plain", + ], + ].map((args) => ({ args })), + )("rejects incompatible project context before resolution: %j", async ({ args }) => { + const subject = await routedCommand(args, { + runtimes: [RUNTIME], + harnesses: [HARNESS], + agentCoreGateways: [GATEWAY], + }); + await expect(subject.route()).rejects.toThrow(); + expect(subject.resolved.targets).toEqual([]); + expect(subject.core.runtime.calls).toEqual([]); + }); + test("local MCP context fails before invoking a development server", async () => { + const subject = await routedCommand( + ["--runtime", RUNTIME.name, "--local", "--payload", "{}", "--payment-user-id", "buyer-a"], + { runtimes: [{ ...RUNTIME, protocol: "MCP" }] }, + { writeTargets: false }, + ); + await expect(subject.route()).rejects.toThrow("HTTP"); + expect(subject.core.runtime.calls).toEqual([]); + }); +}); diff --git a/src/handlers/project/invoke/index.tsx b/src/handlers/project/invoke/index.tsx index 7cdd7b9a2c..ab9d465d94 100644 --- a/src/handlers/project/invoke/index.tsx +++ b/src/handlers/project/invoke/index.tsx @@ -22,6 +22,7 @@ import { projectResourceNames } from "../selection"; import { RESOURCE_LABELS, type ProjectInvokableResource } from "../types"; import { createInvokeRuntimeHandler, invokeRuntimeFlags } from "../../runtime/invoke"; import { invokeProjectRuntimeLocally } from "./runtime"; +import { PaymentInvokeContext } from "../../runtime/invoke/paymentContext"; const RESOURCE = "Resource options:"; const RESOURCE_TYPES = ["runtime", "harness", "gateway"] as const; @@ -146,6 +147,14 @@ export function createProjectInvokeHandler(core: Core, io: AppIO) { `--${unsupported[0]} does not apply to a ${RESOURCE_LABELS[resourceType]}`, ); } + if (resourceType === "runtime") { + const paymentContext = PaymentInvokeContext.fromFlags(flags); + paymentContext.assertContentType(flags["content-type"]); + if (paymentContext.enabled && flags.payload === undefined) + throw new InputValidationError( + "Payment context requires --payload for headless invocation", + ); + } const isProjectName = project && projectResourceNames(project, resourceType).includes(identifier); for (const name of ["target", "local"] as const) { diff --git a/src/handlers/project/invoke/runtime.tsx b/src/handlers/project/invoke/runtime.tsx index c43c60a91f..494a6ade11 100644 --- a/src/handlers/project/invoke/runtime.tsx +++ b/src/handlers/project/invoke/runtime.tsx @@ -6,6 +6,7 @@ import type { Context } from "../../../router"; import { withUserCancellation } from "../../../runnable"; import { runWithProgress } from "../../../tui/progress"; import { JsonKey } from "../../keys"; +import { PaymentInvokeContext } from "../../runtime/invoke/paymentContext"; import { parseRuntimeInvokeHeaders, resolveRuntimeInvokeSources, @@ -25,6 +26,9 @@ export async function invokeProjectRuntimeLocally( throw new InputValidationError("--json cannot be used with --output-file"); } const protocol = runtime.protocol ?? "HTTP"; + const paymentContext = PaymentInvokeContext.fromFlags(flags); + paymentContext.assertProtocol(protocol); + paymentContext.assertContentType(flags["content-type"]); const unsupportedFlag = Object.entries({ target: flags.target, qualifier: flags.qualifier, @@ -60,7 +64,7 @@ export async function invokeProjectRuntimeLocally( { port: flags.port ?? DEV_PORTS[protocol], protocol, - payload: sources.payload, + payload: paymentContext.apply(sources.payload, flags["content-type"]), contentType: flags["content-type"], accept: flags.accept, runtimeSessionId: flags["session-id"], diff --git a/src/handlers/runtime/invoke/index.tsx b/src/handlers/runtime/invoke/index.tsx index 35203e3a1b..4be3e6ce73 100644 --- a/src/handlers/runtime/invoke/index.tsx +++ b/src/handlers/runtime/invoke/index.tsx @@ -17,8 +17,10 @@ import { import { writeRuntimeInvokeResponse } from "./response"; import { RuntimeInvokeLaunchContextKey } from "./launchContext"; import { invokeRuntimeTarget } from "./operation"; +import { PaymentInvokeContext } from "./paymentContext"; export const invokeRuntimeFlags = [ + ...PaymentInvokeContext.flags, flag("id", "the ID of the Runtime", runtimeIdSchema), flag("payload", "the inline payload to send", z.string().optional(), { sensitive: true, @@ -55,6 +57,19 @@ export const createInvokeRuntimeHandler = (core: Core, io: AppIO) => description: "invoke a Runtime", flags: invokeRuntimeFlags, handle: async (ctx, flags) => { + const paymentContext = PaymentInvokeContext.fromFlags(flags); + paymentContext.assertContentType(flags["content-type"]); + if ( + paymentContext.enabled && + [ + flags["mcp-session-id"], + flags["mcp-protocol-version"], + flags["mcp-method"], + flags["mcp-name"], + ].some((value) => value !== undefined) + ) { + throw new InputValidationError("Payment context is not supported for MCP invocation"); + } if (flags.payload === undefined) { const hasHeadlessOnlyFlag = Object.entries(flags).some( ([name, value]) => @@ -116,7 +131,8 @@ export const createInvokeRuntimeHandler = (core: Core, io: AppIO) => { runtimeId, qualifier: flags.qualifier, - payload: sources.payload, + payload: paymentContext.apply(sources.payload, flags["content-type"]), + paymentContext: paymentContext.enabled, contentType: flags["content-type"], accept: flags.accept, runtimeSessionId: flags["session-id"], diff --git a/src/handlers/runtime/invoke/invoke.test.tsx b/src/handlers/runtime/invoke/invoke.test.tsx index 0b87e19360..4f2b7f72a3 100644 --- a/src/handlers/runtime/invoke/invoke.test.tsx +++ b/src/handlers/runtime/invoke/invoke.test.tsx @@ -840,3 +840,84 @@ describe("runtime invoke", () => { } }); }); + +describe("headless payment invocation context", () => { + test("maps merchant context while keeping Runtime identity and sessions separate", async () => { + const { core } = await run([ + "runtime", + "invoke", + "--id", + RUNTIME_ID, + "--payload", + '{"prompt":"hi","big":9007199254740993}', + "--user-id", + "runtime-user", + "--session-id", + "runtime-session", + "--payment-user-id", + "buyer-a", + "--payment-intent-id", + "intent-a", + "--json", + ]); + const request = core.runtime.calls.find((call) => call.method === "invokeRuntime")! + .args[0] as RuntimeInvokeRequest; + expect(new TextDecoder().decode(request.payload)).toContain("9007199254740993"); + expect(JSON.parse(new TextDecoder().decode(request.payload))).toMatchObject({ + prompt: "hi", + user_id: "buyer-a", + payment_intent_id: "intent-a", + }); + expect(request.runtimeUserId).toBe("runtime-user"); + expect(request.runtimeSessionId).toBe("runtime-session"); + expect(request).not.toHaveProperty("paymentContext"); + expect(request.applicationHeaders).toBeUndefined(); + }); + test.each( + [ + ["--payment-intent-id", "intent-a", "--payload", "{}", "--user-id", "runtime-user"], + ["--payment-user-id", "buyer-a"], + ["--payment-user-id", " buyer-a ", "--payload", "{}"], + ["--payment-user-id", "buyer-a", "--payload", '{"user_id":" buyer-a "}'], + ["--payment-user-id", "buyer-a", "--payload", "{}", "--content-type", "text/plain"], + ["--payment-user-id", "buyer-a", "--payload", "{}", "--mcp-method", "tools/call"], + ["--payment-user-id", "buyer-a", "--payload", '{"user_id":"buyer-b"}'], + [ + "--payment-user-id", + "buyer-a", + "--payment-intent-id", + "intent-a", + "--payload", + '{"payment_session_id":"session-a"}', + ], + ].map((args) => ({ args })), + )("rejects incompatible payment flags before Runtime calls: %j", async ({ args }) => { + const core = new TestCoreClient(); + const output = captureIO(); + await expect( + runCommand(core, output.io, ["runtime", "invoke", "--id", RUNTIME_ID, ...args]), + ).rejects.toThrow(); + expect(core.runtime.calls).toEqual([]); + }); + test("rejects a modeled MCP Runtime before invoke", async () => { + const core = new TestCoreClient(); + core.runtime.setGetResponse({ + agentRuntimeArn: RUNTIME_ARN, + protocolConfiguration: { serverProtocol: "MCP" }, + } as GetAgentRuntimeResponse); + await expect( + runCommand(core, captureIO().io, [ + "runtime", + "invoke", + "--id", + RUNTIME_ID, + "--payload", + "{}", + "--payment-user-id", + "buyer-a", + "--json", + ]), + ).rejects.toThrow("HTTP"); + expect(core.runtime.calls.map((call) => call.method)).toEqual(["getRuntime"]); + }); +}); diff --git a/src/handlers/runtime/invoke/paymentContext.test.ts b/src/handlers/runtime/invoke/paymentContext.test.ts new file mode 100644 index 0000000000..142a769124 --- /dev/null +++ b/src/handlers/runtime/invoke/paymentContext.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from "bun:test"; +import { PaymentInvokeContext } from "./paymentContext"; +const bytes = (value: string) => new TextEncoder().encode(value); +const text = (value: Uint8Array) => new TextDecoder().decode(value); +const merchant = () => + PaymentInvokeContext.fromFlags({ "payment-user-id": "buyer-a", "payment-intent-id": "intent-a" }); +test("no payment flags return the exact original bytes, including non-JSON", () => { + const payload = new Uint8Array([255, 0, 1]); + expect(PaymentInvokeContext.fromFlags({}).apply(payload, "application/octet-stream")).toBe( + payload, + ); +}); +test("context appends fields without changing large/exponent numbers or unrelated JSON lexemes", () => { + const original = + '{ "prompt":"hello", "integer":9007199254740993, "large":1e400, "decimal":1.2300 }\n'; + const output = text(merchant().apply(bytes(original))); + expect(output).toContain('"integer":9007199254740993'); + expect(output).toContain('"large":1e400'); + expect(output).toContain('"decimal":1.2300'); + expect(JSON.parse(output)).toMatchObject({ + prompt: "hello", + user_id: "buyer-a", + payment_intent_id: "intent-a", + }); +}); +test("matching context is accepted unchanged; buyer-only and legacy mappings are separate", () => { + const payload = bytes('{"user_id":"buyer-a","payment_intent_id":"intent-a"}'); + expect(merchant().apply(payload)).toBe(payload); + const legacy = PaymentInvokeContext.fromFlags({ + "payment-user-id": "buyer-a", + "payment-instrument-id": "instrument-a", + "payment-session-id": "session-a", + }); + expect(JSON.parse(text(legacy.apply(bytes("{}"))))).toEqual({ + user_id: "buyer-a", + payment_instrument_id: "instrument-a", + payment_session_id: "session-a", + }); + expect( + JSON.parse( + text(PaymentInvokeContext.fromFlags({ "payment-user-id": "buyer-a" }).apply(bytes("{}"))), + ), + ).toEqual({ user_id: "buyer-a" }); +}); +test.each([ + '{"user_id":"other-buyer"}', + '{"payment_intent_id":"other-intent"}', + '{"payment_session_id":"session-a"}', + '{"payment_instrument_id":null}', + '{"user_id":[]}', + '{"payment_session_id":" "}', + "[]", + "null", + '{"sensitive-callback":', +])("rejects incompatible payload safely: %s", (value) => { + const error = (() => { + try { + merchant().apply(bytes(value)); + } catch (error) { + return error as Error; + } + })(); + expect(error).toBeInstanceOf(Error); + expect(error?.cause).toBeUndefined(); + expect(String(error)).not.toContain("sensitive-callback"); +}); +test("flags require their own buyer and reject intent/legacy combination", () => { + expect(() => PaymentInvokeContext.fromFlags({ "payment-intent-id": "intent-a" })).toThrow( + "--payment-user-id", + ); + expect(() => PaymentInvokeContext.fromFlags({ "payment-user-id": " " })).toThrow(); + expect(() => + PaymentInvokeContext.fromFlags({ + "payment-user-id": "buyer", + "payment-intent-id": "intent", + "payment-session-id": "session", + }), + ).toThrow("legacy"); + const legacy = PaymentInvokeContext.fromFlags({ + "payment-user-id": "buyer", + "payment-session-id": "session", + }); + expect(() => legacy.apply(bytes('{"payment_intent_id":"intent"}'))).toThrow("legacy"); +}); +test("rejects invalid UTF-8, non-JSON media type and non-HTTP protocol", () => { + expect(() => merchant().apply(new Uint8Array([255]))).toThrow("UTF-8"); + expect(() => merchant().apply(bytes("{}"), "text/plain")).toThrow("application/json"); + expect(() => merchant().assertProtocol("MCP")).toThrow("HTTP"); + expect(() => merchant().assertProtocol("A2A")).toThrow("HTTP"); + expect( + JSON.parse(text(merchant().apply(bytes("{}"), "application/json; charset=utf-8"))), + ).toHaveProperty("user_id", "buyer-a"); +}); + +test.each([" buyer", "buyer ", "\tbuyer\n"])( + "rejects surrounding buyer whitespace before invocation without disclosing identity: %j", + (buyer) => { + expect(() => PaymentInvokeContext.fromFlags({ "payment-user-id": buyer })).toThrow( + "must not have surrounding whitespace", + ); + expect(() => merchant().apply(bytes(JSON.stringify({ user_id: buyer })))).toThrow( + "must not have surrounding whitespace", + ); + }, +); diff --git a/src/handlers/runtime/invoke/paymentContext.ts b/src/handlers/runtime/invoke/paymentContext.ts new file mode 100644 index 0000000000..db5969d463 --- /dev/null +++ b/src/handlers/runtime/invoke/paymentContext.ts @@ -0,0 +1,129 @@ +import z from "zod"; +import { InputValidationError } from "../../../errors"; +import { flag, type FlagsOf } from "../../../router"; + +const identifier = z + .string() + .refine((value) => value.trim().length > 0, "must not be blank") + .optional(); +const fields = { + "payment-user-id": "user_id", + "payment-intent-id": "payment_intent_id", + "payment-instrument-id": "payment_instrument_id", + "payment-session-id": "payment_session_id", +} as const; + +/** Application JSON context only: the application authenticates the buyer independently. */ +export class PaymentInvokeContext { + static readonly flags = [ + flag( + "payment-user-id", + "explicit payment buyer ID; separate from Runtime --user-id", + identifier.refine( + (value) => value === undefined || value === value.trim(), + "must not have surrounding whitespace", + ), + ), + flag("payment-intent-id", "merchant intent context (does not authorize a payment)", identifier), + flag("payment-instrument-id", "legacy payment instrument context", identifier), + flag("payment-session-id", "legacy payment session context", identifier), + ] as const; + + private constructor(private readonly values: Record) {} + + static fromFlags( + flags: Partial>, + ): PaymentInvokeContext { + const values: Record = {}; + for (const [flagName, key] of Object.entries(fields)) { + const value = flags[flagName as keyof typeof fields]; + if (value !== undefined) { + if (!value.trim()) throw new InputValidationError(`--${flagName} must not be blank`); + if (key === "user_id" && value !== value.trim()) { + throw new InputValidationError("--payment-user-id must not have surrounding whitespace"); + } + values[key] = value; + } + } + if (Object.keys(values).length && !values.user_id) { + throw new InputValidationError( + "Payment context requires explicit --payment-user-id; Runtime identity is separate", + ); + } + PaymentInvokeContext.validateCombination(values); + return new PaymentInvokeContext(values); + } + + get enabled(): boolean { + return Object.keys(this.values).length > 0; + } + + assertContentType(contentType: string | undefined): void { + if ( + this.enabled && + (contentType ?? "application/json").split(";")[0]!.trim().toLowerCase() !== "application/json" + ) { + throw new InputValidationError("Payment context requires an application/json payload"); + } + } + + assertProtocol(protocol: string | undefined): void { + if (this.enabled && protocol !== undefined && protocol !== "HTTP") { + throw new InputValidationError( + "Payment context is supported only for HTTP Runtime invocation", + ); + } + } + + apply(payload: Uint8Array, contentType?: string): Uint8Array { + if (!this.enabled) return payload; + this.assertContentType(contentType); + let text: string; + let body: Record; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(payload); + const parsed: unknown = JSON.parse(text); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(); + body = parsed as Record; + } catch { + throw new InputValidationError("Payment context requires a valid UTF-8 JSON object payload"); + } + for (const key of Object.values(fields)) { + if (Object.hasOwn(body, key) && (typeof body[key] !== "string" || !body[key].trim())) { + throw new InputValidationError(`Payment context field '${key}' must be a nonempty string`); + } + } + if (typeof body.user_id === "string" && body.user_id !== body.user_id.trim()) { + throw new InputValidationError( + "Payment context field 'user_id' must not have surrounding whitespace", + ); + } + for (const [key, value] of Object.entries(this.values)) { + if (Object.hasOwn(body, key) && body[key] !== value) { + throw new InputValidationError(`Payment context conflicts with payload field '${key}'`); + } + } + PaymentInvokeContext.validateCombination({ ...body, ...this.values }); + const additions = Object.entries(this.values).filter(([key]) => !Object.hasOwn(body, key)); + if (!additions.length) return payload; + // Append only new properties: reserializing the caller's JSON would round large numbers. + const end = text.lastIndexOf("}"); + const members = additions + .map(([key, value]) => `${JSON.stringify(key)}:${JSON.stringify(value)}`) + .join(","); + return new TextEncoder().encode( + text.slice(0, end) + (Object.keys(body).length ? "," : "") + members + text.slice(end), + ); + } + + private static validateCombination(values: Record): void { + if ( + values.payment_intent_id !== undefined && + (values.payment_instrument_id !== undefined || values.payment_session_id !== undefined) + ) { + throw new InputValidationError( + "Merchant payment intent context cannot be combined with legacy instrument/session context", + ); + } + } +} diff --git a/src/handlers/runtime/invoke/request.ts b/src/handlers/runtime/invoke/request.ts index 9f185de74e..2472e6acb4 100644 --- a/src/handlers/runtime/invoke/request.ts +++ b/src/handlers/runtime/invoke/request.ts @@ -13,7 +13,7 @@ export type RuntimeInvokeInput = Omit< RuntimeInvokeRequest, "accountId" | "qualifier" | "contentType" > & - Partial>; + Partial> & { paymentContext?: boolean }; const DEFAULT_RUNTIME_USER_ID = "default"; const CUSTOM_HEADER_PREFIX = "x-amzn-bedrock-agentcore-runtime-custom-"; @@ -144,7 +144,15 @@ export function normalizeRuntimeInvokeRequest( const customJwt = authorizer !== undefined && "customJWTAuthorizer" in authorizer; if (authorizer && !customJwt) throw new InputValidationError("Runtime uses an unsupported authorizer"); - const { runtimeId, qualifier, payload, contentType, applicationHeaders = [], ...modeled } = input; + const { + runtimeId, + qualifier, + payload, + contentType, + applicationHeaders = [], + paymentContext: _paymentContext, + ...modeled + } = input; if (customJwt && !modeled.bearerToken) { throw new InputValidationError("CUSTOM_JWT Runtime requires --bearer-token"); } @@ -152,7 +160,11 @@ export function normalizeRuntimeInvokeRequest( throw new InputValidationError("IAM Runtime does not accept --bearer-token"); } - const mcp = detail.protocolConfiguration?.serverProtocol === "MCP"; + const protocol = detail.protocolConfiguration?.serverProtocol; + if (input.paymentContext && protocol !== undefined && protocol !== "HTTP") { + throw new InputValidationError("Payment context is supported only for HTTP Runtime invocation"); + } + const mcp = protocol === "MCP"; const mcpValues = [ modeled.mcpSessionId, modeled.mcpProtocolVersion, diff --git a/src/projectSchemas/credential.test.ts b/src/projectSchemas/credential.test.ts index 4f215b1c42..38e4c4a9fe 100644 --- a/src/projectSchemas/credential.test.ts +++ b/src/projectSchemas/credential.test.ts @@ -98,6 +98,9 @@ describe("credential schema", () => { ); // The suffix must terminate the name; carrying it in the middle is fine. expect(credentialNameFieldSuffix("client-id-service")).toBeUndefined(); + // Payment-only fields are caught by the collision check instead, so existing names stay valid. + expect(credentialNameFieldSuffix("prod-environment")).toBeUndefined(); + expect(credentialNameFieldSuffix("stripe-restricted-key")).toBeUndefined(); }); it("derives the environment variables used by each credential type", () => { diff --git a/src/projectSchemas/credential.ts b/src/projectSchemas/credential.ts index 4389621a6b..f1a983c058 100644 --- a/src/projectSchemas/credential.ts +++ b/src/projectSchemas/credential.ts @@ -1,5 +1,5 @@ import z from "zod"; -import { PaymentProviderSchema } from "./payment"; +import { LegacyPaymentProviderSchema, type PaymentProvider } from "./payment"; // Max length and character set are the Identity service's own limits. The min // is temporarily raised above 1 so `add` never produces a name that the pinned // @aws/agentcore-cdk rejects at `build`; drop it back to 1 once a release that @@ -101,11 +101,53 @@ export const OAuthCredentialSchema = z } }); export type OAuthCredential = z.infer; -export const PaymentCredentialSchema = z.object({ +const paymentCredentialBase = { authorizerType: z.literal("PaymentCredentialProvider"), name: CredentialNameSchema, - provider: PaymentProviderSchema, -}); +}; +export const PaymentCredentialSchema = z.discriminatedUnion("provider", [ + z.object({ ...paymentCredentialBase, provider: LegacyPaymentProviderSchema }), + z + .object({ + ...paymentCredentialBase, + provider: z.literal("Stripe"), + secretRef: SecretReferenceSchema.optional(), + }) + .strict(), + z + .object({ + ...paymentCredentialBase, + provider: z.literal("PayPal"), + secretRef: SecretReferenceSchema.optional(), + }) + .strict(), + z + .object({ + ...paymentCredentialBase, + provider: z.literal("AmazonPay"), + secretRef: SecretReferenceSchema.optional(), + }) + .strict(), +]); + +export const PAYMENT_CREDENTIAL_FIELDS = { + CoinbaseCDP: ["_API_KEY_ID", "_API_KEY_SECRET", "_WALLET_SECRET"], + StripePrivy: ["_APP_ID", "_APP_SECRET", "_AUTHORIZATION_PRIVATE_KEY", "_AUTHORIZATION_ID"], + Stripe: ["_RESTRICTED_KEY", "_PUBLISHABLE_KEY"], + PayPal: ["_CLIENT_ID", "_CLIENT_SECRET", "_ENVIRONMENT"], + AmazonPay: [ + "_MERCHANT_ID", + "_STORE_ID", + "_AUTHORIZATION_TOKEN", + "_ENVIRONMENT", + "_AMAZON_PAY_REGION", + ], +} as const satisfies Record; +export const PAYMENT_EXTERNAL_SECRET_FIELD = { + Stripe: "_RESTRICTED_KEY", + PayPal: "_CLIENT_SECRET", + AmazonPay: "_AUTHORIZATION_TOKEN", +} as const; export type PaymentCredential = z.infer; export const CredentialSchema = z.discriminatedUnion("authorizerType", [ ApiKeyCredentialSchema, @@ -180,10 +222,13 @@ export function credentialEnvironmentVariableNames(credential: Credential): stri ? [] : [credentialEnvVarName(credential.name, "_CLIENT_SECRET")]; case "PaymentCredentialProvider": { - const suffixes = - credential.provider === "CoinbaseCDP" - ? ["_API_KEY_ID", "_API_KEY_SECRET", "_WALLET_SECRET"] - : ["_APP_ID", "_APP_SECRET", "_AUTHORIZATION_PRIVATE_KEY", "_AUTHORIZATION_ID"]; + const externalField = + "secretRef" in credential && credential.secretRef + ? PAYMENT_EXTERNAL_SECRET_FIELD[credential.provider] + : undefined; + const suffixes = PAYMENT_CREDENTIAL_FIELDS[credential.provider].filter( + (suffix) => suffix !== externalField, + ); return suffixes.map((suffix) => credentialEnvVarName(credential.name, suffix)); } } diff --git a/src/projectSchemas/payment.test.ts b/src/projectSchemas/payment.test.ts index 6a24c94d20..927d6c2112 100644 --- a/src/projectSchemas/payment.test.ts +++ b/src/projectSchemas/payment.test.ts @@ -125,3 +125,26 @@ describe("payment manager custom validation", () => { ).toBe(true); }); }); + +describe("AWS Billing connector schema", () => { + it("accepts billing without a credential in implicit or explicit manual mode", () => { + const connector = { name: "billing", provider: "AwsBilling" } as const; + expect(PaymentConnectorSchema.parse(connector)).toEqual(connector); + expect(PaymentConnectorSchema.parse({ ...connector, provisionMode: "MANUAL" })).toEqual({ + ...connector, + provisionMode: "MANUAL", + }); + }); + + it.each([ + { credentialName: "merchant-secret" }, + { provisionMode: "QUICK_CREATE" }, + { awsBillingIamRoleArn: "arn:aws:iam::123456789012:role/unexpected" }, + { roleArn: "arn:aws:iam::123456789012:role/unexpected" }, + ])("rejects billing credential, quick-create or role input %j", (extra) => { + expect( + PaymentConnectorSchema.safeParse({ name: "billing", provider: "AwsBilling", ...extra }) + .success, + ).toBe(false); + }); +}); diff --git a/src/projectSchemas/payment.ts b/src/projectSchemas/payment.ts index 6487751737..f6404362ea 100644 --- a/src/projectSchemas/payment.ts +++ b/src/projectSchemas/payment.ts @@ -1,6 +1,16 @@ import { AllowedScopeSchema, OidcDiscoveryUrlSchema } from "./auth"; import { z } from "zod"; -export const PaymentProviderSchema = z.enum(["CoinbaseCDP", "StripePrivy"]); +export const LegacyPaymentProviderSchema = z.enum(["CoinbaseCDP", "StripePrivy"]); +export type LegacyPaymentProvider = z.infer; +export const PaymentProviderSchema = z.enum([ + "CoinbaseCDP", + "StripePrivy", + "Stripe", + "PayPal", + "AmazonPay", +]); +export const PaymentEnvironmentSchema = z.enum(["SANDBOX", "LIVE"]); +export const AmazonPayRegionSchema = z.enum(["NA", "EU"]); export type PaymentProvider = z.infer; export const DEFAULT_AUTO_PAYMENT = true; export const DEFAULT_SPEND_LIMIT = "10.00"; @@ -40,7 +50,18 @@ export const QuickCreatePaymentConnectorSchema = z.object({ }); export type QuickCreatePaymentConnector = z.infer; +export const AwsBillingPaymentConnectorSchema = z + .object({ + name: PaymentConnectorNameSchema, + provider: z.literal("AwsBilling"), + provisionMode: z.literal("MANUAL").optional(), + credentialName: z.never().optional(), + }) + .strict(); +export type AwsBillingPaymentConnector = z.infer; + export const PaymentConnectorSchema = z.union([ + AwsBillingPaymentConnectorSchema, QuickCreatePaymentConnectorSchema, ManualPaymentConnectorSchema, ]); diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index fbba508331..b49f23dc2e 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -408,3 +408,34 @@ describe("project custom validation", () => { } }); }); + +test("AWS Billing skips credentials while other connectors still validate their references", () => { + const billing = { name: "billing", provider: "AwsBilling" } as const; + const result = ProjectSpecSchema.parse({ + ...minimalProject, + payments: [{ name: "payments", connectors: [billing] }], + }); + expect(result.credentials).toEqual([]); + expect(result.payments?.[0]?.connectors).toEqual([billing]); + + const mixed = ProjectSpecSchema.safeParse({ + ...minimalProject, + payments: [ + { + name: "payments", + connectors: [ + billing, + { name: "wallet", provider: "CoinbaseCDP", credentialName: "missing" }, + ], + }, + ], + }); + expect(mixed.success).toBe(false); + if (!mixed.success) { + expect(mixed.error.issues).toContainEqual( + expect.objectContaining({ + path: ["payments", 0, "connectors", 1, "credentialName"], + }), + ); + } +}); diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index 756e6eaec7..d95f3ae06d 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -236,7 +236,8 @@ export const ProjectSpecSchema = z } for (const [connectorIndex, connector] of payment.connectors.entries()) { - if (connector.provisionMode === "QUICK_CREATE") continue; + if (connector.provisionMode === "QUICK_CREATE" || connector.provider === "AwsBilling") + continue; const credential = spec.credentials.find((c) => c.name === connector.credentialName); if (!credential) { diff --git a/src/router/router.test.ts b/src/router/router.test.ts index 3fc0b5ebef..009f4cefab 100644 --- a/src/router/router.test.ts +++ b/src/router/router.test.ts @@ -1118,3 +1118,102 @@ test("a command without grouped flags leaves the generated help in Options", asy expect(out).not.toContain("Other options:"); expect(out).toContain("-h, --help"); }); + +test("defaultLeaf flags are local to the compatibility action, including before a child", async () => { + const log: string[] = []; + const fallback = createHandler({ + name: "group", + description: "", + flags: [flag("name", "", z.string())], + handle: async (_ctx, flags) => { + log.push(flags.name); + }, + }); + const group = new Router("group").defaultLeaf(fallback).handler( + createHandler({ + name: "child", + description: "", + flags: [flag("name", "", z.string())], + handle: async (_ctx, flags) => { + log.push(flags.name); + }, + }), + ); + const root = new Router("app").use(record(log, "middleware")).handler(group); + await root.route(["node", "app", "group", "--name", "legacy"]); + expect(log).toEqual(["middleware", "legacy"]); + log.length = 0; + await root.route(["node", "app", "group", "child", "--name", "typed"]); + expect(log).toEqual(["middleware", "typed"]); + log.length = 0; + await expect( + root.route(["node", "app", "group", "--name", "parent", "child", "--name", "child"]), + ).rejects.toThrow("cannot be combined"); + expect(log).toEqual([]); +}); + +test("defaultLeaf executes even before subcommands are registered", async () => { + let ran = false; + await new Router("app") + .defaultLeaf( + leaf("fallback", () => { + ran = true; + }), + ) + .route(["node", "app"]); + expect(ran).toBe(true); +}); + +test.each( + [ + ["--region", "r", "payment", "stripe", "--name", "n"], + ["payment", "stripe", "--name", "n", "--region", "r"], + ["payment", "--region", "r", "stripe", "--name", "n"], + ].map((args) => ({ args })), +)("defaultLeaf preserves legitimate globals at every position: $args", async ({ args }) => { + const region = globalFlag("region", "", z.string()); + let result: unknown; + const group = new Router("payment") + .defaultLeaf( + createHandler({ + name: "payment", + description: "", + flags: [flag("name", "", z.string())], + handle: async () => { + throw new Error("unexpected legacy dispatch"); + }, + }), + ) + .handler( + createHandler({ + name: "stripe", + description: "", + flags: [flag("name", "", z.string())], + handle: async (ctx, flags) => { + result = { name: flags.name, region: ctx.value(region) }; + }, + }), + ); + await new Router("app") + .groupFlags(region) + .handler(group) + .route(["node", "app", ...args]); + expect(result).toEqual({ name: "n", region: "r" }); +}); + +test("defaultLeaf compatibility command has no menu or screen of its own", () => { + const fallback = createHandler({ + name: "group", + description: "", + flags: [flag("name", "", z.string())], + handle: async () => {}, + }); + const group = compile( + new Router("group").defaultLeaf(fallback).handler(leaf("child", () => {})), + ValueContext.EmptyContext(), + ); + const internal = group.commands.find((command) => command.name() === "__compatibility")!; + expect(isTuiCommandSupported(group)).toBe(true); + expect(isTuiCommandSupported(internal)).toBe(false); + expect(group.helpInformation()).not.toContain("__compatibility"); +}); diff --git a/src/router/router.tsx b/src/router/router.tsx index cf7bf771e7..b66a70a44f 100644 --- a/src/router/router.tsx +++ b/src/router/router.tsx @@ -40,6 +40,7 @@ class RoutedCommand extends Command { // listedInMenu keeps a command without a screen in place in the parent's // menu instead of moving it below the command-line-only divider. listedInMenu = false; + compatibilityParent?: Command; constructor(readonly handler: Handler) { super(handler.name()); @@ -123,6 +124,19 @@ function declareFlags(c: Command, flags: Flag[]): void { } } +// Commander diagnostics can echo unknown option values or excess arguments. +// A compatibility family may accept secret sources, so reject parser errors +// without retaining raw argv in the error or writing it to stderr. +function protectCompatibilityParseErrors(command: Command): void { + command.configureOutput({ + outputError: () => { + throw new InputValidationError( + "Invalid command options or arguments; run --help for supported flags", + ); + }, + }); +} + function declareArguments(c: Command, args: Argument[]): void { for (const arg of args) { c.addArgument(toCommanderArgument(arg)); @@ -169,6 +183,12 @@ function attachAction( recordCommandPath(ctx); + if (command instanceof RoutedCommand && command.compatibilityParent && command.args.length) { + throw new InputValidationError( + `Compatibility options cannot be combined with a provider subcommand or positional arguments`, + ); + } + // A group's default action also receives positionals that matched no child. // Those are typos, not arguments, so they are named before the default runs. if (command.commands.length > 0 && command.args.length > 0) { @@ -242,8 +262,9 @@ export function compile( }); c.description(node.description()); + const fallback = isDefaultHandlerProvider(node) ? node.defaultHandler() : undefined; const ownFlags = node.flags(); - declareFlags(c, ownFlags); + declareFlags(c, [...ownFlags, ...(node.children().length ? [] : (fallback?.flags() ?? []))]); declareArguments(c, node.arguments()); if (ownFlags.some((f) => f.group)) { @@ -293,14 +314,44 @@ export function compile( const helpGroup = node.helpGroupOf(child.name()); if (helpGroup) childCommand.helpGroup(helpGroup); } + if (fallback?.flags().length) protectCompatibilityParseErrors(childCommand); c.addCommand(childCommand); } // A group may also carry a default handler that runs when it is invoked // without a subcommand. It executes with this group's own middleware and can // read this group's own globals (plus inherited ones) from the context; it - // has no own flags/arguments (globals-only). - const fallback = isDefaultHandlerProvider(node) ? node.defaultHandler() : undefined; - if (fallback) { + // parses its local flags only on this no-subcommand path. + if (fallback?.flags().length) { + // Commander routes unmatched options to this hidden default command. Its + // flags therefore never become parent/global options of the typed leaves. + // Keep the public group's path and metadata for middleware and the wizard. + const compatibility = new RoutedCommand(withEffectiveTuiSupport(fallback, false)); + protectCompatibilityParseErrors(c); + protectCompatibilityParseErrors(compatibility); + compatibility.name("__compatibility"); + compatibility.compatibilityParent = c; + compatibility.allowExcessArguments(); + declareFlags(compatibility, fallback.flags()); + compatibility.exitOverride((error) => { + recordCommandPath(ctx); + throw error; + }); + compatibility.helpInformation = () => c.helpInformation(); + c.addCommand(compatibility, { isDefault: true, hidden: true }); + c.hook("preSubcommand", (_parent, child) => { + if (child === compatibility && c.args[0] === compatibility.name()) { + throw new InputValidationError("Choose a documented provider subcommand"); + } + }); + attachAction( + compatibility, + withEffectiveTuiSupport(fallback, effectiveTuiSupport && fallback.doesSupportTui()), + ctx, + [...nextStack, ...(isMiddlewareProvider(fallback) ? fallback.middlewares() : [])], + childGlobals, + fallback.flags(), + ); + } else if (fallback) { c.allowExcessArguments(); attachAction( c, @@ -311,6 +362,15 @@ export function compile( [], ); } + } else if (fallback) { + attachAction( + c, + withEffectiveTuiSupport(fallback, effectiveTuiSupport && fallback.doesSupportTui()), + ctx, + [...nextStack, ...(isMiddlewareProvider(fallback) ? fallback.middlewares() : [])], + inheritedGlobals, + fallback.flags(), + ); } else { // Middleware wraps the node here; the wrapper's logic runs at leaf execution. attachAction(c, compiledNode, ctx, nextStack, inheritedGlobals, ownFlags); @@ -324,6 +384,7 @@ export class Router implements Handler, MiddlewareProvider, DefaultHandlerProvid private handlers: Handler[] = []; private globalFlags: GlobalFlag[] = []; private defaultHandle?: DefaultHandle; + private defaultLeafHandler?: Handler; private tuiCommandNames?: ReadonlySet; private sectionStarts = new Map(); private pendingSection?: string; @@ -417,10 +478,21 @@ export class Router implements Handler, MiddlewareProvider, DefaultHandlerProvid // subcommand (e.g. `agentcore` or `agentcore harness`). It reads group-level // flags from the context and has no own flags/arguments. default(fn: DefaultHandle): this { + this.defaultLeafHandler = undefined; this.defaultHandle = fn; return this; } + /** Preserve a flat command when adding subcommands, without inheriting its local flags. */ + defaultLeaf(handler: Handler): this { + if (handler.arguments().length || handler.children().length) { + throw new Error("A default leaf cannot declare arguments or children"); + } + this.defaultHandle = undefined; + this.defaultLeafHandler = handler; + return this; + } + // version makes a bare `--version`/`-V` on this router print the given // string and exit 0. It is handled before Commander parses (root command // only, like the original CLI) rather than registered as a Commander @@ -477,6 +549,7 @@ export class Router implements Handler, MiddlewareProvider, DefaultHandlerProvid // like Handler so compile() can wrap it in middleware and execute it uniformly. defaultHandler(): Handler | undefined { + if (this.defaultLeafHandler) return this.defaultLeafHandler; const fn = this.defaultHandle; if (!fn) return undefined; return { diff --git a/src/secrets/sensitiveKeys.test.ts b/src/secrets/sensitiveKeys.test.ts index f197cc5379..483fe7cf3b 100644 --- a/src/secrets/sensitiveKeys.test.ts +++ b/src/secrets/sensitiveKeys.test.ts @@ -8,7 +8,14 @@ test.each([ "PAYMENT_AUTHORIZATION_PRIVATE_KEY", "PAYMENT_APP_SECRET", "OAUTH_CLIENT_SECRET", + "AGENTCORE_CREDENTIAL_STRIPE_RESTRICTED_KEY", + "AGENTCORE_CREDENTIAL_AMAZON_AUTHORIZATION_TOKEN", "AGENTCORE_CREDENTIAL_MODEL", + // Payment identifiers are encrypted too: a readable-suffix list that grows would stop + // encrypting an existing secret such as an API key credential named prod-environment. + "AGENTCORE_CREDENTIAL_PROD_ENVIRONMENT", + "AGENTCORE_CREDENTIAL_STRIPE_PUBLISHABLE_KEY", + "AGENTCORE_CREDENTIAL_AMAZON_MERCHANT_ID", ])("encrypts secret-bearing variable %s", (name) => { expect(isSensitiveKey(name)).toBe(true); }); diff --git a/src/testing/TestCoreClient.tsx b/src/testing/TestCoreClient.tsx index 998921427e..a92b1e027e 100644 --- a/src/testing/TestCoreClient.tsx +++ b/src/testing/TestCoreClient.tsx @@ -158,6 +158,13 @@ import type { import type { GetPaymentInstrumentResponse, GetPaymentInstrumentBalanceResponse, + CreatePaymentIntentResponse, + CreateBuyerApprovalUrlResponse, + InitiatePaymentIntentResponse, + AuthorizePaymentIntentResponse, + CapturePaymentIntentResponse, + CancelPaymentIntentResponse, + GetPaymentIntentResponse, GetPaymentSessionResponse, ListPaymentInstrumentsResponse, ListPaymentSessionsResponse, @@ -1633,6 +1640,27 @@ export class TestPaymentClient implements CorePaymentClient { async rotatePaymentConnectorCredentials(): Promise { throw new Error("Unexpected payment call"); } + async createPaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } + async createBuyerApprovalUrl(): Promise { + throw new Error("Unexpected payment call"); + } + async initiatePaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } + async authorizePaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } + async capturePaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } + async cancelPaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } + async getPaymentIntent(): Promise { + throw new Error("Unexpected payment call"); + } async getPaymentSession(): Promise { throw new Error("Unexpected payment call"); } diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 272f1c0153..45736403b8 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -4,6 +4,7 @@ import { TAGS } from "./e2eTest/constants.ts"; export default defineConfig({ test: { include: ["e2eTest/**/**.test.ts"], + exclude: ["e2eTest/payment/**/*.test.ts"], setupFiles: ["./e2eTest/setup.ts"], tags: Object.values(TAGS).map((name) => ({ name })), reporters: ["verbose"], diff --git a/vitest.payment-e2e.config.ts b/vitest.payment-e2e.config.ts new file mode 100644 index 0000000000..7c50d01595 --- /dev/null +++ b/vitest.payment-e2e.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "vitest/config"; + +// Payment reads use pre-existing sandbox intents and must not run stack cleanup. +export default defineConfig({ + test: { + include: ["e2eTest/payment/**/*.test.ts"], + tags: [{ name: "payment" }], + reporters: ["verbose"], + }, +}); From 40ec0a24a155031e1a6bfef72f49ff07ea60f837 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 30 Nov 2026 19:53:46 +0000 Subject: [PATCH 15/19] chore(release): v1.4.0 --- command.md | 234 ++++++++++++++++++++++++++++++++++-- package.json | 2 +- src/assets/cdk/package.json | 2 +- 3 files changed, 226 insertions(+), 12 deletions(-) diff --git a/command.md b/command.md index 5a68c93a68..e3e1480730 100644 --- a/command.md +++ b/command.md @@ -2,7 +2,7 @@ # AgentCore CLI command reference -This reference was generated from `agentcore --help` for version `1.3.0`. +This reference was generated from `agentcore --help` for version `1.4.0`. ## Table of contents @@ -23,6 +23,11 @@ This reference was generated from `agentcore --help` for version `1.3.0`. - [`agentcore add credentials api-key`](#agentcore-add-credentials-api-key) - [`agentcore add credentials oauth`](#agentcore-add-credentials-oauth) - [`agentcore add credentials payment`](#agentcore-add-credentials-payment) + - [`agentcore add credentials payment stripe`](#agentcore-add-credentials-payment-stripe) + - [`agentcore add credentials payment paypal`](#agentcore-add-credentials-payment-paypal) + - [`agentcore add credentials payment amazon-pay`](#agentcore-add-credentials-payment-amazon-pay) + - [`agentcore add credentials payment coinbase-cdp`](#agentcore-add-credentials-payment-coinbase-cdp) + - [`agentcore add credentials payment stripe-privy`](#agentcore-add-credentials-payment-stripe-privy) - [`agentcore add memory`](#agentcore-add-memory) - [`agentcore add evaluator`](#agentcore-add-evaluator) - [`agentcore add evaluator llm-as-a-judge`](#agentcore-add-evaluator-llm-as-a-judge) @@ -221,6 +226,14 @@ This reference was generated from `agentcore --help` for version `1.3.0`. - [`agentcore payment instrument get`](#agentcore-payment-instrument-get) - [`agentcore payment instrument list`](#agentcore-payment-instrument-list) - [`agentcore payment instrument balance`](#agentcore-payment-instrument-balance) + - [`agentcore payment intent`](#agentcore-payment-intent) + - [`agentcore payment intent create`](#agentcore-payment-intent-create) + - [`agentcore payment intent get`](#agentcore-payment-intent-get) + - [`agentcore payment intent create-buyer-approval-url`](#agentcore-payment-intent-create-buyer-approval-url) + - [`agentcore payment intent initiate`](#agentcore-payment-intent-initiate) + - [`agentcore payment intent authorize`](#agentcore-payment-intent-authorize) + - [`agentcore payment intent capture`](#agentcore-payment-intent-capture) + - [`agentcore payment intent cancel`](#agentcore-payment-intent-cancel) - [CLI settings and feedback](#cli-settings-and-feedback) - [`agentcore feedback`](#agentcore-feedback) - [`agentcore config`](#agentcore-config) @@ -490,18 +503,86 @@ add an OAuth2 credential provider to the current project ##### `agentcore add credentials payment` ```text -agentcore add credentials payment [options] +agentcore add credentials payment [options] [command] ``` add a payment credential provider to the current project +###### `agentcore add credentials payment stripe` + +```text +agentcore add credentials payment stripe [options] +``` + +add Stripe credentials to the current project + +**Options** + +- `--name `: the name of the credential provider (required) +- `--restricted-key `: the Stripe restricted key (file://path or - for stdin; inline values are rejected) +- `--restricted-key-secret-reference `: external secret reference JSON: {"secretId":"<id-or-arn>","jsonKey":"<key>"} +- `--publishable-key `: optional Stripe publishable key + +###### `agentcore add credentials payment paypal` + +```text +agentcore add credentials payment paypal [options] +``` + +add PayPal credentials to the current project + +**Options** + +- `--name `: the name of the credential provider (required) +- `--client-id `: the PayPal REST application client ID +- `--client-secret `: the PayPal client secret (file://path or - for stdin; inline values are rejected) +- `--client-secret-reference `: external secret reference JSON: {"secretId":"<id-or-arn>","jsonKey":"<key>"} +- `--environment `: PayPal environment: SANDBOX or LIVE (no default) + +###### `agentcore add credentials payment amazon-pay` + +```text +agentcore add credentials payment amazon-pay [options] +``` + +add Amazon Pay credentials to the current project + +**Options** + +- `--name `: the name of the credential provider (required) +- `--merchant-id `: the Amazon Pay merchant ID +- `--store-id `: the Amazon Pay store ID +- `--authorization-token `: the Amazon Pay authorization token (file://path or - for stdin; inline values are rejected) +- `--authorization-token-secret-reference `: external secret reference JSON: {"secretId":"<id-or-arn>","jsonKey":"<key>"} +- `--environment `: Amazon Pay environment: SANDBOX or LIVE (no default) +- `--amazon-pay-region `: Amazon Pay merchant region: NA or EU (no default) + +###### `agentcore add credentials payment coinbase-cdp` + +```text +agentcore add credentials payment coinbase-cdp [options] +``` + +add CoinbaseCDP credentials to the current project + **Options** - `--name `: the name of the credential provider (required) -- `--provider `: the payment provider: CoinbaseCDP or StripePrivy (required) - `--api-key-id `: Coinbase CDP API key ID - `--api-key-secret `: Coinbase CDP API key secret (file://path or - for stdin; inline values are rejected) - `--wallet-secret `: Coinbase CDP wallet secret (file://path or - for stdin; inline values are rejected) + +###### `agentcore add credentials payment stripe-privy` + +```text +agentcore add credentials payment stripe-privy [options] +``` + +add StripePrivy credentials to the current project + +**Options** + +- `--name `: the name of the credential provider (required) - `--app-id `: Privy application ID - `--app-secret `: Privy application secret (file://path or - for stdin; inline values are rejected) - `--authorization-private-key `: Stripe/Privy authorization private key (file://path or - for stdin; inline values are rejected) @@ -646,6 +727,7 @@ add a connector to a project payment manager (not available in China regions) - `--manager `: the parent payment manager (required) - `--name `: the payment connector name (required) - `--credential `: an existing payment credential to reuse +- `--aws-billing`: create an AWS Marketplace billing connector (requires its service-linked role) (default: false) - `--quick-create`: create a CoinbaseCDP connector through Quick Create (default: false) ### `agentcore dev` @@ -697,6 +779,16 @@ invoke a Runtime, harness, or Gateway - `--target `: project deployment target (default: "default") - `--local`: invoke the local development server (project Runtime only) (default: false) - `--port `: local development server port (defaults: HTTP/AG-UI 8080, MCP 8000, A2A 9000) +- `--payment-user-id `: explicit payment buyer ID; separate from Runtime --user-id +- `--payment-intent-id `: merchant intent context (does not authorize a payment) +- `--payment-instrument-id `: legacy payment instrument context +- `--payment-session-id `: legacy payment session context +- `--mcp-method `: the MCP method +- `--mcp-name `: the MCP tool, resource, or prompt name +- `--trace-id `: the X-Ray trace ID +- `--trace-parent `: the W3C trace parent +- `--trace-state `: the W3C trace state +- `--baggage `: the W3C baggage - `--payload `: the inline payload to send - `--qualifier `: the Runtime endpoint qualifier - `--content-type `: the payload content type @@ -708,12 +800,6 @@ invoke a Runtime, harness, or Gateway - `--mcp-session-id `: the MCP session ID - `--mcp-protocol-version `: the MCP protocol version - `--output-file `: the response output file -- `--mcp-method `: the MCP method -- `--mcp-name `: the MCP tool, resource, or prompt name -- `--trace-id `: the X-Ray trace ID -- `--trace-parent `: the W3C trace parent -- `--trace-state `: the W3C trace state -- `--baggage `: the W3C baggage - `--prompt `: the message to send to the harness - `--path `: the path relative to the Gateway origin - `--method `: the HTTP request method @@ -1316,6 +1402,10 @@ invoke a Runtime **Options** +- `--payment-user-id `: explicit payment buyer ID; separate from Runtime --user-id +- `--payment-intent-id `: merchant intent context (does not authorize a payment) +- `--payment-instrument-id `: legacy payment instrument context +- `--payment-session-id `: legacy payment session context - `--id `: the ID of the Runtime (required) - `--payload `: the inline payload to send - `--qualifier `: the Runtime endpoint qualifier @@ -3017,7 +3107,7 @@ enable or disable an Agent Insight Store, or change its encryption key agentcore payment [options] [command] ``` -inspect payment managers, sessions, and instruments +inspect payment resources and manage intent lifecycles #### `agentcore payment manager` @@ -3200,6 +3290,130 @@ get a payment instrument's token balance on a specific chain - `--token `: the token to query (USDC) (default: "USDC") - `--agent-name `: optional observability label, not an agent selector +#### `agentcore payment intent` + +```text +agentcore payment intent [options] [command] +``` + +create, inspect and manage payment intents + +##### `agentcore payment intent create` + +```text +agentcore payment intent create [options] +``` + +create a merchant payment intent + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--connector-id `: the payment connector ID (required) +- `--capture-strategy `: INSTANT, FUTURE or SETUP (required) +- `--checkout-details `: checkout JSON object, file://<path>, or '-' for stdin (required) +- `--client-token `: idempotency token (33-256 letters, digits or hyphens); reuse for the same operation + +##### `agentcore payment intent get` + +```text +agentcore payment intent get [options] +``` + +get a payment intent by id + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--intent-id `: the payment intent ID (required) +- `--user-id `: the application user ID associated with the intent (required) +- `--agent-name `: optional observability label, not an agent selector + +##### `agentcore payment intent create-buyer-approval-url` + +```text +agentcore payment intent create-buyer-approval-url [options] +``` + +create an approval URL for delivery to the buyer UI + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--intent-id `: the payment intent ID (required) +- `--parent-origin `: the exact origin allowed to embed the buyer approval widget (required) +- `--client-token `: idempotency token (33-256 letters, digits or hyphens); reuse for the same operation + +##### `agentcore payment intent initiate` + +```text +agentcore payment intent initiate [options] +``` + +initiate an approved intent using developer/backend credentials + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--intent-id `: the payment intent ID (required) +- `--client-token `: idempotency token (33-256 letters, digits or hyphens); reuse for the same operation + +##### `agentcore payment intent authorize` + +```text +agentcore payment intent authorize [options] +``` + +authorize an initiated intent using developer/backend credentials + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--intent-id `: the payment intent ID (required) +- `--partner-callback-result `: sensitive partner callback from file://<path> or stdin '-' +- `--client-token `: idempotency token (33-256 letters, digits or hyphens); reuse for the same operation + +##### `agentcore payment intent capture` + +```text +agentcore payment intent capture [options] +``` + +capture authorized funds using developer/backend credentials + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--intent-id `: the payment intent ID (required) +- `--capture-amount `: optional amount JSON object, file://<path>, or stdin '-' (omitted: remainder) +- `--client-token `: caller-owned capture token (33-256 letters, digits or hyphens); reuse on retries, new token requests a new capture (required) + +##### `agentcore payment intent cancel` + +```text +agentcore payment intent cancel [options] +``` + +cancel a payment intent + +**Options** + +- `--manager-id `: the parent payment manager ID (required) +- `--user-id `: the application buyer ID (required independently of Runtime identity) (required) +- `--agent-name `: optional agent observability label +- `--intent-id `: the payment intent ID (required) +- `--client-token `: idempotency token (33-256 letters, digits or hyphens); reuse for the same operation + ## CLI settings and feedback ### `agentcore feedback` diff --git a/package.json b/package.json index cf56fdf8f3..445f52e65a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@aws/agentcore", - "version": "1.3.0", + "version": "1.4.0", "repository": { "type": "git", "url": "https://github.com/aws/agentcore-cli.git" diff --git a/src/assets/cdk/package.json b/src/assets/cdk/package.json index 244b5d9c75..e5b7fdb1e7 100644 --- a/src/assets/cdk/package.json +++ b/src/assets/cdk/package.json @@ -16,7 +16,7 @@ "typescript": "~5.9.3" }, "dependencies": { - "@aws/agentcore-cdk": "1.3.0", + "@aws/agentcore-cdk": "1.4.0", "aws-cdk-lib": "~2.269.0", "constructs": "~10.7.0" } From f23462e952f12c9db68e61616fc17da6ec749677 Mon Sep 17 00:00:00 2001 From: jariy17 Date: Mon, 30 Nov 2026 19:58:14 +0000 Subject: [PATCH 16/19] test(e2e): give project create 10 minutes on Windows The harness suite's beforeAll runs `create --template empty` with the 3-minute PROJECT_CREATE budget. On the Windows runner that create takes longer while the other E2E files run alongside it, so the hook times out and every harness test is skipped. It has failed this way on every v1.x push since 11/24. --- e2eTest/timeouts.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/e2eTest/timeouts.ts b/e2eTest/timeouts.ts index d2549b8eb4..cc0ceeb06d 100644 --- a/e2eTest/timeouts.ts +++ b/e2eTest/timeouts.ts @@ -1,5 +1,7 @@ export const TIMEOUT_MS = { - PROJECT_CREATE: 3 * 60 * 1000, + // The Windows runner takes over 3 minutes to create a project while the other + // E2E files run alongside it, which timed out the harness suite's beforeAll. + PROJECT_CREATE: (process.platform === "win32" ? 10 : 3) * 60 * 1000, PROJECT_DEV: 3 * 60 * 1000, PROJECT_DEPLOY: 10 * 60 * 1000, PROJECT_ADD: 3 * 60 * 1000, From 4ac7f3bb89ae4d8125c7011b4c18e6f62840f73c Mon Sep 17 00:00:00 2001 From: Varun Gunda <160568957+vvargu@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:22:20 -0800 Subject: [PATCH 17/19] feat(box): merge Box on Runtime from box-integration into v1.x (#2922) * fix(box): Scope the Box gateway role's Bedrock grant to the build region Addresses the review of #2850: the role could invoke any Bedrock model in any region. It may now invoke an inference profile of its own account in the region build builds for, a foundation model there, and a foundation model in another region only through an inference profile in that region, which is how a cross-region (us., global.) profile reaches it. * fix(deploy): Address the review of #2879 - Check every runtime that names a platformVersion after synth, V1 included and not only in a Box project (runtimePlatformVersions), each against its own value. - A runtime the stack exports no RuntimeId for gets its own message, since the cause may be a renamed export, not an old CDK library. - Test the schema's accepted and refused values, and the build refusal for a Box runtime with no platformVersion as well as V1. - The validation comment says the check runs before the runtime sync rewrites agentcore.json. * fix(build): Build for --region from the TUI too, and keep the writers' JSDoc on BOX_NETWORK_WRITERS Addresses the review of #2886: the build screen called build with no region, so a global --region was ignored there; it passes the region withRegion resolved, as the command does. * Revert "fix(box): Scope the Box gateway role's Bedrock grant to the build region" This reverts commit 6072b2c1. #2883 makes the same change and more (the region's partition, and the account in the inference-profile condition), and the two conflict, so the grant lands with #2883. * test(e2e): Skip the Box container dev test when no container tool runs from PATH Addresses the review of #2872: a capability check in place of CI && !linux. It also covers a local machine with no container tool, says nothing about Windows by accident, and runs the test once a runner gains one. * fix(build): Use the partition of the region in the Memory policy of the Box gateway The comment of leo237 on boxMemory.ts: boxMemoryPolicy wrote "arn:aws:bedrock-agentcore:" for each region. Thus `build` for cn-north-1 or us-gov-west-1 wrote a Bedrock policy with the correct partition, and a Memory policy with an incorrect partition. boxMemoryPolicy gets the partition from the region, with the partition data of the AWS SDK, the same as boxBedrockPolicy. Test: boxMemory.test.ts, "boxMemoryPolicy" > "names the partition of the region it is given", for cn-north-1 (aws-cn) and us-gov-west-1 (aws-us-gov). Before this change, the result of this test is incorrect. * test(box): Test a guardrails condition beside the temporal one, for the review comment on hostMap.test.ts * test(box): Drop the unused column of the rotated key test, for the review comment on boxNetworkWriters.test.ts * test(box): Compare the whole host or host:port of a warning, for the review nit on split in manager.boxNetwork.test.ts * fix(box): Give the agent no OTEL when DISABLE_ADOT_OBSERVABILITY is true (comment of Leo on additions.ts) * fix(build): Use the DNS suffix of the partition in the Box gateway hosts The comment of leo237 on shortcuts.ts: boxGatewayBedrockHost wrote "bedrock-runtime..amazonaws.com" for each region, and boxGatewayAgentCoreHost wrote "bedrock-agentcore..amazonaws.com". In the aws-cn partition, the DNS suffix is "amazonaws.com.cn". Thus, for `build` in cn-north-1, the `bedrock` and `agentcore` targets had an incorrect endpoint. Also, boxGatewayIamWarnings compared a target host with an incorrect host, and gave a warning for a correct China host. This problem was on box-integration before this PR. The 2 functions get the DNS suffix from the partition data of the AWS SDK, as boxBedrockPolicy gets the partition. Tests. Before this change, the result of each test is incorrect: - shortcuts.test.ts, "Box gateway targets" > "take the DNS suffix of the partition of the region": cn-north-1 gives amazonaws.com.cn, us-gov-west-1 and us-west-2 give amazonaws.com. - network.test.ts, "the Bedrock and Memory files grant the amazonaws.com.cn hosts of a build for China": no warning. A constant "amazonaws.com" in each of the 2 functions gives an incorrect result in the 2 tests. * docs(e2e): Rewrap the container-tool sentence, and say a stopped tool still counts * fix(deploy): Say that no released @aws/agentcore-cdk supports platformVersion yet * test(tui): Check that the build screen builds for the launch region * fix(build): read no .env.local key for a box route the credential planner skips boxKeyVariables now drops a model-provider route and a route whose variable an existing credential reserves, through the same predicate planBoxProfileCredentials uses. * refactor(box): move the reserved Box target name check to boxMemory The check now tests the egress- prefix with a plain startsWith, so it does not depend on the signature of isManagedTarget. boxMemory already owns the bedrock and agentcore names and imports isBoundGateway. The import of BOX_EGRESS_TARGET_PREFIX from boxNetwork/egress makes no runtime import cycle. The comment now gives only the reason that stays true: a user target of such a name takes the agent's Bedrock or Memory route, or the name of an egress target that build writes. * test(build): generate the two stop cases of the box credential build with test.each * refactor(build): drop the no-routes guard of boxKeyReads With no routes, select rejects every name, so the read decrypts nothing and returns no entry. * fix(box): refuse build-owned target names only for a runtime that runs in a box Build writes the bedrock, agentcore and egress- targets only on the Box gateway of a runtime that runtimeRunsInBox accepts. The check gated on isBoundGateway, so it also refused these names on a bound gateway whose runtime does not run in a box, with a reason that is not true there. The tests give the runtime a box.version, and a new test adds the three names on a bound gateway whose runtime has no box.version. * test(box): run each build-owned target name in its own project The refusal and acceptance tests now use test.each over the three names, with a new project for each name, so a failure names the target name and no state carries over from another name. * test(box): check build's Box gateway targets in the schema tests The test that build's bedrock, agentcore and egress- targets stay valid on a Box gateway tests ProjectSpecSchema, not add gateway-target: it passed with the name check removed. It is now a schema test in project.test.ts, where no test covered these targets before. * fix(build): report the box credential skip and missing-key messages as warnings planBoxProfileCredentials returns them in a separate warnings list, and build emits them as warning events. Progress messages stay steps. * fix(build): say "an OAuthCredentialProvider credential" in the box egress skip warning * refactor(tui): use isBoundGateway in boundRuntimeNote The wizard note now asks isBoundGateway whether a gateway is bound, as the rest of the code does, and does not check boundRuntime itself. * test(build): fold the box credential skip tests into one test.each, on schema-parsed specs The Secrets Manager fixture now uses a valid secretRef, which the old cast hid. A payment credential row covers the article of the warning. * refactor(tui): build the bound gateway lines of remove runtime in one function removedGatewayLines and boundGatewayWarningLines were near copies. One function, boundGatewayLines, now makes both: the lines before the removal name each bound gateway and its targets, and the lines after it name each removed gateway and its target count. The text does not change. A new unit test pins each form for zero, one and more targets. * fix(build): warn when the shell's reserved credential variable differs from the box route's key Deploy provisions the reserved variable, but agentcore dev hands box the route's variable. Build now warns when the two hold different keys. * fix(build): say when build fills in a blank stored box credential key * refactor(box): Keep the targets build owns in one function, for the Chorus note on PR 2887 * fix(box): Drop the record entry of each Box gateway that remove runtime or remove all deletes, for the Chorus note on manager.tsx line 1270 * docs(box): Say that build provisions a model-provider key from the shell, for the Chorus note on item 10 * fix(box): Give equal path patterns one machine, for the Chorus nit on pathSolver.ts * fix(gateway): refuse a bound NONE gateway in a Box project, explain a 403 Companion to aws/agentcore-l3-cdk-constructs#476. That change gives each Box gateway a resource policy that lets only its runtime's execution role invoke it. The project schema now refuses authorizerType "NONE" on a gateway with boundRuntime in a Box project. A Box gateway holds its runtime's outbound credentials, and with NONE anyone with its URL could call it. The L3 schema has the same check and the same message. The CLI writes AWS_IAM for each Box gateway, so only a hand edit hits this. `agentcore gateway invoke` now explains an HTTP 403 from an AWS_IAM gateway. The resource policy denies every other principal, so a developer's own credentials get AccessDenied on a Box gateway, even with administrator access. The command line writes the hint to stderr, and the TUI shows it as the note of the failed exchange. * feat(box): Send a boxed agent's Memory calls to Memory directly The Box gateway signed the agent's Memory calls with its own role. Memory then could not hold each call to the session of the runtime by its context keys, so one session could read or write the memory of another session. Build now adds no `agentcore` target to the Box gateway, and writes no `agentcore/box-memory-policy.json` for the gateway role. The Runtime profile gets a direct `[egress.agentcore]` route to the AgentCore host of the build region. Box signs that route with a bare `aws://`, the execution role, and the route has no gateway backend. The execution role already has the Memory data-plane grants, because the runtime binds its Memory. The route is added only for a runtime with its default Memory. A route or HTTP MCP server of the profile that already has the AgentCore host keeps it. A user route named `agentcore` for another host stops build. When AgentCore Gateway can get the session from the context keys, Memory calls can go through the gateway again. * fix(box): Keep the record and agentcore.json the same when either write fails, for the review nit on manager.tsx * fix(box): Change the record in commitSpec, after remove all removes its keys, for the review nit on manager.tsx line 1360 * test(box): Make the record write fail through an injected writer on every OS, for the review nit on manager.box.test.ts line 1015 * fix(box): Remove the Memory gateway access that an earlier build wrote A project that an earlier build wrote kept the `agentcore` target on its Box gateway and `agentcore/box-memory-policy.json` in the gateway's additionalPolicies and on disk. The gateway rule kept that target as the user's, so the Memory calls still went through the gateway role, and the IAM check read the old file as a user policy and gave no warning. Build now removes the `agentcore` target when it is as the earlier build wrote it for some region, removes the policy listing, and removes the policy file. A target of that name that the user changed stays, and build then stops until the user renames it, because its route would take the name of the Memory route. The Memory route rule now defers only to a direct route or HTTP MCP server to the Memory host. A route through the Box gateway stops build with RUNTIME_MEMORY_THROUGH_GATEWAY. The rule matches the host with `:443`, in any case, and as a `*.` wildcard. The README and the local testing guide now say that Memory calls go to Memory directly, and that a runtime in VPC network mode needs a `bedrock-agentcore` VPC endpoint. * ci(e2e): Refuse a malformed pinned box hash before checking the archive Addresses the review of #2872: macOS's sha256sum passes a checksum line whose hash is malformed (empty, short, or not hex), so a broken pin skipped the check. The step now refuses a pin that is not 64 hex characters. * fix(box): Pin box to the public strands-agents/box v0.3.0 release AppSec H1 (V2414030352): box shipped to customer runtimes from a personal GitHub account. Pin the box-cli archives of strands-agents/box v0.3.0, the first public release with the Boxy CLI, and its SHA-256s. - bump-box-release.ts pins the box-cli-v- archive, which holds box, its helpers, its packs and release.json. The release's box-v-* archives hold no packs. - BOX_MINIMUM_VERSION is 0.3.0, the first public box that reads the profiles the CLI writes; the old minimum has no public release page. - @box/base in 0.3.0 has no uname tool and refuses a [tool.uname] table with no command, so the CodeZip profile no longer writes one. - README and docs/box-local-testing.md download from strands-agents/box, and use aws configure sso instead of ada and Isengard. * fix(box): Pin the macOS box build to v0.3.0-preview.1 The macOS box of v0.3.0 has a broken code signature (codesign reports an invalid Info.plist), so macOS kills it at launch. Keep Linux, which ships to AgentCore Runtime, on v0.3.0, and let the darwin build name its own release: boxRelease.json gains darwin.version, bump-box-release.ts takes --darwin-box, and the e2e workflow installs each build from its own release. The minimum box is 0.3.0-preview.1, which the macOS pin satisfies. * feat(deploy): refuse Box projects in regions without AgentCore Runtime V2 Box runs only on AgentCore Runtime V2 (platformVersion V2). Deploy now refuses a Box project whose target is in a region without V2 (ap-south-2, us-west-1, GovCloud, and the isolated partitions), before the runtime sync rewrites agentcore.json. Other regions, including new ones the CLI does not know, are allowed. * docs(deploy): cite the AgentCore Runtime team for the Runtime V2 region list * fix(deploy): Address the review of #2878 - Refuse a Box project before deploy provisions the default target, so an unsupported --region makes no STS call and writes no aws-targets.json. - Add aws-iso-e to the partitions with no Runtime V2, and say that the European Sovereign Cloud counts as having it, as an unknown region does. - The error names both ways out: change the target's region, or deploy with --target to another target; for the default target, --region. * feat(create): warn about a box template in a region without Runtime V2 create with a box template in a region where AgentCore Runtime has no V2 now warns that the project cannot be deployed there, from the CLI and the wizard alike. It still creates the project: the region at create is often only the one the CLI resolved, and the project can deploy to a target in another region. Deploy stays the hard stop. * test(deploy): Cover the post-synth platformVersion check in CdkBackend.deploy Addresses the review of #2879: deleting the assertPlatformVersions call left every test passing. A deploy test with a V2 runtime whose synthesized template has no PlatformVersion now fails without it. * fix(box): Sign only the /memories path on the direct Memory route, and send a profile route to the host directly The direct Memory route opened every API of the AgentCore data-plane host to the execution role, such as the identity and API key calls. It now names `bedrock-agentcore..amazonaws.com/memories`, so box signs only the Memory calls. A call to another API of the host goes unsigned, and AgentCore refuses it. A route of the profile to the AgentCore host that the gateway rule sends through the Box gateway stopped build with RUNTIME_MEMORY_THROUGH_GATEWAY. That broke profiles that need the host under `agentcore dev`, for Code Interpreter or Browser. On the Runtime such a route now goes to the host directly, signed with a bare `aws://`, with its name and other keys, and build warns that it signs every API of the host. Box refuses the Memory route beside a signed route that covers its path, so build adds none there. A direct route to the host that box does not sign with `aws://` gets a warning, as the Memory calls then fail. Build keeps the Memory policy file of an earlier build while a gateway that is not a Box gateway lists it. The upgrade test now builds twice. The reserved Box gateway target names keep `agentcore`, now as the name of the Memory route. The README and the local testing guide say that box signs only `/memories`, and that a PRIVATE_VPC runtime needs the secure VPC's AgentCore endpoint. * refactor(box): Check that every Box runtime runs on Runtime V2 in the project schema Addresses the review of #2879: the rule reads projectType and a runtime field, like the other cross-resource Box rules in ProjectSpecSchema, so it moves there from build and deploy. Every command that reads agentcore.json now stops on a Box runtime without "platformVersion": "V2", and zod reports it with the project's other problems at once. The build and deploy call sites, which conflicted with #2878, go. Box is unreleased, so an existing Box project without the field is not migrated: add the field, or create the project again. * fix(deploy): Let a Box project with no box runtime deploy anywhere, and name --target when there are targets Addresses Tejas's review of #2878: - A Box project with no runtime was refused in a region without Runtime V2, and deploying an empty project is how its stack is removed, so a stack deployed there by an earlier build could not be torn down. The check now refuses only when a runtime runs in a box. - For the default target, the message names --target when aws-targets.json already has targets, instead of saying to add one. - The Box region tests get their own describe, with one region: the region list itself is partition.test.ts's. * fix(box): Write no gateway target for a host that the Runtime profile sends directly A route of the profile to the AgentCore host goes to the host directly on AgentCore Runtime when the runtime has its default Memory. Build still wrote the host's `egress-` gateway target, which the Runtime did not use, and the gateway IAM check then warned about the gateway role's grants for it. The gateway targets writer now writes a managed target only when a route or MCP server of the derived Runtime profile sends calls to it through a backend. A target that an earlier build wrote for a host that now goes directly is removed, with a step message that says why. * refactor(box): Address Tejas's review of #2886 - withEvents in events.ts replaces eventsWhile: withOutputEvents is now the case of an operation that emits lines. - stageBoxImage, stageBoxContainers and the container dev runner read BOX_RELEASE in place, as no caller passes another release. - The deployed egress test retries only its invoke, so a failed call does not deploy and remove the stack again. - e2eTest/README.md says CI runs only the dev egress test, and the testing guide says the CLI does not check the local box version. - Two loops in boxProfileCredentials.test.ts are test.each. * refactor(box): Remove the cleanup of what an earlier build wrote for Memory Box on AgentCore Runtime is not launched yet, and a Box project built before this change can be discarded. So build no longer removes the `agentcore` gateway target, the `agentcore/box-memory-policy.json` listing, or that file from an earlier build. A user target named `agentcore` still stops build, because its route would take the name of the Memory route. * fix(box): Write the record of build's targets with the gateway edits in build, for the review follow-up on boxNetworkWriters.ts * docs(box): Say how the record of build's targets and the reserved target names of add gateway-target work together * feat(box): Keep the box of a runtime with its default Memory to /memories on the AgentCore host On AgentCore Runtime the box of a runtime with its default Memory now reaches the AgentCore data-plane host only for Memory. Code Interpreter, Browser, identity, and API key calls on that host are blocked inside the box. - Build writes agentcore-memory-paths.dw beside the Runtime profile and lists it last in `policies`. Its first rule denies each request to the host whose path is not /memories or under it. Its second denies a path that could leave /memories once AWS normalizes it: a `..` or `.` segment, an encoded dot, or an encoded backslash. No Memory, actor, session, or record ID holds a dot or a backslash. - A route or HTTP MCP server of the profile to the AgentCore host, and a permit that names it, now stop build with RUNTIME_AGENTCORE_HOST_ROUTED. Box refuses a gateway route for a host that has another route, and a route of its own would reach the other APIs of the host. The problem names the entry or the permit of the local profile. Build no longer sends such a route to the host directly. - A user policy file of the same name stops build. The profile header names the policy file only when the profile lists it. * fix(box): Also block an encoded percent on the AgentCore host Box decodes %2e once before the policy, so a double-encoded %252e reaches the policy as %2e and passes it. No Memory, actor, session, or record ID holds a %, so the dot-segment rule now also blocks %25 on the AgentCore host. * fix(box): Send macOS to the box release whose build runs, and name the box-cli archive The install hint and the profile errors said to download the build for the machine from v0.3.0. Its macOS build does not run, so on macOS they now name the darwin pin's archive and release. They also name the box-cli archive, since the release's box-v archives have no packs. * fix(deploy): Refuse any runtime that asks for Runtime V2 in a region without it, by name Addresses Tejas's review of #2878 (point 2): with platformVersion in the schema, a runtime outside a Box project could ask for V2, pass the region check, and fail in CloudFormation partway through the deploy. The check now refuses each runtime with "platformVersion": "V2" and names it. Every Box runtime asks for V2, as the project schema requires, so Box projects are covered, and an empty project still deploys, which is how its stack is removed. * chore(box): Drop the references to box 0.1.11 and its ffi shim Every box the CLI supports is 0.3.0-preview.1 or later, so: - The open routes of box profile show are a list. The one-string form, which only box 0.1.11-linux-preview.6 printed, and its fixture go. - Comments name no 0.1.11 release, and the e2e README drops its stale note about an ffi shim pin. - The fake release of the boxRelease tests uses the pinned repository and version instead of made-up ones. * feat(box): Send every call of the box to the AgentCore host directly, with no path limit Box chooses where a connection goes from its host and port alone, before it sees the path, so it cannot send /memories directly and Code Interpreter or Browser through the Box gateway on one host. Code Interpreter, Browser, and the other AgentCore primitives are egress destinations on the same host as Memory, so for a runtime with its default Memory they all go to that host directly, signed with the execution role. - [egress.agentcore] now names the whole AgentCore data-plane host, not only /memories. - Build no longer writes agentcore-memory-paths.dw or lists it in policies. - A route or HTTP MCP server of the profile to the AgentCore host no longer stops build. It goes to the host directly, signed with a bare aws://, with its name and other keys, and build adds no second route beside it. What the execution role may call on that host depends on its grants. The README and the profile header say that these calls go to the host directly. * docs(box): Say that a boxed runtime with Memory needs the L3 Memory grant and data-plane endpoint * docs(box): Link the L3 PR that a boxed runtime with Memory needs * feat(box): Forbid the AWS instance metadata service in every box profile Box adds no cloud metadata rule to a profile, so a boxed agent was kept from IMDS only by default deny: a route or rule the user added could open it. On AgentCore Runtime, MMDS at 169.254.169.254 serves the execution role's credentials. agentcore create and add runtime now write .box//local/aws-metadata-block.dw beside the box profile, and the profile lists it under policies. Its two forbids on net:connect refuse 169.254.169.254, fd00:ec2::254, instance-data and instance-data.ec2.internal. Build already stages each policies file into .box-dist/, so the rules hold on the Runtime, CodeZip and container. The file is written before the profile, so a failed write leaves no profile that names a missing file, and it replaces a file already there. The host map leaves the aws_metadata_* rules out of the limits it reports, since an address forbid could hold for any host before DNS resolution and would warn for every host. Comments that said Box writes metadata rules into every profile now say it does not. * fix(box): Sign in to Bedrock with the api-key route of @box/bedrock on the Runtime Box 0.3 (#690 of the box CLI) makes @box/bedrock sign each Bedrock call with aws:// by default, under a new bedrock.sign-in input. On the Runtime, the Bedrock route goes through a Box gateway backend, and box refuses a signed secret beside a backend ("a destination secret beside a backend must be env://"), so box exited before the agent started and each invoke timed out at 30s. The Runtime profile now sets bedrock.sign-in = "api-key", beside bedrock.region, and the gateway rule writes the Bedrock route as [egress.bedrock-api-key], the pack's route for that sign-in. Its env:// secret is one box replaces with a stand-in and strips; the gateway signs the call with its own role. The local profile keeps aws://, so agentcore dev signs with the developer's credentials as before. * test(migrate): Give the two slowest apply tests 30s On GitHub-hosted Windows runners, "on a terminal, asks first and applies on yes" took 5258 ms and failed verify / Windows at bun's 5 s default; "--yes never applies a plan that isn't ready" took 3975 ms. As #2900 did for the Toolkit loading test, give each 30 s. * fix(box): Grant the standard library of the Runtime Python on CodeZip, not its prefix A CodeZip box runtime does not start on AgentCore Runtime. box stops with this error: `[agent] filesystem entry "/usr" is refused: ... a system root is never a grantable tree` The Runtime profile moves the read grant and the exec grant of the uv Pythons of the local profile to `${{ inputs.python.prefix }}`. start.py sets this input to `sys.base_prefix`. The Python of a PYTHON_3_14 Runtime is `/usr/bin/python3.14`. Thus the value is `/usr`. Box Core refuses a grant of `/usr`, and each Box Core release refuses it. Thus box did not start on a CodeZip Runtime before this change. Before [4700b621](https://github.com/aws/agentcore-cli/commit/4700b6215d6c49933263401958dac0606e3ba171), start.sh started the agent with no box when box did not start. That commit and [aws/agentcore-cli#2853](https://github.com/aws/agentcore-cli/pull/2853) removed this fallback. At this time, the Runtime stops the runtime, and the deploy stops with an error. The branch box-integration-development has the same problem. With this change, the uv Pythons of the local profile go to the standard library of the Runtime Python, `${{ inputs.python.stdlib }}`, and not to its prefix. - start.py exports `BOX_PYTHON_STDLIB`, the value of `sysconfig.get_path("stdlib")`, in place of `BOX_PYTHON_PREFIX`. On a PYTHON_3_14 Runtime, the value is `/usr/lib/python3.14`. - The `@box/agentcore-codezip` pack has the input `python.stdlib` in place of `python.prefix`, with the same pattern. - The paths rule moves `${{ home }}/.local/share/uv/python` to `${{ inputs.python.stdlib }}`. After this change, the Runtime profile of each CodeZip template has these grants: - `read = [code folder, standard library, "/usr/lib64", "/lib64"]`. The Python reads its modules. `/usr/lib64` contains the libraries that its native modules use, for example `libssl.so.3`. - `exec = [code folder, standard library]`. box mounts a folder that is not a loader folder with no exec. Thus the Python can use the native modules in `lib-dynload` only with this grant. - The Python itself is the command of the agent, and box gives it exec. A read grant of the loader folder `/usr/lib` also lets the Python start. This change does not use it, because it gives read and exec on all of `/usr/lib`, and not only on the standard library. A CodeZip box runtime that `agentcore create` made before this change has a start.py that exports the prefix. Copy the start.py of this change into its code folder. - `start.py > gives box the standard library of the Runtime's Python, and not its base prefix` (`boxStartPy.test.ts`) starts `main()` of start.py, and replaces `os.execve` with a function that records the environment. It makes sure that `BOX_PYTHON_STDLIB` is the standard library, and that no value is the prefix. - `the Runtime profile of each CodeZip box template of create` (`additions.test.ts`) derives the Runtime profile of the six CodeZip box templates. It makes sure that the read grant and the exec grant of the standard library are in the profile. It also makes sure that no grant has a value on the Runtime that Box Core refuses: a system root in a list, or a loader folder in a list that is not `read`. - The pack test makes sure that the pack has the input `python.stdlib`. The paths test and the test of the recorded profiles in `old-renderer-tables.json` use the standard library. In that file, only these 204 values change. - On the code before this change, 115 of the new and changed tests show an error. - Five mutations of the code, and the errors that each mutation causes: - start.py exports the prefix again: the start.py test shows an error. - The paths rule moves the uv Pythons to the prefix again: 111 tests show an error. - The pack has `python.prefix` again: 2 pack tests show an error. - `runtimeCodeZipRunner` gives no exec grant of the uv Pythons: 110 tests show an error. - `runtimeCodeZipRunner` also gives a grant of the prefix: the six template tests show an error at the check of the refused grants. - `bun test`: `5835 pass`, `6 skip`, `2 fail`. This change does not cause the two errors. `boxProfileResolver.test.ts` also shows the error on box-integration with the same box (0.1.11-preview.10) on PATH. `remove/index.test.ts` stops at its 10 s timeout when all tests operate together. When it operates with no other test, it shows no error. - `bun run typecheck`, `bun run lint:check`, `bun run format:check`, `bun run build`, `bun run audit`, and `bun run secrets:check`: no errors. - A local test in an Amazon Linux 2023 arm64 container, with box 0.1.11-preview.10 and a Python 3.14.3 that has the prefix `/usr` and the standard library `/usr/lib/python3.14`. The Python of the Runtime has the same paths. The results: - The zip of box-integration stops with the `/usr` refusal. - The zip of this change starts the agent, and `/ping` gives 200. - The zip of box-integration-development stops with the `/usr` refusal. - A live test on AgentCore Runtime in a dev account. In the test, we deploy a new CodeZip box project of this branch, with no change. Three invocations get status 200, and the box records are in the log group `-DEFAULT` of the runtime. The test removes all its resources. We did not do `bun run test:e2e`. This change has no test on the CodeZip Runtimes PYTHON_3_10 to PYTHON_3_13, and no test of an `[mcp]` server or a `[tool]` on the Runtime Python. (cherry picked from commit 490c197266ba5bf426342da4dcdf75db5f8dad20) * test(box): Pass otel to createdRuntime in the CodeZip stdlib grant test createdRuntime on box-integration takes the otel flag. The box templates write enableOtel false, so the test passes false. * feat(box): Let a boxed agent use the MCP tools of the other gateways of its project A runtime without a box gets the URL of each gateway of its project in `AGENTCORE_GATEWAY__URL`, and its code uses the MCP tools of that gateway. A boxed agent on AgentCore Runtime cannot do this. Its box has no route to the host of the gateway, so the box refuses each request. The user cannot add the route. Build refuses `aws://` for a gateway host with `UNSIGNABLE_HOST`, and the ID of the gateway is not known before the first deploy. A target and a grant that you make by hand operate, but build does not keep them in `agentcore.json`. - **Which gateways.** A box runtime gets each gateway without `boundRuntime`, the same gateways that the L3 binds to a runtime without a box (`projectGatewaysOf`). A `PRIVATE_VPC` runtime gets none. A `CUSTOM_JWT` gateway gets a warning and no target, because the Box gateway signs only with its role. - **The target.** Build writes `egress-gateway-` on the Box gateway of the runtime, with `passthrough.gateway: ""` and `GATEWAY_IAM_ROLE` for `bedrock-agentcore` in the build region. A `NONE` gateway gets no outbound auth. Build changes and removes the target as it does each other `egress-` target. A host of the profile cannot use its name (`TARGET_NAME_COLLISION`), and the limit of 100 targets counts it. - **The schema.** `passthrough` can have `gateway` or `endpoint`, but not the two. The name must be a gateway of the project without `boundRuntime`, and not the gateway of the target. - **The pack.** The `@box/agentcore` pack of each box runtime declares `gateways..url` from `env:_URL` and `gateways..host` from `env:_HOST`, each with a pattern. The agent gets `_URL` in `[agent.env]` from the input, so the code that uses the gateway without a box operates in the box. - **The Runtime profile.** Only the Runtime profile gets `[mcp.]`, with `destinations = ["${{ inputs.gateways..host }}"]` and one backend to the URL of the Box gateway and `/egress-gateway-`, signed with `aws://` for `bedrock-agentcore`. Box adds a permit for each tool of a declared server, and a forbid rule of the policy stays. The local profile does not change. A server of the local profile with the name of a gateway stops build (`RUNTIME_GATEWAY_SERVER_NAME_TAKEN`). - **Gateway hosts in the profile.** `AWS_ENDPOINTS` has the gateway host, with the service `bedrock-agentcore`. An entry that signs for a gateway host with `aws://` stops build with `UNSIGNABLE_HOST`, and the message names the route that build adds. Build cannot tell a gateway of this project from a gateway of a different project by its host, because the ID of a gateway is known only after deploy. - **IAM warnings.** `boxGatewayIamWarnings` gives no warning for a target with `passthrough.gateway`, because the L3 gives the grant. It gives a warning for a target to a gateway host when the role has no `bedrock-agentcore:InvokeGateway`. - **Interfaces that changed.** `PassthroughConfigSchema` (`endpoint` is optional, `gateway` is new), `BoxNetwork.projectGateways`, `RuntimeProfileContext.projectGateways`, `renderAgentCorePack(spec, gateways)`, and the problem code `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. - **Dependency.** The target needs the L3 branch `sa/box-gateway-to-gateway` of aws/agentcore-l3-cdk-constructs. That branch gives the endpoint, the grant, and `_HOST`. - **Not done.** box 0.1.11-preview.10 takes an input in `destinations` only when its value is a host. Thus the pack reads `_HOST` and not the URL. If the CLI wrote the target from `deployed-state.json`, each new project must deploy two times. - `src/core/project/boxNetwork/network.test.ts`, "the gateways of the project": the gateways that the agent gets, a `PRIVATE_VPC` runtime, a `CUSTOM_JWT` gateway, the name collision, the target that build wrote, the limit of 100, and the refusal of a signed gateway host in `[egress]` and `[mcp]`. "boxGatewayIamWarnings for a gateway of the project" pins the two warnings. - `src/core/project/boxNetworkWriters.test.ts`, "gatewayTargetsWriter for the gateways of the project": the writer adds, changes, and removes the target. "stages the inputs of each gateway that the agent calls in the @box/agentcore pack" pins the staged pack. - `src/core/project/runtimeProfile/rules/gateway.test.ts`, "the gateway rule for a gateway of the project": the `[mcp.]` server, no server with no gateway, and the stop for a server name that a gateway has. - `src/core/project/templates/boxProfile.test.ts`, "for a gateway of the project that the agent calls" (a test name): the two inputs, the agent variable, and the host and URL patterns. - `src/projectSchemas/project.test.ts`, "a passthrough target that names a gateway": the spec that it accepts and the five refusals. - `src/core/project/boxNetwork/projectGateways.test.ts`: the two target shapes. "the box on PATH" operates box 0.1.11-preview.10 on the Runtime profile and the pack that build makes, with the variables that the L3 sets. Box resolves the server to the host, the backend to the target, the agent variable to the URL, and adds its `net:connect` permit for the host. The test skips when no box is on `PATH`. - Without the change in `src/`, 35 of the 265 tests of these six files fail. Each of 19 mutations of `src/` fails one or more of these tests. - `bun test` with box 0.1.11-preview.10 on `PATH`: 5867 pass, 6 skip, 1 fail. The one failure is "the box on PATH > resolves a profile into the rules the tests fake" in `boxProfileResolver.test.ts`. It fails on `upstream/box-integration` too, with this box. CI has no box, so CI skips it. - `bun run typecheck`, `bun run lint:check`, and `bun run format:check` pass. - Live test in a test account in us-west-2: a new project from this branch and the L3 branch, with a second gateway `toolsgw` (`AWS_IAM`) and one Lambda target that gives a known answer. I added the gateway and the target with `agentcore add gateway` and `agentcore add gateway-target`. I did not change the box profile, the targets of the Box gateway, or IAM. One deploy made the target, the grant, and the variables. The agent used `echo___known_answer` and gave the known answer `gw2gw-known-answer-7319`. Box logged a permit for `mcp:call toolsgw/echo___known_answer`, the Box gateway sent the request to `egress-gateway-toolsgw`, and `toolsgw` logged the tool call and the known answer. The test project only had these changes: agent code that uses the gateway, `enableApplicationLogs` on `toolsgw`. I did `agentcore deploy` two more times for that agent code. `add gateway` gives `protocolType: "None"`, so `_URL` has no `/mcp`, and the agent code must add it, the same as without a box. - I did not do these: `bun run test:e2e`, `bun run audit`, `bun run secrets:check`, and `bun run build`. * fix(box): Accept a China host in the gateway host and URL inputs Review feedback: the `_HOST` and `_URL` patterns of `@box/agentcore` stopped at `amazonaws.com`, and the gateway host of `AWS_ENDPOINTS` also accepts `amazonaws.com.cn`. Thus box refused the two inputs in a China region. Each pattern now accepts `amazonaws.com.cn`. Test: "the host pattern takes ... amazonaws.com.cn: true" and "the URL pattern takes https://....amazonaws.com.cn/mcp: true" in `boxProfile.test.ts` fail before this change. * test(box): Resolve a gateway name with "-" and upper case with the box on PATH Review question: a gateway name can hold "-" and upper case, so the Runtime profile has `${{ inputs.gateways.My-Tools-GW.host }}` and `[mcp.My-Tools-GW]`. The test "the box on PATH" now also uses the gateway `My-Tools-GW`. box 0.1.11-preview.10 resolves the input, the server, the backend, the agent variable, and the permit `context.input.server == "My-Tools-GW"`. No code changes, because box accepts these names. This test does not fail before this commit. It pins the behaviour, and it skips when no box is on PATH. * fix(box): Give each gateway of the project its own Box gateway target name Review feedback: `targetNameFor` changes `--` to `-` and cuts a name at 100 characters. Thus the gateways `a--b` and `a-b`, or two long names with the same start, got the same target name, and the writer added two targets with one name. The target name stays `egress-gateway-` when that name keeps the gateway name whole. When `targetNameFor` changes the name, the target name ends in 8 hex digits of the SHA-256 of the gateway name, and it has at most 100 characters. The name is the same on each build. Test: "is not the same for a--b and a-b" and "is not the same for" two names of 96 characters with the same start, in `projectGateways.test.ts`, fail before this change. * fix(box): Write a gateway target only when the CDK library of the project accepts it Review feedback (blocking): `@aws/agentcore-cdk` 1.1.0, which `box-integration` pins, has a strict `PassthroughConfigSchema` that requires `endpoint`. It refuses `passthrough.gateway`. Build wrote that target for each gateway without `boundRuntime` of a Box project, so the synth of such a project failed until a new library ships. Build now asks the library of the CDK app, with `node` in `agentcore/cdk`, whether `PassthroughConfigSchema` accepts `{ gateway, protocolType }` (`cdkAcceptsPassthroughGateway`). Thus it reads the same library as synth, and a local build of the library works too. A version number cannot tell this, because aws/agentcore-l3-cdk-constructs has not released the change, and a local build of its `box-integration` branch has the version 1.0.2. Build asks only when a box runtime and a gateway without `boundRuntime` are in the project. When the library refuses the field, is not there, or the check fails, build writes no target, no server, and no pack input. It removes a target that it wrote before, and gives one warning that names the gateways. The manager takes the check in `cdkAcceptsPassthroughGateway`, so tests do not run `node`. Equal warnings of two box runtimes show once. Tests that fail before this change: - `compatibility.test.ts`, "cdkAcceptsPassthroughGateway": true for a library that accepts the field, false for one that requires `endpoint`, and false with no library or no schema. - `network.test.ts`, "gives the agent no gateway when the @aws/agentcore-cdk of the project refuses passthrough.gateway, and warns once". - `manager.boxNetwork.test.ts`, "writes no target and no server, and warns once, when it does not". The test "writes the target and the server when the @aws/agentcore-cdk of the project accepts passthrough.gateway" pins the other case. I also ran the check on two real libraries: `@aws/agentcore-cdk` 1.1.0 from npm gives false, and the build of aws/agentcore-l3-cdk-constructs branch `sa/box-gateway-to-gateway` gives true. * fix(remove): Remove the Box gateway target of a gateway with the gateway Review feedback (blocking): after one build, each Box gateway has the target `egress-gateway-` with `passthrough.gateway: ""`. `agentcore remove gateway ` kept that target, the project schema refused the new spec because the target names no gateway, and thus the user could not remove the gateway, and build could not remove the target. `removeResource` now also removes, from each other gateway, each target that build owns (its name starts with `egress-`) and that names the removed gateway in `passthrough.gateway`. A target of the user's that names the gateway stays, and the schema still refuses it with its name, so build never removes a target that the user wrote. I did not make the schema accept a target that names no gateway, because the spec then is not valid for the CDK library until the next build. Test: `manager.boxNetwork.test.ts`, "lets remove gateway remove the gateway after a build, with the target build wrote for it", fails before this change with the schema error. It builds, removes the gateway, and then builds again. The user's own target stays. * fix(box): Read a project whose build-owned gateway target names a gateway that it cannot call Review feedback: after a build, a gateway of the project that gets `boundRuntime`, or that is removed from agentcore.json by hand, left the target `egress-gateway-` with a reference that the project schema refused. Each command then stopped when it read agentcore.json, so build could not remove the target. The schema does not do this check for a target whose name starts with `egress-` (`BOX_EGRESS_TARGET_PREFIX`), because build writes and removes each such target. The next build removes the target. A target of the user that names such a gateway is still refused. The prefix moves to `projectSchemas/project.ts`, and `boxNetwork/egress.ts` exports it from there. Tests that fail before this change: `manager.boxNetwork.test.ts`, "reads the project and removes the target after a build when the gateway gets boundRuntime" and "reads the project and removes the target when the gateway is gone from agentcore.json". `project.test.ts`, "accepts a target that build owns and that names ...", pins the schema. The refusals in that file now use a target of the user. * fix(box): Stop build when two gateways of the project get one target name Review feedback: `hostTargets` put the target of each gateway of the project in `owners` with `owners.set`. When two gateways got one target name, the second name replaced the first one with no report, and the writer added two targets with one name. The target names of 7545175a already differ for gateway names that share their first 90 characters: the test now has "a".repeat(90) + "x1" and + "x2". A gateway can still have, as its name, the name that a different gateway gets with its hash, for example `a--b` and `a-b-`. Build now stops with `TARGET_NAME_COLLISION` for two gateways with one target name, as it does for two hosts. Thus the writer never runs with two targets of one name. Test: `network.test.ts`, "fails two gateways whose targets still have one name, as for two hosts", fails before this change. `projectGateways.test.ts`, "is not the same for" the two names of 92 characters, passes before and after. * fix(box): Add the server of a gateway named constructor to the Runtime profile Review feedback: the gateway rule checked `gateway.name in mcp`, which is true for a key that each object has from its prototype. Thus a gateway named `constructor` or `toString` stopped build with `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. The rule now uses `Object.hasOwn(mcp, gateway.name)`. Test: `gateway.test.ts`, "adds the server of a gateway whose name is a key of every object, such as constructor", fails before this change. * fix(box): Give the CUSTOM_JWT gateway notice once, at add gateway, and not on each build Review feedback: build gave the warning for a `CUSTOM_JWT` gateway on each build, one time for each boxed runtime. The CLI gives a notice about a resource when a command writes that resource: `create` and `add runtime` give the notices of the Box gateway logs and of the default log target. This change does the same. `agentcore add gateway` gives `customJwtGatewayNotice` one time, after it writes a `CUSTOM_JWT` gateway without `boundRuntime` to a project that has a boxed runtime that is not `PRIVATE_VPC`. Build gives no warning for the gateway. I did not add an opt-out, because a notice at the write is simpler and is what the CLI does for its other notices. Tests that fail before this change: `network.test.ts`, "gives the agent no route to a CUSTOM_JWT gateway, and no warning on each build", and `manager.boxNetwork.test.ts`, "add gateway gives one notice for a CUSTOM_JWT gateway, and build gives none". * fix(box): Ask the CDK library about a whole gateway target, as its schema now splits passthrough aws/agentcore-l3-cdk-constructs PR 478, commit a1c7d24 (for its review), keeps `PassthroughConfigSchema` with a required `endpoint`, and gives `passthrough.gateway` the schema `GatewayPassthroughConfigSchema`. Thus the check of 801cff58, which parsed `{ gateway }` with `PassthroughConfigSchema`, gave false for the library that accepts the field, and build wrote no target. `cdkAcceptsPassthroughGateway` now parses a whole target as build writes it with `AgentCoreGatewayTargetSchema`, which both libraries export. `@aws/agentcore-cdk` 1.1.0 from npm gives false, and the build of PR 478 at d57f789 gives true. Test: in `compatibility.test.ts`, "is true when the installed library accepts passthrough.gateway" fails before this change. Its fake library now exports `AgentCoreGatewayTargetSchema`. * fix(schema): Skip the passthrough.gateway check only for an egress- target of a Box gateway Review feedback on ff0c48f7: the schema skipped the check for each target whose name starts with `egress-`, on each gateway of each project. Build manages `egress-` targets only on the Box gateway of a runtime: a gateway with `boundRuntime` in a project with `"projectType": "box"`. The skip now applies only to such a target. An `egress-` target on a gateway without `boundRuntime`, or in a project that is not a Box project, gets the check, as each other target does. Tests: in `project.test.ts`, "is refused on a gateway without boundRuntime, which build does not write" and "is refused in a project that is not a Box project" fail before this change. "is accepted on the Box gateway of a Box project when it names ..." pins the case that build removes. * fix(box): Say why build could not check the CDK library for passthrough.gateway Review feedback: `cdkAcceptsPassthroughGateway` gave false for a library that refuses the field, and also when `node` is not there, when the check takes more than 60 seconds, and when the check fails. In each case, the warning told the user to update the library. The check now gives `PassthroughGatewayCheck`: `{ accepts: true }`, or `{ accepts: false, reason }` with the reason `refuses`, `not-installed`, `no-node`, `timed-out`, or `failed`, and for `failed` the first line of the error. The one warning of build says that reason and its fix. Build still writes no target, no server, and no pack input in each case that is not `accepts`. `cdkAcceptsPassthroughGateway` also takes `node` and `timeoutMs`, for tests. Tests that fail before this change: in `compatibility.test.ts`, one test for each answer, with a fake library, a library that throws, a library that does not stop, and a `node` that is not there; in `network.test.ts`, "gives the agent no gateway, and one warning that says why, when the check gives ..." for each reason. * fix(box): Give the CUSTOM_JWT gateway notice also when add runtime adds a boxed runtime Review feedback: `customJwtGatewayNotice` came only from `add gateway`, when a boxed runtime was in the project already. A boxed runtime that `add runtime` adds after the gateway got no notice. `add runtime` now gives `customJwtGatewayNotice` after it writes agentcore.json, for each `CUSTOM_JWT` gateway without `boundRuntime`, when the new runtime runs in a box and is not `PRIVATE_VPC`. `docs/box-local-testing.md` says so. Test: in `manager.box.test.ts`, "add runtime gives the notice of each CUSTOM_JWT gateway without boundRuntime, as the new runtime is boxed" fails before this change. * docs(box): Name the check parameter and add runtime in the comments of projectGateways.ts (comment of Leo on projectGateways.ts line 53) * fix(box): Write no signing region for a gateway target, as the L3 signs in the region of the stack Review feedback: the signing region of a gateway-to-gateway target came from the spec, which build wrote with its own region. A stack in another region then signed for the wrong one. aws/agentcore-l3-cdk-constructs PR 478 (d87cfea) now signs such a target in the region of the stack, and its schema refuses a `region` on it. So that the two agree, `projectGatewayTargetFor` writes `GATEWAY_IAM_ROLE` with the service `bedrock-agentcore` and no region. The writer removes a region that an earlier build wrote. `unmanagedShape` takes `service,type` for such a target. The check of the CDK library parses a target with no region, so the new L3 accepts it. Tests that fail before this change: `projectGateways.test.ts`, "names the gateway and signs for AgentCore with no region ..."; `boxNetworkWriters.test.ts`, "adds a target that names each gateway ..." and "removes a region that an earlier build wrote ..."; `network.test.ts`, "keeps the target that build wrote for a gateway as build's own"; and the build test in `manager.boxNetwork.test.ts`. The check gives `refuses` for `@aws/agentcore-cdk` 1.1.0 from npm, and `accepts` for the build of PR 478 at d87cfea. * fix(box): Stop build when a host takes again a target that a new gateway would get Review feedback on network.ts line 489: a host that takes again a target that build wrote before went into `owners` with no check. With `[egress.gateway-tools]` for `api.github.com`, one build, and then a gateway named `tools`, the next build rewrote `egress-gateway-tools` as the route to the gateway. The profile still sent `api.github.com` to that target, so the agent lost its GitHub route. Now each host that takes a target again goes through the check. When a gateway of the project gets the same target name, build stops with `TARGET_NAME_COLLISION` at the entry, and writes nothing. Tests that fail before this change: `network.test.ts`, "fails a gateway whose target has the name of the target that a host takes again", and `manager.boxNetwork.test.ts`, "stops, and keeps the route of a host, when a new gateway takes the name of its target", which does the steps of the review. * fix(box): Stop build for a gateway with the name of a server that the policy denies Review feedback on gateway.ts line 88: an HTTP `[mcp.tools]` that the policy denies gets no route, so the rule left it out of `mcp`. The check of the gateway name then passed, and a gateway named `tools` took the name of the server. A policy rule with `context.input.server == "tools"` then applied to a different backend. The check now looks at the `[mcp]` table of the local profile too. A gateway with the name of a server there, with a route or not, stops build with `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. Test: `gateway.test.ts`, "stops for an HTTP server of the local profile with the gateway's name that the policy denies", fails before this change. * fix(box): Stop build, and write nothing, when it cannot check the CDK library Review feedback on projectGateways.ts line 75: `timed-out`, `failed`, `no-node`, and `not-installed` took the same path as `refuses`. Thus a transient failure removed each `egress-gateway-*` target, the `[mcp]` server, and the pack inputs, and a deploy then removed the tools of the agent. `not-installed` rewrote agentcore.json, and then stopped with "CDK dependencies are missing". Only `refuses` is an answer about the library, so only `refuses` lets build remove the targets. For each other reason, `applyBoxNetwork` stops the build or the deploy before it writes, with the reason and its fix: "Build stopped, and wrote nothing: build cannot tell if it can route the gateways 'tools' of this project for a boxed agent, because ...". I chose the stop, and not a warning that keeps the targets, because a stop changes nothing that the last build wrote, also when there was no earlier build. `docs/box-local-testing.md` says so. Tests: in `manager.boxNetwork.test.ts`, "stops, and keeps the target and agentcore.json, when the check gives ..." for `not-installed`, `no-node`, `timed-out`, and `failed` fail before this change. Each builds once with the target, then checks that agentcore.json and the Runtime profile do not change. * perf(box): Load only dist/schema of the CDK library, and do the check only when a gateway needs it Review feedback on compatibility.ts line 46: the check loaded the whole `@aws/agentcore-cdk` package, with its constructs, on each build and deploy of a project with a box runtime and a gateway without `boundRuntime`. It did this also when no gateway could get a target: a `CUSTOM_JWT` gateway only, or a `PRIVATE_VPC` runtime. - The check script finds the package with `require.resolve` and loads `dist/schema` by path. It loads the whole package only when the package has no `dist/schema`. - `applyBoxNetwork` does the check only when a boxed runtime calls a gateway through its Box gateway (`reachedGatewayNames`), so the cases above start no `node`. Time of one check with `cdkAcceptsPassthroughGateway`, 5 runs on a MacBook with Node 26.12.1: before, 104 to 107 ms for the build of aws/agentcore-l3-cdk-constructs PR 478 and 102 to 160 ms for `@aws/agentcore-cdk` 1.1.0; after, 69 to 83 ms and 70 to 78 ms. With no compile cache, the load in `node` takes 0.10 to 0.11 s for the whole package and 0.05 to 0.06 s for `dist/schema`. This machine is faster than the one of the review, which measured 6 to 10 s and 2.6 s. Tests that fail before this change: `compatibility.test.ts`, "loads only dist/schema of the library, and not the constructs", with a package whose entry throws; and `manager.boxNetwork.test.ts`, "does not check the CDK library when no gateway gets a target" for a `CUSTOM_JWT` gateway only and for a `PRIVATE_VPC` runtime. * fix(remove): Remove only a target that build owns when the gateway that it names goes Review feedback on manager.tsx line 1306: `remove gateway` used `isManagedTarget`, which checks only the `egress-` prefix of the name. Thus `remove gateway tools` also removed a hand-written `egress-mine` target on an ordinary gateway `front` that names `tools`. The rule of the schema moves out of `superRefine` into the exported `isBuildOwnedTarget(spec, gateway, target)` in `projectSchemas/project.ts`: an `egress-` target on a gateway with `boundRuntime`, in a Box project. The schema and `remove gateway` both use it. `remove gateway` keeps a target of the user, and the schema refuses it with its name, so the user removes it. Test: `manager.boxNetwork.test.ts`, "remove gateway keeps an egress- target that the user wrote on an ordinary gateway", fails before this change. * test(schema): Give the runtime of the Box-project fixture platformVersion V2 After box-integration PR 2879, every runtime of a Box project needs "platformVersion": "V2". The fixture of "a target that build owns" had no platformVersion, so the two "is accepted on the Box gateway of a Box project" cases failed with 'Runtime "agent" has no platformVersion'. The fixture now sets V2 only for a Box project. The other cases stay the same. * fix(box): Put the target of each gateway of the project in managedTargets and the record, and let remove gateway remove only a target that build owns * test(box): Build, remove a called gateway, and build again, for Tejas's review item on the PR 2887 targets * fix(box): Keep the record entry of each Box gateway that has no model in a build, for Tejas's review item on boxNetworkWriters.ts * fix(box): Keep each route and variable of a network for the credential planner, for Tejas's review item on network.ts * fix(box): Read and patch agentcore.json before build writes the record, for Tejas's review item on manager.tsx * fix(box): Stop build for a route that sends its own key to the AgentCore host With the default Memory, box sends every call to the AgentCore host directly, signed with the execution role, and box cannot route one host both ways. A route to that host with an env:// key, such as an HTTP MCP server on another AgentCore Runtime with bearer auth, lost its key with no message: the server got SigV4 instead of the token, and deploy still provisioned the credential. Build now stops with RUNTIME_AGENTCORE_HOST_CREDENTIAL and names the [egress] entry or [mcp] server and its variable, from the Box network model's record of the host's API key, or from a secret other than aws:// that the entry still holds. That also covers an entry with the AgentCore host and another host. Also: - The profile header names the routes that reach the AgentCore host, not always [egress.agentcore]. - The gateway targets writer treats only the AgentCore host's target as direct, so a rule that drops another route never removes its target. - The README says that code in the box can make any AgentCore call that the execution role allows, including a grant added through additionalPolicies. * feat(box): Remove the mcp-python-fastmcp-box template A box MCP server stays available through add runtime in a Box project. Co-Authored-By: Claude * ci(e2e): Deploy the Box tests with the L3 constructs built from source No released @aws/agentcore-cdk deploys a Box project yet, so the Box tests that deploy skipped in CI. On the macOS and Linux arm64 runners, the e2e job now checks out aws/agentcore-l3-cdk-constructs at the new l3Ref input (default box-integration) with a read-only token from the repository's GitHub App, packs it on the runner, and points AGENTCORE_E2E_BOX_CDK at the tarball. Nothing is published. * ci(e2e): Do not fail a run that leaves uv nothing to cache A tagged run that installs nothing with uv, such as tags=box on Windows, which has no box, leaves no uv cache, and setup-uv's post step failed the job for it even though every test passed. * ci(e2e): Run the Box tests on Linux arm64 only, and skip the LangChain box deploy in CI The pinned macOS box build is killed as soon as it starts (Killed: 9 on box --version), which failed the macOS job, so CI no longer installs box there: the macOS Box tests skip and the rest of its suite runs. The AgentCore Runtime logs of agent_python_langchain_box hold OpenTelemetry's "Failed to detach context" at ERROR level, which the deploy test's log check refuses, so CI skips that one case until the template or the check handles it. It still runs locally, and its dev test runs in CI. * fix(box): Use the v0.3.0 macOS box instead of v0.3.0-preview.1 The macOS build of box v0.3.0 runs: its box and both helpers pass codesign --verify --strict (Developer ID, AMZN Mobile LLC) and box --version prints box 0.3.0. The invalid Info.plist reported when it was pinned away came from that copy on disk, not the release asset: the asset's SHA-256 is the same, and it has not been re-uploaded. So macOS and Linux both take v0.3.0 again, boxRelease.json drops darwin.version, and the install hints and docs no longer send macOS to the preview. bump-box-release.ts keeps --darwin-box for a release whose macOS build does not run. * docs(e2e): Say which macOS box build CI saw killed The macOS skip said the pinned macOS box build is killed at start. That was v0.3.0-preview.1, after the workflow's install; the pin is now v0.3.0, which no CI run has tried yet. * ci(e2e): Run the Box tests on macOS again, with box unpacked as the runner user macOS now pins box v0.3.0, which runs when unpacked plainly. CI installs it on the macOS runner again, unpacked as the runner user into $RUNNER_TEMP/box and put on PATH, as a developer does, instead of the sudo unpack into /opt/box after which the signed v0.3.0-preview.1 was killed at start. If macOS refuses box, the step prints codesign's verdict and the recent system log before failing. The macOS runner builds the L3 constructs for the Box deploys too. Linux arm64 is unchanged. * fix(e2e): Unpack the macOS box into a folder not named box macOS reads a folder named box that holds the executable box as a bundle, so codesign reports the signed box as invalid (Info.plist not bound) and macOS kills it at launch. That is why the macOS box was killed under /opt/box/box and, in the last run, $RUNNER_TEMP/box/box, while the same file runs from a folder with another name. The e2e workflow now unpacks it into $RUNNER_TEMP/box-, and the local testing guide warns against a folder named box. * feat(box): Let a Box gateway call only the Bedrock model of its runtime The Box gateway's role could invoke every inference profile and every foundation model of the account: agentcore/box-bedrock-policy.json named `inference-profile/*` and `foundation-model/*`. - create records the model a box runtime's code calls in the runtime's existing `modelId` (the --model-id, or the template default), as it already does for LiteLLM. The minimal template calls no model and gets none. The LangChain template now renders `modelId` into model/load.py, as the other templates do, so the code and agentcore.json name the same model. - When every boxed runtime that calls Bedrock has a modelId, build writes a policy for those models only: an inference profile of the account in the region, and its foundation model only through that profile; or a foundation model ID in the region. - When a runtime has no modelId (a project created before this change), build keeps the every-model policy and warns, naming the runtime and the field to set. * test(remove): Keep a target of the user that the record leaves out when its gateway goes (review) * docs(box): Say in the JSDoc of the egress- prefix that the record decides which targets build owns (review) * docs(remove): Say that a target of the user that names a removed gateway stays and stops the next deploy (review) * fix(build): Warn when a second variable of one credential holds a different key (review) * test(build): Keep the record when the patched agentcore.json fails the schema (review) * docs(remove): Remove the stale line comment above the JSDoc of commitSpec (review) * docs(build): Move the model-provider sentence from boxRouteKeyHeldElsewhere to planBoxProfileCredentials (review) * fix(build): Write the record of the gateway targets through a temporary file and a rename (review) * fix(box): Address the review of the per-model Bedrock policy - A modelId that build cannot scope to falls back, with a warning, instead of writing a policy that matches nothing: build reads a model ID or system inference profile ID (provider.model), a foundation model ARN or a system inference profile ARN (in the ARN's region), and LiteLLM's bedrock/, bedrock/converse/ and bedrock/invoke/ routes. An application inference profile, provisioned, custom or imported model ARN, or an ID that is not provider.model, keeps the every-model policy and the warning. - No list of geographic prefixes: every plain ID gets the profile statement, the model statement through that profile, and the in-region model statement. A model ID's profile statements and a profile ID's model statement name resources that cannot exist, so nothing widens, and in. or a future prefix needs no change. - The warning and the fallback agree: a boxed runtime with no modelProvider (minimal-box, or an added runtime) counts as calling Bedrock in both, so the project keeps every model and build says which runtime to give a modelId. The warning names several runtimes in one sentence. - The no-op recordBoxModelId call in add runtime is removed. - docs/box-local-testing.md and the strands and LangChain READMEs of a box runtime say that the Box gateway calls only the model in modelId, so the code and modelId change together. - The comment on foundation-model/* says why it ends in *. - Tests: an in. profile, a plain model ID, a profile ARN in another region, a foundation model ARN, each LiteLLM route (asserting the resource), the three kinds that fall back, a mixed project, the plural warning; create with a non-default model for strands-box and langchain-box (the code and modelId match), a2a-python-strands-box and agui-python-strands-box; build rewrites the policy to a changed modelId and warns when it is missing. * fix(dev): Send the spans of an agent in a box, and the records of box, to the dev collector ## Problem In `agentcore dev`, an agent in a box sends no span to the dev collector. Thus `agentcore/.cli/traces/otlp` stays empty, and the local trace view shows nothing. An agent that is not in a box sends its spans there. On 2026-11-24, a CodeZip agent that is not in a box wrote a trace file of 19.5 KB. A CodeZip agent in a box wrote no file. There are three causes: 1. Box makes the environment of the agent from the profile only. Thus the agent does not get the OTEL variables and the `PYTHONPATH` that dev gives to an agent that is not in a box. 2. Box sets `OTEL_EXPORTER_OTLP_ENDPOINT` of the agent to the receiver of box. The local profile has no telemetry target for the dev collector. Thus box sends the spans to no collector. 3. In a container, the command of the agent does not start with `opentelemetry-instrument`. Dev also shows the message "Traces are not collected when the agent runs in a box". ## Solution When dev collects traces, dev starts box with a dev profile. Dev makes the dev profile from the local profile of the runtime, and writes it only to a folder that git ignores. The local profile does not change. - The dev profile adds the telemetry target `[telemetry.agentcore_dev]`. The `kind` of the target is `otlp`, the destination is the dev collector, and the target has no secret. If the profile has a target with that name, dev uses `agentcore_dev_2`. - The dev profile adds to `[agent.env]` the OTEL variables that dev gives to an agent that is not in a box. The OTLP endpoints are not in that set, because box sets them. A value of the user stays. - CodeZip: dev writes the dev profile and copies of the policy files to `agentcore/.cli/box-dev//`. The auto-instrumentation folder of the venv goes first on `PYTHONPATH`, the same as for an agent that is not in a box. Thus the auto-instrumentation operates in each Python process of the agent, and `--reload` continues to operate. - Container: the image gets the dev profile. The command starts the Python of the venv with `opentelemetry-instrument`, and dev removes `--reload` and `--reload-dir`, because the image has no live code. If the command does not start the Python of the venv, dev keeps the command, and tells the user that the agent sends no span. The container gets to the collector through `host.docker.internal`, as before. - When `instrumentation.enableOtel` is `false`, or `DISABLE_ADOT_OBSERVABILITY` is `true`, dev starts box with the local profile, as before. - CodeZip: if the venv has no auto-instrumentation, dev starts box with the local profile. Dev then shows the message that dev shows for an agent that is not in a box. - `findOtelSitecustomizeDir` moves out of `CodeZipDevRunner`, so that `BoxDevRunner` can use it. ## Tests - `boxDevTelemetry.test.ts` has 7 tests. They pin the target with no secret, the name when the user has the name, the variables with no OTLP endpoint, `PYTHONPATH` with the command and its reload kept, the container command without reload, a command that dev keeps, and the folder. - `box.test.ts` "runs a dev-time profile that sends traces to the collector, and keeps the local profile" pins the path that `box run` gets, the merge of `PYTHONPATH`, the value of the user, the copy of the policy file, and the local profile with no change. - `box.test.ts` has two more tests. They pin that `DISABLE_ADOT_OBSERVABILITY` and `enableOtel` `false` start box with the local profile, and that dev writes no dev folder. - `container.test.ts` has two tests. They pin the profile in the image for `host.docker.internal`, and the local profile for `DISABLE_ADOT_OBSERVABILITY`. - `bun test` gives `6504 pass, 9 skip, 0 fail`. `bun run typecheck`, `bun run lint:check`, `bun run format:check`, and `bun run build` give no error. - Live CodeZip test with box 0.3.0-preview.1 on macOS: after `agentcore dev`, `agentcore invoke --local` gave 200. The collector got 10 spans and 14 log records, with the service names `agent` and `strands-box`. After a change to `main.py`, uvicorn started again with the changed code, and the next invoke wrote more trace files. - Live container test with Finch: `agentcore invoke --local` gave 200. The collector got 22 spans and 12 log records, with the service names `agent` and `strands-box`. - I did not do the end-to-end tests (`bun run test:e2e`), because no change is in deploy. I did not do a test with Docker or Podman, or with a LangChain agent. * fix(box): Address the follow-ups of the review of the per-model Bedrock policy - An ARN of another partition than the build's falls back to the every-model policy with the warning: it names a model the gateway's role can never call. - The warning says that a runtime whose code calls no model needs no modelId. - The A2A and AG-UI box READMEs get the paragraph that ties the model to modelId, as the strands and LangChain ones do. - Tests: a foundation model ARN with a wildcard, a wildcard model ID and an ARN of another partition fall back; the multi-runtime policy has the deduplicated statement count; create renders the modelId paragraph in the README of strands-box, langchain-box, a2a-strands-box and agui-strands-box. Removing the ARN ID check, the dedupe, or the LangChain README paragraph now fails a test. * feat(box): Sign an aws:// host with the service and region that Box signs it with, and leave IAM to the customer ## Problem An `[egress]` entry or an HTTP `[mcp]` server with `secret.ref = "aws://"` operates correctly with `agentcore dev` for each AWS host that Box signs, for example `s3.us-west-2.amazonaws.com`. Box reads the service and the region from the host name. For a host that is not a Bedrock, AgentCore, or Lambda function URL host, `agentcore build` stops with `UNSIGNABLE_HOST`, and the message tells the customer to use an `env://` secret. An `env://` secret cannot sign an AWS request. Thus, the customer cannot deploy the project, and the step in the message is not correct. ## Solution - On AgentCore Runtime, the Box gateway signs each request again for the destination host, with the service and the region of the target. Build reads the service and the region of an `aws://` host with the same rule as `derive_service_region` in Box Core (`boxSigningOf` in `egress.ts`). Build writes the target with `outboundAuth` type `GATEWAY_IAM_ROLE` and that service and region. - Build gives no IAM permission for these hosts. The current warning tells the customer to add an IAM policy file to `additionalPolicies` of the gateway, for example: `Target 'egress-s3test' calls s3 with the gateway's role, which has no s3 permissions.` Bedrock, AgentCore, and Lambda function URL hosts do not change. - For a host that Box does not sign, for example `my-bucket.s3.us-west-2.amazonaws.com`, build does not stop. It writes no target, keeps the entry out of the Runtime profile, and shows a warning with the target to add to `agentcore.json`. When `agentcore.json` has a `GATEWAY_IAM_ROLE` passthrough target for that host, build uses that target as the customer wrote it. A target with a different auth stops build with `EXISTING_TARGET_CONFLICT`. - An `aws://` entry for the host of an AgentCore gateway stops build, as before. ## Tests - `network.test.ts`, "signs aws:// on an AWS host outside the managed endpoints with the service and region Box signs it with, and grants nothing": `s3.us-west-2.amazonaws.com` gets the target `egress-s3` with `s3` and `us-west-2`, and build gives no IAM action. - "reads the service and region of a host by Box's own signing rule": the example hosts of the Box Core tests, plus a bucket host, a `.amazonaws.com.cn` host, and an empty label. - "gives aws:// on a host Box does not sign no target, and warns with what to add", "routes aws:// on a host with no signing service through the user's own IAM target", and "refuses the user's own target with other auth for aws:// on a host with no signing service". - "an S3 target needs an S3 grant that the user adds, and build adds none": the IAM warning. - "signs an aws:// server on an AWS host with the gateway's role, and gives one on another host no target": the same rules for an HTTP `[mcp]` server. - When I remove the call to `boxSigningOf`, the first test shows a failure. - Typecheck, lint, format, build, and the full `bun test` suite (6498 tests) have no errors. Live test on AgentCore Runtime (a test account, us-west-2, container template, box 0.3.0). The agent sent requests to S3 with boto3 through box, with path-style addresses: - Build wrote `egress-s3test` with `GATEWAY_IAM_ROLE`, `s3`, and `us-west-2`, and showed the IAM warning. The target on AgentCore Runtime has `iamCredentialProvider` with `s3` and `us-west-2`. - With no IAM policy, S3 refused `GetObject`. The message names the role of the gateway, which shows that the gateway signed the request for S3. - After an IAM policy file in `additionalPolicies`, `GetObject` and `ListObjectsV2` operated correctly. From a prompt, the model used the S3 tool and gave the text of the object. - A request to a different bucket stopped at box (403), because of a `forbid` rule. - `PutObject` had an error. Box gave a permit decision for it, and the gateway log has no entry for it. A passthrough target of the gateway sends only GET, POST, and DELETE requests to the host. Not in the tests: a host shape other than `{service}.{region}.amazonaws.com` on AgentCore Runtime. * refactor(dev): Use one NO_AUTO_INSTRUMENTATION constant in codezip.ts and box.ts (review) * fix(box): Stop build again for aws:// on a host that is not an AWS host (review) * fix(box): Count only granted actions for a signed target outside the managed endpoints, not the Bedrock file (review) * fix(box): Say how boxSigningOf differs from Box, and say that the AgentCore Runtime box profile leaves the entry out (review) * fix(dev): Send box's records to the collector when a CodeZip venv has no auto-instrumentation (review) * test(box): Cover a stale managed target for a host Box does not sign, and a user IAM target with no region (review) * refactor(dev): Derive the OTEL variables of a boxed agent from otelEnvVars, and name every OTEL_EXPORTER_OTLP_* variable in the doc comments (review) * fix(dev): Remove the one-word --reload-dir= from a container command too (review) * test(dev): Check the container notice for an agent command that is not the venv's Python (review) * test(dev): Name the box test after what it passes: no collector endpoint (review) * feat(box): Send the spans of a boxed agent to the log group of its runtime (#2914) * feat(box): Send the spans of a boxed agent to the log group of its runtime The default X-Ray target of a Runtime profile sent the spans to X-Ray with no log group, so X-Ray put them in aws/spans, and the spans stream of the runtime's own log group stayed empty. With a box release that takes `log_group` and `log_stream` on a `cloudwatch_traces` target (strands-agents/box#629), the default target now names the log group and the log stream that the Runtime sets in OTEL_EXPORTER_OTLP_TRACES_HEADERS. The @box/agentcore pack reads the two values through the inputs `runtime.traces_log_group` and `runtime.traces_log_stream`. BOX_TRACES_LOG_GROUP_VERSION is the first box release that takes the two keys. A box.version before it gets the target without them, because an older box refuses them. Set the constant to the release that ships strands-agents/box#629. Tests: additions.test.ts and boxProfile.test.ts pin both sides of the version gate, the header line, and the grant. bun test: 6516 pass, 9 skip, 0 fail. Typecheck, lint and format pass. * docs(box): Say where the spans of a boxed agent go on AgentCore Runtime * docs(box): Name the silent span loss and how to find it (review) * fix(box): Gate the traces log group on the staged box, not box.version (review) * test(box): Check that the pack declares each traces input the Runtime profile names (review) --------- Co-authored-by: Sai Abhishek * feat(box): Send box telemetry to Langfuse, LangSmith, and OTLP endpoints on AgentCore Runtime (#2917) * feat(box): Move third-party telemetry keys to AWS Secrets Manager for the Runtime This commit holds five commits of box-integration-development, resolved against box-integration: 7ad00c39, 212d17f1, 96cc7341, 3ad5f5c3, and 71801dfd. Deploy writes the key of each third-party telemetry target (otlp, langfuse, langsmith) into one AWS Secrets Manager secret for each runtime, agentcore///box, outside the stack. The Runtime profile gets plugins = ["@box/aws-secrets-manager"] and an aws-secretsmanager:// reference for each target. The execution role gets secretsmanager:GetSecretValue on that secret only. The container image installs the AWS CLI after a signature check, because the plugin runs aws. * fix(box): Always move third-party telemetry keys to AWS Secrets Manager, and remove the AGENTCORE_BOX_SECRETS_MANAGER switch * feat(box): Keep the third-party telemetry of a PRIVATE_VPC runtime, warn that its VPC has no path to the host, and ask the L3 for an AWS Secrets Manager endpoint * fix(dev): Pass the env:// key of each third-party telemetry target to box under agentcore dev * docs(box): Say how to send box telemetry to Langfuse, LangSmith, or an OTLP endpoint on AgentCore Runtime * test(box): Use the platform path of .env.local in the third-party telemetry build test The step message names ENV_LOCAL_RELATIVE_PATH, which has a backslash on Windows. The test now expects that constant, as the other tests in this file do. * test(box): Add tests that two third-party telemetry targets of the same kind have different secret fields and Runtime profile refs * fix(box): Show the cause and the correct step when build stops for a third-party telemetry target that it does not carry * revert(box): Move the CodeZip stop message fix to its own pull request * fix(box): Refuse to write or delete a telemetry secret that this CLI did not create (review) * fix(box): Read the source variable of a telemetry key from agentcore/.env.local at build, as dev does (review) * fix(box): Name both sources of the key in the hint for a missing telemetry key (review) * docs(box): Say why the account in the ARN of the telemetry secret is * (review) * fix(box): Show a warning when deploy cannot delete a telemetry secret (review) * docs(box): Say that deployment targets in one account and region share the telemetry secret (review) * test(box): Say which renderer recorded the secretsManager fixture cases (review) * style(box): Wrap the comment and messages of the telemetry secret ownership check at 100 columns (review) * fix(box): Stop build when two telemetry targets of different runtimes read their key from one variable (review) * fix(box): Keep the record of a telemetry secret that teardown cannot delete, and delete it on the next deploy (review) * fix(box): Hand the secret:// key of a telemetry target to box in the dev container (review) * fix(box): Remove the PGP check of the AWS CLI, and keep the pinned SHA-256 check (review) * fix(box): Warn at build when the Dockerfile of a box container does not install the AWS CLI that box needs to read a telemetry key (review) * fix(box): Delete runtime.network when the removal of the Secrets Manager endpoint leaves it empty (review) * fix(box): Read the telemetry secret each time it exists, and skip PutSecretValue when the object is equal (review) * fix(box): Keep each field of the telemetry secret until the stack deploy succeeds and no deployment target reads it (review) --------- Co-authored-by: Sai Abhishek * fix(box): Stop build for an env:// egress entry whose name cannot name a credential Build named the API key credential of an env:// [egress] or [mcp] entry after the entry, and skipped an entry whose name is not a valid credential name (such as [egress.w]) with two warnings. Build then said "built project" and exited 0, but deploy gave the host no gateway target. The Box network model now fails such an entry with CREDENTIAL_NAME_INVALID at its file:line:column, so build and deploy stop with a non-zero exit code. The check covers the four rules that agentcore credentials add enforces: a valid name, no credential field suffix, no variable that another credential derives, and no credential of another type with that name. The credential planner uses the same check as a backstop. The guide states the naming rule. Fixes SQ-05 of the Box on CLI bug tracker. * fix(box): Refuse a new credential name that derives the variable of another runtime's Each box runtime gets its own network model, so the check for an entry whose new API key credential derives the variable of an earlier entry's covered only one profile. Two runtimes with [egress.git-hub] and [egress.git_hub] built with exit code 0, and the credential planner skipped one entry with a warning. readBoxNetworks now records the new credential of each entry across runtimes, as it already does for shared keys, and fails a later entry whose credential derives the same variable with CREDENTIAL_NAME_INVALID at its line. Also add tests that pin the derived-variable clash with a secretRef credential and the one failure for an invalid entry with two destinations. * test(box): Pin that an entry using an existing credential holds no new variable across runtimes * Merge pull request #2932 from aws/feat/box-template-tag feat(box): Tag the runtime and Box gateway of a Box project with agentcore:template * fix(box): Pin box to the strands-agents/box 0.3.2 release - boxRelease.json pins 0.3.2: the box-cli archives for Linux arm64 and macOS (Apple silicon), with the SHA-256s of the release's SHA256SUMS.txt. - 0.3.2 is the first release whose cloudwatch_traces target takes log_group and log_stream (strands-agents/box#629), so BOX_TRACES_LOG_GROUP_VERSION now applies: build names the runtime's log group and log stream for the box's spans. The build test follows that gate. - The README, docs/box-local-testing.md and the install hint test name 0.3.2. * fix(dev): Give the dev copy of a box profile its own name, so build works after dev (#2934) ## Problem On a CodeZip box project, `agentcore dev` with traces on starts a copy of the box profile, `agentcore/.cli/box-dev//profile.toml`. [aws/agentcore-cli#2916](https://github.com/aws/agentcore-cli/pull/2916) gave the copy the same `[profile] name` as `.box//local/profile.toml`. Box records each profile name for the first profile file that `box run` starts with that name. Box keeps the record in `~/.strands/box/storage//.profile-source`, and it refuses each different file that declares the name. Thus, after one dev session, `agentcore build` and `agentcore deploy` stop with this error: the profile name "E2eZip-agent" in .box/agent/local/profile.toml belongs to agentcore/.cli/box-dev/agent/profile.toml; give this profile another `[profile] name` An upgrade of the CLI does not repair a project that has this record, because the record stays in the box home. ## Solution - Dev gives its CodeZip copy a name of its own: the local name with `-dev` (`boxDevProfileName`). Box records that name for the copy, and the dev sessions with traces keep their own box storage. The local profile keeps its name for build and deploy. Each name that `create` writes is `-`, with one `-`, thus the dev name is not the name of a local profile. The dev name has a maximum of 64 characters, as box accepts. - The container dev copy keeps the local name. Box operates in the container, with a box home of its own, thus the host gets no record. - Box has no command that removes only the record of a name. `box profile delete` also removes the storage and the boxes of the profile. For a renamed profile file, the Box error tells the user to remove the record of the name and then to start again. - Thus, when `box profile show` refuses a profile because Box recorded its name for a dev copy of this project, build reads the record of that name. If the record has the path of that dev copy, build removes only that one file. Then build shows the profile one more time, and it gives a message that names the removed file. Build does not change a record that has a different path. - `ResolvedBoxProfile` has a new optional field, `notes`. `readBoxNetworks` adds each note to the warnings of the network. ## Tests - `boxDevTelemetry.test.ts`, "gives a CodeZip copy a profile name of its own, which no local profile has": the copy is `Demo-agent-dev`, and a container copy keeps `Demo-agent`. - `box.test.ts`, "runs the dev-time profile under a name of its own, so box binds the local profile's name to the local profile only". - `boxProfileResolver.test.ts`, "shows the local profile after dev runs its copy, which box binds to a name of its own": the box on PATH shows the local profile after a dev session, with no note, and the record of the dev name stays. - `boxDevNameRecord.test.ts` and `boxProfileResolver.test.ts`, "a profile name that an earlier agentcore dev bound to its copy": build removes only the record that has the dev copy, for the two Box errors, with a fake Box output and with the box on PATH. A record that has a different file, or the dev copy of a different project, stays. - `container.test.ts`, "with dev's collector on, stages a profile that sends traces and box's records to it": the container copy keeps the local name. - `boxNetworkSource.test.ts`, "warns with what the resolver changed in box's state before Box resolved the profile". I removed each part of the fix, one at a time. Each test above, other than the container test, then gave an incorrect result. The container test gave an incorrect result when the container copy got the dev name. Gates: `bun test` (6684 pass, 12 skip, 0 fail), `bun run typecheck`, `bun run lint:check`, `bun run format:check`, and `bun run build` are correct. Live test, with box 0.3.0-preview.1 in us-west-2: - A new CodeZip project: dev started its copy as `DevName-agent-dev`, and `invoke --local` gave an answer. The dev collector got the box records and the agent spans. Then build and `deploy --yes` completed with no error, and an invoke of the Runtime gave an answer. - A second project: dev with the previous CLI recorded `DevNameOld-agent` for its copy, and build with the previous CLI stopped with the error above. Build with this CLI removed that one record, gave the message, and completed with no error. The next build gave no message. Not done: `agentcore dev --no-traces` on a project that has the record shows the Box error until build or deploy operates one time. With box 0.3.0-preview.1 on PATH, the test "resolves a profile into the rules the tests fake" gives an incorrect result. It gives the same result on `box-integration` without this change. Co-authored-by: Sai Abhishek * test(e2e): Run each Strands Box template through create, dev, build, deploy, invoke and dev again The Box dev and deploy tests ran in separate projects, so nothing ran build or deploy after dev in one project: a CodeZip build failed after dev (box bound the profile name to dev's copy, fixed in #2934), and no test caught it. Each Box flow test now runs, in one project: create, dev and invoke --local, build, deploy, invoke, the in-a-box check, then dev and invoke --local again. Box listens on the protocol's fixed ingress port, so the dev steps of the tests that share a port take turns (withDevPort); build, deploy and invoke still run concurrently. The container template skips dev without a container tool. The dev-only suite now runs only where the deploy tests cannot (no AGENTCORE_E2E_BOX_CDK). * test(e2e): Add Box scenarios: a second runtime beside a Memory, an egress route with an env:// key, and Memory recall - A runtime added with add runtime to a Box project with a Memory deploys and answers beside the first (the box pack of each runtime reads the ID of every project Memory; L3 #498). - An egress route with secret.ref = "env://E2E_ECHO_KEY": build stops before the first deploy, deploy stores the key as an API key credential, and the Runtime agent, which holds no key, gets back "Authorization: Bearer " from a header-echo host, so the Box gateway added it. - Memory recalls a fact within a session, and from a new session after long-term extraction. CliRunner.run and start take extra environment variables for the key. * test(e2e): Join the streamed text of a reply before the Memory recall assertions * fix(box): Send the Memory calls of every runtime of a project with a Memory to Memory directly The constructs bind every project Memory to every runtime (aws/agentcore-l3-cdk-constructs#498), so a runtime that add runtime puts beside the first gets MEMORY__ID and calls Memory. Build added the [egress.agentcore] route only to the runtime the Memory is named for, so box refused the other runtime's Memory calls with 403 Forbidden. * feat(create)!: rename --containment sandboxed to contained (#2937) * test(e2e): Add a Box scenario for a Memory added with add memory * test(e2e): Add Box scenarios for a Code Interpreter connection, a Browser connection, and a gateway with an MCP target * fix(box): Stop build for a Box gateway target of the user that signs the AgentCore host, and give the credential refusal a remedy that keeps the other runtimes' Memory (review) * fix(box): Say what a private VPC blocks for a third-party telemetry target, and the step that works (#2935) * fix(box): Say what a private VPC blocks for a third-party telemetry target, and the step that works ## Problem `agentcore build` shows a warning for each third-party telemetry target of a runtime with "containment": "PRIVATE_VPC". The warning tells the operator to give the VPC a path to the host, or to remove `--containment private-vpc`. The two steps are incorrect: - An internet path is not sufficient. The DNS firewall of the private VPC (`AgentCoreSecureVpc` in the L3 constructs) resolves only the names of its AWS endpoints, and it gives NXDOMAIN for all other names. No field in agentcore.json adds a name to that list. An end-to-end test on AgentCore Runtime showed NXDOMAIN and a firewall BLOCK for us.cloud.langfuse.com. - `--containment` is a flag of `agentcore create`. After `agentcore create`, the containment is the "containment" field in agentcore.json, and `agentcore create` also writes a "network" field in the same runtime. An operator who does the steps in the warning cannot get data to the host. ## Solution The new warning tells the operator that the VPC has no internet path, and that its DNS firewall resolves only AWS service names. Thus no data gets to the host. The warning keeps "Box tries to send", because `agentcore build` keeps the target. To send to the host, the warning tells the operator to remove "containment" and "network" from the runtime in agentcore.json. It also gives an alternative: use `agentcore create` again without `--containment private-vpc`. The step removes the two fields together, because the schema does not accept "network" without "containment": "PRIVATE_VPC". The warning gives no routing step, because agentcore.json has no field that adds routing or a DNS name. The doc comment of `runtimeTelemetry` and docs/box-local-testing.md tell the same. ## Tests - network.test.ts, "keeps each target of a PRIVATE_VPC runtime, and warns that the VPC has no path to its host", pins the new text for a Langfuse target and a LangSmith target. - manager.boxNetwork.test.ts, "keeps the target of a PRIVATE_VPC runtime, gives its VPC an AWS Secrets Manager endpoint, and warns", pins the new text through `agentcore build`. - project.test.ts, "rejects containment with network without PRIVATE_VPC", pins that the schema does not accept "network" without "containment": "PRIVATE_VPC". - network.test.ts, "gives no private-VPC warning for a runtime on the default network", pins that the warning stops after the step. - `bun test`: 6682 pass, 9 skip, 0 fail. `bun run typecheck`, `bun run lint:check`, `bun run format:check`, and `bun run build` complete with no errors. No test does a deploy with the new step. This change makes no AWS calls. * fix(box): Name the VPC endpoints in the DNS warning, and tell the cost of the default network (review) --------- Co-authored-by: Sai Abhishek * test(e2e): Address the review: distinct project names, checked teardown, LangChain dev in CI, and the env:// scenario under box-egress * test(e2e): Open an MCP session before listing the gateway's tools, and report the gateway's raw answer * fix(box): Fail closed on a Box gateway target's credential for the AgentCore host, and test it at build level (review) * test(e2e): Let the Browser scenario's agent open the automation WebSocket with a policy.dw permit, as a user writes it * fix(box): Take a websocket:connect rule of the box policy, the action box 0.3.2 decides a WebSocket handshake with * test(e2e): Address the second review: the gateway scenario under box-egress, askAgent in the Memory scenario, and the comments (review) * fix(box): Pin box to the strands-agents/box 0.3.3 release * ci(e2e): Add a region input to the e2e workflow A manual or called run can pick the AWS region to deploy and test in. An empty region keeps the E2E_REGION variable, else us-east-1, so ci.yml and canary.yml runs are unchanged. * test(e2e): Run dev before and after deploy for the minimal and container Box templates only, and deploy the others without waiting for dev * test(e2e): Call the project gateway at its /mcp path, which AGENTCORE_GATEWAY__URL leaves out * feat(box): Put a Box project's file assets under a strands-box/ S3 key (#2951) * feat(box): Put a Box project's file assets under a strands-box/ S3 key A Box project's vended CDK app now gives each stack new DefaultStackSynthesizer({ bucketPrefix: 'strands-box/' }), so the agent zip of a Box CodeZip runtime uploads as strands-box/.zip, and the runtime's code location shows that it runs its agent in Strands Box. The container build source and the stack template go under the same prefix. Only a project with "projectType": "box" gets the prefix. Other projects keep the default synthesizer. * test(box): Check the strands-box/ asset keys and image tag in the Box deploy e2e - The Box deploy e2e reads agentcore build's cdk.out: every file asset key starts with strands-box/, and a container runtime's image tag is strands-box-. - The vended CDK app reads projectType with a type guard on the unknown agentcore.json, in place of a cast. * docs(box): Say that the strands-box/ S3 prefix marks each runtime of a Box project --------- Co-authored-by: Abhilash Panigrahi * fix(box): Read a boxed agent's model provider key from the box, not AgentCore Identity * refactor(box): Address review of the boxed model key fix One inline partial per load.py holds the box key block, the missing-key error says what to set and where, and the tests read the variable from the box profile's secret.ref and cover OpenAICompatible and every keyed provider in the a2a and agui templates. * fix(box): Send a boxed Anthropic agent's key in x-api-key, the header the box fills in * fix(box): Give the agent in the box the envVars of its runtime on AgentCore Runtime AgentCore Runtime sets each variable of the runtime's envVars in agentcore.json in the environment of box. Box gives the agent only the variables that the profile names, so a boxed agent did not get them. The Runtime profile now forwards each one into [agent.env] as { from = "env:" }. - A value that [agent.env] or the @box/agentcore pack sets stays. - Build leaves out a variable that box refuses to give the agent, with a warning: a variable that box sets itself, a credential of a route or a server, an AWS credential, AWS_PROFILE, LOCAL_DEV, and the port variable. - agentCorePackEnvNames gives the names of the pack's [agent.env], from the same table that renderAgentCorePack writes. * fix(box): Skip the envVars that box refuses or that would change the routed region Review fixes for the envVars forward: - AWS_REGION and AWS_DEFAULT_REGION always stay out: with @box/bedrock, a forward replaced the region that the pack routes. - AWS_BEARER_TOKEN_BEDROCK is a credential: on the Runtime, the API key route of @box/bedrock reads it, and box refused the profile. - Each LD_* variable and PWD stay out: box refuses them. - A variable that [agent.env] already sets now gives a warning. - Tests for the gateway URL, a server credential of the network model, and OTEL off. Comments and docs match the code. * feat(box): Give the agent AWS_EXECUTION_ENV and AWS_DNS_SUFFIX on AgentCore Runtime AgentCore Runtime sets AWS_EXECUTION_ENV and AWS_DNS_SUFFIX for an agent outside a box. The service reserves both names, so the envVars forward does not cover them. The @box/agentcore pack now reads each one through an input and gives it to the agent. - Each input has a default, so box starts also where the variable is not set: AWS_BedrockAgentCore_Runtime, and the DNS domain of the partition of the build region (amazonaws.com with no region). - Both names are pack names, so an envVar of the same name gives the pack warning. * feat(box): Give the agent the ADOT settings that AgentCore Runtime sets The @box/agentcore pack gave the agent fixed values for OTEL_PYTHON_DISTRO, OTEL_PYTHON_CONFIGURATOR, AGENT_OBSERVABILITY_ENABLED, and OTEL_PYTHON_EXCLUDED_URLS. It now reads each one from the Runtime through an otel. input, and gives the agent the value as it is. Each default is the old fixed value, so box starts also where the Runtime does not set it. - OTEL_TRACES_EXPORTER, OTEL_LOGS_EXPORTER, and OTEL_METRICS_EXPORTER stay fixed: the receiver of box takes only spans and logs. - agentCorePackEnvSources tells a variable that the pack reads from the Runtime from a fixed one. An envVar of a Runtime-read name needs no forward and gives no warning, because the agent gets it through the pack. * fix(box): Keep third-party telemetry keys from the agent, and find credentials as box does Review fixes: - The telemetry rule moves each third-party key to Secrets Manager before the envVars forward runs, so a key such as LANGFUSE_KEY in envVars went to the agent. The credential check now reads the profile from before the rule, and the key variables of context.thirdPartyTelemetry. - Credentials are found as box finds them: secret:// and trimmed references, the env of a secret table, and pass-secret-env entries, NAME* included. - Each DYLD_* variable stays out, as each LD_* variable does. - A profile with no [agent] table, or an [agent.env] that is not a table, gives one warning. - renderAgentCorePack takes { boxVersion, region }. A build test checks the DNS suffix default for cn-north-1, and a test checks that each runtime source of the pack has an input that reads the variable of the same name. - The pack has no dead [agent.env] guard, and its blank lines are correct. - Docs and comments: the defaults in a local run, and the list order. * refactor(box): Do not forward the runtime's envVars to the agent in the box A customer gives a boxed agent a variable in [agent.env] of the local box profile, which works under agentcore dev and on the Runtime. The derived Runtime profile no longer forwards the envVars of agentcore.json, so this change removes withRuntimeEnvVars, its skip rules and warnings, and agentCorePackEnvSources. The pack keeps AWS_EXECUTION_ENV, AWS_DNS_SUFFIX, and the ADOT settings that the Runtime sets. * test(e2e): Run the Box egress tests on AgentCore Runtime concurrently * fix(ci): request two-hour E2E AWS sessions * fix(box): Keep the env:// secret of an [egress] route in the Runtime profile (#2970) The Runtime profile removed the secret from each [egress] route that goes through the Box gateway. Without the secret, box does not set the variable, so an agent that reads its stand-in from the variable under agentcore dev gets KeyError on AgentCore Runtime. An HTTP [mcp] server already keeps its env:// secret. Calls to the host still work: the gateway target adds the real key. Only agent code that requires the variable fails. Keep an env:// secret on the route without inject, as for an [mcp] server. Drop a secret of another kind. Box 0.3.3 accepts this form with no value in the variable, gives the agent a stand-in, and refuses inject beside a backend, as strands-agents/box#311 documents. For this local profile entry: [egress.github] destinations = ["api.github.com"] secret.ref = "env://GITHUB_TOKEN" .box//aws/profile.toml before this change: [egress.github] destinations = [ "api.github.com" ] [[egress.github.backends]] url = "${{ inputs.gateway.url }}/egress-github" [egress.github.backends.auth] ref = "aws://" [egress.github.backends.auth.aws] service = "bedrock-agentcore" region = "${{ inputs.aws.region }}" .box//aws/profile.toml after this change: [egress.github] destinations = [ "api.github.com" ] [egress.github.secret] ref = "env://GITHUB_TOKEN" [[egress.github.backends]] url = "${{ inputs.gateway.url }}/egress-github" [egress.github.backends.auth] ref = "aws://" [egress.github.backends.auth.aws] service = "bedrock-agentcore" region = "${{ inputs.aws.region }}" Add a test that gives the route to the box on PATH. * fix(dev): Run a copy of the box profile with its own name each time, also with no collector ## Problem With OTEL off, `agentcore dev` runs `box run` on the local box profile itself. Box then binds the profile name to that file. A subsequent build for a region that is different from the Bedrock region of the profile resolves a copy of the profile with the same name, and box refuses the copy. Thus a build for a different region fails after agentcore dev runs with OTEL off. With OTEL on, dev runs a copy with the name that ends in `-dev` (aws/agentcore-cli#2934), so the default condition does not fail. ## Solution - Dev writes the dev-time copy for each CodeZip box runtime, with the collector on or off. With the collector off, the copy is the local profile with only the `-dev` name (`boxDevNamedProfile`). Dev writes a copy of each policy file in the same folder, the same as with the collector on. `box run` always gets the copy. Thus dev does not bind the name of the local profile. - When the record of box binds the name to the local profile at the start, dev shows one notice. The notice tells the user to remove the record before a build for a different region. Dev does not remove the record, because it can be from a `box run` of the user. - `writeBoxDevProfile` gets the text of the copy as a parameter. The module comment of `boxDevTelemetry.ts` says when each change applies. - Container dev does not change, because box runs in the container and binds no name on the host. - Build does not change. ## Tests - `src/core/dev/box.test.ts` pins the copy and its `-dev` name with DISABLE_ADOT_OBSERVABILITY, with no collector endpoint, and with `enableOtel: false`. It also pins that the copy has no collector target, that the policy file is in the same folder as the copy, and the notice for a record of the local profile. It pins no notice for a record of a different file, or for no record. - The earlier tests require the copy for the runs with no collector. - Mutation: with the earlier branch, which runs the local profile with the collector off, 7 tests fail. The file was put back. - Box 0.3.3 on macOS, not a test double, on a new CodeZip project with `enableOtel: false`: the dev runner ran `box run ../../agentcore/.cli/box-dev/agent/profile.toml`. Box wrote only the record `-agent-dev`. Then `agentcore build --region eu-central-1` passed. After a `box run` of the local profile, dev showed the notice. - Full suite: 6769 pass, 13 skip, 0 fail. tsc, oxlint, and prettier pass. - Not done: a run of `agentcore dev` itself, because port 8080 is in use on the test machine. This change does not fix a build after a `box run` of the local profile by the user. * fix(box): give no MCP route to a project gateway with only HTTP targets (#2971) On AgentCore Runtime, build routes each other gateway of a Box project to the boxed agent as `[mcp.]`. Box parses each POST to that host as an MCP message, so a POST to an HTTP target of the gateway (`passthrough` or `httpRuntime`) was refused with "MCP frame refused", while a GET passed. `add gateway` writes `protocolType: "None"` by default, so the default gateway with a passthrough target hit this. - **Which gateways get a route.** `unroutedReason` is the one rule: a Box gateway, a `CUSTOM_JWT` gateway, and now a gateway whose targets are all HTTP targets get none. A gateway with no target yet, with MCP targets only, or with both kinds keeps its route, whatever its protocolType. A passthrough target with `protocolType: "MCP"` counts as HTTP: a chain of gateways that ends at an MCP server is out of scope. - **Notices, at the write.** `add gateway-target` gives a notice when it adds an HTTP target, `remove gateway-target` when the gateway is left with only HTTP targets (a new `notices` field on the removal result, printed as a warning and shown in the TUI), and `add runtime` for each gateway with HTTP targets. Each only when a boxed runtime that is not PRIVATE_VPC exists. A gateway with both kinds is told that its HTTP targets are not supported yet. - **CUSTOM_JWT with only HTTP targets** gets one notice, which no longer says that AWS_IAM would give it a route. - **Rebuild.** Build removes the `egress-gateway-` target of such a gateway, and the step now says why. - **Text.** The UNSIGNABLE_HOST reason, the gateway rule's doc table, and docs/box-local-testing.md say which gateways get a route. A boxed agent still cannot POST to the HTTP targets of a gateway that also has MCP targets. Routing HTTP targets through an `[egress]` route is a follow-up. Co-authored-by: Abhilash Panigrahi * test(e2e): Test the create wizard's model choices through the wizard's code, then dev, build, deploy and invoke, under a tui tag * fix(dev): Give the dev copy the paths of the local profile, and apply only the policy file checks of Box to it (review) The dev copy of a CodeZip box profile is in agentcore/.cli/box-dev//. Box 0.3.3 resolves three things from the position of the profile file: `policies`, `${{ profile }}`, and `${{ profile.file }}`. Packs and plugins come by name, and Box refuses a relative path in each other key. - Dev writes each `${{ profile }}` and `${{ profile.file }}` in a value of the copy as the folder and the file of the local profile. A `$` before a placeholder keeps it as text, as in Box. - Dev writes a copy of each policy file, with only the checks that Box applies to a policy file. The names that AgentCore Runtime refuses stay in build and in the container image. Dev refuses a policy file with the name profile.toml, because the copy of the profile has that name. Tests: box.test.ts pins a policy file with the name "my rules.dw" for the copy, with the collector off and on. It also pins the paths of the local profile in the two copies. boxNetworkSource.test.ts pins that dev accepts a name that only the Runtime refuses, and that the image copy refuses it. It also pins that dev refuses a missing file and profile.toml. When I broke each of the three checks, 2, 2, and 1 tests gave an error. Then I put the checks back. * feat(box): Sign a LiteLLM model's Bedrock calls with its API key in a Box template * fix(box): Give build's copy of the box profile a name of its own ## Problem A `box run` of the local box profile binds its `[profile] name` to that file in `~/.strands/box/storage//.profile-source`. Box then refuses each other file with that name. For a region that is different from the Bedrock region of the profile, build resolves a copy of the profile with the same name, so box refuses the copy and build stops. Dev now runs its own copy, but a `box run` of the user still makes the record. Also, the error of box named the temporary copy, because box wraps a long path onto more lines. ## Solution - Build gives its copy the name of the local profile with `-build` (`buildCopyProfile`). Only the line of the name changes, so each line that box names in an error is the line of the local profile. `box profile show` binds no name, so the copy leaves no record. - The error of box names the local profile, its folder, and its own name, also where box wrapped them (`replaceWrapped`). - Dev gives no notice for a record of the local profile, because that record no longer stops a build. ## Testing - `bun test` with no box on PATH: 6781 pass, 13 skip, 0 fail. - `bun run typecheck`, `bun run lint:check`, `bun run format:check`, `bun run build`. - Mutation: without the new name and the error mapping, the two new tests of readBoxNetworks fail. - Box 0.3.3 on macOS, CodeZip project: after a `box run` of the local profile and `agentcore dev --no-traces`, `agentcore build --region eu-central-1` passes. Before, it stopped. With an unknown key in the profile, the error of box names `.box/agent/local/profile.toml:22`, not the temporary copy. * chore(cdk): bump @aws/agentcore-cdk pin to 1.5.0 (#2976) Co-authored-by: Abhilash Panigrahi --------- Co-authored-by: Sai Abhishek Co-authored-by: Quang Nguyen Co-authored-by: Abhilash Panigrahi Co-authored-by: Magic Co-authored-by: Abhilash Panigrahi Co-authored-by: Tejas Kashinath Co-authored-by: Tejas Kashinath <42380254+tejaskash@users.noreply.github.com> Co-authored-by: Gitika <53349492+notgitika@users.noreply.github.com> Co-authored-by: gitikavj Co-authored-by: Trirmadura J Ariyawansa Co-authored-by: jariy17 Co-authored-by: agentcore-devx-automation[bot] <282717993+agentcore-devx-automation[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] Co-authored-by: Claude --- .github/workflows/ci.yml | 4 +- .github/workflows/codeql.yml | 6 +- .github/workflows/e2e-test.yml | 118 +- .github/workflows/pr-automation.yml | 6 +- README.md | 107 +- bun.lock | 1 + command.md | 1 + docs/box-local-testing.md | 833 + e2eTest/README.md | 48 + e2eTest/constants.ts | 4 + e2eTest/helpers/create-with-model-provider.ts | 52 + e2eTest/helpers/run.ts | 12 +- e2eTest/project/modelProviders.test.ts | 381 + e2eTest/project/templates.test.ts | 1418 +- package.json | 1 + scripts/bump-box-release.ts | 83 + src/assets/cdk/bin/cdk.ts | 17 +- src/assets/cdk/package.json | 2 +- .../templates/a2a-python-strands/README.md | 5 +- .../a2a-python-strands/model/load.py | 42 + .../agent-python-langchain/README.md | 7 +- .../agent-python-langchain/model/load.py | 2 +- .../Dockerfile.template | 85 + .../gitignore.template | 45 + .../templates/agent-python-strands/README.md | 4 + .../agent-python-strands/model/load.py | 42 + .../templates/agui-python-strands/README.md | 5 +- .../agui-python-strands/model/load.py | 42 + src/assets/templates/box-codezip/start.py | 101 + src/core/dev/box.test.ts | 789 + src/core/dev/box.ts | 233 + src/core/dev/boxAwsCredentials.test.ts | 118 + src/core/dev/boxAwsCredentials.ts | 129 + src/core/dev/boxDevSecrets.test.ts | 172 + src/core/dev/boxDevSecrets.ts | 132 + src/core/dev/boxDevTelemetry.test.ts | 186 + src/core/dev/boxDevTelemetry.ts | 208 + src/core/dev/codezip.test.ts | 1 + src/core/dev/codezip.ts | 85 +- src/core/dev/container.test.ts | 710 +- src/core/dev/container.ts | 327 +- src/core/dev/containerTool.ts | 2 +- src/core/dev/supervisor.test.ts | 3 + src/core/dev/supervisor.ts | 3 + src/core/factories.tsx | 5 + src/core/partition.test.ts | 26 +- src/core/partition.ts | 28 + .../box-network-build-stopped.golden.txt | 11 + .../box-network-build-warnings.golden.txt | 5 + .../box-profile-show-open-routes-list.json | 1 + .../backends/box-release-test-support.ts | 15 + src/core/project/backends/boxCodeZip.test.ts | 270 + src/core/project/backends/boxCodeZip.ts | 58 + .../project/backends/boxContainer.test.ts | 279 + src/core/project/backends/boxContainer.ts | 197 + src/core/project/backends/boxRelease.json | 16 + src/core/project/backends/boxRelease.test.ts | 280 + src/core/project/backends/boxRelease.ts | 290 + src/core/project/backends/boxStaging.ts | 57 + src/core/project/backends/boxStartPy.test.ts | 138 + src/core/project/backends/cdk.test.ts | 792 +- src/core/project/backends/cdk.ts | 260 +- .../project/backends/cdk/assembly.test.ts | 147 +- src/core/project/backends/cdk/assembly.ts | 118 +- .../backends/cdk/compatibility.test.ts | 94 + .../project/backends/cdk/compatibility.ts | 78 + .../project/backends/cdk/deployedState.ts | 11 + .../backends/cdk/telemetrySecrets.test.ts | 651 + .../project/backends/cdk/telemetrySecrets.ts | 472 + src/core/project/backends/types.ts | 13 +- src/core/project/boxDevNameRecord.test.ts | 109 + src/core/project/boxDevNameRecord.ts | 84 + src/core/project/boxGatewayTargets.test.ts | 42 + src/core/project/boxGatewayTargets.ts | 152 + src/core/project/boxMemory.test.ts | 339 + src/core/project/boxMemory.ts | 425 + src/core/project/boxNetwork/conditions.ts | 622 + src/core/project/boxNetwork/dogwood.test.ts | 204 + src/core/project/boxNetwork/dogwood.ts | 772 + src/core/project/boxNetwork/egress.ts | 294 + src/core/project/boxNetwork/hostMap.test.ts | 418 + src/core/project/boxNetwork/hostMap.ts | 982 ++ src/core/project/boxNetwork/index.ts | 27 + src/core/project/boxNetwork/network.test.ts | 1982 +++ src/core/project/boxNetwork/network.ts | 1043 ++ .../project/boxNetwork/pathSolver.test.ts | 105 + src/core/project/boxNetwork/pathSolver.ts | 168 + src/core/project/boxNetwork/places.ts | 95 + .../project/boxNetwork/policyParser.test.ts | 105 + src/core/project/boxNetwork/policyParser.ts | 93 + .../project/boxNetwork/profileParser.test.ts | 208 + src/core/project/boxNetwork/profileParser.ts | 217 + .../boxNetwork/projectGateways.test.ts | 257 + .../project/boxNetwork/projectGateways.ts | 258 + .../project/boxNetwork/projectSpec.test.ts | 147 + src/core/project/boxNetwork/projectSpec.ts | 81 + src/core/project/boxNetwork/telemetry.test.ts | 250 + src/core/project/boxNetwork/telemetry.ts | 262 + src/core/project/boxNetwork/types.ts | 105 + src/core/project/boxNetworkSource.test.ts | 1189 ++ src/core/project/boxNetworkSource.ts | 845 + src/core/project/boxNetworkWriters.test.ts | 978 ++ src/core/project/boxNetworkWriters.ts | 803 + .../project/boxProfileCredentials.test.ts | 415 + src/core/project/boxProfileCredentials.ts | 296 + src/core/project/boxProfileEgress.test.ts | 11 + src/core/project/boxProfileEgress.ts | 7 + .../boxProfileResolver-test-support.ts | 143 + src/core/project/boxProfileResolver.test.ts | 690 + src/core/project/boxProfileResolver.ts | 270 + src/core/project/boxTelemetry.test.ts | 171 + src/core/project/boxTelemetry.ts | 116 + src/core/project/boxTelemetrySecrets.test.ts | 207 + src/core/project/boxTelemetrySecrets.ts | 160 + src/core/project/boxValidation.test.ts | 131 + src/core/project/boxValidation.ts | 144 + src/core/project/envLocal.test.ts | 70 + src/core/project/envLocal.ts | 47 + src/core/project/events.test.ts | 37 +- src/core/project/events.ts | 28 +- src/core/project/manager.box.test.ts | 1670 ++ .../project/manager.boxCredentials.test.ts | 395 + src/core/project/manager.boxNetwork.test.ts | 2409 +++ src/core/project/manager.export.test.ts | 19 +- src/core/project/manager.test.ts | 642 +- src/core/project/manager.tsx | 803 +- src/core/project/runtimeBuild.test.ts | 50 + src/core/project/runtimeBuild.ts | 28 +- .../__fixtures__/old-renderer-tables.json | 14144 ++++++++++++++++ src/core/project/runtimeProfile/context.ts | 143 + .../project/runtimeProfile/derive.test.ts | 183 + src/core/project/runtimeProfile/derive.ts | 55 + .../project/runtimeProfile/projectPaths.ts | 276 + .../runtimeProfile/rules/additions.test.ts | 1921 +++ .../project/runtimeProfile/rules/additions.ts | 917 + .../runtimeProfile/rules/gateway.test.ts | 980 ++ .../project/runtimeProfile/rules/gateway.ts | 336 + .../runtimeProfile/rules/paths.test.ts | 373 + .../project/runtimeProfile/rules/paths.ts | 137 + .../runtimeProfile/rules/refusals.test.ts | 499 + .../project/runtimeProfile/rules/refusals.ts | 258 + src/core/project/runtimeProfile/serialize.ts | 15 + src/core/project/runtimeProfile/types.ts | 160 + src/core/project/templates/boxProfile.test.ts | 827 + src/core/project/templates/boxProfile.ts | 1109 ++ src/core/project/templates/boxStartPy.test.ts | 163 + src/core/project/templates/fsTree.ts | 12 + src/core/project/templates/project.ts | 159 +- src/core/project/templates/runtime.test.ts | 160 +- src/core/project/templates/runtime.ts | 70 +- src/core/project/templates/spec.ts | 2 + src/core/project/templates/types.ts | 5 + src/core/region.test.ts | 121 +- src/core/region.ts | 28 +- src/core/types.tsx | 2 + src/handlers/gateway/invoke/index.tsx | 4 +- src/handlers/gateway/invoke/invoke.test.tsx | 38 + src/handlers/gateway/invoke/response.ts | 18 + src/handlers/gateway/invoke/screen.tsx | 9 +- .../gateway-connector.screen.test.tsx | 23 +- .../add/gateway-connector/index.test.ts | 31 +- .../project/add/gateway-connector/index.ts | 7 +- .../project/add/gateway-connector/screen.tsx | 5 +- .../gateway-target.screen.test.tsx | 49 + .../project/add/gateway-target/index.test.ts | 116 + .../project/add/gateway-target/index.ts | 3 +- .../project/add/gateway-target/screen.tsx | 5 +- .../project/add/gateway-test-support.ts | 7 +- .../project/add/runtime/screen.test.ts | 27 + src/handlers/project/add/runtime/screen.tsx | 31 +- src/handlers/project/add/shared.test.ts | 19 + src/handlers/project/add/shared.ts | 34 + src/handlers/project/bma.ts | 3 +- src/handlers/project/build/index.test.ts | 16 + src/handlers/project/build/index.ts | 5 +- src/handlers/project/build/screen.tsx | 3 + .../project/buildDeploy.screen.test.tsx | 27 +- .../project/create/create.screen.test.tsx | 134 +- src/handlers/project/create/index.ts | 39 +- src/handlers/project/create/region.ts | 20 +- src/handlers/project/create/screen.tsx | 61 +- src/handlers/project/deploy/index.test.ts | 1 + src/handlers/project/dev/index.test.ts | 52 + src/handlers/project/dev/index.ts | 24 +- src/handlers/project/dev/types.ts | 5 + src/handlers/project/index.ts | 3 +- src/handlers/project/migrate/index.test.ts | 6 +- src/handlers/project/output.ts | 4 +- src/handlers/project/project.test.ts | 101 + src/handlers/project/remove/index.test.ts | 257 +- src/handlers/project/remove/index.ts | 9 +- src/handlers/project/remove/notice.test.ts | 35 + src/handlers/project/remove/notice.ts | 39 + .../project/remove/remove.screen.test.tsx | 72 +- src/handlers/project/remove/screen.tsx | 19 +- .../project/runtimeTemplateProfile.test.ts | 28 + .../project/runtimeTemplateProfile.ts | 20 +- src/handlers/project/shortcuts.test.ts | 49 + src/handlers/project/shortcuts.ts | 287 +- src/handlers/project/types.ts | 33 +- src/io/exec.test.ts | 44 + src/io/exec.ts | 20 + src/projectSchemas/gateway.test.ts | 58 + src/projectSchemas/gateway.ts | 51 +- src/projectSchemas/project.test.ts | 481 +- src/projectSchemas/project.ts | 286 +- src/projectSchemas/runtime.test.ts | 13 + src/projectSchemas/runtime.ts | 114 +- src/projectSchemas/tags.ts | 10 +- src/testing/TestCoreClient.tsx | 6 + 210 files changed, 58930 insertions(+), 490 deletions(-) create mode 100644 docs/box-local-testing.md create mode 100644 e2eTest/helpers/create-with-model-provider.ts create mode 100644 e2eTest/project/modelProviders.test.ts create mode 100644 scripts/bump-box-release.ts create mode 100644 src/assets/templates/agent-python-strands-box/Dockerfile.template create mode 100644 src/assets/templates/agent-python-strands-box/gitignore.template create mode 100644 src/assets/templates/box-codezip/start.py create mode 100644 src/core/dev/box.test.ts create mode 100644 src/core/dev/box.ts create mode 100644 src/core/dev/boxAwsCredentials.test.ts create mode 100644 src/core/dev/boxAwsCredentials.ts create mode 100644 src/core/dev/boxDevSecrets.test.ts create mode 100644 src/core/dev/boxDevSecrets.ts create mode 100644 src/core/dev/boxDevTelemetry.test.ts create mode 100644 src/core/dev/boxDevTelemetry.ts create mode 100644 src/core/project/__fixtures__/box-network-build-stopped.golden.txt create mode 100644 src/core/project/__fixtures__/box-network-build-warnings.golden.txt create mode 100644 src/core/project/__fixtures__/box-profile-show-open-routes-list.json create mode 100644 src/core/project/backends/box-release-test-support.ts create mode 100644 src/core/project/backends/boxCodeZip.test.ts create mode 100644 src/core/project/backends/boxCodeZip.ts create mode 100644 src/core/project/backends/boxContainer.test.ts create mode 100644 src/core/project/backends/boxContainer.ts create mode 100644 src/core/project/backends/boxRelease.json create mode 100644 src/core/project/backends/boxRelease.test.ts create mode 100644 src/core/project/backends/boxRelease.ts create mode 100644 src/core/project/backends/boxStaging.ts create mode 100644 src/core/project/backends/boxStartPy.test.ts create mode 100644 src/core/project/backends/cdk/telemetrySecrets.test.ts create mode 100644 src/core/project/backends/cdk/telemetrySecrets.ts create mode 100644 src/core/project/boxDevNameRecord.test.ts create mode 100644 src/core/project/boxDevNameRecord.ts create mode 100644 src/core/project/boxGatewayTargets.test.ts create mode 100644 src/core/project/boxGatewayTargets.ts create mode 100644 src/core/project/boxMemory.test.ts create mode 100644 src/core/project/boxMemory.ts create mode 100644 src/core/project/boxNetwork/conditions.ts create mode 100644 src/core/project/boxNetwork/dogwood.test.ts create mode 100644 src/core/project/boxNetwork/dogwood.ts create mode 100644 src/core/project/boxNetwork/egress.ts create mode 100644 src/core/project/boxNetwork/hostMap.test.ts create mode 100644 src/core/project/boxNetwork/hostMap.ts create mode 100644 src/core/project/boxNetwork/index.ts create mode 100644 src/core/project/boxNetwork/network.test.ts create mode 100644 src/core/project/boxNetwork/network.ts create mode 100644 src/core/project/boxNetwork/pathSolver.test.ts create mode 100644 src/core/project/boxNetwork/pathSolver.ts create mode 100644 src/core/project/boxNetwork/places.ts create mode 100644 src/core/project/boxNetwork/policyParser.test.ts create mode 100644 src/core/project/boxNetwork/policyParser.ts create mode 100644 src/core/project/boxNetwork/profileParser.test.ts create mode 100644 src/core/project/boxNetwork/profileParser.ts create mode 100644 src/core/project/boxNetwork/projectGateways.test.ts create mode 100644 src/core/project/boxNetwork/projectGateways.ts create mode 100644 src/core/project/boxNetwork/projectSpec.test.ts create mode 100644 src/core/project/boxNetwork/projectSpec.ts create mode 100644 src/core/project/boxNetwork/telemetry.test.ts create mode 100644 src/core/project/boxNetwork/telemetry.ts create mode 100644 src/core/project/boxNetwork/types.ts create mode 100644 src/core/project/boxNetworkSource.test.ts create mode 100644 src/core/project/boxNetworkSource.ts create mode 100644 src/core/project/boxNetworkWriters.test.ts create mode 100644 src/core/project/boxNetworkWriters.ts create mode 100644 src/core/project/boxProfileCredentials.test.ts create mode 100644 src/core/project/boxProfileCredentials.ts create mode 100644 src/core/project/boxProfileEgress.test.ts create mode 100644 src/core/project/boxProfileEgress.ts create mode 100644 src/core/project/boxProfileResolver-test-support.ts create mode 100644 src/core/project/boxProfileResolver.test.ts create mode 100644 src/core/project/boxProfileResolver.ts create mode 100644 src/core/project/boxTelemetry.test.ts create mode 100644 src/core/project/boxTelemetry.ts create mode 100644 src/core/project/boxTelemetrySecrets.test.ts create mode 100644 src/core/project/boxTelemetrySecrets.ts create mode 100644 src/core/project/boxValidation.test.ts create mode 100644 src/core/project/boxValidation.ts create mode 100644 src/core/project/manager.box.test.ts create mode 100644 src/core/project/manager.boxCredentials.test.ts create mode 100644 src/core/project/manager.boxNetwork.test.ts create mode 100644 src/core/project/runtimeProfile/__fixtures__/old-renderer-tables.json create mode 100644 src/core/project/runtimeProfile/context.ts create mode 100644 src/core/project/runtimeProfile/derive.test.ts create mode 100644 src/core/project/runtimeProfile/derive.ts create mode 100644 src/core/project/runtimeProfile/projectPaths.ts create mode 100644 src/core/project/runtimeProfile/rules/additions.test.ts create mode 100644 src/core/project/runtimeProfile/rules/additions.ts create mode 100644 src/core/project/runtimeProfile/rules/gateway.test.ts create mode 100644 src/core/project/runtimeProfile/rules/gateway.ts create mode 100644 src/core/project/runtimeProfile/rules/paths.test.ts create mode 100644 src/core/project/runtimeProfile/rules/paths.ts create mode 100644 src/core/project/runtimeProfile/rules/refusals.test.ts create mode 100644 src/core/project/runtimeProfile/rules/refusals.ts create mode 100644 src/core/project/runtimeProfile/serialize.ts create mode 100644 src/core/project/runtimeProfile/types.ts create mode 100644 src/core/project/templates/boxProfile.test.ts create mode 100644 src/core/project/templates/boxProfile.ts create mode 100644 src/core/project/templates/boxStartPy.test.ts create mode 100644 src/handlers/project/add/runtime/screen.test.ts create mode 100644 src/handlers/project/add/shared.test.ts create mode 100644 src/handlers/project/remove/notice.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3abfac07bd..d9dc2aaf65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [v0.x, v1.x] + branches: [v0.x, v1.x, box-integration] pull_request: - branches: [v0.x, v1.x] + branches: [v0.x, v1.x, box-integration] workflow_dispatch: concurrency: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 487044fd8e..216bac03b6 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -2,13 +2,13 @@ name: CodeQL on: push: - branches: [v0.x, v1.x] + branches: [v0.x, v1.x, box-integration] pull_request: - branches: [v0.x, v1.x, "feat/**"] + branches: [v0.x, v1.x, box-integration, "feat/**"] concurrency: group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: ${{ github.ref != 'refs/heads/v0.x' && github.ref != 'refs/heads/v1.x' }} + cancel-in-progress: ${{ github.ref != 'refs/heads/v0.x' && github.ref != 'refs/heads/v1.x' && github.ref != 'refs/heads/box-integration' }} jobs: analyze: diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index f9eb985d41..fa0c8a7ce5 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -22,6 +22,16 @@ on: required: false type: boolean default: false + l3Ref: + description: aws/agentcore-l3-cdk-constructs ref the Box tests deploy with (branch, tag, or commit) + required: false + type: string + default: box-integration + region: + description: AWS region to deploy and test in; empty uses the E2E_REGION variable, else us-east-1 + required: false + type: string + default: "" secrets: WORKFLOW_SECRETS_READER_ROLE_ARN: required: true @@ -39,6 +49,14 @@ on: description: Run E2E tests only on Linux type: boolean default: false + l3Ref: + description: aws/agentcore-l3-cdk-constructs ref the Box tests deploy with (branch, tag, or commit) + type: string + default: box-integration + region: + description: AWS region to deploy and test in; empty uses the E2E_REGION variable, else us-east-1 + type: string + default: "" concurrency: group: e2e-test-${{ inputs.ref || github.ref }}-${{ inputs.tags || 'all' }}-${{ inputs.linuxOnly && 'linux-only' || 'all-os' }} @@ -90,6 +108,7 @@ jobs: matrix.name == 'Linux' && '["ubuntu-latest"]' || matrix.name == 'Windows' && '["windows-latest"]' || matrix.name == 'macOS' && '["macos-latest"]' + || matrix.name == 'Linux-arm64' && '["ubuntu-24.04-arm"]' ) }} permissions: id-token: write @@ -97,7 +116,7 @@ jobs: strategy: fail-fast: false matrix: - name: ${{ fromJSON(inputs.linuxOnly && '["Linux"]' || '["Linux","Windows","macOS"]') }} + name: ${{ fromJSON(inputs.linuxOnly && '["Linux"]' || '["Linux","Linux-arm64","Windows","macOS"]') }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -111,6 +130,9 @@ jobs: with: # Keep template installs on the newest Python supported by AgentCore CodeZip. python-version: "3.14" + # A run whose tag filter leaves nothing to install with uv (for example `box` on Windows, + # which has no box) has no cache to save, which setup-uv otherwise reports as a failure. + ignore-nothing-to-cache: true - run: bun install --frozen-lockfile - name: Fetch E2E role from Secrets Manager uses: aws/agentcore-devx-devtools/.github/actions/fetch-secrets@e68d09b0c33dfb7a798448d50e6b48beedf00a3b @@ -121,8 +143,96 @@ jobs: uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: role-to-assume: ${{ env.E2E_AWS_ROLE_ARN }} - aws-region: ${{ vars.E2E_REGION || 'us-east-1' }} + aws-region: ${{ inputs.region || vars.E2E_REGION || 'us-east-1' }} + role-duration-seconds: 7200 unset-current-credentials: true + # box ships only arm64 builds, so only the macOS (Apple silicon) and Linux arm64 runners can run + # the Box tests. They skip on a runner with no box on PATH. + - name: Install box + if: matrix.name == 'macOS' || matrix.name == 'Linux-arm64' + env: + # The build's key in boxRelease.json, which pins its archive and SHA-256. + BUILD: ${{ matrix.name == 'macOS' && 'darwin' || 'linux' }} + run: | + PIN=src/core/project/backends/boxRelease.json + REPO=$(jq -er .box.repo "$PIN") + # A build may name its own release, for a release whose build of this machine is broken. + VER=$(jq -er ".box.${BUILD}.version // .box.version" "$PIN") + ASSET=$(jq -er ".box.${BUILD}.asset" "$PIN") + SHA=$(jq -er ".box.${BUILD}.sha256" "$PIN") + # macOS's sha256sum passes a malformed checksum line, so check the hash's shape first. + if [[ ! "$SHA" =~ ^[0-9a-f]{64}$ ]]; then + echo "the pinned .box.${BUILD}.sha256 in $PIN is not a SHA-256: '$SHA'" >&2 + exit 1 + fi + WORK=$(mktemp -d) + curl -fsSL --retry 3 -o "${WORK}/${ASSET}" \ + "https://github.com/${REPO}/releases/download/v${VER}/${ASSET}" + # Check against the pin in the repository, not a checksum file of the same release. + # Linux has sha256sum, and macOS may have only shasum. + SUM=$(command -v sha256sum || echo "shasum -a 256") + echo "${SHA} ${WORK}/${ASSET}" | $SUM -c - + # box reads its packs from resources/ beside it, so keep the release together. + if [[ "$BUILD" == darwin ]]; then + # On macOS, unpack as the runner user into a folder it owns, as a developer does. The + # folder must not be named `box`: macOS reads a folder `box` that holds an executable + # `box` as a bundle, finds the signature invalid (`invalid Info.plist`), and kills box at + # launch (Killed: 9). That is what happened under /opt/box. + DIR="${RUNNER_TEMP}/box-${VER}" + mkdir -p "$DIR" + tar -xzf "${WORK}/${ASSET}" -C "$DIR" + echo "$DIR" >> "$GITHUB_PATH" + # If macOS refuses box, say why before running it. + codesign --verify --strict --verbose=2 "$DIR/box" || codesign -dv --verbose=4 "$DIR/box" || true + if ! "$DIR/box" --version; then + log show --last 2m --predicate 'eventMessage CONTAINS "box"' --style compact 2>/dev/null | tail -40 || true + exit 1 + fi + else + sudo mkdir -p /opt/box + sudo tar --no-same-owner -xzf "${WORK}/${ASSET}" -C /opt/box + sudo ln -sf /opt/box/box /usr/local/bin/box + box --version + fi + # Ubuntu 24.04 lets AppArmor stop an unprivileged process from making a user namespace, which + # `box run` needs for its sandbox. The runner is a throwaway VM. + - name: Allow user namespaces for box + if: matrix.name == 'Linux-arm64' + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + # No released @aws/agentcore-cdk deploys a Box project yet, so on the runners that run the Box + # tests, they deploy with one built from aws/agentcore-l3-cdk-constructs at inputs.l3Ref. That + # repository is private and this job's GITHUB_TOKEN reads only this one, so the token comes + # from the repository's GitHub App, scoped to the L3 repository and read-only. + - name: Generate a read token for the L3 constructs + if: matrix.name == 'macOS' || matrix.name == 'Linux-arm64' + id: l3-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ vars.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + owner: aws + repositories: agentcore-l3-cdk-constructs + permission-contents: read + - name: Check out the L3 constructs + if: matrix.name == 'macOS' || matrix.name == 'Linux-arm64' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: aws/agentcore-l3-cdk-constructs + ref: ${{ inputs.l3Ref || 'box-integration' }} + token: ${{ steps.l3-token.outputs.token }} + path: .l3-cdk + # 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). + - name: Pack the L3 constructs for the Box tests + if: matrix.name == 'macOS' || matrix.name == 'Linux-arm64' + working-directory: .l3-cdk + run: | + npm ci --no-audit --no-fund + npm run build + TARBALL=$(npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" | tail -n 1) + echo "AGENTCORE_E2E_BOX_CDK=file:${RUNNER_TEMP}/${TARBALL}" >> "$GITHUB_ENV" - name: Build CLI if: inputs.npmVersion == '' run: bun run build @@ -137,11 +247,11 @@ jobs: if: inputs.tags == '' env: AGENTCORE_CLI_PATH: ${{ inputs.npmVersion != '' && 'agentcore' || format('node {0}/dist/index.js', github.workspace) }} - AWS_REGION: ${{ vars.E2E_REGION || 'us-east-1' }} + AWS_REGION: ${{ inputs.region || vars.E2E_REGION || 'us-east-1' }} run: bun run test:e2e - name: Run tagged E2E tests if: inputs.tags != '' env: AGENTCORE_CLI_PATH: ${{ inputs.npmVersion != '' && 'agentcore' || format('node {0}/dist/index.js', github.workspace) }} - AWS_REGION: ${{ vars.E2E_REGION || 'us-east-1' }} + AWS_REGION: ${{ inputs.region || vars.E2E_REGION || 'us-east-1' }} run: bun run test:e2e -- --tagsFilter="${{ inputs.tags }}" diff --git a/.github/workflows/pr-automation.yml b/.github/workflows/pr-automation.yml index 0f24d2e73f..7c3ef0eeb1 100644 --- a/.github/workflows/pr-automation.yml +++ b/.github/workflows/pr-automation.yml @@ -2,7 +2,7 @@ name: PR Automation on: pull_request_target: - branches: [v0.x, v1.x, "feat/**"] + branches: [v0.x, v1.x, box-integration, "feat/**"] types: [opened, reopened, edited, synchronize, labeled] workflow_dispatch: inputs: @@ -46,7 +46,7 @@ jobs: with: runner: ubuntu pr_number: ${{ inputs.pr_number || format('{0}', github.event.pull_request.number) }} - allowed_base_branches: '["v0.x","v1.x"]' + allowed_base_branches: '["v0.x","v1.x","box-integration"]' secrets: inherit harness-review: @@ -113,7 +113,7 @@ jobs: fi case "$base_ref" in - v0.x|v1.x|feat/*) ;; + v0.x|v1.x|box-integration|feat/*) ;; *) echo "::error::Unsupported base branch: $base_ref" exit 1 diff --git a/README.md b/README.md index 911806ba48..0118638357 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,10 @@ flags: for templates that take a model provider (`agent-python-strands` and its variant, `a2a-python-strands`, `agui-python-strands`, `agent-typescript-strands`) the wizard asks for the provider (Amazon Bedrock, Anthropic, OpenAI, an OpenAI-compatible endpoint, Gemini, or LiteLLM, which is Python-only), the model id, and an API-key file. The API key is kept in -`agentcore/.env.local` and provisioned as an AgentCore Identity credential on deploy. +`agentcore/.env.local` and provisioned as an AgentCore Identity credential on deploy. For a Box +template created with no API key, build reads the provider's key (such as `OPENAI_API_KEY`) from +your shell or `agentcore/.env.local`, adds a credential such as `openai`, and deploy provisions +that key in AgentCore Identity. To bring your own code into a project instead, add a runtime for it: @@ -206,6 +209,108 @@ yourself. Note that `agentcore status` reports only the resources `agentcore.json` declares, not the ones you add in the stack. +## Running agents in Box (preview) + +Six templates run their agent in a box, both under `agentcore dev` and on AgentCore Runtime: +the CodeZip templates `agent-python-strands-box`, `agent-python-minimal-box`, +`agent-python-langchain-box`, `a2a-python-strands-box`, and `agui-python-strands-box`, and the +container template `agent-python-strands-box-container`. +`agentcore create --template ` makes a Box project from one of them; every other template +runs its agent without box. Each runtime of a Box project runs in a box, with its own box profile, +`.box//local/profile.toml`. `agentcore add runtime` adds a Python CodeZip runtime in a box +to a Box project, and refuses a TypeScript runtime and a Bedrock Agent import there. +`agentcore export harness` refuses a Box project. Each box runtime needs its +`"box": { "version": ... }` in `agentcore.json`, which create and add runtime write, and its local +box profile; build and deploy stop without them. Build derives the AgentCore Runtime profile of +each runtime from its local profile. box comes from the `box-cli` archives of the public GitHub +release `v0.3.3` of [strands-agents/box](https://github.com/strands-agents/box/releases). No token +or account is needed to download it. Use that release's build for your machine for `agentcore dev` +and the profile checks of `build`: an older box cannot read the profiles that this CLI writes. + +`src/core/project/backends/boxRelease.json` pins the Linux build of box that ships to AgentCore +Runtime, with its repository, version and SHA-256. It also pins the macOS arm64 build, which the e2e +workflow installs on its macOS runner. `bun scripts/bump-box-release.ts --box ` +(with `--box-repo` to move repository) rewrites the file from the release's `SHA256SUMS.txt`. + +How each command uses it: + +- A CodeZip agent's zip carries box. `build` and `deploy` download box once with `curl` into + `~/.agentcore/box/`, check it against its pinned SHA-256, and stage box and its packs into the + runtime's `.box-dist/`. +- A container agent's image downloads box while it builds. `dev`, `build` and `deploy` stage the + release that `box.version` names, with its checksum, as `box-release.env` beside the Dockerfile + (`.box-dist/`, or `.box-dev/` under `dev`), and the Dockerfile downloads that release with `curl`, + checks its SHA-256 and unpacks it into `/opt/box`. The CLI downloads nothing for a container, so + the build machine, or AWS CodeBuild on `deploy`, needs network to github.com. `agentcore dev` + builds the image on your machine and `agentcore deploy` builds it in AWS CodeBuild. +- A CodeZip agent under `agentcore dev` runs in the `box` on your PATH, which you install from + the release: download the build for your machine, unpack it into a folder, and add that folder + to your PATH. `agentcore create --template agent-python-strands-box` and `agentcore dev` stop + with that instruction when `box` is not on your PATH. Container agents need no local box. + +Each box runtime names its release in `agentcore.json` with `"box": { "version": "" }`, +which `agentcore create` writes. Every box runtime runs the pinned version, whose checksums +`boxRelease.json` keeps: build and deploy set `box.version` to it, and say so when it named another. + +On AgentCore Runtime, box signs the agent's Bedrock and Memory calls with the execution role: the +profile's bare `aws://` resolves the AWS default credential chain, which box reads and refreshes +itself. + +### Create, run and deploy + +```sh +agentcore create --name MyBoxAgent --template agent-python-strands-box-container +cd MyBoxAgent +AGENTCORE_CONTAINER_TOOL=finch agentcore dev # optional +agentcore deploy --yes +agentcore invoke --runtime agent --session-id my-box-session-0000000000000000000001 --payload '{"prompt":"My favorite color is teal. Remember it."}' +agentcore invoke --runtime agent --session-id my-box-session-0000000000000000000001 --payload '{"prompt":"What is my favorite color?"}' +agentcore logs runtime --name agent --since 15m --query '"running profile"' +``` + +The CodeBuild log of the deploy shows `/tmp/box.tar.gz: OK` and `box 0.3.3`. The +second answer should say teal, and the runtime log shows `running profile ...` with no `ERROR`, +`blocked by egress control` or `AccessDenied` line. For a CodeZip agent, use +`--template agent-python-strands-box` and skip the container settings. + +A boxed agent gets the deployed Memory IDs and the Runtime's region inside the box. It does not get +the `AGENTCORE_GATEWAY__URL` variables of gateways you add yourself: its calls go out through +its Box gateway. When the project has a Memory, each runtime of the project gets every Memory of +the project, and its calls to the AgentCore host (`bedrock-agentcore..amazonaws.com`) are +the exception: box signs them with the execution role and sends them to that host directly, so +Memory can hold each call to the session of the runtime. Box routes a connection by its host alone, +and Code Interpreter, Browser, and the other AgentCore APIs share that host, so their calls go +there directly too, and the execution role needs the grants for them (a `codeInterpreter` or +`browser` connection of the runtime gives one). No boxed runtime of a project with a Memory can send +a credential of its own to that host: build stops for a profile entry with a secret other than +`aws://`, or a Box gateway target with an API key or OAuth credential, that would. A `PRIVATE_VPC` runtime +reaches that host through the AgentCore endpoint of its private VPC, which only the runtime's role +may call through. Code in the box can make any AgentCore call on that host that the +execution role allows, so a `bedrock-agentcore` grant added through `additionalPolicies` is open +to it. A runtime in a VPC of your own needs a `bedrock-agentcore` VPC endpoint. + +A Box project that an older CLI created still has `start.sh`, or a Dockerfile that runs it. Build +and deploy now render profiles that those files cannot start. Create the project again, or copy +`start.py` (CodeZip) or the `Dockerfile` (container) from a new `agentcore create` project. + +### Containment + +`agentcore create --containment private-vpc` with a box template also runs the runtime in its own +private VPC with no internet path. It writes `"containment": "PRIVATE_VPC"` on the runtime. + +### Troubleshooting + +- `ExpiredTokenException` from `aws` or `deploy`: your AWS credentials expired. Refresh them and + run the command again. +- `curl: (22) The requested URL returned error: 404` in the CodeBuild log, or a deploy error that + names the release URL: the pinned version is not published in `strands-agents/box`. +- `SHA-256 ... not the pinned` or `sha256sum: WARNING: 1 computed checksum did NOT match`: the + release asset changed after it was pinned. Nothing was installed. +- `box run` exits with an error in the runtime log: box refused its profile, and the agent does + not start. The error names the reason. The agent never runs outside box on AgentCore Runtime. +- A CodeZip agent on `PYTHON_3_10` needs `tomli` in its dependencies, because `start.py` reads the + profile with it there. `agent-python-strands-box` lists it. + ## Documentation - [AWS Billing connectors](docs/aws-billing.md): headless configuration and deployment prerequisites. diff --git a/bun.lock b/bun.lock index 9baf246f08..e9ab0a6e08 100644 --- a/bun.lock +++ b/bun.lock @@ -15,6 +15,7 @@ "@aws-sdk/client-cloudwatch-logs": "^3.1092.0", "@aws-sdk/client-iam": "^3.1080.0", "@aws-sdk/client-s3": "^3.1121.0", + "@aws-sdk/client-secrets-manager": "^3.1121.0", "@aws-sdk/client-sts": "^3.1092.0", "@aws-sdk/client-xray": "^3.1092.0", "@aws-sdk/util-endpoints": "^3.996.44", diff --git a/command.md b/command.md index e3e1480730..19e14c0f9f 100644 --- a/command.md +++ b/command.md @@ -270,6 +270,7 @@ create a new project - `--name `: name of the project to create (required) - `--template