> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeroruntime.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat & Context

> JavaScript API reference for Chat & Context.

## ChatContext

Create a ChatContext, optionally seeded with messages. Also exposes
`ChatContext.empty()`, `ChatContext.fromContextMessages(...)`, and `ChatContext.fromDict(...)`.

### Constructor

```typescript theme={null}
new ChatContext(initialMessages?: ChatMessage[])
```

<ParamField path="initialMessages" type="ChatMessage[]" />

### addAttributedMessage

```typescript theme={null}
addAttributedMessage(role: ChatRole, content: string, agentId: string, messageId?: string, images?: ImageContent[]): ChatMessage
```

Like ChatContext.addMessage but tags the message with an authoring `agentId`.

<ParamField path="role" type="ChatRole" required />

<ParamField path="content" type="string" required />

<ParamField path="agentId" type="string" required />

<ParamField path="messageId" type="string" />

<ParamField path="images" type="ImageContent[]" />

<ResponseField name="returns" type="ChatMessage" />

### addFunctionCall

```typescript theme={null}
addFunctionCall(name: string, args: string, callId?: string, messageId?: string, agentId?: string): ChatMessage
```

Record an assistant tool call as an ASSISTANT message carrying a FunctionCall.

<ParamField path="name" type="string" required />

<ParamField path="args" type="string" required />

<ParamField path="callId" type="string" />

<ParamField path="messageId" type="string" />

<ParamField path="agentId" type="string" />

<ResponseField name="returns" type="ChatMessage" />

### addFunctionOutput

```typescript theme={null}
addFunctionOutput(name: string, output: string, callId: string, isError?: boolean, messageId?: string, agentId?: string): ChatMessage
```

Record a tool result as a TOOL-role message linked to its `callId`.

<ParamField path="name" type="string" required />

<ParamField path="output" type="string" required />

<ParamField path="callId" type="string" required />

<ParamField path="isError" type="boolean" />

<ParamField path="messageId" type="string" />

<ParamField path="agentId" type="string" />

<ResponseField name="returns" type="ChatMessage" />

### addHandoff

```typescript theme={null}
addHandoff(toAgent: string, fromAgent?: string, reason?: string): AgentHandoff
```

Record a handoff to another agent and return it.

<ParamField path="toAgent" type="string" required />

<ParamField path="fromAgent" type="string" />

<ParamField path="reason" type="string" />

<ResponseField name="returns" type="AgentHandoff" />

### addMessage

```typescript theme={null}
addMessage(role: ChatRole, content: string, messageId?: string, images?: ImageContent[], createdAt?: number | null, replace?: boolean): ChatMessage
```

Append a message and return it. Generates a `messageId` if none is given.
With `replace=true` and `role=SYSTEM`, replaces the existing system message in
place instead of appending a duplicate.

<ParamField path="role" type="ChatRole" required />

<ParamField path="content" type="string" required />

<ParamField path="messageId" type="string" />

<ParamField path="images" type="ImageContent[]" />

<ParamField path="createdAt" type="number | null" />

<ParamField path="replace" type="boolean" />

<ResponseField name="returns" type="ChatMessage" />

### copy

```typescript theme={null}
copy(opts?: { excludeSystemMessages?: boolean; excludeEmptyMessages?: boolean }): ChatContext
```

Return a deep, independent copy of this context.

<ParamField path="opts" type="{ excludeSystemMessages?: boolean; excludeEmptyMessages?: boolean }" />

<ResponseField name="returns" type="ChatContext" />

### estimatedTokens

```typescript theme={null}
estimatedTokens(): number
```

Rough token estimate (\~2 tokens per word).

<ResponseField name="returns" type="number" />

### handoffs

```typescript theme={null}
handoffs(): AgentHandoff[]
```

Return a copy of the recorded handoffs.

<ResponseField name="returns" type="AgentHandoff[]" />

### lastHandoff

```typescript theme={null}
lastHandoff(): AgentHandoff | null
```

The most recent handoff, or `null` if none.

<ResponseField name="returns" type="AgentHandoff | null" />

### merge

```typescript theme={null}
merge(other: ChatContext | ChatMessage[]): ChatContext
```

Append another context's messages in place, de-duped by `messageId`; returns this context.

<ParamField path="other" type="ChatContext | ChatMessage[]" required />

<ResponseField name="returns" type="ChatContext" />

### messages

```typescript theme={null}
messages(): ChatMessage[]
```

Return a shallow copy of the messages.

<ResponseField name="returns" type="ChatMessage[]" />

### toAnthropicMessages

```typescript theme={null}
toAnthropicMessages(): { messages: Array<Record<string, any>>; system: string | null }
```

Render as Anthropic Messages. The system text is returned separately in `system`
(Anthropic takes it as a top-level field, not as a message).

<ResponseField name="returns" type="{ messages: Array<Record<string, any>>; system: string | null }" />

### toContextMessages

```typescript theme={null}
toContextMessages(): ContextMessageProto[]
```

Serialize the conversation context for sending to Zero Runtime.

<ResponseField name="returns" type="ContextMessageProto[]" />

### toDict

```typescript theme={null}
toDict(): { items: ContextMessageProto[]; handoffs: Array<Record<string, string>> }
```

Serialize the whole context (messages + handoffs) to a plain object.

<ResponseField name="returns" type="{ items: ContextMessageProto[]; handoffs: Array<Record<string, string>> }" />

### toGoogleContents

```typescript theme={null}
toGoogleContents(): { contents: Array<Record<string, any>>; systemInstruction: string | null }
```

Render as Google Gemini `contents`, with the system text returned in `systemInstruction`.

<ResponseField name="returns" type="{ contents: Array<Record<string, any>>; systemInstruction: string | null }" />

### toOpenaiMessages

```typescript theme={null}
toOpenaiMessages(opts?: { reasoningModel?: boolean }): Array<Record<string, any>>
```

Export to OpenAI chat messages (text, image parts, tool calls, tool results).

<ParamField path="opts" type="{ reasoningModel?: boolean }" />

<ResponseField name="returns" type="Array<Record<string, any>>" />

### truncate

```typescript theme={null}
truncate(opts?: { maxItems?: number; maxTokens?: number }): ChatContext
```

Return a new context trimmed to the most recent messages.

<ParamField path="opts" type="{ maxItems?: number; maxTokens?: number }" />

<ResponseField name="returns" type="ChatContext" />

### turnCount

```typescript theme={null}
turnCount(): number
```

Number of user turns in the context.

<ResponseField name="returns" type="number" />

***

## ChatMessage

Create a ChatMessage.

### Constructor

```typescript theme={null}
new ChatMessage(opts: ChatMessageOptions)
```

<ParamField path="role" type="ChatRole">
  Author role. Defaults to ChatRole.USER.
</ParamField>

<ParamField path="content" type="string">
  Message text. Defaults to `''`.
</ParamField>

<ParamField path="messageId" type="string">
  Stable message id. Defaults to `''`.
</ParamField>

<ParamField path="toolCalls" type="FunctionCall[]">
  Tool calls requested in this message. Defaults to `[]`.
</ParamField>

<ParamField path="toolCallId" type="string">
  Id of the tool call this message responds to. Defaults to `''`.
</ParamField>

<ParamField path="images" type="ImageContent[]">
  Attached images. Defaults to `[]`.
</ParamField>

<ParamField path="agentId" type="string">
  Id of the agent that authored the message (multi-agent attribution). Defaults to `''`.
</ParamField>

<ParamField path="createdAt" type="number | null">
  Creation timestamp (epoch seconds), or `null` when unset. Defaults to `null`.
</ParamField>

***

## ChatContent

Create a ChatContent text block.

### Constructor

```typescript theme={null}
new ChatContent(opts: ChatContentOptions)
```

<ParamField path="type" type="string">
  Content kind. Defaults to `'text'`.
</ParamField>

<ParamField path="text" type="string">
  The text body. Defaults to `''`.
</ParamField>

***

## ChatRole

Author role of a ChatMessage.

```typescript theme={null}
enum ChatRole {
  SYSTEM = 'system',
  DEVELOPER = 'developer',
  USER = 'user',
  ASSISTANT = 'assistant',
  TOOL = 'tool',
}
```

***

## FunctionCall

Create a FunctionCall.

### Constructor

```typescript theme={null}
new FunctionCall(opts: FunctionCallOptions)
```

<ParamField path="name" type="string">
  Name of the tool being called. Defaults to `''`.
</ParamField>

<ParamField path="arguments" type="string">
  Call arguments as a JSON string. Defaults to `''`.
</ParamField>

<ParamField path="callId" type="string">
  Unique id correlating this call with its output. Defaults to `''`.
</ParamField>

***

## FunctionCallOutput

Create a FunctionCallOutput.

### Constructor

```typescript theme={null}
new FunctionCallOutput(opts: FunctionCallOutputOptions)
```

<ParamField path="name" type="string">
  Name of the tool that produced this output. Defaults to `''`.
</ParamField>

<ParamField path="output" type="string">
  The tool's result, serialized as a string. Defaults to `''`.
</ParamField>

<ParamField path="callId" type="string">
  Id matching the originating FunctionCall. Defaults to `''`.
</ParamField>

<ParamField path="isError" type="boolean">
  Whether the output represents an error. Defaults to `false`.
</ParamField>

***

## ImageContent

Create an ImageContent, or one of its helper constructors:
`fromUrl`, `fromDataUrl`, `fromBase64`, `fromBytes`, `fromFile`, `fromFrame`.
All accept a `detail` hint (`'auto'` | `'low'` | `'high'`, default `'auto'`).

### Constructor

```typescript theme={null}
new ImageContent(opts: ImageContentOptions)
```

<ParamField path="type" type="string">
  Content kind. Defaults to `'image'`.
</ParamField>

<ParamField path="url" type="string">
  Image URL or `data:` URL. Defaults to `''`.
</ParamField>

<ParamField path="detail" type="string">
  Vision detail hint: `'auto'`, `'low'`, or `'high'`. Defaults to `'auto'`.
</ParamField>

***

## ContextWindow

Configure how conversation history is bounded and trimmed. See ContextWindowOptions.

### Constructor

```typescript theme={null}
new ContextWindow(opts: ContextWindowOptions)
```

<ParamField path="maxTokens" type="number | null">
  Maximum tokens of conversation history to keep. Defaults to `null` (no token limit).
</ParamField>

<ParamField path="maxContextItems" type="number | null">
  Maximum number of history items (messages/turns) to keep. Defaults to `null` (no item limit).
</ParamField>

<ParamField path="keepRecentTurns" type="number">
  Number of most recent turns always preserved verbatim when trimming. Defaults to `3`.
</ParamField>

<ParamField path="maxToolCallsPerTurn" type="number">
  Maximum tool calls allowed within a single turn. Defaults to `10`.
</ParamField>

<ParamField path="summaryLlm" type="LLM | null">
  Optional LLM used to summarize older history when trimming. Defaults to `null` (no summarization).
</ParamField>

***

## EncodeOptions

Create an EncodeOptions. Pass `{ resizeOptions: null }` to preserve the
source dimensions; omitting it resizes to 1024x1024.

### Constructor

```typescript theme={null}
new EncodeOptions(init: EncodeOptionsInit)
```

<ParamField path="format" type="ImageFormat">
  Output format. Default: `'JPEG'`.
</ParamField>

<ParamField path="resizeOptions" type="ResizeOptions | null">
  Target dimensions, or `null` to keep the source size. Default: 1024x1024.
</ParamField>

<ParamField path="quality" type="number">
  JPEG quality, 0-100 (ignored for PNG). Default: `75`.
</ParamField>

***

## ResizeOptions

Create a ResizeOptions from width and height in pixels.

### Constructor

```typescript theme={null}
new ResizeOptions(width: number, height: number)
```

<ParamField path="width" type="number" required />

<ParamField path="height" type="number" required />

***

## encode

```typescript theme={null}
function encode(frame: ImageFrame, options?: EncodeOptions | null): Promise<Buffer>
```

Encode an image frame to JPEG or PNG bytes, optionally resizing. Requires the
optional `sharp` dependency. Uses EncodeOptions defaults when `options`
is omitted or `null`.

<ParamField path="frame" type="ImageFrame" required />

<ParamField path="options" type="EncodeOptions | null" />

<ResponseField name="returns" type="Promise<Buffer>" />

***

## coerceImageToJpegBytes

```typescript theme={null}
function coerceImageToJpegBytes(frame: ImageFrame, opts: CoerceImageOptions = {}): Promise<Buffer>
```

Return JPEG-ready bytes for an image frame, re-encoding only when necessary.

If `frame` is already encoded bytes (`Buffer`/`Uint8Array`/`ArrayBuffer`), it is
returned as-is (assumed to be a valid JPEG/PNG) and `sharp` is not required. Otherwise
the frame is encoded with `options` (or DEFAULT\_REALTIME\_ENCODE\_OPTIONS).

<ParamField path="frame" type="ImageFrame" required />

<ParamField path="opts" type="CoerceImageOptions" />

<ResponseField name="returns" type="Promise<Buffer>" />

***

## DEFAULT\_REALTIME\_ENCODE\_OPTIONS

Encode options applied by coerceImageToJpegBytes when a frame must be re-encoded.

```typescript theme={null}
const DEFAULT_REALTIME_ENCODE_OPTIONS = EncodeOptions({ format: 'JPEG', resizeOptions: ResizeOptions(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT), quality: DEFAULT_IMAGE_QUALITY, })
```
