mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(bedrock-agentcore): implement AgentCore Memory events (#3556)
* feat(bedrock-agentcore): implement AgentCore Memory events
The Memory control plane was emulated but the event data plane was not:
CreateEvent, ListEvents, GetEvent and DeleteEvent were all absent, so an
application that reads a conversation's history had nothing to call.
Rather than answer ListEvents with a fixed empty list, the events are
stored, so a read returns what was written. An empty session is then empty
because nothing wrote to it, not because the answer is hardcoded.
Behaviour captured against real AgentCore in us-west-2:
- events are returned newest first, and the event id is a zero-padded
epoch-millisecond prefix plus a random suffix, so ids sort
chronologically as plain strings
- includePayloads=false omits the payload key rather than emptying it
- maxResults accepts 1 to 100; 101 is a ValidationException quoting the
constraint
- a malformed memory id is a ValidationException ("Invalid memoryId: not
a valid memory ID or ARN") while a well-formed but unknown one is a
ResourceNotFoundException ("Memory not found: <id>"). A memory id is a
name followed by exactly ten alphanumerics: a nine or eleven character
suffix is rejected as malformed before any lookup
- an unknown actor or session is an empty list, not an error
- sessionId is optional on create, and AgentCore assigns a UUID when it
is omitted
- an empty payload is accepted, and a new event lands on the main branch
- DeleteEvent echoes the deleted id rather than returning an empty body
The endpoints live on the memory controller rather than the data-plane one
because a JAX-RS request is matched against a single root resource class:
the class rooted at "/memories" owns that subtree, and a class rooted at
"/" never gets a look in. The behaviour stays in the data-plane service.
Verified with the same AWS SDK an application would use, pointed at a local
floci: create, list, get and delete round-trip, eventTimestamp parses back
to the exact Date, and each error above arrives as its typed exception.
Memory records (extraction and retrieval) remain unimplemented; they need
an extraction engine rather than stored events.
* fix(bedrock-agentcore): satisfy the docs and native-image CI gates
Three CI failures on this branch, all mine.
The action tables under docs/services are generated, not hand written. I
edited bedrock-agentcore.md directly and put the new event rows in the
wrong position, so `make docs-check` reported the table stale. Regenerated
with `make docs-sync`, which orders actions by registration and therefore
keeps ListMemories ahead of the event family.
BedrockAgentCoreEventService holds a static SecureRandom for event ids.
GraalVM captures such an instance in the image heap unless the class is
initialized at run time, so NativeImageRuntimeInitializationTest failed and
took both native image builds with it. Registered the class under
--initialize-at-run-time alongside the other services that hold one.
* fix(bedrock-agentcore): correct the event wire contract
Three gaps against the modelled contract, all confirmed in the bundled
botocore service model rather than taken on trust.
CreateEvent answers 201, not 200. The operation's HTTP trait says so, and
the test was pinning the wrong status.
payload is a required member of CreateEvent whose valid values include the
empty list. Turning a null into an empty list made an omitted member
indistinguishable from a valid empty array, so presence now travels
separately from the value and an omitted payload is a ValidationException.
The model also caps the list at 100 items, which is now enforced.
ListEvents is paginated. The default page size is 20 rather than the 100
this used, and the request and response carry a nextToken. The token is the
last event id of the previous page rather than an offset: ids sort with
time and the order is stable, so resuming cannot be shifted by a concurrent
write. No token is emitted on the final page, which is what ends a caller's
loop.
Verified with the real SDK against a local floci: five events traverse in
three pages of two, two and one with the token absent on the last, and an
omitted payload comes back as ValidationException.
* fix(bedrock-agentcore): match AWS wording for the maxResults range error
AWS quotes the submitted value and cites only the bound that was breached.
The message always cited the upper bound and dropped the value, so
maxResults=0 reported "less than or equal to 100". Add a test for the
lower bound, which had none.
This commit is contained in:
1 parent
62407e2479
commit
3003f05953
10 files changed
+792
No files matched your search
@@ -55,6 +55,10 @@ runtimes reach `READY` immediately and hold metadata only. See
|
||||
| `UpdateMemory` | Updates a memory resource |
|
||||
| `DeleteMemory` | Deletes a memory resource |
|
||||
| `ListMemories` | Lists memory resources |
|
||||
| `CreateEvent` | Appends an event to a memory. `sessionId` is optional and generated when omitted |
|
||||
| `ListEvents` | Lists a session's events, newest first. `POST` to the session path, not `GET` |
|
||||
| `GetEvent` | Returns one event |
|
||||
| `DeleteEvent` | Deletes one event and echoes its id |
|
||||
| `CreateBrowser` | Creates a custom browser |
|
||||
| `GetCodeInterpreter` | Returns a custom or system code interpreter |
|
||||
| `DeleteCodeInterpreter` | Deletes a custom code interpreter |
|
||||
@@ -80,6 +84,26 @@ runtimes reach `READY` immediately and hold metadata only. See
|
||||
A `DEFAULT` endpoint is created automatically with each runtime, and each runtime
|
||||
is associated with an auto-created, resolvable workload identity.
|
||||
|
||||
## Memory events
|
||||
|
||||
The event data plane is backed by real storage, so what a read returns is what was written rather
|
||||
than a fixed answer. Behaviour measured against real AgentCore:
|
||||
|
||||
- events come back **newest first**, and the event id embeds a zero-padded timestamp so ids sort
|
||||
chronologically as plain strings
|
||||
- `includePayloads: false` omits the `payload` key entirely rather than emptying it
|
||||
- `maxResults` accepts 1 to 100
|
||||
- a **malformed** memory id is a `ValidationException`, while a **well-formed but unknown** one is a
|
||||
`ResourceNotFoundException`. A memory id is a name followed by exactly ten alphanumerics
|
||||
- an unknown actor or session is an empty list, not an error
|
||||
- a new event lands on the `main` branch, and an empty payload is accepted, though `payload` is a
|
||||
required member: omitting it is a `ValidationException` while `[]` is valid
|
||||
- `CreateEvent` answers `201`, not `200`
|
||||
- `ListEvents` pages with `nextToken` and defaults to 20 events when a caller names no `maxResults`
|
||||
|
||||
Memory *records* (extraction and retrieval) are not emulated: they depend on an extraction engine
|
||||
rather than on stored events.
|
||||
|
||||
## Data plane — `InvokeAgentRuntime`
|
||||
|
||||
`POST /runtimes/{agentRuntimeArn}/invocations` returns a fixed, configurable JSON
|
||||
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.Branch;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.MemoryEvent;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.PayloadType;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* AgentCore Memory events: the data plane behind {@code CreateEvent}, {@code ListEvents},
|
||||
* {@code GetEvent} and {@code DeleteEvent}.
|
||||
*
|
||||
* <p>Behaviour measured against real AgentCore in us-west-2, including the parts that are easy to
|
||||
* assume wrongly: a malformed memory id is a {@code ValidationException} while a well-formed but
|
||||
* unknown one is {@code ResourceNotFoundException}; an unknown actor or session is simply an empty
|
||||
* list rather than an error; events come back newest first; and {@code sessionId} is optional on
|
||||
* create, with the service generating a UUID when it is omitted.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class BedrockAgentCoreEventService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreEventService.class);
|
||||
|
||||
/**
|
||||
* A memory id is a name followed by exactly ten alphanumerics. Measured: a nine or eleven
|
||||
* character suffix is rejected as malformed before the resource is ever looked up.
|
||||
*/
|
||||
private static final Pattern MEMORY_ID = Pattern.compile("^.+-[A-Za-z0-9]{10}$");
|
||||
|
||||
private static final int MAX_RESULTS_LIMIT = 100;
|
||||
/** Documented default when a caller names no page size. */
|
||||
private static final int DEFAULT_MAX_RESULTS = 20;
|
||||
private static final int MAX_PAYLOAD_ITEMS = 100;
|
||||
private static final String DEFAULT_BRANCH = "main";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private final StorageBackend<String, MemoryEvent> eventStore;
|
||||
private final BedrockAgentCoreMemoryService memoryService;
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreEventService(StorageFactory storageFactory,
|
||||
BedrockAgentCoreMemoryService memoryService) {
|
||||
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-events.json",
|
||||
new TypeReference<>() {}), memoryService);
|
||||
}
|
||||
|
||||
BedrockAgentCoreEventService(StorageBackend<String, MemoryEvent> eventStore,
|
||||
BedrockAgentCoreMemoryService memoryService) {
|
||||
this.eventStore = eventStore;
|
||||
this.memoryService = memoryService;
|
||||
}
|
||||
|
||||
public MemoryEvent createEvent(String memoryId, String actorId, String sessionId,
|
||||
Double eventTimestamp, List<PayloadType> payload, boolean payloadPresent,
|
||||
Branch branch, String region) {
|
||||
requireMemory(memoryId, region);
|
||||
requireField(actorId, "actorId");
|
||||
if (eventTimestamp == null) {
|
||||
throw new AwsException("ValidationException", "eventTimestamp is required", 400);
|
||||
}
|
||||
// payload is a required member whose valid values include the empty list, so an omitted
|
||||
// member and an empty array are different requests and only the first is an error.
|
||||
if (!payloadPresent) {
|
||||
throw new AwsException("ValidationException", "payload is required", 400);
|
||||
}
|
||||
List<PayloadType> resolvedPayload = payload == null ? List.of() : payload;
|
||||
if (resolvedPayload.size() > MAX_PAYLOAD_ITEMS) {
|
||||
throw new AwsException("ValidationException",
|
||||
"payload must have at most " + MAX_PAYLOAD_ITEMS + " items", 400);
|
||||
}
|
||||
|
||||
// sessionId is optional: AgentCore assigns a UUID when the caller omits it.
|
||||
String resolvedSession = (sessionId == null || sessionId.isBlank())
|
||||
? UUID.randomUUID().toString()
|
||||
: sessionId;
|
||||
|
||||
MemoryEvent event = new MemoryEvent();
|
||||
event.setMemoryId(memoryId);
|
||||
event.setActorId(actorId);
|
||||
event.setSessionId(resolvedSession);
|
||||
event.setEventId(nextEventId(eventTimestamp));
|
||||
event.setEventTimestamp(eventTimestamp);
|
||||
event.setPayload(resolvedPayload);
|
||||
event.setBranch(branch != null ? branch : new Branch(DEFAULT_BRANCH));
|
||||
|
||||
eventStore.put(eventKey(memoryId, actorId, resolvedSession, event.getEventId()), event);
|
||||
LOG.debugv("CreateEvent: memory={0} actor={1} session={2} event={3}",
|
||||
memoryId, actorId, resolvedSession, event.getEventId());
|
||||
return event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists a session's events, newest first.
|
||||
*
|
||||
* <p>The id embeds a zero-padded timestamp, so ordering by id descending is the same as
|
||||
* ordering by time descending, which is what AgentCore returns.
|
||||
*/
|
||||
public EventPage listEvents(String memoryId, String actorId, String sessionId,
|
||||
Boolean includePayloads, Integer maxResults, String nextToken, String region) {
|
||||
requireMemory(memoryId, region);
|
||||
int limit = resolveMaxResults(maxResults);
|
||||
|
||||
String prefix = eventKeyPrefix(memoryId, actorId, sessionId);
|
||||
List<MemoryEvent> events = new ArrayList<>(eventStore.scan(k -> k.startsWith(prefix)));
|
||||
events.sort(Comparator.comparing(MemoryEvent::getEventId).reversed());
|
||||
|
||||
// The token is the last event id of the previous page. Ids sort with time, and the order
|
||||
// is stable, so resuming is "everything after that id" rather than a positional offset
|
||||
// that a concurrent write could shift.
|
||||
if (nextToken != null && !nextToken.isBlank()) {
|
||||
int resumeAt = -1;
|
||||
for (int i = 0; i < events.size(); i++) {
|
||||
if (nextToken.equals(events.get(i).getEventId())) {
|
||||
resumeAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (resumeAt < 0) {
|
||||
throw new AwsException("ValidationException", "nextToken is not valid", 400);
|
||||
}
|
||||
events = events.subList(resumeAt + 1, events.size());
|
||||
}
|
||||
|
||||
boolean more = events.size() > limit;
|
||||
List<MemoryEvent> page = more ? new ArrayList<>(events.subList(0, limit)) : events;
|
||||
if (Boolean.FALSE.equals(includePayloads)) {
|
||||
// Measured: the payload key is absent entirely, not an empty list.
|
||||
page = page.stream().map(BedrockAgentCoreEventService::withoutPayload).toList();
|
||||
}
|
||||
// A token only when another page exists; an absent token is what stops a caller's loop.
|
||||
String token = more && !page.isEmpty() ? page.get(page.size() - 1).getEventId() : null;
|
||||
return new EventPage(List.copyOf(page), token);
|
||||
}
|
||||
|
||||
/** One page of events plus the token to continue with, or {@code null} at the end. */
|
||||
public record EventPage(List<MemoryEvent> events, String nextToken) {}
|
||||
|
||||
public MemoryEvent getEvent(String memoryId, String actorId, String sessionId,
|
||||
String eventId, String region) {
|
||||
requireMemory(memoryId, region);
|
||||
return eventStore.get(eventKey(memoryId, actorId, sessionId, eventId))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Unable to find event with id " + eventId, 404));
|
||||
}
|
||||
|
||||
public String deleteEvent(String memoryId, String actorId, String sessionId,
|
||||
String eventId, String region) {
|
||||
requireMemory(memoryId, region);
|
||||
String key = eventKey(memoryId, actorId, sessionId, eventId);
|
||||
if (eventStore.get(key).isEmpty()) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Unable to find event with id " + eventId, 404);
|
||||
}
|
||||
eventStore.delete(key);
|
||||
LOG.debugv("DeleteEvent: memory={0} event={1}", memoryId, eventId);
|
||||
return eventId;
|
||||
}
|
||||
|
||||
// ── validation ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A malformed id never reaches a lookup: AgentCore answers {@code ValidationException} for one
|
||||
* that cannot be an id at all, and {@code ResourceNotFoundException} only for a well-formed id
|
||||
* that does not resolve.
|
||||
*/
|
||||
private void requireMemory(String memoryId, String region) {
|
||||
if (memoryId == null || !MEMORY_ID.matcher(memoryId).matches()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid memoryId: not a valid memory ID or ARN", 400);
|
||||
}
|
||||
try {
|
||||
memoryService.get(memoryId, region);
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("ResourceNotFoundException", "Memory not found: " + memoryId, 404);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireField(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationException", field + " is required", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static int resolveMaxResults(Integer maxResults) {
|
||||
if (maxResults == null) {
|
||||
return DEFAULT_MAX_RESULTS;
|
||||
}
|
||||
if (maxResults < 1) {
|
||||
throw new AwsException("ValidationException", rangeViolation(maxResults,
|
||||
"Member must have value greater than or equal to 1"), 400);
|
||||
}
|
||||
if (maxResults > MAX_RESULTS_LIMIT) {
|
||||
throw new AwsException("ValidationException", rangeViolation(maxResults,
|
||||
"Member must have value less than or equal to " + MAX_RESULTS_LIMIT), 400);
|
||||
}
|
||||
return maxResults;
|
||||
}
|
||||
|
||||
/** AWS quotes the submitted value and cites only the bound that was actually breached. */
|
||||
private static String rangeViolation(int value, String constraint) {
|
||||
return "1 validation error detected: Value '" + value + "' at 'maxResults' "
|
||||
+ "failed to satisfy constraint: " + constraint;
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* AgentCore event ids are a zero-padded epoch-millisecond prefix, a {@code #}, then a random
|
||||
* suffix, which makes them sort chronologically as plain strings.
|
||||
*/
|
||||
private static String nextEventId(double eventTimestampSeconds) {
|
||||
long millis = Math.round(eventTimestampSeconds * 1000d);
|
||||
byte[] suffix = new byte[4];
|
||||
RANDOM.nextBytes(suffix);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte b : suffix) {
|
||||
hex.append(String.format("%02x", b));
|
||||
}
|
||||
return String.format("%019d", millis) + "#" + hex;
|
||||
}
|
||||
|
||||
private static MemoryEvent withoutPayload(MemoryEvent source) {
|
||||
MemoryEvent copy = new MemoryEvent();
|
||||
copy.setMemoryId(source.getMemoryId());
|
||||
copy.setActorId(source.getActorId());
|
||||
copy.setSessionId(source.getSessionId());
|
||||
copy.setEventId(source.getEventId());
|
||||
copy.setEventTimestamp(source.getEventTimestamp());
|
||||
copy.setBranch(source.getBranch());
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String eventKeyPrefix(String memoryId, String actorId, String sessionId) {
|
||||
return memoryId + "::" + actorId + "::" + sessionId + "::";
|
||||
}
|
||||
|
||||
private static String eventKey(String memoryId, String actorId, String sessionId, String eventId) {
|
||||
return eventKeyPrefix(memoryId, actorId, sessionId) + eventId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** The branch an event belongs to. AWS defaults a new event to the {@code main} branch. */
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Branch {
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@JsonProperty("rootEventId")
|
||||
private String rootEventId;
|
||||
|
||||
public Branch() {}
|
||||
public Branch(String name) { this.name = name; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getRootEventId() { return rootEventId; }
|
||||
public void setRootEventId(String rootEventId) { this.rootEventId = rootEventId; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** The text of a conversational payload part. */
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Content {
|
||||
@JsonProperty("text")
|
||||
private String text;
|
||||
|
||||
public Content() {}
|
||||
|
||||
public String getText() { return text; }
|
||||
public void setText(String text) { this.text = text; }
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** One conversational turn: a role and its content. */
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Conversational {
|
||||
@JsonProperty("content")
|
||||
private Content content;
|
||||
@JsonProperty("role")
|
||||
private String role;
|
||||
|
||||
public Conversational() {}
|
||||
|
||||
public Content getContent() { return content; }
|
||||
public void setContent(Content content) { this.content = content; }
|
||||
public String getRole() { return role; }
|
||||
public void setRole(String role) { this.role = role; }
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* One AgentCore Memory event.
|
||||
*
|
||||
* <p>Named {@code MemoryEvent} rather than {@code Event} to keep it distinct from the many other
|
||||
* event types in this codebase. The wire name is {@code Event}.
|
||||
*
|
||||
* <p>{@code eventTimestamp} is carried as epoch milliseconds and serialised as epoch seconds with a
|
||||
* fractional part, which is the restJson1 default the SDK expects.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class MemoryEvent {
|
||||
@JsonProperty("memoryId")
|
||||
private String memoryId;
|
||||
@JsonProperty("actorId")
|
||||
private String actorId;
|
||||
@JsonProperty("sessionId")
|
||||
private String sessionId;
|
||||
@JsonProperty("eventId")
|
||||
private String eventId;
|
||||
@JsonProperty("eventTimestamp")
|
||||
private Double eventTimestamp;
|
||||
@JsonProperty("payload")
|
||||
private List<PayloadType> payload;
|
||||
@JsonProperty("branch")
|
||||
private Branch branch;
|
||||
|
||||
public MemoryEvent() {}
|
||||
|
||||
public String getMemoryId() { return memoryId; }
|
||||
public void setMemoryId(String memoryId) { this.memoryId = memoryId; }
|
||||
public String getActorId() { return actorId; }
|
||||
public void setActorId(String actorId) { this.actorId = actorId; }
|
||||
public String getSessionId() { return sessionId; }
|
||||
public void setSessionId(String sessionId) { this.sessionId = sessionId; }
|
||||
public String getEventId() { return eventId; }
|
||||
public void setEventId(String eventId) { this.eventId = eventId; }
|
||||
public Double getEventTimestamp() { return eventTimestamp; }
|
||||
public void setEventTimestamp(Double eventTimestamp) { this.eventTimestamp = eventTimestamp; }
|
||||
public List<PayloadType> getPayload() { return payload == null ? null : new ArrayList<>(payload); }
|
||||
public void setPayload(List<PayloadType> payload) { this.payload = payload == null ? null : new ArrayList<>(payload); }
|
||||
public Branch getBranch() { return branch; }
|
||||
public void setBranch(Branch branch) { this.branch = branch; }
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* One part of an event payload. AWS models this as a union of {@code conversational} and
|
||||
* {@code blob}; exactly one is set, and the other stays absent from the wire.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class PayloadType {
|
||||
@JsonProperty("conversational")
|
||||
private Conversational conversational;
|
||||
@JsonProperty("blob")
|
||||
private Object blob;
|
||||
|
||||
public PayloadType() {}
|
||||
|
||||
public Conversational getConversational() { return conversational; }
|
||||
public void setConversational(Conversational conversational) { this.conversational = conversational; }
|
||||
public Object getBlob() { return blob; }
|
||||
public void setBlob(Object blob) { this.blob = blob; }
|
||||
}
|
||||
+124
@@ -17,6 +17,13 @@ import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreEventService;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.Branch;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.MemoryEvent;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.model.PayloadType;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
@@ -40,13 +47,16 @@ public class BedrockAgentCoreMemoryController {
|
||||
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreMemoryController.class);
|
||||
|
||||
private final BedrockAgentCoreMemoryService service;
|
||||
private final BedrockAgentCoreEventService eventService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreMemoryController(BedrockAgentCoreMemoryService service,
|
||||
BedrockAgentCoreEventService eventService,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.eventService = eventService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
@@ -198,4 +208,118 @@ public class BedrockAgentCoreMemoryController {
|
||||
.entity(new AwsErrorResponse("ValidationException", e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
|
||||
// ── AgentCore Memory events (data plane) ─────────────────────
|
||||
//
|
||||
// These are data-plane operations, but they live under /memories, and a JAX-RS request is
|
||||
// matched against one root resource class only: a class rooted at "/" never gets a look in
|
||||
// once this class claims the subtree. So the endpoints sit here while the behaviour stays in
|
||||
// BedrockAgentCoreEventService.
|
||||
|
||||
@POST
|
||||
@Path("/{memoryId}/events")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response createEvent(@Context HttpHeaders headers,
|
||||
@PathParam("memoryId") String memoryId,
|
||||
CreateEventRequest request) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
CreateEventRequest body = request == null ? new CreateEventRequest() : request;
|
||||
// payload is required but may legitimately be empty, so presence is passed separately
|
||||
// from the value: null means the member was omitted, not that it was an empty list.
|
||||
MemoryEvent event = eventService.createEvent(memoryId, body.actorId(), body.sessionId(),
|
||||
body.eventTimestamp(), body.payload(), body.payload() != null, body.branch(), region);
|
||||
// AWS answers CreateEvent with 201, not 200.
|
||||
return Response.status(201).entity(Map.of("event", event)).build();
|
||||
} catch (AwsException e) {
|
||||
return awsError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** ListEvents is a POST to the session path, not a GET. That is the real wire shape. */
|
||||
@POST
|
||||
@Path("/{memoryId}/actor/{actorId}/sessions/{sessionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response listEvents(@Context HttpHeaders headers,
|
||||
@PathParam("memoryId") String memoryId,
|
||||
@PathParam("actorId") String actorId,
|
||||
@PathParam("sessionId") String sessionId,
|
||||
ListEventsRequest request) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
ListEventsRequest body = request == null ? new ListEventsRequest() : request;
|
||||
BedrockAgentCoreEventService.EventPage page = eventService.listEvents(memoryId, actorId, sessionId,
|
||||
body.includePayloads(), body.maxResults(), body.nextToken(), region);
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("events", page.events());
|
||||
// Only present when another page exists: an absent token ends a caller's loop.
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
} catch (AwsException e) {
|
||||
return awsError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{memoryId}/actor/{actorId}/sessions/{sessionId}/events/{eventId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getEvent(@Context HttpHeaders headers,
|
||||
@PathParam("memoryId") String memoryId,
|
||||
@PathParam("actorId") String actorId,
|
||||
@PathParam("sessionId") String sessionId,
|
||||
@PathParam("eventId") String eventId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
return Response.ok(Map.of("event",
|
||||
eventService.getEvent(memoryId, actorId, sessionId, eventId, region))).build();
|
||||
} catch (AwsException e) {
|
||||
return awsError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{memoryId}/actor/{actorId}/sessions/{sessionId}/events/{eventId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response deleteEvent(@Context HttpHeaders headers,
|
||||
@PathParam("memoryId") String memoryId,
|
||||
@PathParam("actorId") String actorId,
|
||||
@PathParam("sessionId") String sessionId,
|
||||
@PathParam("eventId") String eventId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
// DeleteEvent echoes the id rather than answering with an empty body.
|
||||
return Response.ok(Map.of("eventId",
|
||||
eventService.deleteEvent(memoryId, actorId, sessionId, eventId, region))).build();
|
||||
} catch (AwsException e) {
|
||||
return awsError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders an {@link AwsException} the way this protocol needs it: the SDK maps the error by the
|
||||
* {@code X-Amzn-Errortype} header, which the shared exception mapper does not set.
|
||||
*/
|
||||
private static Response awsError(AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("X-Amzn-Errortype", e.getErrorCode())
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Request body of {@code CreateEvent}; {@code sessionId} and {@code branch} are optional. */
|
||||
public record CreateEventRequest(String actorId, String sessionId, Double eventTimestamp,
|
||||
List<PayloadType> payload, Branch branch) {
|
||||
public CreateEventRequest() { this(null, null, null, null, null); }
|
||||
}
|
||||
|
||||
/** Request body of {@code ListEvents}. */
|
||||
public record ListEventsRequest(Boolean includePayloads, Integer maxResults, String nextToken) {
|
||||
public ListEventsRequest() { this(null, null, null); }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -92,6 +92,7 @@ quarkus:
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoSrpHelper
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.kms.KmsService
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreEventService
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.cloudfront.CloudFrontService
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.emr.EmrService
|
||||
- --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService
|
||||
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
* AgentCore Memory events.
|
||||
*
|
||||
* <p>Every expectation here was measured against real AgentCore in us-west-2. The ones worth
|
||||
* naming, because they are easy to assume wrongly: a malformed memory id is a
|
||||
* {@code ValidationException} while a well-formed but unknown one is
|
||||
* {@code ResourceNotFoundException}; an unknown actor or session is an empty list rather than an
|
||||
* error; events come back newest first; {@code sessionId} is optional and generated when omitted;
|
||||
* and {@code includePayloads=false} drops the key rather than emptying it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class BedrockAgentCoreEventIntegrationTest {
|
||||
|
||||
private static String createMemory(String name) {
|
||||
return given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"" + name + "\",\"eventExpiryDuration\":7}")
|
||||
.when().post("/memories/create")
|
||||
.then().statusCode(202)
|
||||
.extract().path("memory.id");
|
||||
}
|
||||
|
||||
private static String createEvent(String memoryId, String actorId, String sessionId,
|
||||
double timestamp, String text) {
|
||||
String session = sessionId == null ? "" : "\"sessionId\":\"" + sessionId + "\",";
|
||||
return given().contentType(ContentType.JSON)
|
||||
.body("{\"actorId\":\"" + actorId + "\"," + session
|
||||
+ "\"eventTimestamp\":" + timestamp + ","
|
||||
+ "\"payload\":[{\"conversational\":{\"role\":\"USER\","
|
||||
+ "\"content\":{\"text\":\"" + text + "\"}}}]}")
|
||||
.when().post("/memories/" + memoryId + "/events")
|
||||
.then().statusCode(201)
|
||||
.extract().path("event.eventId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createdEventIsListedWithItsPayload() {
|
||||
String memoryId = createMemory("evtList");
|
||||
createEvent(memoryId, "actor1", "sess1", 1789300800d, "hello");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(1))
|
||||
.body("events[0].payload[0].conversational.content.text", equalTo("hello"))
|
||||
.body("events[0].payload[0].conversational.role", equalTo("USER"))
|
||||
// AgentCore puts a new event on the main branch when the caller names none.
|
||||
.body("events[0].branch.name", equalTo("main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventsAreListedNewestFirst() {
|
||||
String memoryId = createMemory("evtOrder");
|
||||
createEvent(memoryId, "actor1", "sess1", 1789300800d, "older");
|
||||
createEvent(memoryId, "actor1", "sess1", 1789301400d, "newer");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(2))
|
||||
.body("events[0].payload[0].conversational.content.text", equalTo("newer"))
|
||||
.body("events[1].payload[0].conversational.content.text", equalTo("older"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludingPayloadsOmitsTheKeyEntirely() {
|
||||
String memoryId = createMemory("evtNoPayload");
|
||||
createEvent(memoryId, "actor1", "sess1", 1789300800d, "hello");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{\"includePayloads\":false}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(1))
|
||||
.body("events[0].eventId", notNullValue())
|
||||
.body("events[0].payload", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionIdIsGeneratedWhenTheCallerOmitsIt() {
|
||||
String memoryId = createMemory("evtNoSession");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"actorId\":\"actor1\",\"eventTimestamp\":1789300800,\"payload\":[]}")
|
||||
.when().post("/memories/" + memoryId + "/events")
|
||||
.then().statusCode(201)
|
||||
// Measured: AgentCore assigns a UUID rather than rejecting the request.
|
||||
.body("event.sessionId", notNullValue())
|
||||
.body("event.eventId", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyPayloadIsAccepted() {
|
||||
String memoryId = createMemory("evtEmptyPayload");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"actorId\":\"a\",\"sessionId\":\"s\",\"eventTimestamp\":1789300800,\"payload\":[]}")
|
||||
.when().post("/memories/" + memoryId + "/events")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownActorOrSessionIsAnEmptyListRatherThanAnError() {
|
||||
String memoryId = createMemory("evtUnknownActor");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/" + memoryId + "/actor/nobody/sessions/nosuch")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedMemoryIdIsAValidationError() {
|
||||
// The suffix must be exactly ten alphanumerics; this never reaches a lookup.
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/nope-1234/actor/a/sessions/s")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", startsWith("Invalid memoryId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWellFormedButUnknownMemoryIdIsNotFound() {
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/absent-AAAAAAAAAA/actor/a/sessions/s")
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", startsWith("Memory not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxResultsAboveTheLimitIsRejected() {
|
||||
String memoryId = createMemory("evtMaxResults");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{\"maxResults\":101}")
|
||||
.when().post("/memories/" + memoryId + "/actor/a/sessions/s")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value '101' at 'maxResults' "
|
||||
+ "failed to satisfy constraint: Member must have value less than or equal to 100"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxResultsBelowOneIsRejectedWithTheLowerBound() {
|
||||
String memoryId = createMemory("evtMaxResultsLow");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{\"maxResults\":0}")
|
||||
.when().post("/memories/" + memoryId + "/actor/a/sessions/s")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value '0' at 'maxResults' "
|
||||
+ "failed to satisfy constraint: Member must have value greater than or equal to 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void gettingAnUnknownEventIsNotFound() {
|
||||
String memoryId = createMemory("evtGetMissing");
|
||||
|
||||
given()
|
||||
.when().get("/memories/" + memoryId + "/actor/a/sessions/s/events/0000000000000000000#deadbeef")
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnEventEchoesItsIdAndRemovesIt() {
|
||||
String memoryId = createMemory("evtDelete");
|
||||
String eventId = createEvent(memoryId, "actor1", "sess1", 1789300800d, "hello");
|
||||
|
||||
given()
|
||||
.when().delete("/memories/" + memoryId + "/actor/actor1/sessions/sess1/events/" + eventId)
|
||||
.then().statusCode(200)
|
||||
// DeleteEvent echoes the id rather than answering with an empty body.
|
||||
.body("eventId", equalTo(eventId));
|
||||
|
||||
given().contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventAnswersWith201() {
|
||||
String memoryId = createMemory("evtCreated");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"actorId\":\"a\",\"sessionId\":\"s\",\"eventTimestamp\":1789300800,\"payload\":[]}")
|
||||
.when().post("/memories/" + memoryId + "/events")
|
||||
.then().statusCode(201)
|
||||
.body("event.eventId", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOmittedPayloadIsRejectedEvenThoughAnEmptyOneIsValid() {
|
||||
String memoryId = createMemory("evtNoPayload2");
|
||||
|
||||
// payload is a required member, so its absence is an error while [] is accepted.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"actorId\":\"a\",\"sessionId\":\"s\",\"eventTimestamp\":1789300800}")
|
||||
.when().post("/memories/" + memoryId + "/events")
|
||||
.then().statusCode(400)
|
||||
.body("message", containsString("payload"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listingPagesThroughWithANextToken() {
|
||||
String memoryId = createMemory("evtPaged");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
createEvent(memoryId, "actor1", "sess1", 1789300800d + (i * 60), "m" + i);
|
||||
}
|
||||
|
||||
String firstPage = given().contentType(ContentType.JSON).body("{\"maxResults\":2}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(2))
|
||||
.body("nextToken", notNullValue())
|
||||
.extract().path("nextToken");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"maxResults\":2,\"nextToken\":\"" + firstPage + "\"}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(200)
|
||||
.body("events", hasSize(1))
|
||||
// No token on the last page: that is what ends a caller's loop.
|
||||
.body("nextToken", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidNextTokenIsRejected() {
|
||||
String memoryId = createMemory("evtBadToken");
|
||||
createEvent(memoryId, "actor1", "sess1", 1789300800d, "hello");
|
||||
|
||||
given().contentType(ContentType.JSON).body("{\"nextToken\":\"not-a-real-token\"}")
|
||||
.when().post("/memories/" + memoryId + "/actor/actor1/sessions/sess1")
|
||||
.then().statusCode(400);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user