Skip to content

Contract WebSocket API

Reese Hodge edited this page Sep 27, 2026 · 5 revisions

Contract: WebSocket API

This page mirrors specs/001-max-height-ai-character/contracts/websocket-api.md. It defines the transport frames between the browser and backend; the application turn semantics live in Contract-Message-Protocol.

Connection

Field Contract
Protocol wss:// in production; UTF-8 JSON text frames only
Auth SigV4 presigned URL from Cognito guest credentials
URL expiry 5 minutes; refresh before expiry
Endpoint shape API Gateway WebSocket → Lambda → AgentCore Runtime
Subprotocol none
Max message size 32 KB
Server heartbeat ping every 30 seconds; client replies pong

Lifecycle: get guest identity → presign URL → open socket → receive connection_ack → exchange frames → send or receive session_end → close code 1000.

Client to server frames

type ClientMessage =
  | { type: 'session_start'; payload: SessionStartPayload }
  | { type: 'user_message'; payload: UserMessagePayload }
  | { type: 'interrupt'; payload: InterruptPayload }
  | { type: 'session_resume'; payload: SessionResumePayload }
  | { type: 'session_end'; payload: SessionEndPayload };

interface SessionStartPayload {
  actorId: string;              // UUID v4, persistent visitor ID
  displayAlias: string | null;  // optional visitor alias
  greetingId: string;           // e.g. greeting-001
  clientTimestamp: string;      // ISO-8601
}

interface UserMessagePayload {
  text: string;                 // 1-2000 chars by contract
  turnIndex: number;
  inputMethod: 'text' | 'voice';
}

interface InterruptPayload {
  turnIndex: number;
}

interface SessionResumePayload {
  sessionId: string;            // UUID v4 by contract
  actorId: string;              // UUID v4
  lastReceivedTurnIndex: number;
}

interface SessionEndPayload {
  reason: 'user_exit' | 'cap_reached' | 'timeout';
}

Server to client frames

type ServerMessage =
  | { type: 'connection_ack'; payload: ConnectionAckPayload }
  | { type: 'agent_token'; payload: AgentTokenPayload }
  | { type: 'agent_turn_complete'; payload: AgentTurnCompletePayload }
  | { type: 'session_state_change'; payload: SessionStateChangePayload }
  | { type: 'error'; payload: ErrorPayload };

interface ConnectionAckPayload {
  agentCoreSessionId: string;
}

interface AgentTokenPayload {
  turnIndex: number;
  token: string;                // one or more chars
  isFinal: boolean;
}

interface AgentTurnCompletePayload {
  turnIndex: number;
  fullText: string;
  tokenCount: number;           // tokens used this turn
  sessionTokenTotal: number;
  sessionTurnTotal: number;
}

type SessionState =
  | 'INITIALIZING'
  | 'GREETING'
  | 'ACTIVE'
  | 'ENDED'
  | 'BUDGET_CAPPED'
  | 'RATE_LIMITED'
  | 'SIGNAL_LOST'
  | 'ERROR';

interface SessionStateChangePayload {
  previousState: SessionState;
  newState: SessionState;
  reason: string;
  inCharacterMessage: string | null;
}

interface ErrorPayload {
  code: 'RATE_LIMITED' | 'INPUT_TOO_LONG' | 'MODERATION_BLOCKED' | 'INTERNAL';
  message: string;
  retryable: boolean;
}

Rate limits and close codes

Limit Value Breach behavior
Messages per hour 60 error with RATE_LIMITED, then session_state_change
Messages per day 500 same
Message length 2,000 chars error with INPUT_TOO_LONG
Concurrent sessions per visitor 1 new session_start closes prior session
Close code Meaning
1000 normal closure
1001 client going away
4000 session cap reached
4001 budget hard-stop
4002 rate limit exceeded
4008 presigned URL expired
4500 internal server error

Native AgentCore WebSocket — an alternative, not a plan

AgentCore Runtime now supports WebSocket natively, which would let the browser reach the runtime directly and delete the API Gateway and Lambda hop from the table above. Nothing has been decided or deployed, and adopting it would trip the Spec Kit hybrid rule, so it needs a spec rather than a pull request.

Three parts of the contract above conflict with the platform and would have to change together:

Contract says Platform does
Subprotocol: none Browser OAuth carries the token in Sec-WebSocket-Protocol; no other subprotocol is supported
Custom close codes 4000–4500 Emits 1000/1001/1008/1009/1011; our semantics would move into application frames
Ping every 30 seconds Any activity — including ping/pong — resets the 15-minute idle timer, so the session never scales to zero

The 32 KB maximum message size already matches. Full detail, including the WebRTC option and its budget implications, is on Source-AgentCore-Bidirectional-Streaming.

Verified implementation status

packages/frontend/src/types/messages.ts matches the contract frame names and core payload fields. websocketManager.ts enforces 32 KB serialization, parses known server frame types, maps close codes, and has session_resume payload construction. useWebSocket.ts handles ack, tokens, full text, counters, and state changes, but reconnect logic does not yet send session_resume.

packages/infra/lib/handlers/websocket-handler.ts is not contract-complete: it uses placeholder payloads, a 500-character user-message limit, and non-contract error codes such as INVALID_JSON. Treat the source contract above as authoritative until the handler is brought into parity. See Feature-Max-Height-Core for broader current-state gaps.

Clone this wiki locally