diff --git a/docs/services/bedrock-agentcore.md b/docs/services/bedrock-agentcore.md index 0d60336e10..ed00b0c81d 100644 --- a/docs/services/bedrock-agentcore.md +++ b/docs/services/bedrock-agentcore.md @@ -79,6 +79,12 @@ runtimes reach `READY` immediately and hold metadata only. See | `GetResourcePolicy` | Returns the policy attached to an AgentCore resource | | `PutResourcePolicy` | Creates or replaces a policy on an AgentCore resource | | `DeleteResourcePolicy` | Deletes the policy attached to an AgentCore resource | +| `CreateHarness` | Creates a harness at version 1, filling in AWS's defaults; see [Harnesses](#harnesses) | +| `ListHarnesses` | Lists harnesses (paginated) | +| `GetHarness` | Returns a harness, optionally at a specific `harnessVersion` | +| `UpdateHarness` | Updates a harness; appends a new immutable version | +| `DeleteHarness` | Deletes a harness | +| `ListHarnessVersions` | Lists a harness's versions, newest first (paginated) | A `DEFAULT` endpoint is created automatically with each runtime, and each runtime @@ -104,6 +110,30 @@ than a fixed answer. Behaviour measured against real AgentCore: Memory *records* (extraction and retrieval) are not emulated: they depend on an extraction engine rather than on stored events. +## Harnesses + +A harness is stored with its configuration and settles in `READY` at once. No agent runtime is +started for it, and `InvokeHarness` does not read it. + +- `harnessName` (a letter, then up to 39 letters, digits and underscores) and `executionRoleArn` + are required. The id is the name plus `-` and 10 alphanumerics, and a second harness with the + same name in the Region is a `ConflictException`. A repeated `clientToken` answers the harness + the first call created. +- Members a request leaves out are filled in as AWS fills them: `apiFormat` `converse_stream` on a + `bedrockModelConfig`, empty `systemPrompt`, `tools`, `skills`, `allowedTools` and + `environmentVariables`, and a `sliding_window` truncation keeping 150 messages. `memory`, + `maxIterations`, `maxTokens` and `timeoutSeconds` are returned only when given. +- `environment.agentCoreRuntimeEnvironment` names the harness's runtime `harness_`, with an + id and ARN that stay the same across updates, a 900-second idle session timeout and an 8-hour + maximum lifetime unless given, and `PUBLIC` networking. +- Each `UpdateHarness` appends a version. A member the request carries replaces the current one; + `environmentArtifact`, `authorizerConfiguration` and `memory` are set through `optionalValue`, + and an empty wrapper removes them. `GetHarness?harnessVersion=` reads an earlier version. +- An unknown harness is `ResourceNotFoundException` with AWS's message, "Agent with name `` not + found.", and an unknown version "Version `` not found for harness ``". +- Tags are set with `tags` on create and through the shared `/tags/{resourceArn}` route. + `deleteManagedMemory` on `DeleteHarness` is accepted and has no effect. + ## Data plane — `InvokeAgentRuntime` `POST /runtimes/{agentRuntimeArn}/invocations` returns a fixed, configurable JSON @@ -135,8 +165,8 @@ message**, so a chat client visibly works end to end and a request that failed t rather than hidden behind a fixed string. A request whose `messages` array is present but empty, or carries no user turn, is legitimate and gets a canned reply rather than an error. -The `harnessArn` is not resolved: the emulator models no harness resource, so there is nothing to -look one up in. Tool execution, skills and multi-turn iteration are not emulated, so no tool-use +The `harnessArn` is not resolved against the [harnesses](#harnesses) created through the control +plane, so an application can invoke a harness it never created here. Tool execution, skills and multi-turn iteration are not emulated, so no tool-use block is ever produced even when a request supplies `tools`. ## Configuration diff --git a/docs/services/index.md b/docs/services/index.md index 1e5bfb7cc5..6152ccac5f 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -101,7 +101,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AppSync](appsync.md) | `/v1/apis/...` | REST JSON | 33 | | [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 12 | | [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/invoke` | REST JSON | 2 (stub; streaming returns 501) | -| [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 65 (+ 3 tagging via shared `/tags/{arn}` route) | +| [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/harnesses*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 71 (+ 3 tagging via shared `/tags/{arn}` route) | | [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) | | [EKS](eks.md) | `/clusters`, `/clusters/{name}`, `/tags/{resourceArn}` | REST JSON | 7 | | [ELB v2](elb.md) | `POST /` with `Action=` param | Query | 37 | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 007a19b556..20d5bf884d 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -15,9 +15,11 @@ import io.github.hectorvent.floci.services.backup.BackupController; import io.github.hectorvent.floci.services.batch.BatchController; import io.github.hectorvent.floci.services.bedrock.BedrockController; import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreController; +import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreHarnessInvokeController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreGatewayController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreGatewayRuleController; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreHarnessController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreIdentityController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryController; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreResourcePolicyController; @@ -463,13 +465,14 @@ public class ResolvedServiceCatalog { Set.of(BedrockAgentCoreControlController.class, BedrockAgentCoreIdentityController.class, BedrockAgentCoreGatewayController.class, BedrockAgentCoreMemoryController.class, BedrockAgentCoreToolsController.class, BedrockAgentCoreGatewayRuleController.class, - BedrockAgentCoreResourcePolicyController.class)), + BedrockAgentCoreResourcePolicyController.class, + BedrockAgentCoreHarnessController.class)), descriptor("bedrock-agentcore", "bedrock-agentcore", config.services().bedrockAgentCore().enabled(), true, null, null, 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of(), Set.of(), - Set.of(BedrockAgentCoreController.class)), + Set.of(BedrockAgentCoreController.class, BedrockAgentCoreHarnessInvokeController.class)), descriptor("elasticloadbalancing", "elbv2", config.services().elbv2().enabled(), true, "elbv2", config.storage().mode(), 5000L, AwsNamespaces.ELB_V2, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java index 02593bfbb2..72e4b0d5b4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java @@ -1,14 +1,9 @@ package io.github.hectorvent.floci.services.bedrockagentcore; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsErrorResponse; -import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService; -import io.smallrye.common.annotation.Blocking; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; @@ -17,19 +12,15 @@ import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.GenericEntity; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.StreamingOutput; import org.jboss.logging.Logger; -import java.io.IOException; -import java.io.OutputStream; -import java.util.function.Consumer; /** - * Amazon Bedrock AgentCore data-plane stub ({@code InvokeAgentRuntime}). + * Amazon Bedrock AgentCore data-plane stub ({@code InvokeAgentRuntime}). {@code InvokeHarness} is served + * by {@code BedrockAgentCoreHarnessInvokeController}, rooted at {@code /harnesses/invoke}. * *

Real endpoint: {@code POST /runtimes/{agentRuntimeArn}/invocations}. The ARN is * URL-encoded in the path, so the template regex captures the remaining path segments. @@ -47,24 +38,18 @@ public class BedrockAgentCoreController { private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id"; private final BedrockAgentCoreService service; - private final BedrockAgentCoreHarnessService harnessService; private final BedrockAgentCoreControlService controlService; private final RegionResolver regionResolver; - private final ObjectMapper objectMapper; private final boolean validateRuntimeExists; @Inject public BedrockAgentCoreController(BedrockAgentCoreService service, - BedrockAgentCoreHarnessService harnessService, BedrockAgentCoreControlService controlService, RegionResolver regionResolver, - ObjectMapper objectMapper, EmulatorConfig config) { this.service = service; - this.harnessService = harnessService; this.controlService = controlService; this.regionResolver = regionResolver; - this.objectMapper = objectMapper; this.validateRuntimeExists = config.services().bedrockAgentCore().validateRuntimeExists(); } @@ -97,55 +82,4 @@ public class BedrockAgentCoreController { } return builder.build(); } - - /** - * {@code InvokeHarness}. Answers with an {@code application/vnd.amazon.eventstream} response, - * the same framing ConverseStream uses, so an SDK client's stream iterator works unchanged. - * - *

{@code harnessArn} arrives as a query parameter and {@code runtimeSessionId} as a header, - * which is how the SDK binds them; only {@code messages}, {@code model} and {@code tools} are in - * the body. - * - *

Request validation happens before the first frame: once the stream is committed the status - * is already 200 and a problem could only be reported as an in-stream exception frame. - */ - @POST - @Blocking - @Path("/harnesses/invoke") - @Consumes(MediaType.WILDCARD) - public Response invokeHarness(@Context HttpHeaders headers, - @QueryParam("harnessArn") String harnessArn, - @QueryParam("qualifier") String harnessQualifier, - String body) { - ObjectNode request; - try { - JsonNode parsed = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); - request = parsed.isObject() ? (ObjectNode) parsed : objectMapper.createObjectNode(); - } catch (IOException e) { - throw new AwsException("ValidationException", "Request body is not valid JSON", 400); - } - - // runtimeSessionId and runtimeUserId are headers on the wire, not body fields. Only the - // session id is read: runtimeUserId reaches the harness on AWS but changes nothing here. - String runtimeSessionId = headers.getHeaderString(SESSION_HEADER); - Consumer stream = harnessService.invokeHarness(harnessArn, runtimeSessionId, request); - LOG.debugv("InvokeHarness: arn={0}, qualifier={1}, session={2}", - harnessArn, harnessQualifier, runtimeSessionId); - - Response.ResponseBuilder builder = Response.ok(streaming(stream)) - .header("Content-Type", "application/vnd.amazon.eventstream"); - if (runtimeSessionId != null) { - builder.header(SESSION_HEADER, runtimeSessionId); - } - return builder.build(); - } - - /** - * The explicit return type is what lets {@code GenericEntity} keep {@code StreamingOutput} as - * the entity type; inlining the constructor erases it to {@code Object}. Same helper as the - * bedrock-runtime controller. - */ - private static GenericEntity streaming(Consumer stream) { - return new GenericEntity<>(stream::accept, StreamingOutput.class); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessInvokeController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessInvokeController.java new file mode 100644 index 0000000000..509de25640 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessInvokeController.java @@ -0,0 +1,97 @@ +package io.github.hectorvent.floci.services.bedrockagentcore; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.smallrye.common.annotation.Blocking; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.GenericEntity; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.function.Consumer; + +/** + * {@code InvokeHarness}, the AgentCore data plane's streaming operation. Answers with an + * {@code application/vnd.amazon.eventstream} response, the same framing ConverseStream uses, so an + * SDK client's stream iterator works unchanged. + * + *

Rooted at {@code /harnesses/invoke} on its own: the control plane's harness controller claims + * {@code /harnesses}, and a request is matched against one root resource class, the one with the + * longest literal path. A class of its own keeps this operation behind the data plane's service flag + * and free of the control plane's JSON-only {@code @Produces}. + */ +@Path("/harnesses/invoke") +public class BedrockAgentCoreHarnessInvokeController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreHarnessInvokeController.class); + private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id"; + + private final BedrockAgentCoreHarnessService harnessService; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreHarnessInvokeController(BedrockAgentCoreHarnessService harnessService, + ObjectMapper objectMapper) { + this.harnessService = harnessService; + this.objectMapper = objectMapper; + } + + /** + * {@code harnessArn} arrives as a query parameter and {@code runtimeSessionId} as a header, + * which is how the SDK binds them; only {@code messages}, {@code model} and {@code tools} are in + * the body. + * + *

Request validation happens before the first frame: once the stream is committed the status + * is already 200 and a problem could only be reported as an in-stream exception frame. + */ + @POST + @Blocking + @Consumes(MediaType.WILDCARD) + public Response invokeHarness(@Context HttpHeaders headers, + @QueryParam("harnessArn") String harnessArn, + @QueryParam("qualifier") String harnessQualifier, + String body) { + ObjectNode request; + try { + JsonNode parsed = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + request = parsed.isObject() ? (ObjectNode) parsed : objectMapper.createObjectNode(); + } catch (IOException e) { + throw new AwsException("ValidationException", "Request body is not valid JSON", 400); + } + + // runtimeSessionId and runtimeUserId are headers on the wire, not body fields. Only the + // session id is read: runtimeUserId reaches the harness on AWS but changes nothing here. + String runtimeSessionId = headers.getHeaderString(SESSION_HEADER); + Consumer stream = harnessService.invokeHarness(harnessArn, runtimeSessionId, request); + LOG.debugv("InvokeHarness: arn={0}, qualifier={1}, session={2}", + harnessArn, harnessQualifier, runtimeSessionId); + + Response.ResponseBuilder builder = Response.ok(streaming(stream)) + .header("Content-Type", "application/vnd.amazon.eventstream"); + if (runtimeSessionId != null) { + builder.header(SESSION_HEADER, runtimeSessionId); + } + return builder.build(); + } + + /** + * The explicit return type is what lets {@code GenericEntity} keep {@code StreamingOutput} as + * the entity type; inlining the constructor erases it to {@code Object}. Same helper as the + * bedrock-runtime controller. + */ + private static GenericEntity streaming(Consumer stream) { + return new GenericEntity<>(stream::accept, StreamingOutput.class); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControllerSupport.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControllerSupport.java index dd82f6f423..fc04d9caeb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControllerSupport.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControllerSupport.java @@ -9,11 +9,13 @@ import org.jboss.logging.Logger; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; /** * Helpers shared by the sibling REST controllers under this package (control, gateway, gateway - * rule, identity, memory, resource policy, tools). Each used to carry its own copy of the same - * error-response builder and JSON-to-map conversion, found duplicated by CPD across all seven. + * rule, identity, memory, resource policy, tools) and by its services. Each used to carry its own + * copy of the same error-response builder and JSON-to-map conversion, found duplicated by CPD across + * all seven, and four services their own random id suffix. * *

{@code putInstant} deliberately stays out of here: different AgentCore resource types encode * timestamps differently (ISO-8601 strings for runtimes, epoch seconds for workload identities and @@ -57,6 +59,23 @@ final class BedrockAgentCoreControllerSupport { return map; } + /** The letters and digits AgentCore's generated id suffixes are drawn from. */ + static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + /** {@code length} characters drawn at random from {@code alphabet}, for a generated id suffix. */ + static String random(String alphabet, int length) { + StringBuilder value = new StringBuilder(length); + for (int i = 0; i < length; i++) { + value.append(alphabet.charAt(ThreadLocalRandom.current().nextInt(alphabet.length()))); + } + return value.toString(); + } + + /** {@code length} random letters and digits, the suffix AgentCore puts after a resource's name. */ + static String randomAlphanumeric(int length) { + return random(ALPHANUMERIC, length); + } + /** Reads a text field from a JSON node, or null when the field is absent or JSON null. */ static String text(JsonNode node, String field) { JsonNode v = node.get(field); diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java index b7249f40f6..0e0e792dde 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java @@ -18,7 +18,6 @@ import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; /** CRUD for AgentCore gateways and their targets. Metadata registry only. */ @ApplicationScoped @@ -28,7 +27,6 @@ public class BedrockAgentCoreGatewayService { private static final String STATUS_READY = "READY"; private static final String STATUS_DELETING = "DELETING"; private static final String LOWER = "abcdefghijklmnopqrstuvwxyz0123456789"; - private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static final int DEFAULT_PAGE = 100; private static final int MAX_PAGE = 1000; @@ -58,7 +56,7 @@ public class BedrockAgentCoreGatewayService { throw new AwsException("ValidationException", "roleArn is required", 400); } Instant now = Instant.now(); - String id = sanitize(name) + "-" + random(LOWER, 10); + String id = sanitize(name) + "-" + BedrockAgentCoreControllerSupport.random(LOWER, 10); Gateway gateway = new Gateway(); gateway.setGatewayId(id); gateway.setName(name); @@ -166,7 +164,7 @@ public class BedrockAgentCoreGatewayService { Gateway gateway = get(gatewayId, region); Instant now = Instant.now(); GatewayTarget target = new GatewayTarget(); - target.setTargetId(random(ALNUM, 10)); + target.setTargetId(BedrockAgentCoreControllerSupport.randomAlphanumeric(10)); target.setName(name); target.setStatus(STATUS_READY); target.setTargetConfiguration(targetConfiguration); @@ -234,13 +232,6 @@ public class BedrockAgentCoreGatewayService { return s.length() > 40 ? s.substring(0, 40) : s; } - private static String random(String alphabet, int len) { - StringBuilder sb = new StringBuilder(len); - for (int i = 0; i < len; i++) { - sb.append(alphabet.charAt(ThreadLocalRandom.current().nextInt(alphabet.length()))); - } - return sb.toString(); - } private static String key(String region, String id) { return keyPrefix(region) + id; diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessController.java new file mode 100644 index 0000000000..c6c3b244e5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessController.java @@ -0,0 +1,210 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreHarnessRegistry.HarnessView; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Harness; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.HarnessVersion; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +/** + * The AgentCore harness control plane under {@code /harnesses}: {@code CreateHarness}, + * {@code GetHarness}, {@code UpdateHarness}, {@code DeleteHarness}, {@code ListHarnesses} and + * {@code ListHarnessVersions}. The data plane's {@code InvokeHarness} has a class of its own rooted at + * {@code /harnesses/invoke}, {@code BedrockAgentCoreHarnessInvokeController}. + */ +@Path("/harnesses") +@Produces(MediaType.APPLICATION_JSON) +public class BedrockAgentCoreHarnessController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreHarnessController.class); + + private final BedrockAgentCoreHarnessRegistry registry; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreHarnessController(BedrockAgentCoreHarnessRegistry registry, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.registry = registry; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Consumes(MediaType.WILDCARD) + public Response createHarness(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + HarnessView view = registry.create(object(body), region); + return Response.status(201).entity(wrapped(view, region)).build(); + } catch (Exception e) { + return error(e, "creating harness"); + } + } + + @GET + public Response listHarnesses(@Context HttpHeaders headers, + @QueryParam("maxResults") String maxResultsParam, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException"); + PaginatedResult page = registry.list(maxResults, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode harnesses = out.putArray("harnesses"); + for (Harness harness : page.items()) { + ObjectNode summary = harnesses.addObject(); + summary.put("harnessId", harness.getHarnessId()); + summary.put("harnessName", harness.getHarnessName()); + summary.put("arn", registry.arn(harness, region)); + summary.put("status", harness.getStatus()); + putInstant(summary, "createdAt", harness.getCreatedAt()); + putInstant(summary, "updatedAt", harness.getUpdatedAt()); + summary.put("harnessVersion", harness.getCurrentVersion().getVersion()); + } + if (page.nextToken() != null) { + out.put("nextToken", page.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing harnesses"); + } + } + + @GET + @Path("/{harnessId}") + public Response getHarness(@Context HttpHeaders headers, @PathParam("harnessId") String harnessId, + @QueryParam("harnessVersion") String harnessVersion) { + String region = regionResolver.resolveRegion(headers); + try { + return Response.ok(wrapped(registry.get(harnessId, harnessVersion, region), region)).build(); + } catch (Exception e) { + return error(e, "getting harness"); + } + } + + @PATCH + @Path("/{harnessId}") + @Consumes(MediaType.WILDCARD) + public Response updateHarness(@Context HttpHeaders headers, @PathParam("harnessId") String harnessId, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + return Response.ok(wrapped(registry.update(harnessId, object(body), region), region)).build(); + } catch (Exception e) { + return error(e, "updating harness"); + } + } + + /** {@code deleteManagedMemory} is accepted and ignored: Floci creates no managed memory for a harness. */ + @DELETE + @Path("/{harnessId}") + public Response deleteHarness(@Context HttpHeaders headers, @PathParam("harnessId") String harnessId, + @QueryParam("clientToken") String clientToken, + @QueryParam("deleteManagedMemory") String deleteManagedMemory) { + String region = regionResolver.resolveRegion(headers); + try { + return Response.ok(wrapped(registry.delete(harnessId, region), region)).build(); + } catch (Exception e) { + return error(e, "deleting harness"); + } + } + + @GET + @Path("/{harnessId}/versions") + public Response listHarnessVersions(@Context HttpHeaders headers, @PathParam("harnessId") String harnessId, + @QueryParam("maxResults") String maxResultsParam, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException"); + Harness harness = registry.get(harnessId, null, region).harness(); + PaginatedResult page = registry.listVersions(harnessId, maxResults, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode versions = out.putArray("harnessVersions"); + for (HarnessVersion version : page.items()) { + ObjectNode summary = versions.addObject(); + summary.put("harnessId", harness.getHarnessId()); + summary.put("harnessName", harness.getHarnessName()); + summary.put("arn", registry.arn(harness, region)); + summary.put("harnessVersion", version.getVersion()); + summary.put("status", harness.getStatus()); + putInstant(summary, "createdAt", version.getCreatedAt()); + putInstant(summary, "updatedAt", version.getCreatedAt()); + } + if (page.nextToken() != null) { + out.put("nextToken", page.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing harness versions"); + } + } + + /** {@code {"harness": {...}}}, the members in the order AWS returns them. */ + private ObjectNode wrapped(HarnessView view, String region) { + Harness harness = view.harness(); + HarnessVersion version = view.version(); + ObjectNode out = objectMapper.createObjectNode(); + ObjectNode node = out.putObject("harness"); + node.put("harnessId", harness.getHarnessId()); + node.put("harnessName", harness.getHarnessName()); + node.put("arn", registry.arn(harness, region)); + node.put("status", harness.getStatus()); + node.put("harnessVersion", version.getVersion()); + node.put("executionRoleArn", version.getExecutionRoleArn()); + putInstant(node, "createdAt", harness.getCreatedAt()); + putInstant(node, "updatedAt", version.getCreatedAt()); + for (String member : BedrockAgentCoreHarnessRegistry.memberOrder()) { + JsonNode value = version.getConfiguration().get(member); + if (value != null) { + node.set(member, value.deepCopy()); + } + } + return out; + } + + private ObjectNode object(String body) throws IOException { + JsonNode parsed = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + if (!parsed.isObject()) { + throw new AwsException("ValidationException", "Request body must be a JSON object", 400); + } + return (ObjectNode) parsed; + } + + private static void putInstant(ObjectNode node, String field, Instant instant) { + if (instant != null) { + // ISO-8601, as AgentCore models these timestamps. + node.put(field, instant.truncatedTo(ChronoUnit.MILLIS).toString()); + } + } + + private Response error(Exception e, String action) { + return BedrockAgentCoreControllerSupport.error(LOG, e, action); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessRegistry.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessRegistry.java new file mode 100644 index 0000000000..8e89611302 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessRegistry.java @@ -0,0 +1,374 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Harness; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.HarnessVersion; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * The AgentCore harness control plane: {@code CreateHarness}, {@code GetHarness}, + * {@code UpdateHarness}, {@code DeleteHarness}, {@code ListHarnesses} and + * {@code ListHarnessVersions}, plus tags on harness ARNs. A metadata registry: a harness settles in + * {@code READY} at once, and no agent runtime is started for it. + * + *

Defaults are the ones AWS fills in for a harness created without them: {@code apiFormat} + * {@code converse_stream} on a Bedrock model, empty {@code systemPrompt}, {@code tools}, + * {@code skills} and {@code allowedTools}, a {@code sliding_window} truncation of 150 messages, no + * environment variables, and an AgentCore Runtime environment named {@code harness_} with a + * 900-second idle session timeout, an 8-hour maximum lifetime and {@code PUBLIC} networking. + */ +@ApplicationScoped +public class BedrockAgentCoreHarnessRegistry { + + private static final String ARN_SERVICE = "bedrock-agentcore"; + private static final String STATUS_READY = "READY"; + private static final String STATUS_DELETING = "DELETING"; + private static final int MAX_PAGE = 100; + private static final int MAX_TAGS = 50; + private static final int MAX_VERSION = 99999; + + private static final Pattern HARNESS_NAME = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,39}"); + private static final Pattern ROLE_ARN = + Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::([0-9]{12})?:role/.+"); + + private static final String RUNTIME_ENVIRONMENT = "agentCoreRuntimeEnvironment"; + private static final int DEFAULT_IDLE_SESSION_TIMEOUT = 900; + private static final int DEFAULT_MAX_LIFETIME = 28800; + private static final int DEFAULT_TRUNCATION_MESSAGES = 150; + + /** Members replaced whole when a request carries them, in the order {@code GetHarness} returns them. */ + private static final List PLAIN_MEMBERS = List.of("model", "systemPrompt", "tools", "skills", + "allowedTools", "truncation", "environmentVariables", "maxIterations", "maxTokens", "timeoutSeconds"); + /** Members an update sets or clears through an {@code optionalValue} wrapper. */ + private static final List OPTIONAL_MEMBERS = List.of("environmentArtifact", "authorizerConfiguration", + "memory"); + /** Every configuration member, in the order {@code GetHarness} returns them. */ + private static final List MEMBER_ORDER = List.of("model", "systemPrompt", "tools", "skills", + "allowedTools", "truncation", "environment", "environmentArtifact", "environmentVariables", + "authorizerConfiguration", "memory", "maxIterations", "maxTokens", "timeoutSeconds"); + + private final StorageBackend storage; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreHarnessRegistry(StorageFactory storageFactory, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-harnesses.json", + new TypeReference>() {}), regionResolver, objectMapper); + } + + BedrockAgentCoreHarnessRegistry(StorageBackend storage, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.storage = storage; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + /** A harness at one of its versions: what {@code GetHarness} and the write operations answer. */ + public record HarnessView(Harness harness, HarnessVersion version) {} + + public synchronized HarnessView create(ObjectNode request, String region) { + String clientToken = text(request, "clientToken"); + if (clientToken != null) { + Optional replay = storage.scan(key -> key.startsWith(keyPrefix(region))).stream() + .filter(harness -> clientToken.equals(harness.getClientToken())) + .findFirst(); + if (replay.isPresent()) { + return new HarnessView(replay.get(), replay.get().getCurrentVersion()); + } + } + String name = text(request, "harnessName"); + if (name == null || !HARNESS_NAME.matcher(name).matches()) { + throw validation("harnessName must start with a letter and contain up to 40 letters, digits and " + + "underscores"); + } + String roleArn = requireRoleArn(text(request, "executionRoleArn")); + Map tags = tags(request.get("tags")); + boolean taken = storage.scan(key -> key.startsWith(keyPrefix(region))).stream() + .anyMatch(harness -> name.equals(harness.getHarnessName())); + if (taken) { + throw new AwsException("ConflictException", "A harness named " + name + " already exists.", 409); + } + + ObjectNode configuration = objectMapper.createObjectNode(); + for (String member : PLAIN_MEMBERS) { + copy(request, configuration, member); + } + for (String member : OPTIONAL_MEMBERS) { + copy(request, configuration, member); + } + JsonNode environment = request.path("environment").path(RUNTIME_ENVIRONMENT); + configuration.set("environment", runtimeEnvironment(name, null, environment, region)); + + Instant now = Instant.now(); + Harness harness = new Harness(); + harness.setHarnessId(name + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10)); + harness.setHarnessName(name); + harness.setStatus(STATUS_READY); + harness.setCreatedAt(now); + harness.setUpdatedAt(now); + harness.setClientToken(clientToken); + harness.getTags().putAll(tags); + harness.getVersions().add(version("1", now, roleArn, withDefaults(configuration))); + storage.put(key(region, harness.getHarnessId()), harness); + return new HarnessView(harness, harness.getCurrentVersion()); + } + + /** The harness at {@code version}, or at its current version when {@code version} is null. */ + public HarnessView get(String id, String version, String region) { + Harness harness = find(id, region); + if (version == null) { + return new HarnessView(harness, harness.getCurrentVersion()); + } + HarnessVersion found = harness.findVersion(version).orElseThrow(() -> new AwsException( + "ResourceNotFoundException", "Version " + version + " not found for harness " + id, 404)); + return new HarnessView(harness, found); + } + + /** + * Appends the next version. A member the request carries replaces the current one, and an + * {@code optionalValue} wrapper sets its member, or clears it when the wrapper is empty. The + * runtime environment keeps its runtime and takes the lifecycle, network and filesystem + * configuration the request gives. + */ + public synchronized HarnessView update(String id, ObjectNode request, String region) { + Harness harness = find(id, region); + HarnessVersion current = harness.getCurrentVersion(); + String roleArn = request.hasNonNull("executionRoleArn") + ? requireRoleArn(text(request, "executionRoleArn")) : current.getExecutionRoleArn(); + int next = Integer.parseInt(current.getVersion()) + 1; + + ObjectNode configuration = current.getConfiguration().deepCopy(); + for (String member : PLAIN_MEMBERS) { + copy(request, configuration, member); + } + for (String member : OPTIONAL_MEMBERS) { + JsonNode wrapper = request.get(member); + if (wrapper == null || wrapper.isNull()) { + continue; + } + JsonNode value = wrapper.get("optionalValue"); + if (value == null || value.isNull()) { + configuration.remove(member); + } else { + configuration.set(member, value.deepCopy()); + } + } + JsonNode environment = request.path("environment").path(RUNTIME_ENVIRONMENT); + if (environment.isObject()) { + configuration.set("environment", runtimeEnvironment(harness.getHarnessName(), + current.getConfiguration().path("environment").path(RUNTIME_ENVIRONMENT), environment, region)); + } + + Instant now = Instant.now(); + harness.getVersions().add(version(String.valueOf(next), now, roleArn, withDefaults(configuration))); + harness.setUpdatedAt(now); + storage.put(key(region, id), harness); + return new HarnessView(harness, harness.getCurrentVersion()); + } + + /** Removes the harness and answers it as it was, {@code DELETING}. */ + public synchronized HarnessView delete(String id, String region) { + Harness harness = find(id, region); + storage.delete(key(region, id)); + harness.setStatus(STATUS_DELETING); + return new HarnessView(harness, harness.getCurrentVersion()); + } + + public PaginatedResult list(Integer maxResults, String nextToken, String region) { + List all = storage.scan(key -> key.startsWith(keyPrefix(region))); + return Pagination.paginate(all, Harness::getHarnessId, maxResults, nextToken, MAX_PAGE, "ValidationException"); + } + + /** A harness's versions, newest first, as AWS lists them. */ + public PaginatedResult listVersions(String id, Integer maxResults, String nextToken, + String region) { + Harness harness = find(id, region); + return Pagination.paginate(harness.getVersions(), + version -> String.format("%05d", MAX_VERSION - Integer.parseInt(version.getVersion())), + maxResults, nextToken, MAX_PAGE, "ValidationException"); + } + + public String arn(Harness harness, String region) { + return regionResolver.buildArn(ARN_SERVICE, region, "harness/" + harness.getHarnessId()); + } + + /** Every configuration member, in the order {@code GetHarness} returns them. */ + public static List memberOrder() { + return MEMBER_ORDER; + } + + // ── Tagging ── + + public Map getTagsByArn(String region, String arn) { + return new HashMap<>(getByArn(region, arn).getTags()); + } + + public synchronized void tagByArn(String region, String arn, Map tags) { + Harness harness = getByArn(region, arn); + Map merged = new HashMap<>(harness.getTags()); + merged.putAll(tags); + if (merged.size() > MAX_TAGS) { + throw validation("A harness can have at most " + MAX_TAGS + " tags."); + } + harness.setTags(merged); + storage.put(key(region, harness.getHarnessId()), harness); + } + + public synchronized void untagByArn(String region, String arn, List keys) { + Harness harness = getByArn(region, arn); + keys.forEach(harness.getTags()::remove); + storage.put(key(region, harness.getHarnessId()), harness); + } + + /** The harness a harness ARN names; ValidationException for any other ARN, ResourceNotFoundException when gone. */ + public Harness getByArn(String region, String arn) { + String resource = BedrockAgentCoreArns.resource(arn); + if (resource == null || !resource.startsWith("harness/")) { + throw validation("Unsupported resource ARN: " + arn); + } + return find(resource.substring("harness/".length()), region); + } + + private Harness find(String id, String region) { + // AWS's own wording, "Agent" included. + return storage.get(key(region, id)).orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Agent with name " + id + " not found.", 404)); + } + + /** + * The AgentCore Runtime environment a harness runs in: the runtime is named after the harness + * and keeps its id across updates; lifecycle and network configuration default as on AWS. + */ + private ObjectNode runtimeEnvironment(String harnessName, JsonNode existing, JsonNode requested, + String region) { + ObjectNode runtime = objectMapper.createObjectNode(); + String runtimeName = "harness_" + harnessName; + String runtimeId = existing != null && existing.hasNonNull("agentRuntimeId") + ? existing.get("agentRuntimeId").asText() + : runtimeName + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10); + runtime.put("agentRuntimeArn", regionResolver.buildArn(ARN_SERVICE, region, "runtime/" + runtimeId)); + runtime.put("agentRuntimeName", runtimeName); + runtime.put("agentRuntimeId", runtimeId); + + ObjectNode lifecycle = objectMapper.createObjectNode(); + JsonNode requestedLifecycle = requested.path("lifecycleConfiguration"); + lifecycle.put("idleRuntimeSessionTimeout", requestedLifecycle.path("idleRuntimeSessionTimeout") + .asInt(DEFAULT_IDLE_SESSION_TIMEOUT)); + lifecycle.put("maxLifetime", requestedLifecycle.path("maxLifetime").asInt(DEFAULT_MAX_LIFETIME)); + runtime.set("lifecycleConfiguration", lifecycle); + + JsonNode network = requested.get("networkConfiguration"); + if (network != null && network.isObject()) { + runtime.set("networkConfiguration", network.deepCopy()); + } else { + runtime.putObject("networkConfiguration").put("networkMode", "PUBLIC"); + } + JsonNode filesystems = requested.get("filesystemConfigurations"); + if (filesystems != null && filesystems.isArray()) { + runtime.set("filesystemConfigurations", filesystems.deepCopy()); + } + ObjectNode environment = objectMapper.createObjectNode(); + environment.set(RUNTIME_ENVIRONMENT, runtime); + return environment; + } + + /** The configuration with AWS's defaults filled in, its members in the order AWS returns them. */ + private ObjectNode withDefaults(ObjectNode configuration) { + JsonNode bedrockModel = configuration.path("model").path("bedrockModelConfig"); + if (bedrockModel instanceof ObjectNode model && !model.hasNonNull("apiFormat")) { + model.put("apiFormat", "converse_stream"); + } + for (String list : List.of("systemPrompt", "tools", "skills", "allowedTools")) { + if (!configuration.hasNonNull(list)) { + configuration.putArray(list); + } + } + if (!configuration.hasNonNull("truncation")) { + ObjectNode truncation = configuration.putObject("truncation"); + truncation.put("strategy", "sliding_window"); + truncation.putObject("config").putObject("slidingWindow") + .put("messagesCount", DEFAULT_TRUNCATION_MESSAGES); + } + if (!configuration.hasNonNull("environmentVariables")) { + configuration.putObject("environmentVariables"); + } + ObjectNode ordered = objectMapper.createObjectNode(); + for (String member : MEMBER_ORDER) { + if (configuration.hasNonNull(member)) { + ordered.set(member, configuration.get(member)); + } + } + return ordered; + } + + private static HarnessVersion version(String number, Instant createdAt, String roleArn, ObjectNode configuration) { + HarnessVersion version = new HarnessVersion(); + version.setVersion(number); + version.setCreatedAt(createdAt); + version.setExecutionRoleArn(roleArn); + version.setConfiguration(configuration); + return version; + } + + private static void copy(ObjectNode from, ObjectNode to, String member) { + JsonNode value = from.get(member); + if (value != null && !value.isNull()) { + to.set(member, value.deepCopy()); + } + } + + private static String requireRoleArn(String roleArn) { + if (roleArn == null || !ROLE_ARN.matcher(roleArn).matches()) { + throw validation("executionRoleArn must be the ARN of an IAM role"); + } + return roleArn; + } + + private static Map tags(JsonNode node) { + Map tags = BedrockAgentCoreControllerSupport.stringMap(node); + if (tags == null) { + return Map.of(); + } + if (tags.size() > MAX_TAGS) { + throw validation("A harness can have at most " + MAX_TAGS + " tags."); + } + return tags; + } + + private static String text(JsonNode node, String field) { + return BedrockAgentCoreControllerSupport.text(node, field); + } + + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } + + + private static String key(String region, String id) { + return keyPrefix(region) + id; + } + + private static String keyPrefix(String region) { + return "harness:" + region + ":"; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java index 4b26da6d29..f416164f39 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java @@ -18,7 +18,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; @@ -30,7 +29,6 @@ public class BedrockAgentCoreMemoryService { private static final String ARN_SERVICE = "bedrock-agentcore"; private static final String STATUS_ACTIVE = "ACTIVE"; private static final String STATUS_DELETING = "DELETING"; - private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static final int MAX_PAGE = 100; private final StorageBackend storage; @@ -89,7 +87,7 @@ public class BedrockAgentCoreMemoryService { } validateExpiry(eventExpiryDuration); Instant now = Instant.now(); - String id = sanitize(name) + "-" + random(10); + String id = sanitize(name) + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10); Memory memory = new Memory(); memory.setMemoryId(id); memory.setName(name); @@ -241,13 +239,6 @@ public class BedrockAgentCoreMemoryService { return s.length() > 60 ? s.substring(0, 60) : s; } - private static String random(int len) { - StringBuilder sb = new StringBuilder(len); - for (int i = 0; i < len; i++) { - sb.append(ALNUM.charAt(ThreadLocalRandom.current().nextInt(ALNUM.length()))); - } - return sb.toString(); - } private static String key(String region, String id) { return keyPrefix(region) + id; diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java index 87b1e66778..28c59633e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java @@ -14,7 +14,7 @@ import java.util.Map; * Tagging for AgentCore resources, dispatched from the shared {@code /tags/{resourceArn}} * route. All AgentCore resources share the ARN service segment {@code bedrock-agentcore}, * so this handler further dispatches by the resource type in the ARN. AWS supports tagging - * for runtimes, gateways, and memories. + * for runtimes, gateways, memories and harnesses. */ @ApplicationScoped public class BedrockAgentCoreTagHandler implements TagHandler { @@ -22,16 +22,19 @@ public class BedrockAgentCoreTagHandler implements TagHandler { private final BedrockAgentCoreControlService runtimeService; private final BedrockAgentCoreGatewayService gatewayService; private final BedrockAgentCoreMemoryService memoryService; + private final BedrockAgentCoreHarnessRegistry harnessRegistry; private final RegionResolver regionResolver; @Inject public BedrockAgentCoreTagHandler(BedrockAgentCoreControlService runtimeService, BedrockAgentCoreGatewayService gatewayService, BedrockAgentCoreMemoryService memoryService, + BedrockAgentCoreHarnessRegistry harnessRegistry, RegionResolver regionResolver) { this.runtimeService = runtimeService; this.gatewayService = gatewayService; this.memoryService = memoryService; + this.harnessRegistry = harnessRegistry; this.regionResolver = regionResolver; } @@ -46,6 +49,7 @@ public class BedrockAgentCoreTagHandler implements TagHandler { case GATEWAY -> gatewayService.getTagsByArn(region, arn); case MEMORY -> memoryService.getTagsByArn(region, arn); case RUNTIME -> runtimeService.getTagsByArn(region, arn); + case HARNESS -> harnessRegistry.getTagsByArn(region, arn); }; } @@ -55,6 +59,7 @@ public class BedrockAgentCoreTagHandler implements TagHandler { case GATEWAY -> gatewayService.tagByArn(region, arn, tags); case MEMORY -> memoryService.tagByArn(region, arn, tags); case RUNTIME -> runtimeService.tagByArn(region, arn, tags); + case HARNESS -> harnessRegistry.tagByArn(region, arn, tags); } } @@ -64,10 +69,11 @@ public class BedrockAgentCoreTagHandler implements TagHandler { case GATEWAY -> gatewayService.untagByArn(region, arn, tagKeys); case MEMORY -> memoryService.untagByArn(region, arn, tagKeys); case RUNTIME -> runtimeService.untagByArn(region, arn, tagKeys); + case HARNESS -> harnessRegistry.untagByArn(region, arn, tagKeys); } } - private enum ResourceKind { RUNTIME, GATEWAY, MEMORY } + private enum ResourceKind { RUNTIME, GATEWAY, MEMORY, HARNESS } private ResourceKind kind(String region, String arn) { String resource = BedrockAgentCoreArns.resource(arn); @@ -85,14 +91,17 @@ public class BedrockAgentCoreTagHandler implements TagHandler { if (resource.startsWith("memory/")) { return ResourceKind.MEMORY; } - // Not a runtime, gateway, or memory → not a taggable AgentCore resource. + if (resource.startsWith("harness/")) { + return ResourceKind.HARNESS; + } + // Not a runtime, gateway, memory or harness → not a taggable AgentCore resource. throw new AwsException("ValidationException", "Tagging is not supported for this AgentCore resource: " + arn, 400); } /** - * All three services resolve a resource from the ARN's id suffix alone, so without this a - * caller could reach a local runtime, gateway, or memory through an ARN naming another + * All four services resolve a resource from the ARN's id suffix alone, so without this a + * caller could reach a local runtime, gateway, memory or harness through an ARN naming another * account or region and read or change its tags. Reported as not found rather than a * validation error, so the response does not confirm what exists behind the foreign identity. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java index 08d393d402..12d399b76f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java @@ -18,14 +18,12 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; @ApplicationScoped public class BedrockAgentCoreToolsService { private static final Pattern TOOL_NAME = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}"); - private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private final StorageBackend storage; private final RegionResolver regionResolver; @@ -68,7 +66,7 @@ public class BedrockAgentCoreToolsService { throw new AwsException("ConflictException", "Browser already exists: " + name, 409); } - String id = name + "-" + random(10); + String id = name + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10); Instant now = Instant.now(); ObjectNode browser = request.deepCopy(); browser.put("browserId", id); @@ -123,7 +121,7 @@ public class BedrockAgentCoreToolsService { if (findByName("browser-profile", region, name) != null) { throw new AwsException("ConflictException", "Browser profile already exists: " + name, 409); } - String id = name + "-" + random(10); + String id = name + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10); Instant now = Instant.now(); ObjectNode profile = request.deepCopy(); profile.put("profileId", id); @@ -161,7 +159,7 @@ public class BedrockAgentCoreToolsService { if (findByName("code-interpreter", region, name) != null) { throw new AwsException("ConflictException", "Code interpreter already exists: " + name, 409); } - String id = name + "-" + random(10); + String id = name + "-" + BedrockAgentCoreControllerSupport.randomAlphanumeric(10); Instant now = Instant.now(); ObjectNode interpreter = request.deepCopy(); interpreter.put("codeInterpreterId", id); @@ -446,13 +444,6 @@ public class BedrockAgentCoreToolsService { return value == null || value.isNull() ? null : value.asText(); } - private static String random(int length) { - StringBuilder value = new StringBuilder(length); - for (int i = 0; i < length; i++) { - value.append(ALNUM.charAt(ThreadLocalRandom.current().nextInt(ALNUM.length()))); - } - return value.toString(); - } private static String key(String family, String region, String id) { return prefix(family, region) + id; diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Harness.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Harness.java new file mode 100644 index 0000000000..b45f5c40be --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Harness.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * An AgentCore harness: a managed agent loop configuration. Metadata only; {@code InvokeHarness} + * does not read it. Its configuration lives in {@link #getVersions() versions}, the last of which is + * current. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Harness { + + private String harnessId; + private String harnessName; + private String status; + private Instant createdAt; + private Instant updatedAt; + private String clientToken; + private Map tags = new HashMap<>(); + private List versions = new ArrayList<>(); + + public String getHarnessId() { + return harnessId; + } + + public void setHarnessId(String harnessId) { + this.harnessId = harnessId; + } + + public String getHarnessName() { + return harnessName; + } + + public void setHarnessName(String harnessName) { + this.harnessName = harnessName; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags != null ? tags : new HashMap<>(); + } + + public List getVersions() { + return versions; + } + + public void setVersions(List versions) { + this.versions = versions != null ? versions : new ArrayList<>(); + } + + /** The current version: the one written last. */ + @JsonIgnore + public HarnessVersion getCurrentVersion() { + return versions.getLast(); + } + + /** The version with this number, empty when there is none. */ + public Optional findVersion(String version) { + return versions.stream().filter(candidate -> candidate.getVersion().equals(version)).findFirst(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/HarnessVersion.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/HarnessVersion.java new file mode 100644 index 0000000000..c45f0c771f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/HarnessVersion.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * Immutable snapshot of an AgentCore harness at one version. {@code CreateHarness} writes version 1 + * and each {@code UpdateHarness} appends the next; earlier ones stay readable through + * {@code GetHarness?harnessVersion=} and {@code ListHarnessVersions}. + * + *

{@code configuration} holds the harness members after {@code executionRoleArn} exactly as + * {@code GetHarness} returns them ({@code model} through {@code timeoutSeconds}), defaults filled in. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class HarnessVersion { + + private String version; + private Instant createdAt; + private String executionRoleArn; + private ObjectNode configuration; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public String getExecutionRoleArn() { + return executionRoleArn; + } + + public void setExecutionRoleArn(String executionRoleArn) { + this.executionRoleArn = executionRoleArn; + } + + public ObjectNode getConfiguration() { + return configuration; + } + + public void setConfiguration(ObjectNode configuration) { + this.configuration = configuration; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessIntegrationTest.java index 3c32b8b40e..c39b5d4769 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreHarnessIntegrationTest.java @@ -80,6 +80,19 @@ class BedrockAgentCoreHarnessIntegrationTest { assertThat(assistantText(body), containsString("what is EIDR?")); } + /** An SDK client asks for the event stream; that must not be refused as unacceptable. */ + @Test + void aClientAskingForTheEventStreamGetsIt() { + request(ARN, SESSION) + .header("Accept", "application/vnd.amazon.eventstream") + .body(""" + {"messages": [{"role": "user", "content": [{"text": "hello"}]}]} + """) + .when().post("/harnesses/invoke") + .then().statusCode(200) + .header("Content-Type", containsString("application/vnd.amazon.eventstream")); + } + @Test void theStreamCarriesTheFullEventSequenceInOrder() { String body = request(ARN, SESSION) diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessControlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessControlIntegrationTest.java new file mode 100644 index 0000000000..18d708735d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreHarnessControlIntegrationTest.java @@ -0,0 +1,200 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * The AgentCore harness control plane over its REST routes: {@code CreateHarness}, + * {@code GetHarness}, {@code UpdateHarness}, {@code DeleteHarness}, {@code ListHarnesses}, + * {@code ListHarnessVersions} and tags on a harness ARN. + */ +@QuarkusTest +class BedrockAgentCoreHarnessControlIntegrationTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/harness-role"; + + private final List created = new ArrayList<>(); + + @AfterEach + void deleteHarnesses() { + created.forEach(id -> given().delete("/harnesses/" + id)); + } + + @Test + void aHarnessCreatedWithTheMinimumGetsAwsDefaults() { + String name = name(); + String id = create(""" + {"harnessName": "%s", "executionRoleArn": "%s", + "model": {"bedrockModelConfig": {"modelId": "us.anthropic.claude-sonnet-4-6"}}, + "systemPrompt": [{"text": "Be brief."}]} + """.formatted(name, ROLE)) + .body("harness.harnessName", equalTo(name)) + .body("harness.harnessId", matchesPattern(name + "-[a-zA-Z0-9]{10}")) + .body("harness.arn", matchesPattern( + "arn:aws:bedrock-agentcore:us-east-1:000000000000:harness/" + name + "-[a-zA-Z0-9]{10}")) + .body("harness.status", equalTo("READY")) + .body("harness.harnessVersion", equalTo("1")) + .body("harness.executionRoleArn", equalTo(ROLE)) + .body("harness.createdAt", notNullValue()) + .body("harness.model.bedrockModelConfig.apiFormat", equalTo("converse_stream")) + .body("harness.systemPrompt[0].text", equalTo("Be brief.")) + .body("harness.tools", empty()) + .body("harness.skills", empty()) + .body("harness.allowedTools", empty()) + .body("harness.truncation.strategy", equalTo("sliding_window")) + .body("harness.truncation.config.slidingWindow.messagesCount", equalTo(150)) + .body("harness.environmentVariables.size()", equalTo(0)) + .body("harness.environment.agentCoreRuntimeEnvironment.agentRuntimeName", equalTo("harness_" + name)) + .body("harness.environment.agentCoreRuntimeEnvironment.agentRuntimeId", + matchesPattern("harness_" + name + "-[a-zA-Z0-9]{10}")) + .body("harness.environment.agentCoreRuntimeEnvironment.agentRuntimeArn", + containsString(":runtime/harness_" + name + "-")) + .body("harness.environment.agentCoreRuntimeEnvironment.lifecycleConfiguration.idleRuntimeSessionTimeout", + equalTo(900)) + .body("harness.environment.agentCoreRuntimeEnvironment.lifecycleConfiguration.maxLifetime", + equalTo(28800)) + .body("harness.environment.agentCoreRuntimeEnvironment.networkConfiguration.networkMode", + equalTo("PUBLIC")) + .body("harness.memory", nullValue()) + .body("harness.maxIterations", nullValue()) + .extract().path("harness.harnessId"); + + given().get("/harnesses/" + id).then().statusCode(200) + .body("harness.harnessId", equalTo(id)) + .body("harness.truncation.config.slidingWindow.messagesCount", equalTo(150)); + given().get("/harnesses").then().statusCode(200) + .body("harnesses.harnessId", hasItem(id)) + .body("harnesses.find { it.harnessId == '" + id + "' }.harnessVersion", equalTo("1")); + } + + @Test + void anUpdateAppendsAVersionAndKeepsTheRuntime() { + String name = name(); + String id = create(""" + {"harnessName": "%s", "executionRoleArn": "%s", + "model": {"bedrockModelConfig": {"modelId": "model-a", "apiFormat": "converse"}}, + "memory": {"disabled": {}}, + "truncation": {"strategy": "sliding_window", "config": {"slidingWindow": {"messagesCount": 1}}}, + "environment": {"agentCoreRuntimeEnvironment": { + "lifecycleConfiguration": {"idleRuntimeSessionTimeout": 3600, "maxLifetime": 28800}, + "networkConfiguration": {"networkMode": "PUBLIC"}}}, + "allowedTools": [], "maxIterations": 2, "timeoutSeconds": 60, "environmentVariables": {}} + """.formatted(name, ROLE)) + .body("harness.model.bedrockModelConfig.apiFormat", equalTo("converse")) + .body("harness.memory.disabled.size()", equalTo(0)) + .extract().path("harness.harnessId"); + String runtimeId = given().get("/harnesses/" + id).then() + .extract().path("harness.environment.agentCoreRuntimeEnvironment.agentRuntimeId"); + + given().contentType(ContentType.JSON).body(""" + {"maxIterations": 5, "memory": {}, + "environment": {"agentCoreRuntimeEnvironment": { + "lifecycleConfiguration": {"idleRuntimeSessionTimeout": 1200}}}} + """) + .patch("/harnesses/" + id).then().statusCode(200) + .body("harness.harnessVersion", equalTo("2")) + .body("harness.maxIterations", equalTo(5)) + .body("harness.timeoutSeconds", equalTo(60)) + .body("harness.memory", nullValue()) + .body("harness.model.bedrockModelConfig.modelId", equalTo("model-a")) + .body("harness.environment.agentCoreRuntimeEnvironment.agentRuntimeId", equalTo(runtimeId)) + .body("harness.environment.agentCoreRuntimeEnvironment.lifecycleConfiguration.idleRuntimeSessionTimeout", + equalTo(1200)) + .body("harness.environment.agentCoreRuntimeEnvironment.lifecycleConfiguration.maxLifetime", + equalTo(28800)); + given().contentType(ContentType.JSON) + .body("{\"memory\": {\"optionalValue\": {\"disabled\": {}}}, \"executionRoleArn\": \"" + ROLE + "2\"}") + .patch("/harnesses/" + id).then().statusCode(200) + .body("harness.harnessVersion", equalTo("3")) + .body("harness.executionRoleArn", equalTo(ROLE + "2")) + .body("harness.memory.disabled.size()", equalTo(0)); + + given().get("/harnesses/" + id + "?harnessVersion=1").then().statusCode(200) + .body("harness.harnessVersion", equalTo("1")) + .body("harness.maxIterations", equalTo(2)) + .body("harness.executionRoleArn", equalTo(ROLE)); + given().get("/harnesses/" + id + "/versions").then().statusCode(200) + .body("harnessVersions.harnessVersion", contains("3", "2", "1")) + .body("harnessVersions[0].harnessId", equalTo(id)); + given().get("/harnesses/" + id + "/versions?maxResults=2").then().statusCode(200) + .body("harnessVersions.harnessVersion", contains("3", "2")) + .body("nextToken", notNullValue()); + } + + @Test + void tagsDeletionAndRefusals() { + String name = name(); + String arn = create(""" + {"harnessName": "%s", "executionRoleArn": "%s", "tags": {"team": "data"}} + """.formatted(name, ROLE)).extract().path("harness.arn"); + String id = arn.substring(arn.indexOf("harness/") + "harness/".length()); + + given().get("/tags/" + arn).then().statusCode(200).body("tags.team", equalTo("data")); + given().contentType(ContentType.JSON).body("{\"tags\": {\"env\": \"local\"}}") + .post("/tags/" + arn).then().statusCode(204); + given().delete("/tags/" + arn + "?tagKeys=team").then().statusCode(204); + given().get("/tags/" + arn).then().statusCode(200) + .body("tags.env", equalTo("local")).body("tags.team", nullValue()); + + given().contentType(ContentType.JSON) + .body("{\"harnessName\": \"" + name + "\", \"executionRoleArn\": \"" + ROLE + "\"}") + .post("/harnesses").then().statusCode(409) + .header("X-Amzn-Errortype", equalTo("ConflictException")); + given().contentType(ContentType.JSON).body("{\"harnessName\": \"1bad\", \"executionRoleArn\": \"" + ROLE + "\"}") + .post("/harnesses").then().statusCode(400); + given().contentType(ContentType.JSON).body("{\"harnessName\": \"" + name() + "\"}") + .post("/harnesses").then().statusCode(400); + given().get("/harnesses/" + id + "?harnessVersion=9").then().statusCode(404) + .body("message", equalTo("Version 9 not found for harness " + id)); + + given().delete("/harnesses/" + id + "?deleteManagedMemory=true").then().statusCode(200) + .body("harness.harnessId", equalTo(id)) + .body("harness.status", equalTo("DELETING")); + given().get("/harnesses/" + id).then().statusCode(404) + .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException")) + .body("message", equalTo("Agent with name " + id + " not found.")); + given().get("/harnesses/" + id + "/versions").then().statusCode(404); + given().get("/harnesses").then().body("harnesses.harnessId", not(hasItem(id))); + created.remove(id); + } + + @Test + void aRepeatedClientTokenAnswersTheFirstHarness() { + String token = UUID.randomUUID() + "-harness-token"; + String body = """ + {"harnessName": "%s", "executionRoleArn": "%s", "clientToken": "%s"} + """.formatted(name(), ROLE, token); + String first = create(body).extract().path("harness.harnessId"); + given().contentType(ContentType.JSON).body(body).post("/harnesses").then().statusCode(201) + .body("harness.harnessId", equalTo(first)); + } + + private ValidatableResponse create(String body) { + ValidatableResponse response = given().contentType(ContentType.JSON).body(body) + .post("/harnesses").then().statusCode(201); + created.add(response.extract().path("harness.harnessId")); + return response; + } + + private static String name() { + return "h_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12); + } +} diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 77e1191a26..2c712bba0b 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -51,6 +51,7 @@ services: - { path: services/bedrockagentcorecontrol/BedrockAgentCoreToolsController.java, mode: rest } - { path: services/bedrockagentcorecontrol/BedrockAgentCoreGatewayRuleController.java, mode: rest } - { path: services/bedrockagentcorecontrol/BedrockAgentCoreResourcePolicyController.java, mode: rest } + - { path: services/bedrockagentcorecontrol/BedrockAgentCoreHarnessController.java, mode: rest } rename_actions: CreateEndpoint: CreateAgentRuntimeEndpoint GetEndpoint: GetAgentRuntimeEndpoint