feat(bedrock-agentcore): implement InvokeHarness (#3557)

* feat(bedrock-agentcore): implement InvokeHarness

InvokeHarness was the last gap keeping an application's agent chat on real
AWS. #3556 added the Memory event data plane, so conversation history works
locally, but the invoke call itself had nothing to answer it.

There is no agent loop here and no model. What is emulated is the wire
contract an application integrates against: POST /harnesses/invoke returns
an application/vnd.amazon.eventstream response carrying messageStart,
contentBlockStart, one contentBlockDelta per chunk, contentBlockStop,
messageStop and metadata, in that order. The reply echoes the caller's last
user message, which makes a chat client visibly work end to end and leaves
a request that failed to parse obvious rather than hidden behind a fixed
string.

The wire bindings are the part worth knowing, and they are not what the
request model suggests. harnessArn and qualifier are query parameters,
runtimeSessionId and runtimeUserId are headers
(X-Amzn-Bedrock-AgentCore-Runtime-Session-Id / -User-Id), and only
messages, model and tools travel in the JSON body. Reading them from the
body compiles, passes a hand-written test, and then fails against the real
SDK with "harnessArn is required".

A request carrying no user message is legitimate rather than an error: a
caller whose memory already holds the current turn sends none, so that case
answers with a canned line. harnessArn is not resolved, because the
emulator models no harness resource; InvokeAgentRuntime is permissive for
the same reason.

BedrockStreamEncoder moves to core/common as AwsEventStreamWriter and
becomes public, next to the AwsEventStreamEncoder it already delegates to.
Both services now share one frame writer rather than duplicating the
header-map wrapper. bedrock-runtime keeps its behaviour and its streaming
tests are the regression guard.

Tool execution, skills and multi-turn iteration are not emulated, so no
tool-use block is produced even when a request supplies tools.

* fix(bedrock-agentcore): validate the InvokeHarness request contract

messages is a required member. Treating a missing or non-array field the
same as an empty array made an omitted required member indistinguishable
from a legitimate empty one, so the two are now separated: an empty array
still gets the canned reply, an absent member is a ValidationException.

harnessArn and runtimeSessionId were only checked for being non-blank.
Both carry modelled constraints, taken from the bundled botocore service
model rather than guessed:

  harnessArn        arn:...:bedrock-agentcore:<region>:<account>:harness/
                    <name>-<10 alphanumerics>
  runtimeSessionId  33 to 100 characters, [a-zA-Z0-9][a-zA-Z0-9-_]*

Real AgentCore enforces the ARN shape before anything else: an ARN of
harness/h-1 comes back as "Invalid harness ARN format" even when the rest
of the request is wrong too, which is why the test values in this branch
had to change.

The ARN's shape is checked but the harness is still not resolved, because
the emulator models no harness resource. A well formed ARN naming nothing
is accepted, and has a test saying so.

* fix(bedrock-agentcore): report a malformed harness ARN before a missing session id

The ARN shape was checked after both presence checks, so a request carrying a
malformed ARN and no runtimeSessionId header came back as "runtimeSessionId is
required" rather than the ARN error AWS returns. No test exercised two bad
fields at once.

The ARN is now validated whole, presence and shape together, before
runtimeSessionId is read.
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-09-15 07:44:22 -04:00
1 parent 917e94914f
commit 6f05442218
9 files changed
+503 -24

No files matched your search

@@ -0,0 +1,199 @@
package io.github.hectorvent.floci.services.bedrockagentcore;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
/**
* {@code InvokeHarness} streams an event-stream response.
*
* <p>The body is binary event-stream framing rather than JSON, but the event names and the JSON
* payload text still appear as UTF-8 substrings between the framing bytes, which is how the
* bedrock-runtime streaming tests assert on the same encoding.
*/
@QuarkusTest
class BedrockAgentCoreHarnessIntegrationTest {
/** Matches the modelled ARN pattern: a name then a ten character suffix. */
private static final String ARN =
"arn:aws:bedrock-agentcore:us-east-1:000000000000:harness/myHarness-abc1234567";
/** A runtime session id has a documented minimum of 33 characters. */
private static final String SESSION = "session-0123456789abcdef0123456789abcdef";
private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id";
/**
* Rebuilds the assistant text from the contentBlockDelta frames, the way a consumer does.
* Asserting on the whole phrase directly would fail: the reply is chunked, so it is split
* across frames and never appears contiguously in the body.
*/
private static String assistantText(String eventStreamBody) {
Matcher matcher = Pattern.compile("\\{\"text\":\"(.*?)\"\\}").matcher(eventStreamBody);
StringBuilder text = new StringBuilder();
while (matcher.find()) {
text.append(matcher.group(1));
}
return text.toString();
}
/**
* Posts with the bindings the SDK uses: {@code harnessArn} is a query parameter and
* {@code runtimeSessionId} a header. Only messages/model/tools travel in the body.
*/
private static RequestSpecification request(String harnessArn, String sessionId) {
RequestSpecification spec = given().contentType("application/json");
if (harnessArn != null) {
spec = spec.queryParam("harnessArn", harnessArn);
}
if (sessionId != null) {
spec = spec.header(SESSION_HEADER, sessionId);
}
return spec;
}
private static String invoke(String harnessArn, String sessionId, String body, int expectedStatus) {
return request(harnessArn, sessionId).body(body)
.when().post("/harnesses/invoke")
.then().statusCode(expectedStatus)
.extract().body().asString();
}
@Test
void theReplyEchoesTheLastUserMessage() {
String body = request(ARN, SESSION)
.body("""
{"messages": [{"role": "user", "content": [{"text": "what is EIDR?"}]}]}
""")
.when().post("/harnesses/invoke")
.then().statusCode(200)
.header("Content-Type", containsString("application/vnd.amazon.eventstream"))
.extract().body().asString();
assertThat(assistantText(body), containsString("what is EIDR?"));
}
@Test
void theStreamCarriesTheFullEventSequenceInOrder() {
String body = request(ARN, SESSION)
.body("""
{"messages": [{"role": "user", "content": [{"text": "hello"}]}]}
""")
.when().post("/harnesses/invoke")
.then().statusCode(200)
.extract().body().asString();
assertThat(body, containsString("messageStart"));
assertThat(body, containsString("assistant"));
assertThat(body, containsString("contentBlockStart"));
assertThat(body, containsString("contentBlockDelta"));
assertThat(body, containsString("contentBlockStop"));
assertThat(body, containsString("messageStop"));
assertThat(body, containsString("end_turn"));
assertThat(body, containsString("metadata"));
// Order matters to a consumer building a message from the stream.
assertThat(body.indexOf("messageStart"), lessThan(body.indexOf("contentBlockDelta")));
assertThat(body.indexOf("contentBlockDelta"), lessThan(body.indexOf("messageStop")));
assertThat(body.indexOf("messageStop"), lessThan(body.indexOf("metadata")));
}
@Test
void onlyTheLastUserMessageIsEchoed() {
String body = request(ARN, SESSION)
.body("""
{"messages": [
{"role": "user", "content": [{"text": "first question"}]},
{"role": "assistant", "content": [{"text": "an answer"}]},
{"role": "user", "content": [{"text": "second question"}]}]}
""")
.when().post("/harnesses/invoke")
.then().statusCode(200)
.extract().body().asString();
assertThat(assistantText(body), containsString("second question"));
assertThat(assistantText(body), not(containsString("first question")));
}
@Test
void anEmptyMessagesArrayStillStreamsAWellFormedResponse() {
// Legitimate: a caller whose memory already holds the current turn sends no messages.
String body = invoke(ARN, SESSION, "{\"messages\": []}", 200);
assertThat(body, containsString("messageStart"));
assertThat(body, containsString("messageStop"));
assertThat(assistantText(body), containsString("No user message was supplied."));
}
@Test
void aRequestWithoutAHarnessArnIsRejected() {
String body = invoke(null, SESSION, "{}", 400);
assertThat(body, containsString("ValidationException"));
assertThat(body, containsString("harnessArn"));
}
@Test
void aRequestWithoutARuntimeSessionIdIsRejected() {
String body = invoke(ARN, null, "{}", 400);
assertThat(body, containsString("ValidationException"));
assertThat(body, containsString("runtimeSessionId"));
}
@Test
void anUnknownHarnessArnIsAccepted() {
// The emulator models no harness resource, so there is nothing to resolve an ARN against.
// Well formed but naming no harness: the shape is checked, the resource is not resolved.
request("arn:aws:bedrock-agentcore:us-east-1:000000000000:harness/unknownOne-zzzz999999", SESSION)
.body("""
{"messages": [{"role": "user", "content": [{"text": "hi"}]}]}
""")
.when().post("/harnesses/invoke")
.then().statusCode(200);
}
@Test
void anOmittedMessagesMemberIsRejected() {
// messages is required. An empty array is a legitimate request; omitting the member is not,
// so the two must not collapse into the same canned reply.
String body = invoke(ARN, SESSION, "{}", 400);
assertThat(body, containsString("messages"));
}
@Test
void aNonArrayMessagesMemberIsRejected() {
invoke(ARN, SESSION, "{\"messages\": \"hello\"}", 400);
}
@Test
void aRuntimeSessionIdShorterThanTheMinimumIsRejected() {
String body = invoke(ARN, "short", "{\"messages\": []}", 400);
assertThat(body, containsString("runtimeSessionId"));
}
@Test
void aMalformedHarnessArnIsRejected() {
String body = invoke("anything", SESSION, "{\"messages\": []}", 400);
assertThat(body, containsString("harness ARN"));
}
@Test
void aMalformedArnIsReportedAheadOfAMissingRuntimeSessionId() {
String body = invoke("anything", null, "{\"messages\": []}", 400);
assertThat(body, containsString("harness ARN"));
assertThat(body, not(containsString("runtimeSessionId")));
}
@Test
void anArnWithoutTheTenCharacterSuffixIsRejected() {
invoke("arn:aws:bedrock-agentcore:us-east-1:000000000000:harness/h-1", SESSION,
"{\"messages\": []}", 400);
}
}