Skip to content

Component Agent Runtime

Reese Hodge edited this page Nov 25, 2026 · 20 revisions

Component Agent Runtime

Branch review qualification (2026-11-15)

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.

Files

  • packages/agent/src/index.ts creates the Strands agent and HTTP server.
  • packages/agent/src/bedrock/warmup.ts drives the startup probe that warms the Bedrock runtime client.
  • packages/agent/src/handlers/sessionManager.ts creates sessions and enforces caps.
  • packages/agent/src/handlers/reEngagement.ts schedules idle nudges.
  • packages/agent/src/handlers/personalityCheck.ts checks response text for voice and banned patterns.
  • packages/agent/src/handlers/observability.ts emits trace spans as JSON.
  • packages/agent/src/memory/* defines memory extraction, adapter, handlers, and a client abstraction.
  • packages/agent/src/personality/systemPrompt.ts builds the system prompt.
  • packages/agent/src/personality/stutterInjection.ts detects/injects stutters.
  • packages/agent/src/tools/* defines weather, news, and web-search tool schemas and fetchers.
  • packages/agent/src/evaluations/personality-gate.ts exports the golden-set evaluation configuration.
  • packages/agent/src/types/index.ts exports shared agent-side interfaces.

Exported functions and types

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 }): Session
  • checkSessionCaps(session: Session): SessionCapResult
  • endSession(session: Session, reason: EndReason): Session
  • getSessionState(session: Session): SessionState

Personality and stutter:

  • buildSystemPrompt(options?: SystemPromptOptions): string
  • checkPersonality(input: PersonalityCheckInput): PersonalityCheckResult
  • isStutter(text: string): boolean
  • countStutters(text: string): number
  • injectStutters(text: string, options: StutterOptions): StutterResult

Memory:

  • createMemoryAdapter(config: MemoryAdapterConfig): MemoryAdapter
  • extractMemories(turns: TurnContent[], sessionId: string): ExtractionResult
  • createAgentCoreMemoryClient(): 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

Runtime path

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:

  1. Starts a session.cold_start span.
  2. Gets or creates an in-memory Session.
  3. Enforces 50 turns, 20,000 estimated/reported tokens, and 30 minutes.
  4. Creates a Strands agent with the current display alias.
  5. Invokes the model with the message or Hello.
  6. Extracts text blocks from the result.
  7. Updates turn/token counts.
  8. 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.

Resilience-testing reference

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.

Protocol integration status

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 behavior

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.

What spec 003's plan found

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:96 uses the global. 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 to us-west-2, which spec 003's research.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) reads result.usage, but Strands SDK 1.20.0 reports usage at result.metrics.accumulatedUsage (telemetry/meter.d.ts:149). It returns null on 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:182 builds a fresh Agent for every request, so each turn starts with an empty conversation.
  • N3: handleDeleteMemory(adapter, memoryRecordId) has no ownership check. It takes no actorId, 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.

Gotchas

  • 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 same bedrock-runtime host as Converse but 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. CountTokens is not a substitute: it is free, but AWS documents Claude models offered only through cross-Region inference as unsupported for CountTokens on bedrock-runtime, and global.anthropic.claude-haiku-4-5-* is exactly such a model.
  • The probe means the runtime execution role needs bedrock:ListAsyncInvokes in 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.ts does not retrieve memories, store extracted memories, or pass memory context into buildSystemPrompt().
  • checkPersonality() and injectStutters() exist but are not invoked in index.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). handleInvocations runs each turn under an AbortController wired to res.on('close'), guarded by res.writableFinished so a normal completion — which also emits close — is not mistaken for a disconnect. The signal reaches agent.invoke({ cancelSignal }) and every tool callback forwards context.cancelSignal to its fetcher, which passes it to fetch as init.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) and session.cold_start is tagged cancelled=true.
  • An aborted turn leaves its reply.first_token span open, because the abort path skips endSpan. This is inert: activeSpans is keyed by name so the next turn overwrites the entry, and nothing in production reads getActiveSpans(). 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 cancelSignal makes agent.stream finish with stopReason: 'cancelled' (Source-Strands-Harness-SDK-Docs already said so). Handling abort only in catch therefore missed every cancel and every deadline: the turn settled at the flat estimate and refunded most of its reservation, sent done after a deadline, and wrote the partial reply to long-term memory. serveInvocation now throws TurnCancelledError when the result's stopReason is cancelled, so the existing abort path settles at the full reservation, sends no done and 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. handleInvocations now runs breaker, admission and counted-session/allowlist checks before consumeRate(), 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.forget remains 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 terminal ENDED state. The browser renders the supplied in-character reply and permits another send.
  • Conservative settlement starts at the reservation. After admission, settleMicroUsd begins at lease.reservedMicroUsd; pre-model refusals set it to zero, while missing usage or cancellation retain the full reservation. Verified model usage replaces it through computeTurnUsage; memory retrieval no longer lowers it before the model reports usage.
  • Web-search claims persist before outbound execution. ControlTable.claimWebSearch atomically increments SESSION#<sub>.webSearches for the exact counted-session ID and expected snapshot at the configured allowance. searchForTurn awaits that claim, so cancellation or failure cannot leave the search uncounted. recordTurn receives the absolute persisted count and does not add searchTurn.sent again. putSession includes webSearches in its exact-snapshot condition.
  • An error after the response has started must end it, not answer it. serveInvocation's finally closes the SSE stream, which sends a 200. requestHandler's .catch used to call res.writeHead(500) after that, which threw ERR_HTTP_HEADERS_SENT inside an unawaited promise and exited the process, leaking admission leases that never expire. answerInvocationFailure ends a response that has started and writes the 500 only when nothing was sent. Process-level unhandledRejection handlers are deliberately absent because they would swallow errors, and #85 owns the SIGTERM drain. Reproducing the crash needs a real http.createServer and a socket destroyed mid-upload (tests/index.invocationFailure.test.ts).
  • boundModelInput must measure and cut the complete model request on a turn boundary. Bedrock Converse rejects a conversation that opens with an assistant message or holds a toolResult whose toolUse is 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 no toolResult block), never drops the turn in progress, tool calls included, and cancels the model call if static prompt/tools or the current turn still exceed MODEL_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 with splice, because the SDK has no per-call message override.
  • printer: false in createMaxHeightAgent() 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. BedrockModel accepts cacheConfig: { 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 requestTimeout of 120 000 ms to the Bedrock client because the AWS SDK's own default is 0 (disabled). It measures stream inactivity, not total duration, so a long-thinking model or a quiet tool call can trip it with Stream timed out because of no activity.
  • Native invocation limits (limits: { turns, outputTokens, totalTokens } on agent.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 them maxTurns / 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: /invocations trusts a caller-supplied sessionId, and omitting it creates a fresh budget each turn. The endpoint is not authenticated. #55 owns a binding cap; see Concept-Budget-Ceiling.
  • webSearchTool.ts calls AgentCore's InvokeWebSearch through an injected BedrockAgentCoreClient, 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. searchForTurn now awaits the persisted session claim before calling the tool, and turn-local sent is 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.

Clone this wiki locally