Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(agentCore): add agentcore (#1208)
Nahuel Nucera3fb166f59719
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20e89503..55b1a31d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,8 +8,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed-- **SQS — `QueueUrl` used a hardcoded `localhost` host, breaking Docker-executed Lambdas (#1152)** — a Node.js Lambda running under `LAMBDA_EXECUTOR=docker` could not post to SQS without hardcoding the endpoint in its client: the AWS JS SDK v3 SQS client uses the returned `QueueUrl` as its request endpoint (`useQueueUrlAsEndpoint`), and every URL was rendered as `http://localhost:4566/…`, which inside the Lambda container resolves to the container itself rather than the host running MiniStack, so the request failed with connection refused. `CreateQueue`, `GetQueueUrl`, and `ListQueues` now render `QueueUrl`(s) using the caller's incoming `Host` header (how they actually reached MiniStack, e.g. `host.docker.internal:4566`), the same approach LocalStack takes; internal queue state stays keyed on canonical URLs and lookups remain host-agnostic. An explicitly configured `MINISTACK_HOST` pins the host and disables the rewrite.+- **SQS — `QueueUrl` used a hardcoded `localhost` host, breaking Docker-executed Lambdas** — a Node.js Lambda running under `LAMBDA_EXECUTOR=docker` could not post to SQS without hardcoding the endpoint in its client: the AWS JS SDK v3 SQS client uses the returned `QueueUrl` as its request endpoint (`useQueueUrlAsEndpoint`), and every URL was rendered as `http://localhost:4566/…`, which inside the Lambda container resolves to the container itself rather than the host running MiniStack, so the request failed with connection refused. `CreateQueue`, `GetQueueUrl`, and `ListQueues` now render `QueueUrl`(s) using the caller's incoming `Host` header (how they actually reached MiniStack, e.g. `host.docker.internal:4566`), the same approach LocalStack takes; internal queue state stays keyed on canonical URLs and lookups remain host-agnostic. An explicitly configured `MINISTACK_HOST` pins the host and disables the rewrite. Contributed by @thejusdutt. Reported by @Millroy094.+### Added+- **Amazon Bedrock AgentCore — new service emulator** — the agent-runtime control plane and data plane are now emulated. The `bedrock-agentcore-control` endpoint implements `CreateAgentRuntime`, `GetAgentRuntime`, `ListAgentRuntimes`, `UpdateAgentRuntime`, `DeleteAgentRuntime`, `ListAgentRuntimeVersions`, and the runtime-endpoint operations (`CreateAgentRuntimeEndpoint`, `GetAgentRuntimeEndpoint`, `ListAgentRuntimeEndpoints`, `UpdateAgentRuntimeEndpoint`, `DeleteAgentRuntimeEndpoint`); the `bedrock-agentcore` data-plane endpoint implements `InvokeAgentRuntime`, which returns the invocation payload echoed back. `CreateAgentRuntime` reports `CREATING` and `UpdateAgentRuntime` reports `UPDATING` before settling to `READY`, each update bumps `agentRuntimeVersion`, ARNs follow the real `agent/{uuid}:{version}` and `agentEndpoint/{uuid}` shapes, and all state is account+region scoped. Reported by @wolfgangmeyers.- **SNS — `ListPlatformApplications`** — the mobile-push action returned `InvalidAction` even though platform applications created with `CreatePlatformApplication` were already stored. It now lists the caller's platform applications with their attributes and `NextToken` pagination; results are account+region scoped, matching AWS's per-region platform applications. Reported by @ctalibard-sk.- **Kinesis Data Firehose — `AWS::KinesisFirehose::DeliveryStream` CloudFormation support** — stacks containing a delivery stream failed with `Unsupported resource type` even though the Firehose API already implemented `CreateDeliveryStream`. The resource now provisions through CloudFormation into the existing Firehose control plane (S3, Extended S3, Iceberg, and the other destination configs), `Ref` returns the delivery stream name, and `Fn::GetAtt Arn` returns its ARN. Reported by @ryan-bennett.- **Kinesis Data Firehose — Apache Iceberg (S3 Tables) delivery** — a DirectPut delivery stream with an `IcebergDestinationConfiguration` now actually writes records into the target S3 Tables Iceberg table, not just provisions the stream. Each record routes to its destination table from the `DestinationTableConfigurationList` (or a transform Lambda's `metadata.otfMetadata`), and the row operation follows real Firehose Merge-on-Read semantics: `insert` by default, `update`/`delete` matched on the table's `UniqueKeys` (a record whose operation needs keys but has none is dropped to the error path, as on AWS). Rows are written through the S3 Tables Iceberg REST catalog using the bundled DuckDB engine and are immediately queryable. Reported by @ryan-bennett.diff --git a/ministack/app.py b/ministack/app.pyindex 41255215..6f82d51e 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -317,6 +317,7 @@ SERVICE_REGISTRY = {"bedrock-runtime": {"module": "bedrock_runtime"},"bedrock-agent": {"module": "bedrock_agent"},"bedrock-agent-runtime": {"module": "bedrock_agent_runtime"},+ "bedrock-agentcore": {"module": "bedrock_agentcore"},"kafka": {"module": "msk"},}@@ -361,6 +362,7 @@ _state_map = {"bedrock_runtime": "bedrock_runtime","bedrock_agent": "bedrock_agent","bedrock_agent_runtime": "bedrock_agent_runtime",+ "bedrock_agentcore": "bedrock_agentcore","msk": "msk",}diff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex 3845e1c6..2315e2aa 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -29,6 +29,7 @@ STATE_FORMAT_VERSION = 2SERVICE_STATE_FORMAT_VERSIONS = {"appsync": 3,"autoscaling": 3,+ "bedrock_agentcore": 3,"athena": 3,"emr": 3,"eks": 3,diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 5e7f8517..622ce3ff 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -524,6 +524,10 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) -># Map common credential scope namesscope_map = {"monitoring": "monitoring",+ # bedrock-agentcore-control and bedrock-agentcore both sign with+ # credential scope "bedrock-agentcore" (verified via botocore+ # signing_name); one handler serves both, dispatching by path.+ "bedrock-agentcore": "bedrock-agentcore","execute-api": "apigateway","ses": "ses","states": "states",diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.pynew file mode 100644index 00000000..308db136--- /dev/null+++ b/ministack/services/bedrock_agentcore.py@@ -0,0 +1,476 @@+"""Amazon Bedrock AgentCore emulator.++Covers the two AgentCore services, which both sign as ``bedrock-agentcore``:++ * ``bedrock-agentcore-control`` (rest-json) — agent runtime + endpoint control+ plane: Create/Get/List/Update/Delete AgentRuntime and AgentRuntimeEndpoint,+ plus ListAgentRuntimeVersions.+ * ``bedrock-agentcore`` (rest-json) — data plane: InvokeAgentRuntime.++Deterministic and stateful: resources provision instantly (``READY``) and+InvokeAgentRuntime returns a deterministic echo response, so teams can test+runtime lifecycle, endpoint wiring, and Invoke request/response contracts+locally without live AWS.++Shapes, HTTP methods, URIs, ARN/ID patterns, and status enums are verified+against botocore ``bedrock-agentcore-control`` / ``bedrock-agentcore``+service-2.json.+"""+import copy+import json+import logging+import re+import secrets+import string+import time+from urllib.parse import unquote++from ministack.core.persistence import load_state+from ministack.core.responses import (+ AccountRegionScopedDict,+ error_response_json,+ get_account_id,+ get_region,+ json_response,+ new_uuid,+)++logger = logging.getLogger("bedrock_agentcore")++# ---------------------------------------------------------------------------+# State (account + region scoped)+# ---------------------------------------------------------------------------++_runtimes = AccountRegionScopedDict() # agentRuntimeId -> runtime record+_endpoints = AccountRegionScopedDict() # agentRuntimeId -> {endpointName -> endpoint record}++# AgentRuntimeName / EndpointName: start with a letter, then letters/digits/_,+# up to 48 chars total (botocore pattern ^[a-zA-Z][a-zA-Z0-9_]{0,47}$).+_NAME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]{0,47}$")+++def get_state():+ return copy.deepcopy({"runtimes": _runtimes, "endpoints": _endpoints})+++def restore_state(data):+ if not data:+ return+ _runtimes.clear()+ _endpoints.clear()+ _runtimes.update(data.get("runtimes", {}))+ _endpoints.update(data.get("endpoints", {}))+++try:+ _persisted = load_state("bedrock_agentcore")+ if _persisted:+ restore_state(_persisted)+except Exception: # pragma: no cover - best-effort restore+ pass+++def reset():+ _runtimes.clear()+ _endpoints.clear()+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _rand_suffix() -> str:+ alphabet = string.ascii_letters + string.digits+ return "".join(secrets.choice(alphabet) for _ in range(10))+++def _resource_id(name: str) -> str:+ # botocore pattern: [a-zA-Z][a-zA-Z0-9_]{0,99}-[a-zA-Z0-9]{10}+ return f"{name}-{_rand_suffix()}"+++def _runtime_arn(runtime_uuid: str, version: str) -> str:+ return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"+ f"agent/{runtime_uuid}:{version}")+++def _endpoint_arn(endpoint_uuid: str) -> str:+ return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"+ f"agentEndpoint/{endpoint_uuid}")+++def _workload_identity_arn(name: str) -> str:+ return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"+ f"workload-identity-directory/default/workload-identity/{name}")+++def _validation(message: str):+ return error_response_json("ValidationException", message, 400)+++def _not_found(message: str):+ return error_response_json("ResourceNotFoundException", message, 404)+++def _conflict(message: str):+ return error_response_json("ConflictException", message, 409)+++def _parse_body(body) -> dict:+ if not body:+ return {}+ try:+ return json.loads(body)+ except (ValueError, TypeError):+ return {}+++# ---------------------------------------------------------------------------+# Control plane — AgentRuntime+# ---------------------------------------------------------------------------++def _create_agent_runtime(body):+ data = _parse_body(body)+ name = data.get("agentRuntimeName")+ if not name or not _NAME_RE.match(name):+ return _validation("agentRuntimeName must match ^[a-zA-Z][a-zA-Z0-9_]{0,47}$")+ for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):+ if not data.get(field):+ return _validation(f"{field} is required")+ if any(r.get("agentRuntimeName") == name for r in _runtimes.values()):+ return _conflict(f"Agent runtime with name {name} already exists")++ runtime_uuid = new_uuid()+ runtime_id = _resource_id(name)+ version = "1"+ now = time.time()+ arn = _runtime_arn(runtime_uuid, version)+ workload = {"workloadIdentityArn": _workload_identity_arn(name)}+ record = {+ "agentRuntimeArn": arn,+ "agentRuntimeName": name,+ "agentRuntimeId": runtime_id,+ "agentRuntimeVersion": version,+ "createdAt": now,+ "lastUpdatedAt": now,+ "roleArn": data["roleArn"],+ "networkConfiguration": data["networkConfiguration"],+ "status": "READY",+ "agentRuntimeArtifact": data["agentRuntimeArtifact"],+ "workloadIdentityDetails": workload,+ "_uuid": runtime_uuid,+ }+ for opt in ("description", "protocolConfiguration", "environmentVariables",+ "authorizerConfiguration", "requestHeaderConfiguration",+ "lifecycleConfiguration", "metadataConfiguration",+ "filesystemConfigurations"):+ if opt in data:+ record[opt] = data[opt]+ _runtimes[runtime_id] = record+ _endpoints[runtime_id] = {}++ # AWS returns CREATING at create time; the runtime settles to READY.+ return json_response({+ "agentRuntimeArn": arn,+ "workloadIdentityDetails": workload,+ "agentRuntimeId": runtime_id,+ "agentRuntimeVersion": version,+ "createdAt": now,+ "status": "CREATING",+ })+++def _get_agent_runtime(runtime_id):+ record = _runtimes.get(runtime_id)+ if record is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ out = {k: v for k, v in record.items() if not k.startswith("_")}+ return json_response(out)+++def _list_agent_runtimes(body):+ summaries = []+ for r in _runtimes.values():+ summaries.append({+ "agentRuntimeArn": r["agentRuntimeArn"],+ "agentRuntimeId": r["agentRuntimeId"],+ "agentRuntimeVersion": r["agentRuntimeVersion"],+ "agentRuntimeName": r["agentRuntimeName"],+ "description": r.get("description", ""),+ "lastUpdatedAt": r["lastUpdatedAt"],+ "status": r["status"],+ })+ return json_response({"agentRuntimes": summaries})+++def _list_agent_runtime_versions(runtime_id, body):+ record = _runtimes.get(runtime_id)+ if record is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ summary = {+ "agentRuntimeArn": record["agentRuntimeArn"],+ "agentRuntimeId": record["agentRuntimeId"],+ "agentRuntimeVersion": record["agentRuntimeVersion"],+ "agentRuntimeName": record["agentRuntimeName"],+ "description": record.get("description", ""),+ "lastUpdatedAt": record["lastUpdatedAt"],+ "status": record["status"],+ }+ return json_response({"agentRuntimes": [summary]})+++def _update_agent_runtime(runtime_id, body):+ record = _runtimes.get(runtime_id)+ if record is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ data = _parse_body(body)+ for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):+ if not data.get(field):+ return _validation(f"{field} is required")+ now = time.time()+ new_version = str(int(record["agentRuntimeVersion"]) + 1)+ record["agentRuntimeVersion"] = new_version+ record["agentRuntimeArn"] = _runtime_arn(record["_uuid"], new_version)+ record["lastUpdatedAt"] = now+ record["status"] = "READY"+ for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):+ record[field] = data[field]+ for opt in ("description", "protocolConfiguration", "environmentVariables",+ "authorizerConfiguration", "requestHeaderConfiguration",+ "lifecycleConfiguration", "metadataConfiguration",+ "filesystemConfigurations"):+ if opt in data:+ record[opt] = data[opt]+ return json_response({+ "agentRuntimeArn": record["agentRuntimeArn"],+ "agentRuntimeId": runtime_id,+ "workloadIdentityDetails": record.get("workloadIdentityDetails"),+ "agentRuntimeVersion": new_version,+ "createdAt": record["createdAt"],+ "lastUpdatedAt": now,+ "status": "UPDATING",+ })+++def _delete_agent_runtime(runtime_id):+ record = _runtimes.get(runtime_id)+ if record is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ _runtimes.pop(runtime_id, None)+ _endpoints.pop(runtime_id, None)+ return json_response({"status": "DELETING", "agentRuntimeId": runtime_id})+++# ---------------------------------------------------------------------------+# Control plane — AgentRuntimeEndpoint+# ---------------------------------------------------------------------------++def _create_agent_runtime_endpoint(runtime_id, body):+ runtime = _runtimes.get(runtime_id)+ if runtime is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ data = _parse_body(body)+ name = data.get("name")+ if not name or not _NAME_RE.match(name):+ return _validation("name must match ^[a-zA-Z][a-zA-Z0-9_]{0,47}$")+ endpoints = _endpoints.setdefault(runtime_id, {})+ if name in endpoints:+ return _conflict(f"Endpoint {name} already exists")+ target_version = data.get("agentRuntimeVersion") or runtime["agentRuntimeVersion"]+ endpoint_uuid = new_uuid()+ now = time.time()+ record = {+ "name": name,+ "id": _resource_id(name),+ "agentRuntimeEndpointArn": _endpoint_arn(endpoint_uuid),+ "agentRuntimeArn": runtime["agentRuntimeArn"],+ "targetVersion": target_version,+ "liveVersion": target_version,+ "status": "READY",+ "description": data.get("description", ""),+ "createdAt": now,+ "lastUpdatedAt": now,+ }+ endpoints[name] = record+ return json_response({+ "targetVersion": target_version,+ "agentRuntimeEndpointArn": record["agentRuntimeEndpointArn"],+ "agentRuntimeArn": runtime["agentRuntimeArn"],+ "agentRuntimeId": runtime_id,+ "endpointName": name,+ "status": "CREATING",+ "createdAt": now,+ })+++def _get_agent_runtime_endpoint(runtime_id, endpoint_name):+ record = (_endpoints.get(runtime_id) or {}).get(endpoint_name)+ if record is None:+ return _not_found(f"Endpoint {endpoint_name} not found")+ return json_response({+ "liveVersion": record.get("liveVersion"),+ "targetVersion": record.get("targetVersion"),+ "agentRuntimeEndpointArn": record["agentRuntimeEndpointArn"],+ "agentRuntimeArn": record["agentRuntimeArn"],+ "description": record.get("description", ""),+ "status": record["status"],+ "createdAt": record["createdAt"],+ "lastUpdatedAt": record["lastUpdatedAt"],+ "name": record["name"],+ "id": record["id"],+ })+++def _list_agent_runtime_endpoints(runtime_id, body):+ if _runtimes.get(runtime_id) is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ endpoints = _endpoints.get(runtime_id) or {}+ items = []+ for record in endpoints.values():+ items.append({+ "name": record["name"],+ "liveVersion": record.get("liveVersion"),+ "targetVersion": record.get("targetVersion"),+ "agentRuntimeEndpointArn": record["agentRuntimeEndpointArn"],+ "agentRuntimeArn": record["agentRuntimeArn"],+ "status": record["status"],+ "id": record["id"],+ "description": record.get("description", ""),+ "createdAt": record["createdAt"],+ "lastUpdatedAt": record["lastUpdatedAt"],+ })+ return json_response({"runtimeEndpoints": items})+++def _update_agent_runtime_endpoint(runtime_id, endpoint_name, body):+ runtime = _runtimes.get(runtime_id)+ if runtime is None:+ return _not_found(f"Agent runtime {runtime_id} not found")+ record = (_endpoints.get(runtime_id) or {}).get(endpoint_name)+ if record is None:+ return _not_found(f"Endpoint {endpoint_name} not found")+ data = _parse_body(body)+ now = time.time()+ if data.get("agentRuntimeVersion"):+ record["targetVersion"] = data["agentRuntimeVersion"]+ record["liveVersion"] = data["agentRuntimeVersion"]+ if "description" in data:+ record["description"] = data["description"]+ record["lastUpdatedAt"] = now+ record["status"] = "READY"+ return json_response({+ "liveVersion": record.get("liveVersion"),+ "targetVersion": record.get("targetVersion"),+ "agentRuntimeEndpointArn": record["agentRuntimeEndpointArn"],+ "agentRuntimeArn": record["agentRuntimeArn"],+ "status": "UPDATING",+ "createdAt": record["createdAt"],+ "lastUpdatedAt": now,+ })+++def _delete_agent_runtime_endpoint(runtime_id, endpoint_name):+ endpoints = _endpoints.get(runtime_id) or {}+ if endpoint_name not in endpoints:+ return _not_found(f"Endpoint {endpoint_name} not found")+ endpoints.pop(endpoint_name, None)+ return json_response({+ "status": "DELETING",+ "agentRuntimeId": runtime_id,+ "endpointName": endpoint_name,+ })+++# ---------------------------------------------------------------------------+# Data plane — InvokeAgentRuntime+# ---------------------------------------------------------------------------++def _invoke_agent_runtime(runtime_arn, headers, body):+ # The runtime is addressed by ARN; resolve it in this account+region.+ runtime = next((r for r in _runtimes.values()+ if r["agentRuntimeArn"] == runtime_arn+ or r["agentRuntimeArn"].rsplit(":", 1)[0] == runtime_arn.rsplit(":", 1)[0]),+ None)+ if runtime is None:+ return _not_found(f"Agent runtime {runtime_arn} not found")++ session_id = (headers.get("x-amzn-bedrock-agentcore-runtime-session-id")+ or new_uuid())+ content_type = headers.get("content-type", "application/json")+ # Deterministic echo: return the request payload back under a stable shape+ # so contract tests can assert Invoke request/response handling without a+ # real model. No inference is performed.+ try:+ payload = json.loads(body) if body else {}+ except (ValueError, TypeError):+ payload = None+ response = {+ "agentRuntimeArn": runtime["agentRuntimeArn"],+ "input": payload,+ }+ out_body = json.dumps(response).encode("utf-8")+ out_headers = {+ "Content-Type": content_type,+ "x-amzn-bedrock-agentcore-runtime-session-id": session_id,+ }+ return 200, out_headers, out_body+++# ---------------------------------------------------------------------------+# Router — dispatch by rest-json HTTP method + path+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body, query_params):+ inner = path.strip("/")+ # InvokeAgentRuntime: POST /runtimes/{agentRuntimeArn}/invocations. The ARN+ # is a single path label but carries literal '/' and ':' (agent/{uuid}:{ver}),+ # so match the suffix before splitting on '/'.+ if (method == "POST" and inner.startswith("runtimes/")+ and inner.endswith("/invocations")):+ arn = inner[len("runtimes/"):-len("/invocations")]+ return _invoke_agent_runtime(unquote(arn), headers, body)++ parts = [p for p in inner.split("/") if p]+ # All remaining AgentCore paths are rooted at /runtimes.+ if not parts or parts[0] != "runtimes":+ return error_response_json("InvalidAction",+ f"Unsupported AgentCore path: {path}", 400)++ n = len(parts)+ if n == 1:+ if method == "PUT":+ return _create_agent_runtime(body)+ if method == "POST":+ return _list_agent_runtimes(body)+ elif n == 2:+ runtime_id = unquote(parts[1])+ if method == "GET":+ return _get_agent_runtime(runtime_id)+ if method == "PUT":+ return _update_agent_runtime(runtime_id, body)+ if method == "DELETE":+ return _delete_agent_runtime(runtime_id)+ elif n == 3:+ seg = parts[2]+ if seg == "invocations" and method == "POST":+ return _invoke_agent_runtime(unquote(parts[1]), headers, body)+ runtime_id = unquote(parts[1])+ if seg == "versions" and method == "POST":+ return _list_agent_runtime_versions(runtime_id, body)+ if seg == "runtime-endpoints":+ if method == "PUT":+ return _create_agent_runtime_endpoint(runtime_id, body)+ if method == "POST":+ return _list_agent_runtime_endpoints(runtime_id, body)+ elif n == 4 and parts[2] == "runtime-endpoints":+ runtime_id = unquote(parts[1])+ endpoint_name = unquote(parts[3])+ if method == "GET":+ return _get_agent_runtime_endpoint(runtime_id, endpoint_name)+ if method == "PUT":+ return _update_agent_runtime_endpoint(runtime_id, endpoint_name, body)+ if method == "DELETE":+ return _delete_agent_runtime_endpoint(runtime_id, endpoint_name)++ return error_response_json("InvalidAction",+ f"Unsupported AgentCore request: {method} {path}", 400)diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.pynew file mode 100644index 00000000..96c4831d--- /dev/null+++ b/tests/test_bedrock_agentcore.py@@ -0,0 +1,158 @@+"""Amazon Bedrock AgentCore emulator tests.++Covers the v1 surface: agent-runtime CRUD, runtime-endpoint CRUD,+InvokeAgentRuntime (deterministic echo), region isolation, and validation.+"""+import json+import os+import uuid as _uuid_mod++import boto3+import pytest+from botocore.config import Config+from botocore.exceptions import ClientError++ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")++_ARTIFACT = {"containerConfiguration": {"containerUri": "0.dkr.ecr.us-east-1.amazonaws.com/agent:latest"}}+_ROLE = "arn:aws:iam::000000000000:role/agentcore"+_NET = {"networkMode": "PUBLIC"}+++def _client(service, region="us-east-1"):+ return boto3.client(+ service,+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=region,+ config=Config(region_name=region, retries={"mode": "standard"}),+ )+++def _create(ctl, name):+ return ctl.create_agent_runtime(+ agentRuntimeName=name, agentRuntimeArtifact=_ARTIFACT,+ roleArn=_ROLE, networkConfiguration=_NET,+ )+++def test_agentcore_runtime_lifecycle():+ ctl = _client("bedrock-agentcore-control")+ name = f"rt_{_uuid_mod.uuid4().hex[:8]}"+ created = _create(ctl, name)+ rid = created["agentRuntimeId"]+ assert created["status"] == "CREATING"+ assert created["agentRuntimeVersion"] == "1"+ assert created["agentRuntimeArn"].startswith(+ "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/")+ assert created["workloadIdentityDetails"]["workloadIdentityArn"]+ try:+ got = ctl.get_agent_runtime(agentRuntimeId=rid)+ assert got["status"] == "READY"+ assert got["agentRuntimeName"] == name+ assert got["roleArn"] == _ROLE++ ids = [r["agentRuntimeId"] for r in ctl.list_agent_runtimes()["agentRuntimes"]]+ assert rid in ids++ updated = ctl.update_agent_runtime(+ agentRuntimeId=rid, agentRuntimeArtifact=_ARTIFACT,+ roleArn=_ROLE, networkConfiguration=_NET,+ )+ assert updated["agentRuntimeVersion"] == "2"+ assert updated["status"] == "UPDATING"+ assert ctl.get_agent_runtime(agentRuntimeId=rid)["agentRuntimeVersion"] == "2"++ versions = ctl.list_agent_runtime_versions(agentRuntimeId=rid)["agentRuntimes"]+ assert versions and versions[0]["agentRuntimeId"] == rid+ finally:+ deleted = ctl.delete_agent_runtime(agentRuntimeId=rid)+ assert deleted["status"] == "DELETING"++ with pytest.raises(ClientError) as exc:+ ctl.get_agent_runtime(agentRuntimeId=rid)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_agentcore_endpoint_lifecycle():+ ctl = _client("bedrock-agentcore-control")+ name = f"rt_{_uuid_mod.uuid4().hex[:8]}"+ rid = _create(ctl, name)["agentRuntimeId"]+ try:+ ep = ctl.create_agent_runtime_endpoint(agentRuntimeId=rid, name="prod")+ assert ep["endpointName"] == "prod"+ assert ep["status"] == "CREATING"+ assert ep["agentRuntimeEndpointArn"].startswith(+ "arn:aws:bedrock-agentcore:us-east-1:000000000000:agentEndpoint/")++ got = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")+ assert got["status"] == "READY"+ assert got["name"] == "prod"++ names = [e["name"] for e in+ ctl.list_agent_runtime_endpoints(agentRuntimeId=rid)["runtimeEndpoints"]]+ assert names == ["prod"]++ upd = ctl.update_agent_runtime_endpoint(+ agentRuntimeId=rid, endpointName="prod", description="live")+ assert upd["status"] == "UPDATING"++ assert ctl.delete_agent_runtime_endpoint(+ agentRuntimeId=rid, endpointName="prod")["status"] == "DELETING"+ with pytest.raises(ClientError):+ ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")+ finally:+ ctl.delete_agent_runtime(agentRuntimeId=rid)+++def test_agentcore_invoke_returns_deterministic_echo():+ ctl = _client("bedrock-agentcore-control")+ rt = _client("bedrock-agentcore")+ rid_resp = _create(ctl, f"rt_{_uuid_mod.uuid4().hex[:8]}")+ arn = rid_resp["agentRuntimeArn"]+ try:+ resp = rt.invoke_agent_runtime(+ agentRuntimeArn=arn, payload=json.dumps({"prompt": "hello"}).encode())+ assert resp["contentType"] == "application/json"+ body = json.loads(resp["response"].read())+ assert body["agentRuntimeArn"] == arn+ assert body["input"] == {"prompt": "hello"}++ with pytest.raises(ClientError) as exc:+ rt.invoke_agent_runtime(+ agentRuntimeArn="arn:aws:bedrock-agentcore:us-east-1:000000000000:"+ "agent/00000000-0000-0000-0000-000000000000:1",+ payload=b"{}")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ ctl.delete_agent_runtime(agentRuntimeId=rid_resp["agentRuntimeId"])+++def test_agentcore_runtimes_are_region_scoped():+ east = _client("bedrock-agentcore-control", "us-east-1")+ west = _client("bedrock-agentcore-control", "us-west-2")+ name = f"shared_{_uuid_mod.uuid4().hex[:8]}"+ e = _create(east, name)+ w = _create(west, name)+ try:+ east_ids = {r["agentRuntimeId"] for r in east.list_agent_runtimes()["agentRuntimes"]}+ west_ids = {r["agentRuntimeId"] for r in west.list_agent_runtimes()["agentRuntimes"]}+ assert e["agentRuntimeId"] in east_ids and e["agentRuntimeId"] not in west_ids+ assert w["agentRuntimeId"] in west_ids and w["agentRuntimeId"] not in east_ids+ assert ":us-east-1:" in e["agentRuntimeArn"]+ assert ":us-west-2:" in w["agentRuntimeArn"]+ with pytest.raises(ClientError):+ west.get_agent_runtime(agentRuntimeId=e["agentRuntimeId"])+ finally:+ east.delete_agent_runtime(agentRuntimeId=e["agentRuntimeId"])+ west.delete_agent_runtime(agentRuntimeId=w["agentRuntimeId"])+++def test_agentcore_create_validation():+ ctl = _client("bedrock-agentcore-control")+ with pytest.raises(ClientError) as exc:+ ctl.create_agent_runtime(+ agentRuntimeName="bad name!", agentRuntimeArtifact=_ARTIFACT,+ roleArn=_ROLE, networkConfiguration=_NET)+ assert exc.value.response["Error"]["Code"] == "ValidationException"diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex a3ef0a8c..410f995a 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -2667,6 +2667,48 @@ def test_athena_region_scoped_state_is_rejected_by_v2_reader(assert persistence.load_state("athena") is None+def test_bedrock_agentcore_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject AgentCore's regional schema instead of+ accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ runtimes = AccountRegionScopedDict()+ runtimes.set_scoped(+ "000000000000",+ "us-west-2",+ "regional-runtime",+ {+ "agentRuntimeId": "regional-runtime",+ "agentRuntimeArn": (+ "arn:aws:bedrock-agentcore:us-west-2:000000000000:"+ "agent/11111111-1111-1111-1111-111111111111:1"+ ),+ },+ )+ persistence.save_state(+ "bedrock_agentcore",+ {"runtimes": runtimes, "endpoints": AccountRegionScopedDict()},+ )++ raw = _json.loads((tmp_path / "bedrock_agentcore.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded = persistence.load_state("bedrock_agentcore")["runtimes"]+ assert loaded.get_scoped(+ "000000000000", "us-west-2", "regional-runtime"+ )["agentRuntimeArn"].endswith(":1")++ # Simulate the previous binary, whose highest understood format is v2.+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("bedrock_agentcore") is None++def test_inspector2_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):