Repository navigation
feat(runtime): add V2 runtime settings, dev warmup hooks, and V2 template fixes - #2905
Conversation
jariy17
left a comment
There was a problem hiding this comment.
Two more that aren't on changed lines:
src/assets/cdk/package.jsonstill pins@aws/agentcore-cdk1.2.0, which doesn't knowresourceConfigurationsorhooksConfiguration(L3 #482). Can we bump the pin once #482 releases, so deploy doesn't drop the new fields?- The "A starting point" Dockerfile in
runtime-docs/python/README.mdstill usespython:3.12-slim-trixie, which the new V2 section says to avoid. Can we switch it to AL2023 withopenssl-snapsafe-libs, likeagent-python-strands?
| if (response.ok) { | ||
| const body = (await response.json().catch(() => undefined)) as | ||
| { status?: unknown } | undefined; | ||
| if (typeof body?.status === "string" && HEALTHY_STATUSES.has(body.status)) return; |
There was a problem hiding this comment.
The AG-UI template's /ping comes from ag_ui_strands.add_ping, which returns {"status": "healthy"} (lowercase, checked in ag-ui-strands 1.0.4). HEALTHY_STATUSES only has Healthy and HealthyBusy, so agentcore dev never sees an AG-UI runtime with a warmup hook as healthy. Can we compare case-insensitively?
There was a problem hiding this comment.
Good catch. /ping status now compares case-insensitively, with a test for healthy. Checked live: agentcore dev on the AG-UI template with a warmup hook now gets past /ping and runs both calls.
| const url = `http://127.0.0.1:${port}/ping`; | ||
| for (;;) { | ||
| if (signal.aborted) throw new Error("Aborted while waiting for /ping to report healthy."); | ||
| if (Date.now() - lastActivityAt() > idleMs) { |
There was a problem hiding this comment.
Each /ping poll makes uvicorn print an access-log line, which counts as agent output and resets this idle timer. A /ping that never reports healthy (the AG-UI case above, or a 404) polls forever instead of failing. Can we use a fixed deadline from the start of the wait instead of last activity?
There was a problem hiding this comment.
Agreed. /ping now has a fixed 120 s deadline from the start of the wait, independent of agent output, with a test where the agent keeps logging.
| if (!httpPost) return undefined; | ||
| const { path, port } = httpPost; | ||
| if (port === undefined) return { path, port: devPort }; | ||
| if (!isContainerBuild(runtime)) return { path, port }; |
There was a problem hiding this comment.
For CodeZip, a hook with port set to the serving port (8080, as in the PR example) returns 8080 as-is. The agent listens on the dev port, so when dev picks 8081 (8080 busy, --port, or a second agent) the warmup goes to the wrong process or gets ECONNREFUSED. Can we do the serving-port check before the isContainerBuild branch, the same way the container path does?
There was a problem hiding this comment.
Fixed. The serving-port check now comes before the build-type branch, so a hook whose port is the protocol's serving port follows the dev port in both builds. Verified live: with 8080 busy, dev moved the agent to 8081 and sent both warmup calls to 8081.
| return (await resolveDevPort(runtime.protocol, input.port, config.checkPort, signal)) | ||
| .port; | ||
| }, | ||
| resolveHookPort: async (_runtime, hookPort) => |
There was a problem hiding this comment.
The container hook's host port comes from findFreePort without reserving it against the dev ports from resolveDevPorts or other agents starting in parallel. Two agents can claim the same host port, and docker fails with "port is already allocated". Can we pick hook ports in the same pass as the dev ports?
There was a problem hiding this comment.
Fixed. Hook host ports now come from a HookPortReserver that starts with the headless dev ports from resolveDevPorts, also covers dev ports the Inspector picks later, and serializes reservations, so agents starting together can't collide. Tests cover skipping dev ports and concurrent reservations.
| }); | ||
| } | ||
|
|
||
| // Resolved before the agent starts, so an unreachable hook fails without launching it. |
There was a problem hiding this comment.
This repeats the supervisor's warmup startup (hook port, warmupTarget, wait then warmup, chained abort), and the two copies already differ in how they resolve the hook port. Can dev --agent go through a single-agent DevSupervisor or a shared helper, so fixes like the ones above only land once?
There was a problem hiding this comment.
Done. Both paths now go through the same two helpers in readiness.ts: planWarmup (hook host port plus target, so port resolution can't drift) and waitUntilReady (port, then /ping, then warmup). I kept dev --agent out of the supervisor because its exit-code and port-message behaviour differs. The start-up logic is now in one place.
| }); | ||
| export type LifecycleHook = z.infer<typeof LifecycleHookSchema>; | ||
|
|
||
| export const RuntimeHooksConfigurationSchema = z.strictObject({ |
There was a problem hiding this comment.
We pass JSON config through to the service as-is in the CLI. strictObject all the way down means any field the service adds later (another build hook, another httpPost field) fails agentcore.json validation until we ship a release. Can we use z.object (or passthrough) for these service-owned shapes?
There was a problem hiding this comment.
Agreed. Both schemas are now z.looseObject, which keeps unknown keys; plain z.object would drop them. They're shape-only for what we model. Since the constructs re-validate and render these fields, aws/agentcore-l3-cdk-constructs#482 got the same change, plus a generic camelCase-to-PascalCase conversion, so new fields reach CloudFormation too. The misspelled-key test became "keeps fields it doesn't model".
| code to work that is the same for every request, and create random values | ||
| (`secrets` or `os.urandom()`), timestamps, and credentials inside the | ||
| request handler. | ||
| - If `platformVersion` is `V2` in `agentcore/agentcore.json`, load models and |
There was a problem hiding this comment.
This says to load models at module scope, but the AG-UI template now loads API-key models on the first request so the key isn't frozen into the snapshot. A coding agent following this line would move load_model() back to module scope. Can we add the exception: anything that fetches credentials stays per session?
There was a problem hiding this comment.
Done, in both the Python and TypeScript AGENTS.md: anything that fetches credentials, such as a model whose API key comes from AgentCore Identity, stays per session and is built on the first request, not at import.
| self._lock = threading.Lock() | ||
|
|
||
| def run(self, *args, **kwargs): | ||
| with self._lock: |
There was a problem hiding this comment.
_build_agui_agent() does a blocking Identity call on the event loop, so /ping and other requests stall while it runs. The threading.Lock doesn't help in a single-threaded loop. Can we drop the lock and run the build with asyncio.to_thread?
There was a problem hiding this comment.
Right, the lock didn't help. run is now an async generator that builds the agent with await asyncio.to_thread(_build_agui_agent), so the event loop keeps serving /ping during the Identity call. I kept a lock, but as an asyncio.Lock, so concurrent first requests share one build instead of each fetching the key. Checked in isolation: one build for two concurrent requests, and a stand-in /ping kept answering every 50 ms during a 0.5 s blocking build.
…late fixes - resourceConfigurations and hooksConfiguration in agentcore.json, with `agentcore add runtime --resource-configurations/--hooks-configuration` (JSON, V2 only) and memory and hooks rows in `agentcore runtime get`. - `agentcore dev` runs a runtime's build warmup hook the way V2 does: waits for a healthy GET /ping, sends the memory and disk calls in one 120 s budget, and fails the start if either fails. Covers the supervisor and `dev --agent`; a container hook on its own port is published with an extra port mapping. - Templates: AG-UI builds the agent on the first request for API-key model providers, so the key isn't frozen into a V2 snapshot; the Strands container moves to Amazon Linux 2023 with snapshot-safe OpenSSL and Python 3.12; BMA uses AL2023's Python 3.14, which links the base image's snapshot-safe OpenSSL, instead of a uv-installed Python with its own. - Runtime docs follow the current "Optimize for V2" guidance.
6d4014a to
7d390e3
Compare
|
Thanks, all addressed in the new revision:
|
Description
Runtime platform version V2 follow-ups on
feat/snapshot, based on the "AgentCore CLI templates on V2: suggested fixes" doc and the current AWS guides (Optimize for V2, Lifecycle hooks).1.
resourceConfigurationsandhooksConfigurationagentcore.jsonaccepts both on a runtime (src/projectSchemas/runtime.ts). Validation is shape-only and loose: fields the service adds later pass through, and the service rejects invalid sizes, paths, ports, and use without V2.agentcore add runtime --resource-configurations '<json>' --hooks-configuration '<json>', with help ending "(JSON, V2 only)". Both spec builders carry them through.agentcore runtime getshowsmemory(e.g.4096 MiB) andhooks(e.g.build.warmup POST /warmup:8080), or-when the service returns nothing.2.
agentcore devruns the build warmup hookFor a runtime with
hooksConfiguration.build.warmup,devnow does what V2 does before an agent is ready (newsrc/core/dev/readiness.ts):GET /pingto reportHealthyorHealthyBusy;POST <path>withx-amzn-bedrock-agentcore-runtime-warmup-type: memory, thendisk, with no body and no Content-Type, in one 120 s budget;Runtimes without a hook behave exactly as before. Both the supervisor (browser and multi-agent headless) and
dev --agent, which doesn't use the supervisor, run the sequence.A hook on the serving port, the default, is reached on the dev port for both build types. A CodeZip hook on its own port is reached on
127.0.0.1:<port>. For a container hook on its own port,devpublishes it with an extra-p 127.0.0.1:<free host port>:<hook port>. That works for servers listening on0.0.0.0. A loopback-only listener, such as the SDK's own-portHookConfig, can't be reached through port mapping, so the error says to leave the port unset. Status lines note thatdevruns both calls in one process and that a code reload doesn't rerun the hook.3. Template fixes for V2
agui-python-strands_LazyAguiAgent); Bedrock still builds it at importload_model()fetched the API key at import, so it was frozen into the V2 snapshot. Bedrock clients are reusable clients, which the guide says to build before the snapshot.agent-python-strandscontainerpython:3.12-slim-trixie→ Amazon Linux 2023 withdnf swap -y openssl-libs openssl-snapsafe-libsand Python 3.12. OS updates, the non-root user and uv removal are kept.bedrock-managed-agentsuv python install→ AL2023'spython3.14, with uv held to the system Pythonmicrovms:al2023-minimalbase already shipsopenssl-snapsafe-libs, but uv's standalone Python bundled its own OpenSSL. A V2 probe showed BMA's OpenSSL in use before/ping, which is the doc's condition for this switch.runtime-docs(README and AGENTS.md, Python and TypeScript)/ping; snapshot-safe OpenSSL in containers; Node'srandomUUID({ disableEntropyCache: true }); the new settings replace on every updateRelated Issue
Constructs PR: aws/agentcore-l3-cdk-constructs#482
Documentation PR
Documentation is included here: the runtime-docs templates and the README's
agentcore devsection.Type of Change
Testing
How have you tested the change?
bun test(5134 passed, 6 skipped, 326 files)bun run test:e2e, or explained why they are not applicable (CI does not run them for you). I didn't run the e2e suite. I tested by hand on V2 instead (below), because the tests need the linked constructs PR.bun run typecheckbun run lint:checkbun run format:checkbun run auditbun run secrets:checkbun run buildsrc/assets/, I updated affected snapshots withbun test <test-file> --update-snapshotsand committed them (no snapshots cover the changed assets; the template tests are updated)command.md(the release workflow regenerates it)Unit and command-flow tests:
readiness.test.ts: hook-port resolution,/pingretries and timeout, exact warmup headers with no body, non-2xx, budget timeout, and the loopback hint.dev --agent: running only after both calls, a failing hook stops the agent, a container hook through the extra mapping, and no HTTP calls without a hook.-ponly when needed.add runtime: all flags, and a misspelled hook key is rejected.runtime getrows; AG-UI render per provider.V2 deploys (us-east-1, ARM64, with the linked constructs PR packed locally):
READY; a prompt calledadd_numbersand answered 5READY;statusreturned 200READY; full AG-UI event stream, including the tool call and resultagentcore dev, run locally:POST /warmupreceivedmemorythendiskwith no body or Content-Type, and its first invoke saw both.0.0.0.0:9300sidecar was published as127.0.0.1:9300->9300and warmed.127.0.0.1:9300failed with the loopback hint, and the container was cleaned up.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the
terms of your choice.