Skip to content

Latest commit

 

History

History
514 lines (442 loc) · 39.3 KB

05-agentcore.md

File metadata and controls

514 lines (442 loc) · 39.3 KB

05. AgentCore Agents — v2 Reference

The GitHub deploy job prepares its host provisioner with Python 3.12 and the hash-pinned scripts/v2/agentcore/requirements-provision.txt closure through scripts/v2/ci/setup-provision-python.py. Before credential setup or agent image work in that job, local preflight checks the provisioner's complete ctrl operation references, the runtime smoke operation, exact SDK versions and imports. This follows the separate private migration job. The owned SDK environment is cleaned afterward; package-cleanup warnings do not overwrite deployment results.

Purpose

The AI brain of AWSops v2: a Strands agent on AgentCore Runtime fronted by domain gateways that expose read-only MCP tools, plus a Memory store and a Code Interpreter. v2 replaces v1's hand-run CLI/06* scripts and config.json ARN injection with a single idempotent boto3 provisioner driven from Terraform outputs, with all config delivered through SSM.

Chat model configuration

The Strands chat runtime defaults to global.openai.gpt-6-luna. AGENT_MODEL_ID is a process environment override read when agent/agent.py loads; an absent or blank value retains Luna. It does not change the separate Claude diagnosis workers or the default-off Anthropic loop, which retains Sonnet 5.5. The resolved chat model is logged at startup. IAM permits the curated Claude namespace and Luna, including their dated suffixes; other overrides require a separately reviewed grant.

Before deploying either the web or AgentCore image, the controller must review and apply the saved Terraform plan containing task_web_models and agentcore_model_resources. Deploying images first leaves both Terra and its Sonnet fallback without the web grant, or Luna without the runtime grant; model fallback cannot recover missing IAM permissions. Complete the release's required migrations before AgentCore provisioning.

Under the default model_provider = mixed, the supported rollback is the Terraform variable agentcore_chat_model_id (empty by default; other providers reject it; validated to global.openai.gpt-6-luna or global.anthropic.claude-sonnet-5-5, both granted by the runtime role). The applied value reaches scripts/v2/agentcore/provision.py through output.agentcore.model_env, so every provisioning run, including Dev Deploy AgentCore, writes the same AGENT_MODEL_ID; each run also records the effective chat model in its result log. The deployer's shell cannot change the model, and an output value outside the reviewed allowlist refuses the runtime update (runtime ERR). Each reconciliation rewrites the whole environment map, so a manual runtime environment change does not survive it. Rolling back is a reviewed saved-plan apply followed by provisioning, never autonomous.

Luna requests omit explicit cachePoint blocks and cache_tools; any automatic cache benefit must be verified before rollout using a multi-turn tool-using session and its cacheReadInputTokens. A prompt-only probe does not establish tool caching. The two GPT pricing rows are provisional third-party estimates: recheck the AWS Price List API when those models appear for the selected region and inference profile, including cache-read/write billing. No live caching or pricing verification is claimed by the local regression tests.

Deploy-time model provider

model_provider (terraform/foundation/models.tf) chooses the model family for chat, query generation, synthesis, routing and the diagnosis workers: mixed (default; the behavior above, no role env), bedrock_claude (Claude only on Bedrock), bedrock_openai (GPT-6 Luna / GPT-6.1 Terra only on Bedrock, no Claude fallback) or anthropic_api (Claude through the Anthropic Messages API with the key in anthropic_api_key_secret_arn). Non-default values set MODEL_PROVIDER and one model ID per role on the web task, worker Lambda/Fargate task and, through the agentcore output's model_env (allowlisted keys only, provision.py runtime_model_env), the AgentCore runtime. Bedrock model grants shrink to the chosen family; anthropic_api removes them and grants secretsmanager:GetSecretValue on that one secret ARN to the web task, AgentCore, worker task and worker Lambda roles. Code keeps the Bedrock request shapes: web/lib/model-runtime.ts and model_runtime.py (identical copies in agent/ and scripts/v2/workers/) translate Converse / Anthropic-format InvokeModel calls for GPT models on Bedrock and for the Anthropic API; the chat agent uses Strands AnthropicModel for anthropic_api. The default-off Anthropic loop runs only under mixed or bedrock_claude. See model-provider.md.

Current design

Components (provisioned skeleton):

  • AgentCore Runtime — Strands; reuses agent/agent.py as-is. Gateway URLs are injected via a GATEWAYS_JSON env var (agent.py's documented discovery fallback — no awscli-in-image dependency). Runtime name awsops_v2_agent (underscores only).
  • 9 section gateways — awsops-v2-{network,container,data,security,cost,monitoring,iac,ops,external-obs}-gateway (ADR-004 as amended 2026-06-24: 9 provisioned / 9 routed — external-obs, hosting the Prometheus·ClickHouse connectors, was promoted from a provisioned-only slot into the routing set; the chat key observability aliases to it). Integrations is the governance axis (ADR-007/017) — its gated vendor-hosted MCP presets (Datadog·Dynatrace·New Relic, official_mcp_enabled) attach to the external-obs gateway as mcpServer targets when enabled. monitoring covers AWS-native monitoring; the external-obs plugin datasource registry / OTLP / datasource-diag re-home is the Integrations axis (P3).
  • Memory — awsops_v2_memory-*, eventExpiryDuration = 365 days.
  • Code Interpreter — awsops_v2_code_interpreter-* (underscores only).

Design target: 9 section agents + 1 incident orchestrator (the orchestrator is P4). Fleet state: complete — 30 Lambda slices are defined in ai.tf local.agent_lambdas (21 gated on agentcore_enabled, 9 on integrations_enabled; both flags default false, so a fresh plan is a no-op). In the live environment (flags enabled) all 9 gateways carry READY MCP targets and all 16 chat section keys are registered and routable — fleet completed 2026-08-02. Note the runtime nuance (matches the customer deck's slide 12): aws-data and the 6 collector keys currently fall back to standard ops routing because the BFF-local live-Steampipe path is closed by design (ADR-001/010, steampipeAvailable() hard-false); the 9 gateway-routed keys answer via their own agents.

Chat context the BFF passes to the agent (web/app/api/chat/route.ts → agent/agent.py):

  • Follow-up continuity. The client sends previousSection, the last answering gateway. The BFF accepts it only for an active, gateway-backed built-in section; aws-data and collectors are excluded. The routing order is pin > keyword > previous section > default (ops, or ACTIVE_FALLBACK with hybrid routing, where the classifier also decides before the previous section and the result carries method: 'previous').
  • Region scope. chatRegionScope() sends the regions AWSops is configured to inventory for the target account (['*'] for the host and all-regions accounts). This is an AWSops selection, not AWS region enablement, and the ## Region Scope prompt block says so. A failed read sends nothing and logs chat_region_scope_unavailable.
  • Per-turn account labels. Answers carry account (host or a 12-digit id) on the meta frame and in the stored exchange meta, and the client echoes it per history message. When a thread spans accounts, scoped_conversation() prefixes user turns with [Account for this turn: …]. The labels are client-echoed: they are narrative context, not authorization, since the current target is still resolved server-side. Client-supplied copies of the runtime markers are neutralized first. The Strands handler and the flag-gated anthropic_loop path share both helpers.
  • Per-turn tool provenance. History carries text only; earlier tool results are not replayed. The client therefore echoes each assistant turn's footer tools list, sanitizeHistory() keeps at most 32 well-formed names on assistant turns, and build_conversation() appends [Tools called for this answer: …] (with (+N more) past 32) inside the per-message cap. The common footer says such figures may be tool-grounded and should be re-checked with the named tool rather than assumed invented. Like account labels, the list is client-echoed narrative context, not proof; scoped_conversation() neutralizes typed copies of the marker first.

2026-08-31 rollout note (ADR-021): Phase 1's quota guard, structured terminal state, and freshness threshold are implemented in the repository. The agent making this change did not run apply; controller deployment status must be verified separately. Current truth is coexistence: the ops gateway's limited Aurora-backed inventory-read-target is already present alongside direct domain inventory/configuration control-plane targets. query_inventory and inventory_summary disclose per-type healthy|degraded|stale|unavailable using durable last-success metadata and the oldest current row timestamp. A later failed/partial/running attempt does not erase a genuine zero-row success, and preserved stale rows cannot be hidden by newer rows. Phase 2 expands domain-aware Aurora coverage and retires direct targets after parity; Aurora-only is not live. Phase 3 cache work is also pending. ADR-005's mutation/autonomy FROZEN posture is unchanged.

For CloudFront, optional query_inventory.resource_id performs a validated, parameterized identity lookup (one row, no origins/aliases). Responses mark projection=identity_only and echo the ID; omitted attributes are outside this projection. Deployment gate: first apply the reviewed Terraform plan for the inventory Lambda, then run AgentCore deployment (make agentcore) to update the gateway schema. make agentcore does not ship Lambda code. Schema-first rollout lets the old Lambda ignore the ID and return an unmarked bulk list. Consumers must require projection=identity_only and a matching echoed ID; missing/mismatched metadata means unverified, never an exact result or absence proof. Existing sql_reader views/grants suffice; no mutation or migration is added. A miss includes a fixed note directing readers to freshness/direct reads, not an AWS-absence verdict.

Section handoff

With handoff on, a built-in section agent gets a consult_section tool. Calling it attaches another section gateway's read-only tools to the same Strands agent for the rest of the answer, so a question that crosses domains (for example a security-group question that also needs monitoring data) finishes in one answer instead of reporting that no tool is available.

  • Gating (both required): Terraform chat_section_handoff_enabled (default false) flows through provision.py to the runtime env CHAT_SECTION_HANDOFF_ENABLED, and the BFF sends handoff: true only for the built-in tier's main streaming invoke (web/app/api/chat/route.ts). The runtime checks both in handoff_eligible (agent/agent.py).
  • Limits: at most 2 extra sections, never the primary section, depth 1 (consulted tools cannot consult again), no retry of a section whose connect failed, MCP connect startup_timeout=10, and tools whose names duplicate an attached tool are skipped (agent/section_handoff.py).
  • Exclusions: custom agents, any request with a toolAllowlist or systemPromptOverride, ADR-003 multi-domain fan-out, the Bedrock-direct fallback, anthropic_loop and RCA mode never hand off.
  • Provenance: the runtime emits a {"gateways": [...]} frame only when at least one other section was consulted (two or more canonical section keys in use order, primary first); the BFF forwards it as gateways in the final SSE meta and stores it in the message's meta. The chat UI shows a "gateways used" card when it lists two or more.
  • Consult targets: the model picks a section from SECTION_CAPABILITIES (agent/section_handoff.py); agent/test_section_handoff.py fails when a gateway target in scripts/v2/agentcore/catalog.py is not named there. The SDK behaviour handoff relies on (tool specs re-read each event-loop cycle, tools resolved at call time) is pinned against the installed Strands release in agent/tests/test_runtime_dependencies.py.
  • Prompt cache cost: attaching tools changes the request's tool list, so the Bedrock prompt-cache prefix that starts with the tools no longer matches. Every model call after a consult in that answer pays full input tokens for the larger tool list, and cacheReadInputTokens drops for those calls. Answers without a consult are unaffected.

Chat routing of network objects

This applies to every chat request, independent of chat_section_handoff_enabled. In web/lib/route.ts, a network-object rule (security group / 보안 그룹, ENI, NACL / network ACL, route table) sits before the security rule, so "보안 그룹 정책" or "ENI 권한" goes to the network gateway, which has the security-group, NACL and route tools; the security gateway is IAM-only. When the question names an IAM principal (IAM, role, 역할, principal), the rule steps aside and the security rule answers ("which IAM role may modify the security group"); user/사용자 alone is not a principal. On the hybrid path security is dropped from the classifier candidates only when it matched through the network object and a policy word directly after it (only whitespace or 의/에 대한 between) and no principal is named; any other security subject ("보안 그룹과 퍼블릭 노출된 S3", "보안 그룹과 버킷 정책", "… and the account password policy") keeps both candidates for the classifier.

Resource-first routing. A prompt naming an AWS resource ID or ARN (ENI/SG/subnet/VPC-family IDs and EC2 instance IDs, plus IAM/EKS/ECS/RDS/ELB/CloudFront/CloudFormation ARNs) routes to the owning section after a pin (web/lib/route-resources.ts, web/lib/route.ts resourceRoute, method resource). Before keyword matching (stripResources) every network ID is replaced by a network-object word (sg, eni, nacl, route table, or network-resource for vpc/subnet/vpce/tgw/nat/igw/pcx/vpn/vgw/cgw), an instance ID by a neutral token and an ARN by its service name; a role/user ARN (IAM, or an STS assumed-role) also keeps a role word, so it counts as a named IAM principal ("Can arn:aws:sts::…:assumed-role/… modify sg-…?" goes to security). ARN text stops at whitespace, a comma or CJK text, so comma-joined words or ARNs stay separate. Resource-name text is never a keyword, an ARN of a service without its own resource rule (for example DynamoDB) still routes by its service name, and every network ID follows the network-object rule exactly like the object's name: "sg-… 정책" and "subnet-… 권한" go to network, while "sg-… 과 버킷 정책" keeps both network and security as classifier candidates. The resource decides alone only when no IAM principal is named (unless it is an IAM ARN), at most one area's keywords match (a list/count phrasing such as "list all … sg-…" does not count), and that area is absent, the resource's own, or security through 보안 directly after an instance ID ("i-… 보안 점검"). Otherwise the keyword rules, the hybrid classifier and ADR-003 fan-out decide: "which IAM role can modify sg-…", "why is i-… access denied?" and "i-… 퍼블릭 노출" go to security, "i-… CPU 지표" to monitoring, "sg-… 비용" to cost, and "eni-… 와 RDS 연결" to the classifier. An ops-owned resource (EC2 instance, load balancer, CloudFront ARN) is weak evidence like a lone ops keyword: on the hybrid path the classifier arbitrates and the resource's section is the fallback. When several resources are named, the first-named one decides. An enabled custom agent whose keywords match still outranks resource routing (web/app/api/chat/route.ts precedence).

Tool result completeness contract

Capped list results from the domain MCP Lambdas carry completeness metadata so the chat model never reads the first N items as the whole set. cap_list(items, limit, more_pages) (agent/lambda/cross_account.py) produces the base fields; the Runtime Context (build_runtime_context, agent/agent.py) tells the model how to read them.

Field Meaning
returned, total Items in this response, and items the API returned before the cap. total is a lower bound when more_pages or api_result_capped is set.
truncated false is the only completeness certificate; true means partial. A successful call with truncated=false and no items is a real empty result for that account and region.
more_pages The API returned a pagination token, so more items can be fetched.
api_result_capped AWS capped the result and offers no next page (SearchTransitGatewayRoutes); only a narrower filter reaches the rest.
complete=false, query_status, query_failed A Logs Insights result that is interim (Running/Scheduled) or ended without results (Failed/Cancelled/Timeout). This is not a pagination signal.
kept Which end of a capped series was kept (latest for get_metric_data).
*Meta, breakdown* The same fields for a nested list when the top-level total means something else, such as a cost sum.
details_incomplete, readFailed ECS describe calls failed or omitted resources, or the read itself failed (serverless caches): the result is unknown, not empty.
costPagesCut, costPagesCutReason Cost Explorer paging stopped early (page_cap, time_budget, repeated_token); totals and rankings cover only the pages read.

A list without these fields may still be capped, so it is never presented as complete. The synced-inventory tools add a separate scope block stating that they read the host account only (see graph read contract).

Provisioner: scripts/v2/agentcore/{catalog.py, provision.py, provision_report.py} — catalog.py holds the 9 gateway names + the target tool schemas; provision.py does boto3 list → create/update for Runtime, the 9 gateways, the target slices, Memory, and the Code Interpreter, then writes ARNs to SSM. Public output contains fixed stages/reason codes, catalog resource keys, status counts and an explicit dropped-event count; no ARNs or raw errors. Migrations must run FIRST — they create the awsops_sql_reader role and sync its password, and make agentcore does neither; skipping it leaves execute_sql and inventory-read failing Data API auth (see agent-sql-reader). Dev's workflow reuses the private migration task; main/preview retain make migrate. The dev workflow uses node scripts/v2/agentcore.mjs --build-only, refreshes the SAME OIDC role, then calls --provision-only with the verified project/digest. The second phase rechecks the commit tag/digest without rebuilding. Fresh sessions and aggregate phase deadlines keep each phase inside one hour. Other stacks keep make agentcore; SMOKE=1 checks after provisioning. Before dev workflow dispatch, set CI_MIGRATIONS_ENABLED_DEV=true and apply a reviewed plan with ci_migrations_enabled=true, producing a non-null migration_job output. This private-migration prerequisite also applies when smoke is off. The configured dev build role needs push/BatchGetImage access to the selected ${project}-steampipe or ${project}-worker repository; the dev deployer needs those actions on ${project}-agentcore. Web-only ECR grants do not establish this access. See CI ECR scopes; the workflows check access but do not grant it.

Dev smoke requires the matching readiness producer and runtime_deployment output with inventory enabled; these producer dependencies must land before selecting smoke. The applied agentcore.deployment_readiness_enabled output must also be boolean true. The provisioner maps it to DEPLOYMENT_READINESS_ENABLED; missing/false keeps the probe disabled, even if an ambient environment variable says true. Other stacks retain advisory compatibility invocation when readiness is unavailable, and advisory structured checks when available. Invocation transport failures still fail. AgentCore foundation resources require agentcore_enabled (default false → count/for_each = 0, a no-op). The dev CI migration task has its own default-off ci_migrations_enabled gate.

The structured check traverses the Ops inventory tools and the model through the producer. It accepts one SSE payload (optional data spacing, event/id/comments and [DONE]), checks nonce/account and fixed booleans, and retains a count protocol cap of 500. The current exact lookup reports zero or one identity match; success requires a positive count. ageMinutes is bounded to 0–1440 for validation; freshness comes from the MCP producer's stale_after_minutes classifier, not a hard 15-minute client threshold. This optional CLI smoke is not the full web/worker release gate or a Memory/Code Interpreter test.

Terraform-owned parts (terraform/foundation/ai.tf): dual-tier ECR (awsops-v2-agentcore), the AgentCore IAM role (Runtime + gateways), the agent Lambda role + the Lambda slices (for_each over local.agent_lambdas + archive_file + permission), 3 SSM placeholder params (ignore_changes = [value]), and the web task-role SSM read grant. Control-plane resources are not Terraform-native, so they live in provision.py.

Config source of truth = SSM, at /ops/awsops-v2/agentcore/{runtime_arn, interpreter_id, memory_id}. The web BFF reads these at runtime via the task role — not ECS valueFrom — to avoid a task-start race. Placeholders are written by Terraform; provision.py overwrites with real values.

Provisioner reconciliation

Before upgrading, verify that the operator-owned deployer has bedrock-agentcore:GetGateway as described in the deployment role prerequisites. New gateways use AWS_IAM inbound auth: every caller SigV4-signs with the Runtime role, which holds bedrock-agentcore:InvokeGateway on the account's gateways. Existing gateways are read in full before reconciling the applied role and catalog description. UpdateGateway rejects authorizer-type changes ("Authorizer type cannot be updated for an existing gateway"), so a deployed NONE gateway records ERR gateway_auth_replacement_required and the run exits nonzero; the provisioner never deletes or recreates it. Updates preserve deployed inbound auth/protocol and optional security settings; absent optional protocol fields are omitted, never invented from create-time defaults. Known IDs remain available to Runtime routing, pruning and all ADR-017 teardown paths after read/update failures. Description-only request failures remain warnings.

Replacing an unauthenticated gateway

Gateways created before the AWS_IAM default use NONE: any caller who knows the gateway URL can list and invoke its tools. Replacement is an operator procedure for the affected stack only; the stack's section tools are unavailable until it completes.

  1. Select only this stack's gateways: awsops-v2-*-gateway whose roleArn is this stack's AgentCore role and whose ID appears in this stack's Runtime GATEWAYS_JSON. Gateway names are not project-scoped, so confirm no other stack's Runtime references them, and leave every other gateway untouched.
  2. For each selected gateway, delete every target (list-gateway-targets, delete-gateway-target) and wait until the target list is empty.
  3. Delete the gateway and poll get-gateway until it returns ResourceNotFoundException; DELETING is not complete.
  4. Re-run make agentcore SMOKE=1 (dev: dispatch Deploy AgentCore with smoke=true). The provisioner creates AWS_IAM gateways and their targets and updates the Runtime's GATEWAYS_JSON.
  5. Verify get-gateway reports AWS_IAM, an unsigned MCP tools/list request is rejected, and the signed smoke/readiness check passes.

Role verification is functional, even when the listed description already matches: a matching label cannot prove that the gateway uses the applied role. If SDK retry handling still returns a GetGateway failure, including a throttle or timeout, it records ERR and makes the run exit nonzero while retaining the known ID and baseline teardown. This does not claim that role drift was observed; it reports that reconciliation could not be verified. Only after a successful read confirms the role may a description-only update failure be reported as WARN. The old description-only path's warning policy does not establish a role-verification success.

Verified deployment prerequisite, 2026-09-14: the public repository's historical dev-branch audit workflow at the audited commit completed run 34819307611. These links identify the workflow and execution at dev commit cdb8d4b13b9ab2dbc9b38ac0534f4d50ef58fbdd, independently of which workflow files exist in a reader's checkout. That run successfully read the data gateway and RDS target using a restricted read session of AWS_CI_DEPLOYER_DEV_ROLE_ARN in the configured development account. The READY resources had a role and Lambda ARN that did not match applied state. This verifies the new read prerequisite for that deployment identity; other installations must verify their own grant before upgrading. The snapshot proves configuration drift, not the cause of the earlier failed target request.

Lambda target drift covers the applied Lambda ARN, managed credential-provider type and tool definitions (name, description, inputSchema). Target metadata and private endpoints are preserved. No new gateway/target wait or automatic state-based recovery is added. CREATED/UPDATED mean request acceptance; EXISTS means configuration match. None proves readiness or tool invocation. Existing Runtime and curated MCP-target readiness/retirement behavior remains.

Runtime construction and ADR-017 enforcement keep their baseline behavior. There is no new identity-completeness gate or retirement exemption. Explicit disabled/blocked endpoints, revoked acknowledgments, missing credentials and tombstones still retire on known gateways; an unconfirmed allowlist-carrying Runtime still invokes the existing fail-closed retirement policy.

Validation/conflict/not-found/SDK-validation failures have fixed public codes; raw messages, configuration, credentials and ARNs are not emitted. An old operation_failed record cannot establish its original cause. A persistent FAILED state requires authorized read evidence and operator-approved repair; the provisioner never automatically deletes/recreates it. Normal configuration drift may submit an update, with service rejection reported safely.

Offline tests need pytest and the SDK dependencies declared in scripts/v2/requirements-test.txt and agent/requirements.txt. Run each file in its own process, as required by merge verification:

for test_file in scripts/v2/agentcore/test_*.py; do
  python3 -m pytest -q "$test_file" || exit
done
python3 -m pytest -q scripts/v2/ci/test_setup_provision_python.py
python3 scripts/v2/ci/runtime-build-provision.test.py

API contracts: UpdateGateway and UpdateGatewayTarget.

Connector target sync on datasource registration

A connector Lambda created by a later Terraform apply has no gateway target until the provisioner runs again, so chat reports zero connector tools for a freshly registered datasource. With connector_target_sync_enabled (default false; requires workers_enabled, agentcore_enabled and integrations_enabled), POST /api/datasources/manage enqueues a connector_target_sync job (scripts/v2/workers/connector_targets.py, Lambda runtime) fire-and-forget, only for the five connector kinds (ClickHouse, Prometheus, Loki, Tempo, Mimir). Before writing, the job calls GetGateway and proceeds only when the gateway's roleArn is this stack's AgentCore role (CONNECTOR_TARGET_GATEWAY_ROLE_ARN) and its inbound auth is AWS_IAM; otherwise it skips with gateway_owned_by_another_stack / gateway_auth_not_iam. A missing or ambiguous gateway fails the job (a failed row), every outcome is logged to the dedicated function's log group (/aws/lambda/<project>-connector-target-sync), and a concurrent create conflict is reported as exists. The job creates or updates <kind>-mcp-target on the kind's catalog gateway — awsops-v2-external-obs-gateway for ClickHouse/Prometheus, awsops-v2-monitoring-gateway for Loki/Tempo/Mimir — with the configuration ensure_targets writes (packaged catalog.py; parity is unit-tested). Vendor MCP presets (Datadog/Dynatrace) remain owned by ensure_mcp_server_targets; Jaeger has no chat target. The job accepts only this stack's connector Lambda ARNs from CONNECTOR_TARGET_LAMBDAS, never deletes, and leaves a target that invokes another stack's Lambda untouched (gateway names are account-wide). IAM: the grant sits on the role of a dedicated <project>-connector-target-sync Lambda (runs outside the VPC; AgentCore control plane only): ListGateways (region-scoped) plus Get/List/Create/UpdateGatewayTarget and GetGateway on those two gateway ARN patterns only. The worker job invokes that function synchronously; the shared worker role holds only lambda:InvokeFunction on that one function. Gateway names are account-wide (not var.project-scoped), so IAM cannot tell two awsops stacks in one account apart; the runtime GetGateway role/auth check is the stack boundary. This is ADR-023 (owner 2026-11-05), the ADR-005 owner-override exception second after ADR-015. created/updated mean the request was accepted, not that the target is READY (same semantics as the provisioner); chat sees the connector once the gateway finishes reconciling the target. make agentcore remains the full reconciler. In an account shared by several awsops stacks, a gateway's roleArn follows whichever stack last ran the provisioner, so the check accepts the stack that currently owns the gateway; enable the flag on one stack per account. Before its first control-plane call the function preflights the runtime SDK's bedrock-agentcore-control service model and fails with sdk_model_missing when the model or a required operation is absent. Operations (enable, verify, reason codes, rollback): connector-target-sync runbook.

Decisions (ADRs)

ADR bodies live in the private upstream repository; the paths below are reference identifiers, not files in this public checkout.

  • ADR-004 — AgentCore gateways & runtime, incl. runtime-customizable agents & skills (Aurora catalog + resolver + registry-agnostic agent.py; built-in vs custom tiers; per-account Agent Spaces; BYO-MCP). ../decisions/004-agentcore-gateways-runtime.md
  • ADR-004 — gateway role split (note the 2026-06-03 correction: 7 → 8 gateways). ../decisions/004-agentcore-gateways-runtime.md
  • ADR-003 — AI agent routing (hybrid routing & multi-route parallel synthesis; the classifier picks built-in routes + enabled custom agents). ../decisions/003-ai-agent-routing.md
  • ADR-021 — quota-isolated inventory reads; Phase 1 repository implementation complete, limited ops Aurora reader coexists with direct targets, Phase 2/3 cutover pending. ADR-021 (private upstream decision)

Key files

File Role
terraform/foundation/ai.tf TF-owned ECR/IAM/Lambda-slice/SSM/web-grant (gated on agentcore_enabled)
scripts/v2/agentcore.mjs Dev build-only/provision-only phases with verified digest handoff; legacy make agentcore elsewhere
scripts/v2/agentcore/catalog.py 9 gateway names + GW descriptions + target tool schemas
scripts/v2/agentcore/provision.py Idempotent provisioner, SSM writes and post-provision smoke (strict on dev; advisory elsewhere)
scripts/v2/agentcore/provision_report.py Fixed stage/error codes, catalog keys and bounded status counts; no raw resource/error output
scripts/v2/ci/runtime-build.mjs Dev account checks, BatchGetImage repository preflight, bounded ARM64 build/push and digest verification
agent/agent.py Strands agent (reused as-is; receives GATEWAYS_JSON)
agent/lambda/ Agent tool Lambda sources — full fleet (30 slices; e.g. aws_iam_mcp.py, flowmonitor.py, connector lambdas, cross_account.py)

Status

P1f ✅ — A7 GREEN (historical milestone record — the provisioner's first verified run, back when only the 2 bootstrap slices existed; see Current design above for the fleet's present size).

  • provision first run: 0 errors; historical smoke invoked runtime → security gateway → list_roles. This historical record is not the current structured-readiness contract.
  • Idempotent re-run: every resource EXISTS, Runtime UPDATED (the update path re-passes roleArn + networkConfiguration — proves the v1 quirk is handled, not a ConflictException).
  • Intentional schema drift re-run: update_gateway_target (UPDATED ... (schema drift)) — a reconciliation path v1 never had.

Skeleton first verified (P1f) with 9 gateways incl. awsops-v2-external-obs-gateway, runtime ARN + memory id in SSM (not PENDING) and an initial 2-slice lambda_arns = [iam-mcp, flow-monitor]; the fleet has since grown to the full 30 slices (2026-08-02).

Learnings & gotchas

  • Explicit model output ceiling — the Strands BedrockModel in agent/agent.py sets max_tokens=AGENT_MAX_TOKENS (default 16000, env-overridable). Without it ConverseStream used the model's default output limit, and a live dev root-cause answer stopped mid-sentence with MaxTokensReachedException. An answer that still stops after streaming began ends with a localized notice saying whether it hit the length limit or lost the connection.
  • SSM reserved prefix — SSM rejects any parameter path starting with aws… (reserved). Use /ops/${project}/… (hence /ops/awsops-v2/agentcore/*).
  • Gateway not yet READY — a just-created gateway can make the first create_gateway_target throw ValidationException. Confirm READY through an authorized read, then re-run the idempotent provisioner. Persistent FAILED states require diagnosis; request acceptance is not readiness and does not authorize destructive recreation.
  • Underscore-only names — Code Interpreter and Memory names allow underscores only, no hyphens (awsops_v2_code_interpreter, awsops_v2_memory).
  • Memory expiry — eventExpiryDuration ≤ 365 days.
  • Runtime update — must re-pass roleArn + networkConfiguration on every update.
  • Name collision avoidance — gateways were renamed from v1's awsops-{key} to awsops-v2-{key}-gateway to isolate from v1 in the shared account.

P3 backlog (DO NOT implement — list only; struck items shipped since):

  • Full Lambda tool fleet (shipped 2026-08-02)
  • section = routing
  • Right-docking chat UI
  • OpenCost setup = a read-only out-of-band install bundle the operator runs (AWS-resource mutation stays FROZEN, ADR-005) — NOT an in-app mutating action

Source

Consolidates three source docs (now archived):

  • docs/history/archive/2026-05-31-awsops-v2-p1f-agentcore-provisioner.md (primary)
  • docs/history/archive/2026-05-31-custom-agents-skills-design.md
  • docs/history/archive/2026-05-31-adr-031-phase1.md

Review: v2-p1f-scope-architecture-review (private upstream repo) (3-AI cross review — MID-minus scope decision, least-privilege roles, SSM-not-valueFrom).

Deployment readiness mode

agent/readiness.py implements bounded, default-off mode=deployment_readiness. Before the mandatory dev Deploy Web gate, explicitly apply ci_readiness_enabled=true with AgentCore enabled, then provision. CI_READINESS_ENABLED_DEV=true supplies this separate opt-in in public dev CI. Only the applied agentcore.deployment_readiness_enabled sets DEPLOYMENT_READINESS_ENABLED; shell overrides are ignored. Fixed MCP tools read one CloudFront identity; producer freshness and bounded inference leave unknown attributes unassessed. Nonce/account-bound responses retain completed checks on timeout. Administrator or deployment-verifiers membership, one in-flight request and a 60-second process cooldown are required. The mandatory release gate combines web-role SSM/AgentCore/model proof, a fresh known CloudFront record, complete post-marker evidence for every current catalog type and both owned workers under the collection contract. Partial, failed, stale or unknown evidence cannot pass; the configured catalog does not establish universal AWS-resource coverage. An opt-in apply creates the verifier group only with readiness and AgentCore enabled; membership additionally requires the managed demo flag. No admin/IAM role is granted. Public CI permits readiness only on dev. CI_READINESS_ENABLED_DEV is a dedicated true/false override; empty/unset preserves explicit Terraform configuration and default false. The runtime profile alone does not enable it. The controller verifies authenticated readiness access, not live group/membership state. Use the reviewed import procedure for existing resources; do not create duplicates. Use a fresh login after membership changes. Removal leaves issued group claims unchanged for their remaining 12-hour lifetime unless session revocation rejects them; runtime disablement is independent. Web invocation validates the runtime ARN before caching; PENDING or malformed values fail. Status discovery only extracts a runtime ID and does not perform that full ARN validation. Both honor an explicitly empty SSM_RUNTIME_ARN_PARAM, which the web task receives when AgentCore is disabled. The separate AGENTCORE_RUNTIME_ARN_PARAM alias and incident bridge's literal project paths are unchanged; other control-plane status reads can still run.

The Web custom-agent resolver consumes web/lib/gateway-tool-catalog.json, an exact read-only target-identity mirror of catalog.py, checked by web/lib/agent-resolver.test.ts. Update both together. Both Runtime loops filter ambiguous identities before deduplication; configured empty grants use the legacy-safe deny-all token. Web policy history requires the agent-tool-policy-history migration before Web rollout; Runtime code rollout is separate.