chat

package
v1.101.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package chat is the fleet's conversation surface, with a pluggable backend.

It replaced gokit/chatbot, which was one chat UI welded to goclaw through a WebSocket proxy and that gateway's own endpoints. This package keeps the part worth reusing — server-rendered turns, markdown prose, tool steps, the composer, the shared chrome words — and takes the backend as an interface, so a service implements two methods and mounts a section.

A conversation is named by an opaque key the consumer chooses and the surface never interprets: a ticket id, a document id, a user id, a compound of several. Two conversations render side by side on one page, because every element id is derived from that key.

Who is asking is resolved once per request by the section's Identifier and handed to the backend inside Conversation, so the model can be told whom it is talking to — by name for a logged-in user, and in so many words as an unknown visitor for an anonymous one.

Transport is plain HTMX: the composer posts a form and the server answers with the re-rendered surface. There is no WebSocket and no streaming.

Voice is the one thing HTMX cannot express, and it is opt-in per backend: a Backend that also implements VoiceBackend mints a LiveKit room, and only then does the surface render call controls and load the vendored LiveKit client. The audio itself never reaches this package — the browser and the backend's own voice agent meet in that room, and the speech-to-text and text-to-speech around it belong to the backend.

Index

Constants

View Source
const (
	// RoleUser is the human's own turn.
	RoleUser = views.RoleUser
	// RoleAssistant is the agent's turn.
	RoleAssistant = views.RoleAssistant
)

The roles a backend reports.

Variables

View Source
var (
	// ErrBackendRequired is returned when SectionConfig.Backend is nil.
	ErrBackendRequired = errors.New("chat: SectionConfig.Backend is required")
	// ErrTracerRequired is returned when SectionConfig.Tracer is nil. A nil
	// tracer is a nil interface that compiles and segfaults on the first
	// request, so it is refused at construction instead.
	ErrTracerRequired = errors.New("chat: SectionConfig.Tracer is required")
	// ErrBasePathRequired is returned when SectionConfig.BasePath is empty.
	ErrBasePathRequired = errors.New("chat: SectionConfig.BasePath is required")
	// ErrIdentifierRequired is returned when SectionConfig.Identify is nil. A
	// backend that is never told who is asking cannot tell the model either,
	// so the surface refuses to mount without one.
	ErrIdentifierRequired = errors.New("chat: SectionConfig.Identify is required")
	// ErrNoConversation is recorded when SectionConfig.Key refused a request.
	ErrNoConversation = errors.New("chat: no conversation for this request")
)

Errors the section reports rather than rendering a broken surface.

View Source
var ErrNoParticipant = errors.New("chat: no participant for this request")

ErrNoParticipant is recorded when the Identifier refused a request: the surface answers 401, because a conversation with nobody in it is not one the backend should be asked to hold.

Functions

This section is empty.

Types

type Backend

type Backend interface {
	// History returns the conversation so far, oldest first. An unknown
	// conversation is an empty history, not an error — a surface opened on a
	// ticket nobody has asked about yet renders its empty state.
	History(ctx context.Context, conversation Conversation) ([]Message, error)

	// Send delivers the visitor's message and returns the turns the assistant
	// produced in reply, oldest first, with any ToolSteps it took along the
	// way. Returning no messages is legal and renders as the user's turn
	// alone; the backend is expected to have persisted both sides, since the
	// surface re-reads History on the next load.
	Send(ctx context.Context, conversation Conversation, text string) ([]Message, error)
}

Backend is what a consuming service implements to put a conversation on a screen. It is the whole contract: two methods, no transport, no storage shape, no opinion about what a conversation is about.

conversation carries the opaque key the consumer's SectionConfig.Key produced for the request, and the Participant its Identifier resolved. An implementation keys storage on Key however it likes, and hands Participant.Describe to the model so it knows whom it is answering.

Every method takes a context and is expected to honour its deadline: Send runs inside a browser's request, so an agent that thinks for a minute needs a backend that says so rather than one that blocks the page.

type Conversation

type Conversation struct {
	// Key names the conversation. A backend is free to treat it as a primary
	// key, a namespace, or a composite it parses itself.
	Key string
	// Participant is who is on the other side of this request.
	Participant Participant
}

Conversation is what a Backend is asked about: which conversation, and who is asking. Key is the opaque name SectionConfig.Key produced and the surface never interprets; Participant is who SectionConfig.Identify resolved.

func (Conversation) Attributes

func (c Conversation) Attributes() []attribute.KeyValue

Attributes tags a span with the conversation key and the participant's safe attributes.

type Identifier

type Identifier interface {
	Identify(writer http.ResponseWriter, request *http.Request) (participant Participant, ok bool)
}

Identifier resolves who is asking. It is the one seam between the surface and however the consuming app knows its users: an OIDC session, a minted visitor cookie, anything else.

An implementation may write to writer to establish an identity — the anonymous identifier sets its cookie there. ok false means the request has no participant and the surface answers 401.

func NewAnonymousIdentifier

func NewAnonymousIdentifier(cookieName string, maxAge time.Duration, siteSlug string) Identifier

NewAnonymousIdentifier returns an Identifier for a site with no login.

The first request from a browser gets a fresh "<siteSlug>_<uuid>" id set in cookieName for maxAge; every later request reads it back. The participant it reports is Anonymous, with that id and nothing else, and Describe says so.

type IdentifierFunc

type IdentifierFunc func(writer http.ResponseWriter, request *http.Request) (Participant, bool)

IdentifierFunc adapts a plain function to Identifier, the way http.HandlerFunc adapts a handler.

func (IdentifierFunc) Identify

func (f IdentifierFunc) Identify(writer http.ResponseWriter, request *http.Request) (Participant, bool)

Identify calls the function.

type Message

type Message = views.Message

Message is one turn in a conversation.

type OIDCIdentifier

type OIDCIdentifier struct {
	// Auth is the app's OIDC handler, the one whose RequireSession guards the
	// section's routes.
	Auth *oidcauth.Handler
}

OIDCIdentifier resolves the participant from the session gokit/oidcauth established: the subject claim is the ID, and the name and email travel along when the provider supplied them.

func (OIDCIdentifier) Identify

func (o OIDCIdentifier) Identify(_ http.ResponseWriter, request *http.Request) (Participant, bool)

Identify reads the OIDC session. A request with no subject has no participant — RequireSession should have turned it away already, so ok false here is a route mounted outside its guard.

type Participant

type Participant struct {
	// ID is the stable identifier for this participant: the OIDC subject for
	// an authenticated user, the minted visitor id for an anonymous one. It
	// is what a backend keys per-user memory on, and it is never empty.
	ID string
	// Name is how the participant should be addressed. Empty when nothing is
	// known — always, for an anonymous visitor.
	Name string
	// Email is the participant's address, when the session carries one.
	Email string
	// Anonymous is true when nobody has authenticated: the ID is a session
	// cookie the surface minted, and nothing else about the participant is
	// known or trustworthy.
	Anonymous bool
}

Participant is who is talking to the assistant, as far as the surface can tell. The backend hands it to the model so an answer can address a known user by name and treat an anonymous visitor as exactly that.

Identity is resolved once per request by the section's Identifier and travels inside Conversation; a backend never reads a cookie or a session itself.

func (Participant) Attributes

func (p Participant) Attributes() []attribute.KeyValue

Attributes tags a span with what is safe to record about the participant: whether they authenticated, and nothing that names them. IDs, names and addresses are high-cardinality and personal, so they stay out of telemetry.

func (Participant) Describe

func (p Participant) Describe() string

Describe returns the participant as one plain sentence for a model's context, so every backend on the fleet tells the model who it is talking to in the same words. An anonymous visitor is stated as unknown rather than left implicit: a model given no user at all tends to invent one.

type Role

type Role = views.Role

Role is who produced a message.

type Section

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

Section is a mountable conversation surface. Merge Routes() into the app's route map.

func NewSection

func NewSection(cfg SectionConfig) (*Section, error)

NewSection builds a Section from cfg.

func (*Section) BasePath

func (s *Section) BasePath() string

BasePath returns where the section mounts, for building a nav entry.

func (*Section) MessagesPath

func (s *Section) MessagesPath() string

MessagesPath returns where the composer posts, for the same reason.

func (*Section) Routes

func (s *Section) Routes() map[string]http.Handler

Routes returns the section's handlers keyed by Go 1.22 mux patterns.

func (*Section) VoicePath

func (s *Section) VoicePath() string

VoicePath returns where the browser asks for a voice room, for a consumer building its own link or test. It is empty when the backend has no voice.

type SectionConfig

type SectionConfig struct {
	// Backend answers the conversation. Required.
	Backend Backend
	// Key names the conversation this request is about, from whatever the
	// consumer keys on: a path wildcard, a query parameter, the session. ok
	// false answers 404 — the surface has nothing to show and must not guess.
	// Required.
	Key func(request *http.Request) (conversation string, ok bool)
	// Identify resolves who is asking: OIDCIdentifier behind an OIDC session,
	// NewAnonymousIdentifier on a site with no login, IdentifierFunc for
	// anything else. ok false answers 401. Required.
	Identify Identifier
	// BasePath is where the section mounts. It may carry Go 1.22 wildcards
	// ("/incidents/{incident}/chat"), which is how a consumer gives every
	// record its own conversation without mounting a section per record.
	// Required.
	BasePath string
	// Title names the conversation. Domain text, so the consumer owns it; an
	// empty one falls back to the shared chrome word. Everything else the
	// surface says comes from webui.Word and is not configurable.
	Title func(request *http.Request) string
	// Lang selects the chrome language. Nil reads the shared lang cookie.
	Lang func(request *http.Request) string
	// Shell wraps the surface in the app's layout on direct navigation, and
	// is not called on an HTMX swap. Nil renders the surface bare.
	Shell func(request *http.Request, content templ.Component) templ.Component
	// Tracer records spans. Required.
	Tracer trace.Tracer
}

SectionConfig configures a mountable conversation surface.

type ToolStep

type ToolStep = views.ToolStep

ToolStep is one tool the assistant invoked while producing a message.

type VoiceBackend

type VoiceBackend interface {
	Backend

	// Voice mints a join grant for this conversation, putting the backend's
	// voice agent in the same room. The conversation is the same one History
	// and Send are given, so a spoken turn lands in the conversation the page
	// is already showing, and the agent knows who joined.
	//
	// A backend that can answer this conversation in text but not by voice
	// returns client.ErrUnavailable, which answers 404 rather than an error
	// banner: the caller asked for something this conversation does not have.
	Voice(ctx context.Context, conversation Conversation) (client.Grant, error)
}

VoiceBackend is the optional voice half of Backend: a backend that can also hold the conversation out loud.

A Backend that does not implement it renders a text-only surface — no call button, no LiveKit script, nothing loaded. Voice is opt-in per backend, not per deployment, because a backend with no agent in the room is a call that connects to silence. gokit/webui/chat/server.Wrap turns any Backend into one.

It lives here rather than in chat/client because it is Backend plus one method over Conversation, and chat/client is what this package renders the call with: the interface in chat/client would be an import cycle.

Directories

Path Synopsis
Package chattest holds an in-memory chat.Backend.
Package chattest holds an in-memory chat.Backend.
Package client is the browser half of a voice call: the call controls, the one module script that joins a LiveKit room, the header that lets the page use a microphone, and the answer the voice route gives the browser.
Package client is the browser half of a voice call: the call controls, the one module script that joins a LiveKit room, the header that lets the page use a microphone, and the answer the voice route gives the browser.
Package server is the server half of a voice call: it mints the browser's LiveKit join grant, puts an agent in the same room, and holds the conversation out loud — the person's speech is transcribed through gpu-manager, answered by the same Send that answers typed messages, and the reply is spoken back through gpu-manager.
Package server is the server half of a voice call: it mints the browser's LiveKit join grant, puts an agent in the same room, and holds the conversation out loud — the person's speech is transcribed through gpu-manager, answered by the same Send that answers typed messages, and the reply is spoken back through gpu-manager.
Package views renders the reusable conversation surface and holds the data it draws from.
Package views renders the reusable conversation surface and holds the data it draws from.

Jump to

Keyboard shortcuts

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