mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(bedrock-agentcore): add the harness control plane (#7387)
* feat(bedrock-agentcore): add the harness control plane CreateHarness, GetHarness, UpdateHarness, DeleteHarness, ListHarnesses and ListHarnessVersions were unknown, so aws_bedrockagentcore_harness could not be created. Harnesses are stored per Region with a name-<10 alphanumerics> id and settle in READY at once. Each update appends an immutable version, and members a create leaves out take the defaults AWS fills in, including an AgentCore Runtime environment named harness_<name>. Tags work on harness ARNs through the shared /tags route. InvokeHarness moves into the new /harnesses controller unchanged: a request is matched against one root resource class, so the data-plane controller rooted at / would no longer see /harnesses/invoke. * fix(bedrock-agentcore): match a harness role ARN with AwsArnUtils.PARTITION_REGEX * fix(bedrock-agentcore): serve InvokeHarness from a data-plane class of its own InvokeHarness sat in the control plane's /harnesses controller, so it inherited its JSON-only @Produces (an Accept: application/vnd.amazon.eventstream request was refused with 406) and was gated by no service flag, since the controller was missing from ResolvedServiceCatalog. It now has its own class rooted at /harnesses/invoke, the more specific root, registered with the data plane, and the harness controller is registered with the control plane. * refactor(bedrock-agentcore): share one random id suffix helper The harness registry, and the memory, tools and gateway services before it, each carried their own copy of the alphanumeric alphabet and the random suffix builder. One random(alphabet, length) and randomAlphanumeric(length) in BedrockAgentCoreControllerSupport now serve all four; the gateway keeps its lowercase alphabet for gateway ids.
This commit is contained in:
1 parent
58cd1ec758
commit
2e47b9c571
17 files changed
+1143
-113
No files matched your search
@@ -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) |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
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_<name>`, 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 `<id>` not
|
||||
found.", and an unknown version "Version `<n>` not found for harness `<id>`".
|
||||
- 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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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),
|
||||
|
||||
+2
-68
@@ -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}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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.
|
||||
*
|
||||
* <p>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<OutputStream> 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<StreamingOutput> streaming(Consumer<OutputStream> stream) {
|
||||
return new GenericEntity<>(stream::accept, StreamingOutput.class);
|
||||
}
|
||||
}
|
||||
+97
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<OutputStream> 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<StreamingOutput> streaming(Consumer<OutputStream> stream) {
|
||||
return new GenericEntity<>(stream::accept, StreamingOutput.class);
|
||||
}
|
||||
}
|
||||
+21
-2
@@ -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.
|
||||
*
|
||||
* <p>{@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);
|
||||
|
||||
+2
-11
@@ -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;
|
||||
|
||||
+210
@@ -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<Harness> 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<HarnessVersion> 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);
|
||||
}
|
||||
}
|
||||
+374
@@ -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.
|
||||
*
|
||||
* <p>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_<name>} 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<String> 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<String> OPTIONAL_MEMBERS = List.of("environmentArtifact", "authorizerConfiguration",
|
||||
"memory");
|
||||
/** Every configuration member, in the order {@code GetHarness} returns them. */
|
||||
private static final List<String> MEMBER_ORDER = List.of("model", "systemPrompt", "tools", "skills",
|
||||
"allowedTools", "truncation", "environment", "environmentArtifact", "environmentVariables",
|
||||
"authorizerConfiguration", "memory", "maxIterations", "maxTokens", "timeoutSeconds");
|
||||
|
||||
private final StorageBackend<String, Harness> 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<Map<String, Harness>>() {}), regionResolver, objectMapper);
|
||||
}
|
||||
|
||||
BedrockAgentCoreHarnessRegistry(StorageBackend<String, Harness> 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<Harness> 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<String, String> 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<Harness> list(Integer maxResults, String nextToken, String region) {
|
||||
List<Harness> 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<HarnessVersion> 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<String> memberOrder() {
|
||||
return MEMBER_ORDER;
|
||||
}
|
||||
|
||||
// ── Tagging ──
|
||||
|
||||
public Map<String, String> getTagsByArn(String region, String arn) {
|
||||
return new HashMap<>(getByArn(region, arn).getTags());
|
||||
}
|
||||
|
||||
public synchronized void tagByArn(String region, String arn, Map<String, String> tags) {
|
||||
Harness harness = getByArn(region, arn);
|
||||
Map<String, String> 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<String> 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<String, String> tags(JsonNode node) {
|
||||
Map<String, String> 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 + ":";
|
||||
}
|
||||
}
|
||||
+1
-10
@@ -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<String, Memory> 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;
|
||||
|
||||
+14
-5
@@ -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.
|
||||
*/
|
||||
|
||||
+3
-12
@@ -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<String, ObjectNode> 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;
|
||||
|
||||
+108
@@ -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<String, String> tags = new HashMap<>();
|
||||
private List<HarnessVersion> 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<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? tags : new HashMap<>();
|
||||
}
|
||||
|
||||
public List<HarnessVersion> getVersions() {
|
||||
return versions;
|
||||
}
|
||||
|
||||
public void setVersions(List<HarnessVersion> 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<HarnessVersion> findVersion(String version) {
|
||||
return versions.stream().filter(candidate -> candidate.getVersion().equals(version)).findFirst();
|
||||
}
|
||||
}
|
||||
+59
@@ -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}.
|
||||
*
|
||||
* <p>{@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;
|
||||
}
|
||||
}
|
||||
+13
@@ -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)
|
||||
|
||||
+200
@@ -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<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user