|
| 1 | +"""Invoke Bedrock AgentCore Harness to review a GitHub PR. |
| 2 | +
|
| 3 | +Reads PR_URL from the environment. Streams harness output to stdout. |
| 4 | +Uses raw HTTP with SigV4 signing — no custom service model needed. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import time |
| 11 | +import uuid |
| 12 | + |
| 13 | +import boto3 |
| 14 | +from botocore.auth import SigV4Auth |
| 15 | +from botocore.awsrequest import AWSRequest |
| 16 | +from botocore.eventstream import EventStreamBuffer |
| 17 | +from urllib.parse import quote |
| 18 | +import urllib3 |
| 19 | + |
| 20 | +# ANSI color codes |
| 21 | +CYAN = "\033[36m" |
| 22 | +YELLOW = "\033[33m" |
| 23 | +GREEN = "\033[32m" |
| 24 | +RED = "\033[31m" |
| 25 | +DIM = "\033[2m" |
| 26 | +RESET = "\033[0m" |
| 27 | + |
| 28 | +SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..") |
| 29 | + |
| 30 | + |
| 31 | +def read_prompt(filename): |
| 32 | + """Read a prompt template from the prompts directory.""" |
| 33 | + path = os.path.join(SCRIPTS_DIR, "prompts", filename) |
| 34 | + with open(path) as f: |
| 35 | + return f.read() |
| 36 | + |
| 37 | + |
| 38 | +def invoke_harness(harness_arn, body, region): |
| 39 | + """Send a SigV4-signed request to the harness invoke endpoint. Returns a streaming response. |
| 40 | +
|
| 41 | + InvokeHarness is not in standard boto3, so we call the REST API directly. |
| 42 | + boto3 is only used to resolve AWS credentials (from env vars, OIDC, etc.) |
| 43 | + and sign the request with SigV4. The response is an AWS binary event stream. |
| 44 | + """ |
| 45 | + session = boto3.Session(region_name=region) |
| 46 | + credentials = session.get_credentials().get_frozen_credentials() |
| 47 | + url = f"https://bedrock-agentcore.{region}.amazonaws.com/harnesses/invoke?harnessArn={quote(harness_arn, safe='')}" |
| 48 | + request = AWSRequest(method="POST", url=url, data=body, headers={ |
| 49 | + "Content-Type": "application/json", |
| 50 | + "Accept": "application/vnd.amazon.eventstream", |
| 51 | + }) |
| 52 | + SigV4Auth(credentials, "bedrock-agentcore", region).add_auth(request) |
| 53 | + return urllib3.PoolManager().urlopen( |
| 54 | + "POST", url, body=body, |
| 55 | + headers=dict(request.headers), |
| 56 | + preload_content=False, |
| 57 | + timeout=urllib3.Timeout(connect=10, read=600), |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def parse_events(http_response): |
| 62 | + """Yield (event_type, payload) tuples from the harness binary event stream. |
| 63 | +
|
| 64 | + The response arrives as raw bytes in AWS binary event stream format. |
| 65 | + EventStreamBuffer reassembles complete events from the 4KB chunks, |
| 66 | + and we decode each event's JSON payload before yielding it. |
| 67 | + """ |
| 68 | + event_buffer = EventStreamBuffer() |
| 69 | + for chunk in http_response.stream(4096): |
| 70 | + event_buffer.add_data(chunk) |
| 71 | + for event in event_buffer: |
| 72 | + if event.headers.get(":message-type") == "exception": |
| 73 | + payload = json.loads(event.payload.decode("utf-8")) |
| 74 | + print(f"\n{RED}ERROR: {payload}{RESET}", file=sys.stderr) |
| 75 | + sys.exit(1) |
| 76 | + event_type = event.headers.get(":event-type", "") |
| 77 | + if event.payload: |
| 78 | + yield event_type, json.loads(event.payload.decode("utf-8")) |
| 79 | + |
| 80 | + |
| 81 | +def print_stream(http_response): |
| 82 | + """Display harness events with GitHub Actions log groups. |
| 83 | +
|
| 84 | + The harness streams events as the agent works: |
| 85 | + contentBlockStart — a new block begins (text or tool call) |
| 86 | + contentBlockDelta — incremental chunks of text or tool input JSON |
| 87 | + contentBlockStop — block complete, we now have full tool input to display |
| 88 | + messageStop — agent finished |
| 89 | + internalServerException — server error |
| 90 | +
|
| 91 | + Tool calls are wrapped in ::group::/::endgroup:: for collapsible sections |
| 92 | + in the GitHub Actions log UI. Agent reasoning text is printed inline in dim. |
| 93 | + """ |
| 94 | + start_time = time.time() |
| 95 | + iteration = 0 |
| 96 | + tool_name = None |
| 97 | + tool_input = "" |
| 98 | + tool_start = 0.0 |
| 99 | + in_group = False |
| 100 | + text_buffer = "" |
| 101 | + |
| 102 | + def close_group(): |
| 103 | + nonlocal in_group |
| 104 | + if in_group: |
| 105 | + print("::endgroup::", flush=True) |
| 106 | + in_group = False |
| 107 | + |
| 108 | + def flush_text(): |
| 109 | + nonlocal text_buffer |
| 110 | + if text_buffer: |
| 111 | + for line in text_buffer.splitlines(): |
| 112 | + print(f"{DIM}{line}{RESET}", flush=True) |
| 113 | + text_buffer = "" |
| 114 | + |
| 115 | + for event_type, payload in parse_events(http_response): |
| 116 | + |
| 117 | + if event_type == "contentBlockStart": |
| 118 | + start = payload.get("start", {}) |
| 119 | + if "toolUse" in start: |
| 120 | + tool_name = start["toolUse"].get("name", "unknown") |
| 121 | + tool_input = "" |
| 122 | + tool_start = time.time() |
| 123 | + iteration += 1 |
| 124 | + |
| 125 | + elif event_type == "contentBlockDelta": |
| 126 | + delta = payload.get("delta", {}) |
| 127 | + if "text" in delta: |
| 128 | + close_group() |
| 129 | + text_buffer += delta["text"] |
| 130 | + if "toolUse" in delta: |
| 131 | + tool_input += delta["toolUse"].get("input", "") |
| 132 | + |
| 133 | + elif event_type == "contentBlockStop": |
| 134 | + flush_text() |
| 135 | + if tool_name: |
| 136 | + elapsed = time.time() - tool_start |
| 137 | + try: |
| 138 | + parsed = json.loads(tool_input) |
| 139 | + except (json.JSONDecodeError, TypeError): |
| 140 | + parsed = tool_input |
| 141 | + |
| 142 | + close_group() |
| 143 | + |
| 144 | + cmd = parsed.get("command") if isinstance(parsed, dict) else None |
| 145 | + header = f"{CYAN}[{iteration}]{RESET} {YELLOW}{tool_name}{RESET} {DIM}({elapsed:.1f}s){RESET}" |
| 146 | + if cmd: |
| 147 | + header += f": $ {cmd}" |
| 148 | + |
| 149 | + print(f"::group::{header}", flush=True) |
| 150 | + in_group = True |
| 151 | + |
| 152 | + if isinstance(parsed, dict): |
| 153 | + for k, v in parsed.items(): |
| 154 | + if k != "command": |
| 155 | + print(f" {DIM}{k}:{RESET} {str(v)[:300]}", flush=True) |
| 156 | + |
| 157 | + tool_name = None |
| 158 | + tool_input = "" |
| 159 | + |
| 160 | + elif event_type == "messageStop": |
| 161 | + flush_text() |
| 162 | + close_group() |
| 163 | + if payload.get("stopReason") == "end_turn": |
| 164 | + total = time.time() - start_time |
| 165 | + print(f"\n\n{GREEN}{'=' * 50}", flush=True) |
| 166 | + print(f" Done ({int(total // 60)}m {int(total % 60)}s)", flush=True) |
| 167 | + print(f"{'=' * 50}{RESET}", flush=True) |
| 168 | + |
| 169 | + elif event_type == "internalServerException": |
| 170 | + close_group() |
| 171 | + print(f"\n{RED}ERROR: {payload}{RESET}", file=sys.stderr) |
| 172 | + sys.exit(1) |
| 173 | + |
| 174 | + close_group() |
| 175 | + total = time.time() - start_time |
| 176 | + print(f"\n{GREEN}Review complete.{RESET} {DIM}({iteration} tool calls, {int(total)}s total){RESET}") |
| 177 | + |
| 178 | + |
| 179 | +# --- Main --- |
| 180 | + |
| 181 | +# All config comes from environment variables (set via GitHub secrets/workflow) |
| 182 | +MODEL_ID = os.environ.get("HARNESS_MODEL_ID", "us.anthropic.claude-opus-4-7") |
| 183 | +HARNESS_ARN = os.environ.get("HARNESS_ARN", "") |
| 184 | +PR_URL = os.environ.get("PR_URL", "") |
| 185 | + |
| 186 | +for name, val in [("HARNESS_ARN", HARNESS_ARN), ("PR_URL", PR_URL)]: |
| 187 | + if not val: |
| 188 | + print(f"{RED}ERROR: {name} environment variable is required{RESET}", file=sys.stderr) |
| 189 | + sys.exit(1) |
| 190 | + |
| 191 | +# Extract region from the ARN (arn:aws:bedrock-agentcore:{region}:{account}:harness/{id}) |
| 192 | +REGION = HARNESS_ARN.split(":")[3] |
| 193 | +SESSION_ID = str(uuid.uuid4()).upper() |
| 194 | + |
| 195 | +print(f"{CYAN}Session:{RESET} {SESSION_ID}") |
| 196 | +print(f"{CYAN}PR:{RESET} {PR_URL}") |
| 197 | +print(f"{CYAN}Harness:{RESET} {HARNESS_ARN}") |
| 198 | +print() |
| 199 | + |
| 200 | +SYSTEM_PROMPT = read_prompt("system.md") |
| 201 | +REVIEW_PROMPT = read_prompt("review.md").format(pr_url=PR_URL) |
| 202 | + |
| 203 | +request_body = json.dumps({ |
| 204 | + "runtimeSessionId": SESSION_ID, |
| 205 | + "systemPrompt": [{"text": SYSTEM_PROMPT}], |
| 206 | + "messages": [{"role": "user", "content": [{"text": REVIEW_PROMPT}]}], |
| 207 | + "model": {"bedrockModelConfig": {"modelId": MODEL_ID}}, |
| 208 | +}) |
| 209 | + |
| 210 | +http_response = invoke_harness(HARNESS_ARN, request_body, REGION) |
| 211 | + |
| 212 | +if http_response.status != 200: |
| 213 | + error = http_response.read().decode("utf-8") |
| 214 | + print(f"{RED}ERROR: HTTP {http_response.status}: {error}{RESET}", file=sys.stderr) |
| 215 | + sys.exit(1) |
| 216 | + |
| 217 | +print_stream(http_response) |
0 commit comments