Repository navigation
Component Agent Runtime
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, fetchFn?)
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.
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'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 cannot ship on the Free plan.
index.ts:96uses theglobal.Claude Haiku 4.5 profile. AWS documents no global or geographic cross-Region inference on the Free plan. Spike S0 found the profile works in this account today, but the builder chose not to rely on it. 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. -
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 Google Custom Search withSEARCH_API_KEYandSEARCH_ENGINE_ID. AgentCore now offers a managed, MCP-native alternative whose queries never leave AWS — but at $7.00/1,000 queries it is far more expensive than the CSE free tier. See 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.