serve

package
v1.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package serve provides a WebSocket client SDK for the chat-agent serve mode. It encapsulates the full WebSocket protocol: connection, chat selection, streaming responses, tool calls, thinking indicators, approval requests, and more.

Index

Constants

View Source
const (
	DefaultReconnectDelay = 2 * time.Second
	DefaultMaxReconnect   = 5
	DefaultWriteTimeout   = 5 * time.Second
	DefaultReadTimeout    = 10 * time.Second
)

Default values for client configuration.

View Source
const (
	MsgSessionInit     = "session_init"
	MsgChatSelected    = "chat_selected"
	MsgChunk           = "chunk"
	MsgToolCall        = "tool_call"
	MsgThinking        = "thinking"
	MsgComplete        = "complete"
	MsgError           = "error"
	MsgApprovalRequest = "approval_request"
	MsgMessageCount    = "message_count"
	MsgStopped         = "stopped"
	MsgKept            = "kept"
	MsgCleared         = "cleared"
)

Message types sent from server to client.

View Source
const (
	CmdSelectChat       = "select_chat"
	CmdChat             = "chat"
	CmdRegenerate       = "regenerate"
	CmdStop             = "stop"
	CmdClear            = "clear"
	CmdKeep             = "keep"
	CmdApprovalResponse = "approval_response"
	CmdDeselectChat     = "deselect_chat"
)

Message types sent from client to server.

Variables

This section is empty.

Functions

func ConcatToolArguments

func ConcatToolArguments(existing, delta string) string

ConcatToolArguments accumulates incremental tool call arguments. When streaming=true, each SendToolCall carries a delta of the arguments JSON string. Callers should use this function to build the complete arguments string by concatenating successive deltas for the same tool call.

Types

type ApprovalItem

type ApprovalItem struct {
	Approved bool   `json:"approved"`
	Reason   string `json:"reason,omitempty"`
}

ApprovalItem represents a single approval decision.

type ApprovalRequestPayload

type ApprovalRequestPayload struct {
	ApprovalID string                  `json:"approval_id"`
	Targets    []ApprovalTargetPayload `json:"targets"`
}

ApprovalRequestPayload is sent when tool execution requires user approval.

type ApprovalResponsePayload

type ApprovalResponsePayload struct {
	ApprovalID string                  `json:"approval_id"`
	Results    map[string]ApprovalItem `json:"results"`
}

ApprovalResponsePayload is the payload for approval_response command.

type ApprovalTargetPayload

type ApprovalTargetPayload struct {
	ID      string `json:"id"`
	Tool    string `json:"tool"`
	Details string `json:"details"`
}

ApprovalTargetPayload describes a single target requiring approval.

type ChatRequest

type ChatRequest struct {
	ChatName string        `json:"chat_name,omitempty"`
	Message  string        `json:"message,omitempty"`
	Files    []FilePayload `json:"files,omitempty"`
}

ChatRequest is the payload for select_chat and chat commands.

type ChatSelectedPayload

type ChatSelectedPayload struct {
	SessionID    string `json:"session_id"`
	ChatName     string `json:"chat_name"`
	Description  string `json:"description"`
	Message      string `json:"message"`
	MessageCount int    `json:"message_count"`
}

ChatSelectedPayload is received after a chat is successfully selected.

type ChunkPayload

type ChunkPayload struct {
	Content     string `json:"content"`
	First       bool   `json:"first"`
	Last        bool   `json:"last"`
	ContentType string `json:"content_type"` // "response" or "thinking"
}

ChunkPayload represents a streaming content chunk.

type ClearedPayload

type ClearedPayload struct {
	ChatName     string `json:"chat_name,omitempty"`
	Message      string `json:"message"`
	MessageCount int    `json:"message_count"`
}

ClearedPayload is sent after the conversation context is cleared.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a WebSocket client SDK for the chat-agent serve mode. It manages the connection lifecycle and message passing.

func NewClient

func NewClient(serverURL string, opts ...ClientOption) *Client

NewClient creates a new WebSocket client for the given server URL.

The serverURL should be a full WebSocket URL, e.g. "ws://localhost:8080/ws". Options can be used to configure authentication, reconnection, timeouts, etc.

Example:

client := serve.NewClient("ws://localhost:8080/ws",
    serve.WithBasicAuth("user", "pass"),
    serve.WithReconnect(2*time.Second, 5),
)
client.SetEventHandler(myHandler)
if err := client.Connect(); err != nil {
    log.Fatal(err)
}
defer client.Close()

func (*Client) Clear

func (c *Client) Clear() error

Clear clears the conversation context for the current chat.

func (*Client) Close

func (c *Client) Close() error

Close gracefully closes the WebSocket connection and stops all goroutines.

func (*Client) Connect

func (c *Client) Connect() error

Connect establishes a WebSocket connection to the server. It blocks until the connection is established or an error occurs.

func (*Client) DeselectChat

func (c *Client) DeselectChat() error

DeselectChat deselects the current chat and returns to the selection page.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*Client) Keep

func (c *Client) Keep() error

Keep triggers the keep hook for the current session.

func (*Client) Regenerate

func (c *Client) Regenerate() error

Regenerate requests regeneration of the last response.

func (*Client) SelectChat

func (c *Client) SelectChat(chatName string) error

SelectChat selects a chat by name. Must be called before sending messages.

func (*Client) SendApprovalResponse

func (c *Client) SendApprovalResponse(approvalID string, results map[string]ApprovalItem) error

SendApprovalResponse sends the user's approval decision back to the server.

func (*Client) SendMessage

func (c *Client) SendMessage(text string) error

SendMessage sends a text message to the currently selected chat.

func (*Client) SendMessageWithFiles

func (c *Client) SendMessageWithFiles(text string, files []FilePayload) error

SendMessageWithFiles sends a text message with file attachments.

func (*Client) SessionID

func (c *Client) SessionID() string

SessionID returns the current session ID (available after session_init).

func (*Client) SetEventHandler

func (c *Client) SetEventHandler(handler EventHandler)

SetEventHandler registers the handler to receive server events. Must be called before Connect.

func (*Client) Stop

func (c *Client) Stop() error

Stop stops the current ongoing response.

type ClientOption

type ClientOption func(*Client)

ClientOption is a functional option for configuring the Client.

func WithBasicAuth

func WithBasicAuth(username, password string) ClientOption

WithBasicAuth sets Basic Authentication credentials for the WebSocket connection.

func WithHTTPHeader

func WithHTTPHeader(key, value string) ClientOption

WithHTTPHeader sets a custom HTTP header for the WebSocket upgrade request.

func WithHTTPHeaders

func WithHTTPHeaders(headers http.Header) ClientOption

WithHTTPHeaders sets multiple custom HTTP headers for the WebSocket upgrade request.

func WithReadTimeout

func WithReadTimeout(d time.Duration) ClientOption

WithReadTimeout sets the read deadline for WebSocket reads.

func WithReconnect

func WithReconnect(delay time.Duration, maxAttempts int) ClientOption

WithReconnect enables automatic reconnection with the given delay between attempts. maxAttempts controls how many reconnection attempts are made (0 = unlimited).

func WithSessionID

func WithSessionID(sessionID string) ClientOption

WithSessionID sets a specific session ID for the connection. If not set, the server will generate one automatically.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ClientOption

WithWriteTimeout sets the write deadline for WebSocket writes.

type CompletePayload

type CompletePayload struct {
	Message string `json:"message"`
}

CompletePayload signals completion of a response.

type ErrorPayload

type ErrorPayload struct {
	Error string `json:"error"`
}

ErrorPayload carries an error message.

type EventHandler

type EventHandler interface {
	// OnSessionInit is called when the server sends the session_init message.
	OnSessionInit(payload *SessionInitPayload)

	// OnChatSelected is called when a chat is successfully selected.
	OnChatSelected(payload *ChatSelectedPayload)

	// OnChunk is called for each streaming content chunk received.
	OnChunk(payload *ChunkPayload)

	// OnToolCall is called when the model invokes a tool.
	OnToolCall(payload *ToolCallPayload)

	// OnThinking is called when the thinking/reasoning state changes.
	OnThinking(payload *ThinkingPayload)

	// OnComplete is called when the model response is complete.
	OnComplete(payload *CompletePayload)

	// OnError is called when an error occurs.
	OnError(payload *ErrorPayload)

	// OnApprovalRequest is called when tool execution requires user approval.
	// The handler should call SendApprovalResponse to provide the decision.
	OnApprovalRequest(payload *ApprovalRequestPayload)

	// OnMessageCount is called when the message count changes.
	OnMessageCount(payload *MessageCountPayload)

	// OnStopped is called when a response is stopped by the user.
	OnStopped(payload *StoppedPayload)

	// OnKept is called after a keep hook executes.
	OnKept(payload *KeptPayload)

	// OnCleared is called after the conversation context is cleared.
	OnCleared(payload *ClearedPayload)

	// OnDisconnected is called when the WebSocket connection is lost.
	// err is nil for intentional disconnection.
	OnDisconnected(err error)

	// OnReconnected is called when the client successfully reconnects.
	OnReconnected()
}

EventHandler is the interface that clients must implement to receive server events. All methods are called from the read loop goroutine; implementations should be thread-safe or delegate work to other goroutines as needed.

type FilePayload

type FilePayload struct {
	URL      string `json:"url"`
	Type     string `json:"type"`
	Name     string `json:"name"`
	FileSize int64  `json:"file_size,omitempty"`
}

FilePayload represents a file attachment in a chat request.

type KeptPayload

type KeptPayload struct {
	ChatName string `json:"chat_name,omitempty"`
	Message  string `json:"message"`
}

KeptPayload is sent after a keep hook execution.

type MessageCountPayload

type MessageCountPayload struct {
	Count int `json:"count"`
}

MessageCountPayload carries the current message count.

type SessionInitPayload

type SessionInitPayload struct {
	SessionID string `json:"session_id"`
}

SessionInitPayload is received when a connection is first established.

type StoppedPayload

type StoppedPayload struct {
	Message string `json:"message"`
}

StoppedPayload is sent when a response is stopped by the user.

type ThinkingPayload

type ThinkingPayload struct {
	Status bool `json:"status"`
}

ThinkingPayload indicates whether the model is in a thinking/reasoning phase.

type ToolCallPayload

type ToolCallPayload struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	Index     string `json:"index"`
	Streaming bool   `json:"streaming"`
}

ToolCallPayload is sent when the model invokes a tool.

type WSMessage

type WSMessage struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

WSMessage is the raw WebSocket message format used by the server protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL