Repository navigation
Component Agent Runtime
Source-Agent-Infra-Deployment-Review records code checked at 98fadf7,
not merged/deployed behavior. It supersedes this page's warm-up claim for that
revision: serving requests do not reuse the separately warmed client.
The T159-T162 branch batch (ee4e458) reads invocationContext.usage, not lifetime
metrics, and makes control reads/session writes strongly consistent/conditional.
The 2026-11-25 T189-T192 remediation now wires admission/reservation
refusals, retryable deadlines and persistent web-search claims. Live AWS
deployment and billable probes remain unauthorized; the historical
walkthrough below is not proof of deployment readiness.
The agent runtime is a Node HTTP server around the Strands SDK. It creates a Max Height agent with a Bedrock model and three tools, exposes /ping and /invocations, tracks short-lived sessions in memory, and includes separate modules for memory extraction/storage, personality checking, stutter injection, re-engagement, observability spans, and golden personality evaluation data. It connects conceptually to Component-WebSocket-Transport and deployment resources in Component-Infra-Stacks.
-
packages/agent/src/index.tscreates the Strands agent and HTTP server. -
packages/agent/src/bedrock/warmup.tsdrives the startup probe that warms the Bedrock runtime client. -
packages/agent/src/handlers/sessionManager.tscreates sessions and enforces caps. -
packages/agent/src/handlers/reEngagement.tsschedules idle nudges. -
packages/agent/src/handlers/personalityCheck.tschecks response text for voice and banned patterns. -
packages/agent/src/handlers/observability.tsemits trace spans as JSON. -
packages/agent/src/memory/*defines memory extraction, adapter, handlers, and a client abstraction. -
packages/agent/src/personality/systemPrompt.tsbuilds the system prompt. -
packages/agent/src/personality/stutterInjection.tsdetects/injects stutters. -
packages/agent/src/tools/*defines weather, news, and web-search tool schemas and fetchers. -
packages/agent/src/evaluations/personality-gate.tsexports the golden-set evaluation configuration. -
packages/agent/src/types/index.tsexports shared agent-side interfaces.
Runtime:
createMaxHeightAgent(options?: { displayAlias?: string })__test = { sessions, requestHandler, handleInvocations }
Session handling:
type SessionState = 'GREETING' | 'ACTIVE' | 'IDLE' | 'WINDING_DOWN' | 'ENDED'type EndReason = 'cap_reached' | 'user_left' | 'error' | 'manual'createSession(params: { actorId: string; greetingId: string }): SessioncheckSessionCaps(session: Session): SessionCapResultendSession(session: Session, reason: EndReason): SessiongetSessionState(session: Session): SessionState
Personality and stutter:
buildSystemPrompt(options?: SystemPromptOptions): stringcheckPersonality(input: PersonalityCheckInput): PersonalityCheckResultisStutter(text: string): booleancountStutters(text: string): numberinjectStutters(text: string, options: StutterOptions): StutterResult
Memory:
createMemoryAdapter(config: MemoryAdapterConfig): MemoryAdapterextractMemories(turns: TurnContent[], sessionId: string): ExtractionResultcreateAgentCoreMemoryClient(): AgentCoreMemoryClient-
handleForgetMe(adapter, actorId),handleListMemories(adapter, actorId),handleDeleteMemory(adapter, memoryRecordId)
Tools:
-
newsToolSchema,fetchNews(input, fetchFn?) -
weatherToolSchema,fetchWeather(input, fetchFn?) -
webSearchToolSchema,fetchWebSearch(input, { client, signal? })
Observability and evaluation:
TRACE_SPANS-
startSpan(name, attributes?),endSpan(name, additionalAttributes?),getActiveSpans(),setSpanEmitter(fn) -
RUBRIC_DIMENSIONS,PASS_CRITERIA,AUTO_FAIL_RULES,TEST_CATEGORY_REQUIREMENTS,goldenTestCases
index.ts runs initialize() before it listens (unless running under tests). Initialization constructs the agent and then drives a real ListAsyncInvokes round-trip through bedrock/warmup.ts, so the V2 snapshot captures a genuinely warmed client; until it resolves, GET /ping answers 503 {"status":"initializing"} and the listener is not accepting connections. A failure — or the 120 s deadline — rejects and exits rather than retrying. Once ready, GET /ping returns 200 {"status":"healthy"}. POST /invocations parses JSON containing optional message, displayAlias, sessionId, actorId, and greetingId.
For each invocation it:
- Starts a
session.cold_startspan. - Gets or creates an in-memory
Session. - Enforces 50 turns, 20,000 estimated/reported tokens, and 30 minutes.
- Creates a Strands agent with the current display alias.
- Invokes the model with the message or
Hello. - Extracts text blocks from the result.
- Updates turn/token counts.
- Writes Server-Sent Events shaped as
data: { type: 'text' | 'done' | 'error', ... }.
The agent factory uses a Bedrock model ID and maxTokens: 250, plus tools named get_news, get_weather, and web_search.
Despite the SSE content type, agent.invoke() completes before any text
frame is written; one complete-text frame and then done are sent. There are
no incremental model tokens and the first-token span ends after the full
invocation. #45 owns the streaming change, not this documentation update.
checkPersonality() and injectStutters() are not called on the response;
#42 owns the processing decision.
Source-AWS-AgentCore-Resilience-Testing describes a Python
chaos_plugins() integration controlled by FIS and SSM. The current
createMaxHeightAgent() registers its tools without a plugins option, and
the pinned Strands dependency is the TypeScript SDK; the blog's implementation
is not a drop-in for this runtime. No FIS/SSM fault-injection integration is
present in the inspected application code.
The pinned TypeScript SDK exposes McpClient and the experimental A2A
A2AAgent/A2AServer APIs, but createMaxHeightAgent() currently registers
only the three local tools newsTool, weatherTool, and webSearchTool.
There is no MCP or A2A integration in this runtime. The browser contract remains
the custom WebSocket frames in Contract-WebSocket-API; the current HTTP/SSE
agent path is not an AG-UI integration. None of these protocols, including
x402 payments, is adopted. See
Source-AWS-Open-Protocols-Strands-Agents-SDK for the protocol map and
version-specific qualifications.
Memory extraction is pattern-based. It can extract:
- display alias from assistant name questions followed by user answers.
- user facts.
- preferences.
- repeated or multi-turn topics.
- summaries after at least five user turns.
createMemoryAdapter() namespaces records as /max-height/{actorId}/, retrieves top 10 records, stores records with batch create, lists records, deletes one record, and wipes all records for an actor. Retrieval failures degrade to an empty list.
Spec 003 plans to replace this regex extraction with AgentCore's built-in strategies. Those strategies run inference cross-Region, so that plan conflicts with the in-Region rule. Storing records with batch create is, in AWS's terms, a self-managed strategy, which is one of the ways out. See Source-AgentCore-Long-Term-Memory.
Spec 003's plan read this runtime against the first deployment. These are findings about current code. The fixes are planned, not built. See Source-Spec-003.
-
D1: the model ID's Free-plan status (resolved for the first deployment).
index.ts:96uses theglobal.Claude Haiku 4.5 profile. AWS documents no global or geographic cross-Region inference on the Free plan, but spike S0 found the profile works in this account. The Free plan ends in December 2026 and rejects nothing (Decision-AWS-Account-Plan), and spec 003's T144 adopted this profile on 2026-11-02 as the cheaper of the two S0-proven profiles. What remains is cost and model lifecycle, plus an IAM policy that cannot be limited tous-west-2, which spec 003'sresearch.md§ Q2 records for T140. See Decision-LLM-Model-Selection. -
N1: usage is read from a field that does not exist.
extractUsage(index.ts:44-51) readsresult.usage, but Strands SDK 1.20.0 reports usage atresult.metrics.accumulatedUsage(telemetry/meter.d.ts:149). It returnsnullon every turn, so the token cap falls back to a character estimate, and a spend tally would have no real counts to add up. -
N2: there is no in-session history.
index.ts:182builds a freshAgentfor every request, so each turn starts with an empty conversation. -
N3:
handleDeleteMemory(adapter, memoryRecordId)has no ownership check. It takes noactorId, so any caller holding a record ID could delete another friend's memory. -
N5: long-term Memory records have no TTL.
eventExpiryDuration(7 to 365 days) retains raw short-term events only, and AWS's create-memory guide offers no expiry for extracted long-term records (re-read 2026-10-11). Keeping them within the constitution's 30-day window needs a scheduled pruner.
-
warmBedrockClient()must exercise the Bedrock client, not merely construct it. The SDK allocates credential resolution, endpoint-ruleset evaluation, SigV4 signing, protocol serde and the TLS connection pool lazily, so none of it lands in the V2 snapshot unless something drives a request. Until T154 the warm-up only constructed the agent, and every restored instance silently re-paid that setup — nothing failed, the readiness gate simply protected a warm-up that was not warm. - The warm-up probe is
ListAsyncInvokes(maxResults: 1), not an inference call. It reaches the samebedrock-runtimehost asConversebut runs no model and bills nothing, which is what makes it acceptable under Concept-Budget-Ceiling on a scale-to-zero service where container starts are frequent.CountTokensis not a substitute: it is free, but AWS documents Claude models offered only through cross-Region inference as unsupported forCountTokensonbedrock-runtime, andglobal.anthropic.claude-haiku-4-5-*is exactly such a model. - The probe means the runtime execution role needs
bedrock:ListAsyncInvokesin addition to the inference permissions. Without it the container fails to start — by design, since a warm-up failure must not be swallowed into a degraded snapshot every later instance inherits. -
createAgentCoreMemoryClient()intentionally throws:AgentCore Memory client not configured.... Production memory requires a real client or dependency injection; tests can mock it. - Memory modules are exported, but
index.tsdoes not retrieve memories, store extracted memories, or pass memory context intobuildSystemPrompt(). -
checkPersonality()andinjectStutters()exist but are not invoked inindex.ts; current runtime relies on the system prompt and tools rather than a post-generation gate. - The agent server streams SSE over HTTP, while the frontend transport currently expects WebSocket message frames.
-
Client disconnect cancels the invocation (since #43 / PR #46).
handleInvocationsruns each turn under anAbortControllerwired tores.on('close'), guarded byres.writableFinishedso a normal completion — which also emitsclose— is not mistaken for a disconnect. The signal reachesagent.invoke({ cancelSignal })and every tool callback forwardscontext.cancelSignalto its fetcher, which passes it tofetchasinit.signal. That last hop is required, not belt-and-braces: Strands cancellation is cooperative, so a tool that never observes the signal holds its outbound HTTP request open even after the model stops. On an aborted turn no error SSE is written (nobody is listening) andsession.cold_startis taggedcancelled=true. - An aborted turn leaves its
reply.first_tokenspan open, because the abort path skipsendSpan. This is inert:activeSpansis keyed by name so the next turn overwrites the entry, and nothing in production readsgetActiveSpans(). It stops being inert if the endpoint ever streams for real — see issue #45. -
Strands resolves a cancelled turn; it does not throw. An aborted
cancelSignalmakesagent.streamfinish withstopReason: 'cancelled'(Source-Strands-Harness-SDK-Docs already said so). Handling abort only incatchtherefore missed every cancel and every deadline: the turn settled at the flat estimate and refunded most of its reservation, sentdoneafter a deadline, and wrote the partial reply to long-term memory.serveInvocationnow throwsTurnCancelledErrorwhen the result'sstopReasoniscancelled, so the existing abort path settles at the full reservation, sends nodoneand writes no memory (tasks.md C37, C44). A test for this needs a stream that resolves on abort, as the SDK does; a mock that throws proves nothing. -
Pre-admission refusals consume no fixed-window allowance.
handleInvocationsnow runs breaker, admission and counted-session/allowlist checks beforeconsumeRate(), and memory actions use the same order after their allowlist check. A tripped breaker, busy/friend-lease conflict, session cap or allowlist refusal neither consumes a rate window nor starts model/memory work. A rate-window refusal settles the just-created lease at 0 µUSD.memory.forgetremains outside the action rate counter. -
A turn deadline is retryable, not a permanent session sign-off. Memory retrieval or model/voice cancellation caused by the configured deadline emits
turn_deadline, leaves the counted session active and gives the browser no terminalENDEDstate. The browser renders the supplied in-character reply and permits another send. -
Conservative settlement starts at the reservation. After admission,
settleMicroUsdbegins atlease.reservedMicroUsd; pre-model refusals set it to zero, while missing usage or cancellation retain the full reservation. Verified model usage replaces it throughcomputeTurnUsage; memory retrieval no longer lowers it before the model reports usage. -
Web-search claims persist before outbound execution.
ControlTable.claimWebSearchatomically incrementsSESSION#<sub>.webSearchesfor the exact counted-session ID and expected snapshot at the configured allowance.searchForTurnawaits that claim, so cancellation or failure cannot leave the search uncounted.recordTurnreceives the absolute persisted count and does not addsearchTurn.sentagain.putSessionincludeswebSearchesin its exact-snapshot condition. -
An error after the response has started must end it, not answer it.
serveInvocation'sfinallycloses the SSE stream, which sends a 200.requestHandler's.catchused to callres.writeHead(500)after that, which threwERR_HTTP_HEADERS_SENTinside an unawaited promise and exited the process, leaking admission leases that never expire.answerInvocationFailureends a response that has started and writes the 500 only when nothing was sent. Process-levelunhandledRejectionhandlers are deliberately absent because they would swallow errors, and #85 owns theSIGTERMdrain. Reproducing the crash needs a realhttp.createServerand a socket destroyed mid-upload (tests/index.invocationFailure.test.ts). -
boundModelInputmust measure and cut the complete model request on a turn boundary. Bedrock Converse rejects a conversation that opens with an assistant message or holds atoolResultwhosetoolUseis gone. The complete byte check includes the system prompt, registered tool specifications and messages, not messages alone. The cut therefore falls only on a genuine user message (one with notoolResultblock), never drops the turn in progress, tool calls included, and cancels the model call if static prompt/tools or the current turn still exceedMODEL_INPUT_MAX_BYTES. The rule comes from those API constraints and unit tests; it has not been run against live Bedrock (tasks.md T179). The hook trims the SDK's message array in place withsplice, because the SDK has no per-call message override. -
printer: falseincreateMaxHeightAgent()is load-bearing, not cosmetic. The SDK's default printer streams the whole conversation to the console; left on in a server runtime it duplicates every token into CloudWatch logs, inflating log volume and putting guest conversation text somewhere it was never meant to go. -
Prompt caching is available but its saving is unproven.
BedrockModelacceptscacheConfig: { strategy: 'auto' }, or{ messagesTTL: false }to cache only the system prompt and tool definitions, but neither is configured. A cache checkpoint needs 4,096 tokens, more than the ~2,990-token system prompt alone; prompt plus tool definitions has not been measured. #49 owns that check. See Concept-Budget-Ceiling and Source-Strands-Harness-SDK-Docs. - The TypeScript SDK applies a default
requestTimeoutof 120 000 ms to the Bedrock client because the AWS SDK's own default is0(disabled). It measures stream inactivity, not total duration, so a long-thinking model or a quiet tool call can trip it withStream timed out because of no activity. - Native invocation limits (
limits: { turns, outputTokens, totalTokens }onagent.invoke) exist but reset on every invocation, so they cannot implement our per-session caps. They are an inner guard, not a replacement. (Until 2026-10-01 this page named themmaxTurns/maxTotalTokens/maxOutputTokens, which do not exist in 1.19.0.) - Even the 50-turn/20k-token/30-minute application limits only bind a cooperative client:
/invocationstrusts a caller-suppliedsessionId, and omitting it creates a fresh budget each turn. The endpoint is not authenticated. #55 owns a binding cap; see Concept-Budget-Ceiling. -
webSearchTool.tscalls AgentCore'sInvokeWebSearchthrough an injectedBedrockAgentCoreClient, signed with the runtime role, so it needs no API key and no SSM parameter. It replaced Google Custom Search on 2026-11-16 because Google's API is closed to new customers and ends 2027-01-01. The first 5,000 queries a month are free, then $7.00/1,000; the hard stop denies the action.searchForTurnnow awaits the persisted session claim before calling the tool, and turn-localsentis for metering/source reporting rather than a second increment at final session write. Quality is untested. See Decision-Web-Search-Provider and Source-AgentCore-Web-Search-Tool. - Tool callbacks execute with the runtime process's permissions. This runtime uses custom news, weather, and web-search callbacks that make outbound HTTP requests and read API-key variables from the environment; it does not register the quickstart's file editor or shell tools. Audit a new tool's filesystem, network, and shell behavior and keep credentials and IAM scope tight. See Concept-Credential-Hygiene and Source-AWS-Prescriptive-Guidance-Strands-Agents.
- Concept-Cloud-Only-Inference
- Concept-Budget-Ceiling
- Concept-Personality-Gate
- Concept-IP-And-Legal-Posture
- Concept-Supply-Chain-Discipline
- Concept-Graceful-Degradation
- Concept-Observability
- Concept-Testing-And-TDD
- Concept-Credential-Hygiene
Editing in the browser? Wiki edits are live and bypass wiki:lint. Read
Guide-Wiki-Contributing first.