chatbot

package
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 36 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DefaultApprovalTimeout = 5 * time.Minute

Default approval timeout

Variables

This section is empty.

Functions

func NewCleanupRegistry

func NewCleanupRegistry() *cleanupRegistry

NewCleanupRegistry creates a new cleanup registry for the session

func TrimLeadingWhitespace added in v1.5.3

func TrimLeadingWhitespace(s string) string

TrimLeadingWhitespace strips leading whitespace characters (space, tab, newline, carriage return)

func TruncateToTermWidth

func TruncateToTermWidth(s string) (string, bool)

Types

type ApprovalRequest

type ApprovalRequest struct {
	ApprovalID string
	ResultChan chan ApprovalResultMap
}

ApprovalRequest holds the approval ID and result channel

type ApprovalResultMap

type ApprovalResultMap map[string]*mcp.ApprovalResult

ApprovalResultMap holds approval results for multiple targets

type ApprovalTarget

type ApprovalTarget struct {
	ID            string
	ToolName      string
	ArgumentsInfo string
}

ApprovalTarget represents a single approval request target

type ChatBot

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

ChatBot struct for the chatbot

func NewChatBot

func NewChatBot(ctx context.Context, agent *adk.ChatModelAgent, manager *manager.Manager, scanner *readline.Instance, persistence *store.PersistenceStore) ChatBot

func (*ChatBot) ClearContext

func (cb *ChatBot) ClearContext()

ClearContext clears the context

func (*ChatBot) GetContextSummary

func (cb *ChatBot) GetContextSummary() string

GetContextSummary retrieves context summary

func (*ChatBot) SetHandler

func (cb *ChatBot) SetHandler(handler Handler)

SetHandler sets the output handler for the chatbot

func (*ChatBot) StreamChat

func (cb *ChatBot) StreamChat(ctx context.Context, userInput string) error

StreamChat performs streaming chat conversation with CLI output

func (*ChatBot) StreamChatWithHandler

func (cb *ChatBot) StreamChatWithHandler(ctx context.Context, userInput string, files []FileData) error

StreamChatWithHandler performs streaming chat with a custom handler

type ChatSession

type ChatSession struct {
	ID        string
	Name      string
	Preset    config.Chat
	Agent     *adk.ChatModelAgent
	Manager   *manager.Manager
	Tools     []tool.BaseTool
	MCPClient *mcp.Client
	// contains filtered or unexported fields
}

ChatSession represents a chat session with its configuration

func InitChatSession

func InitChatSession(ctx context.Context, cfg *config.Config, chatName string, sessionID string, debug bool) (*ChatSession, error)

InitChatSession initializes a new chat session with the given chat name and session ID

func (*ChatSession) Clear

func (s *ChatSession) Clear() error

Clear clear the current context

func (*ChatSession) Close

func (s *ChatSession) Close() error

Close closes the chat session and releases all resources

func (*ChatSession) GetLastUserMessage

func (s *ChatSession) GetLastUserMessage() string

GetLastUserMessage returns the last user message from the conversation, if any. Used for redo/regenerate functionality.

func (*ChatSession) GetMessageCount

func (s *ChatSession) GetMessageCount() int

GetMessageCount returns the number of messages in the session

func (*ChatSession) OnGenModelInput

func (s *ChatSession) OnGenModelInput(ctx context.Context, instruction string, inputMessages []*schema.Message) ([]*schema.Message, error)

OnGenModelInput executes the genmodelinput hook if configured This hook is called before sending messages to the model and can modify the message list

func (*ChatSession) OnKeep

func (s *ChatSession) OnKeep() error

func (*ChatSession) PersistenceStore

func (s *ChatSession) PersistenceStore() *store.PersistenceStore

PersistenceStore returns the persistence store for this session

func (*ChatSession) RemoveLastRound

func (s *ChatSession) RemoveLastRound()

RemoveLastRound removes the last round of messages (used for regenerate)

func (*ChatSession) RunCronTask added in v1.8.0

func (s *ChatSession) RunCronTask(ctx context.Context, task config.CronTask, handler Handler) error

RunCronTask executes a configured cron task for this session:

  1. run the task hook (script or http) — its output must be JSON,
  2. render the task prompt as a Go template with the hook's JSON data,
  3. run the agent with the rendered prompt as the user message.

type ConnectionChat added in v1.7.0

type ConnectionChat struct {
	Name        string
	ChatSession *ChatSession
	ChatBot     *ChatBot
	WSHandler   *WSChatHandler
	// contains filtered or unexported fields
}

ConnectionChat holds the per-chat state attached to a single WebSocket connection. A connection can attach several chats at the same time and stream responses from multiple chats concurrently; every event sent to the client carries the chat name so the client can route it to the right view.

func (*ConnectionChat) InFlight added in v1.7.0

func (c *ConnectionChat) InFlight() *atomic.Bool

InFlight exposes the in-flight flag (atomic.Bool) for busy checks.

func (*ConnectionChat) IsCancelled added in v1.7.0

func (c *ConnectionChat) IsCancelled() bool

IsCancelled returns whether the chat's stream is cancelled

func (*ConnectionChat) ResetCancel added in v1.7.0

func (c *ConnectionChat) ResetCancel()

ResetCancel resets the cancel state for a new request

func (*ConnectionChat) SetCancelFunc added in v1.7.0

func (c *ConnectionChat) SetCancelFunc(cancelFunc context.CancelFunc)

SetCancelFunc sets the cancel function for the current request

func (*ConnectionChat) SetCancelled added in v1.7.0

func (c *ConnectionChat) SetCancelled()

SetCancelled marks the chat's stream as cancelled

type FileData

type FileData struct {
	URL      string
	Type     string
	Name     string
	FileSize int64
}

FileData represents file data for multimodal messages

type Handler

type Handler interface {
	// SendChunk sends a content chunk with position markers
	// contentType: "response" or "thinking"
	SendChunk(content string, first, last bool, contentType string)

	// SendToolCall sends a tool call notification with name, arguments, index and streaming status
	// index: the tool call index
	// streaming: true if this is a streaming update (arguments may be partial), false when complete
	SendToolCall(name string, arguments string, id string, streaming bool)

	// SendThinking sends a thinking indicator
	SendThinking(status bool)

	// SendComplete sends a completion signal
	SendComplete(message string)

	// SendError sends an error message
	SendError(err string)

	// SendApprovalRequest sends an approval request to the client and waits for the result
	// targets: list of approval targets requiring user authorization
	// Returns a map of target IDs to their approval results
	SendApprovalRequest(targets []ApprovalTarget) (ApprovalResultMap, error)

	// SendMessageCount sends the current message count to the client
	SendMessageCount()
}

Handler interface for handling chat output events This allows the same streaming logic to be used in different contexts (CLI with readline, WebSocket, etc.)

type StreamFilter

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

func NewStreamFilter

func NewStreamFilter() *StreamFilter

func (*StreamFilter) Finish

func (f *StreamFilter) Finish() *string

func (*StreamFilter) Process

func (f *StreamFilter) Process(chunk string) *string

type WSChatHandler

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

WSChatHandler implements Handler for WebSocket output of a single chat. Every event it sends carries the chat name in the payload.

func NewWSChatHandler

func NewWSChatHandler(cc *ConnectionChat) *WSChatHandler

func (*WSChatHandler) SendApprovalRequest

func (h *WSChatHandler) SendApprovalRequest(targets []ApprovalTarget) (ApprovalResultMap, error)

SendApprovalRequest sends an approval request to the client and waits for the result. Requests from different chats do not block each other.

func (*WSChatHandler) SendChunk

func (h *WSChatHandler) SendChunk(content string, first, last bool, contentType string)

func (*WSChatHandler) SendComplete

func (h *WSChatHandler) SendComplete(message string)

func (*WSChatHandler) SendError

func (h *WSChatHandler) SendError(err string)

func (*WSChatHandler) SendMessageCount

func (h *WSChatHandler) SendMessageCount()

SendMessageCount sends the current message count of this chat to the client

func (*WSChatHandler) SendThinking

func (h *WSChatHandler) SendThinking(status bool)

func (*WSChatHandler) SendToolCall

func (h *WSChatHandler) SendToolCall(name string, arguments string, id string, streaming bool)

type WSMessage

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

WebSocket message types

type WSSession

type WSSession struct {
	SessionID string
	// CurrentChat is the last chat selected on this connection. It is used
	// as the fallback target for commands that carry no chat_name (legacy
	// single-chat clients).
	CurrentChat string
	// contains filtered or unexported fields
}

WSSession represents a WebSocket session with its connection. It holds only connection-level state; per-chat state lives in ConnectionChat entries returned by AttachChat/GetChat.

func NewWSSession

func NewWSSession(conn *websocket.Conn, sessionID string, cfg *config.Config) *WSSession

func (*WSSession) AttachChat added in v1.7.0

func (s *WSSession) AttachChat(name string, chatSession *ChatSession, chatBot *ChatBot) *ConnectionChat

AttachChat registers (or re-attaches) a chat on this connection and (re) binds its ChatBot output handler to this connection. It returns the ConnectionChat entry which callers may further update.

func (*WSSession) CancelAllInFlight added in v1.7.0

func (s *WSSession) CancelAllInFlight()

CancelAllInFlight cancels the stream of every attached chat that is currently generating. Used when the connection closes.

func (*WSSession) ChatNames added in v1.7.0

func (s *WSSession) ChatNames() []string

ChatNames returns the names of all chats attached to this connection.

func (*WSSession) DetachChat added in v1.7.0

func (s *WSSession) DetachChat(name string)

DetachChat removes a chat from this connection (state is kept in the session manager for later restoration).

func (*WSSession) GetChat added in v1.7.0

func (s *WSSession) GetChat(name string) *ConnectionChat

GetChat returns the chat attached to this connection, or nil.

func (*WSSession) HandleApprovalResponse

func (s *WSSession) HandleApprovalResponse(approvalID string, results ApprovalResultMap)

HandleApprovalResponse processes an approval response from the client. Approval requests from different chats can be pending concurrently and are matched by approval ID.

func (*WSSession) IsClosed

func (s *WSSession) IsClosed() bool

IsClosed returns true if the session has been marked as closed.

func (*WSSession) MarkClosed

func (s *WSSession) MarkClosed()

MarkClosed marks the session as closed so that subsequent SendMessage/SendPing calls are silently dropped instead of writing to a closed connection.

func (*WSSession) SendError

func (s *WSSession) SendError(errMsg string)

SendError sends a connection-level (not chat-scoped) error message.

func (*WSSession) SendMessage

func (s *WSSession) SendMessage(msgType string, content interface{})

func (*WSSession) SendPing

func (s *WSSession) SendPing()

SendPing sends a WebSocket ping frame to the client. Used for keepalive to detect dead connections. The write deadline ensures we don't block forever if the connection is dead. The deadline is cleared after the write to avoid affecting subsequent writes.

func (*WSSession) SetApprovalTimeout

func (s *WSSession) SetApprovalTimeout(timeout time.Duration)

SetApprovalTimeout sets the timeout for approval requests

func (*WSSession) SetReadTimeout

func (s *WSSession) SetReadTimeout(d time.Duration)

SetReadTimeout sets the read timeout used to reset the read deadline after writes.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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